Brightlane's fulfillment dashboard assigns every order a unique position based on order value for priority processing.
Write a query to return the ID and total amount of every order, plus a unique sequential number assigned in descending order of total_amount.
Assumptions:
- The
orderstable has one row per order with anidand atotal_amount. - The position is
1for the highesttotal_amountand increments by1for each subsequent order. - Every order receives a different position; if two orders share the same
total_amount, they still receive consecutive numbers in some order.
Output:
- One row per order, with columns
id,total_amount, androw_num.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
total_amount,
ROW_NUMBER() OVER (
ORDER BY
total_amount DESC
) AS row_num
FROM
orders The shape
ROW_NUMBER() OVER (ORDER BY total_amount DESC) assigns each order a unique sequential integer in descending-total order. The largest order gets 1, the next-largest 2, and so on, with no gaps and no repeats, even when two orders share the same total.
Clause by clause
SELECT id, total_amount, ROW_NUMBER() OVER (ORDER BY total_amount DESC) AS row_numreturns each order's ID, its amount, and a positional rank. The window'sORDER BY total_amount DESCdefines the ordering inside which positions are assigned; the window has noPARTITION BY, so every order is in the same window and the positions run1, 2, 3, ...straight through the table.FROM ordersreads the orders. Every order receives a row number; no row is dropped.
Why ROW_NUMBER and not RANK
If two orders tie on total_amount, ROW_NUMBER still hands out two distinct integers because every row gets its own number regardless of value. RANK would give them the same number and then skip the next integer. When the consumer needs a strict one-to-one mapping between orders and positions, ROW_NUMBER is the function that guarantees no repeats. The cost is that the tie-breaking between equal-amount orders is arbitrary in the absence of a secondary sort.
You practiced ROW_NUMBER() OVER (ORDER BY ...) — assign a unique sequential integer to every row; ties get consecutive numbers in an unspecified order.