Full answer
Why order changes:
- A different plan (index scan versus sequential scan versus hash aggregate) returns rows in a different order.
- Updates move rows physically in PostgreSQL, so a table scan's order drifts.
- Parallel workers return rows as they finish.
- Synchronized scans in PostgreSQL can start a scan in the middle of a table when another scan is already running.
Rules:
- Any user-visible list needs ORDER BY.
- Ties need a tiebreaker (
ORDER BY created_at DESC, id DESC), or rows with equal keys can swap between requests, duplicating or hiding items across pages. - ORDER BY inside a subquery or view does not guarantee the order of the outer result.
- GROUP BY does not imply sorted output.
SQLite offers PRAGMA reverse_unordered_selects = ON to reverse the order of unordered queries, a cheap way to find code that relies on accidental order in tests.
Key points
- No ORDER BY means no guaranteed order
- Plans and layout change order
- Add unique tiebreakers
- Subquery ORDER BY does not carry outward
- reverse_unordered_selects finds hidden reliance
Common mistakes
- Relying on insertion order
- Assuming GROUP BY sorts
Follow-ups
- How do ties break pagination?
- Can a view's ORDER BY be trusted?
Tips
- Mention the SQLite testing pragma