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

TableColumnDescription
ordersstatusThree values: DONE, PAID, CANCELED
ordersord_dtOrder datetime
IndexColumns
orders_x2status, 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 a Stream 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 the status > current value range with an Index Seek, and Top stops reading at the row where ROW_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 the CROSS APPLY reads one row from the end of the orders_x2 range (3 times, 9 pages). Including the Index Spool that holds the recursive result, Buffers are 28.
  • Written as a MAX scalar subquery, the optimizer turns it into a GROUP BY status aggregate and an outer join and reads 2 million entries again (Buffers 6,009). TOP (1) … ORDER BY does 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 need OPTION (MAXRECURSION 0).

Key points

  • GROUP BY + MIN/MAX reads 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 TOP in the recursive part is worked around with ROW_NUMBER() … = 1.
  • For the part that reads one row per value, TOP (1) … ORDER BY is safer than a MAX subquery. Check that Top and Index Seek remain in the execution plan.