SQL Server window functions: ranking functions, LAG and LEAD, aggregate windows with frames, top-N per group, deduplication and running totals, ROWS versus RANGE, and the POC indexing pattern.
A window function computes a value across a set of rows related to the current row, defined by OVER (PARTITION BY ... ORDER BY ... ROWS ...), without collapsing the rows like GROUP BY. ROW_NUMBER gives a unique sequence, RANK leaves gaps on ties, DENSE_RANK doesn't. LAG/LEAD read the previous or next row, replacing self-joins. SUM() OVER (ORDER BY ...) gives running totals.
Two things matter in production: specify ROWS UNBOUNDED PRECEDING for running totals, because the default RANGE frame uses an on-disk spool and groups ties; and create a POC index (partition, order, covering) so the plan avoids a big Sort. You can't filter on a window result in WHERE, so wrap it in a CTE.
"Window functions let me compute something over a group of rows while keeping every row. The OVER clause defines the window: PARTITION BY splits the rows into groups, ORDER BY orders them inside each group, and the frame clause says which rows around the current one count. The logical processing order matters: they're evaluated after WHERE, GROUP BY and HAVING, which is why I can't filter on ROW_NUMBER in the WHERE clause and have to wrap it in a CTE.
The patterns I use all the time: top-N per group, like each customer's three latest orders, is ROW_NUMBER partitioned by customer ordered by date descending, then rn <= 3 outside. Deduplication is the same with rn > 1 in a DELETE. LAG gives me the previous row's value, so 'change since last month' doesn't need a self-join. And SUM(Amount) OVER (PARTITION BY AccountId ORDER BY TxDate ROWS UNBOUNDED PRECEDING) is a running balance. I choose RANK when ties should share a position, like a leaderboard, and ROW_NUMBER with a tie-breaker when I need exactly N rows.
On performance, two things. If I write ORDER BY in an aggregate window without a frame, SQL Server defaults to RANGE UNBOUNDED PRECEDING, which uses an on-disk worktable spool and adds tied rows together, so a running total can jump. Specifying ROWS uses an in-memory spool and is often several times faster. Second, the window needs rows sorted by partition then order columns; an index on exactly those columns, with the selected columns included, removes the Sort operator. The mistake I see is people writing a correlated subquery for running totals, which is quadratic, when a window does it in one pass."
| Score | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 95 | 1 | 1 | 1 |
| 90 | 2 | 2 | 2 |
| 90 | 3 | 2 | 2 |
| 80 | 4 | 4 | 3 |
| Problem | Window |
|---|---|
| Top-N per group | ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) + rn <= N |
| Remove duplicates | ROW_NUMBER() + DELETE ... WHERE rn > 1 |
| Running total | SUM(x) OVER (PARTITION BY g ORDER BY d ROWS UNBOUNDED PRECEDING) |
| Change vs previous | x - LAG(x) OVER (PARTITION BY g ORDER BY d) |
| Moving average | AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) |
| Percent of total | x * 100.0 / SUM(x) OVER (PARTITION BY g) |
| Gaps and islands | d - ROW_NUMBER() grouping key |
An account statement calculated running balances with a correlated subquery, about 4.2 million logical reads and 38 seconds for a large business account with 60,000 transactions. Rewriting it as SUM() OVER (... ROWS UNBOUNDED PRECEDING) with an index on (AccountId, TxDate, TxId) INCLUDE (Amount) brought it to 350 ms and 900 reads.
Checks fluency with window functions on real problems and awareness of their performance traps.
Green flags
Red flags
FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> window functions -> SELECT -> DISTINCT -> ORDER BY -> TOP/OFFSET
Window functions see the rows left after WHERE and HAVING, which is why they can only appear in SELECT and ORDER BY.
PARTITION BY: restarts the calculation per group (optional).ORDER BY: required for ranking functions, LAG/LEAD, and to get a running aggregate.ROWS counts physical rows; RANGE counts rows with the same ORDER BY value as peers. SQL Server supports RANGE only with UNBOUNDED and CURRENT ROW.Without a frame but with ORDER BY, aggregate windows default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Row mode:
Sequence Project (ROW_NUMBER)
└─ Segment (new partition?)
└─ Sort (CustomerId, OrderDate DESC) <- removed by a POC index
└─ Clustered Index Scan (Orders)
Running total, RANGE default: Window Spool -> worktable in tempdb (on-disk)
Running total, ROWS: Window Spool -> in-memory when frame is ROWS
Batch mode: Window Aggregate operator, no spool
Batch mode on rowstore (compatibility level 150+, Enterprise/Azure SQL) or a columnstore index enables the Window Aggregate operator, often 5-10x faster.
Index key = partition columns, then order columns (matching direction), include the selected columns. Then the plan reads rows already sorted and the Sort disappears. For top-N per group with few groups, a CROSS APPLY (SELECT TOP (N) ...) per group can beat ROW_NUMBER because it seeks rather than reading every row.
ROW_NUMBER with a non-unique ORDER BY can number ties differently between runs. Add a unique tie-breaker (the primary key).
SQL Server 2022 added the WINDOW clause for naming a window once and IGNORE NULLS for FIRST_VALUE, LAST_VALUE, LAG and LEAD.
ROWS UNBOUNDED PRECEDING using SET STATISTICS IO (look at the Worktable reads).CROSS APPLY TOP, and compare reads for 100 vs 100,000 customers.DATEADD(day, -ROW_NUMBER() ..., LoginDate).Top-N per group, deduplication, running totals and month-over-month change.
-- POC index: Partition, Order, Covering
CREATE INDEX IX_Orders_Customer_Date
ON dbo.Orders (CustomerId, OrderDate DESC, OrderId DESC)
INCLUDE (Total, Status);
-- Top 3 latest orders per customer
WITH Ranked AS (
SELECT o.CustomerId, o.OrderId, o.OrderDate, o.Total,
ROW_NUMBER() OVER (PARTITION BY o.CustomerId
ORDER BY o.OrderDate DESC, o.OrderId DESC) AS rn -- tie-breaker
FROM dbo.Orders o
)
SELECT CustomerId, OrderId, OrderDate, Total
FROM Ranked
WHERE rn <= 3;
-- Deduplicate customers by email, keep the newest
WITH d AS (
SELECT ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt DESC, CustomerId DESC) AS rn
FROM dbo.Customers
)
DELETE FROM d WHERE rn > 1;
-- Running balance: ROWS, not the default RANGE
SELECT AccountId, TxId, TxDate, Amount,
SUM(Amount) OVER (PARTITION BY AccountId
ORDER BY TxDate, TxId
ROWS UNBOUNDED PRECEDING) AS Balance
FROM dbo.AccountTransactions
WHERE AccountId = @AccountId;
-- Month-over-month revenue change with LAG
WITH Monthly AS (
SELECT DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) AS MonthStart,
SUM(Total) AS Revenue
FROM dbo.Orders
GROUP BY DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1)
)
SELECT MonthStart, Revenue,
Revenue - LAG(Revenue) OVER (ORDER BY MonthStart) AS ChangeFromPrevious,
RANK() OVER (ORDER BY Revenue DESC) AS RevenueRank
FROM Monthly
ORDER BY MonthStart;
ORDER BY and no frame, SQL Server uses RANGE UNBOUNDED PRECEDING. In row mode that needs an on-disk worktable spool in tempdb (visible as Worktable reads in SET STATISTICS IO), while ROWS can use a much faster in-memory spool. RANGE also treats rows with the same ORDER BY value as peers, so all transactions on the same date get the same, already-summed balance. Instead: Write ROWS UNBOUNDED PRECEDING and include a unique tie-breaker such as the transaction id.WHERE ROW_NUMBER() OVER (...) = 1. Why it is wrong: Window functions are evaluated after WHERE, so it doesn't compile. Instead: Wrap in a CTE or derived table and filter outside.ORDER BY in ROW_NUMBER. Why it is wrong: Ties get different numbers between runs, so pagination or dedupe is unstable. Instead: Add the primary key as a tie-breaker.SUM() OVER with a frame.RANK when exactly N rows are needed. Why it is wrong: Ties can return more than N rows, e.g. a "top 3 products" widget showing five. Instead: Use ROW_NUMBER with a tie-breaker for exact counts; RANK for leaderboards where tied scores share a place; DENSE_RANK for "top 3 distinct price points".Window functions replace a whole class of slow self-joins and cursors, and that's usually the story interviewers want: a quadratic query turned linear. The senior details are the frame default, determinism and indexing.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| ROW_NUMBER + filter | Top-N per group, many groups, few rows each | Reads every row | Few groups with huge histories |
| CROSS APPLY TOP (N) | Few groups, index on (group, order) | One seek per group | Many groups (millions of seeks) |
| SUM() OVER ROWS | Running totals, balances | Sort unless POC index | Need to persist results (store them) |
| Batch mode window aggregate | Analytics on large tables | Columnstore or batch mode on rowstore | Small OLTP queries |
Measure Worktable reads in SET STATISTICS IO, the Sort's memory grant and any spill warnings in the actual plan.
I start with a baseline: SET STATISTICS IO, TIME ON and the actual plan, using realistic parameter values. Logical reads per table are my main number, because elapsed time varies with cache and blocking.
Then I read the plan right to left: a clustered index scan on Orders, a seek with a residual predicate, key lookups executed thousands of times, a sort for ORDER BY. I fix non-SARGable predicates first, then add or adjust an index shaped to the query (equality columns, then the sort or range column, small INCLUDE), and trim the query (no SELECT *, no DISTINCT hiding duplicates).
I prove it by re-measuring with the same and extreme values, checking the write cost, and comparing Query Store before and after.
Islands are runs of consecutive values (consecutive login days, contiguous ids); gaps are the missing values between them. Classic solution: subtract ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY LoginDate) days from each date; rows in the same island share the same result, so GROUP BY UserId, grp gives start and end with MIN/MAX. For gaps, use LEAD(value) OVER (ORDER BY value) and keep rows where the next value is more than one step away. Both are single-pass and need distinct values first.
How to tell it (STAR)
**S:** At [company], statements for our largest business accounts were timing out at month-end. **T:** I needed to make them fast without changing a single balance. **A:** Query Store showed a correlated subquery doing quadratic reads. I rewrote it with a windowed SUM using an explicit ROWS frame, added a POC index to remove the sort, and compared outputs across [500] accounts before releasing. **R:** The worst statement went from [38 seconds] to [350 ms], and logical reads fell from about [4.2 million] to [900].
Last updated 23 Nov 2026.