Sub topic 11
When to use something other than LATERAL
LATERAL is a good fit when each outer row needs its own subquery. Sometimes a simpler or faster tool does the same job. This chapter compares LATERAL with window functions, DISTINCT ON, correlated scalar subqueries, and plain joins with aggregates. It ends with criteria for choosing between them.
It assumes you have read the earlier chapters on CROSS JOIN LATERAL, LEFT JOIN LATERAL ... ON true, top-N per group, and EXPLAIN. The examples use these tables:
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,
created_at timestamptz NOT NULL
);The question to ask first
A LATERAL subquery runs once per outer row. That is its strength: it can use LIMIT, ORDER BY, and the outer row's values inside the subquery. It is also its cost, because the work grows with the number of outer rows.
Before writing LATERAL, ask what the subquery actually needs:
- Does it need a per-row
LIMIT, or an index probe for each outer row? LATERAL is a strong candidate. - Does it only compute a total, count, or maximum per group? A
GROUP BYis probably simpler. - Does it return exactly one value? A scalar subquery may be enough.
- Does it rank rows inside each group? A window function may be faster.
Window functions for top-N per group
The top-3 query from earlier in the chapter series can be written with row_number():
SELECT customer_id, name, order_id, total
FROM (
SELECT c.id AS customer_id,
c.name,
o.id AS order_id,
o.total,
row_number() OVER (
PARTITION BY o.customer_id
ORDER BY o.created_at DESC, o.id DESC
) AS rn
FROM customers c
JOIN orders o ON o.customer_id = c.id
) ranked
WHERE rn <= 3
ORDER BY customer_id, rn;This query reads every joined order row, sorts or groups them by customer, numbers them, and then throws away everything with rn > 3. It does one pass over the data and no per-customer probing.
How the two compare
| Situation | Better fit | Reason |
|---|---|---|
| Millions of orders, a few hundred customers, index on `(customer_id, created_at DESC)` | LATERAL | Each customer needs only 3 index reads. The window version ranks every order. |
| Many customers, each with only a handful of orders | Window function | One scan is cheaper than thousands of separate index probes. |
| Top N for every group, no outer filter, no useful index | Window function | A single sort replaces many sorts. |
| Outer query is already filtered to a few customers | Either, usually LATERAL | Only the filtered customers are probed. |
| You need ties handled in a specific way | Window function | `rank()` and `dense_rank()` exist for this. |
Ties need care in both styles. LIMIT 3 and row_number() pick exactly three rows and break ties arbitrarily unless the ORDER BY is unique. Add a unique column such as id as the last sort key. If you want all tied rows, use rank() <= 3 or LIMIT ... WITH TIES (PostgreSQL 13 and later) inside the lateral subquery.
SELECT c.id, 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 total DESC
FETCH FIRST 3 ROWS WITH TIES
) AS o;A window function also gives you more than a filter. You can return the rank itself, compare each row to the previous one with lag(), or compute a running total. A lateral subquery sees only its own rows, so those jobs fit windows better.
DISTINCT ON for one row per group
When N is 1, PostgreSQL has a dedicated feature. DISTINCT ON keeps the first row of each group according to the ORDER BY:
SELECT DISTINCT ON (customer_id)
customer_id, id AS order_id, total, created_at
FROM orders
ORDER BY customer_id, created_at DESC, id DESC;This returns each customer's latest order in one pass. It is short and easy to read. Three limits apply:
- It is PostgreSQL-specific, so it will not port to other databases.
- Customers without orders do not appear, because the query reads only
orders. To keep them, join the result tocustomerswith aLEFT JOIN. - With a large
orderstable and few customers, the LATERAL form with an index can beat it. The latest order per customer then costs one index probe each, instead of sorting everything.
A LATERAL version of the same query:
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, id DESC
LIMIT 1
) AS o ON true;Use DISTINCT ON when you want the simplest text. Use LATERAL when you need to keep customers with no orders, or when the outer table is much smaller than the inner one.
Correlated scalar subqueries
A scalar subquery sits in the select list, returns one value, and may refer to the outer row:
SELECT c.id,
c.name,
(SELECT max(o.created_at)
FROM orders o
WHERE o.customer_id = c.id) AS last_order_at
FROM customers c;This is a good choice when you need one column. It keeps customers with no orders, which gives them a NULL, so it behaves like a LEFT JOIN LATERAL. It also reads naturally.
Where scalar subqueries break down
- One column only. To get the latest order's id, total, and date, you would repeat the subquery three times. Each copy runs separately.
- At most one row. If the subquery can return two rows, PostgreSQL raises
ERROR: more than one row returned by a subquery used as an expression. A LATERAL subquery can return many rows, and each one becomes an output row. - No reuse. The result is available only in the select list position where you wrote it. You cannot refer to it by name in the same
SELECT.
If you find yourself writing the same correlated subquery twice with different columns, switch to LATERAL:
SELECT c.id, c.name, o.id AS last_order_id, o.total, o.created_at
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total, created_at
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC, id DESC
LIMIT 1
) AS o ON true;Here the subquery runs once per customer and returns three columns.
Plain joins and GROUP BY for aggregates
Many LATERAL queries are really aggregates. This one counts orders per customer:
SELECT c.id, c.name, s.order_count, s.revenue
FROM customers c
LEFT JOIN LATERAL (
SELECT count(*) AS order_count, sum(total) AS revenue
FROM orders
WHERE orders.customer_id = c.id
) AS s ON true;It works, but the ordinary form lets the planner choose a hash join and a single pass over orders:
SELECT c.id, c.name,
count(o.id) AS order_count,
coalesce(sum(o.total), 0) AS revenue
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;Note the differences in how the two handle customers with no orders. The lateral aggregate always returns one row, so order_count is 0 and revenue is NULL. In the GROUP BY form, count(o.id) counts only non-NULL ids and gives 0, and coalesce turns the NULL sum into 0. Use count(o.id) and not count(*), because count(*) would count the single NULL-extended row as 1.
When no LIMIT or per-row logic is involved, prefer the GROUP BY form. If the aggregate is over a pre-aggregated subquery, you can also aggregate orders once in a subquery and join it:
SELECT c.id, c.name, coalesce(s.order_count, 0) AS order_count
FROM customers c
LEFT JOIN (
SELECT customer_id, count(*) AS order_count
FROM orders
GROUP BY customer_id
) s ON s.customer_id = c.id;This one is also a single pass, and it does not repeat grouping columns.
What the planner does with each form
A LATERAL subquery with LIMIT or an aggregate is generally executed as a nested loop. For each outer row, PostgreSQL runs the inner plan with the outer values as parameters. In EXPLAIN output this shows as a Nested Loop whose inner side has a loops=N count equal to the number of outer rows.
A simple lateral subquery without those features may be flattened into an ordinary join, in which case the planner has more freedom, such as choosing a hash join. You cannot rely on this. Check EXPLAIN for the join node that was actually chosen.
Window functions and GROUP BY queries run the other way around. They scan the inner table in bulk, then sort or hash. The cost is roughly proportional to the size of orders, not to the number of customers.
This gives a rule of thumb for the size comparison:
- LATERAL cost ≈ (outer rows) × (cost of one index probe plus N row reads).
- Window or GROUP BY cost ≈ (cost of reading all inner rows) plus a sort or hash.
LATERAL wins when the outer row count is small or when N is much smaller than the group size. Window or GROUP BY wins when the groups are small, or when you need most of the table anyway.
Readability and maintenance
Performance is not the only criterion.
- Team familiarity. Window functions and
GROUP BYare widely known. LATERAL is less familiar, so a short comment above a lateral join helps the next reader. - Portability.
LATERALis in the SQL standard and exists in several databases, but syntax and support differ (SQL Server usesCROSS APPLYandOUTER APPLY).DISTINCT ONis PostgreSQL only. - Intent.
DISTINCT ON (customer_id)states "one row per customer" directly. A lateral subquery withLIMIT 1says the same thing, but more indirectly.
Choosing: a summary
| You need | Use | Watch for |
|---|---|---|
| One aggregate per group | `GROUP BY` with a join | `count(*)` versus `count(col)` after a `LEFT JOIN` |
| One value per outer row | Scalar subquery | Error if it can return more than one row |
| One full row per group | `DISTINCT ON` or `LEFT JOIN LATERAL ... LIMIT 1` | Groups with no rows drop out of a plain `DISTINCT ON` |
| Top N per group, many small groups | Window function with `row_number()` | Unique tie-breaker in `ORDER BY` |
| Top N per group, big groups, index available | `LATERAL` with `LIMIT` | Needs an index on the correlation and sort columns |
| Several columns computed from the outer row | `LATERAL` | One subquery run per outer row |
| Rows from an array or `jsonb` column | `LATERAL` with a set-returning function | Rows with empty or NULL arrays disappear under `CROSS JOIN` |
Exercise
A reporting query lists each customer with the total, date, and id of their most recent order. It currently uses three correlated scalar subqueries in the select list, each with ORDER BY created_at DESC LIMIT 1. Customers with no orders must still appear. Rewrite it, and explain why the new form is better.
Show answer
Use one LEFT JOIN LATERAL that selects id, total, and created_at with ORDER BY created_at DESC, id DESC LIMIT 1 and ON true. The three scalar subqueries each run their own lookup per customer, while the lateral subquery runs once per customer and returns all three columns. LEFT JOIN ... ON true keeps customers with no orders and gives NULL in the order columns.
Exercise
A table orders has 40 million rows and customers has 200 rows. You need each customer's 5 most recent orders, and an index on (customer_id, created_at DESC) exists. Which form do you try first, a window function or LATERAL, and what do you check afterward?
Show answer
Try CROSS JOIN LATERAL (or LEFT JOIN LATERAL ... ON true to keep customers without orders) with ORDER BY created_at DESC LIMIT 5. With only 200 outer rows and a supporting index, it reads about 5 index entries per customer, instead of ranking 40 million rows. Then run EXPLAIN (ANALYZE, BUFFERS) and confirm that the inner side is an index scan with loops=200 and that the buffer counts are small. Compare it with the row_number() version if you have doubts.
Exercise
A query uses LEFT JOIN LATERAL (SELECT count(*) AS n FROM orders WHERE orders.customer_id = c.id) s ON true to count orders. Rewrite it with GROUP BY so that customers with no orders show 0, and say which count expression to use.
Show answer
SELECT c.id, c.name, count(o.id) AS n FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.id, c.name;. Use count(o.id) and not count(*). For a customer with no orders, the LEFT JOIN produces one row with NULL order columns. count(o.id) skips NULLs and returns 0, while count(*) would return 1.