Cut the Top-N First, Then Attach the Aggregate
The 20 most recent paid orders get their customer's total order count and cumulative amount attached. Joining a per-customer aggregate subquery puts the aggregate of 2 million orders into a Table Spool and scans it from the start for each of the 20 outer rows, for 220K Buffers. Cutting the 20 rows first and aggregating only those 20 customers with CROSS APPLY brings it down to 13,187.
SQL
Situation
The payment confirmation screen shows the 20 most recent paid orders, together with each customer's order count and cumulative amount so far. The per-customer aggregate reuses a subquery that other screens also use.
Tables
| Table | Column | Description |
|---|---|---|
orders | status, ord_dt, cust_id, amt | About 140,000 paid (PAID) orders. Customers 1 to 100 have 2,000+ orders |
| Index | Columns |
|---|---|
orders_pk (clustered) | ord_id |
orders_x1 | cust_id, ord_dt |
orders_x2 | status, ord_dt, ord_id |
Query
BEFORE · Join with aggregate subquery, then Top-N
SELECT TOP (20) o.ord_id, o.ord_dt, o.amt, o.cust_id, s.ord_cnt, s.tot_amt
FROM orders o
JOIN (SELECT cust_id, COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders
GROUP BY cust_id) s ON s.cust_id = o.cust_id
WHERE o.status = 'PAID'
ORDER BY o.ord_dt DESC
Look at the execution count and actual rows of the Table Spool, and the row count of the Hash Match (Aggregate) below it.
Approach
1. See at how many rows the outer orders stopped
The optimizer chose a plan that reads the outer orders in reverse order of orders_x2 and stops at 20 rows (Scenario 13). If it is still slow, the cost is on the join partner's side. See how many customers the aggregate subquery computed, and how many times its result was read.
2. Check whether the join condition went inside the aggregate
To aggregate only 20 customers, s.cust_id = o.cust_id must become a condition inside the subquery. Check whether the Clustered Index Scan under the aggregate has such a condition (Seek Predicate).
3. Choose a way to attach the aggregate to the 20 cut rows
If the 20 rows are cut first, at most 20 customers need an aggregate. Consider syntax that uses the outer row's values inside the subquery. Also confirm that the join does not change the row count (one aggregate row per customer, and a customer with orders always appears in the aggregate).
Explanation
Cut 20 rows first and aggregate per customer with CROSS APPLY
AFTER · TOP first + CROSS APPLY aggregate
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt, s.tot_amt
FROM (SELECT TOP (20) ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC) t
CROSS APPLY (
SELECT COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders x
WHERE x.cust_id = t.cust_id
) s
ORDER BY t.ord_dt DESC
Why it got faster
- In Before, the outer orders stop at 20 rows (47 pages). But the aggregate subquery on the join side does not receive the join condition, so it reads 2 million orders and aggregates 100,000 customers (13,201 pages). The aggregate result goes into a
Table Spool (Lazy Spool), and the NL join scans the spool from the start for each of the 20 outer rows to find the wanted customer. The spool emits 1,964,405 rows, and including the spool worktable reads, Buffers are 221,750. - After cuts 20 rows, then finds only that customer's orders through
orders_x1per customer and aggregates them with aStream Aggregate(20 executions, 4,356 rows).amtis not inorders_x1, so it does 4,356Key Lookups (13,068 pages). Buffers are 13,187. - The result is the same. A
CROSS APPLYaggregate returns exactly one row per outer row, so the row count is unchanged.
Why this is optimal
- The remaining cost is the
Key Lookupof the 4,356 orders of the 20 customers. If a high-volume customer (2,000+ orders) is among the customers of the latest 20 rows, that customer's orders make up most of it. Sinceamtis not in a nonclustered index,SUM(amt)must read the clustered index. - If the cumulative amount is not needed, the aggregate finishes with
orders_x1alone. The variation below checks this.
Variation: cut first, then join the aggregate subquery
TRY · TOP first + join aggregate subquery
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt, s.tot_amt
FROM (SELECT TOP (20) ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC) t
JOIN (SELECT cust_id, COUNT(*) AS ord_cnt, SUM(amt) AS tot_amt
FROM orders
GROUP BY cust_id) s ON s.cust_id = t.cust_id
ORDER BY t.ord_dt DESC
- In this shape SQL Server moves the aggregate above the join. It first joins the 20 rows with those customers' 4,356 orders and then groups them with a
Stream Aggregate. Buffers are 12,625, close to After. Cutting the 20 rows first is enough; the optimizer handles the rest. PostgreSQL aggregates all 100,000 customers in the same shape.
TRY · Order count only (aggregate with orders_x1 alone)
SELECT t.ord_id, t.ord_dt, t.amt, t.cust_id, s.ord_cnt
FROM (SELECT TOP (20) ord_id, ord_dt, amt, cust_id
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC) t
CROSS APPLY (
SELECT COUNT(*) AS ord_cnt FROM orders x WHERE x.cust_id = t.cust_id
) s
ORDER BY t.ord_dt DESC
COUNT(*)only needs to count thecust_idrange oforders_x1, so there is noKey Lookup. Buffers are 119.
Key points
- In a Top-N query, attach joins and aggregates unrelated to the sort key after cutting the 20 rows.
- A
Table Spoolon the inner side of an NL join only avoids recomputing the result; it may still scan the whole spool for each outer row. Check execution count × spool rows. - To aggregate per outer row, use
CROSS APPLY(or a scalar subquery). Before cutting, confirm that the join does not change the row count.