Monday, 9:02. A message from sales: "Can you send me every order, with its product's total sales next to it? And the grand total too, so I can see each order's share."
Easy, I thought. GROUP BY. Five minutes later I had a red error, then a query that ran but gave the wrong numbers. This episode is how I got out of that hole.
GROUP BY summarizes and changes the grain. A window function enriches and keeps it.
Why GROUP BY couldn't do it
The lab table is Sales.Orders: 10 orders, 4 products, 380 in total sales. Product 101 has four orders (10, 20, 90, 20), so its total is 140.
SELECT OrderID, OrderDate, ProductID, SUM(Sales) AS TotalSales FROM Sales.Orders GROUP BY ProductID;
Msg 8120, Level 16, State 1, Line 4 Column 'Sales.Orders.OrderID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
After grouping, one product row stands for many orders. SQL can't pick which OrderID to show.
SELECT OrderID, OrderDate, ProductID, SUM(Sales) AS TotalSales FROM Sales.Orders GROUP BY OrderID, OrderDate, ProductID;
OrderID ProductID TotalSales 1 101 10 <- product 101 should be 140 3 101 20 <- different "total" for the same product?
No error, wrong answer. OrderID is unique, so every order became its own group and SUM of one value is that value. The grain never changed.
That's the real limit: GROUP BY uses one grain for the whole query. My task needed two at once: rows at order level, total at product level.
So how do you get a total without losing the rows? →
No error ≠ correct result. Ask "what does one row mean?" before and after every GROUP BY.
OVER: split, sort, crop
A window function is a normal function plus OVER (...). The word OVER is what tells SQL: keep the rows. Inside the parentheses you describe the window, the set of rows the function looks at for the current row.
AVG(Sales) -- f(x): what to calculate OVER ( PARTITION BY ProductID -- split the rows into windows ORDER BY OrderDate -- sort inside each window ROWS UNBOUNDED PRECEDING -- crop a frame around the current row )
| part | job | required? |
|---|---|---|
| PARTITION BY | split rows into groups; the calculation restarts in each one | optional (default: everything is one window) |
| ORDER BY | sort rows inside each window | required for rank and value functions |
| frame | which rows around the current row are used | optional, needs ORDER BY |
SELECT OrderID, ProductID, OrderStatus, Sales, SUM(Sales) OVER () AS TotalSales, SUM(Sales) OVER (PARTITION BY ProductID) AS SalesByProduct, SUM(Sales) OVER (PARTITION BY ProductID, OrderStatus) AS SalesByProductStatus FROM Sales.Orders ORDER BY OrderID;
OrderID ProductID OrderStatus Sales TotalSales SalesByProduct SalesByProductStatus 1 101 Delivered 10 380 140 30 2 102 Shipped 15 380 105 75 3 101 Delivered 20 380 140 30 4 105 Shipped 60 380 60 60 5 104 Delivered 25 380 75 75 6 104 Delivered 50 380 75 75 7 102 Delivered 30 380 105 30 8 101 Shipped 90 380 140 110 9 101 Shipped 20 380 140 110 10 102 Shipped 60 380 105 75
Checks I ran: 140 + 105 + 75 + 60 = 380 · 101: 30 + 110 = 140 · still 10 rows. Four granularities in one query, the thing GROUP BY can't do.
Two things that surprised me:
Same value ≠ same window. 30 shows up for 101-Delivered and 102-Delivered. Different windows, same total by coincidence. Always read the partition columns.
The output order is a side effect. Without the final ORDER BY OrderID, SQL Server returned rows grouped by product (product 102 came out as 10, 2, 7) because it sorted internally to compute the partitions. If order matters, say so with an outer ORDER BY.
And what happens when I add ORDER BY inside OVER? The total turns into something else →
OVER keeps the rows. PARTITION BY says "for each". Several windows can live in one SELECT.
The frame slides with you
Add ORDER BY inside OVER and the window gets a direction. Now a frame can crop it: "from the first row to me", "the two rows before me", "me and the next one".
| frame | Jan | Feb | Mar | Apr | Jun | Jul |
|---|---|---|---|---|---|---|
| UNBOUNDED PRECEDING AND CURRENT ROW | 20 | 30 | 60 | 65 | 135 | 175 |
| CURRENT ROW AND UNBOUNDED FOLLOWING | 175 | 155 | 145 | 115 | 110 | 40 |
| 1 PRECEDING AND CURRENT ROW | 20 | 30 | 40 | 35 | 75 | 110 |
| CURRENT ROW AND 2 FOLLOWING | 60 | 45 | 105 | 115 | 110 | 40 |
| 1 PRECEDING AND 1 FOLLOWING | 30 | 60 | 45 | 105 | 115 | 110 |
| UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING | 175 | 175 | 175 | 175 | 175 | 175 |
Rule of thumb: an UNBOUNDED end is fixed, a CURRENT ROW or N end moves. Near the edges a frame just gets smaller, it never crosses into another partition.
SUM(Sales) OVER (PARTITION BY OrderStatus ORDER BY OrderDate ROWS UNBOUNDED FOLLOWING)
Msg 102, Level 15, State 1, Line 7 Incorrect syntax near 'FOLLOWING'.
The short form ROWS x means BETWEEN x AND CURRENT ROW. With FOLLOWING the start would come after the end. Fix: write the full BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. (The course slide used ROWS 2 FOLLOWING as its example: same error.)
SUM(Sales) OVER (ORDER BY x) with no frame quietly uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: a running total, not a total. And it's RANGE, not ROWS: rows with the same sort value are peers and get the same result.
| Sales (sorted) | default RANGE | explicit ROWS |
|---|---|---|
| 10 | 10 | 10 |
| 15 | 25 | 25 |
| 20 | 65 | 45 |
| 20 | 65 | 65 |
| … | … | … |
| 60 | 290 | 230 |
| 60 | 290 | 290 |
| 90 | 380 | 380 |
For a real row-by-row running total: write ROWS explicitly and add a tiebreaker to the sort.
Frames are flexible. But there are four rules you can't bend →
ORDER BY inside OVER always means a frame. If you just wanted sorted output, use the outer ORDER BY.
Four rules, four error messages
All four rules come from one fact: window functions run late.
FROM → WHERE → GROUP BY → HAVING → window functions → SELECT → ORDER BY
| rule | what I hit | fix |
|---|---|---|
| 1 · only in SELECT and ORDER BY | Msg 4108: windowed functions can only appear in the SELECT or ORDER BY clauses | compute in a subquery or CTE, filter outside |
| 2 · no nesting | Msg 4109: window function inside another window or aggregate | one layer per CTE step |
| 3 · WHERE runs first | no error: totals change (135 / 245 became 60 / 185) | filter in the outer query if you need full-data totals |
| 4 · with GROUP BY, use grouped columns or aggregates | Msg 8120 for ORDER BY Sales after GROUP BY CustomerID | RANK() OVER (ORDER BY SUM(Sales) DESC) |
-- keep rows whose status total is above 100 SELECT * FROM ( SELECT OrderID, OrderStatus, Sales, SUM(Sales) OVER (PARTITION BY OrderStatus) AS TotalSales FROM Sales.Orders ) t -- the derived table needs an alias WHERE TotalSales > 100; -- aggregate first, then rank SELECT CustomerID, SUM(Sales) AS TotalSales, RANK() OVER (ORDER BY SUM(Sales) DESC) AS RankCustomers FROM Sales.Orders GROUP BY CustomerID;
CustomerID TotalSales RankCustomers 3 125 1 1 110 2 4 90 3 2 55 4
Ranking by CustomerID instead also ran without errors, and put customer 4 first. Valid syntax, wrong business answer.
| SQL Server | PostgreSQL | |
|---|---|---|
| window in WHERE | Msg 4108 | ERROR: window functions are not allowed in WHERE |
| RANGE with offsets | only UNBOUNDED / CURRENT ROW | RANGE BETWEEN INTERVAL '7 days' PRECEDING … |
| reuse a window | — | named windows: WINDOW w AS (...) |
| extra frame mode | — | GROUPS (counts peer groups) |
Last level: where all this shows up at work →
Window functions run after WHERE and GROUP BY, so filter on them one level up.
In real data engineering
Report tables with several levels. A sales export for Power BI often needs order line + product subtotal + business-line total + grand total on one row. Before window functions this meant one GROUP BY subquery per level and a join back for each. Now it's one pass over the table.
Grain discipline. The first question for any fact table (like a fact_SalesLine) is "what does one row mean?" Window results repeat on every row of the window, so never SUM a window-total column again: 4 rows × 140 = 560, not 140. That's the double-counting bug that makes dashboard totals look too big.
Decide where the filter goes. "Show product 101 with its share of all sales" needs the window over all rows and the filter outside. Put the filter in WHERE and the share is computed on the wrong denominator. Many "the % in my report doesn't match" tickets start here.
Detail + subtotal + total in one row, one pass: that is the everyday job of a window function.
I started with a red error and ended with four levels of totals in one query. Next episode: what each aggregate function does inside a window, and the NULL traps hiding in them.
next → ep09b · sum it up
Glossary
All the new words from this episode.
Boss level: quick quiz
No pressure, the cat isn't grading.
// sources
- PostgreSQL tutorial: Window Functions
- PostgreSQL docs: window function calls (frames, RANGE, GROUPS)
- Microsoft Learn: SELECT - OVER clause (Transact-SQL)
- Lab data: the SalesDB sample database from the course I followed, run in SQL Server Management Studio.