DENSE_RANK()
Rank without gaps — consecutive numbers even when values tie
DENSE_RANK: No Gaps
DENSE_RANK() gives tied values the same rank but never skips numbers. After a tie, the next rank is always the immediately following integer — no gaps in the sequence. Here's the comparison:
WHERE dense_rnk <= 3 gives exactly 3 distinct value tiers, regardless of how many individual items share each tier. Ideal for queries like "top 3 salary bands" or "5 highest price levels."How DENSE_RANK Works
Rank without gaps — consecutive numbers
- Tied values share the same rank (like RANK)
- Next rank is consecutive — no gaps: 1, 2, 2, 3
- DENSE_RANK ≤ number of distinct values
- Best for "top N distinct values" queries
ROW_NUMBER vs RANK vs DENSE_RANK
The complete ranking function comparison
When to Use DENSE_RANK
Ideal scenarios
- "Top 3 price tiers" (may return many products)
- "Nth highest value" problems
- Bucketing by rank without gaps
- Interview classic: "Find the 2nd highest price"
Interview Classic
The Nth highest price
- DENSE_RANK() OVER (ORDER BY price DESC) AS rnk
- Filter WHERE rnk = 2 for 2nd highest
- Returns ALL products at that price
- Use ROW_NUMBER if you want exactly one row
SELECT name, price FROM (
SELECT name, price,
DENSE_RANK() OVER (ORDER BY price DESC) AS rnk
FROM products
) WHERE rnk = 2;DENSE_RANK()Same rank for ties, NO gaps: 1, 2, 2, 3Top N distinctWHERE dense_rnk <= N gives N distinct levels| name | price |
|---|---|
| Wireless Mouse | 24.99 |
| Office Desk | 189 |
| LED Desk Lamp | 45.5 |
| USB-C Cable | 12.99 |
| Bluetooth Speaker | 79 |
| Office Chair | 95 |
| Coffee Maker | 89.99 |
| Notebook Set | 8.5 |
| Wireless Headphones | 159 |
| Standing Desk | 425 |
Worked Example
Show the top 3 distinct price levels among products.
| name | price | price_tier |
|---|---|---|
| Standing Desk | 425 | 1 |
| Office Desk | 189 | 2 |
| Wireless Headphones | 159 | 3 |
Key Concepts
Pro Tip
DENSE_RANK is the right choice for "top N distinct levels" — like the 3 highest salary bands, regardless of how many employees share each one.
When to Use
Top N salary tiers, price tier analysis, grading systems with consecutive grades, finding the Nth highest value.
Find the 2nd highest product price (not the 2nd most expensive product — the 2nd distinct price level). Show the price. Use DENSE_RANK.