Skip to content

ROW_NUMBER vs RANK vs DENSE_RANK: SQL Ranking Functions Explained

Three ranked lists showing how ties are numbered by ROW_NUMBER, RANK and DENSE_RANK.

Ranking rows is one of the most common jobs for window functions: find the top three products per region, keep the latest record per customer, number rows within a group. Three functions look almost identical, ROW_NUMBER, RANK and DENSE_RANK, and the only difference is what they do with ties.

The three functions side by side

Suppose a table of results has these scores: 90, 85, 85 and 80. The query below numbers them three ways.

SELECT name, score,
       ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
       RANK()       OVER (ORDER BY score DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rnk
FROM results;
score ROW_NUMBER RANK DENSE_RANK
90 1 1 1
85 2 2 2
85 3 2 2
80 4 4 3
  • ROW_NUMBER gives every row a unique number. Tied rows still get different numbers.
  • RANK gives tied rows the same number and then skips ahead, so after two rows tied at 2, the next is 4.
  • DENSE_RANK gives tied rows the same number and does not skip, so the next is 3.

Ties and ROW_NUMBER

When rows tie on the ordering column, ROW_NUMBER picks an order among them arbitrarily, and it may differ between runs. If the result matters, add a tie-breaker, such as an ID, to the ORDER BY so the numbering is deterministic.

Top N per group

The PARTITION BY clause restarts the numbering for each group. Because window functions cannot be filtered in the same query’s WHERE clause, wrap the ranking in a CTE and filter outside it, as explained in SQL CTEs explained.

WITH ranked AS (
    SELECT region, product, revenue,
           ROW_NUMBER() OVER (
               PARTITION BY region ORDER BY revenue DESC
           ) AS rn
    FROM sales
)
SELECT region, product, revenue
FROM ranked
WHERE rn <= 3;

Use RANK or DENSE_RANK instead if tied products should all be included, and ROW_NUMBER if you want exactly three rows per region.

Keeping the latest record per key

Numbering rows within each key, newest first, and keeping number one is a standard way to remove duplicates, covered further in data deduplication.

WITH numbered AS (
    SELECT *,
           ROW_NUMBER() OVER (
               PARTITION BY customer_id ORDER BY updated_at DESC
           ) AS rn
    FROM customers_raw
)
SELECT * FROM numbered WHERE rn = 1;

LAG and LEAD: comparing with neighbors

LAG returns a value from a previous row, and LEAD returns one from a following row, within the window ordering. They are handy for change over time, such as the difference between this month’s revenue and last month’s.

SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_revenue;

The first row has no previous value, so its result is NULL, which behaves the way described in SQL NULL explained.

When to use window functions instead of grouping

Grouping collapses rows into one per group, as in GROUP BY and HAVING. Window functions keep every row and add a calculated column, which is why they suit rankings and comparisons. How they compare with subqueries is covered in window functions vs subqueries.

A quick checklist

  1. Do ties matter? Choose RANK or DENSE_RANK if they do, ROW_NUMBER if you need exact counts.
  2. Did you add a tie-breaker to make ROW_NUMBER repeatable?
  3. Is the ranking wrapped in a CTE before you filter on it?
  4. Did you use PARTITION BY to restart numbering per group?
  5. Did you account for NULL in the first row of LAG and LEAD?

If you want reporting queries and dashboards built on your data, see my analytics dashboards service.

FAQ

What is the difference between RANK and DENSE_RANK?
Both give tied rows the same number. RANK then skips numbers after a tie, while DENSE_RANK continues with the next consecutive number.

How do I get the top N rows per group in SQL?
Number the rows with ROW_NUMBER partitioned by the group and ordered by the value, put that in a CTE, and filter for numbers up to N.

Can I filter on a window function in the WHERE clause?
No. Window functions are calculated after WHERE, so compute them in a CTE or subquery and filter in the outer query.

Related posts

Leave a comment

Your email address will not be published. Required fields are marked *