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.
OVER (...)is what makesSUMa window function. WithoutOVER,SUMis an ordinary aggregate function that folds rows.PARTITION BY departmentsplits the table into several windows, one per department. This is like the groups ofGROUP BY, but the rows are not folded.- An empty
OVER ()means one window for the whole table:SUM(salary) OVER ()gives 31,000 on every row.
What goes inside the parentheses of OVER can have three parts, and you may leave out any of them:
PARTITION BY: splits the rows into several windows.ORDER BY: the order of the rows inside each window.- a frame, such as
ROWS BETWEEN ...: which rows are counted.
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 |
ROW_NUMBER()numbers the rows 1, 2, 3 in each window. Its parentheses are empty, but you must write them.PARTITION BY departmentmakes the numbering start again at 1 in HR and in IT.ORDER BY salary DESCinsideOVERdecides who is number 1: the biggest salary.AS rankonly gives the result column the namerank.ORDER BY department ASC, rank ASCat the end of the query sorts the final result: HR before IT (alphabetical), then, within each department, number 1 first. That's why Dewi is in the first row.
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 |
ROW_NUMBERalways gives different numbers, even on a tie. Which of Andi and Joko gets 2 is not guaranteed. When it must be certain, add a second column toORDER BY, such asname.RANKgives a tie the same number, then skips: 2, 2, then straight to 4. The RANK number = 1 + the number of people with a bigger salary. Budi is below three people, so his number is 4.DENSE_RANKalso gives the same number, but doesn't skip: 2, 2, then 3.- Need exactly the top 3 per group, even when some tie? Use
ROW_NUMBER. WithRANKandDENSE_RANK, numbers 1 to 3 can belong to more than 3 rows. (NTILE(3)is something else: it splits the rows into 3 equal groups, it doesn't take the top 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 |
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWis the frame: which rows are added up. Here it means from the first row of the window (UNBOUNDED PRECEDING) down to the row being calculated (CURRENT ROW). That's why the last row of each window (11,500 and 19,500) equals itsGROUP BYtotal.- With
SUM, the frameROWS BETWEEN 1 PRECEDING AND CURRENT ROWonly adds the one row before and this row. This frame is used withAVGfor a moving average, the average of the last few rows. LAG(salary)fetchessalaryfrom the row before in the same window. The first row of each window has no row before it, so it getsNULL. Its opposite,LEAD, fetches the row after.LAG(salary) OVER (...) - salarygives the salary gap to the person in the row before: Andi earns 1,500 less than Siti.
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.
- In MySQL 8,
rank,dense_rankandrow_numberare reserved words (words SQL already uses for itself), soAS rankis refused. WriteAS `rank`or pick another name. SQLite and PostgreSQL acceptAS rank. - The error for
WHERE rn <= 2differs in each database: SQLitemisuse of aliased window function rn, PostgreSQLcolumn "rn" does not exist, MySQLUnknown column 'rn' in 'where clause'. - When
OVERhas anORDER BYbut no frame is written, the frame isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, the same in all three databases. RANGE counts rows with the same value together. For example, in the IT window with Joko in it,SUM(salary) OVER (ORDER BY salary DESC)gives Andi and Joko both 21,000 (the salaries of Siti, Andi and Joko). UseROWSto count row by row.
⚠️ A WHERE that comes too early, an ORDER BY in the wrong place
- Filtering a window function's result in
WHERE.WHERE rn <= 2in the same query is refused. Calculate it in a CTE first, then filter in the main query. - Forgetting
ORDER BYinsideOVER.RANK() OVER (PARTITION BY department)gives everyone number 1, because with no order they all tie.ROW_NUMBER()with noORDER BYstill numbers the rows, but in an order you can't predict. - Thinking
ORDER BYinsideOVERsorts the final result. ThatORDER BYonly orders the rows inside the window, to decide their numbers. In the exercise,ORDER BY department ASC, rank ASCis needed at the end of the query so Dewi is in the first row. - Typing the rank numbers yourself. In the exercise, the checker looks for
ROW_NUMBER(),RANK()orDENSE_RANK()followed byOVER (.
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.