SQL SELECT DISTINCT statement
The SELECT DISTINCT
statement is used to retrieve only unique or distinct records from a database table. This query retrieves all the distinct values of a column in a table.
Syntax
The basic syntax of the SELECT DISTINCT
statement is as follows:
SELECT DISTINCT column1, column2
FROM table_name;
Here, column1
and column2
are the names of the columns that we want to retrieve unique values from. table_name
is the name of the table from which we want to retrieve the data.
Example
Consider a table named employee
with columns id
, name
, department
, and salary
. The following SQL query will retrieve all the distinct values of the department
column from the employee
table:
SELECT DISTINCT department
FROM employee;
Output
The output of the above query will be a list of all the unique departments in the employee table.
department
----------
Sales
Marketing
Finance
Human Resources
Explanation
The SELECT DISTINCT
statement works by eliminating all the duplicate values from the result set and only returning the distinct values. In the example above, we want to retrieve all the unique or distinct departments from the employee
table.
Use
The SELECT DISTINCT
statement is mostly used to retrieve unique values from a table. It can also be used with aggregate functions like COUNT()
, MAX()
, etc. to get the unique results.
Important Points
- The
DISTINCT
keyword is used to retrieve only the unique values from the result set. SELECT DISTINCT
statement works with a single or multiple columns.- It eliminates the duplicate values from the result set.
Summary
In summary, the SELECT DISTINCT
statement is used to retrieve unique or distinct values from a table. It is handy when we want to eliminate duplicate values from the result set. It can also be used with aggregate functions to fetch unique or distinct results.