🗄️ SQL for beginners · Class 12 · Lesson 16 of 18 · Free
SQL Window Functions – ROW_NUMBER, RANK, Running Totals and PARTITION BY
⏱ About 40 minutes · ▶ run real SQL here — nothing to install · no sign-in
In this lesson you will
- Add a calculation across rows with OVER () without losing any rows
- Rank rows with ROW_NUMBER, RANK and DENSE_RANK, also per group with PARTITION BY
- Build running totals and compare with the previous row using LAG
The class teacher wants each student's marks AND the class average on the same line. Then a rank list where two toppers with equal marks share first place. Then a cricket score that grows over by over. GROUP BY from Lesson 8 squeezes rows into one, so it cannot do this. Window functions can.
What is a window function in SQL?
A window function calculates over a group of rows, but keeps every row. You add OVER (…) after it. The "window" is the set of rows it looks at.
AVG(marks) OVER () means: the average over all rows of the result, written next to each row. With GROUP BY you would get one row for the whole class instead.
Try it: change subject_id = 1 to subject_id = 4 to see Computer Science, and run again.
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons) CREATE TABLE students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, class INTEGER NOT NULL, section TEXT NOT NULL, city TEXT, joined TEXT NOT NULL ); INSERT INTO students VALUES (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'), (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'), (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'), (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'), (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'), (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'), (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'), (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12'); CREATE TABLE subjects ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE ); INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English'); CREATE TABLE teachers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, subject_id INTEGER REFERENCES subjects(id) ); INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL); CREATE TABLE marks ( student_id INTEGER NOT NULL REFERENCES students(id), subject_id INTEGER NOT NULL REFERENCES subjects(id), marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100), PRIMARY KEY (student_id, subject_id) ); INSERT INTO marks VALUES (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84), (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90), (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88), (4,1,64),(4,2,58),(4,4,88),(4,5,71), (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86), (6,1,55),(6,2,62),(6,3,49),(6,5,67), (7,1,73),(7,4,99),(7,5,80); CREATE TABLE fees ( student_id INTEGER NOT NULL REFERENCES students(id), month TEXT NOT NULL, amount INTEGER NOT NULL, paid INTEGER NOT NULL DEFAULT 0 ); INSERT INTO fees VALUES (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0), (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1), (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
┌─────────────┬───────┬───────────┬────────────┐ │ name │ marks │ class_avg │ difference │ ├─────────────┼───────┼───────────┼────────────┤ │ Meera Iyer │ 95 │ 76.4 │ 18.6 │ │ Riya Sharma │ 92 │ 76.4 │ 15.6 │ │ Sara Khan │ 81 │ 76.4 │ 4.6 │ │ Aman Verma │ 75 │ 76.4 │ -1.4 │ │ Anaya Joshi │ 73 │ 76.4 │ -3.4 │ │ Dev Patil │ 64 │ 76.4 │ -12.4 │ │ Kabir Singh │ 55 │ 76.4 │ -21.4 │ └─────────────┴───────┴───────────┴────────────┘ (7 rows)
What is the difference between ROW_NUMBER, RANK and DENSE_RANK in SQL?
All three number rows in the order given by OVER (ORDER BY …). They differ only when there is a tie.
ROW_NUMBER gives 1, 2, 3, 4 even to equal scores. RANK gives equal scores the same rank and then skips: 1, 1, 3. DENSE_RANK gives the same rank without skipping: 1, 1, 2. Sports tables usually use RANK.
Try it: change DESC to ASC in all three OVER parts and run again.
📋 Tables in this example: quiz — tap to see how they are made
CREATE TABLE quiz (
name TEXT NOT NULL,
score INTEGER NOT NULL
);
INSERT INTO quiz VALUES
('Riya', 18), ('Aman', 20), ('Sara', 18), ('Dev', 15), ('Meera', 20), ('Kabir', 12);┌───────┬───────┬─────────┬─────────┬──────────┐ │ name │ score │ row_num │ rank_no │ dense_no │ ├───────┼───────┼─────────┼─────────┼──────────┤ │ Aman │ 20 │ 1 │ 1 │ 1 │ │ Meera │ 20 │ 2 │ 1 │ 1 │ │ Riya │ 18 │ 3 │ 3 │ 2 │ │ Sara │ 18 │ 4 │ 3 │ 2 │ │ Dev │ 15 │ 5 │ 5 │ 3 │ │ Kabir │ 12 │ 6 │ 6 │ 4 │ └───────┴───────┴─────────┴─────────┴──────────┘ (6 rows)
How does PARTITION BY work in SQL?
PARTITION BY splits the rows into groups and restarts the window for each group. It is like GROUP BY, but no rows disappear.
Here RANK restarts for every subject, so you get a rank list per subject. You cannot use a window function in WHERE, so the outer query (a subquery from Lesson 9) keeps only pos = 1: the topper of each subject.
Try it: change pos = 1 to pos <= 2 and run again to see the top two.
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons) CREATE TABLE students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, class INTEGER NOT NULL, section TEXT NOT NULL, city TEXT, joined TEXT NOT NULL ); INSERT INTO students VALUES (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'), (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'), (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'), (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'), (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'), (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'), (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'), (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12'); CREATE TABLE subjects ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE ); INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English'); CREATE TABLE teachers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, subject_id INTEGER REFERENCES subjects(id) ); INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL); CREATE TABLE marks ( student_id INTEGER NOT NULL REFERENCES students(id), subject_id INTEGER NOT NULL REFERENCES subjects(id), marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100), PRIMARY KEY (student_id, subject_id) ); INSERT INTO marks VALUES (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84), (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90), (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88), (4,1,64),(4,2,58),(4,4,88),(4,5,71), (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86), (6,1,55),(6,2,62),(6,3,49),(6,5,67), (7,1,73),(7,4,99),(7,5,80); CREATE TABLE fees ( student_id INTEGER NOT NULL REFERENCES students(id), month TEXT NOT NULL, amount INTEGER NOT NULL, paid INTEGER NOT NULL DEFAULT 0 ); INSERT INTO fees VALUES (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0), (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1), (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
┌──────────────────┬─────────────┬───────┐ │ subject │ name │ marks │ ├──────────────────┼─────────────┼───────┤ │ Chemistry │ Meera Iyer │ 89 │ │ Computer Science │ Anaya Joshi │ 99 │ │ English │ Aman Verma │ 90 │ │ Maths │ Meera Iyer │ 95 │ │ Physics │ Meera Iyer │ 91 │ └──────────────────┴─────────────┴───────┘ (5 rows)
How do I calculate a running total in SQL?
SUM(runs) OVER (ORDER BY over_no) adds up all rows from the first over up to the current one. That is a running total: the team's score after each over.
A window can also be a sliding frame. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means: this over and the two before it. AVG over that frame is the run rate of the last 3 overs.
Try it: change 2 PRECEDING to 4 PRECEDING and run again. The last-overs average gets smoother.
📋 Tables in this example: overs — tap to see how they are made
CREATE TABLE overs ( over_no INTEGER PRIMARY KEY, runs INTEGER NOT NULL ); INSERT INTO overs VALUES (1, 4), (2, 7), (3, 2), (4, 12), (5, 6), (6, 0), (7, 9), (8, 5), (9, 8), (10, 11);
┌─────────┬──────┬───────┬───────────┐ │ over_no │ runs │ score │ last3_avg │ ├─────────┼──────┼───────┼───────────┤ │ 1 │ 4 │ 4 │ 4 │ │ 2 │ 7 │ 11 │ 5.5 │ │ 3 │ 2 │ 13 │ 4.3 │ │ 4 │ 12 │ 25 │ 7 │ │ 5 │ 6 │ 31 │ 6.7 │ │ 6 │ 0 │ 31 │ 6 │ │ 7 │ 9 │ 40 │ 5 │ │ 8 │ 5 │ 45 │ 4.7 │ │ 9 │ 8 │ 53 │ 7.3 │ │ 10 │ 11 │ 64 │ 8 │ └─────────┴──────┴───────┴───────────┘ (10 rows)
How do I compare a row with the previous row using LAG?
LAG(marks) OVER (ORDER BY test_no) reads the marks from the row before. LEAD reads the row after. For the first row there is no previous one, so LAG gives NULL.
Below, a student's unit test marks show the change from the last test. A negative number means the marks dropped.
Window functions work the same way in MySQL 8, PostgreSQL and SQLite (from version 3.25). Try it: change LAG to LEAD and run again.
📋 Tables in this example: unit_tests — tap to see how they are made
CREATE TABLE unit_tests ( test_no INTEGER PRIMARY KEY, marks INTEGER NOT NULL ); INSERT INTO unit_tests VALUES (1, 62), (2, 70), (3, 66), (4, 81), (5, 85);
┌─────────┬───────┬──────────┬────────┐ │ test_no │ marks │ previous │ change │ ├─────────┼───────┼──────────┼────────┤ │ 1 │ 62 │ NULL │ NULL │ │ 2 │ 70 │ 62 │ 8 │ │ 3 │ 66 │ 70 │ -4 │ │ 4 │ 81 │ 66 │ 15 │ │ 5 │ 85 │ 81 │ 4 │ └─────────┴───────┴──────────┴────────┘ (5 rows)
🤔 Predict the output
Think like SQL: read the code and choose what it prints. You get the reason straight away.
Question 1. Dev has the 5th highest score in the class. What does this return?
📋 The tables (tap to see them)
CREATE TABLE quiz (
name TEXT NOT NULL,
score INTEGER NOT NULL
);
INSERT INTO quiz VALUES
('Riya', 18), ('Aman', 20), ('Sara', 18), ('Dev', 15), ('Meera', 20), ('Kabir', 12);SELECT name, RANK() OVER (ORDER BY score DESC) AS r FROM quiz WHERE name = 'Dev';
Question 2. Scores: 20, 20, 18, 18, 15 (Dev), 12. What is Dev's DENSE_RANK?
📋 The tables (tap to see them)
CREATE TABLE quiz (
name TEXT NOT NULL,
score INTEGER NOT NULL
);
INSERT INTO quiz VALUES
('Riya', 18), ('Aman', 20), ('Sara', 18), ('Dev', 15), ('Meera', 20), ('Kabir', 12);SELECT r FROM (
SELECT name, DENSE_RANK() OVER (ORDER BY score DESC) AS r
FROM quiz
)
WHERE name = 'Dev';Question 3. Runs in the first three overs were 4, 7 and 2. What is the score after over 3?
📋 The tables (tap to see them)
CREATE TABLE overs ( over_no INTEGER PRIMARY KEY, runs INTEGER NOT NULL ); INSERT INTO overs VALUES (1, 4), (2, 7), (3, 2), (4, 12), (5, 6), (6, 0), (7, 9), (8, 5), (9, 8), (10, 11);
SELECT score FROM (
SELECT over_no, SUM(runs) OVER (ORDER BY over_no) AS score
FROM overs
)
WHERE over_no = 3;🧩 Your challenge
Find the topper of each class (11 and 12) by average marks. Use a CTE (Lesson 3) for each student's average (1 decimal), rank inside each class with RANK() OVER (PARTITION BY class …), and keep rank 1. Expected: 11 | Meera Iyer | 90.8 and 12 | Riya Sharma | 87.6.
┌───────┬─────────────┬─────────┐ │ class │ name │ average │ ├───────┼─────────────┼─────────┤ │ 11 │ Meera Iyer │ 90.8 │ │ 12 │ Riya Sharma │ 87.6 │ └───────┴─────────────┴─────────┘ (2 rows)
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons) CREATE TABLE students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, class INTEGER NOT NULL, section TEXT NOT NULL, city TEXT, joined TEXT NOT NULL ); INSERT INTO students VALUES (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'), (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'), (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'), (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'), (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'), (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'), (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'), (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12'); CREATE TABLE subjects ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE ); INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English'); CREATE TABLE teachers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, subject_id INTEGER REFERENCES subjects(id) ); INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL); CREATE TABLE marks ( student_id INTEGER NOT NULL REFERENCES students(id), subject_id INTEGER NOT NULL REFERENCES subjects(id), marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100), PRIMARY KEY (student_id, subject_id) ); INSERT INTO marks VALUES (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84), (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90), (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88), (4,1,64),(4,2,58),(4,4,88),(4,5,71), (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86), (6,1,55),(6,2,62),(6,3,49),(6,5,67), (7,1,73),(7,4,99),(7,5,80); CREATE TABLE fees ( student_id INTEGER NOT NULL REFERENCES students(id), month TEXT NOT NULL, amount INTEGER NOT NULL, paid INTEGER NOT NULL DEFAULT 0 ); INSERT INTO fees VALUES (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0), (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1), (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
⚠️ Common mistakes (and how to fix them)
❌ Wrong
SELECT name, score FROM quiz WHERE RANK() OVER (ORDER BY score DESC) = 1;
Error: misuse of window function RANK()
✅ Right
SELECT name, score FROM (
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS pos
FROM quiz
)
WHERE pos = 1
ORDER BY name;Window functions are worked out after WHERE, so they cannot be used inside it. Rank in a subquery or CTE, then filter outside.
❌ Wrong
SELECT name, score FROM (
SELECT name, score, ROW_NUMBER() OVER (ORDER BY score DESC, name) AS pos
FROM quiz
)
WHERE pos = 1;Runs, but gives the wrong result: ┌──────┬───────┐ │ name │ score │ ├──────┼───────┤ │ Aman │ 20 │ └──────┴───────┘ (1 row)
✅ Right
SELECT name, score FROM (
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS pos
FROM quiz
)
WHERE pos = 1
ORDER BY name;ROW_NUMBER never gives a tie, so one of the two toppers with 20 is left out. Use RANK when equal scores should share a place.
❌ Wrong
SELECT over_no, runs, SUM(runs) OVER () AS score FROM overs WHERE over_no <= 3 ORDER BY over_no;
Runs, but gives the wrong result: ┌─────────┬──────┬───────┐ │ over_no │ runs │ score │ ├─────────┼──────┼───────┤ │ 1 │ 4 │ 13 │ │ 2 │ 7 │ 13 │ │ 3 │ 2 │ 13 │ └─────────┴──────┴───────┘ (3 rows)
✅ Right
SELECT over_no, runs, SUM(runs) OVER (ORDER BY over_no) AS score FROM overs WHERE over_no <= 3 ORDER BY over_no;
Without ORDER BY inside OVER, the window is all rows, so every line shows the full total. ORDER BY over_no makes it a running total.
📌 Remember
- A window function calculates across rows but keeps every row: function OVER (…).
- ROW_NUMBER never ties; RANK ties and skips (1, 1, 3); DENSE_RANK ties without skipping (1, 1, 2).
- PARTITION BY restarts the window for each group, like GROUP BY without losing rows.
- SUM(…) OVER (ORDER BY …) gives a running total; ROWS BETWEEN sets a sliding frame.
- Window functions run after WHERE, so filter on them in a subquery or CTE.
Finished the quiz and the challenge?
Questions students ask
What is the difference between GROUP BY and PARTITION BY?
GROUP BY turns each group into one row. PARTITION BY keeps all rows and only tells the window function where each group starts and ends. You can use both in one query.
Does MySQL support window functions?
Yes, from MySQL 8.0. PostgreSQL has supported them for a long time, and SQLite from version 3.25. The syntax in this lesson works in all three.
How do I find the second highest marks in SQL?
Rank the rows with DENSE_RANK() OVER (ORDER BY marks DESC) in a subquery, then keep the rows where the rank is 2. DENSE_RANK makes sure equal top marks still count as one place.
Why do I get NULL from LAG?
The first row has no row before it, so LAG returns NULL. You can give a default as the third argument, for example LAG(marks, 1, 0).