Sub topic 5
Top-N per group
This chapter uses CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true to return the newest N rows for each group. It assumes you can write SELECT, WHERE, ORDER BY and LIMIT, and that you know inner and left joins, subqueries in FROM, and table aliases. It also assumes you have read the earlier chapters on what LATERAL does.
The problem
"Show each customer's three most recent orders" is a common request. It is awkward in plain SQL because LIMIT applies to the whole result, not to each group:
ORDER BY created_at DESC LIMIT 3returns three rows in total, not three per customer.GROUP BY customer_idcollapses each customer into one row, so you lose the individual orders.
LATERAL solves this directly. For each row of the outer table, it runs a small query that has its own ORDER BY and LIMIT. Because that query can see the outer row, its LIMIT applies to one group at a time.
Sample data
The examples in this chapter use these tables. Run this first if you want to follow along.
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total numeric(10,2) NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ana'), (2, 'Ben'), (3, 'Chi');
INSERT INTO orders (id, customer_id, total, status, created_at) VALUES
(1, 1, 20.00, 'paid', '2026-01-01 10:00+00'),
(2, 1, 35.50, 'paid', '2026-01-05 10:00+00'),
(3, 1, 12.00, 'refunded', '2026-01-09 10:00+00'),
(4, 1, 80.00, 'paid', '2026-01-12 10:00+00'),
(5, 1, 15.25, 'paid', '2026-01-20 10:00+00'),
(6, 2, 50.00, 'paid', '2026-01-03 10:00+00'),
(7, 2, 70.00, 'paid', '2026-01-15 10:00+00');Ana has five orders, Ben has two, and Chi has none.
The basic pattern
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o;The result:
| id | name | order_id | total |
|---|---|---|---|
| 1 | Ana | 5 | 15.25 |
| 1 | Ana | 4 | 80.00 |
| 1 | Ana | 3 | 12.00 |
| 2 | Ben | 7 | 70.00 |
| 2 | Ben | 6 | 50.00 |
A top-N lateral subquery has three parts, and each does a different job:
- The correlation predicate.
orders.customer_id = c.idties the subquery to the current outer row. It defines the group. - The ordering.
ORDER BY created_at DESCdefines what "top" means. - The limit.
LIMIT 3is N. It cuts off each group separately because the subquery runs once per group.
Chi has no orders, so the subquery returns zero rows for her. A cross join of her row with nothing produces nothing, so she is missing from the result.
This is the logical model. The planner may execute the query differently, as long as the result is the same. In practice a nested loop is common for this pattern, with the lateral subquery as the inner side.
Keeping groups that have no rows
To keep Chi in the output, use LEFT JOIN LATERAL ... ON true:
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o ON true
ORDER BY c.id;Chi now appears once, with NULL in order_id and total. The ON true is required syntax. A left join needs an ON clause, but the real matching already happens inside the subquery, so the condition is always true.
Choose between the two forms by asking what an empty group should mean:
- Use
CROSS JOIN LATERALwhen you only want groups that have data. - Use
LEFT JOIN LATERAL ... ON truewhen every outer row must appear, for example in a report that lists all customers.
Make the order deterministic
ORDER BY created_at DESC LIMIT 3 is only well defined if created_at values are unique within a group. If two orders share a timestamp at the cut-off, PostgreSQL may return either one, and the choice can change between runs or after an index change.
Add a tie-breaker, usually the primary key:
SELECT c.id, o.id AS order_id, o.created_at
FROM customers c
CROSS JOIN LATERAL (
SELECT id, created_at
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o;If you would rather keep every tied row, PostgreSQL 13 and later supports FETCH FIRST 3 ROWS WITH TIES in place of LIMIT 3. The group can then return more than three rows. WITH TIES requires an ORDER BY, and it counts ties only on the columns you sort by. In this example it would only treat rows as tied if they had the same created_at, so do not add id to the sort if you want it to work.
Filtering: inside or outside the subquery
Where you put a filter changes the result. Suppose you want each customer's three most recent paid orders.
Filtering inside the subquery is correct:
SELECT c.id, o.id AS order_id, o.status
FROM customers c
CROSS JOIN LATERAL (
SELECT id, status
FROM orders
WHERE orders.customer_id = c.id
AND orders.status = 'paid'
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o;Ana's rows are orders 5, 4 and 2. The refunded order 3 is skipped before LIMIT runs.
Filtering outside is a different question:
SELECT c.id, o.id AS order_id, o.status
FROM customers c
CROSS JOIN LATERAL (
SELECT id, status
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o
WHERE o.status = 'paid';This takes Ana's latest three orders (5, 4, 3) and then removes the refunded one. She gets only two rows. The first query answers "the latest three paid orders". The second answers "which of the latest three orders were paid".
A rule that covers both cases:
- A condition on the rows being ranked belongs inside the subquery.
- A condition on the groups, such as
c.country = 'DE', belongs in the outer query. This also saves work, because the subquery runs only for outer rows that survive the filter.
Groups that are not in their own table
You do not need a customers table to use the pattern. If the group key only exists in the fact table, build the list of groups in a derived table:
SELECT g.customer_id, o.id AS order_id, o.created_at
FROM (SELECT DISTINCT customer_id FROM orders) AS g
CROSS JOIN LATERAL (
SELECT id, created_at
FROM orders
WHERE orders.customer_id = g.customer_id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o;A real lookup table is usually better. It is already small, and it avoids scanning the large table to find the distinct keys.
Showing each row's rank
Sometimes you want a rank column such as 1, 2, 3 beside each kept row. Compute it inside the subquery with a window function. The window runs only over that group's rows:
SELECT c.id, o.rank, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id,
row_number() OVER (ORDER BY created_at DESC, id DESC) AS rank
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 3
) AS o;LIMIT is applied after the window function is computed, so the ranks are 1, 2 and 3 for each customer who has enough orders.
Ordering NULLs
DESC puts NULL values first by default in PostgreSQL. If the sort column can be null, for example a shipped_at date that is empty until shipping, a "most recent" query will return the unshipped rows first. Say what you mean:
ORDER BY shipped_at DESC NULLS LAST, id DESCIf you also want an index to serve this sort, the index must declare the same order, for example (customer_id, shipped_at DESC NULLS LAST).
Making it fast
The lateral subquery runs once per outer row. Its cost depends on how cheaply it can find the newest rows for one customer.
Without a suitable index, each run reads all of that customer's orders and sorts them just to keep three. A composite index on the correlation column followed by the sort column removes both steps:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);PostgreSQL can now go to the entries for one customer_id, read them already sorted, and stop after three. To confirm this, look at the plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.id, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o;In the output, look for an index scan on orders_customer_created_idx under a Limit node, with no separate Sort node. Check the loops= count on that inner node. It should equal the number of customers that were processed.
If your query sorts by created_at DESC, id DESC, the index needs to match, for example (customer_id, created_at DESC, id DESC). Otherwise the planner cannot return rows in that order straight from the index. The index and the query's ORDER BY should agree.
When a window function is better
The same result can be written with row_number():
SELECT id, customer_id, total
FROM (
SELECT o.id, o.customer_id, o.total,
row_number() OVER (
PARTITION BY o.customer_id
ORDER BY o.created_at DESC, o.id DESC
) AS rn
FROM orders o
) AS ranked
WHERE rn <= 3;The trade-offs:
| Situation | Better fit |
|---|---|
| Few groups, many rows per group, matching index | `LATERAL` |
| You filter the groups first, so only a few of them are needed | `LATERAL` |
| Many groups with only a few rows each | Window function |
| You need every group and no useful index exists | Window function |
| You must keep empty groups | `LEFT JOIN LATERAL` |
A window function reads every row of the table before it can discard any. A lateral query with a good index touches only about N rows per group. Many small groups reverse this, because the per-group startup cost of the lateral subquery then outweighs the savings. When the choice matters, test both with EXPLAIN (ANALYZE) on real data.
Common mistakes
- Missing
LIMITorORDER BY. WithoutORDER BY, "top" is arbitrary. WithoutLIMIT, you get a plain per-group join. - Putting a ranking filter outside the subquery. See the paid-orders example above.
- Forgetting
ON true. ALEFT JOIN LATERALwithout anONclause is a syntax error. - No tie-breaker. Results can change from run to run when sort values tie.
- Using
LEFT JOIN LATERALwhen empty groups should disappear. You then get rows full ofNULL. Filter them withWHERE o.id IS NOT NULLor switch toCROSS JOIN.
Exercise
Write a query that returns, for every customer (including those with no orders), their two largest paid orders by total. Break ties by the lower order id. Which join form do you use, and where does the status = 'paid' condition go?
Show answer
Use LEFT JOIN LATERAL ... ON true so customers with no matching orders stay in the result. Put the status condition inside the subquery so it is applied before LIMIT:
SELECT c.id, c.name, o.id AS orderid, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customerid = c.id AND orders.status = 'paid'
ORDER BY total DESC, id ASC
LIMIT 2
) AS o ON true
ORDER BY c.id, o.total DESC;
For the sample data, Ana gets orders 4 (80.00) and 2 (35.50), Ben gets 7 (70.00) and 6 (50.00), and Chi appears with NULLs.
Exercise
A query returns each customer's latest 3 orders using ORDER BY created_at DESC LIMIT 3 inside a lateral subquery. EXPLAIN ANALYZE shows a Sort node inside the lateral subquery, executed once per customer. What index would remove the sort, and why does the column order matter?
Show answer
Create CREATE INDEX ON orders (customer_id, created_at DESC);. The first column is the equality condition from the correlation predicate, so PostgreSQL can jump to one customer's entries. The second column matches the ORDER BY, so those entries are already in the needed order and PostgreSQL can stop after three rows. If the columns were reversed, entries for one customer would be scattered through the index in created_at order, and the index could not serve both the filter and the sort. If the query also sorts by id DESC as a tie-breaker, add it to the index as a third column.