DISTINCT
DISTINCT removes duplicate values from a query's results, returning only the unique ones. Imagine a students table where several students share the same grade level. SELECT grade FROM students; would list that grade once per matching student, with plenty of repeats. SELECT DISTINCT grade FROM students; instead returns each grade value only once, no matter how many students share it. DISTINCT can apply across multiple columns too: SELECT DISTINCT grade, section FROM students; returns each unique grade-and-section combination two rows only count as duplicates if every selected column matches exactly. DISTINCT is commonly used for quick questions like "what are all the different grade levels we have students in?" a summary question, rather than a per-row listing.
Why this matters
- ·DISTINCT quickly answers 'what are the unique values here' without manual scanning.
- ·It works across multiple columns, finding unique combinations, not just single-column duplicates.
- ·It's a lightweight way to summarize a column before reaching for heavier tools like GROUP BY.
Common mistakes
- ·DISTINCT across many columns can return more rows than expected, since it only removes rows that match on every selected column.
- ·Overusing DISTINCT to 'clean up' a query can sometimes hide an underlying JOIN or WHERE mistake that's producing accidental duplicates.
- ·On a very large table, DISTINCT has real computational cost it's not free.
+-----+ | age | +-----+ | 16 | | 17 | +-----+ 2 rows in set
PHP runs on a server, not in the browser this shows the expected output instead of a live one.
Frequently asked questions
It removes duplicate rows from a result, keeping only unique values (or unique combinations, across the selected columns).
Practice questions
Question 1
Write a query that returns the unique names in the students table.
PHP runs on a server, not in the browser this shows the expected output instead of a live one.
Question 2
Write a query that returns unique age values, sorted from smallest to largest.
PHP runs on a server, not in the browser this shows the expected output instead of a live one.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 3
