By default, a SELECT query returns all rows — including duplicates. The DISTINCT keyword tells MySQL to return only unique values, eliminating repeated entries from the result set. This is especially useful when you want to see a list of all possible values in a column without seeing the same value appear multiple times.
SELECT DISTINCT column1, column2
FROM table_name;
DISTINCT is placed immediately after SELECT and applies to all the columns listed.
| id | name | city | age |
|---|---|---|---|
| 1 | Rahim Uddin | Dhaka | 22 |
| 2 | Sara Begum | Chittagong | 20 |
| 3 | Karim Ali | Sylhet | 23 |
| 4 | Nila Akter | Dhaka | 21 |
| 5 | Rafi Hossain | Rajshahi | 24 |
| 6 | Tania Islam | Dhaka | 22 |
Notice that Dhaka appears three times and age 22 appears twice.
Get the list of unique cities — each city appears only once regardless of how many students are from there:
SELECT DISTINCT city FROM students;
| city |
|---|
| Dhaka |
| Chittagong |
| Sylhet |
| Rajshahi |
Without DISTINCT, Dhaka would appear three times:
SELECT city FROM students;
| city |
|---|
| Dhaka |
| Chittagong |
| Sylhet |
| Dhaka |
| Rajshahi |
| Dhaka |
When you use DISTINCT with multiple columns, it removes rows where the combination of all listed columns is a duplicate:
SELECT DISTINCT city, age FROM students;
| city | age |
|---|---|
| Dhaka | 22 |
| Chittagong | 20 |
| Sylhet | 23 |
| Dhaka | 21 |
| Rajshahi | 24 |
Dhaka still appears twice because the combination (Dhaka, 22) and (Dhaka, 21) are different pairs. The row with Tania Islam (Dhaka, 22) is deduplicated against Rahim Uddin's identical combination.
Combine DISTINCT with COUNT to count how many unique values exist in a column:
-- How many unique cities do our students come from?
SELECT COUNT(DISTINCT city) AS unique_cities FROM students;
-- Returns: 4
If a column contains multiple NULL values, DISTINCT treats all of them as a single unique value and returns only one NULL in the output:
SELECT DISTINCT phone FROM students;
-- If phone has 3 NULL rows, only one NULL appears in the result
SELECT DISTINCT removes duplicate rows from the result set.DISTINCT immediately after SELECT.DISTINCT deduplicates based on the combination of all listed columns.COUNT(DISTINCT column) to count the number of unique values in a column.NULL values are treated as a single unique entry by DISTINCT.