Menu

How to get the top 1 row of each group in SQL?

How to get the top 1 row of each group?

Written by Selva Prabhakaran | 3 min read

Problem

From the test_scores table below, select the top 1 row in each group.

For example, you have a table with data about ‘students’ test scores, and you want to find the highest-scoring student in each subject.

Input

student_idsubjectscore
1Math90
2Math85
3Math95
1Science88
2Science92
3Science89
1History78
2History88
3History92

Try Hands-On: Fiddle

Create Input Table: Gist

Desired Output

student_idsubjectscore
3History92
3Math95
2Science92

There are multiple ways to do this. Let’s look at some of them.

Solution 1:

Using ROW_NUMBER()

In this approach, we consider the Top 1 row are the first row in the table, ordered based on score.

You can use a common table expression (CTE) along with the ROW_NUMBER() function to achieve this. Here’s the SQL query to retrieve the top 1 row from each subject group.

Note: ROW_NUMBER() works on MySQL only from v8 onwards.

sql
    WITH RankedScores AS (
        SELECT
            student_id,
            subject,
            score,
            ROW_NUMBER() OVER (PARTITION BY subject ORDER BY score DESC) AS row_num
        FROM
            test_scores
    )
    SELECT
        student_id,
        subject,
        score
    FROM
        RankedScores
    WHERE
        row_num = 1;

Explanation:

This query first assigns a row number to each row within each subject group, based on the score in descending order. Then, it selects only the rows where the row number is 1, which represents the top-scoring student in each subject.

Solution 2:

By using a subquery with a JOIN

In this approach, we condider the top 1 row to be the row with maximum score.

sql
SELECT t1.student_id, t1.subject, t1.score
FROM test_scores t1
JOIN (
    SELECT subject, MAX(score) AS max_score
    FROM test_scores
    GROUP BY subject
) t2
ON t1.subject = t2.subject AND t1.score = t2.max_score;

Explanation:

This query first creates a subquery (aliased as t2) that calculates the maximum score for each subject group using the MAX() function and GROUP BY.

Then, it joins the original table test_scores with this subquery based on both subject and score.

This way, it retrieves the rows where the score matches the maximum score for each subject group.

Solution 3:

Using a Correlated Subquery

sql
SELECT ts.student_id, ts.subject, ts.score
FROM test_scores ts
WHERE ts.score = (
    SELECT MAX(score)
    FROM test_scores
    WHERE subject = ts.subject
);

Explanation:

In this query, we use a correlated subquery in the WHERE clause.

For each row in the main query (aliased as ts), the subquery finds the maximum score for the same subject in the test_scores table.

If the score of the current row matches the maximum score for that subject, the row is included in the result.

  1. SQL for Data Science – Level 1
  2. SQL for Data Science – Level 2
  3. SQL for Data Science – Level 3
  1. Introduction to SQL
  2. SQL Window Functons – Made Simple and Easy
  3. SQL Subquery

More SQL Questions

  1. How to select only rows with max value on a column?
  2. How to transpose columns to rows in SQL?
  3. How to select first row in each GROUP BY group?
Free Course
Master Core Python — Your First Step into AI/ML

Build a strong Python foundation with hands-on exercises designed for aspiring Data Scientists and AI/ML Engineers.

Start Free Course
Trusted by 50,000+ learners
Related Course
Master SQL — Hands-On
Join 5,000+ students at edu.machinelearningplus.com
Explore Course
Free Callback - Limited Slots
Not Sure Which Course to Start With?
Talk to our AI Counsellors and Practitioners. We'll help you clear all your questions for your background and goals, bridging the gap between your current skills and a career in AI.
10-digit mobile number
📞
Thank You!
We'll Call You Soon!
Our learning advisor will reach out within 24 hours.
(Check your inbox too — we've sent a confirmation)
⚡ Before you go

Python.
SQL. NumPy.
All free.

Get the exact 10-course programming foundation that Data Science professionals use.

🐍
Core Python — from first line to expert level
📈
NumPy & Pandas — the #1 libraries every DS job needs
🗃️
SQL Levels I–III — basics to Window Functions
📄
Real industry data — Jupyter notebooks included
R A M S K
57,000+ students
★★★★★ Rated 4.9/5
⚡ Before you go
Python. SQL.
All Free.
R A M S K
57,000+ students  ★★★★★ 4.9/5
Get Free Access Now
10 courses. Real projects. Zero cost. No credit card.
New learners enrolling right now
🔒 100% free ☕ No spam, ever ✓ Instant access
🚀
You're in!
Check your inbox for your access link.
(Check Promotions or Spam if you don't see it)
Or start your first course right now:
Start Free Course →
Scroll to Top
Scroll to Top
Course Preview

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free Sample Videos:

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science