Sub topic 10
Performance, indexes and EXPLAIN
A lateral subquery is easy to write and easy to make slow. This chapter explains how PostgreSQL runs a LATERAL join, which index makes it fast, and how to confirm that in EXPLAIN output.
This chapter assumes you can read basic EXPLAIN output (node names, cost, rows) and that you know the top-N-per-group pattern from earlier in this tutorial. You should also know what a B-tree index is.
How a lateral join runs
A lateral subquery depends on the current row of the table to its left. PostgreSQL therefore cannot compute the right side once and join the results. It uses a nested loop: for each outer row, it runs the inner query with that row's values plugged in.
The cost is roughly this:
total cost ≈ outer rows × cost of one inner queryThe cost of one inner query is the thing to optimize. If it scans the whole orders table, then 1,000 customers means 1,000 full scans. If it reads three index entries, 1,000 customers means about 3,000 cheap reads.
Since PostgreSQL 12, the planner can sometimes flatten a simple lateral subquery into an ordinary join. A subquery with LIMIT is not flattened, so the top-N pattern always runs as a loop.
A dataset to experiment on
Run this setup so every plan below can be reproduced. The data is random, so your row counts and timings will differ from the sample output.
CREATE TABLE customers (
id int PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id serial PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers (id),
total numeric(10, 2) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO customers
SELECT g, 'customer ' || g
FROM generate_series(1, 1000) AS g;
INSERT INTO orders (customer_id, total, created_at)
SELECT (random() * 999)::int + 1,
round((random() * 500)::numeric, 2),
now() - random() * interval '2 years'
FROM generate_series(1, 200000);
ANALYZE customers;
ANALYZE orders;This gives about 200 orders per customer, spread over two years.
The slow plan: no supporting index
Start with the top-3 query and no index on orders.customer_id.
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;The plan looks like this (abbreviated and illustrative):
Nested Loop (actual time=3.1..2410.5 rows=3000 loops=1)
-> Seq Scan on customers c (actual rows=1000 loops=1)
-> Limit (actual time=2.4..2.4 rows=3 loops=1000)
-> Sort (actual time=2.4..2.4 rows=3 loops=1000)
Sort Method: top-N heapsort Memory: 25kB
-> Seq Scan on orders (actual time=0.01..2.1 rows=200 loops=1000)
Filter: (customer_id = c.id)
Rows Removed by Filter: 199800Three details matter here:
loops=1000on the inner nodes means they ran once per customer. InEXPLAIN ANALYZE,actual timeandrowson a node are averages per loop. Multiply byloopsto get the real totals. The sequential scan above hasrows=200per loop, but it read all 200,000 rows each time.Rows Removed by Filter: 199800shows the scan reading nearly the whole table to keep 200 rows. It repeats that 1,000 times.top-N heapsortis PostgreSQL's cheap way to keep only the three best rows while sorting. It still has to visit every matching row first.
The fix: a composite index
The inner query does two things: it filters on customer_id, then sorts by created_at DESC. One composite index can serve both.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);Equal rows for one customer_id are stored together in the index, already sorted by created_at. The inner query jumps to that customer's entries and reads the first three. No sort is needed.
Nested Loop (actual time=0.05..14.2 rows=3000 loops=1)
-> Seq Scan on customers c (actual rows=1000 loops=1)
-> Limit (actual time=0.008..0.011 rows=3 loops=1000)
-> Index Scan using orders_customer_created_idx on orders
(actual time=0.008..0.010 rows=3 loops=1000)
Index Cond: (customer_id = c.id)The plan has no Sort node and no Rows Removed by Filter line. The inner scan returns 3 rows per loop, and Limit stops it after those 3. This is the shape you want to see.
The column order in the index matters:
| Index | Serves the lateral query? | Why |
|---|---|---|
| `(customer_id, created_at DESC)` | Yes | Equality column first, then the sort column |
| `(created_at DESC, customer_id)` | No | Entries are grouped by time, so one customer's rows are scattered |
| `(customer_id)` only | Partly | Finds the customer's rows fast, but still sorts about 200 of them per loop |
Putting the equality column first and the sort column second is the general rule for any "filter, then order, then limit" query.
Index-only scans with INCLUDE
The query above still visits the orders table for each row to read id (and total, if you select it). If your lateral subquery returns a few columns, you can add them to the index as non-key columns:
CREATE INDEX orders_customer_created_cover_idx
ON orders (customer_id, created_at DESC)
INCLUDE (id, total);
VACUUM orders;The planner can then answer the inner query from the index alone and show Index Only Scan. Two conditions apply:
- The visibility map must be current, which is why the
VACUUMis there. On a table with many recent writes,Heap Fetchesin the plan will stay high. - The index gets larger and writes get slower. Add
INCLUDEcolumns only for hot queries.
Reading the numbers that matter
For a lateral query, check these items in the plan, in this order:
- The inner node's
loops. It should equal the number of outer rows you expect. If it is far larger, the outer side is producing more rows than you thought. - The inner scan type.
Index ScanorIndex Only ScanwithIndex Cond: (customer_id = c.id)is good.Seq Scanwith aFilteris the problem from the slow plan. Rows Removed by Filter. A large number means the index does not match the predicate.- A
Sortnode underLimit. It means the index does not provide the order. Buffers: shared hit/read. Multiply per-loop figures byloops. Highreadcounts mean disk access.
You can also run EXPLAIN without ANALYZE to see the plan without running the query. That is safer on a large table, but it gives you no loops or real timings.
Outer row count dominates
A fast inner query does not rescue a huge outer side. With 1,000 customers and a 0.01 ms inner lookup, the query takes about 10 ms. With 10 million outer rows, the same lookup takes about 100 seconds. So narrow the outer side before the lateral runs:
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 created_at DESC
LIMIT 3
) AS o
WHERE c.id BETWEEN 1 AND 50;Filters on c apply to the outer side, so the inner query runs only for 50 customers. Use the same idea when you need data for a single page of results: select the page of outer rows first, then attach details.
Memoize and repeated keys
If the outer side has many duplicate values of the correlation column, the inner query would run the same lookup again and again. PostgreSQL 14 and later can insert a Memoize node that caches inner results by parameter value. You may see this in plans where the outer table is something like an orders list joined laterally to a small lookup table.
-> Memoize (actual rows=1 loops=5000)
Cache Key: o.customer_id
Hits: 4900 Misses: 100 Evictions: 0Hits against Misses tells you how many inner runs were avoided. You do not enable it. The planner chooses it from its estimates, which is another reason to keep statistics fresh.
Stale statistics and bad estimates
The planner chooses between a nested loop, a hash join, and a merge join using row estimates. When estimates are far off, you see the gap in EXPLAIN ANALYZE as rows= estimates in the plan header versus actual rows. A large gap means one of these:
- The table has not been analyzed since a big load. Run
ANALYZE orders;. - The data is skewed, so a few customers have most of the orders. The average per-customer estimate hides that. For a heavy customer the index scan still works, because
LIMIT 3stops early. A lateral query withoutLIMITwould not be saved. - Estimates for the inner side do not account for the
LIMIT. The planner does account for it with a "startup cost" fraction, but it can misjudge when it thinks matching rows are rare and scans an unrelated index in the sort order instead.
Partial indexes for filtered laterals
If the lateral subquery always has a constant filter, a partial index keeps the index small and the lookup short. For example, if you only ever want shipped orders:
CREATE INDEX orders_shipped_idx
ON orders (customer_id, created_at DESC)
WHERE total > 0;
SELECT c.id, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
AND total > 0
ORDER BY created_at DESC
LIMIT 3
) AS o;The planner uses a partial index only when the query's WHERE clause provably implies the index's predicate. Repeat the exact condition in the query.
When the loop is the wrong tool
A nested loop is good when the outer side is modest and each inner lookup is cheap. It is bad when most outer rows need most of the inner table. Consider these cases:
| Situation | Better approach |
|---|---|
| Few groups (say 5 categories) with very many rows each | A window function with `row_number()` makes one pass over the table |
| You need the top 3 for nearly every group, and the table has no suitable index | A window function, because it scans once instead of once per group |
| One value per outer row, such as the latest order date | A correlated scalar subquery |
| Many outer rows, each needing a few rows from an indexed table | `LATERAL` with the composite index |
You can measure the difference. Run the lateral version and the window version under EXPLAIN (ANALYZE, BUFFERS) and compare total time and buffers. The next chapter discusses the choice in detail.
A checklist for tuning a lateral query
- Run
EXPLAIN (ANALYZE, BUFFERS)and find the inner node'sloops. - If the inner node is a
Seq Scanor has aSort, create a composite index: correlation columns first, then theORDER BYcolumns. - Re-run
EXPLAINand confirm anIndex ScanwithIndex Condon the correlation column and noSort. - Run
ANALYZEif estimates and actual rows disagree widely. - Reduce the outer rows with a
WHEREon the outer table if you do not need all of them. - Compare against a window-function version when the groups are few and large.
Exercise
You run EXPLAIN (ANALYZE) on a top-3-per-customer lateral query. The inner part of the plan shows Sort over Seq Scan on orders with Filter: (customer_id = c.id), Rows Removed by Filter: 199800, and loops=1000. What index would you create, why does column order matter, and what should the plan show afterwards?
Show answer
Create CREATE INDEX ON orders (customer_id, created_at DESC);. The equality column customer_id comes first, so one customer's rows sit together in the index, and created_at comes second, so those rows are already in the order the query needs. After the change, the inner side should be an Index Scan (or Index Only Scan with INCLUDE) with Index Cond: (customer_id = c.id), no Sort node, no large Rows Removed by Filter, and rows=3 per loop under Limit. The loops count stays at 1000, because the lateral join still runs once per customer. Each loop is just much cheaper.
Exercise
In an EXPLAIN ANALYZE plan, an inner node shows actual time=0.010..0.012 rows=3 loops=50000. Roughly how much time did that node spend in total, and why is the per-loop number misleading on its own?
Show answer
About 0.012 ms × 50,000 = 600 ms. In EXPLAIN ANALYZE, actual time and rows are averages for one loop, so the node's real contribution is the per-loop figure multiplied by loops. A tiny per-loop time can still add up to a large total when the outer side has many rows. Reducing the outer rows or caching repeated lookups (as Memoize does) is then more useful than tuning the inner query further.