ROW_NUMBER and SUM Over a Window
Lesson 20 of 33 in the SQL / MySQL learning path.
How do I rank rows without collapsing them with GROUP BY?
GROUP BY collapses a lesson to one row, which is what you want for a count and the wrong shape for a roster that still needs every student. A window function computes a value across a set of related rows and writes it onto each row. ROW_NUMBER assigns a position inside a partition. SUM OVER a partition attaches the lesson total without folding the students away.
This lesson needs MySQL 8. The partition is lesson_id. ROW_NUMBER orders each lesson by enrollment id, and the SUM counts confirmed seats across that whole lesson. The query ORDER BY still controls the order of the result. The ORDER BY inside the window only controls the numbering.
Syntax & Parameters
ROW_NUMBER() OVER (PARTITION BY lesson_id ORDER BY id)
SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) OVER (PARTITION BY lesson_id)
Example
CREATE DATABASE IF NOT EXISTS school
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
USE school;
SET NAMES utf8mb4;
DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
email VARCHAR(254) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE lessons (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(160) NOT NULL,
track VARCHAR(80) NOT NULL,
published_at DATETIME NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE enrollments (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
lesson_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
status VARCHAR(20) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO users (name, email, created_at) VALUES
('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
('Grace Hopper', 'grace@school.test', '2026-03-14 11:00:00'),
('Alan Turing', 'alan@school.test', '2026-03-18 08:30:00'),
('Katherine Johnson', 'katherine@school.test', '2026-03-19 10:00:00');
INSERT INTO lessons (title, track, published_at) VALUES
('Algebra I', 'math', '2026-03-02 09:00:00'),
('SQL Basics', 'data', '2026-03-10 09:00:00'),
('Studio Draft', 'art', NULL);
INSERT INTO enrollments (lesson_id, user_id, status) VALUES
(1, 1, 'confirmed'),
(1, 2, 'waitlist'),
(1, 3, 'cancelled'),
(1, 4, 'confirmed'),
(2, 1, 'confirmed');
SELECT
e.id,
e.lesson_id,
l.title,
u.name,
e.status,
ROW_NUMBER() OVER (
PARTITION BY e.lesson_id
ORDER BY e.id
) AS row_in_lesson,
SUM(CASE WHEN e.status = 'confirmed' THEN 1 ELSE 0 END) OVER (
PARTITION BY e.lesson_id
) AS confirmed_in_lesson
FROM enrollments AS e
INNER JOIN lessons AS l ON l.id = e.lesson_id
INNER JOIN users AS u ON u.id = e.user_id
ORDER BY e.lesson_id, e.id;
SELECT
lesson_id,
COUNT(*) AS enrollment_rows,
SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) AS confirmed_in_lesson
FROM enrollments
GROUP BY lesson_id
ORDER BY lesson_id;
Expected Output
id | lesson_id | title | name | status | row_in_lesson | confirmed_in_lesson 1 | 1 | Algebra I | Ada Lovelace | confirmed | 1 | 2 2 | 1 | Algebra I | Grace Hopper | waitlist | 2 | 2 3 | 1 | Algebra I | Alan Turing | cancelled | 3 | 2 4 | 1 | Algebra I | Katherine Johnson | confirmed | 4 | 2 5 | 2 | SQL Basics | Ada Lovelace | confirmed | 1 | 1 5 rows in set lesson_id | enrollment_rows | confirmed_in_lesson 1 | 4 | 2 2 | 1 | 1 2 rows in set
Line-by-Line Walkthrough
- The roster has four Algebra I enrollments, two of them confirmed, and one confirmed SQL Basics enrollment. Studio Draft has none.
- ROW_NUMBER starts again at 1 for each lesson_id because PARTITION BY e.lesson_id opens a new window per lesson.
- ORDER BY e.id inside that window numbers the four Algebra I enrollments 1, 2, 3, and 4. The id is unique, so the positions do not tie.
- The SUM window uses the same partition and has no ORDER BY of its own, so each row sees the confirmed total for the whole lesson.
- Algebra I rows all show confirmed_in_lesson 2. The SQL Basics row shows 1. Cancelled and waitlist rows remain in the list.
- The query-level ORDER BY e.lesson_id, e.id sorts the result. The window ORDER BY only feeds ROW_NUMBER.
- The second statement is the GROUP BY version of the same sum. Algebra I becomes one row with enrollment_rows 4, and the student names are gone.
- A window is how you rank or total without that collapse. Use GROUP BY when one row per lesson is what the report should return.
- MySQL 8 supports OVER. A server that only has the older 5.7 parser rejects these functions. Filter with WHERE before the window so the partition is already the set you care about.
Common Pitfalls & Security
A window keeps detail rows, and it can also explode the amount of work when the partition is the whole table. The ORDER BY inside OVER is not the sort the client sees. Adding it to a SUM also changes the meaning of the sum.
- The query ORDER BY is the only sort of the result. Leave it out and MySQL may return the numbered rows in another order.
- SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) OVER (PARTITION BY lesson_id ORDER BY id) becomes a running total under the default frame. Leave ORDER BY out of that SUM when every row should show the full lesson total.
- ROW_NUMBER still increments when the sort values tie. RANK repeats a number on a tie. This lesson orders by id so each position is unique.
- You cannot filter on row_in_lesson in the same WHERE. Wrap the window query if you need the first row per lesson only.
- Window functions do not replace a WHERE for privacy. A cancelled student is still in the result until the WHERE clause removes that status.
Best Practices & Modern Standards
Use a window when the report needs each enrollment and a fact about its lesson, such as a position or a confirmed total. Keep PARTITION BY narrow, usually the foreign key you would have grouped by. Put a unique column at the end of the window ORDER BY so the numbering stays stable from run to run.
Use GROUP BY when the caller wants one row per lesson and does not need the students. MySQL 8 is the version that implements these functions. Filter first, then number, and add the result ORDER BY explicitly so the roster comes back in lesson and enrollment order.
Real-World Use
The Algebra I roster must list every student and also show how many seats in that class are confirmed. ROW_NUMBER gives the office a stable line number, and the window SUM prints 2 on every Algebra I row. The attendance sheet stays one row per student, which a GROUP BY count would have erased.
Frequently Asked Questions
Does the ORDER BY inside OVER sort the rows I get back?
No. That ORDER BY only defines the window, which is how ROW_NUMBER assigns positions. The ORDER BY at the end of the query sorts the result.
Why not use GROUP BY for the confirmed total?
GROUP BY returns one row per lesson and drops the student columns. The window SUM writes the same total onto every enrollment row so the roster stays intact.
Why do all Algebra I rows show the same confirmed total?
The SUM has no ORDER BY, so its window is the whole lesson_id partition. Ada, Grace, Alan, and Katherine each see the two confirmed seats.
Which MySQL versions accept OVER?
MySQL 8. The 5.7 parser does not implement window functions and rejects the OVER clause. This lesson is written for MySQL 8.