Window Functions — SQL

A window function calculates something from a group of rows (the window) without folding the rows, so they are not merged into one row per group. Its shape is…

Open a school report: on your row there's your mark, and next to it a "rank in class" column. To fill that column, the homeroom teacher looks at the marks of every student in the same class. But your report is still yours alone: your classmates' marks aren't merged into one row.

A window function works the same way. It calculates something from a group of rows, but every row still comes out, with the result in a column next to it. That group of rows is called the window. On the report, each student is one row, the class is the window, and the rank in class is the window function's result.

GROUP BY folds, a window doesn't

The data is the exercise's employees table, with the columns id, name, department and salary. It holds 5 employees: Budi (IT, 5,000), Siti (IT, 8,000), Andi (IT, 6,500), Dewi (HR, 7,000), and Rizky (HR, 4,500).

In the GROUP BY lesson you added up per group. SELECT department, SUM(salary) AS total FROM employees GROUP BY department; gives 2 rows: HR 11,500 and IT 19,500. Five rows fold (are merged per department) into two, and the employees' names are gone. Now the window function version. Before you look at the result, guess: how many rows come out?

SELECT name, department, salary,
       SUM(salary) OVER (PARTITION BY department) AS total
FROM employees;
name department salary total
Dewi HR 7,000 11,500
Rizky HR 4,500 11,500
Budi IT 5,000 19,500
Siti IT 8,000 19,500
Andi IT 6,500 19,500

Five rows stay five: every employee is still there, with their department's total in the next column.

What goes inside the parentheses of OVER can have three parts, and you may leave out any of them:

Ranking: ROW_NUMBER, RANK, DENSE_RANK

This is the query from the exercise: it numbers the salaries within each department, with the highest salary as number 1.

SELECT name, department, salary,
       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees
ORDER BY department ASC, rank ASC;
name department salary rank
Dewi HR 7,000 1
Rizky HR 4,500 2
Siti IT 8,000 1
Andi IT 6,500 2
Budi IT 5,000 3

There are three ranking functions (functions that give a rank): ROW_NUMBER, RANK and DENSE_RANK. They only differ when there is a tie (the same value). Say Joko joins IT with a salary of 6,500, the same as Andi. This is SQLite's result for all three in the IT window, with ORDER BY salary DESC inside OVER:

name salary ROW_NUMBER RANK DENSE_RANK
Siti 8,000 1 1 1
Andi 6,500 2 2 2
Joko 6,500 3 2 2
Budi 5,000 4 4 3

Running total and LAG

The balance column on a bank statement is a running total: the sum of all the money in and out, from the first row down to that row. The query below calculates a running total of the salaries in each department. It also uses LAG, which fetches a value from the row before, like when you compare today's revenue with yesterday's.

SELECT name, department, salary,
       SUM(salary) OVER (
         PARTITION BY department
         ORDER BY salary DESC
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total,
       LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS prev_salary
FROM employees
ORDER BY department, salary DESC;
name department salary running_total prev_salary
Dewi HR 7,000 7,000 NULL
Rizky HR 4,500 11,500 7,000
Siti IT 8,000 8,000 NULL
Andi IT 6,500 14,500 8,000
Budi IT 5,000 19,500 6,500

Top N per group: window + CTE

Want the 2 highest salaries in each department (the top N, with N = 2)? Number the rows with ROW_NUMBER() in a column rn, then keep the rows where rn <= 2. But you can't write WHERE rn <= 2 in the same query, because the database runs WHERE before it calculates the columns of SELECT. When WHERE runs, the number rn doesn't exist yet. Calculate the numbers in a CTE first (the named query from the previous lesson), then filter in the main query:

WITH ranked AS (
  SELECT name, department, salary,
         ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
  FROM employees
)
SELECT * FROM ranked WHERE rn <= 2;

The result is 4 rows: Dewi and Rizky from HR, Siti and Andi from IT. The same pattern can also remove duplicates, in a table with the columns email and created_at (when the row was made). Swap PARTITION BY department for PARTITION BY email, and ORDER BY salary DESC for ORDER BY created_at DESC. Then keep only the rows with rn = 1: the newest row for each email.

📌 SQLite, PostgreSQL and MySQL differ

The exercise and the Lab here use SQLite. Window functions are in SQLite 3.25 and up, PostgreSQL, and MySQL 8.0 and up. MySQL 5.7 doesn't have them.

⚠️ A WHERE that comes too early, an ORDER BY in the wrong place

TL;DR: A window function calculates something from a group of rows (the window) without folding the rows, so they are not merged into one row per group. Its shape is function() OVER (PARTITION BY ... ORDER BY ... frame): PARTITION BY splits the rows into windows, ORDER BY orders the rows inside a window, and the frame picks which rows are counted. GROUP BY gives 1 row per group, while SUM(...) OVER (PARTITION BY ...) gives every row, each with its group's total. ROW_NUMBER gives row numbers that are always different (right for top N, the first N per group). RANK gives a tie (equal values) the same number and then skips (2, 2, 4), and DENSE_RANK doesn't skip (2, 2, 3). SUM(...) OVER (ORDER BY ... ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) is a running total (the sum from the first row down to this one), and LAG fetches a value from the row before. A window function's result can't be filtered in the same query's WHERE: calculate it in a CTE first.

⚡ Count without folding

Write:

SELECT name, department, salary,
       SUM(salary) OVER (PARTITION BY department) AS total
FROM employees;

Meaning: The employees table holds 5 employees in two departments, HR and IT. OVER turns SUM into a window function: a function that calculates from a group of rows (the window) without merging the rows. PARTITION BY department makes one window per department. So five rows stay five, and each employee gets their department's total in the next column. GROUP BY would fold them into two rows.

⚡ A row number per department

Write:

SELECT name, department, salary,
       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees
ORDER BY department ASC, rank ASC;

Meaning: ROW_NUMBER() numbers the rows 1, 2, 3 in each window. PARTITION BY starts the numbering again from 1 in each department, and ORDER BY salary DESC inside OVER makes the highest salary number 1. The ORDER BY at the end of the query sorts the final result.

⚡ When there's a tie

Guess first: besides ROW_NUMBER(), there are RANK() and DENSE_RANK(), which give tied values the same number. You need exactly the top 3 products per category, even when some values tie. Which ranking function?

ROW_NUMBER(). It always gives different numbers. RANK and DENSE_RANK give ties the same number, so you could get more than 3 rows.

Meaning: RANK skips after a tie (2, 2, 4), while DENSE_RANK doesn't skip (2, 2, 3).

⚡ Filter through a CTE

Meaning: To get the 2 highest salaries per department, you filter on their row numbers, for example a column rn from ROW_NUMBER(). But WHERE rn <= 2 in the same query is refused, because WHERE runs before the columns in SELECT are calculated. Calculate the numbers in a CTE first (a named query in WITH), then filter in the main query.

What you will learn