DISTINCT with ORDER BY
SELECT DISTINCT gradeFROM students_infoORDER BY grade; SELECT COUNT(DISTINCT grade) AS unique_gradesFROM students_info;- Result: 9, 10, 11
- unique_grades = 3
You have a students_info table.
Table: students_info
| id | name | grade |
|---|---|---|
| 1 | Ana | 10 |
| 2 | Raj | 9 |
| 3 | Mei | 10 |
| 4 | Sam | 11 |
| 5 | Zoe | 9 |
Task
Write a query that returns every unique grade in ascending order, and a second query that returns how many unique grades there are.
Expected output
| grade |
|---|
| 9 |
| 10 |
| 11 |
The count query should return 3.
Work out your queries on your own, then open Answers & Optimization to compare.
Found a mistake in this question?
Report a problemA basic answer first, then the optimized one.
DISTINCT removes duplicate rows across all the selected columns, not just the first one.COUNT(DISTINCT col) counts unique non-NULL values.DISTINCT and GROUP BY give the same result here and usually the same plan.SELECT DISTINCT gradeFROM students_infoORDER BY grade; SELECT COUNT(DISTINCT grade) AS unique_gradesFROM students_info;-- With this index the engine can read the index only, not the whole tableCREATE INDEX idx_students_grade ON students_info (grade); SELECT gradeFROM students_infoGROUP BY gradeORDER BY grade; -- Only need to know whether a value exists? Stop at the first matchSELECT EXISTS (SELECT 1 FROM students_info WHERE grade = 10) AS has_grade_10;Log in to mark questions completed and keep your streak.
Log inSpotted a mistake in these answers?
Report a problem