// SQL snippet

Stable ordering with tiebreaks

SQL does not guarantee row order without it; ties are free to shuffle.

Main statement
All engines

The task

Rows with the same order_date come back in a different order on every run, which breaks pagination, screenshots and ROW_NUMBER determinism.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT id, customer_id, order_date, amount
FROM orders
ORDER BY order_date DESC, amount DESC, id;

Как это работает

The first two keys express the real sort; id, which is unique, makes the order total, so no two rows can tie and the engine has no freedom left. Any unique column works, such as the primary key or another column with a unique constraint. The same tiebreak belongs inside window ORDER BY clauses when ROW_NUMBER must be reproducible.

Variations

Tiebreak inside a ranking window

WITH ranked AS (
  SELECT id, customer_id, amount,
         ROW_NUMBER() OVER (ORDER BY amount DESC, id) AS rn
  FROM orders
)
SELECT id, customer_id, amount, rn
FROM ranked
WHERE rn <= 5
ORDER BY rn;

Questions that come up

Why does the same query return rows in a different order each time?

Without a unique key in the ORDER BY, the plan may use a hash or parallel scan whose visit order varies. SQL only promises order when ORDER BY can distinguish every pair of rows, which is what the tiebreak column provides.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.