MySQL DISTINCT Clause
The DISTINCT
clause in MySQL is used to remove duplicate rows from the result set. It ensures that only unique rows are returned based on the specified column(s).
Syntax
column1, column2
: The columns you want to retrieve without duplicates.table_name
: The name of the table to query.
1. Selecting Unique Values from a Single Column
Example
Get unique country
names from the customers
table:
Result
2. Selecting Unique Values from Multiple Columns
When using multiple columns with DISTINCT
, the combination of values in those columns must be unique.
Example
Get unique combinations of country
and city
:
Result
3. Using DISTINCT with Aggregate Functions
DISTINCT
can also be used inside aggregate functions to perform operations only on unique values.
Example
Find the sum of distinct order amounts:
Result
4. Using DISTINCT with LIMIT
You can combine DISTINCT
with LIMIT
to retrieve a specified number of unique rows.
Example
Get the first 3 unique countries:
5. Practical Example
Sample Table: products
Query: Unique Categories
Result:
Query: Unique Product Names
Result:
6. Common Errors
Using DISTINCT on All Columns:
UsingSELECT DISTINCT *
may result in duplicates if any column values differ.This returns all unique rows across all columns.
Incorrect Placement of DISTINCT:
EnsureDISTINCT
is correctly placed afterSELECT
but before column names.
7. Performance Considerations
- Using
DISTINCT
can be resource-intensive for large data sets because MySQL must compare rows to identify duplicates. - Optimize queries with proper indexing to improve performance.
8. Best Practices
Avoid Using
DISTINCT
as a Fix:
If duplicates occur due to improper joins or logic, fix the query rather than relying onDISTINCT
.Index Key Columns:
Indexing columns used inDISTINCT
queries can improve performance significantly.
Let me know if you need further assistance or examples!