SQL Quest · episode 09a · world 2 · window saga 1/4

SEE THROUGH
THE WINDOW

Keep every row, and still see the big picture. Window functions add totals, ranks and comparisons next to your data instead of squashing it.

2026-11-16·15 min read·#sql #window-functions #over #partition-by

study cat on duty (asleep, as usual)

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.

level 01the problem

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.

// lab · attempt 1: details + GROUP BY
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.

// lab · attempt 2: put the details in GROUP BY too
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.

orders · 4 rowsidproductsales1Caps102Caps303Gloves54Gloves20GROUP BY productproducttotalCaps40Gloves254 rows → 2 · id is gonewindow · PARTITION BY productidproductsalestotal1Caps10402Caps30403Gloves5254Gloves20254 rows → 4 · every detail kept
Same data, same SUM. GROUP BY squashes each group into one row (the id disappears). The window function writes the group total next to every row, so detail and total sit side by side.

So how do you get a total without losing the rows? →

💾 save point · the cat says

No error ≠ correct result. Ask "what does one row mean?" before and after every GROUP BY.

level 02the syntax

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
)
partjobrequired?
PARTITION BYsplit rows into groups; the calculation restarts in each oneoptional (default: everything is one window)
ORDER BYsort rows inside each windowrequired for rank and value functions
framewhich rows around the current row are usedoptional, needs ORDER BY
// lab · the three-level report
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 →

💾 save point · the cat says

OVER keeps the rows. PARTITION BY says "for each". Several windows can live in one SELECT.

level 03frames

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

ORDER BY month · current row = AprJan20Feb10Mar30Apr5Jun70Jul4065 runningUNBOUNDED PRECEDING45 rolling2 PRECEDING175 totalwhole windowrolling frame at Jul = 5 + 70 + 40 = 115
One current row, three frames. The frame decides which rows the function sees for this row, then it slides down with the current row.
frameJanFebMarAprJunJul
UNBOUNDED PRECEDING AND CURRENT ROW20306065135175
CURRENT ROW AND UNBOUNDED FOLLOWING17515514511511040
1 PRECEDING AND CURRENT ROW2030403575110
CURRENT ROW AND 2 FOLLOWING604510511511040
1 PRECEDING AND 1 FOLLOWING306045105115110
UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING175175175175175175

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.

// lab · the short form only works backwards
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.)

// trap · the default frame

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 RANGEexplicit ROWS
101010
152525
206545
206565
………
60290230
60290290
90380380

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 →

💾 save point · the cat says

ORDER BY inside OVER always means a frame. If you just wanted sorted output, use the outer ORDER BY.

level 04rules

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
rulewhat I hitfix
1 · only in SELECT and ORDER BYMsg 4108: windowed functions can only appear in the SELECT or ORDER BY clausescompute in a subquery or CTE, filter outside
2 · no nestingMsg 4109: window function inside another window or aggregateone layer per CTE step
3 · WHERE runs firstno 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 aggregatesMsg 8120 for ORDER BY Sales after GROUP BY CustomerIDRANK() OVER (ORDER BY SUM(Sales) DESC)
// lab · rule 1 workaround and rule 4 pattern
-- 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.

// compare · SQL Server (course) vs PostgreSQL (this series)
SQL ServerPostgreSQL
window in WHEREMsg 4108ERROR: window functions are not allowed in WHERE
RANGE with offsetsonly UNBOUNDED / CURRENT ROWRANGE 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 →

💾 save point · the cat says

Window functions run after WHERE and GROUP BY, so filter on them one level up.

level 05DE angle

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.

💾 save point · the cat says

Detail + subtotal + total in one row, one pass: that is the everyday job of a window function.

// episode cleared

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

  1. PostgreSQL tutorial: Window Functions
  2. PostgreSQL docs: window function calls (frames, RANGE, GROUPS)
  3. Microsoft Learn: SELECT - OVER clause (Transact-SQL)
  4. Lab data: the SalesDB sample database from the course I followed, run in SQL Server Management Studio.
← ep08 · Queries inside queries (soon)ep09b · Sum It Up →