Window vs GROUP BY: Keep the Rows
Chapter 7 — “Seeing Across Rows”
QUERY wakes you before the general signal.
A new clearance appears on the main holopanel: the Academy's amber seal and a rank you've never seen before.
Until now, you've looked at the archive in two ways.
The first is row by row:
SELECT id, total_amount
FROM orders;
You can see every detail, but you can't see the bigger picture.
The second is a summary:
SELECT SUM(total_amount) AS total_revenue
FROM orders;
You can see the grand total, but the individual orders disappear.
A higher-rank archivist sees a third way: every row stays visible, along with its place in the overall flow.
QUERY: A summary answers “how much in total?” A higher-rank archivist can see that total without taking their eyes off the individual rows. That's what do.

The problem with GROUP BY: it collapses rows
Suppose you need to calculate the total value of all paid orders.
A regular does the job:
SELECT
SUM(total_amount) AS total_paid
FROM orders
WHERE status = 'paid';
But the result is a single row:
total_paid
----------
13812.30
That's fine for a summary. But if you need to see every order with the grand total beside it, this query won't work: the individual rows are already gone.
You can return the orders themselves:
SELECT
id,
total_amount
FROM orders
WHERE status = 'paid'
ORDER BY id;
But now the grand total is missing.
Before , you had to calculate the grand total separately and join it back to the detailed rows. It worked, but it required more machinery than the task itself.
Window functions solve this problem.
A window function calculates without collapsing rows
A window function adds a calculation over a set of rows to each row in the result.
The syntax is:
function(...) OVER (...)
For example:
SUM(total_amount) OVER ()
This means:
calculate the sum of
total_amountover the window and show the result next to every row.
The empty parentheses in OVER () mean that the window contains every row in the current result.
For example:
SELECT
id AS order_id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE status = 'paid'
ORDER BY id
LIMIT 8;
Each order remains a separate row, and the grand total for all paid orders appears beside it.
A window function doesn't replace the rows with one summary row. It adds context to each row instead.
First example: total and average on each order row
You can show both the grand total and the average order value at once:
Here's what's happening:
WHERE status = 'paid'keeps only paid orders;- every order row stays in the result;
SUM(total_amount) OVER ()calculates the sum across all remaining rows;AVG(total_amount) OVER ()calculates the average across all remaining rows;ROUND(..., 2)rounds the average to two decimal places.
The total and average repeat on every row. That's expected: they provide context for each individual order.
How this differs from GROUP BY
To compare the two approaches fairly, ask the same question in both cases. Here the question is “how much money is there across all orders?”
Aggregate:
SELECT
SUM(total_amount) AS total_all
FROM orders;
There's no explicit GROUP BY here, but there is still one group: the entire table. The result is one row, 18557.90. The individual orders are gone.
Window function:
SELECT
id,
status,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
ORDER BY id;
The result keeps all 120 orders, and every row gets the same 18557.90 in a separate column.
The question and the number are the same. What changes is what happens to the rows: an collapses them, while a window keeps them.
The same principle works at any other level of . If you need totals by status:
SELECT
status,
SUM(total_amount) AS total_status
FROM orders
GROUP BY status;
The result has one row per status: paid — $13812.30, refunded — $2477.40, cancelled — $1261.40, pending — $1006.80.
A window with the same boundary:
SELECT
id,
status,
total_amount,
SUM(total_amount) OVER (PARTITION BY status) AS total_status
FROM orders
ORDER BY id;
The result again keeps all 120 orders, and each order gets the total for its own status beside it: a paid order gets $13812.30, while a refunded order gets $2477.40. These are the same numbers as in the summary, repeated on the relevant detail rows.
We'll cover PARTITION BY in detail later in the module. For now, focus on this idea: a summary can often be expressed as a window calculation that answers the same question without removing rows.
You can remember it this way:
GROUP BY reduces the number of rows.
A keeps the number of rows and adds a calculation.
Why this matters
Window functions are useful whenever you need “detail plus context.”
For example:
- show an order and the grand total across all orders;
- show an order and the average order value across all orders;
- calculate an order's share of total revenue;
- number rows;
- find a user's position in a ranking;
- compare the current month with the previous month;
- calculate a running total.
In this lesson, you start with the simplest window: OVER (), meaning “look at the entire result.”
Later, you'll learn to narrow the window:
PARTITION BYwill split rows into groups inside the window;ORDER BYinsideOVERwill define the order in which the window processes rows;- functions such as
ROW_NUMBER,RANK,LAG, andLEADwill give you row numbers, ranks, and values from neighboring rows.
For now, focus on the basic principle: a window calculates over a set of rows without removing those rows.
products, return the products in the Electronics category: name, price, and the average price of those products as avg_price, rounded to 2 decimal places. Don't combine the products into groups: each product should remain a separate row, with the average price beside it.A window is the set of rows a function can look at from the current row.
SUM(total_amount) OVER ()
OVER () means: look at the entire result—all rows that remain after FROM and WHERE, and after GROUP BY and HAVING if the query contains them.
The calculates over that set without collapsing the rows. Every source row remains in the result, with the calculation shown beside it in a separate column.
Later, you'll learn to narrow that field of view: PARTITION BY will split the window into sections, while ORDER BY inside OVER will define the order in which the function processes the rows.
When the window comes into play: execution order
To use confidently, you need to know when they're calculated.
A simplified logical query execution order looks like this:
FROM— where the rows come from;WHERE— which rows we keep;GROUP BY— how we group them;HAVING— which groups we keep;- window functions — calculate values such as
... OVER (...); SELECT— build the final list of columns;DISTINCT— remove duplicates if needed;ORDER BY— sort the result;LIMIT— limit the number of rows.
Window functions are calculated late: after WHERE, GROUP BY, and HAVING.
This has two important consequences.
A window sees only rows that survived WHERE
In this query:
SELECT
id AS order_id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE status = 'paid';
the window calculates the sum over the rows that passed this filter, rather than over the entire orders table:
WHERE status = 'paid'
First, unpaid orders are filtered out. Then the window sees the remaining rows.
So total_all here is the sum of paid orders, not the sum of every order in the table.
That's often exactly what you want. The important part is knowing why it happens.
You can't filter on a window result in WHERE
Bad query:
SELECT
id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE total_amount > 0.02 * SUM(total_amount) OVER ();
This isn't allowed.
When WHERE runs, the result of SUM(total_amount) OVER () doesn't exist yet. Window functions are calculated later.
PostgreSQL will return an error because window functions aren't allowed in WHERE.
Pattern: window inside, filter outside
If you need to filter rows by the result of a window function, use a or .
For example, find paid orders whose value is greater than 2% of total paid revenue.
SELECT *
FROM (
SELECT
id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE status = 'paid'
) t
WHERE total_amount > 0.02 * total_all
ORDER BY total_amount DESC;
Here's what happens:
- The inner query keeps the paid orders and calculates
total_all. - The outer query can now see the
total_allcolumn. - The outer
WHEREcan therefore filter on it.
You can write the same thing with a CTE:
WITH orders_with_total AS (
SELECT
id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE status = 'paid'
)
SELECT *
FROM orders_with_total
WHERE total_amount > 0.02 * total_all
ORDER BY total_amount DESC;
A CTE is often easier to read, especially when the logic takes more than one step.
Why windows can't be used in GROUP BY or HAVING
For the same reason, you can't use window functions in GROUP BY or HAVING.
Those parts of the query run before window functions are calculated.
You can't group by a value that hasn't been calculated yet.
You also can't filter groups in HAVING by a window column that doesn't exist yet.
If you need to filter on a window result, use the same pattern:
window inside, filter outside.
You'll see this pattern again later, especially in “ within each group” problems.
But you can use them in ORDER BY
You can use a window function in ORDER BY because sorting happens after window functions are calculated.
Sorting by one is useful only if the expression can produce different values for different rows. Here's a useless example:
-- the order will be exactly the same as with ORDER BY total_amount DESC
ORDER BY total_amount / SUM(total_amount) OVER () DESC;
SUM(total_amount) OVER () is the same number for every row. Dividing every value by the same positive denominator doesn't change their relative order: if one order was larger than another before division, it will still be larger afterward. The window only adds work here, and if the sum is zero, the query will also fail with division by zero.
A window in ORDER BY becomes useful when it produces a value that would otherwise be difficult to express in the sort. For example, suppose you want the most unusual orders at the top—the ones farthest from the average order value:
SELECT
id,
total_amount
FROM orders
WHERE status = 'paid'
ORDER BY ABS(total_amount - AVG(total_amount) OVER ()) DESC;
Here's how it works, step by step:
AVG(total_amount) OVER ()— the average value across all paid orders. It's one number, available to every row.total_amount - AVG(total_amount) OVER ()— the row's deviation from the average: positive for expensive orders and negative for cheap ones.ABS(...)removes the sign, leaving the distance from the average.DESCputs the rows with the greatest distance at the top.
This order differs from ORDER BY total_amount DESC: both the most expensive and the cheapest orders can appear near the top, while orders close to the average fall toward the bottom.
The difference from the useless example is the transformation itself. Division by a constant is monotonic, so it preserves the order of the values. ABS is not monotonic across values on opposite sides of the average, so it can produce a different sort order.
For readability, it's usually better to move the calculation into a subquery or CTE and sort by a clearly named column.
WITH orders_with_avg AS (
SELECT
id,
total_amount,
AVG(total_amount) OVER () AS avg_all
FROM orders
WHERE status = 'paid'
)
SELECT
id,
total_amount,
ABS(total_amount - avg_all) AS distance_from_avg
FROM orders_with_avg
ORDER BY distance_from_avg DESC;
That makes the query easier to read and check.
Windows and GROUP BY can work together
Sometimes a query groups rows first and then applies a window function to the grouped result.
For example, first calculate revenue by month, then show each month's share of total revenue.
WITH monthly_revenue AS (
SELECT
DATE_TRUNC('month', created_at) AS month_start,
SUM(total_amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY DATE_TRUNC('month', created_at)
)
SELECT
month_start,
revenue,
revenue / SUM(revenue) OVER () AS share_of_total
FROM monthly_revenue
ORDER BY month_start;
Here, GROUP BY first collapses the orders into one row per month. Then the window function calculates the grand total across those monthly rows.
There's no conflict because the two operations happen at different levels of the query.
The important part is knowing what each row represents at each level.
products whose price is above the average price across the entire catalog. Return name, price, and the catalog's average price as avg_price, rounded to 2 decimal places.Interview question
Interview question: What's the difference between a and an with GROUP BY, and when should you use each one?
Strong answer: An aggregate with GROUP BY collapses the rows in each group into one result row. Use it for summaries such as revenue by month, order counts by status, or average order value by category.
A window function also calculates over a set of rows, but it keeps the original rows. The result appears as an additional column beside each one.
Use a window for “detail plus context” tasks: an order with the grand total, an order with its share of revenue, a user with their position in a ranking, or the current month with the previous month's value.
Remember the execution order: window functions are calculated after WHERE, GROUP BY, and HAVING. So you can't filter directly on a window result in WHERE. Calculate the window in an inner query or , then filter in the outer query.
Interview question: Why doesn't a query with a window function in WHERE work?
Strong answer: Because WHERE runs before window functions are calculated. When filtering happens, the window column doesn't exist yet.
You can't write:
WHERE total_amount > 0.02 * SUM(total_amount) OVER ()
Instead, calculate the window value in an inner query first, then filter the outer result:
SELECT *
FROM (
SELECT
id,
total_amount,
SUM(total_amount) OVER () AS total_all
FROM orders
WHERE status = 'paid'
) t
WHERE total_amount > 0.02 * total_all;
This is the “window inside, filter outside” pattern.
SUM(x) OVER () and GROUP BY with SUM(x)?QUERY opens the first layer of your new vision: you can now look at a row while also seeing the larger flow it belongs to.
- Portfolio Composition as of December 2, 2024HARD
- Each Product's Share of Total Revenue via SUM() OVER ()MEDIUM
- Staff Salaries: How Far From the AverageMEDIUM
SELECT id AS order_id, total_amount, SUM(total_amount) OVER () AS total_all,
ROUND(AVG(total_amount) OVER (), 2) AS avg_all
FROM orders
WHERE status = 'paid'
ORDER BY id
LIMIT 8;