Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the difference between a window function and GROUP BY? Show a query that lists each order with its customer's total spend and the order's share of that total.

GROUP BY collapses the rows of each group into one result row, while a window function computes a value over a set of related rows but keeps every input row. So SELECT id, customer_id, total, SUM(total) OVER (PARTITION BY customer_id) AS cust_total, total / NULLIF(SUM(total) OVER (PARTITION BY customer_id), 0) AS share FROM orders lists every order next to its customer's total and its share of it. Repeated window definitions can be named once in a WINDOW clause.

Why this question is asked

Window functions are the feature that most often turns a twenty-line Java loop, or a query joined to itself, into a single readable SELECT. Interviewers start with the difference from GROUP BY because once we understand that one difference, every window function makes sense: ranking, running totals, moving averages, comparisons with the previous row. In this answer, we will recap what GROUP BY does to rows, see how a window function differs, write the order share query and protect it against division by zero, name a window to avoid repetition, and look at a few other window functions that build on the same idea.

1A Quick Recap of GROUP BY

GROUP BY puts rows with the same value of the grouping columns into one group and returns one row per group. Any column we select must either be a grouping column or be inside an aggregate function such as SUM or COUNT, because the individual rows no longer exist in the result.

SQL
-- orders: (1, 'A', 100) (2, 'A', 300) (3, 'B', 50)
SELECT customer_id, SUM(total) AS cust_total
FROM orders
GROUP BY customer_id;
-- A | 400
-- B | 50
SELECT id, customer_id, SUM(total) FROM orders GROUP BY customer_id;
-- ERROR: column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function

The error in the second query is the point. We asked for each order's id, but after grouping there is no single id for customer A; there were two. GROUP BY answers 'what is the total per customer', not 'what is each order, and what is its customer's total'.

2How a Window Function Differs

A window function also computes over a set of rows, but it does not collapse them. For each row, it looks at a window, a set of rows related to the current one, computes its value, and attaches it to the current row. The OVER clause defines the window. PARTITION BY customer_id means 'the window for this row is all rows with the same customer_id'.

So SUM(total) OVER (PARTITION BY customer_id) returns, on every order row, the sum of totals for that order's customer. The number of rows in the result is the same as the number of rows in the input.

Same data, two results
Order idCustomerTotalGROUP BY resultWindow result (cust_total)
1A100A: 400 (one row for both)400
2A300400
3B50B: 5050
GROUP BY returns two rows for three orders; the window function returns three rows, each carrying its customer's total.

3Writing the Order Share Query

Now the query in the question is direct. We keep every order and add two computed columns.

SQL
SELECT id, customer_id, total,
SUM(total) OVER (PARTITION BY customer_id) AS cust_total,
total / SUM(total) OVER (PARTITION BY customer_id) AS share
FROM orders;
-- 1 | A | 100 | 400 | 0.25
-- 2 | A | 300 | 400 | 0.75
-- 3 | B | 50 | 50 | 1.00

Notice that the shares within each customer add up to 1. Window functions are computed after WHERE and GROUP BY, near the end of the query, so if we add WHERE created_at >= '2025-01-01', the totals and shares are computed over the filtered orders only.

One detail about types: if total is an integer column, PostgreSQL divides integers as integers and 100 / 400 gives 0. With numeric columns, which money should use, the division is exact. With integers, we cast first: total::numeric / SUM(total) OVER (...).

4Guarding Against Division by Zero

If a customer's orders sum to zero, for example one order of 50 and a refund of minus 50, the division fails with ERROR: division by zero and the whole query aborts. NULLIF(x, 0) returns NULL when x is 0 and x otherwise, and dividing by NULL gives NULL instead of an error.

