Window Functions · Lesson 63 of 64

SQL Top N per Group

What you will learn

  • The number, then filter pattern
  • How to get the latest row per group
  • How to get the top N per group
  • How to treat ties

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. The problem

"The most expensive product of every category", "the latest order of every customer", "the three best students in each course". LIMIT cannot do it, because it limits the whole result, not each group. The pattern is:

  1. Number the rows inside each group with a window function.
  2. Filter on the number in an outer query (a CTE), because a window result cannot be used in WHERE.

2. The latest row per group

Number each customer's orders from the newest, then keep number 1:

WITH numbered AS (
    SELECT customer_id, order_id, order_date,
           ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS n
    FROM orders
)
SELECT customer_id, order_id, order_date
FROM numbered
WHERE n = 1
ORDER BY customer_id
LIMIT 5;
customer_id  order_id  order_date
-----------  --------  ----------
          1      2580  2025-10-01
          2      1522  2026-06-09
          3      2531  2026-05-28
          4       796  2026-05-04
          5       469  2026-08-13
(5 rows)
WITH numbered AS (
    SELECT account_id, txn_id, txn_date,
           ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY txn_date DESC, txn_id DESC) AS n
    FROM transactions
)
SELECT account_id, txn_id, txn_date
FROM numbered
WHERE n = 1
ORDER BY account_id
LIMIT 5;
account_id  txn_id  txn_date
----------  ------  ----------
         1    7390  2026-09-27
         2    7177  2026-08-29
         3    7055  2026-08-12
         4    3263  2024-05-10
         5    7296  2026-09-15
(5 rows)
WITH numbered AS (
    SELECT student_id, section_id, enrolled_on,
           ROW_NUMBER() OVER (PARTITION BY student_id ORDER BY enrolled_on DESC, section_id DESC) AS n
    FROM enrollments
)
SELECT student_id, section_id, enrolled_on
FROM numbered
WHERE n = 1
ORDER BY student_id
LIMIT 5;
student_id  section_id  enrolled_on
----------  ----------  -----------
         1          19  2026-01-18
         2           4  2026-01-16
         3          25  2026-01-26
         4           7  2025-01-24
         5          16  2025-08-06
(5 rows)

Exactly one row per group, even when two rows share the latest date, because ROW_NUMBER never ties and the tie-breaker (order_id DESC) decides. The correlated subquery of lesson 7.3 returned both.

3. The top 3 per group

Keep n <= 3:

WITH ranked AS (
    SELECT category_id, name, price,
           ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC, product_id) AS n
    FROM products
)
SELECT category_id, n, name, price
FROM ranked
WHERE n <= 3 AND category_id IN (2, 3)
ORDER BY category_id, n;
category_id  n  name              price
-----------  -  ----------------  -----
          2  1  Tea kettle         79.0
          2  2  Ceramic mug        44.1
          2  3  Wooden spoon set   29.5
          3  1  Plant pot          42.9
          3  2  Garden gloves      39.0
          3  3  Seed tray          39.0
(6 rows)
WITH ranked AS (
    SELECT branch_id, account_id, balance_cents,
           ROW_NUMBER() OVER (PARTITION BY branch_id ORDER BY balance_cents DESC, account_id) AS n
    FROM accounts
)
SELECT branch_id, n, account_id, balance_cents
FROM ranked
WHERE n <= 3 AND branch_id IN (1, 2)
ORDER BY branch_id, n;
branch_id  n  account_id  balance_cents
---------  -  ----------  -------------
        1  1         243         432800
        1  2         165         428004
        1  3         418         337200
        2  1         122         364200
        2  2         260         314200
        2  3         316         301400
(6 rows)
WITH ranked AS (
    SELECT department_id, code, credits,
           ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY credits DESC, course_id) AS n
    FROM courses
)
SELECT department_id, n, code, credits
FROM ranked
WHERE n <= 3 AND department_id IN (1, 2)
ORDER BY department_id, n;
department_id  n  code     credits
-------------  -  -------  -------
            1  1  MATH101        4
            1  2  MATH301        4
            1  3  MATH201        3
            2  1  SCI101         4
            2  2  SCI201         4
            2  3  SCI202         4
(6 rows)

The extra filter on the group (category_id IN (2, 3)) only keeps the output short. Put it inside the CTE (with the partition column) if the table is big, so fewer rows are numbered.

4. Ties: RANK instead of ROW_NUMBER

ROW_NUMBER forces exactly N rows per group and cuts through a tie arbitrarily (by the tie-breaker). If "everyone tied for the top" should be kept, use RANK:

WITH ranked AS (
    SELECT category_id, name, stock,
           RANK() OVER (PARTITION BY category_id ORDER BY stock DESC) AS r
    FROM products
)
SELECT category_id, r, name, stock
FROM ranked
WHERE r = 1 AND category_id IN (2, 3, 5)
ORDER BY category_id, name;
category_id  r  name            stock
-----------  -  --------------  -----
          2  1  Ceramic mug       150
          3  1  Plant pot         150
          3  1  Pruning shears    150
          3  1  Seed tray         150
          3  1  Watering can      150
          5  1  Highlighters      150
          5  1  Notebook A5       150
