Introduction
RANK and DENSE_RANK help us order data by giving positions to rows based on values, but they handle ties differently.
RANK() OVER (ORDER BY column_name [ASC|DESC]) DENSE_RANK() OVER (ORDER BY column_name [ASC|DESC])
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM players;
SELECT name, score, DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank FROM players;
WITH players AS ( SELECT 'Alice' AS name, 100 AS score UNION ALL SELECT 'Bob', 90 UNION ALL SELECT 'Charlie', 90 UNION ALL SELECT 'David', 80 ) SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank, DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank FROM players ORDER BY score DESC;
RANK() and DENSE_RANK() functions in SQL?RANK() works with tiesRANK() assigns the same rank to tied rows but skips the next rank numbers accordingly. For example, if two rows tie for rank 1, the next rank will be 3.DENSE_RANK() works with tiesDENSE_RANK() also assigns the same rank to tied rows but does not skip rank numbers. So after two rows tied at rank 1, the next rank will be 2.RANK() skips rank numbers after ties, DENSE_RANK() does not skip numbers. -> Option BRANK() [OK]DENSE_RANK()?DENSE_RANK() syntaxDENSE_RANK() OVER (ORDER BY column) to rank rows based on a column.Scores with values:Player | Score
Alice | 100
Bob | 90
Carol | 90
Dave | 80SELECT Player, Score, RANK() OVER (ORDER BY Score DESC) AS Rank, DENSE_RANK() OVER (ORDER BY Score DESC) AS DenseRank FROM Scores;
RANK() valuesDENSE_RANK() valuesSELECT name, RANK() ORDER BY score DESC FROM players;
RANK() function usageRANK() is a window function and must be followed by OVER() clause specifying order.OVER() clauseRANK() without OVER(), causing syntax error.Salesperson | SalesAmount
John | 500
Jane | 700
Joe | 700
Jill | 600DENSE_RANK() assigns same rank to ties and does not skip ranks. RANK() skips ranks after ties. ROW_NUMBER() never assigns same rank to ties. SELECT Salesperson, SalesAmount, RANK() OVER (PARTITION BY SalesAmount ORDER BY SalesAmount DESC) AS Rank FROM sales; misuses PARTITION BY.Pass the test and this pattern moves unknown