HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

MySQL DISTINCT

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.


Syntax

SELECT DISTINCT column1, column2
FROM table_name;

DISTINCT is placed immediately after SELECT and applies to all the columns listed.


Sample Table

idnamecityage
1Rahim UddinDhaka22
2Sara BegumChittagong20
3Karim AliSylhet23
4Nila AkterDhaka21
5Rafi HossainRajshahi24
6Tania IslamDhaka22

Notice that Dhaka appears three times and age 22 appears twice.


DISTINCT on a Single Column

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 — For Comparison

Without DISTINCT, Dhaka would appear three times:

SELECT city FROM students;
city
Dhaka
Chittagong
Sylhet
Dhaka
Rajshahi
Dhaka

DISTINCT on Multiple Columns

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;
cityage
Dhaka22
Chittagong20
Sylhet23
Dhaka21
Rajshahi24

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.


COUNT DISTINCT

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

DISTINCT and NULL

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

Key Points to Remember

  • SELECT DISTINCT removes duplicate rows from the result set.
  • Place DISTINCT immediately after SELECT.
  • With multiple columns, DISTINCT deduplicates based on the combination of all listed columns.
  • Use COUNT(DISTINCT column) to count the number of unique values in a column.
  • Multiple NULL values are treated as a single unique entry by DISTINCT.
What's next? The next lesson covers Aliases (AS) — how to give columns and tables temporary names in a query to make results cleaner and queries easier to read.