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
Mumbai

Delhi and Mumbai appear multiple times.

Example: With DISTINCT

SELECT DISTINCT city FROM orders;

Result:

city
-------
Delhi
Mumbai
Chennai

Each 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
-------------
3

DISTINCT vs GROUP BY

Both DISTINCT and GROUP BY can return unique values, but they serve different purposes:

FeatureDISTINCTGROUP BY
PurposeRemove duplicate rows from resultGroup rows for aggregation
Used with aggregatesOnly inside functions like COUNT()Commonly used with SUM, COUNT, AVG
SimplicitySimpler for deduplicationMore powerful for summary data

DISTINCT with ORDER BY

SELECT DISTINCT city FROM orders ORDER BY city ASC;

Result:

city
-------
Chennai
Delhi
Mumbai

Key Points

  • DISTINCT filters 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.
  • DISTINCT can be combined with ORDER BY for sorted unique results.
  • Use DISTINCT for simple deduplication; use GROUP BY when aggregation is needed.

Leave a Comment

Your email address will not be published. Required fields are marked *