Scalar subquery → aggregate then join
Replaces two scalar subqueries that read the same table with one aggregate-then-join. SQL Server unnests scalar subqueries into joins on its own, but the cost of reading the table twice remains.
SQL
Situation
A report shows the 2025 order amount total and order count for about 20,000 Seoul customers. The amount and the count are each computed with a scalar subquery.
Tables
| Table | Column | Description |
|---|---|---|
customers | cust_id, cust_nm, region | 100,000 customers, about 20,000 in Seoul |
orders | cust_id, ord_dt, amt | 2,000,000 orders, about 540,000 in 2025 |
| Index | Columns |
|---|---|
customers_pk (clustered) | cust_id |
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 >= CAST('2025-01-01' AS datetime2(0))) AS amt,
(SELECT COUNT(*) FROM orders o
WHERE o.cust_id = c.cust_id AND o.ord_dt >= CAST('2025-01-01' AS datetime2(0))) AS cnt
FROM customers c
WHERE c.region = 'SEOUL'
Run it and check how many times and in what way orders was read.
Approach
1. Check whether the subquery runs per row
Taken literally, a scalar subquery runs once per outer row. SQL Server unnests it into a join (decorrelation) and builds a plan that aggregates in one pass on its own. If the execution plan shows Hash Match rather than Nested Loops, it has already been unnested.
2. Check whether the same table is read several times
The amount and the count come from orders with the same condition (customer, 2025). Because there are two subqueries, the optimizer reads orders twice. Check whether one read can produce both values.
3. Aggregate first, then join
Aggregate orders once per customer (GROUP BY cust_id) to produce the amount and the count together, and join that result with customers.
Explanation
Aggregate then join
AFTER · Aggregate then join
SELECT c.cust_id, c.cust_nm, o.amt, ISNULL(o.cnt, 0) AS cnt
FROM customers c
LEFT JOIN (
SELECT cust_id, SUM(CAST(amt AS bigint)) AS amt, COUNT(*) AS cnt
FROM orders
WHERE ord_dt >= CAST('2025-01-01' AS datetime2(0))
GROUP BY cust_id
) o ON o.cust_id = c.cust_id
WHERE c.region = 'SEOUL'
Why it got faster
- In Before, SQL Server unnests each of the two subqueries into a join and reads
ordersonce as the whole table (Clustered Index Scan, about 13,200) and once as all oforders_x1(Index Scan, about 5,000). Buffers about 18,800. - After reads
ordersonly once, aggregates the amount and the count together (Hash Match Aggregate), and hash joins the result with customers. Buffers about 13,800.
Why this is optimal
- Reading the 540,000 orders of 2025 once is the minimum cost of this report.
amtis not inorders_x1, so the table must be read.
Variation: when it really runs per row
TRY · Forced LOOP JOIN (runs per row)
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 >= CAST('2025-01-01' AS datetime2(0))) AS amt,
(SELECT COUNT(*) FROM orders o
WHERE o.cust_id = c.cust_id AND o.ord_dt >= CAST('2025-01-01' AS datetime2(0))) AS cnt
FROM customers c
WHERE c.region = 'SEOUL'
OPTION (LOOP JOIN)
- Pinning the join method to NL makes the subqueries run per customer. The
orders_x1Index Seekhas Starts 19,953, and with a Key Lookup per order (108,626 times) to get the amount, Buffers reach about 446,800. This is the cost SQL Server would have paid had it not unnested the scalar subqueries on its own.
Variation: code lookup subquery
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'
- A lookup into a 3-row code table is also unnested into a hash join and reads
grade_cdonly once (Buffers about 600).
Key points
- SQL Server unnests scalar subqueries into joins. But one table read per subquery remains, so subqueries that read the same table several times must be merged into one by hand.
- When the join method turns into NL (hint, bad estimate), the subquery runs per outer row.
- DB differences: Oracle caches scalar subquery results (it does not rerun for the same input), and PostgreSQL neither caches nor transforms into a join, so it runs per row. SQL Server transforms into a join instead of caching.