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

TableColumnsDescription
customerscust_id, cust_nm, region, grade100,000 customers, about 20,000 in Seoul
orderscust_id, ord_dt, amt2 million orders
grade_cdgrade, grade_nm3 grade codes
IndexColumns
orders_x1cust_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) and SubPlan 2 (count) each run 19,949 times. For each customer, amount visits orders_x1 with Bitmap Heap Scan and count with Index Only Scan. Buffers about 229,000.
  • After reads orders once (Seq Scan), aggregates per customer (HashAggregate), and hash-joins with Seoul customers (Hash Join Right). Buffers about 19,600.
  • LEFT JOIN and COALESCE(cnt, 0) keep customers without orders. The scalar subquery's COUNT(*) returns 0 and SUM returns NULL, so the results match.

Why this is optimal

  • Reading orders once 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 LATERAL cuts 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 SubPlan runs 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).