One Row at the Index End per Value: GROUP BY MAX → Skipping with a Recursive CTE
Getting the latest order time per status with GROUP BY status reads all 2 million entries of orders_x2. There are only three status values, so a recursive CTE that finds the next status value in the index one at a time, plus a TOP (1) per value that reads one row at the index end, cuts Buffers from 5,990 to 28. ROW_NUMBER works around the restriction that the recursive part cannot use aggregates or TOP.
SQL
Situation
The operations monitoring screen shows the last order time per order status every minute. The result is three rows, yet every run reads the whole order index.
Tables
| Table | Column | Description |
|---|---|---|
orders | status | Three values: DONE, PAID, CANCELED |
orders | ord_dt | Order datetime |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id |
There is no separate table holding the status codes.
Query
BEFORE · GROUP BY status
SELECT status, MAX(ord_dt) AS last_dt
FROM orders
GROUP BY status
Approach
1. See how many pages one value needs
The last ord_dt for WHERE status = 'PAID' is the single row at the end of the PAID range of orders_x2. Written as TOP (1) … ORDER BY ord_dt DESC, it finishes with one Index Seek. Grouped with GROUP BY, the index is read from start to end and grouped by a Stream Aggregate.
2. Consider where to get the list of status values
Writing the values into the statement misses new statuses when they are added. In the index, "the first value greater than the current value" is the first entry of the status > current value range. Consider a recursive CTE that repeats this until no value is left.
3. Check the restrictions of recursive CTEs
SQL Server does not allow aggregates such as MIN, TOP, or GROUP BY in the recursive part (Msg 467). Another way to pick the single first entry is needed. Also check in the execution plan that the optimizer does not unfold the per-value MAX subquery back into a GROUP BY.
Explanation
Skip through status values with a recursive CTE, and TOP (1) per value
AFTER · Recursive CTE + ROW_NUMBER + TOP (1)
WITH s (status) AS (
SELECT MIN(status) FROM orders
UNION ALL
SELECT n.status
FROM s
CROSS APPLY (SELECT o.status, ROW_NUMBER() OVER (ORDER BY o.status) AS rn
FROM orders o
WHERE o.status > s.status) n
WHERE n.rn = 1
)
SELECT s.status, m.last_dt
FROM s
CROSS APPLY (SELECT TOP (1) o.ord_dt AS last_dt
FROM orders o
WHERE o.status = s.status
ORDER BY o.ord_dt DESC) m
Why it got faster
- Before reads 2 million entries in order with
Index Scan (orders_x2)and gathers them into three groups with aStream Aggregate. Buffers are 5,990. - In After, the anchor gets
MIN(status)from the first index entry alone (Top) (3 pages). The recursive part enters thestatus > current valuerange with anIndex Seek, andTopstops reading at the row whereROW_NUMBER()is 1. It runs three times, finds the next two values, and ends with an empty result (9 pages). - Per value, the
TOP (1)in theCROSS APPLYreads one row from the end of theorders_x2range (3 times, 9 pages). Including theIndex Spoolthat holds the recursive result, Buffers are 28. - Written as a
MAXscalar subquery, the optimizer turns it into aGROUP BY statusaggregate and an outer join and reads 2 million entries again (Buffers 6,009).TOP (1) … ORDER BYdoes not get this transformation.
Why this is optimal
- The cost is proportional to the number of distinct values, not the row count. Each value takes only two index descents (finding the next value, finding the end value).
- If distinct values grow to tens of thousands, the number of searches grows with them and becomes more expensive than a full read. A recursive CTE stops at 100 levels by default (
MAXRECURSION), so more than 100 values needOPTION (MAXRECURSION 0).
Key points
GROUP BY+MIN/MAXreads every row even when there are few groups. If an index starts with the group key, it can be turned into one row at the index end per value.- Without a value list, a recursive CTE finds the "next value" in the index one at a time (Loose Index Scan). In SQL Server, the ban on aggregates and
TOPin the recursive part is worked around withROW_NUMBER() … = 1. - For the part that reads one row per value,
TOP (1) … ORDER BYis safer than aMAXsubquery. Check thatTopandIndex Seekremain in the execution plan.