SELECT DISTINCT in MySQL
What DISTINCT Changes
DISTINCT removes duplicate rows from the displayed result after selected expressions are evaluated. It does not modify the table and it does not promise an order.
students contains Aarav (X-A, 86.50, Active), Meera (X-A, 91.00, Active), Kabir (X-B, 74.00, Inactive) and Sana (X-B, 88.50, Active).SELECT DISTINCT class_name
FROM students
ORDER BY class_name;One Column: Unique Values
Without DISTINCT the class appears once per student. With DISTINCT, identical class_name results collapse. The comparison follows the column collation, so case or accent variants may compare equal under a case-insensitive collation.
SELECT DISTINCT status
FROM students
ORDER BY status;DISTINCT on Multiple Columns
SELECT DISTINCT class_name, status
FROM students
ORDER BY class_name, status;DISTINCT applies to the pair, not separately to each column. Adding student_id, a unique key, makes every selected row unique and therefore makes DISTINCT unnecessary.
NULL and COUNT(DISTINCT)
SELECT DISTINCT marks FROM students;
SELECT COUNT(DISTINCT class_name) AS class_count
FROM students;SELECT DISTINCT can show one NULL among repeated NULL results. COUNT(DISTINCT expression) counts distinct non-NULL values. For multiple expressions, read the current MySQL manual because NULL and tuple behavior must match your exact version and intention.
Displayed Duplicates vs Stored Duplicates
| Goal | Correct tool |
|---|---|
| Show each class once | SELECT DISTINCT |
| Count students per class | GROUP BY + COUNT |
| Prevent duplicate email/roll number | UNIQUE constraint |
| Find duplicate stored values | GROUP BY value HAVING COUNT(*) > 1 |
Mistakes and Practice
- Expecting DISTINCT to sort.
- Selecting a unique ID and wondering why nothing collapses.
- Using DISTINCT to hide bad joins.
- Confusing result uniqueness with database constraints.
- List each status once.
- List unique class/status combinations and predict three rows.
- Count distinct classes.
- Design a UNIQUE constraint for a school roll number.
Quick Summary
- DISTINCT removes duplicate selected rows only.
- Multiple columns form one comparison combination.
- ORDER BY is still required for predictable display order.
- Constraints, not DISTINCT, prevent invalid stored duplicates.
Official References
References reviewed 14 August 2026.