Window Functions · Lesson 59 of 64

SQL ROW_NUMBER, RANK and DENSE_RANK

What you will learn

  • How ROW_NUMBER() numbers rows
  • How RANK() and DENSE_RANK() handle ties
  • How to rank inside groups
  • Why you need a tie-breaker

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. ORDER BY inside OVER

Ranking needs an order: OVER (ORDER BY column) says what "first" means. The order inside OVER is separate from the ORDER BY of the query:

SELECT name, price,
       ROW_NUMBER() OVER (ORDER BY price DESC, product_id) AS row_no
FROM products
ORDER BY row_no
LIMIT 5;
name          price  row_no
------------  -----  ------
Water bottle   86.9       1
Tea kettle     79.0       2
Highlighters   79.0       3
Foam roller    79.0       4
Drawing kit    53.9       5
(5 rows)
SELECT account_id, balance_cents,
       ROW_NUMBER() OVER (ORDER BY balance_cents DESC, account_id) AS row_no
FROM accounts
ORDER BY row_no
LIMIT 5;
account_id  balance_cents  row_no
----------  -------------  ------
       398         502080       1
       243         432800       2
       165         428004       3
       238         401600       4
       295         379900       5
(5 rows)
SELECT code, credits,
       ROW_NUMBER() OVER (ORDER BY credits DESC, course_id) AS row_no
FROM courses
ORDER BY row_no
LIMIT 5;
code     credits  row_no
-------  -------  ------
MATH101        4       1
MATH301        4       2
SCI101         4       3
SCI201         4       4
SCI202         4       5
(5 rows)

ROW_NUMBER() gives 1, 2, 3, ... with no ties and no gaps. When two rows have the same value, the order between them is decided by the next term (product_id above). Without a tie-breaker the numbering between tied rows is not guaranteed.

2. RANK and DENSE_RANK: ties

Real rankings give tied rows the same rank. RANK() then skips numbers; DENSE_RANK() does not:

SELECT name, stock,
       ROW_NUMBER() OVER (ORDER BY stock DESC, product_id) AS row_no,
       RANK()       OVER (ORDER BY stock DESC) AS rank_no,
       DENSE_RANK() OVER (ORDER BY stock DESC) AS dense_no
FROM products
ORDER BY stock DESC, product_id
LIMIT 8 OFFSET 7;
name            stock  row_no  rank_no  dense_no
--------------  -----  ------  -------  --------
Footrest          150       8        1         1
Folding stool     150       9        1         1
Skipping rope     150      10        1         1
Board game        150      11        1         1
Chopping board     80      12       12         2
Hand trowel        80      13       12         2
Desk organiser     80      14       12         2
Paper clips        80      15       12         2
(8 rows)
SELECT account_id, balance_cents / 100000 AS hundred_thousands,
       ROW_NUMBER() OVER (ORDER BY balance_cents / 100000 DESC, account_id) AS row_no,
       RANK()       OVER (ORDER BY balance_cents / 100000 DESC) AS rank_no,
       DENSE_RANK() OVER (ORDER BY balance_cents / 100000 DESC) AS dense_no
FROM accounts
ORDER BY hundred_thousands DESC, account_id
LIMIT 8;
account_id  hundred_thousands  row_no  rank_no  dense_no
----------  -----------------  ------  -------  --------
       398                  5       1        1         1
       165                  4       2        2         2
       238                  4       3        2         2
       243                  4       4        2         2
        15                  3       5        5         3
        33                  3       6        5         3
        35                  3       7        5         3
       122                  3       8        5         3
(8 rows)
SELECT code, credits,
       ROW_NUMBER() OVER (ORDER BY credits DESC, course_id) AS row_no,
       RANK()       OVER (ORDER BY credits DESC) AS rank_no,
       DENSE_RANK() OVER (ORDER BY credits DESC) AS dense_no
FROM courses
ORDER BY credits DESC, course_id
LIMIT 8;
code     credits  row_no  rank_no  dense_no
-------  -------  ------  -------  --------
MATH101        4       1        1         1
MATH301        4       2        1         1
SCI101         4       3        1         1
SCI201         4       4        1         1
SCI202         4       5        1         1
CS201          4       6        1         1
CS301          4       7        1         1
MATH201        3       8        8         2
(8 rows)

The Shop example skips the first seven rows (OFFSET 7) so that you see the place where the tie ends and the gap appears. The numbers are still calculated over all rows.

Function Values 10, 10, 8
ROW_NUMBER() 1, 2, 3
RANK() 1, 1, 3 (a gap)
DENSE_RANK() 1, 1, 2 (no gap)

Use ROW_NUMBER when you need exactly one row per number, RANK for sports-style ranking, DENSE_RANK for "the second highest value".

3. Rank inside groups

Add PARTITION BY and the numbering restarts for each group:

SELECT category_id, name, price,
       RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS price_rank
FROM products
ORDER BY category_id, price_rank, product_id
LIMIT 8;
category_id  name              price  price_rank
-----------  ----------------  -----  ----------
          2  Tea kettle         79.0           1
          2  Ceramic mug        44.1           2
          2  Wooden spoon set   29.5           3
          2  Lunch box          29.5           3
          2  Chopping board     26.4           5
          2  Steel pan           6.6           6
          2  Glass jar           5.4           7
          3  Plant pot          42.9           1
(8 rows)
SELECT branch_id, account_id, balance_cents,
       RANK() OVER (PARTITION BY branch_id ORDER BY balance_cents DESC) AS balance_rank
FROM accounts
ORDER BY branch_id, balance_rank, account_id
LIMIT 8;
branch_id  account_id  balance_cents  balance_rank
---------  ----------  -------------  ------------
        1         243         432800             1
        1         165         428004             2
        1         418         337200             3
        1         425         325400             4
        1         204         311947             5
        1         221         305213             6
        1         193         290625             7
        1         194         276648             8
