Predict the output
What does the query print?
CREATE TABLE scores (name text, pts int);
INSERT INTO scores VALUES ('a', 90), ('b', 90), ('c', 80);
SELECT name, rank() OVER w, dense_rank() OVER w
FROM scores WINDOW w AS (ORDER BY pts DESC)
ORDER BY name;Hint 1 of 1
What happens to the number after a tie?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A a|1|1, b|1|1, c|3|2
Correct. rank skips 2 after the tie; dense_rank doesn't.
rank() gives tied rows the same number and then skips ahead by the size of the tie. dense_rank() gives the next distinct value the next number, so c is 3 by rank and 2 by dense_rank.
Why not the others?
- B
a|1|1,b|2|2,c|3|3. That's row_number for both: ties aren't broken by rank functions. - C
a|1|1,b|1|1,c|2|2. rank leaves a gap after a two-way tie. - D
a|1|1,b|1|1,c|3|3. dense_rank never leaves gaps.
| name | rank | dense_rank |
|---|---|---|
| a | 1 | 1 |
| b | 1 | 1 |
| c | 3 | 2 |
(3 rows)