SQL Select Distinct
SQL SELECT DISTINCT
The SELECT DISTINCT statement is used to return only unique (different) values from a column. It removes duplicate rows from the result set.
Basic Syntax
SELECT DISTINCT column_name FROM table_name;
Example: Unique Countries
If a customers table contains many customers from the same country, DISTINCT returns each country only once.
SELECT DISTINCT country FROM customers;
Without DISTINCT, the same country would appear multiple times.
Multiple Columns
DISTINCT applies to the entire row of selected columns. When selecting multiple columns, only completely identical rows are removed.
SELECT DISTINCT country, city FROM customers;
In this case, duplicate country-city combinations are removed.
COUNT DISTINCT
You can combine DISTINCT with COUNT to see how many unique values exist in a column.
SELECT COUNT(DISTINCT country) AS unique_countries FROM customers;
When to Use DISTINCT
- When generating reports that require unique values
- When building filters (for example, a dropdown list of categories)
- When analyzing data distribution
Performance Note
DISTINCT may require additional sorting or grouping internally. On large tables, using indexes can significantly improve performance.
Next Step
Continue with SQL WHERE to learn how to filter records based on conditions.