…
…
SQL and Database Fundamentals · Lesson 41 / 41 · Window functions
PreviewIn this lesson you will
AVG(...) OVER (PARTITION BY ...)) and rank within the group (ROW_NUMBER, RANK, DENSE_RANK) next to each row without merging rows, and choose the right ranking function for tiesYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The dean's office at Northbridge University wants to reward the best student in each department and also see where each student stands against their own department's average. GROUP BY gives one row per department, so the students disappear. In this lesson you will keep every student's row and write the group information on the same row.
This is an advanced, optional lesson. With what you have learned so far, you can answer every report question somehow; window functions make some questions much shorter and easier to read. Everyone who writes reports uses them every day, so we still recommend learning them.
The result the dean's office wants is a seven-row table that shows each department's top student:
| department_id | student_no | first_name | last_name | gpa |
|---|---|---|---|---|
| 1 | 202501001 | Kenji | Park | 3.57 |
| 2 | 202502007 | Noor | García | 4 |
| 3 | 202303001 | Anika | Park | 3.65 |
| ... | ... | ... | ... | ... |
At the end of the lesson you will produce this table with one query.
In this lesson you will:
In lesson 12 you found department averages with GROUP BY. GROUP BY collapses the rows of one department into a single row; no students are left in the result, only departments. The dean's second question is "where is each student within their department's average?" For that, the student's row and the department's average must be on the same row.
A window function does exactly this: it runs an aggregate function without merging rows and writes the result next to each row as a new column. The word that makes a function a window function is OVER. The parentheses after OVER say which rows go into the calculation, that is, the row's window. PARTITION BY department_id means "split the rows into departments, and use only the rows of the row's own department in its calculation."
Example 1 (case): The same question, two ways. First the way you already know: the average for departments 1 and 2 with GROUP BY.
SELECT department_id, ROUND(AVG(gpa), 2) AS dept_avg FROM student WHERE department_id IN (1, 2) GROUP BY department_id ORDER BY department_id;
| department_id | dept_avg |
|---|---|
| 1 | 2.48 |
| 2 | 2.44 |
(2 rows)
Now calculate the same average with a window. GROUP BY is gone, and OVER (PARTITION BY department_id) comes after AVG. We also leave out students with an empty GPA with WHERE.
Department 1 has 8 students with a GPA and department 2 has 17. How many rows does the windowed query below return?
SELECT department_id, first_name, gpa, ROUND(AVG(gpa) OVER (PARTITION BY department_id), 2) AS dept_avg FROM student WHERE department_id IN (1, 2) AND gpa IS NOT NULL;
SELECT department_id, student_no, first_name, gpa, ROUND(AVG(gpa) OVER (PARTITION BY department_id), 2) AS dept_avg FROM student WHERE department_id IN (1, 2) AND gpa IS NOT NULL ORDER BY department_id, student_no;
| department_id | student_no | first_name | gpa | dept_avg |
|---|---|---|---|---|
| 1 | 202501001 | Kenji | 3.57 | 2.48 |
| 1 | 202501002 | Lucas | 1.92 | 2.48 |
| 1 | 202501003 | Omar | 2.59 | 2.48 |
| 1 | 202501004 | Ayesha | 2.74 | 2.48 |
| 1 | 202501005 | Diego | 2.95 | 2.48 |
(first 5 of 25 rows)
The averages are the same: 2.48 and 2.44. The difference is in the number of rows. Next to all eight students of department 1 you see 2.48, and next to all seventeen students of department 2 you see 2.44. The most common mistake is thinking that a window function also reduces rows like GROUP BY; it does not. A window only adds a column.
When the group information sits next to the row, you can calculate with both. If you subtract the department average from the student's GPA, you find how many points the student is above or below their department.
Example 2 (case): Difference from the department average. WHERE keeps only department 1, so OVER () is enough: empty parentheses mean "the window is all rows of the query," and here all rows are already department 1.
SELECT student_no, first_name, gpa, ROUND(AVG(gpa) OVER (), 2) AS dept_avg, ROUND(gpa - AVG(gpa) OVER (), 2) AS diff FROM student WHERE department_id = 1 AND gpa IS NOT NULL ORDER BY diff DESC LIMIT 5;
| student_no | first_name | gpa | dept_avg | diff |
|---|---|---|---|---|
| 202501001 | Kenji | 3.57 | 2.48 | 1.09 |
| 202501007 | Liam | 3.24 | 2.48 | 0.76 |
| 202501005 | Diego | 2.95 | 2.48 | 0.47 |
| 202501004 | Ayesha | 2.74 | 2.48 | 0.26 |
| 202501003 | Omar | 2.59 | 2.48 | 0.11 |
(5 rows)
Kenji is 1.09 points above the department average. A window result enters calculations like any other column, and you can use it in ORDER BY too. A negative difference only means "below the department average"; it does not say the student failed. Try the two departments together below.
Try it now· not graded; doesn't affect progress
With PARTITION BY, the first rows come from department 2: Noor 1.56, Camila 1.44, Pablo 1.33, then Kenji 1.09. Each student is compared with their own department. Without PARTITION BY, the two departments become one window and everyone is compared with the shared average of both departments; that is not what the dean's office wants.
The dean's real question is "who is first?" For that, each student needs a rank number. Ranking functions take nothing inside their parentheses; they get the order from the ORDER BY inside OVER: RANK() OVER (ORDER BY gpa DESC). The three functions differ only when there is a tie. Think of a running race: if two runners finish in the same time, both are first. But is the next runner second or third?
ROW_NUMBER() gives every row a different number: 1, 2, 3, 4. It ignores ties.RANK() gives ties the same rank, then skips as many numbers as there were tied rows: 1, 1, 3.DENSE_RANK() gives ties the same rank but does not skip: 1, 1, 2.Two students are first with a 4.00 GPA. What rank does RANK() give the next student?
Example 3 (case): Three functions side by side.
SELECT student_no, first_name, gpa, ROW_NUMBER() OVER (ORDER BY gpa DESC, student_no) AS row_num, RANK() OVER (ORDER BY gpa DESC) AS rank, DENSE_RANK() OVER (ORDER BY gpa DESC) AS dense FROM student WHERE gpa IS NOT NULL ORDER BY row_num LIMIT 6;
| student_no | first_name | gpa | row_num | rank | dense |
|---|---|---|---|---|---|
| 202407009 | Omar | 4 | 1 | 1 | 1 |
| 202502007 | Noor | 4 | 2 | 1 | 1 |
| 202302001 | Camila | 3.88 | 3 | 3 | 2 |
| 202405001 | Anika | 3.88 | 4 | 3 | 2 |
| 202304004 | Zara | 3.85 | 5 | 5 | 3 |
| 202504004 | Kenji |
(6 rows)
The OVER of ROW_NUMBER has a second sort column: student_no. Omar and Noor have the same GPA; without the second column, ROW_NUMBER would choose by itself who gets 1, and the result might not be the same on every run. The second column breaks the tie and makes the result stable. Notice also that you can use more than one window function in the same query; each has its own OVER.
Four students have GPAs of 4.00 · 4.00 · 3.80 · 3.50. Which numbers does each function give?
For each row, pick its match from the list, then check.
ROW_NUMBER()RANK()DENSE_RANK()When you write PARTITION BY and ORDER BY together inside OVER, the rank number starts again from 1 in each department: RANK() OVER (PARTITION BY department_id ORDER BY gpa DESC). PARTITION BY comes first, then ORDER BY.
Here the NULL rule from lesson 7 comes back: when sorting from largest to smallest (DESC), PostgreSQL puts NULL values first. Students with an empty GPA, that is, new students who started this term, appear as first in the ranking.
Example 4 (case): Who is first?
SELECT first_name, student_no, gpa, RANK() OVER (PARTITION BY department_id ORDER BY gpa DESC) AS place FROM student WHERE department_id = 1 ORDER BY place, student_no LIMIT 8;
| first_name | student_no | gpa | place |
|---|---|---|---|
| Adaeze | 202601001 | NULL | 1 |
| Mina | 202601002 | NULL | 1 |
| Kenji | 202601003 | NULL | 1 |
| Liam | 202601004 | NULL | 1 |
| Jin | 202601005 | NULL | 1 |
| Greta | 202601006 | NULL | 1 |
| Kenji | 202501001 | 3.57 | 7 |
| Liam | 202501007 | 3.24 | 8 |
(8 rows)
The six students with an empty GPA are counted as "tied" and became first; the real first, Kenji, appears seventh. There are two fixes: either remove the empty ones first with WHERE gpa IS NOT NULL, or write ORDER BY gpa DESC NULLS LAST inside OVER. NULLS LAST does not work if you add it to the ORDER BY at the end of the query, because the rank number is given inside OVER. In the cell below, see the effect of NULLS LAST yourself.
Try it now· not graded; doesn't affect progress
With NULLS LAST, department 1 starts with Kenji (3.57), and the students with an empty GPA drop to rank 9. When you delete it, the first six rows are again the students with an empty GPA.
Now every student has a rank within their department. To get the top students, the first idea is to add WHERE place = 1.
What does this query do?
SELECT department_id, first_name, gpa, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY gpa DESC) AS place FROM student WHERE place = 1;
PostgreSQL's message:
OutputERROR: column "place" does not existWriting the function itself in WHERE instead of the alias does not work either; a window function cannot be used in WHERE at all. The fix is the CTE from lesson 23. The job is split into two steps: the CTE writes a rank number for each student, and the outer query looks at this ready column and cuts the list. For the outer query, place is now an ordinary column.
Example 5 (case): Department top students.
WITH s AS ( SELECT department_id, student_no, first_name, last_name, gpa, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY gpa DESC, student_no) AS place FROM student WHERE gpa IS NOT NULL ) SELECT department_id, student_no, first_name, last_name, gpa FROM s WHERE place = 1 ORDER BY department_id;
| department_id | student_no | first_name | last_name | gpa |
|---|---|---|---|---|
| 1 | 202501001 | Kenji | Park | 3.57 |
| 2 | 202502007 | Noor | García | 4 |
| 3 | 202303001 | Anika | Park | 3.65 |
| 4 | 202304004 | Zara | Larsen | 3.85 |
| 5 | 202405001 | Anika | Rivera | 3.88 |
| 6 | 202406004 | Ethan | Bianchi | 3.69 |
| 7 | 202407009 |
(7 rows)
This is the table from the start of the lesson. ROW_NUMBER was chosen here because exactly one person is wanted from each department; when there is a tie, the one with the smaller number is chosen. If the dean's office said "everyone who ties should get the award," you would write RANK() and take the ties together with WHERE place = 1. The pattern for "top N in each group" is always the same: a rank number in the CTE, WHERE place <= N outside. Put the lines in the right order.
Put the lines of the query that finds each department's top student in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Two more uses of window functions are common in reports; you only need to recognize them, and there are no exercises for them. NTILE(4) OVER (ORDER BY gpa DESC) splits the rows into four equal groups by order and gives each row a group number from 1 to 4. The 88 students with a GPA are split into four groups of 22; the first group is between 3.10 and 4.00. The second use is a percentage share in a grouped query: SUM(COUNT(*)) OVER () adds up the counts of all groups, so each department's share is found in one query. The query and result of both are in the Examples section below.
Ranking functions are useful in any score table. In a school league, four teams have points; we build the table inside the query with VALUES.
Example 6 (outside the case): School league.
SELECT team, points, RANK() OVER (ORDER BY points DESC) AS rank, DENSE_RANK() OVER (ORDER BY points DESC) AS dense FROM (VALUES ('Falcons', 13), ('Gulls', 13), ('Hawks', 10), ('Kestrels', 7)) AS league(team, points) ORDER BY points DESC, team;
| team | points | rank | dense |
|---|---|---|---|
| Falcons | 13 | 1 | 1 |
| Gulls | 13 | 1 | 1 |
| Hawks | 10 | 3 | 2 |
| Kestrels | 7 | 4 | 3 |
(4 rows)
The rule, not the data, decides which function is correct. The same table gives two different rankings under two different regulations.
League regulation: teams with equal points share the same rank, and the next rank is skipped. Which function gives Hawks' rank correctly?
In the next lesson you will use the same OVER structure to look at the previous and next row and to calculate running totals.
To see how many students are in each group and the lowest and highest GPA of the group, the group number is written in the CTE and grouped outside.
WITH d AS ( SELECT gpa, NTILE(4) OVER (ORDER BY gpa DESC) AS quarter FROM student WHERE gpa IS NOT NULL ) SELECT quarter, COUNT(*) AS students, MIN(gpa) AS lowest, MAX(gpa) AS highest FROM d GROUP BY quarter ORDER BY quarter;
| quarter | students | lowest | highest |
|---|---|---|---|
| 1 | 22 | 3.1 | 4 |
| 2 | 22 |
Filtering a window result in WHERE of the same query.
OutputSELECT department_id, first_name, gpa,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY gpa DESC) AS place
FROM student
WHERE place = 1;
-- ERROR: column "place" does not existWindow functions are calculated after WHERE; when WHERE runs, place does not exist, and the function itself cannot be written in WHERE either. Calculate the rank in a CTE and do the filtering in the outer query. Do not forget NULLs, too: in a DESC sort, empty values come first; remove them with WHERE before giving a rank number, or write NULLS LAST inside OVER.
AVG(gpa) OVER (PARTITION BY department_id). The number of rows does not change; OVER () looks at all rows.DESC sort, NULLs come first.WHERE place <= N.Next lesson: With LAG, LEAD and running totals, you will compare each row with the one before it and calculate cumulative totals.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| 6 |
| 6 |
| 4 |
| Kim |
| 4 |
| 3.08 |
| 3 | 22 | 1.83 | 2.5 |
| 4 | 22 | 0.14 | 1.75 |
(4 rows)
COUNT(*) is the number of students in each department; SUM(COUNT(*)) OVER () adds these seven numbers (120). Because the window is calculated after GROUP BY is finished, it works on the grouped rows.
SELECT department_id, COUNT(*) AS students, ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct FROM student GROUP BY department_id ORDER BY department_id;
| department_id | students | pct |
|---|---|---|
| 1 | 14 | 11.7 |
| 2 | 20 | 16.7 |
| 3 | 12 | 10 |
| 4 | 24 | 20 |
| 5 | 17 | 14.2 |
| 6 | 10 | 8.3 |
| 7 | 23 | 19.2 |
(7 rows)