Order By Two Columns
Description
Write a SQL query to return all students ordered by grade descending, then name ascending for same grades.
students| Column | Type |
|---|---|
| id | INT |
| name | TEXT |
| grade | INT |
Examples
CREATE TABLE students (id INT, name TEXT, grade INT); INSERT INTO students VALUES (1, 'Charlie', 90), (2, 'Alice', 90), (3, 'Bob', 95);Bob|95
Alice|90
Charlie|90Bob has the highest grade (95), so he's first. Alice and Charlie both have 90, so they're ordered alphabetically: Alice before Charlie.
CREATE TABLE students (id INT, name TEXT, grade INT); INSERT INTO students VALUES (1, 'David', 88), (2, 'Emma', 92), (3, 'Frank', 88), (4, 'Grace', 85), (5, 'Henry', 92);Emma|92
Henry|92
David|88
Frank|88
Grace|85Students are first ordered by grade in descending order (92, 88, 85). For students with the same grade (Emma and Henry both have 92, David and Frank both have 88), they are ordered by name in ascending order (Emma before Henry, David before Frank).
CREATE TABLE students (id INT, name TEXT, grade INT); INSERT INTO students VALUES (1, 'Alex', 100), (2, 'Zoe', 75), (3, 'Mike', 100), (4, 'Sara', 100);Alex|100
Mike|100
Sara|100
Zoe|75Three students have the highest grade of 100, so they are ordered alphabetically by name (Alex, Mike, Sara). Zoe has the lowest grade of 75 and appears last. This demonstrates how alphabetical ordering works when multiple students share the same grade.
Constraints
- •
Use ORDER BY with multiple columns
Ready to solve this problem?
Practice solo and sharpen your skills for technical interviews.