…
…
SQL and Database Fundamentals · Lesson 42 / 41 · Window functions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Course enrollment for 2026-Fall lasted six days, and 310 enrollments were made in that time. The registrar's office wants one table that shows how many enrollments came in each day, how much that is up or down from the day before, and how many have piled up so far. They are also curious how the grades of students who retook a course changed compared with their earlier attempt.
Like the previous lesson, this one is advanced and optional: you can move on to the next lesson even if you do not pass its quiz. But it solves a question you will meet in any data that changes over time (daily sales, monthly spending, term enrollments): "What changed compared with the one before?"
In lesson 41 you used window functions to put a group value or a rank number next to each row without merging the rows. Here you will use the same OVER (... ORDER BY ...) structure, but this time you will compare a row with its neighbor. At the end of the lesson, the table the registrar's office asked for will look like this:
| day | enrollments | previous | change | running |
|---|---|---|---|---|
| 2026-09-15 | 44 | NULL | NULL | 44 |
| 2026-09-16 | 49 | 44 | 5 | 93 |
| 2026-09-17 | 54 | 49 | 5 | 147 |
| 2026-09-18 | 54 | 54 | 0 | 201 |
| 2026-09-19 | 50 | 54 | -4 | 251 |
| 2026-09-20 | 59 | 50 | 9 | 310 |
In this lesson you will:
To find the daily change, each row needs two numbers: that day's enrollments and the previous day's enrollments. But in SQL each row is processed on its own, and a row normally cannot see its neighbor's value. LAG(column) solves this: it brings the value of the previous row in the window to the current row. LEAD(column) does the opposite and brings the value of the next row.
The words "previous" and "next" have nothing to do with the order of the table on disk. The ORDER BY inside OVER decides the order. LAG(enrollments) OVER (ORDER BY day) means "the previous row when sorted by day". First we group the daily enrollment counts in a CTE (lesson 23), then we compare them in the outer query.
Example 1 (case): Previous day, change and next day
WITH g AS ( SELECT e.enrolled_on AS day, COUNT(*) AS enrollments FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 3 GROUP BY e.enrolled_on ) SELECT day, enrollments, LAG(enrollments) OVER (ORDER BY day) AS previous, enrollments - LAG(enrollments) OVER (ORDER BY day) AS change, LEAD(enrollments, 1, 0) OVER (ORDER BY day) AS next FROM g ORDER BY day;
| day | enrollments | previous | change | next |
|---|---|---|---|---|
| 2026-09-15 | 44 | NULL | NULL | 49 |
| 2026-09-16 | 49 | 44 | 5 | 54 |
| 2026-09-17 | 54 | 49 | 5 | 54 |
| 2026-09-18 | 54 | 54 | 0 | 50 |
| 2026-09-19 | 50 | 54 | -4 | 59 |
| 2026-09-20 | 59 | 50 | 9 | 0 |
Look at the second row: previous is 44, the value for September 15. The change is 49 - 44 = 5. On September 19 the change is -4: enrollments dropped compared with the day before. LEAD(enrollments, 1, 0) takes three arguments: which column, how many rows ahead, and what to write if there is no such row. There is no day after the last day, so next became 0 there. The same three arguments work for LAG too; LAG(enrollments, 2) looks two days back.
Pay attention to the NULLs in the first row. Think about it before moving on:
Why is the change value of the first day (September 15) NULL, and not 0 or 44?
Two common misunderstandings come up here. The first is "the change of the first row is 0". It is not; it is NULL, because there is nothing to compare with. The second is "LAG brings the row above in the table". If you sort by the count instead of the day, for example ORDER BY enrollments, LAG does not bring "the previous day"; it brings "the next smaller enrollment count", and the result becomes meaningless without any error.
A difference alone can be misleading. An increase of 5 enrollments is big on a day with 40 and small on a day with 400. Percent change divides the difference by the previous value: 100.0 * (new - old) / old. Remember from lesson 25: dividing an integer by an integer drops the decimals, so we start with 100.0.
Example 2 (case): Enrollments from term to term
WITH t AS ( SELECT o.term_id, tm.name AS term, COUNT(*) AS enrollments FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN term tm ON tm.id = o.term_id GROUP BY o.term_id, tm.name ) SELECT term, enrollments, enrollments - LAG(enrollments) OVER (ORDER BY term_id) AS change, ROUND(100.0 * (enrollments - LAG(enrollments) OVER (ORDER BY term_id)) / LAG(enrollments) OVER (ORDER BY term_id), 1) AS pct FROM t ORDER BY term_id;
| term | enrollments | change | pct |
|---|---|---|---|
| 2025-Fall | 233 | NULL | NULL |
| 2026-Spring | 238 | 5 | 2.1 |
| 2026-Fall | 310 | 72 | 30.3 |
In 2026-Spring the increase is only 5 enrollments, which is 2.1%. In 2026-Fall it is 72 enrollments, which is 30.3%. We sorted by term_id, not by term name: sorted by name, "2026-Fall" would come before "2026-Spring" (F comes before S), which is the wrong order in time. The column that carries the order is the id. Try it yourself: change two things in the cell. Write the difference against the next term (LEAD(enrollments) OVER (ORDER BY term_id) - enrollments), and round the percent to 0 digits instead of 1. Which row did the NULL move to this time?
Try it now· not graded; doesn't affect progress
A percent change is as important for what it does not say as for what it says. 30.3% says that the number of enrollments grew; by itself it does not say that the number of students or the number of offered sections grew. The same students may simply have signed up for more courses.
Aggregate functions also work as window functions; you saw this in lesson 41 with AVG(...) OVER (PARTITION BY ...). What is new: when you write an ORDER BY inside OVER, the calculation uses the rows from the start of the window up to the current row. SUM(enrollments) OVER (ORDER BY day) writes the enrollments accumulated up to that day on each day. This is called a running (cumulative) total. Think of a piggy bank: each day you note the money you put in and the total collected so far; the second column is the running total.
So what happens if you do not write ORDER BY? Predict:
On the daily enrollment CTE, what does SUM(enrollments) OVER () write in each row?
Example 3 (case): Running total, grand total and 3-day average
WITH g AS ( SELECT e.enrolled_on AS day, COUNT(*) AS enrollments FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 3 GROUP BY e.enrolled_on ) SELECT day, enrollments, SUM(enrollments) OVER (ORDER BY day) AS running, SUM(enrollments) OVER () AS total, ROUND(AVG(enrollments) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3day FROM g ORDER BY day;
| day | enrollments | running | total | avg_3day |
|---|---|---|---|---|
| 2026-09-15 | 44 | 44 | 310 | 44 |
| 2026-09-16 | 49 | 93 | 310 | 46.5 |
| 2026-09-17 | 54 | 147 | 310 | 49 |
| 2026-09-18 | 54 | 201 | 310 | 52.3 |
| 2026-09-19 | 50 | 251 | 310 | 52.7 |
| 2026-09-20 | 59 | 310 | 310 | 54.3 |
The running column climbs from 44 to 310; the running total in the last row equals the grand total, as it should. The total column is 310 in every row. The only difference between the two columns is the ORDER BY day inside OVER.
A running total looks from the start of the window. Sometimes only the last few rows matter, such as "the average of the last three days". The frame decides which rows take part in the calculation. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means "from two rows before up to this row". Imagine a sliding window: a narrow glass slides over a long list and shows only three rows, and at each step you take the average of the three numbers under the glass.
The avg_3day column in Example 3 was calculated this way. On September 18, the average of 54, 54 and 49 is 52.3. On the first two days there are not two days before them, so the frame uses the rows it has: on the first day it is only 44, on the second day it is the average of 44 and 49, which is 46.5. If you want "the last 7 days", you write 6 PRECEDING, because the day itself is also in the frame.
ROWS counts rows. RANGE, which applies when you do not write one, treats rows with equal ORDER BY values together; if several rows share the same date, the running total writes the same value in all of them. Because the daily enrollment data has one row per day, both give the same result.
Match each SUM(enrollments) window on the daily enrollment CTE with its result.
For each row, pick its match from the list, then check.
OVER ()OVER (ORDER BY day)OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)OVER (PARTITION BY course_id ORDER BY day)Now the second question of the case: did the grades of students who retook a course change? Student 17 took BUS301 from the Business Administration department twice.
Example 4 (case): The midterm of the previous attempt
SELECT tm.name AS term, c.code, e.midterm, LAG(e.midterm) OVER (PARTITION BY c.code ORDER BY o.term_id) AS previous_midterm FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id JOIN term tm ON tm.id = o.term_id WHERE e.student_id = 17 AND c.code = 'BUS301' ORDER BY o.term_id;
| term | code | midterm | previous_midterm |
|---|---|---|---|
| 2025-Fall | BUS301 | 76 | NULL |
| 2026-Fall | BUS301 | 94 | 76 |
The midterm went from 76 to 94. This query works correctly because the WHERE left only one student. But if you remove the student condition from WHERE to see everyone who retook the course, what happens? Then the window holds all students who took BUS301, and LAG can bring the midterm of another student who is ahead in the row order. The idea "even if I do not write PARTITION BY, LAG will not look at another student" is wrong: LAG only looks at the window, and you define the window. Try it in the cell: first delete the e.student_id = 17 AND part and run it, then write PARTITION BY e.student_id, c.code instead of PARTITION BY c.code and set the order to ORDER BY e.student_id, o.term_id. In each student's first row previous_midterm goes back to NULL; the values no longer get mixed up.
Try it now· not graded; doesn't affect progress
Most queries in this lesson follow the same two-step pattern. First you reduce the raw rows (single enrollments) to the unit you want (day, month, term) with GROUP BY. Then you compare the rows of that summary with LAG or SUM OVER. Window functions are calculated after GROUP BY, so you can also write both in one query, but a CTE makes each step easier to read and check on its own.
The cell below applies the same pattern to the dates when students enrolled at the university. DATE_TRUNC('month', ...) (lesson 27) reduces each date to the first day of its month; you get a series of 8 months, and the running total in the last row is 120, which is all the students. Run it, then write 'year' instead of 'month' and look at the yearly series.
Try it now· not graded; doesn't affect progress
Put the lines of the query that finds the daily enrollment change in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
LAG and LEAD look at a neighbor. Sometimes you want to compare each row with the value at the start of the series. FIRST_VALUE(column) writes the value of the first row in the window into every row. In offering 47, the GEN101 section of 2025-Fall, FIRST_VALUE(final_exam) OVER (ORDER BY final_exam DESC) writes the highest final of the section (100) next to each student; 100 - final_exam gives everyone's distance from the top: a student with 99 is 1 point behind. Its twin LAST_VALUE often does not give the expected result, because the default frame only looks up to the current row; if you need the largest value of the series, MAX(final_exam) OVER () is simpler.
These tools are useful on any ordered data. A student has written down their spending for four months; they want to see each month's difference from the one before and the total since the beginning of the year. We build the table inside the query with VALUES (the no column carries the order of the months).
Example 5 (outside the case): Monthly spending
SELECT month, amount, amount - LAG(amount) OVER (ORDER BY no) AS change, SUM(amount) OVER (ORDER BY no) AS cumulative FROM (VALUES (1, 'January', 1200), (2, 'February', 950), (3, 'March', 1400), (4, 'April', 1100)) AS h(no, month, amount) ORDER BY no;
| month | amount | change | cumulative |
|---|---|---|---|
| January | 1200 | NULL | 1200 |
| February | 950 | -250 | 2150 |
| March | 1400 | 450 | 3550 |
| April | 1100 | -300 | 4650 |
Spending dropped by $250 in February and rose by $450 in March; the total for the four months is $4,650.
The change value in the March row is 450. What does this number say?
Notice that the query takes the order from the no column, not from the month name. If you had sorted by month name, the alphabetical order would be April, February, January, March, and all the differences would become meaningless.
The goal table from the start of the lesson: previous day, change and running total in one query.
WITH g AS ( SELECT e.enrolled_on AS day, COUNT(*) AS enrollments FROM enrollment e JOIN course_offering o ON o.id = e.offering_id WHERE o.term_id = 3 GROUP BY e.enrolled_on ) SELECT day, enrollments, LAG(enrollments) OVER (ORDER BY day) AS previous, enrollments - LAG(enrollments) OVER (ORDER BY day) AS change, SUM(enrollments) OVER (ORDER BY day) AS running FROM g ORDER BY day;
| day | enrollments | previous | change | running |
|---|---|---|---|---|
Forgetting to write ORDER BY inside OVER for a running total. SUM(enrollments) OVER () writes the grand total (310) on every day, and since it gives no error, it may go unnoticed. The correct form is SUM(enrollments) OVER (ORDER BY day): 44, 93, 147, 201, 251, 310. The same care applies to LAG and LEAD: "previous row" only has meaning when the ORDER BY inside OVER sorts the right column (day, term, month number); and if each person has a separate series, PARTITION BY is needed too.
LAG brings the value of the previous row and LEAD the value of the next row; the ORDER BY inside OVER decides the order, and when there is no row to compare with, you get NULL (or the default in the third argument); the change is enrollments - LAG(enrollments), and the percent change is 100.0 * (enrollments - LAG(enrollments)) / LAG(enrollments).SUM(...) OVER (ORDER BY ...) gives a running total; without ORDER BY, the grand total is written in every row; ROWS BETWEEN n PRECEDING AND CURRENT ROW narrows the frame, and this is how you find a moving average.Next lesson: You will bring together everything you have learned and build a small database from scratch: its tables, constraints and data.
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.
| 44 |
| NULL |
| NULL |
| 44 |
| 2026-09-16 | 49 | 44 | 5 | 93 |
| 2026-09-17 | 54 | 49 | 5 | 147 |
| 2026-09-18 | 54 | 54 | 0 | 201 |
| 2026-09-19 | 50 | 54 | -4 | 251 |
| 2026-09-20 | 59 | 50 | 9 | 310 |
Each student has their own series (PARTITION BY e.student_id); first attempts, which have no previous midterm, are removed in the outer query. Because a window result cannot be used in the WHERE of the same query (lesson 41), LAG is calculated in a CTE.
WITH t AS ( SELECT e.student_id, o.term_id, e.midterm, LAG(e.midterm) OVER (PARTITION BY e.student_id ORDER BY o.term_id) AS previous_midterm FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id WHERE c.code = 'BUS301' ) SELECT student_id, previous_midterm, midterm, midterm - previous_midterm AS change FROM t WHERE previous_midterm IS NOT NULL ORDER BY change DESC, student_id;
| student_id | previous_midterm | midterm | change |
|---|---|---|---|
| 34 | 40 | 91 | 51 |
| 52 | 49 | 76 | 27 |
| 65 | 70 | 90 | 20 |
| 17 | 76 | 94 | 18 |
| 64 | 92 | 100 | 8 |
| 89 | 74 | 76 | 2 |
| 32 | 76 | 72 | -4 |
| 113 | 55 | 45 | -10 |
| 36 | 72 | 61 | -11 |
Of the 9 students who retook the course, 6 raised their midterm and 3 lowered it.