Short answer: a window function calculates a value for each row from a set of related rows, its window, without collapsing the rows the way GROUP BY does. OVER (PARTITION BY ... ORDER BY ...) defines the window: which rows belong together and in what order. Three uses cover most of the daily work: keep the latest row per key, a running total, and the previous value for a change.
GROUP BY answers "how much per customer" with one row per customer. Window functions answer "for each order, how much had this customer spent so far" and keep every order.
How does OVER define a window?
| CustomerID | OrderDate | Amount | Running total |
|---|---|---|---|
| 1042 | 2026-01-04 | 120 | 120 |
| 1042 | 2026-02-11 | 80 | 200 |
| 1042 | 2026-03-02 | 50 | 250 |
| a new partition starts: the total starts again | |||
| 2077 | 2026-01-20 | 300 | 300 |
| 2077 | 2026-02-03 | 40 | 340 |
PARTITION BY splits the rows into groups that do not see each other. ORDER BY orders the rows inside each group. An optional frame, like ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, says which of those rows the function adds up.
Which three uses come up every day?
The latest version of each order, a common clean-up step in silver:
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY OrderID ORDER BY ModifiedDate DESC) AS rn
FROM stage.Orders
)
SELECT * FROM ranked WHERE rn = 1;A running total per customer:
SELECT CustomerID, OrderDate, Amount,
SUM(Amount) OVER (PARTITION BY CustomerID ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM dbo.Orders;The change from the month before:
SELECT [Month], Revenue,
Revenue - LAG(Revenue) OVER (ORDER BY [Month]) AS ChangeFromLastMonth
FROM dbo.MonthlyRevenue;What goes wrong?
- Ties in ROW_NUMBER. Two rows with the same date get an arbitrary order. Add a tie-breaker to
ORDER BY, like the load timestamp. - The default frame. With
ORDER BYand no frame, SQL Server usesRANGE, which treats rows with equal dates as one step and is slower. WriteROWS BETWEEN ...when you mean rows. - Filtering in the same SELECT. A window function cannot be used in
WHERE. Wrap the query in a CTE, as above, and filter outside.
Where can you check this?
- Microsoft Learn: SELECT - OVER clause (Transact-SQL)
- Microsoft Learn: ROW_NUMBER (Transact-SQL)
- Microsoft Learn: LAG (Transact-SQL)
Where do you start?
The open course Upserts into Azure SQL keeps one row per key in staging before the merge, which is where ROW_NUMBER earns its keep. In a lakehouse, the same clean-up runs in a notebook before the merge in Bronze, silver and gold.