(8 rows)
SELECT department_id, code, credits,
       RANK() OVER (PARTITION BY department_id ORDER BY credits DESC) AS credit_rank
FROM courses
ORDER BY department_id, credit_rank, course_id
LIMIT 8;
department_id  code     credits  credit_rank
-------------  -------  -------  -----------
            1  MATH101        4            1
            1  MATH301        4            1
            1  MATH201        3            3
            2  SCI101         4            1
            2  SCI201         4            1
            2  SCI202         4            1
            2  SCI301         3            4
            3  LANG101        3            1
(8 rows)

4. Number the rows of a group

ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) numbers the rows of each group from 1. It is the basis for "first row per group" and "top N per group" (lesson 8.7):

Each customer's orders, numbered from the earliest:

SELECT customer_id, order_id, order_date,
       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, order_id) AS order_no
FROM orders
WHERE customer_id <= 2
ORDER BY customer_id, order_no
LIMIT 6;
customer_id  order_id  order_date  order_no
-----------  --------  ----------  --------
          1       135  2025-10-01         1
          1       289  2025-10-01         2
          1       328  2025-10-01         3
          1       554  2025-10-01         4
          1       952  2025-10-01         5
          1      1070  2025-10-01         6
(6 rows)
SELECT account_id, txn_id, txn_date,
       ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY txn_date, txn_id) AS txn_no
FROM transactions
WHERE account_id <= 2
ORDER BY account_id, txn_no
LIMIT 6;
account_id  txn_id  txn_date    txn_no
----------  ------  ----------  ------
         1    4704  2025-05-27       1
         1    4713  2025-05-28       2
         1    4820  2025-06-23       3
         1    4894  2025-07-10       4
         1    5059  2025-08-17       5
         1    5172  2025-09-08       6
(6 rows)
SELECT student_id, section_id, enrolled_on,
       ROW_NUMBER() OVER (PARTITION BY student_id ORDER BY enrolled_on, section_id) AS enrollment_no
FROM enrollments
WHERE student_id <= 2
ORDER BY student_id, enrollment_no
LIMIT 6;
student_id  section_id  enrolled_on  enrollment_no
----------  ----------  -----------  -------------
         1          30  2025-01-14               1
         1          41  2025-01-17               2
         1          19  2026-01-18               3
         2          32  2025-01-17               1
         2           6  2025-08-05               2
         2           9  2025-08-09               3
(6 rows)

5. Rank by an aggregate

You can rank the results of a GROUP BY, because the window is calculated after grouping:

SELECT category_id, COUNT(*) AS products,
       RANK() OVER (ORDER BY COUNT(*) DESC) AS size_rank
FROM products
GROUP BY category_id
ORDER BY size_rank, category_id
LIMIT 5;
category_id  products  size_rank
-----------  --------  ---------
          2         7          1
          5         7          1
         10         7          1
          3         6          4
          6         6          4
(5 rows)
SELECT branch_id, COUNT(*) AS accounts,
       RANK() OVER (ORDER BY COUNT(*) DESC) AS size_rank
FROM accounts
GROUP BY branch_id
ORDER BY size_rank, branch_id
LIMIT 5;
branch_id  accounts  size_rank
---------  --------  ---------
        1        87          1
        2        79          2
        5        76          3
        6        75          4
        4        69          5
(5 rows)
SELECT department_id, COUNT(*) AS courses,
       RANK() OVER (ORDER BY COUNT(*) DESC) AS size_rank
FROM courses
GROUP BY department_id
ORDER BY size_rank, department_id
LIMIT 5;
department_id  courses  size_rank
-------------  -------  ---------
            2        4          1
            1        3          2
            3        3          2
            4        3          2
            5        3          2
(5 rows)

Worked example: choose the function

Question Function
"number the rows 1, 2, 3 with no repeats" ROW_NUMBER()
"league table: tied teams share a place, next place is skipped" RANK()
"the second highest distinct price" DENSE_RANK(), then keep rank 2

Always add a tie-breaker to the ORDER BY of ROW_NUMBER, so the result is repeatable. The questions are made up.

Common mistakes

  • No tie-breaker in the OVER (ORDER BY ...) of ROW_NUMBER.
  • Using ROW_NUMBER when ties should share a rank.
  • Using RANK and expecting no gaps.
  • Filtering on the rank in the same SELECT (use a CTE, lesson 8.7).
  • Forgetting PARTITION BY and ranking all rows together.

Key takeaways

  • OVER (ORDER BY ...) sets the order for numbering and ranking.
  • ROW_NUMBER has no ties; RANK shares ranks and skips; DENSE_RANK shares ranks and does not skip.
  • PARTITION BY restarts the numbering for each group.
  • Add a tie-breaker to get a repeatable order.

Practice

1. What do RANK() and DENSE_RANK() return for values 10, 10, 8?

Show answer

RANK: 1, 1, 3. DENSE_RANK: 1, 1, 2.

2. Why add product_id to the ORDER BY inside ROW_NUMBER?

Show answer

As a tie-breaker, so tied rows always get the same numbers in the same order.

3. How do you restart the numbering for each customer?

Show answer

Add PARTITION BY customer_id inside OVER.

4. Can you rank the result of a GROUP BY?

Show answer

Yes, e.g. RANK() OVER (ORDER BY COUNT(*) DESC), because the window is calculated after grouping.

5. Which function finds "the second highest distinct value"?

Show answer

DENSE_RANK(), keeping rank 2.

6. Can you write WHERE row_no = 1 in the same SELECT?

Show answer

No. Window results are not allowed in WHERE; use a CTE or subquery.