Numbering rows with ROW_NUMBER
A window function works out a value for each row by looking at other rows, without squashing
them into groups the way GROUP BY does. You recognise one by OVER (…).
ROW_NUMBER() numbers the rows 1, 2, 3… in the order you choose:
SELECT name, list_price,
ROW_NUMBER() OVER (ORDER BY list_price DESC, id) AS position
FROM productsThe ORDER BY inside OVER decides the numbering. It doesn't sort the output: add an ordinary
ORDER BY at the end for that.
Notice , id after list_price DESC. If two products cost the same, ROW_NUMBER still has to put
one first, and without a tie-breaker the database picks either. Adding a unique column makes the
numbering the same every time you run it.