Window ordering
Overview
Window ORDER BY defines the logical sequence for an individual window calculation. The final ORDER BY controls display independently. These two orderings can be different. The examples rank shop products by price while presenting rows by identifier, and show how peers influence the default aggregate frame.
First example
SELECT id, name, ROW_NUMBER() OVER (ORDER BY price_cents, id) AS positionFROM products ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "Notebook", 3 ], [ 2, "Pen", 2 ], [ 3, "Bag", 4 ], [ 4, "Pencil", 1 ]]How it works
In the first query the cheapest product is Pencil (id 4), so its row number is 1 even though it appears last. For the second query, two A scores are 90. With only points DESC in the window ORDER BY, both are peers and both receive cumulative 180 in the default frame. Adding id changes peer membership, so use a separate ordering when you need ties preserved. A ROWS frame is demonstrated in the next chapter.
Practical example
SELECT id, points, SUM(points) OVER (ORDER BY points DESC) AS runningFROM window_scores WHERE team = 'A' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 90, 180 ], [ 2, 90, 180 ], [ 3, 70, 250 ], [ 4, 60, 310 ], [ 5, 50, 360 ]]Practice and mistakes
Change the outer ordering to price_cents DESC and observe that the attached row numbers do not change. Predict the cumulative total at score 70 (250). Do not rely on physical row order or implicit NULL ordering across engines; specify NULLS FIRST/LAST where needed. Both engines support the tested syntax; only SQLite was executed.