Scalar subquery → aggregate then join
Replace scalar subqueries that run once per row with an aggregate-then-join. PostgreSQL does not cache scalar subquery results, so every repeated run is a cost.
SQL
Situation
A report shows the 2025 order amount and count per Seoul customer. The amount and count for each customer come from separate scalar subqueries. As customers grew, the report slowed down.
Tables
| Table | Columns | Description |
|---|---|---|
customers | cust_id, cust_nm, region, grade | 100,000 customers, about 20,000 in Seoul |
orders | cust_id, ord_dt, amt | 2 million orders |
grade_cd | grade, grade_nm | 3 grade codes |
| Index | Columns |
|---|---|
orders_x1 | cust_id, ord_dt |
2025 order amount and count per customer
BEFORE · Two scalar subqueries
SELECT c.cust_id, c.cust_nm,
(SELECT SUM(o.amt) FROM orders o
WHERE o.cust_id = c.cust_id AND o.ord_dt >= DATE '2025-01-01') AS amt,
(SELECT COUNT(*) FROM orders o
WHERE o.cust_id = c.cust_id AND o.ord_dt >= DATE '2025-01-01') AS cnt
FROM customers c
WHERE c.region = 'SEOUL'
Run it and check how many times SubPlan ran (Starts).
Approach
1. Look at how many times the subquery runs
A scalar subquery runs once per outer row. If the Starts of SubPlan 1 and SubPlan 2 in the execution plan equal the number of Seoul customers, orders was visited customers × 2 times.
2. Consider whether caching can be expected
Oracle caches scalar subquery results for the same input value. PostgreSQL does not cache scalar subqueries (SubPlan). Here the input value (cust_id) differs per row anyway, so a cache would not help.
3. Turn row-by-row repetition into set processing
Amount and count per customer can be built all at once by reading orders once with GROUP BY cust_id. Join that result to customers.
Explanation
Aggregate then join
AFTER · Aggregate then join
SELECT c.cust_id, c.cust_nm, o.amt, COALESCE(o.cnt, 0) AS cnt
FROM customers c
LEFT JOIN (
SELECT cust_id, SUM(amt) AS amt, COUNT(*) AS cnt
FROM orders
WHERE ord_dt >= DATE '2025-01-01'
GROUP BY cust_id
) o ON o.cust_id = c.cust_id
WHERE c.region = 'SEOUL'
Why it got faster
- In Before,
SubPlan 1(amount) andSubPlan 2(count) each run 19,949 times. For each customer, amount visitsorders_x1withBitmap Heap Scanand count withIndex Only Scan. Buffers about 229,000. - After reads
ordersonce (Seq Scan), aggregates per customer (HashAggregate), and hash-joins with Seoul customers (Hash Join Right). Buffers about 19,600. LEFT JOINandCOALESCE(cnt, 0)keep customers without orders. The scalar subquery'sCOUNT(*)returns 0 andSUMreturns NULL, so the results match.
Why this is optimal
- Reading
ordersonce is the minimum cost of aggregating all 2025 orders. - The remaining cost is reading all of
orders(about 18,750 blocks). Only Seoul customers' orders are needed, but one read is cheaper than looking up 20,000 customers' orders one by one through the index.
Variation: all at once with LATERAL
TRY · LATERAL (single repetition)
SELECT c.cust_id, c.cust_nm, o.amt, o.cnt
FROM customers c
CROSS JOIN LATERAL (
SELECT SUM(amt) AS amt, COUNT(*) AS cnt
FROM orders
WHERE cust_id = c.cust_id AND ord_dt >= DATE '2025-01-01'
) o
WHERE c.region = 'SEOUL'
- Merging the two subqueries into one
LATERALcuts the repetition to one set of 19,949 runs: Buffers about 169,000. It still repeats per customer, so it costs more than aggregate-then-join. With few customers (e.g. 1,000 VIPs), this shape can win.
Variation: code lookups are not cached either
TRY · Code lookup scalar subquery
SELECT c.cust_id, c.cust_nm,
(SELECT g.grade_nm FROM grade_cd g WHERE g.grade = c.grade) AS grade_nm
FROM customers c
WHERE c.region = 'SEOUL'
- There are only 3 grade codes, yet
SubPlanruns 19,949 times (Buffers about 20,800). In Oracle the cache would make it run only a few times. In PostgreSQL, write even such code lookups as joins.
Key points
- A scalar subquery runs once per outer row. Turning the aggregation or lookup into set processing (aggregate then join) removes the repetition.
- DB difference: Oracle caches scalar subquery results (a big effect when input values are few); PostgreSQL does not. Instead, since PostgreSQL 14 the inner side of an NL join is cached with
Memoize(scenario 20).