← All lessons
Advanced SQL · Lesson 4 of 11

Top N per group and duplicates

"The latest order for each customer" or "the two best sellers in each category" come up all the time. GROUP BY can find each customer's latest date, but not the rest of that order's row. The pattern: number the rows in each group with ROW_NUMBER in a CTE, then keep the numbers you want outside it.

WITH ranked AS (
  SELECT customer_id, id, ordered_on,
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_on DESC) AS rn
  FROM orders
)
SELECT customer_id, id, ordered_on
FROM ranked
WHERE rn = 1
ORDER BY customer_id;
Returns
customer_id | id  | ordered_on
------------+-----+-----------
1           | 108 | 2024-10-05
2           | 106 | 2024-09-20
3           | 110 | 2024-10-11
4           | 105 | 2024-09-15
5           | 107 | 2024-10-02
6           | 109 | 2024-10-07
(6 rows)

rn <= 2 gives the top two per group, and so on. Choose the function for ties on purpose. ROW_NUMBER gives exactly N rows per group and picks between tied rows arbitrarily, so add a tie-breaker to the ORDER BY. RANK keeps every tied row, so you can get more than N:

WITH ranked AS (
  SELECT name, role, salary,
    RANK() OVER (PARTITION BY role ORDER BY salary DESC) AS r
  FROM staff
)
SELECT role, name, salary
FROM ranked
WHERE r = 1 AND role IN ('Packer', 'Sales')
ORDER BY role, name;
Returns
role   | name | salary
-------+------+-------
Packer | Theo | 36000
Packer | Zara | 36000
Sales  | Mia  | 43000
(3 rows)

Both packers earn the top packer salary, so both are kept. Some warehouses (Snowflake, BigQuery, Databricks, DuckDB) let you skip the CTE with QUALIFY rn = 1, a WHERE for window functions.

The same pattern removes duplicates. First decide what makes two rows the same, called the key. In signups it's the email address, ignoring capital letters. Number the rows within each key; keep number 1. The ORDER BY in the window decides which copy wins, here the latest:

WITH ranked AS (
  SELECT id, LOWER(email) AS email, name,
    ROW_NUMBER() OVER (PARTITION BY LOWER(email) ORDER BY signed_up_at DESC) AS rn
  FROM signups
)
SELECT id, email, name
FROM ranked
WHERE rn = 1
ORDER BY email;
Returns
id | email            | name
---+------------------+---------
3  | [email protected]  | Ana
7  | [email protected]  | Benjamin
4  | [email protected] | Cleo
6  | [email protected]  | Dev
(4 rows)

SELECT DISTINCT can't do this: it only drops rows identical in every column, and Ben and Benjamin share an email but not a name. To find the repeats in the first place, GROUP BY LOWER(email) HAVING COUNT(*) > 1.

Practice

The dearest product in each category: category, name and price. Use ROW_NUMBER in a CTE.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

ROW_NUMBER() … WHERE rn <= nExactly n rows per group (add a tie-breaker).
RANK() … WHERE r = 1Every row tied for first.
QUALIFY rn = 1Filter on a window function (some warehouses).
PARTITION BY LOWER(email)Duplicates by a cleaned-up key.
GROUP BY key HAVING COUNT(*) > 1Find the keys that repeat.

The other AI and data engineering courses