SQL Interview Questions · Question 14

A ranking query contains duplicate salaries. How will ROW_NUMBER(), RANK(), and DENSE_RANK() assign values differently?

Interview preparation resource from Gate Smashers.

Interview-ready answer

ROW_NUMBER gives every row a unique sequence; RANK gives ties the same rank and leaves gaps; DENSE_RANK gives ties the same rank without gaps.

Ranking behaviour
SalaryROW_NUMBERRANKDENSE_RANK
90000111
80000222
80000322
70000443
SQL querysql
SELECT employee_name,
       salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_no,
       RANK() OVER (ORDER BY salary DESC)     AS rank_no,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank_no
FROM Employees;
Understand it clearly

Direct answer

ROW_NUMBER assigns a unique sequential number to each row. RANK assigns the same rank to tied values but leaves gaps after ties. DENSE_RANK assigns the same rank to tied values and does not leave gaps.

Concrete example

For the salaries 90000, 80000, 80000 and 70000 the functions produce different sequences as shown in the table below.

  • ROW_NUMBER: 1, 2, 3, 4 (unique sequence for every row)
  • RANK: 1, 2, 2, 4 (ties share rank; gap after the tie)
  • DENSE_RANK: 1, 2, 2, 3 (ties share rank; no gap)

Practical notes

When you need repeatable ordering with ROW_NUMBER (so ties always resolve the same way), add a deterministic tie-breaker to ORDER BY (for example, ORDER BY salary DESC, employee_id ASC). Use DENSE_RANK when you need the nth distinct salary (e.g., find the 2nd highest distinct salary).

SQL example

This query shows all three ranking functions over salaries ordered descending.

Quick comparison
BasisROW_NUMBERRANK / DENSE_RANK
Tie handlingAssigns a unique sequential number to every row (no ties).Assigns the same rank to tied values.
Gaps after tiesNever leaves gaps (numbers continue sequentially).RANK leaves gaps after ties; DENSE_RANK does not leave gaps.
Typical use caseWhen each row needs a unique sequence or when you use a deterministic tie-breaker to enforce repeatable order.When you care about ranks of distinct values (e.g., nth distinct salary) or preserving ties as equal ranks.