Sub topic 5
Top-N per group
Assume you know SELECT, WHERE, ORDER BY, LIMIT, joins, table aliases, and subqueries in FROM. This chapter uses PostgreSQL's LATERAL keyword to return a limited number of rows for every group.
“Top-N per group” means choosing the best few rows separately inside each group. For example, you might need the three newest orders for every customer. A single LIMIT 3 cannot do that. It limits the complete result, so it returns only three orders overall.
A lateral subquery solves this by running once for each row produced by the table on its left.
The basic pattern
Suppose the tables have these columns:
customers(id, name)orders(id, customer_id, created_at, total)
The left side supplies one customer ID. The LATERAL subquery can use that ID in its WHERE clause.
SELECT c.id,
c.name,
o.id AS order_id,
o.created_at,
o.total
FROM customers AS c
CROSS JOIN LATERAL (
SELECT id, created_at, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o
ORDER BY c.id, o.created_at DESC, o.id DESC;For each customer, PostgreSQL evaluates the subquery, filters that customer's orders, sorts them, and keeps three rows. The final result can therefore contain three rows for each customer.
The second sort key, id DESC, makes the result deterministic when two orders have the same created_at. Without a tie-breaker, PostgreSQL may return tied rows in either order.
CROSS JOIN LATERAL keeps only customers for which the subquery returns at least one row. A customer with no orders disappears from the result.
Keeping groups with fewer than N rows
Use LEFT JOIN LATERAL when every group must remain in the result, including groups with no matching rows.
SELECT c.id,
c.name,
o.id AS order_id,
o.created_at,
o.total
FROM customers AS c
LEFT JOIN LATERAL (
SELECT id, created_at, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o ON true
ORDER BY c.id, o.created_at DESC NULLS LAST, o.id DESC NULLS LAST;The condition ON true means that the lateral subquery itself determines whether a match exists. When it returns no rows, the LEFT JOIN supplies one result row with NULL in the order columns.
A group with one or two matching rows returns those rows. A group with more than three returns only its three newest rows. A group with none returns one row with NULL order values in the left-join version.
Choosing the ordering rule
“Top” has meaning only when you define an order. Common choices include:
- newest:
ORDER BY created_at DESC - highest value:
ORDER BY total DESC - lowest price:
ORDER BY price ASC - highest score:
ORDER BY score DESC
Add a unique column as a final tie-breaker when the primary ordering column is not unique.
For example, the following returns the three most expensive orders for each customer:
SELECT c.id,
c.name,
o.id AS order_id,
o.total
FROM customers AS c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY total DESC, id DESC
LIMIT 3
) AS o;Do not move LIMIT 3 outside the lateral subquery. This would limit the complete joined result rather than applying the limit independently to each customer.
Checking the plan
The useful index usually begins with the correlation column, followed by the ordering column.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC, id DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.id, o.id AS order_id
FROM customers AS c
CROSS JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o;EXPLAIN shows the plan PostgreSQL selected. ANALYZE executes the query and adds actual row counts and timing. BUFFERS shows shared-buffer activity.
Look for an index scan on orders that uses customer_id and can produce rows in the requested order. The LIMIT should allow PostgreSQL to stop reading after finding the required rows for each customer. Compare estimated and actual rows. Large differences can indicate stale statistics or an inaccurate data distribution.
Alternatives
A window function can also solve top-N-per-group problems:
SELECT id, customer_id, created_at, total
FROM (
SELECT o.*,
row_number() OVER (
PARTITION BY customer_id
ORDER BY created_at DESC, id DESC
) AS position
FROM orders AS o
) AS ranked
WHERE position <= 3;Prefer a window function when you are ranking one complete table result. Prefer LATERAL when each group starts with a row from another table and an indexed lookup can fetch only a few rows.
Exercise
Which change keeps customers with no orders while still returning at most three orders per customer?
Show answer
Replace CROSS JOIN LATERAL with LEFT JOIN LATERAL and add ON true after the lateral subquery.