Rows with the Maximum per Group
Sometimes you need the whole row that holds the maximum value in each group, such as "the most recently joined customer in each grade". GROUP BY gives the maximum value, but not the other columns of the row that holds it.
GROUP BY gives only the value
SELECT grade, MAX(join_dt) AS last_join_dt
FROM customers
WHERE cust_id BETWEEN 1700 AND 3500
GROUP BY grade
ORDER BY grade
Adding cust_id to the SELECT is an error, because the column is not in GROUP BY. All examples in this chapter use customers 1700–3500. Join dates repeat in an 1800-day cycle, so VIP customers 1700 and 3500 have the same join date: a tie.
Correlated subquery: = MAX
For each outer row, compute the maximum of the same group and compare.
Most recently joined customer per grade (correlated subquery)
SELECT c.cust_id, c.grade, c.join_dt
FROM customers c
WHERE c.cust_id BETWEEN 1700 AND 3500
AND c.join_dt = (SELECT MAX(x.join_dt)
FROM customers x
WHERE x.grade = c.grade
AND x.cust_id BETWEEN 1700 AND 3500)
ORDER BY c.grade, c.cust_id
The result has 4 rows: GOLD 1790, NORMAL 1799, and VIP 1700 and 3500.
Aggregate in an inline view, then join
Compute the per-group maximum first in an inline view and join it to the original table. The join condition uses two columns: the group column and the value column.
Most recently joined customer per grade (inline view join)
SELECT c.cust_id, c.grade, c.join_dt
FROM customers c
JOIN (SELECT grade, MAX(join_dt) AS max_dt
FROM customers
WHERE cust_id BETWEEN 1700 AND 3500
GROUP BY grade) m
ON m.grade = c.grade AND m.max_dt = c.join_dt
WHERE c.cust_id BETWEEN 1700 AND 3500
ORDER BY c.grade, c.cust_id
In Oracle and PostgreSQL the same meaning can also be written as (c.grade, c.join_dt) IN (SELECT grade, MAX(join_dt) … GROUP BY grade) (row value comparison).
NOT EXISTS: rows with no larger row
Write "no row in the same group is larger than me" as is. No aggregate function is needed.
Most recently joined customer per grade (NOT EXISTS)
SELECT c.cust_id, c.grade, c.join_dt
FROM customers c
WHERE c.cust_id BETWEEN 1700 AND 3500
AND NOT EXISTS (SELECT 1
FROM customers x
WHERE x.grade = c.grade
AND x.cust_id BETWEEN 1700 AND 3500
AND x.join_dt > c.join_dt)
ORDER BY c.grade, c.cust_id
Because it uses >, tied rows do not eliminate each other, and both remain. The result is the same 4 rows as the two methods above.
Window function: ROW_NUMBER
Number the rows within each group and keep only number 1. The function itself is covered in Window Functions.
Most recently joined customer per grade (ROW_NUMBER)
SELECT cust_id, grade, join_dt
FROM (SELECT c.cust_id, c.grade, c.join_dt,
ROW_NUMBER() OVER (PARTITION BY c.grade ORDER BY c.join_dt DESC, c.cust_id) AS rn
FROM customers c
WHERE c.cust_id BETWEEN 1700 AND 3500) r
WHERE rn = 1
ORDER BY grade
The result has 3 rows. ROW_NUMBER gives different numbers even to ties, so exactly 1 row remains per group. For VIP, the second sort key cust_id picks 1700. Without a second key, which row remains is undefined. Replacing ROW_NUMBER() with RANK() ranks all ties first, giving 4 rows.
Ties and NULLs: different results per method
A small data set with ties and NULLs in the value column compares the four methods at once. Group A has a tie at 30, B has 20 and NULL, and C has only NULL.
Results per method (ties and NULLs)
WITH t AS (
SELECT grp, id, val
FROM (VALUES ('A', 1, 10), ('A', 2, 30), ('A', 3, 30),
('B', 4, 20), ('B', 5, NULL), ('C', 6, NULL)) v(grp, id, val)
)
SELECT 'max' AS method, t.grp, t.id, t.val
FROM t WHERE t.val = (SELECT MAX(x.val) FROM t x WHERE x.grp = t.grp)
UNION ALL
SELECT 'not_exists', t.grp, t.id, t.val
FROM t WHERE NOT EXISTS (SELECT 1 FROM t x WHERE x.grp = t.grp AND x.val > t.val)
UNION ALL
SELECT 'row_number', r.grp, r.id, r.val
FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY val DESC, id) AS rn FROM t) r
WHERE r.rn = 1
UNION ALL
SELECT 'row_number_nl', r.grp, r.id, r.val
FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY grp
ORDER BY CASE WHEN val IS NULL THEN 1 ELSE 0 END, val DESC, id) AS rn
FROM t) r
WHERE r.rn = 1
UNION ALL
SELECT 'rank_nl', r.grp, r.id, r.val
FROM (SELECT t.*, RANK() OVER (PARTITION BY grp
ORDER BY CASE WHEN val IS NULL THEN 1 ELSE 0 END, val DESC) AS rk
FROM t) r
WHERE r.rk = 1
ORDER BY method, grp, id
| Method | A (30, 30) | B (20, NULL) | C (NULL only) |
|---|---|---|---|
= MAX correlated subquery, inline view join | 2, 3 | 4 | none |
NOT EXISTS (no larger row) | 2, 3 | 4, 5 | 6 |
ROW_NUMBER … ORDER BY val DESC | 2 | Oracle, PostgreSQL: 5 / SQL Server: 4 | 6 |
ROW_NUMBER, NULLs last | 2 | 4 | 6 |
RANK, NULLs last | 2, 3 | 4 | 6 |
The differences come from the following.
- Ties:
= MAX,NOT EXISTS, andRANKkeep all ties.ROW_NUMBERkeeps only 1 row. - NULL and MAX:
MAXskips NULLs. For group C, which has only NULLs,MAXis NULL andval = NULLis unknown, so the whole group drops out. - NULL and NOT EXISTS:
x.val > NULLis unknown, so no "larger row" is found. Rows 5 and 6, which are NULL, remain as if they were the maximum. AddingAND t.val IS NOT NULLmakes it the same as= MAX. - NULL and sorting: In descending order, Oracle and PostgreSQL put NULLs first, and SQL Server puts them last (Sorting and Paging). So the same
ROW_NUMBERquery picks different rows per DB. PuttingCASE WHEN val IS NULL THEN 1 ELSE 0 ENDas the first sort key makes all three DBs agree.
Applying it to order data
Get each customer's most recent order with an inline view join. Order data differs per DB, so the results differ too.
Most recent order of customers 101–110
SELECT o.cust_id, o.ord_id, o.ord_dt, o.amt
FROM orders o
JOIN (SELECT cust_id, MAX(ord_dt) AS last_dt
FROM orders
WHERE cust_id BETWEEN 101 AND 110
GROUP BY cust_id) m
ON m.cust_id = o.cust_id AND m.last_dt = o.ord_dt
ORDER BY o.cust_id, o.ord_id
If the result has more than 10 rows, some customer has 2 or more orders at the same last order time. If you want only 1 row, use ROW_NUMBER with a unique key such as ord_id as the second sort key.
TIP Choose by the shape of the result. To see all ties, use
= MAX, an inline view join, orRANK; when you need exactly 1 row per group, useROW_NUMBERwith a unique sort key. Check speed differences between methods that return the same result in the execution plan (tuning scenario 4, 7).