SELECT DISTINCT in SQL

SELECT DISTINCT in SQL

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

  1. Removes Duplicate Rows:
    The DISTINCT keyword ensures that only unique records are returned, eliminating duplicate entries from the result.

  2. 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 and job_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.