28 November 2026

MySQL 8.4 CTEs and Window Functions for Beginners: Rank Student Scores

  Asp.Net CS By Example       28 November 2026

Standard aggregate queries with GROUP BY collapse all matching students into a single summary row—so you lose individual names and scores. In MySQL 8.4 LTS and MySQL 9, Window Functions (OVER (PARTITION BY ...)) let you calculate track averages and rankings while keeping every student row intact, and Common Table Expressions (CTEs) let you write multi-step queries in clean, readable stages.

GROUP BY vs. Window Functions + CTE

GROUP BY (Collapses rows) • OVER (PARTITION BY track) (Keeps every student) → WITH RankedStudents AS (...) (Filter top rank cleanly)

1. Create a Sample Student Scores Table

CREATE TABLE student_scores (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    track VARCHAR(50) NOT NULL,
    score INT NOT NULL
);

INSERT INTO student_scores (name, track, score) VALUES
('Aarav', 'Backend', 95),
('Maya', 'Backend', 89),
('Liam', 'Frontend', 91),
('Zoe', 'Frontend', 91),
('Noah', 'Frontend', 84);

2. Compare Each Student to Their Track Average with OVER()

Unlike GROUP BY, adding OVER (PARTITION BY track) computes the average for each track alongside every individual student row:

SELECT
    name,
    track,
    score,
    AVG(score) OVER (PARTITION BY track) AS track_avg,
    RANK() OVER (PARTITION BY track ORDER BY score DESC) AS track_rank
FROM student_scores;

3. Filter Top Scorers Cleanly Using a CTE (WITH)

Because SQL does not allow window functions directly inside a WHERE clause, wrap the window query in a WITH CTE and filter the outer SELECT:

WITH RankedStudents AS (
    SELECT
        name,
        track,
        score,
        DENSE_RANK() OVER (PARTITION BY track ORDER BY score DESC) AS rnk
    FROM student_scores
)
SELECT name, track, score
FROM RankedStudents
WHERE rnk = 1;

Practice

  1. Compare the ranks returned by ROW_NUMBER(), RANK(), and DENSE_RANK() on Liam and Zoe's tied score of 91.
  2. Add a running sum column using SUM(score) OVER (ORDER BY id).
  3. Update the final WHERE filter to return the top 2 students per track (WHERE rnk <= 2).

Continue learning: MySQL Lessons and Practice.

References: MySQL Official Documentation.

logoblog

Thanks for reading MySQL 8.4 CTEs and Window Functions for Beginners: Rank Student Scores

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.