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;
Result on the Acme Co. (company data) sample data (5 rows)
namesalarydept_avgvs_avg
Omar Haddad21500016300052000
Maya Chen21000016300047000
Lena Park150000163000-13000
Ravi Patel120000163000-43000
Sofia Rossi120000163000-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;
Result on the SQL Café sample data (6 rows)
ordered_onsoldrunning_total
2024-07-0133
2024-07-0225
2024-07-0349
2024-07-04211
2024-07-05314
2024-07-06115

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;
Result on the SQL Café sample data (3 rows)
categorydrinkspct
coffee550
other220
tea330

Common mistakes

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+.

Related SQL tutorials