📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are window functions in SQL Server? Use ROW_NUMBER, RANK, DENSE_RANK, LAG/LEAD and SUM() OVER to solve top-N per group, deduplication and running totals, and explain PARTITION BY, ORDER BY and the frame clause (ROWS vs RANGE) and how to index for them.

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.

Mid-Level Sql Intermediate indexes query-performance reporting sql-server t-sql window-functions

🎯 Key points

  • Window functions compute over a set of rows related to the current row without collapsing them like GROUP BY
  • ROW_NUMBER is unique; RANK leaves gaps on ties; DENSE_RANK doesn't
  • Top-N per group: ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) filtered in an outer query
  • LAG/LEAD read previous/next rows without self-joins
  • Default frame with ORDER BY is RANGE UNBOUNDED PRECEDING: spools to tempdb and treats ties together; specify ROWS for running totals
  • POC index: Partition columns, then Order columns, then Covering includes, avoids the Sort
  • Windowed results can't be filtered in WHERE; wrap in a CTE or derived table
  • Batch mode Window Aggregate (columnstore or batch mode on rowstore) makes them much faster

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Ranking functions on ties

Score ROW_NUMBER RANK DENSE_RANK
95 1 1 1
90 2 2 2
90 3 2 2
80 4 4 3

Common patterns

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

Production example

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.

🔍 What the interviewer is checking

Checks fluency with window functions on real problems and awareness of their performance traps.

Green flags

  • Solves top-N per group and dedupe with ROW_NUMBER correctly
  • Explains RANK vs DENSE_RANK vs ROW_NUMBER on ties
  • Knows the ROWS vs RANGE default and specifies ROWS for running totals
  • Mentions a POC index to avoid the Sort

Red flags

  • Uses correlated subqueries or cursors for running totals
  • Tries to filter window results in WHERE
  • No tie-breaker in ordering

📚 Learn in depth

1. Logical processing order

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.

2. The OVER clause

  • PARTITION BY: restarts the calculation per group (optional).
  • ORDER BY: required for ranking functions, LAG/LEAD, and to get a running aggregate.
  • Frame: 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.

3. How the plan looks

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.

4. POC indexing

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.

5. Determinism

ROW_NUMBER with a non-unique ORDER BY can number ties differently between runs. Add a unique tie-breaker (the primary key).

6. Newer features

SQL Server 2022 added the WINDOW clause for naming a window once and IGNORE NULLS for FIRST_VALUE, LAST_VALUE, LAG and LEAD.

Try it yourself

  1. Compare a running total with the default frame and with ROWS UNBOUNDED PRECEDING using SET STATISTICS IO (look at the Worktable reads).
  2. Add a POC index and confirm the Sort operator disappears.
  3. Solve top-3 orders per customer with ROW_NUMBER and with CROSS APPLY TOP, and compare reads for 100 vs 100,000 customers.
  4. Solve a gaps-and-islands problem (consecutive login days) using DATEADD(day, -ROW_NUMBER() ..., LoginDate).

💻 Code

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;

⚠ Common mistakes

  • Mistake: Relying on the default frame for running totals. Why it is wrong: With 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.
  • Mistake: Filtering 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.
  • Mistake: Non-deterministic 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.
  • Mistake: Running totals with a correlated subquery or self-join. Why it is wrong: It is O(n²) in reads. Instead: Use SUM() OVER with a frame.
  • Mistake: Using 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".
  • Mistake: No supporting index. Why it is wrong: A large Sort with a memory grant, possibly spilling to tempdb. Instead: Create a POC index or accept the sort for small sets.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions removing a Sort operator with an index Why: Checks the step-by-step tuning method with plans and logical reads.
    How to answer

    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.

  2. When: Candidate is comfortable with ROW_NUMBER and LAG Why: Checks advanced set-based thinking on sequences such as consecutive days or ranges.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Statement running balance using a correlated subquery
Situation
A [banking or payments] portal generated account statements with a running balance computed by a correlated subquery over AccountTransactions, on Azure SQL with [about 200 million] transaction rows.
Signals
Statement generation for large business accounts timed out at 30 seconds; Query Store showed the query among the top CPU consumers with millions of logical reads per execution; customers complained at month-end.
Investigation
Pulled the query and actual plan from Query Store; saw a nested loop executing an index seek once per transaction (60,000 executions) each reading all prior rows. SET STATISTICS IO showed about 4.2 million logical reads for one account.
Resolution
Rewrote the balance as SUM(Amount) OVER (PARTITION BY AccountId ORDER BY TxDate, TxId ROWS UNBOUNDED PRECEDING), and added an index on (AccountId, TxDate, TxId) INCLUDE (Amount) so the Sort disappeared. Verified balances matched the old output on a sample of accounts.
Prevention
Added a performance test for the largest account size, a Query Store alert on logical reads regression, and a code review checklist item to prefer window functions over correlated subqueries for running calculations.

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].

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me