The SELECT DISTINCT
statement is used to retrieve unique values from a column or combination of columns in a table. It eliminates duplicate rows from the result set.
Key Points
Removes Duplicate Rows:
TheDISTINCT
keyword ensures that only unique records are returned, eliminating duplicate entries from the result.Applies to Specific Columns:
DISTINCT
can be applied to one or more columns. When applied to multiple columns, it considers the combination of values across those columns for uniqueness.
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example
Single Column Example
SELECT DISTINCT department
FROM employees;
- This query returns all unique department names in the
employees
table.
Multiple Columns Example
SELECT DISTINCT department, job_title
FROM employees;
- This query returns unique combinations of
department
andjob_title
.
When to Use SELECT DISTINCT
When you want to identify all unique entries in a dataset.
When you want to reduce redundancy in the query result.
Note: Using DISTINCT
can be resource-intensive for large datasets, as the database engine has to evaluate uniqueness across rows.