SQL SELECT DISTINCT
The SELECT DISTINCT statement is used to retrieve unique values from a column or set of columns in a table. The basic syntax of a SELECT DISTINCT statement is as follows:
SELECT DISTINCT column1, column2, ..., columnN FROM table_name;
In this syntax, column1
, column2
, ..., columnN
are the names of the columns that you want to retrieve unique values from. table_name
is the name of the table that contains the columns.
For example, to retrieve all the unique values from the department
column of the employees
table, you would use the following SELECT DISTINCT statement:
SELECT DISTINCT department FROM employees;
This statement retrieves all the unique values from the department
column of the employees
table. If the department
column contains duplicate values, only one instance of each unique value is returned in the result set.
Note that the DISTINCT keyword applies to all the columns specified in the SELECT statement. If you want to retrieve unique values from a single column, you only need to specify that column in the SELECT DISTINCT statement.
The SELECT DISTINCT statement can also be used in combination with the WHERE clause to retrieve unique values that satisfy a particular condition. For example, to retrieve all the unique values from the department
column of the employees
table where the salary
column is greater than or equal to 50000, you would use the following SELECT DISTINCT statement with a WHERE clause:
SELECT DISTINCT department FROM employees WHERE salary >= 50000;
This statement retrieves all the unique values from the department
column of the employees
table where the value of the salary
column is greater than or equal to 50000. If there are duplicate values in the department
column that satisfy this condition, only one instance of each unique value is returned in the result set.