Consider the following table Scores with columns Player and Points:
Player | Points -------|------- Alice | 100 Bob | 90 Carol | 90 Dave | 80
What is the output of the following query?
SELECT Player, Points, RANK() OVER (ORDER BY Points DESC) AS RankPos FROM Scores;
CREATE TABLE Scores (Player VARCHAR(10), Points INT); INSERT INTO Scores VALUES ('Alice', 100), ('Bob', 90), ('Carol', 90), ('Dave', 80); SELECT Player, Points, RANK() OVER (ORDER BY Points DESC) AS RankPos FROM Scores;
RANK() assigns the same rank to ties but skips ranks after ties.
RANK() assigns the same rank to tied rows and then skips the next ranks accordingly. Here, Bob and Carol tie at 90 points and share rank 2, so the next rank is 4 for Dave.
Using the same Scores table, what is the output of this query?
SELECT Player, Points, DENSE_RANK() OVER (ORDER BY Points DESC) AS DenseRankPos FROM Scores;
SELECT Player, Points, DENSE_RANK() OVER (ORDER BY Points DESC) AS DenseRankPos FROM Scores;
DENSE_RANK() assigns the same rank to ties but does not skip ranks after ties.
DENSE_RANK() assigns the same rank to tied rows but the next rank is the immediate next integer. So Bob and Carol share rank 2, and Dave gets rank 3.
Why does the RANK() function sometimes skip rank numbers after ties?
Think about how RANK() reflects the position of rows in the sorted order.
RANK() assigns the same rank to tied rows but then skips the next ranks to reflect the actual position in the sorted list. For example, if two rows tie at rank 2, the next rank is 4, skipping 3.
Which scenario best describes when to use DENSE_RANK() instead of RANK()?
Consider if you want ranks to be consecutive numbers or to reflect gaps.
DENSE_RANK() is used when you want ranks to be consecutive numbers without gaps, even if there are ties. This is useful when you want a compact ranking sequence.
Which of the following SQL queries will cause a syntax error?
SELECT Player, Points, RANK(ORDER BY Points DESC) AS RankPos FROM Scores;
Check the correct syntax for window functions like RANK().
RANK() requires the OVER clause with parentheses. Option D misses OVER and will cause a syntax error.