SQL
SELECT id, customer_id, total,
total / NULLIF(SUM(total) OVER (PARTITION BY customer_id), 0) AS share
FROM orders;
-- 4 | C | 50 | NULL (customer C's orders sum to 0)
-- 5 | C | -50 | NULL

NULL is the honest answer here, because a share of zero is undefined. If the report needs a number, we can wrap it in COALESCE(..., 0) and say so in the report's notes.

5Naming a Window With the WINDOW Clause

When several columns use the same window, repeating PARTITION BY customer_id everywhere is noisy and easy to get wrong when one copy is edited. The WINDOW clause, written after WHERE, GROUP BY and HAVING, gives the definition a name.

SQL
SELECT id, customer_id, total,
SUM(total) OVER w AS cust_total,
COUNT(*) OVER w AS cust_orders,
total / NULLIF(SUM(total) OVER w, 0) AS share
FROM orders
WINDOW w AS (PARTITION BY customer_id);

Besides readability, it tells the database clearly that these columns share one window, so it partitions the data once. PostgreSQL and MySQL 8.0 and later both support the WINDOW clause.

6Other Window Functions Built on the Same Idea

Once the idea of a window is clear, other functions are small steps. Adding ORDER BY inside OVER gives the window an order, which ranking and distribution functions need. NTILE(4) OVER (ORDER BY total) splits rows into four groups of nearly equal size and returns 1 to 4, which is a quick way to label quartiles. PERCENT_RANK() returns (rank - 1) / (rows - 1), so the smallest value gets 0 and the largest 1. CUME_DIST() returns the fraction of rows with a value less than or equal to the current one, so the largest gets 1.

SQL
SELECT id, total,
NTILE(4) OVER (ORDER BY total) AS quartile,
PERCENT_RANK() OVER (ORDER BY total) AS pct_rank,
CUME_DIST() OVER (ORDER BY total) AS cume
FROM orders;
-- totals 50, 100, 300, 500
-- 50 | 1 | 0.000 | 0.25
-- 100 | 2 | 0.333 | 0.50
-- 300 | 3 | 0.667 | 0.75
-- 500 | 4 | 1.000 | 1.00

The same partition idea applies here too: NTILE(4) OVER (PARTITION BY customer_id ORDER BY total) gives quartiles within each customer rather than across all orders.

7Follow-up questions

Can I use a window function in WHERE?

No. WHERE is evaluated before window functions are computed, so the value does not exist yet. We compute the window in a subquery or CTE and filter in the outer query, for example SELECT * FROM (SELECT ..., total / SUM(total) OVER w AS share FROM orders WINDOW w AS (...)) t WHERE share > 0.5.

Can I combine GROUP BY and a window function in one query?

Yes, and the window then works on the grouped rows. SELECT customer_id, SUM(total) AS s, SUM(total) / SUM(SUM(total)) OVER () AS share_of_all FROM orders GROUP BY customer_id gives each customer's share of all revenue. The inner SUM is the group aggregate, and the outer SUM ... OVER () adds up the group sums across all result rows.

Is the window version slower than a join to a grouped subquery?

Usually it is about the same or faster, because the database reads orders once and sorts or hashes by customer_id, instead of reading orders twice and joining. On very large tables the sort for the partition can spill to disk, which EXPLAIN ANALYZE shows; an index on customer_id can sometimes provide presorted input.

8Conclusion

In this answer, we saw that GROUP BY collapses each group into one row, while a window function computes over a set of related rows and keeps every input row. That let us list each order with its customer's total and its share using SUM(total) OVER (PARTITION BY customer_id), guard the division with NULLIF, name a repeated window with a WINDOW clause, and extend the same idea to NTILE, PERCENT_RANK and CUME_DIST.

What to say in the interviewAbout 80 seconds aloud

Open with

GROUP BY collapses all the rows of a group into one output row, so I lose the individual rows and can only select grouping columns and aggregates. A window function computes over a set of related rows, defined by the OVER clause, but keeps every input row and just adds the computed value to it.

Then, if they want more

For this question I'd write: SELECT id, customer_id, total, SUM(total) OVER (PARTITION BY customer_id) AS cust_total, and total divided by that same window sum as share, FROM orders. Every order comes back, carrying its customer's total and its fraction of it.

Two practical details: I'd wrap the denominator in NULLIF of the sum and zero, so a customer whose orders net to zero gives NULL instead of a division by zero error, and if total were an integer I'd cast to numeric to avoid integer division.

Since I use the same window twice, I'd name it once with WINDOW w AS (PARTITION BY customer_id) and write OVER w. The same idea extends to other functions, like NTILE(4) for quartiles, or PERCENT_RANK and CUME_DIST for percentiles, which just add an ORDER BY to the window. And window functions run after WHERE, so filtering on them needs a subquery.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.0
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is the difference between a window function and GROUP BY? Show a query that lists...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/21311b1a13/