🗄️ Fix a Window Function Re-Sorting an Already Sorted Input
ROW_NUMBER() and its relatives require their own sort to satisfy the PARTITION BY and ORDER BY clause in the OVER() window, and SQL Server’s optimizer only skips that sort when it can prove an existing index already delivers rows in exactly the order the window function needs — partition columns first, then order columns, in the same directions. A source that happens to already be sorted the right way, whether from a CTE’s own ORDER BY or from reading a table that’s naturally insert-ordered, doesn’t automatically satisfy that proof; without an index matching the window’s own partition and order columns, the optimizer adds a redundant Sort operator rather than trusting that the input is already correctly ordered.
🔎 The Problem
SELECT CustomerId, OrderDate,
ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate) AS rn
FROM Orders;
-- Execution plan shows a Sort operator before the Sequence Project /
-- Window Spool, even if Orders happens to be scanned in an order that
-- already matches CustomerId, OrderDate - the optimizer doesn't trust
-- "happens to be ordered," it needs an index that GUARANTEES it
✅ Fix: A Window Function Re-Sorting an Already Sorted Input
- Create or confirm a nonclustered index on (CustomerId, OrderDate) – matching the window’s PARTITION BY and ORDER BY columns in the same order – so the optimizer can prove the sort requirement is already satisfied and skip the extra Sort operator.
- Check the actual execution plan rather than assuming: look specifically for a Sort operator feeding into the window function’s Window Spool/Sequence Project, which confirms the index isn’t being used for this purpose.
- Remember that the clustered index’s physical order alone isn’t necessarily enough if the window function partitions or orders by columns that aren’t its leading key columns – the index needs to match the window’s own clause, not just any sort.
🚨 Why This Is Dangerous
- A redundant Sort operator on a large table can dominate a query’s cost far more than the window function itself, and it’s an easy one to miss since the query still returns correct results — just slower than it needs to be.
SQL Server won’t take your word for it that the data’s already sorted — it needs an index that proves it.



