Case study: daily per-account trade settlement batch (9 tables, 5 scalar subqueries)
A "per-account trade settlement" batch that runs per region after market close. For each account with trades, five separate scalar subqueries compute the execution count, buy and sell amounts, commission, and transaction tax, and because those subqueries filter only on the execution date, each one rereads 41 days of the account's orders every time. Reading the day's executions once and switching to conditional aggregation cuts Buffers from 901,350 to 4,904 and CPU from 0.80 s to 0.05 s.
SQL
Situation
After market close (15:30), the settlement batch runs this statement for each region to build the "per-account daily trade settlement sheet". For each active account with executions that day, it outputs the execution count, buy amount, sell amount, commission, sell transaction tax, and settlement amount (sell − buy − commission − tax). The result is written to a file and sent to the branches.
When first built, one region finished in a few seconds, but as API orders from corporate accounts grew, the whole batch running five regions began to overlap with other closing jobs. The result (rows and amounts) must stay the same.
Tables
| Table | Columns used by this statement | Rows |
|---|---|---|
ACCT accounts | ACCT_NO, CUST_ID, BRANCH_CD, ACCT_TYPE, ACCT_STATUS | 200,000 |
BRANCH branches | BRANCH_NM, REGION | 50 (10 per region) |
CUSTOMERS, GRADE_CD | Customer name, grade name | 100,000 / 3 |
STK_ORD orders | ORD_NO, ACCT_NO, TRD_DT, ITEM_CD, SIDE_CD, CHANNEL_CD, ORD_STATUS | 2,050,000 (50,000 per business day) |
STK_EXEC executions | ORD_NO, TRD_DT, EXEC_QTY, EXEC_PRC | 2,316,020 (about 56,000 per business day) |
FEE_POLICY | Commission rate per channel × account type × effective period | 30 |
STK_ITEM, TAX_RATE | Item's market, transaction tax rate per market × effective period | 2,000 / 2 |
| Index | Columns |
|---|---|
STK_ORD_X1 | ACCT_NO, TRD_DT |
STK_ORD_X3 | TRD_DT, ORD_STATUS |
STK_EXEC_X1 | ORD_NO |
STK_EXEC_X2 | TRD_DT, EXEC_TM |
| Others | Primary key of each table |
Business rule: executions occur only for FILL and PART orders, and an execution's TRD_DT equals its order's TRD_DT (only same-day orders exist). The schema and distribution are in the common lab environment. The result for the Seoul region on 2025-09-26 is 5,510 accounts.
Query
BEFORE · Batch SQL in production
SELECT s.branch_cd, s.branch_nm, s.acct_no, s.cust_nm, s.grade_nm, s.acct_type,
s.exec_cnt, s.buy_amt, s.sell_amt, s.fee_amt, s.tax_amt,
s.sell_amt - s.buy_amt - s.fee_amt - s.tax_amt AS net_amt
FROM (
SELECT b.branch_cd, b.branch_nm, a.acct_no, cu.cust_nm, g.grade_nm, a.acct_type,
(SELECT COUNT(*)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')) AS exec_cnt,
(SELECT NVL(SUM(e.exec_qty * e.exec_prc), 0)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'B') AS buy_amt,
(SELECT NVL(SUM(e.exec_qty * e.exec_prc), 0)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'S') AS sell_amt,
(SELECT NVL(SUM(ROUND(e.exec_qty * e.exec_prc * f.fee_rate)), 0)
FROM stk_exec e
JOIN stk_ord o ON o.ord_no = e.ord_no
JOIN fee_policy f ON f.channel_cd = o.channel_cd AND f.acct_type = a.acct_type
AND e.trd_dt BETWEEN f.from_dt AND f.to_dt
WHERE o.acct_no = a.acct_no AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')) AS fee_amt,
(SELECT NVL(SUM(ROUND(e.exec_qty * e.exec_prc * t.tax_rate)), 0)
FROM stk_exec e
JOIN stk_ord o ON o.ord_no = e.ord_no
JOIN stk_item i ON i.item_cd = o.item_cd
JOIN tax_rate t ON t.market_cd = i.market_cd AND e.trd_dt BETWEEN t.from_dt AND t.to_dt
WHERE o.acct_no = a.acct_no AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'S') AS tax_amt
FROM acct a
JOIN branch b ON b.branch_cd = a.branch_cd
JOIN customers cu ON cu.cust_id = a.cust_id
JOIN grade_cd g ON g.grade = cu.grade
WHERE b.region = :region
AND a.acct_status = 'ACTIVE'
AND EXISTS (SELECT 1 FROM stk_ord o
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')
AND o.ord_status IN ('FILL', 'PART'))
) s
ORDER BY s.branch_cd, s.acct_no
Write down Starts and Buffers for each of the five SORT AGGREGATE operations (the scalar subqueries) at the top of the execution plan, and compare the A-Rows of STK_ORD_X1 below them with the number of result accounts. Also look at CPU and query (consistent gets) in the Trace tab.
Approach
1. Break down where the cost is in numbers
Write down the Buffers of the main query (accounts, branches, customers, EXISTS) and of each of the five scalar subqueries. If the main query is small and the subqueries are large, calculate the cost of one subquery run × the number of runs (Starts). Scalar subquery caching helps only when input values repeat; consider whether this subquery's input (a.acct_no) repeats.
2. See whether one subquery run reads the right amount
The subquery finds "this account's executions of the day". Yet look at how many rows per account the STK_ORD_X1(ACCT_NO, TRD_DT) probe has in A-Rows. Determine which table the date condition is on, and whether the business rule (execution date = order date) lets the condition be placed on another table too. The optimizer does not know the business rule, so it does not create this condition on its own.
3. Count how many times the same set is read
All five subqueries read the same set, "this account's executions of the day + orders", and differ only in the condition (SIDE_CD) and the tables they attach (commission rate, tax rate). Consider reading that set once and summing it split by CASE. The commission rate and tax rate are range joins with a period condition (BETWEEN).
4. Write down the conditions that keep the result the same after the change
- The original statement returns only "accounts with
FILL/PARTorders that day" throughEXISTS. A statement that joins with executions and aggregates returns "accounts with executions that day". Find in the business rule the basis for the two sets being equal. - The original statement's
NVL(SUM(…), 0)returns 0 when no matching commission or tax rate exists. In the rewritten statement, make sure executions without a commission rate do not drop out of the aggregation. - Amounts are rounded with
ROUNDper execution before summing. Changing the order changes the amounts in won.
Explanation
Read the day's executions once and aggregate conditionally
AFTER · Read once and aggregate conditionally
SELECT b.branch_cd, b.branch_nm, x.acct_no, cu.cust_nm, g.grade_nm, x.acct_type,
x.exec_cnt, x.buy_amt, x.sell_amt, x.fee_amt, x.tax_amt,
x.sell_amt - x.buy_amt - x.fee_amt - x.tax_amt AS net_amt
FROM (
SELECT a.acct_no, a.acct_type, a.branch_cd, a.cust_id,
COUNT(*) AS exec_cnt,
SUM(CASE WHEN o.side_cd = 'B' THEN e.exec_qty * e.exec_prc ELSE 0 END) AS buy_amt,
SUM(CASE WHEN o.side_cd = 'S' THEN e.exec_qty * e.exec_prc ELSE 0 END) AS sell_amt,
NVL(SUM(ROUND(e.exec_qty * e.exec_prc * f.fee_rate)), 0) AS fee_amt,
NVL(SUM(CASE WHEN o.side_cd = 'S' THEN ROUND(e.exec_qty * e.exec_prc * t.tax_rate) END), 0) AS tax_amt
FROM stk_exec e
JOIN stk_ord o ON o.ord_no = e.ord_no
JOIN acct a ON a.acct_no = o.acct_no
JOIN branch b2 ON b2.branch_cd = a.branch_cd
JOIN stk_item i ON i.item_cd = o.item_cd
LEFT JOIN fee_policy f ON f.channel_cd = o.channel_cd AND f.acct_type = a.acct_type
AND e.trd_dt BETWEEN f.from_dt AND f.to_dt
LEFT JOIN tax_rate t ON t.market_cd = i.market_cd AND e.trd_dt BETWEEN t.from_dt AND t.to_dt
WHERE e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')
AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')
AND b2.region = :region
AND a.acct_status = 'ACTIVE'
GROUP BY a.acct_no, a.acct_type, a.branch_cd, a.cust_id
) x
JOIN branch b ON b.branch_cd = x.branch_cd
JOIN customers cu ON cu.cust_id = x.cust_id
JOIN grade_cd g ON g.grade = cu.grade
ORDER BY b.branch_cd, x.acct_no
What Before did (Buffers 901,350, CPU 0.80 s)
- The main query is 2,614 blocks. It picks 5,510 accounts by hash join and hash semi join of 10 branches, active accounts, and orders executed that day (
STK_ORD_X3). - The remaining 898,736 blocks are the five scalar subqueries. All have Starts 5,510. The input is the account number, so the same value never repeats and caching has no effect.
| Subquery | Buffers |
|---|---|
| Execution count | 202,926 |
| Buy amount | 132,830 |
| Sell amount | 131,620 |
| Commission | 226,426 |
| Transaction tax | 204,934 |
- Each subquery run probes
STK_ORD_X1withACCT_NOalone, because the date condition is only on executions (e.trd_dt). So it reads 41 days of the account's orders (50,359 rows over 5,510 runs) through to the table, finds executions for each order throughSTK_EXEC_X1, and filters by date in the executions table. Only 8,659 rows remain as executions of the day.
What After did (Buffers 4,904, CPU 0.05 s)
- It reads the 50,000 orders of the day through
STK_ORD_X3(1,847 blocks) and the 56,670 executions of the day throughSTK_EXEC_X2(1,397 blocks), once each. - It hash-joins all accounts (1,053 blocks), the 10 Seoul branches, items, commission rates, tax rates, and customers, and produces the five values for 5,510 accounts at once with a single
SORT GROUP BY. - The 5,510 result rows are the same as Before. Comparing the two statements with
MINUSin both directions returns 0 rows.
Problems solved one at a time
| # | Problem | Fix | Why the result is the same |
|---|---|---|---|
| 1 | The date condition is only on executions, so all of the account's orders for every date are read | Also write o.trd_dt = :trd_dt | Business rule: execution date = order date |
| 2 | Five subqueries reread the same set 5,510 times each | Read once and aggregate conditionally with CASE | Same row set, only the conditions differ |
| 3 | Repeated probes per account (NL) | Hash-join the whole set of the day | The join method does not affect the result |
| 4 | Picking accounts with EXISTS | Inner join with executions + GROUP BY | Executions occur only for FILL/PART orders and only on the same day |
| 5 | 0 when no rate exists | LEFT JOIN for commission and tax rates, NVL(SUM(…), 0) | ROUND(amount × NULL) is NULL, and SUM ignores it |
Why this is optimal
- Producing the result requires reading the day's orders and executions at least once. After reads those two sets once each by index range (about 3,200 blocks) and reads accounts and customers once into hash tables. There are no repeated probes proportional to the number of accounts.
- Running the five regions separately reads the day's orders and executions five times. For the batch as a whole, dropping the
regioncondition, aggregating once, and splitting the output by region is cheaper. That changes the batch design, so agree on it with the business side.
Variation: fix only the date condition
TRY · Add only the date condition (keep the 5 subqueries)
SELECT s.branch_cd, s.branch_nm, s.acct_no, s.cust_nm, s.grade_nm, s.acct_type,
s.exec_cnt, s.buy_amt, s.sell_amt, s.fee_amt, s.tax_amt,
s.sell_amt - s.buy_amt - s.fee_amt - s.tax_amt AS net_amt
FROM (
SELECT b.branch_cd, b.branch_nm, a.acct_no, cu.cust_nm, g.grade_nm, a.acct_type,
(SELECT COUNT(*)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')) AS exec_cnt,
(SELECT NVL(SUM(e.exec_qty * e.exec_prc), 0)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'B') AS buy_amt,
(SELECT NVL(SUM(e.exec_qty * e.exec_prc), 0)
FROM stk_exec e JOIN stk_ord o ON o.ord_no = e.ord_no
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'S') AS sell_amt,
(SELECT NVL(SUM(ROUND(e.exec_qty * e.exec_prc * f.fee_rate)), 0)
FROM stk_exec e
JOIN stk_ord o ON o.ord_no = e.ord_no
JOIN fee_policy f ON f.channel_cd = o.channel_cd AND f.acct_type = a.acct_type
AND e.trd_dt BETWEEN f.from_dt AND f.to_dt
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')) AS fee_amt,
(SELECT NVL(SUM(ROUND(e.exec_qty * e.exec_prc * t.tax_rate)), 0)
FROM stk_exec e
JOIN stk_ord o ON o.ord_no = e.ord_no
JOIN stk_item i ON i.item_cd = o.item_cd
JOIN tax_rate t ON t.market_cd = i.market_cd AND e.trd_dt BETWEEN t.from_dt AND t.to_dt
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND e.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD') AND o.side_cd = 'S') AS tax_amt
FROM acct a
JOIN branch b ON b.branch_cd = a.branch_cd
JOIN customers cu ON cu.cust_id = a.cust_id
JOIN grade_cd g ON g.grade = cu.grade
WHERE b.region = :region
AND a.acct_status = 'ACTIVE'
AND EXISTS (SELECT 1 FROM stk_ord o
WHERE o.acct_no = a.acct_no AND o.trd_dt = TO_DATE(:trd_dt, 'YYYYMMDD')
AND o.ord_status IN ('FILL', 'PART'))
) s
ORDER BY s.branch_cd, s.acct_no
- Buffers 158,774, CPU 0.14 s. Each subquery run now reads only the day's orders, so it is one sixth of Before. But the 5,510 accounts × 5 subqueries = 27,550 repeated probes remain, so it is 32 times more than After. When setting tuning priorities, separate the easy fix (one condition line) from the structural problem (repeated execution) and measure the effect of each.
Key points
- Read a scalar subquery as Starts × cost per run. If the input is a non-repeating key (account number), caching has no effect and it runs as many times as the main query has rows (Scenario 4).
- When several subqueries reread the same set, read it once and aggregate conditionally with
CASE. Attach range joins (rate periods) withLEFT JOINto keep "no rate = 0". - The optimizer does not know business rules (execution date = order date). Writing the condition on the other table too narrows the index range. Such a condition relies on a rule, not a constraint, so record the basis in documents and comments.
- For a transformation that changes the definition of a set, such as turning
EXISTSinto a join, write down why the two sets are equal and check both directions withMINUS.