Window Functions vs GROUP BY Aggregations (Preserving Row Granularity)
Use windows when you need aggregates without collapsing detail rows.
In plain words
GROUP BY squashes rows into one per group. A window function keeps all the rows and writes the group's answer on each.
Think of it like…
A class's exam results: GROUP BY gives you one summary line per class ("Class A: average 72"). A window function gives every student's line with the class average printed next to their own mark.
Where you’ve seen it
SELECT name, dept, salary, AVG(salary) OVER (PARTITION BY dept) AS dept_avg, salary - AVG(salary) OVER (PARTITION BY dept) AS diff FROM employees;: every employee, their department average, and how far above or below it they are.
Words you’ll hear
- Row grain
- Whether the output has one row per group (GROUP BY) or one per original row (window).
- OVER ()
- Turns an aggregate into a window function; empty parentheses mean the whole result set.
- PARTITION BY
- The window's equivalent of GROUP BY: which rows each calculation looks at.
- Evaluation order
- Window functions run after WHERE, GROUP BY and HAVING.
Visual diagram
Theory & example queries
Choosing between them
If the answer should have one row per group (revenue per month), use GROUP BY. If each detail row should stay and be compared with its group (each order versus the customer's average), use a window function with PARTITION BY on the same columns you'd have grouped by.
Without window functions, the detail-plus-aggregate shape needs a GROUP BY subquery joined back to the detail table. That works, but it's longer and reads the table twice.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT order_id, customer_id, amount, amount / SUM(amount) OVER ( PARTITION BY customer_id ) AS shareFROM orders;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Orders as shares of customer totals3 sample rows
| order_id | customer_id | amount | share |
|---|---|---|---|
| 101 | 7 | 600 | 0.6 |
| 102 | 7 | 400 | 0.4 |
| 201 | 8 | 250 | 1 |
Note: Assumes a 1,000 total for customer 7 and a 250 total for customer 8; all source rows remain visible with a window SUM.
Key takeaway: Summary → GROUP BY; detail with group context → window.
Using both in one query
Window functions are evaluated after GROUP BY, so they can operate on grouped results. SELECT dept, SUM(salary) AS total, SUM(SUM(salary)) OVER () AS company_total FROM employees GROUP BY dept gives each department's total next to the company total, and dividing them gives each department's share.
Because they run after WHERE, you can't filter on a window result in the same query's WHERE. Compute it in a CTE and filter outside, which is the standard pattern for "rows above their group's average".
WITH x AS ( SELECT name, salary, AVG(salary) OVER ( PARTITION BY dept ) AS dept_avg FROM employees )SELECT nameFROM xWHERE salary > dept_avg;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Above-average employees2 sample rows
| name |
|---|
| Priya |
| Sam |
Note: Representative salaries where the returned employees earn more than the AVG(salary) for their department.
Key takeaway: Windows run after grouping; filter their results in an outer query.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide the output grain
Ask whether the result needs one row per group or one row per original record.
per department vs per employee
When to use it & trade-offs
What it is
GROUP BY collapses each group into a single row. A window function (AVG(salary) OVER (PARTITION BY dept)) computes the same kind of aggregate but keeps every original row, attaching the group's value to each one. Same maths, different shape of result.
Why it matters: Questions like "show each employee with their department's average" or "each order as a percentage of the customer's total" need detail rows and group aggregates together. GROUP BY alone can't do it without joining back; a window function does it in one pass. Knowing which one fits is a basic SQL interview check.
When to reach for it
- Each row next to its group's average, total or count
- Percent of total per row
- Rows above or below their group's average
When to avoid or be careful
- GROUP BY plus a join back when a window function would do
- Window functions when you actually want one row per group (you'd need DISTINCT to undo the duplication)
- Filtering on a window result in the same WHERE
GROUP BY vs window function vs join-back
Strengths: Smallest result; exactly what a report needs.
Watch out: Loses the detail rows.
Strengths: One pass, keeps every row, no extra join.
Watch out: Results can't be filtered in the same WHERE.
Strengths: Works everywhere.
Watch out: Longer and reads the table twice.
Interview signals & numbers to know
When this topic comes up
- “Show each employee with their department's average”
- “Percentage of total”
- “Above the group average”
- OVER (PARTITION BY …)
- Keep detail rows
Benchmarks & rules of thumb
- GROUP BY
- rows = number of groups
- Window
- rows = number of input rows
- OVER ()
- one window over everything
Common mistakes & follow-ups
Common interview mistakes
- Using a window function and then adding DISTINCT to get one row per group, when GROUP BY was the right tool.
- Trying to select a detail column with GROUP BY and getting the "must appear in GROUP BY" error.
- Filtering
WHERE salary > AVG(salary) OVER (…)in the same query level.
Likely interviewer follow-ups
- How would you show each product's sales and its share of its category's sales?
- Can you use a window function together with GROUP BY in one query?
- Why can't you filter on a window function in WHERE?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Window Functions vs GROUP BY Aggregations (Preserving Row Granularity) with hands-on SQL practice and interview Q&A.