The SELECT DISTINCT statement is used to retrieve unique values from a column, eliminating duplicate entries.
Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
DISTINCT: Ensures only unique values are returned.column1, column2, ...: Specify the columns you want to select data from.table_name: The name of the table containing the data.
Purpose
In many tables, a column can contain duplicate values. Sometimes, you might only want to list the unique values from a column.
Examples
1. Using SELECT DISTINCT
Retrieve all unique countries from the Customers table:
SELECT DISTINCT Country
FROM Customers;
If the Customers table contains the following Country column:
| Country |
|---|
| Germany |
| Mexico |
| Mexico |
| UK |
| Sweden |
The result will be:
| Country |
|---|
| Germany |
| Mexico |
| UK |
| Sweden |
2. Without DISTINCT
When you omit the DISTINCT keyword, duplicate values are included in the results:
SELECT Country
FROM Customers;
Output:
| Country |
|---|
| Germany |
| Mexico |
| Mexico |
| UK |
| Sweden |
Key Notes
-
Multiple Columns:
When usingDISTINCTwith multiple columns, the combination of values across the columns must be unique to be included in the result.SELECT DISTINCT Country, City FROM Customers; -
Performance:
UsingDISTINCTcan be resource-intensive on large datasets, as the database engine needs to sort and filter duplicates. -
Common Use Cases:
- Fetching a list of unique categories.
- Identifying distinct combinations of fields.
Practice Example
Consider the following query to find unique combinations of City and Country:
SELECT DISTINCT City, Country
FROM Customers;
This will return rows where each combination of City and Country is unique.
The SELECT DISTINCT statement is an essential tool for filtering out duplicates, making it ideal for summarizing data and identifying unique values in a dataset.