MySQL SELECT DISTINCT
MySQL SELECT DISTINCT: Removing Duplicate Rows
The MySQL SELECT DISTINCT modifier removes duplicate rows from a query result set so each unique value or column combination appears once. Analysts and developers use it to build filter dropdowns, country lists, and unique-user counts.
Basic Syntax
Place DISTINCT immediately after SELECT. When you list multiple columns, MySQL deduplicates on the combined tuple (column1, column2), not on each column separately.
SELECT DISTINCT column1, column2
FROM table_name
WHERE condition;
Practical SQL Examples
The first query lists every unique country code among active rows in demo_customers.
SELECT DISTINCT country_code
FROM demo_customers
WHERE is_active = 1
ORDER BY country_code ASC;
| country_code |
|---|
| CA |
| DE |
| GB |
| US |
You can also place DISTINCT inside COUNT() to count unique buyers in demo_orders without fetching every row:
SELECT COUNT(DISTINCT customer_id) AS unique_buyers
FROM demo_orders
WHERE status = 'paid';
Common Mistakes and Best Practices
- Do Not Mask Broken Joins with
DISTINCT: If aJOINduplicates parent rows unexpectedly, fix the join key or rewrite withEXISTSinstead of hiding duplicates withSELECT DISTINCT. - Understand How
DISTINCTTreatsNULL:SELECT DISTINCTconsiders allNULLvalues equal and returns oneNULLrow, whereasCOUNT(DISTINCT col)ignoresNULLcompletely. - Check
ONLY_FULL_GROUP_BYCompatibility: When combiningSELECT DISTINCTwithORDER BY, every sort column must appear in theSELECTlist.
Frequently Asked Questions
Does SELECT DISTINCT apply to one column or the entire row?
It always applies to the entire combination of columns listed in the SELECT clause.
Is SELECT DISTINCT slower than a normal SELECT?
Yes, because MySQL must sort or hash the matching rows in memory or a temporary table to drop duplicates.
What is the difference between SELECT DISTINCT and GROUP BY?
SELECT DISTINCT simply removes duplicate rows, while GROUP BY groups rows so you can compute aggregates like COUNT() or SUM().
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.