Lesson

MySQL SELECT DISTINCT

10 min reading
Free Course

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 a JOIN duplicates parent rows unexpectedly, fix the join key or rewrite with EXISTS instead of hiding duplicates with SELECT DISTINCT.
  • Understand How DISTINCT Treats NULL: SELECT DISTINCT considers all NULL values equal and returns one NULL row, whereas COUNT(DISTINCT col) ignores NULL completely.
  • Check ONLY_FULL_GROUP_BY Compatibility: When combining SELECT DISTINCT with ORDER BY, every sort column must appear in the SELECT list.

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().

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum