01 / 19

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.

Database Programming

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.

Original Rows Alice | Sales | 100 Bob | Sales | 150 Carol | Eng | 200 Dave | Eng | 180 Eve | Sales | 120 GROUP BY dept Grouped Result Sales SUM = 370 | COUNT = 3 Eng SUM = 380 | COUNT = 2 5 rows → 2 rows Rows are collapsed. Detail is lost.

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.

Original Rows Alice | Sales | 100 Bob | Sales | 150 Carol | Eng | 200 Dave | Eng | 180 Eve | Sales | 120 SUM(...) OVER (PARTITION BY dept) Result (all rows kept) Alice | Sales | 100 | 370 Bob | Sales | 150 | 370 Carol | Eng | 200 | 380 Dave | Eng | 180 | 380 Eve | Sales | 120 | 370 5 rows → 5 rows New column added. No rows lost.

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.

GROUP BY
Use when you only need summary rows: totals, counts, averages per group.
Window Function
Use when you need the summary alongside every individual row.
Mixing Both
Dangerous: the window function runs after GROUP BY, so it sees grouped rows, not original rows.

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.

1. FROM / JOIN 2. WHERE 3. GROUP BY 4. HAVING 5. SELECT + Window Fns 6. ORDER BY / LIMIT Window sees grouped rows!

The Golden Rule

1
Without GROUP BY: a window function scans all original rows.
2
With GROUP BY: the rows are collapsed first, then the window function scans the collapsed rows.
3
Consequence: mixing them changes what your window function counts, sums, or ranks.

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

1
Ask: "Do I need every original row in the output?" If yes, skip GROUP BY and use a window function alone.
2
Ask: "Do I need only summary rows?" If yes, use GROUP BY with regular aggregates: no window function needed.
3
Ask: "Do I need a summary of summaries?" Only then combine both. The window function will operate on the grouped result.
4
Verify: mentally count the rows after GROUP BY. That is the dataset your window function sees.
5
Alternative: if you need row-level detail + group-level totals, use a subquery or CTE instead of mixing.

Example 1: Window Function Alone

Goal: show each employee's salary alongside their department total.

SELECT name, dept, salary, SUM(salary) OVER (PARTITION BY dept) AS dept_total FROM employees;

Example 2: GROUP BY Alone

Goal: show the total salary per department, nothing more.

SELECT dept, SUM(salary) AS dept_total FROM employees GROUP BY dept;

Example 3: Mixing Both (The Trap)

Goal: rank departments by total salary. A developer writes:

SELECT dept, SUM(salary) AS dept_total, RANK() OVER (ORDER BY SUM(salary) DESC) AS rnk FROM employees GROUP BY dept;

When Mixing Goes Wrong

A developer wants to rank individual employees within each department, but mistakenly adds GROUP BY:

-- WRONG: wants per-employee rank, but GROUP BY collapses rows SELECT dept, SUM(salary) AS dept_total, RANK() OVER (PARTITION BY dept ORDER BY SUM(salary) DESC) AS emp_rank FROM employees GROUP BY dept;

Correct Mixed Use: Summary of Summaries

Goal: for each department, show its total salary and what percentage of the company total it represents.

SELECT dept, SUM(salary) AS dept_total, SUM(salary) * 100.0 / SUM(SUM(salary)) OVER () AS pct_of_company FROM employees GROUP BY dept;

Visualizing the Data Pipeline

Raw Table Alice | Sales | 100 Bob | Sales | 150 Eve | Sales | 120 Carol | Eng | 200 Dave | Eng | 180 5 rows GROUP BY After GROUP BY Sales | 370 Eng | 380 2 rows Window Fn After Window Fn Sales | 370 | 49.3% Eng | 380 | 50.7% Still 2 rows The window function never saw the original 5 rows. It only operated on the 2 grouped rows.

Common Mistakes

✕ Expecting Row-Level Rank
Adding ROW_NUMBER() with GROUP BY, then wondering why every rank is 1. The window sees only grouped rows.
✕ Accessing Pre-Grouped Columns
Trying to use a window function on a raw column (e.g. SUM(salary) OVER()) after a GROUP BY. This fails because the window function only sees grouped data, not the original 'salary' column.
✕ Missing PARTITION BY
Forgetting PARTITION BY in the OVER clause, so the window function treats the entire result as one partition.

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

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?