Window Functions
& GROUP BY
Learn how window functions and GROUP BY operate at different levels of your data, and why mixing them incorrectly produces surprising results.
What Is GROUP BY?
GROUP BY collapses many rows into fewer rows. Each group becomes one output row. You can then compute aggregates like SUM, COUNT, or AVG for each group.
What Are Window Functions?
A window function performs a calculation across a set of rows related to the current row, without collapsing them. Every original row is preserved in the output.
Why Does This Matter?
In real SQL, you will often want both aggregated summaries and row-level detail in the same query. Understanding when to use GROUP BY versus a window function prevents bugs, wrong numbers, and hours of debugging.
The Execution Order Rule
SQL has a strict logical order of operations. Window functions run after GROUP BY and HAVING, but before ORDER BY and LIMIT. This is the root cause of every mixing mistake.
The Golden Rule
GROUP BY vs Window Functions
| GROUP BY | Window Function | |
|---|---|---|
| Output rows | One per group | Same as input |
| Row detail | Lost | Preserved |
| Clause | After WHERE clause | OVER() in SELECT phase |
| Non-agg columns | Must be in GROUP BY list | All columns available |
| Can use together? | Yes, but the window sees grouped rows | |
Step-by-Step Decision Process
Example 1: Window Function Alone
Goal: show each employee's salary alongside their department total.
Example 2: GROUP BY Alone
Goal: show the total salary per department, nothing more.
Example 3: Mixing Both (The Trap)
Goal: rank departments by total salary. A developer writes:
When Mixing Goes Wrong
A developer wants to rank individual employees within each department, but mistakenly adds GROUP BY:
Correct Mixed Use: Summary of Summaries
Goal: for each department, show its total salary and what percentage of the company total it represents.
Visualizing the Data Pipeline
Common Mistakes
Summary: When to Use What
| Scenario | Approach | Key Clause |
|---|---|---|
| Summary rows only | GROUP BY + aggregates | GROUP BY |
| Detail rows + per-group calc | Window function alone | OVER(PARTITION BY) |
| Rank groups after aggregation | GROUP BY + window fn | Both (intentional) |
| Percent of total per group | GROUP BY + window fn | SUM(...) OVER() |
| Rank individuals within groups | Window function alone | NOT GROUP BY |
Question 1 of 3
In SQL's logical order of operations, when do window functions execute relative to GROUP BY?
Question 2 of 3
Consider a table orders with 100 rows, where there are 10 distinct customers. A developer writes:
SELECT customer_id, COUNT(*) AS order_count, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rnk FROM orders GROUP BY customer_id;
How many rows does ROW_NUMBER() operate on?
Question 3 of 3
You want to display each employee's name and salary alongside their department's average salary. Which approach is correct?