SQL Window Functions
A window function calculates across a set of related rows without collapsing them. Unlike GROUP BY, every row stays in the result, with the group’s value alongside it. The OVER (...) clause defines the window.
Updated December 1, 2026
Syntax
FUNCTION(column) OVER (
PARTITION BY group_column
ORDER BY sort_column
)
Compare each row to its group
Each engineer’s salary next to the department average. PARTITION BY restarts the calculation for each department.
SELECT name, salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg,
salary - AVG(salary) OVER (PARTITION BY department_id) AS vs_avg
FROM employees
WHERE department_id = 1
ORDER BY salary DESC;
| name | salary | dept_avg | vs_avg |
|---|---|---|---|
| Omar Haddad | 215000 | 163000 | 52000 |
| Maya Chen | 210000 | 163000 | 47000 |
| Lena Park | 150000 | 163000 | -13000 |
| Ravi Patel | 120000 | 163000 | -43000 |
| Sofia Rossi | 120000 | 163000 | -43000 |
Running total
With ORDER BY inside OVER, SUM adds up rows so far: total drinks sold to date.
SELECT ordered_on, SUM(quantity) AS sold,
SUM(SUM(quantity)) OVER (ORDER BY ordered_on) AS running_total
FROM orders
GROUP BY ordered_on;
| ordered_on | sold | running_total |
|---|---|---|
| 2024-07-01 | 3 | 3 |
| 2024-07-02 | 2 | 5 |
| 2024-07-03 | 4 | 9 |
| 2024-07-04 | 2 | 11 |
| 2024-07-05 | 3 | 14 |
| 2024-07-06 | 1 | 15 |
Share of the total
An empty OVER () makes the window the whole result, so each category can be shown as a percentage.
SELECT category, COUNT(*) AS drinks,
ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM drinks
GROUP BY category;
| category | drinks | pct |
|---|---|---|
| coffee | 5 | 50 |
| other | 2 | 20 |
| tea | 3 | 30 |
Common mistakes
- Filtering on a window function in
WHERE. Windows are calculated afterWHERE, so wrap the query in a CTE and filter outside. - Expecting
PARTITION BYto remove rows. It only groups the calculation; useGROUP BYto collapse rows. - Leaving out
ORDER BYin a running total, which gives the grand total on every row.
Practice Window Functions interactively
Write real queries in your browser and get instant feedback in the lesson “PARTITION BY” (Unit 8). New learners can start free from the first lesson.
Frequently asked questions
What is the difference between GROUP BY and PARTITION BY?
GROUP BY returns one row per group. PARTITION BY keeps every row and adds the group’s value to each.
Which databases support window functions?
All the major ones: PostgreSQL, MySQL 8+, SQL Server, Oracle and SQLite 3.25+.