← Back to MySQL Course | Chapter 5: Inserting & Selecting Data | Lesson 4 of 6

SELECT DISTINCT

Introduction to DISTINCT

SELECT DISTINCT removes duplicate rows from a result set, returning only the unique values present in the specified column or columns — useful for quickly listing, say, every distinct city in a customers table.

Example: Introduction to DISTINCT

sql
SELECT DISTINCT city FROM users;

Distinct on Multiple Columns

When DISTINCT is applied across multiple columns, MySQL treats the *combination* as the uniqueness key, so a row is only filtered out if every listed column matches another row exactly.

Example: Distinct on Multiple Columns

sql
SELECT DISTINCT city, country FROM users;

Counting Unique Values

Pairing DISTINCT with COUNT (as in COUNT(DISTINCT column)) tells you how many unique values exist in a column, which is different from a plain COUNT that would include every duplicate.

Example: Counting Unique Values

sql
SELECT COUNT(DISTINCT city) FROM users;

Distinct and Null Values

MySQL treats all NULL values in a column as equal to each other for DISTINCT purposes, collapsing any number of NULLs down into a single NULL row in the result set.

Example: Distinct and Null Values

sql
SELECT DISTINCT city FROM users; -- multiple NULL rows collapse into one

Distinct vs Group By

DISTINCT is best for simple deduplication of a result list; once you need aggregated calculations grouped by category, GROUP BY is the more appropriate and more powerful tool.

Example: Distinct vs Group By

sql
SELECT DISTINCT city FROM users;
SELECT city, COUNT(*) FROM users GROUP BY city;
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.