Cut the Top-N first, then attach the aggregate
The 20 most recent paid orders get their customer's total order count and cumulative amount attached. Joining with a per-customer aggregate subquery aggregates 2 million orders and spills to disk even though only 20 rows are needed. PostgreSQL cannot push the join condition into the aggregate subquery, so cutting the 20 rows first and aggregating only those 20 customers with LATERAL cuts Buffers from 18,758 to 8,444.
SQL
Situation
A payment confirmation screen shows the 20 most recent paid orders, along with each customer's order count and cumulative amount to date. The per-customer aggregate is a subquery also used on another screen, attached as is.
Tables
| Table | Columns | Description |
|---|---|---|
orders | status, ord_dt, cust_id, amt | About 140,000 paid (PAID) orders. Customers 1–100 have 2,000+ orders |
| Index | Columns |
|---|---|
orders_x1 | cust_id, ord_dt |
orders_x2 | status, ord_dt, ord_id |
Query
BEFORE · Join with aggregate subquery, then Top-N
SELECT o.ord_id, o.ord_dt, o.amt, o.cust_id, s.ord_cnt, s.tot_amt
FROM orders o
JOIN (SELECT cust_id, COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders
GROUP BY cust_id) s ON s.cust_id = o.cust_id
WHERE o.status = 'PAID'
ORDER BY o.ord_dt DESC
LIMIT 20
Look at the Rows and Disk Usage of HashAggregate and the Loops of Materialize.
Approach
1. See at how many rows the outer orders stopped
The planner picked a plan that reads the outer orders in reverse orders_x2 order and stops at 20 rows (scenario 13). If it is still slow, the cost is on the join partner's side. Check how many customers the aggregate subquery computed.
2. See whether the join condition got into the aggregate
To aggregate only 20 customers, s.cust_id = o.cust_id must become a condition inside the subquery's GROUP BY (WHERE cust_id = outer value). Check in the execution plan whether the Seq Scan under the aggregate has such a condition.
3. Choose a way to attach the aggregate to the 20 cut rows
Cutting 20 rows first means at most 20 customers need aggregation. Consider which syntax is needed to use an outer row's value inside the subquery. Also confirm that the join does not change the row count (one aggregate row per customer, and every customer with orders is always in the aggregate).
Explanation
Cut 20 rows first and aggregate per customer with LATERAL
AFTER · Top-N first + LATERAL aggregate
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt, s.tot_amt
FROM (SELECT ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
LIMIT 20) t
CROSS JOIN LATERAL (
SELECT COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders x
WHERE x.cust_id = t.cust_id
) s
ORDER BY t.ord_dt DESC
Why it got faster
- The outer orders in Before stop at 20 rows (6 blocks). But the aggregate subquery, the join partner, does not receive the join condition, so it reads 2 million rows with a
Seq Scanand aggregates 99,467 customers (18,752 blocks). The hash table exceedswork_mem, givingBatches: 5and 19MB on disk. The aggregate result is held inMaterialize, which the 20 outer rows scan in turn. Buffers 18,758, plus temp file reads and writes. - After cuts 20 rows, then for each customer gathers only that customer's orders through
orders_x1and aggregates them (20 executions). That averages 418 rows, 8,345 heap blocks. Buffers 8,444, no temp files. - The result is the same. The
LATERALaggregate returns exactly one row per outer row, so the row count is unchanged.
Why this is optimal
- The remaining cost is reading the 20 customers' orders from the heap. If the customers of the latest 20 rows include high-volume customers (2,000+ orders), their orders make up most of it.
SUM(amt)must read the heap becauseamtis not in the index. - Without the cumulative amount, the aggregate finishes from the index alone. The variation below confirms this.
Variation: only cutting first
TRY · Top-N first + aggregate subquery join
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt, s.tot_amt
FROM (SELECT ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
LIMIT 20) t
JOIN (SELECT cust_id, COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders
GROUP BY cust_id) s ON s.cust_id = t.cust_id
ORDER BY t.ord_dt DESC
- The 20 rows are cut first, but the aggregate subquery still computes 100,000 customers. Buffers are at the same level as Before. Oracle pushes the join condition into the aggregate view in this shape (
VIEW PUSHED PREDICATE), but PostgreSQL does not. Hence it is written directly withLATERAL.
TRY · Order count only (Index Only Scan)
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt
FROM (SELECT ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
LIMIT 20) t
CROSS JOIN LATERAL (
SELECT COUNT(*) AS ord_cnt FROM orders x WHERE x.cust_id = t.cust_id
) s
ORDER BY t.ord_dt DESC
COUNT(*)only needs to count thecust_idrange oforders_x1, so it finishes with anIndex Only Scan(Heap Fetches: 0). Buffers 100.
Key points
- In a Top-N query, attach joins and aggregates unrelated to the sort key after cutting the 20 rows.
- PostgreSQL does not push join conditions into a
GROUP BYsubquery. To aggregate per outer row, write it withLATERAL(or a scalar subquery). - Before cutting, confirm that the join does not change the row count. If it does, fewer than 20 rows may come out after the cut.