sql · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
and let tied rows share a place.
In a bake-off, two bakers with the same score deserve the same place. ROW_NUMBER cannot do that, because every row gets its own number. RANK and DENSE_RANK give tied rows the same place.
They differ after a tie. RANK skips, like a sports table: two bakers share 2nd, so the next is 4th. DENSE_RANK never skips, so the next is 3rd. That suits questions like the three best scores.
Here Ava and Sam both scored 24 in total, so they share second place.
WITH totals AS (
SELECT baker, SUM(score) AS points
FROM entries GROUP BY baker
)
SELECT baker, points,
RANK() OVER (ORDER BY points DESC) AS rank_place,
DENSE_RANK() OVER (ORDER BY points DESC) AS dense_place
FROM totals
ORDER BY points DESC, baker; Tied rows share a place, so a tie-breaker here only decides who is listed first.
guess first
Ava and Leo both scored 7 for cake. What are the places?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
SELECT baker, score,
RANK() OVER (ORDER BY score DESC) AS place
FROM entries
WHERE round = 'cake'
ORDER BY place, baker;
your turn
Your turn. Rank the bread round.
Ava and Mia tie in the bread round. Pick RANK or DENSE_RANK, and make the highest score come first. Then run it again with the other one and compare Sam's place.
result
Your answer appears here as a table.
fix it
Leo has the third-best score but came 4th. Fix it!
result
Your answer appears here as a table.
- Leo has the third-highest score of the four, yet he shows as 4. What happens after Ava and Sam tie?
RANKleaves a gap after a tie. You need the function that never skips a place.- Change RANK to DENSE_RANK on line 6, then press run.
nailed it
nobody gets robbed of a shared place. :D
RANKgives tied rows the same place, then skips.DENSE_RANKgives tied rows the same place and never skips.ROW_NUMBERnever shares, so tied rows get different numbers.
new words in your collection
- RANK
- DENSE_RANK
This lesson isn’t saved. A free account remembers every lesson you finish.