Sub topic 10
Performance, indexes and EXPLAIN
This chapter assumes you know SELECT, WHERE, ORDER BY, LIMIT, joins, subqueries in FROM, and table aliases. It also assumes you can read a basic PostgreSQL execution plan.
A lateral query evaluates its right-hand side for each row from the left-hand side. That makes it useful for “the newest three orders for each customer,” but it also creates a possible performance problem: PostgreSQL may need to run many small lookups. The right index can make each lookup very cheap.
The index for a top-N lateral query
Consider this query:
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers AS 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;For every customer, PostgreSQL must find orders with one customer_id, sort them by created_at, and keep only three rows. An index matching the filter and sort can support that work:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);The first index column supports the equality condition:
WHERE orders.customer_id = c.idThe second column supports the ordering:
ORDER BY created_at DESCBecause the index is already ordered, PostgreSQL can often read the first three matching entries and stop. It does not need to scan every order for the customer or sort all of them.
If several orders can have the same created_at, add a unique tie-breaker:
CREATE INDEX orders_customer_created_id_idx
ON orders (customer_id, created_at DESC, id DESC);Then use the same complete ordering in the query:
ORDER BY created_at DESC, id DESCThis makes which three rows PostgreSQL returns predictable.
Read the plan with EXPLAIN
Use EXPLAIN to inspect the plan without running the query. Use EXPLAIN ANALYZE to run it and report actual timing and row counts.
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;A good plan commonly contains a Nested Loop. The outer side reads customers. The inner side runs the lateral lookup for each customer.
Look for an index scan or index-only scan on orders. A useful plan may resemble this:
Nested Loop
-> Seq Scan on customers c
-> Limit
-> Index Scan using orders_customer_created_id_idx on orders
Index Cond: (customer_id = c.id)Important fields include:
| Plan detail | What it tells you |
|---|---|
| `loops` | How many times a plan node ran |
| `actual rows` | How many rows it produced |
| `Index Cond` | Which index condition PostgreSQL used |
| `Buffers` | Pages read from disk or memory |
The inner node should usually return only a few rows per loop because of LIMIT 3. If it scans many rows before applying the limit, the index may not match the filter and ordering.
Compare estimated and actual rows. Large differences can lead PostgreSQL to choose a poor plan. Refresh statistics when the data has changed substantially:
ANALYZE customers;
ANALYZE orders;EXPLAIN ANALYZE adds overhead, so production measurements should use representative data and careful timing. BUFFERS helps distinguish work satisfied from shared memory from work that required disk reads.
Common performance mistakes
- Missing the correlation index: An index only on
created_atmay not efficiently find one customer’s orders. - Putting columns in the wrong order: For this query,
(created_at, customer_id)is usually less useful because the lookup starts withcustomer_id. - Sorting after fetching too much data: Without a matching index, PostgreSQL may scan and sort every matching order for every customer.
- Returning too many columns: An index-only scan may be possible only when the index contains the columns needed by the query and the visibility map permits it.
- Ignoring the outer row count: Ten indexed lookups and ten million indexed lookups are different workloads. Measure with realistic data.
- Expecting an index to fix everything: A lateral query can still be costly when most customers have many matching rows or when the result needs a large fraction of the table.
Choose based on the workload
LATERAL is a strong choice when each group needs a small number of rows and the lookup can use an index. A window function can be better when PostgreSQL should process many rows in one pass:
SELECT id, customer_id, 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;A correlated scalar subquery fits when you need one value, such as the latest order total, rather than several rows. Compare alternatives with EXPLAIN (ANALYZE, BUFFERS) on your actual data.
Exercise
Which index best supports a lateral query that filters orders by customerid and returns the newest three orders using ORDER BY createdat DESC, id DESC?
Show answer
An index beginning with the equality column and continuing with the ordering columns: CREATE INDEX ON orders (customerid, createdat DESC, id DESC).