SQL deterministic window ordering
A window ORDER BY that does not uniquely identify rows leaves tie order to the engine, so numbers and running sums can change between runs.
- Category
- Window
- Returns
stable per-row values- In this category
- 47 of 79
Syntax
ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC, id)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | MySQL 8.0+ |
| SQLite | Yes | SQLite 3.25+ |
| Oracle | Yes | Supported under this name. |
Examples
Any engine
-- order_id breaks the tie: without it, equal amounts may swap numbers
SELECT customer_id, order_id, amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, order_id) AS rn
FROM orders;
Good to know
- Any unique column (primary key, id) appended as the last ORDER BY key makes the order total; without one, equal-key rows can permute and flip dedupes, top-N cuts and deltas.
- RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST and default-frame (RANGE) aggregates give tied rows identical values, so they are stable without tiebreakers. ROW_NUMBER, NTILE, LAG/LEAD, FIRST_VALUE/LAST_VALUE and ROWS frames are the ones that wobble.
- Tie order follows the plan: a parallel scan, a new index or a different row count can change it, so a query that passes on a small test table can number rows differently in production.
Questions about Deterministic Window Order
Do I need a tiebreaker if I use RANK?
Not for stability: tied rows legitimately share a rank. But if the query then filters RANK() = 1 you can get several rows; that is the tie speaking, not nondeterminism.
Why did my running total change between environments?
The frame is ROWS and the ORDER BY has ties, so tied rows accumulated in a different order and the partial sums changed. Add a unique tiebreaker to the ORDER BY. (The default RANGE frame does not have this problem: tied rows all get the same total.)
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.