Scalar subquery → join (understanding the caching effect)
Replace scalar subqueries that run once per row with aggregate-then-join. Also see when caching pays off and how it interacts with partial range processing.
SQL
Situation
A report computes the 2025 order amount and order count for each Seoul customer (about 20,000). The screen downloads the whole result as a file, so the comparison uses "fetch all".
Tables
CUSTOMERS (100,000 rows) has 5 regions at 20% each. ORDERS (2 million rows) holds orders accumulated at 2,000 per day from 2023-01-01 to 2025-09-26. GRADE_CD (3 rows) holds grade codes.
| Table | Column | Type | Description |
|---|---|---|---|
CUSTOMERS | CUST_ID | NUMBER | Customer ID (PK) |
CUSTOMERS | CUST_NM | VARCHAR2 | Customer name |
CUSTOMERS | GRADE | VARCHAR2 | VIP 1%, GOLD 9%, NORMAL 90% |
CUSTOMERS | REGION | VARCHAR2 | SEOUL, BUSAN, DAEGU, INCHEON, GWANGJU |
ORDERS | CUST_ID | NUMBER | Ordering customer |
ORDERS | ORD_DT | DATE | Order date and time |
ORDERS | AMT | NUMBER | Order amount |
GRADE_CD | GRADE | VARCHAR2(10) | Grade code (PK) |
GRADE_CD | GRADE_NM | VARCHAR2(30) | Grade name |
| Index | Columns |
|---|---|
CUSTOMERS_PK | CUST_ID |
ORDERS_X1 | CUST_ID, ORD_DT |
REGION has no index.
2025 order amount and count per customer
For each Seoul customer, compute the total 2025 order amount and the order count. The result has as many rows as Seoul customers, about 20,000. Customers without orders also appear in the result, with a count of 0.
BEFORE · Two scalar subqueries
SELECT c.cust_id, c.cust_nm,
(SELECT /*+ NO_UNNEST */ SUM(o.amt) FROM orders o
WHERE o.cust_id = c.cust_id AND o.ord_dt >= DATE '2025-01-01') AS amt,
(SELECT /*+ NO_UNNEST */ 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'
NO_UNNESTkeeps the optimizer from turning the scalar subqueries into a join. It reproduces the behavior up to 11g, or a complex query that does not meet the transformation conditions.- The Buffers of scalar subqueries are shown separately in the execution plan, not added to the top line (Id 0). The sandbox "total" shows the sum of the two values.
Run it and check the Buffers total and the Starts of the subquery operations.
Approach
1. Look at the Starts of the subquery operations
A scalar subquery can run once per outer row. In the execution plan, see the Starts of the operations under the subqueries. Here the two subquery operations each have 20,000 Starts (repeated once per Seoul customer).
2. Consider whether caching can pay off
Oracle caches a scalar subquery's input values and results. When the same input value comes again, the subquery does not run. So the question is "how many distinct input values are there". Here the input value is CUST_ID, which differs for every customer. Caching has no effect.
3. See whether the same table is read several times
The two subqueries have the same conditions and differ only in the value they select (SUM and COUNT). The same ORDERS range is read twice per customer. Think about whether one read can produce both values.
4. See whether row-by-row repetition can become set-based processing
For a report that must produce the whole result, instead of probing the index for each customer, the query can read the 2025 orders once, aggregate them per customer, and join with customers.
- The result must be the same. Customers without orders must appear, so an outer join is needed, and the count must come out as 0, not NULL.
- On the other hand, a screen that shows only the first few rows quickly is a different story. An approach that must finish the aggregation first returns its first row late. Consider the number of rows fetched as well.
Explanation
Aggregate, then join
AFTER · Aggregate then join
SELECT c.cust_id, c.cust_nm, o.amt, NVL(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
ORDERSis read once, aggregated, and hash joined. Compare the Buffers total with Before.- Before ran two subqueries per customer (20,000 Starts each). After has no repeated execution.
- In Before,
cntis 0 for customers without orders, so After usesNVL(o.cnt, 0)to match the result.
Why this is optimal
- The cost of reading the 2025 orders of
ORDERSonce remains.ORDERShas no region information, so reading only the orders of Seoul customers requires probing the index for each customer. That is exactly Before's approach. - The whole result must be produced, so the orders of every Seoul customer have to be read anyway. Reading them all at once and hash joining reads less than probing 20,000 separate times.
- Reducing this cost further requires changing the schema, such as storing the aggregates separately. That is outside the scope of this scenario.
The optimizer's automatic transformation
TRY · No hint (automatic transformation)
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'
- From 12c, the optimizer turns scalar subqueries into a join on its own (Scalar Subquery Unnesting). If
VIEW VW_SSQ_1andHASH JOIN OUTERappear in the execution plan, the query was transformed into the same shape as After. - Do not rely on the automatic transformation; check the execution plan. When the transformation does not happen (ROWNUM inside the subquery, some aggregate functions, older versions), the query runs as Before.
Contrast lab ①: when caching works well
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'
- The input value (
GRADE) has only 3 distinct values, so scalar subquery caching works. The subquery's Starts comes out near 3.
Contrast lab ②: combined with partial range processing
Change Before to "rows to fetch: 200" and run it again.
- A scalar subquery runs each time a result row is fetched. Fetching only 200 rows gives 200 Starts, and Buffers is on the order of a few hundred blocks.
- In contrast, After's hash join must finish aggregating
ORDERSbefore returning the first row, so fetching only 200 rows costs the same. - So for "a list that shows only the first screen quickly", a scalar subquery can be the better choice. This continues in scenario 10.
Key points
- Whether a scalar subquery is good or bad is decided by the number of distinct input values and the number of rows fetched.
- If several scalar subqueries that read the same table must produce the whole result, merge them into a single aggregation and join.