# Window Functions

> Add a per-group number such as an average next to every row without collapsing the rows, using OVER and PARTITION BY.

Subject: SQL | Lesson 27 of 44 | 6 min read
Interactive lesson: https://codewithanimation.in/sql/window-functions
Previous: [Recursive CTEs](https://codewithanimation.in/sql/recursive-ctes.md) | Next: [Ranking & Running Totals](https://codewithanimation.in/sql/ranking-and-running-totals.md)

## Calculate across rows, keep every row

A **window function** calculates a value from a set of rows related to the current row, but unlike `GROUP BY` it does not collapse them. Every input row stays in the output, and the calculated value is added next to it.

A window function call always has an `OVER (...)` clause right after it. `PARTITION BY` inside `OVER` splits the rows into groups called partitions, and the function is calculated separately in each one.

## Detail and summary on one row

"Show every player and their team's average" needs both the single row and the group value. With `GROUP BY` you would need a join back to the table. A window function gives it in one step.

## Each player next to the team average

```sql
SELECT name, team, points,
       avg(points) OVER (PARTITION BY team) AS team_avg
FROM players;
```

All 8 players are returned. Asha, Chen and Fay each show 27.5 (Red's average of 31 and 24, since NULL is skipped). Ben, Eli and Hana show 17.0. Dara and Gus show 32.0.

`OVER ()` with nothing inside means one window of all rows, so `sum(points) OVER ()` puts the same total, 153, on every row. Any aggregate, such as `count`, `sum`, `avg`, `min` or `max`, can be used as a window function.

## Common mistake: When the window runs

Window functions run after `WHERE`, `GROUP BY` and `HAVING`. A row removed by `WHERE` is never seen by the window, so the counts and averages change when you filter.

That also means a window function is not allowed in `WHERE`, `GROUP BY` or `HAVING`. `WHERE rank() OVER (...) = 1` fails with `window functions are not allowed in WHERE`. To filter on a window result, wrap the query in a subquery or CTE and filter outside.

Do not confuse the two tools: `GROUP BY` gives one row per group, a window function gives one row per input row.

## Tip: Pick by the shape you want back

Want one row per group? Use `GROUP BY`. Want every row, plus a group value beside it? Use `OVER (PARTITION BY ...)`.

## Try it: Collapse or keep the rows

Compare GROUP BY with the window versions, then switch on the WHERE filter and watch the window values change.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/window-functions

## Check yourself

### Question 1

`players` has 8 rows. How many rows does `SELECT name, avg(points) OVER (PARTITION BY team) FROM players` return?

- A. 8
- B. 3
- C. 1

Correct answer: A

Window functions add a value to each row. They never reduce the number of rows.

- Why not B: 3 is what GROUP BY team would give. A window function keeps every input row.
- Why not C: One row would come from a plain aggregate with no GROUP BY and no OVER.

### Question 2

A query has `WHERE points IS NOT NULL` and `count(*) OVER (PARTITION BY team)`. For the Red team (3 players, 1 with NULL points), what does count show?

- A. 2, because the NULL row was removed before the window ran
- B. 3, because the window counts all rows
- C. 1

Correct answer: A

WHERE runs before window functions, so rows it removes are never counted.

- Why not B: The window only sees the rows left after WHERE.
- Why not C: Two Red players have points, so two rows remain.

### Question 3

Can you write `WHERE row_number() OVER (ORDER BY points) = 1`?

- A. No, window functions are not allowed in WHERE
- B. Yes, it keeps the first row
- C. Yes, but only with PARTITION BY

Correct answer: A

Window functions run after WHERE, so use a subquery or CTE and filter on the window column outside.

- Why not B: PostgreSQL rejects it. WHERE runs before window functions exist.
- Why not C: PARTITION BY does not change the rule. The window function must be in the SELECT list or ORDER BY.

## Remember this

- A window function calculates a value across related rows without collapsing them.
- OVER (PARTITION BY ...) splits the rows into partitions, and OVER () is the whole table.
- Window functions run after WHERE, GROUP BY and HAVING, so rows removed by WHERE are not seen.
- They are allowed only in SELECT and ORDER BY. To filter on one, use a subquery or CTE.
