SQL SELECT UNIQUE
The SQL SELECT UNIQUE statement is used to return unique values from a column in a table. It eliminates duplicate rows from the result set. This is particularly useful when you want to retrieve distinct records without any repetition.
Syntax
The basic syntax for SELECT UNIQUE is:
SELECT UNIQUE column_name
FROM table_name;
Example
Consider a table Staff with a column Department. We want to retrieve all unique departments from the table.
Code Example
-- Retrieve unique departments from the Staff table
SELECT UNIQUE Department FROM Staff;
-- Alternative syntax with DISTINCT
SELECT DISTINCT Department FROM Staff;
Output
Department |
---|
HR |
IT |
Finance |
Explanation
- The SELECT UNIQUE Department query retrieves all unique values from the Department column.
- In this example, even if multiple employees belong to the same department, each department is listed only once in the result.
- The SELECT DISTINCT
statement is equivalent to SELECT UNIQUE
and is the preferred syntax in modern SQL.
Best Practices
- Use SELECT DISTINCT instead of SELECT UNIQUE for better compatibility across SQL implementations.
- Ensure that the column used in the query contains meaningful data where duplication needs to be avoided.