(7 rows)
WITH ranked AS (
    SELECT branch_id, account_type, COUNT(*) AS accounts,
           RANK() OVER (PARTITION BY branch_id ORDER BY COUNT(*) DESC) AS r
    FROM accounts GROUP BY branch_id, account_type
)
SELECT branch_id, r, account_type, accounts
FROM ranked
WHERE r = 1
ORDER BY branch_id, account_type;
branch_id  r  account_type  accounts
---------  -  ------------  --------
        1  1  checking            58
        2  1  checking            56
        3  1  checking            47
        4  1  checking            46
        5  1  checking            56
        6  1  checking            53
(6 rows)
WITH ranked AS (
    SELECT department_id, code, credits,
           RANK() OVER (PARTITION BY department_id ORDER BY credits DESC) AS r
    FROM courses
)
SELECT department_id, r, code, credits
FROM ranked
WHERE r = 1
ORDER BY department_id, code;
department_id  r  code     credits
-------------  -  -------  -------
            1  1  MATH101        4
            1  1  MATH301        4
            2  1  SCI101         4
            2  1  SCI201         4
            2  1  SCI202         4
            3  1  LANG101        3
            3  1  LANG201        3
            4  1  HUM101         3
            4  1  HUM201         3
            5  1  ART101         2
            5  1  ART201         2
            5  1  ART202         2
... (14 rows in total, the first 12 shown)

A group with a tie for first place shows several rows. Choose between ROW_NUMBER (exact N) and RANK (keep ties) by what the question means.

5. Compare with the group's best

Combine a window with the filter: each row next to the best row of its group, or the gap to the leader:

SELECT category_id, name, price,
       MAX(price) OVER (PARTITION BY category_id) AS category_best,
       ROUND(MAX(price) OVER (PARTITION BY category_id) - price, 2) AS gap_to_best
FROM products
WHERE category_id = 2
ORDER BY price DESC, product_id
LIMIT 4;
category_id  name              price  category_best  gap_to_best
-----------  ----------------  -----  -------------  -----------
          2  Tea kettle         79.0           79.0          0.0
          2  Ceramic mug        44.1           79.0         34.9
          2  Wooden spoon set   29.5           79.0         49.5
          2  Lunch box          29.5           79.0         49.5
(4 rows)
SELECT branch_id, account_id, balance_cents,
       MAX(balance_cents) OVER (PARTITION BY branch_id) AS branch_best,
       MAX(balance_cents) OVER (PARTITION BY branch_id) - balance_cents AS gap_to_best
FROM accounts
WHERE branch_id = 1
ORDER BY balance_cents DESC, account_id
LIMIT 4;
branch_id  account_id  balance_cents  branch_best  gap_to_best
---------  ----------  -------------  -----------  -----------
        1         243         432800       432800            0
        1         165         428004       432800         4796
        1         418         337200       432800        95600
        1         425         325400       432800       107400
(4 rows)
SELECT department_id, code, credits,
       MAX(credits) OVER (PARTITION BY department_id) AS department_best,
       MAX(credits) OVER (PARTITION BY department_id) - credits AS gap_to_best
FROM courses
WHERE department_id = 1
ORDER BY credits DESC, course_id
LIMIT 4;
department_id  code     credits  department_best  gap_to_best
-------------  -------  -------  ---------------  -----------
            1  MATH101        4                4            0
            1  MATH301        4                4            0
            1  MATH201        3                4            1
(3 rows)

Worked example: the pattern

"The two most recent orders of every customer."

Step Do
1 ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS n
2 put it in a CTE
3 SELECT ... FROM cte WHERE n <= 2
4 check: no customer appears more than twice

Change <= 2 to <= N for any N. The question is made up from the Shop sample.

Common mistakes

  • Using LIMIT for "top N per group".
  • Filtering on the number in the same SELECT (needs a CTE).
  • No tie-breaker in the window's ORDER BY.
  • ROW_NUMBER when ties should all stay, or RANK when exactly N rows are needed.
  • Numbering the whole table when a WHERE could first reduce it.

Key takeaways

  • Number rows in each group (ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)), then filter the number in an outer query.
  • n = 1 gives the latest or best row per group; n <= N gives the top N.
  • Use RANK when tied rows should all be kept.
  • Always add a tie-breaker so the result is repeatable.

Practice

1. Why can't you write WHERE ROW_NUMBER() OVER (...) = 1?

Show answer

Window functions are not allowed in WHERE. Number the rows in a CTE and filter outside.

2. Which function gives exactly one row per group for "the latest"?

Show answer

ROW_NUMBER() with WHERE n = 1.

3. How do you keep everyone tied for first?

Show answer

Use RANK() and filter r = 1.

4. What goes in PARTITION BY for "top 3 products per category"?

Show answer

category_id.

5. Why add order_id DESC to the window's order?

Show answer

As a tie-breaker, so two orders on the same date always come out in the same order.

6. Why is the window approach better than the correlated subquery here?

Show answer

It returns exactly one row per group even with ties, and scans the table once instead of once per row.