MySQL DISTINCT Keyword
The DISTINCT keyword in MySQL removes duplicate values from the result of a SELECT query. It returns only unique (different) values from the specified column or combination of columns.
Why Use DISTINCT?
When querying a table, the same value may appear in many rows. For example, a sales table may have hundreds of rows, all with the same city name repeated. Using DISTINCT returns each city name only once, giving a clean list without repetition.
Syntax
SELECT DISTINCT column_name
FROM table_name;Example: Without DISTINCT
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_name VARCHAR(100),
city VARCHAR(50)
);
INSERT INTO orders VALUES (1, 'Anita Roy', 'Delhi');
INSERT INTO orders VALUES (2, 'Suresh Mehta', 'Mumbai');
INSERT INTO orders VALUES (3, 'Priya Nair', 'Delhi');
INSERT INTO orders VALUES (4, 'Karan Shah', 'Chennai');
INSERT INTO orders VALUES (5, 'Nisha Das', 'Mumbai');SELECT city FROM orders;Result:
city
-------
Delhi
Mumbai
Delhi
Chennai
MumbaiDelhi and Mumbai appear multiple times.
Example: With DISTINCT
SELECT DISTINCT city FROM orders;Result:
city
-------
Delhi
Mumbai
ChennaiEach city appears only once.
DISTINCT with Multiple Columns
When DISTINCT is used with more than one column, it removes rows where the combination of all selected columns is a duplicate.
SELECT DISTINCT city, customer_name FROM orders;This returns rows where the combination of city and customer_name is unique. Two customers in Delhi are different combinations, so both appear.
DISTINCT with COUNT
DISTINCT is often used inside the COUNT() function to count unique values.
SELECT COUNT(DISTINCT city) AS unique_cities FROM orders;Result:
unique_cities
-------------
3DISTINCT vs GROUP BY
Both DISTINCT and GROUP BY can return unique values, but they serve different purposes:
| Feature | DISTINCT | GROUP BY |
|---|---|---|
| Purpose | Remove duplicate rows from result | Group rows for aggregation |
| Used with aggregates | Only inside functions like COUNT() | Commonly used with SUM, COUNT, AVG |
| Simplicity | Simpler for deduplication | More powerful for summary data |
DISTINCT with ORDER BY
SELECT DISTINCT city FROM orders ORDER BY city ASC;Result:
city
-------
Chennai
Delhi
MumbaiKey Points
DISTINCTfilters out duplicate rows from query results.- It applies to all selected columns together when used with multiple columns.
COUNT(DISTINCT column)counts only unique values.DISTINCTcan be combined withORDER BYfor sorted unique results.- Use
DISTINCTfor simple deduplication; useGROUP BYwhen aggregation is needed.
