×

sql · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

numbers rows in the order you choose.

ROW_NUMBER() OVER (ORDER BY total DESC) numbers the rows: 1 for the biggest order, 2 for the next, and so on. The ORDER BY inside OVER decides the numbers. The query's own ORDER BY, at the end, decides how rows are shown.

Watch for a : two rows with the same value. Orders 1 and 8 are both £30, so which is 3rd and which is 4th? SQL does not promise. The numbers could change between versions.

Add a , a second column that settles ties. ORDER BY total DESC, id numbers the same way every time.

SELECT id, total,
  ROW_NUMBER() OVER (ORDER BY total DESC, id) AS position
FROM orders
ORDER BY position;

An id makes a perfect tie-breaker, because no two rows share one.