QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Window functions

What are window functions and how do they differ from GROUP BY?

A window function computes over a group of rows but keeps every row, while GROUP BY collapses a group into one row. It adds the value as a separate column: function() OVER (PARTITION BY … ORDER BY …). Window functions run after WHERE, GROUP BY and HAVING, so they are written only in SELECT and ORDER BY, and filtering by them needs a CTE or subquery.

SQL · Window functions

You need to show each employee and the total of their department. GROUP BY hides rows. What now?

A report has to show every salary separately with the department total beside it. A plain GROUP BY leaves one row per department and the details vanish. Then people add a JOIN to a grouped subquery and the query grows. A window function solves it in one line: it computes over a group but does not collapse the rows.

How it works and why. An ordinary aggregate reduces a group of rows to one. A window function computes the same over a "window" of rows but writes the result into every row as a separate column. The syntax: function() OVER (PARTITION BY … ORDER BY …). PARTITION BY splits rows into groups like GROUP BY but without collapsing. ORDER BY inside OVER sets the order within a group (needed for ranks and running totals). Empty parentheses OVER () mean the window is the whole result. The sample data: five employees.

namedeptsalary
AnnaDev9000
BohdanDev8000
ClaraDev8000
DmytroDev7000
EvaQA7000
-- GROUP BY: one row per department, the details are gone
SELECT dept, SUM(salary) AS dept_total
FROM employees
GROUP BY dept;

-- OVER: all rows stay, the total sits next to them
SELECT name, dept, salary,
       SUM(salary) OVER (PARTITION BY dept) AS dept_total
FROM employees;

Collapsing against a window

GROUP BY dept
deptdept_total
Dev32000
QA7000
OVER (PARTITION BY dept)
namedeptdept_total
AnnaDev32000
BohdanDev32000
ClaraDev32000
DmytroDev32000
EvaQA7000
Figure 1. GROUP BY gives two rows, the window keeps all five and adds the department total to each.

The total for Dev: 9000 + 8000 + 8000 + 7000 = 32000, QA has one employee with 7000. The window returns these numbers next to every row and the number of rows does not change.

Where the window fits in a query. Logically window functions are computed after FROM, WHERE, GROUP BY and HAVING but before ORDER BY and LIMIT. So they can be written only in SELECT and ORDER BY, not in WHERE: at that moment the window is not computed yet.

SELECT name FROM employees
WHERE SUM(salary) OVER (PARTITION BY dept) > 20000;
-- ERROR: window functions are not allowed in WHERE

To filter by the value of a window function, wrap it in a CTE or a subquery and filter outside.

Example: from JOIN to a window. Show the difference between a salary and the department average. Without window functions:

-- without window functions: a JOIN to a grouped table
SELECT e.name, e.salary, s.avg_salary
FROM employees e
JOIN (SELECT dept, AVG(salary) AS avg_salary
      FROM employees GROUP BY dept) s ON s.dept = e.dept;

With a window function the same meaning needs no subquery:

-- with a window function; difference from the average: 1000, 0, 0, -1000, 0
SELECT name, dept, salary,
       salary - AVG(salary) OVER (PARTITION BY dept) AS diff_from_avg
FROM employees;

Two models of the same calculation

GROUP BY

Rows collapse

One row per group. The details must be brought back separately with a JOIN to the result.

OVER

Rows stay

Every row is kept and gets the group value. The aggregate and the details in one query.

Figure 2. Both compute per group, the difference is what stays in the result.

Limits and alternatives. If only a summary table is needed (one row per group), GROUP BY is simpler and usually faster. Window functions are used when the details must stay in the result. Several functions with the same window are convenient to describe once through WINDOW:

-- a named window: one definition for several functions
SELECT name, dept,
       SUM(salary) OVER w AS dept_total,
       COUNT(*)    OVER w AS dept_size
FROM employees
WINDOW w AS (PARTITION BY dept);

Aggregates in a window work with any number of rows, while special functions (ROW_NUMBER, RANK, LAG, LEAD) exist only in the window form. Window functions are part of the SQL standard and are supported in PostgreSQL, MySQL 8.0+, SQL Server and Oracle. MySQL before 8.0 has none.

Typical mistakes.

  • A window function in WHERE or HAVING: an error, a CTE or subquery is needed.
  • Mixing a window function with an ordinary column in a query with GROUP BY: window functions work over the already grouped result and ungrouped columns are unavailable.
  • Forgetting PARTITION BY: the window becomes the whole result and the sum is computed over the entire table.
  • Believing a window function "removes" duplicates: it deletes nothing.

Check yourself

The query SELECT dept, name, COUNT(*) FROM employees GROUP BY dept fails. How to get the department headcount next to each name?

Answer

The column name is neither in GROUP BY nor an aggregate, so the database refuses. A window function is needed: SELECT name, dept, COUNT(*) OVER (PARTITION BY dept) AS dept_size FROM employees.

Why can SUM(salary) OVER (PARTITION BY dept) not be placed in WHERE?

Answer

Window functions are computed after WHERE, so at the WHERE stage they do not exist yet. To filter by their value, wrap the query in a CTE or a subquery and add a WHERE outside.

In an interview. Junior: A window function computes a value over a group of rows but, unlike GROUP BY, does not collapse them: every row stays and gets an extra column. PARTITION BY sets the groups, ORDER BY the order inside. Middle/Senior: Window functions are computed after WHERE, GROUP BY and HAVING, so they can be written only in SELECT and ORDER BY, and filtering by them needs a CTE. If only totals are needed I use GROUP BY: simpler and faster. I use a window when the details must stay beside the aggregate, for example the difference from the department average. A repeated window goes into WINDOW.

More articles in this chapter