QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Window functions

How do ROW_NUMBER, RANK and DENSE_RANK differ?

ROW_NUMBER, RANK and DENSE_RANK number rows by an ordering and differ only in how they treat equal values. ROW_NUMBER gives every row a unique number, RANK gives equal rows the same rank and skips the following numbers, and DENSE_RANK gives the same rank without gaps. ROW_NUMBER is used for deduplication, DENSE_RANK for the Nth value with ties, and a unique key is added to the ORDER BY of ROW_NUMBER.

SQL · Window functions

Two people share the second salary. Who is third by salary: somebody or nobody?

In the interview query "the third highest salary" two employees have the same second amount. One function returns a result, another an empty set, and a third gives a person whose salary is not the third highest by value. All three number rows by an ordering and differ only in what they do with equal values.

How it works and why. All three functions sort the window rows by ORDER BY inside OVER and assign a number. For different values the result is the same. The difference appears on equal values (called ties). ROW_NUMBER ignores equality and gives every row a unique number, RANK gives equal rows the same rank and skips the following numbers, DENSE_RANK gives equal rows the same rank without gaps.

salaryROW_NUMBERRANKDENSE_RANK
9000111
8000222
8000322
7000443
SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS rn,
       RANK()       OVER (ORDER BY salary DESC)       AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC)       AS drnk
FROM employees
WHERE dept = 'Dev';
-- salaries 9000, 8000, 8000, 7000: rn 1,2,3,4; rnk 1,2,2,4; drnk 1,2,2,3

For the two 8000s RANK says "both are second" and skips third place, so the next one gets rank four (the number of rows above plus one). DENSE_RANK skips nothing: 7000 gets rank three. The order among equals in ROW_NUMBER is not defined: the example adds name as a second key so that Bohdan always goes before Clara.

Example: the Nth highest salary. The sample data: in Dev the salaries are 9000, 8000, 8000, 7000. The task "the third highest salary, count repeats as one":

-- the third highest salary with repeats allowed: 7000 (Dmytro)
WITH r AS (
  SELECT name, salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk
  FROM employees
  WHERE dept = 'Dev'
)
SELECT name, salary FROM r WHERE drnk = 3;
-- with RANK the result would be empty: there is no rank 3 (1, 2, 2, 4)

The answer is 7000 (Dmytro): there are three distinct values at the top, and 7000 is the third. With RANK the ranks would be 1, 2, 2, 4 and rank 3 simply does not exist, so the result is empty. With ROW_NUMBER the third would be Clara with 8000, although she does not have a third salary by value.

A tie and a second sort key

Unstable

ORDER BY salary DESC

For two salaries of 8000 ROW_NUMBER numbers them as it happens. Between runs and plans the order can change, and the test becomes flaky.

Stable

ORDER BY salary DESC, name

An extra unique key makes the order unambiguous. The same result every time.

Figure 1. ROW_NUMBER needs a deterministic order.
-- without a second key the order of equal salaries is arbitrary
ROW_NUMBER() OVER (ORDER BY salary DESC)

-- with an extra key the result is stable
ROW_NUMBER() OVER (ORDER BY salary DESC, name)

So the choice depends on the question. "Give one row per group" or "remove duplicates" is ROW_NUMBER. "A place in a ranking with equal places and a gap" is RANK. "The Nth by value, counting repeats once" is DENSE_RANK.

Limits and alternatives. The order of NULL depends on the database. In PostgreSQL NULL sorts as larger than any value, so ORDER BY salary DESC puts it first and it gets rank 1. In MySQL and SQL Server it is the opposite: NULL is treated as the smallest. Explicit NULLS FIRST and NULLS LAST (standard, available in PostgreSQL and Oracle) remove the question:

-- PostgreSQL: NULL goes first with DESC and gets rank 1
RANK() OVER (ORDER BY salary DESC)

-- explicit: NULL last
RANK() OVER (ORDER BY salary DESC NULLS LAST)

For a simple "Nth largest" without windows people sometimes write ORDER BY salary DESC LIMIT 1 OFFSET N-1, but it does not remove repeats and does not work "per group". There are also NTILE (splits into a given number of groups) and PERCENT_RANK, but interviews most often ask about the three main ones.

Typical mistakes.

  • ROW_NUMBER without a unique sort key: the result differs between runs.
  • RANK for "the Nth by value": a gap after a tie, the wanted rank is missing.
  • NULL in the sort column without NULLS LAST: an empty salary becomes "the highest".
  • Forgetting PARTITION BY in a "for each department" task: the whole list is ranked.
  • Adding WHERE rnk = 2 in the same query: the window function is not computed yet, a CTE is needed.

Check yourself

Salaries 9000, 8000, 8000, 7000. Which ranks do RANK and DENSE_RANK give for 7000?

Answer

RANK gives 4 because three rows with higher or equal salaries come before it. DENSE_RANK gives 3 because it counts only distinct values above: 9000, 8000, 7000.

Why is ROW_NUMBER used for deduplication by key and not RANK?

Answer

ROW_NUMBER always gives unique numbers, so the condition rn = 1 keeps exactly one row per group. RANK gives rank 1 to several rows on a tie, and duplicates would remain.

In an interview. Junior: All three number rows by an ordering, the difference is in equal values. ROW_NUMBER always gives unique numbers, RANK gives equal rows the same rank with a gap after them, DENSE_RANK without a gap. For "the second highest salary" with repeats I take DENSE_RANK, for deduplication ROW_NUMBER. Middle/Senior: In ROW_NUMBER I add a unique key to ORDER BY so the order on ties is deterministic. I remember NULL: in PostgreSQL it goes first with DESC, so I write NULLS LAST. I filter by rank in an outer query because a window function cannot go in WHERE.

More articles in this chapter