Sub topic 4
Ordering rows inside a window
This chapter assumes you can read an OVER (PARTITION BY ...) clause and that you know how GROUP BY, CTEs and ordinary ORDER BY work. The examples run on PostgreSQL, MySQL 8+, SQL Server and SQLite 3.25+ unless a note says otherwise.
Two different ORDER BY clauses
A query with window functions can contain two unrelated ORDER BY clauses:
- The one inside
OVER (...)sets the order in which a window function sees the rows of its partition. - The one at the end of the query sets the order of the result rows you receive.
The first is part of the function's definition. It does not sort the output. Here is a query that uses both:
SELECT salesperson, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM sales
ORDER BY salesperson;The numbers in rn follow amount, highest first. The rows come back sorted by name. If you leave out the final ORDER BY, the database may return rows in any order, even though the window had to sort internally to compute rn. Do not rely on a window's sort order for the order of the result.
What the window ORDER BY does
Inside OVER, ORDER BY arranges the rows of each partition into a sequence. Whether that matters depends on the kind of function:
| Function family | Without window ORDER BY | With window ORDER BY |
|---|---|---|
| Ranking (`ROW_NUMBER`, `RANK`, `DENSE_RANK`) | Not allowed or meaningless | Required. The order defines the rank. |
| `LAG` and `LEAD` | Accepted by some databases, but "previous" has no meaning | Required in practice. The order defines "previous" and "next". |
| Aggregates (`SUM`, `AVG`, `COUNT`) | One value for the whole partition | Cumulative value, because the default frame changes |
| `FIRST_VALUE`, `LAST_VALUE` | Result is arbitrary | Result depends on the order and the frame |
The third row is a common source of surprises. Adding ORDER BY to an aggregate window function changes what the aggregate covers, not only the order. Later chapters cover the frame in detail. For now, remember that an aggregate with an ORDER BY stops being a whole-partition total.
The sample data
The examples use this small table. It has a tie on amount and on date in the East region, and a NULL amount in the West region.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(10),
salesperson VARCHAR(10),
amount INTEGER,
sale_date DATE
);
INSERT INTO sales (id, region, salesperson, amount, sale_date) VALUES
(1, 'East', 'Ana', 100, '2026-01-05'),
(2, 'East', 'Ben', 200, '2026-01-05'),
(3, 'East', 'Cy', 200, '2026-01-07'),
(4, 'West', 'Dee', 150, '2026-01-06'),
(5, 'West', 'Eli', NULL, '2026-01-08'),
(6, 'West', 'Fay', 300, '2026-01-09');Sort direction and multiple keys
The window ORDER BY accepts the same syntax as a normal one. You can list several keys, give each its own ASC or DESC, and sort by expressions such as ABS(amount - 150).
The window cannot sort by a column alias defined in the same SELECT list. Window functions are evaluated before the select list is finished, so ORDER BY alias inside OVER fails in most databases. Repeat the expression instead.
Different functions in one query can use different orderings. Each OVER clause is independent:
SELECT salesperson, sale_date, amount,
ROW_NUMBER() OVER (ORDER BY sale_date, id) AS by_date,
ROW_NUMBER() OVER (ORDER BY amount DESC, id) AS by_amount
FROM sales
WHERE region = 'East'
ORDER BY id;| salesperson | sale_date | amount | by_date | by_amount |
|---|---|---|---|---|
| Ana | 2026-01-05 | 100 | 1 | 3 |
| Ben | 2026-01-05 | 200 | 2 | 1 |
| Cy | 2026-01-07 | 200 | 3 | 2 |
The database may need one sort per distinct window definition. Windows that share the same PARTITION BY and ORDER BY can often share a single sort. This is one reason to keep orderings consistent when you can.
Ties and non-deterministic results
If two rows have equal values in every window ORDER BY key, they are peers. The database may place peers in either order, and the order can change between runs, after an index change or after a version upgrade. Ben and Cy both have an amount of 200 in the East region, so this query is ambiguous:
SELECT salesperson, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM sales
WHERE region = 'East';Ben may get 1 and Cy 2, or the reverse. Both results are valid, and nothing in the query tells you which you will get. This matters most with ROW_NUMBER, because it must hand out distinct numbers. With RANK and DENSE_RANK the peers get the same rank, so the ambiguity is hidden in this case, but it can still affect functions such as LAG, LEAD and LAST_VALUE.
The fix is a tiebreaker: add a column that is unique within the partition, usually the primary key.
SELECT salesperson, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC, id) AS rn
FROM sales
WHERE region = 'East';The result is now always Ben 1, Cy 2, Ana 3.
Ordering changes what an aggregate means
Compare these two sums over the East region. The first has no window ORDER BY. The second adds one:
SELECT salesperson, sale_date, amount,
SUM(amount) OVER () AS total_all,
SUM(amount) OVER (ORDER BY sale_date) AS running_by_date,
SUM(amount) OVER (ORDER BY sale_date, id) AS running_unique
FROM sales
WHERE region = 'East'
ORDER BY id;| salesperson | sale_date | amount | total_all | running_by_date | running_unique |
|---|---|---|---|---|---|
| Ana | 2026-01-05 | 100 | 500 | 300 | 100 |
| Ben | 2026-01-05 | 200 | 500 | 300 | 300 |
| Cy | 2026-01-07 | 200 | 500 | 500 | 500 |
The running_by_date column shows 300 for both Ana and Ben. When a frame is not given, the default frame runs from the start of the partition to the current row and includes all of the current row's peers. Ana and Ben share a date, so each one's frame includes the other. Once the ordering is made unique with id, no two rows are peers and you get the running total you probably expected: 100, 300, 500.
This is the same ties problem as before, with a different symptom. Ties affect the order for ranking and neighbour functions, and they affect the frame for aggregates. A later chapter on the default frame explains the rule in full, and the chapter on frames shows how to choose ROWS explicitly.
NULLs in the window ORDER BY
Databases disagree about where NULL sorts. This affects ranks, neighbours and running values.
| Database | NULL sorts as | Result with ASC | Result with DESC | NULLS FIRST / LAST syntax |
|---|---|---|---|---|
| PostgreSQL | Largest value | NULLs last | NULLs first | Supported |
| Oracle | Largest value | NULLs last | NULLs first | Supported |
| SQLite | Smallest value | NULLs first | NULLs last | Supported from 3.30 |
| MySQL | Smallest value | NULLs first | NULLs last | Not supported |
| SQL Server | Smallest value | NULLs first | NULLs last | Not supported |
In the West region, Eli has a NULL amount. On PostgreSQL, ranking by amount DESC puts Eli first, which is almost never what you want in a "top seller" ranking. State the intent explicitly where the syntax exists:
SELECT salesperson, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC NULLS LAST, id) AS rn
FROM sales
WHERE region = 'West';The result is Fay 1, Dee 2, Eli 3. On MySQL and SQL Server, which do not accept NULLS LAST, sort on a flag first:
SELECT salesperson, amount,
ROW_NUMBER() OVER (
ORDER BY CASE WHEN amount IS NULL THEN 1 ELSE 0 END,
amount DESC,
id
) AS rn
FROM sales
WHERE region = 'West';The CASE key sorts non-NULL rows (0) before NULL rows (1). Within each group, the second key then applies.
Common mistakes
- Relying on the window's order for the order of the output rows. Add a final
ORDER BY. - Leaving ties unresolved, then seeing different
ROW_NUMBERresults on different runs. - Adding
ORDER BYtoSUMand expecting the whole-partition total. It now produces a cumulative value. - Forgetting that
NULLplacement depends on the database, which moves rows in rankings and changes which rowLAGreturns. - Sorting by a select-list alias inside
OVER.
Exercise
In the East region, you want a running total of amount by saledate, so that Ana shows 100, Ben 300 and Cy 500. Your query uses SUM(amount) OVER (ORDER BY saledate) and returns 300 for both Ana and Ben. Why does this happen, and what is the smallest change that fixes it?
Show answer
Ana and Ben have the same saledate, so they are peers in the window ordering. The default frame includes all peers of the current row, so both rows see 100 + 200 = 300. Add a unique tiebreaker to the window ORDER BY, for example SUM(amount) OVER (ORDER BY saledate, id). With no peers, each row's frame ends at that row, giving 100, 300 and 500.
Exercise
On PostgreSQL, ROW_NUMBER() OVER (ORDER BY amount DESC) ranks a salesperson with a NULL amount first. Write the ORDER BY for the window so that NULL amounts come last and ties are broken by id. Then say how you would write it on SQL Server.
Show answer
PostgreSQL: ORDER BY amount DESC NULLS LAST, id. SQL Server has no NULLS LAST, so sort on a flag first: ORDER BY CASE WHEN amount IS NULL THEN 1 ELSE 0 END, amount DESC, id.