Member-only story
SQL SELECT DISTINCT Statement
In SQL, the SELECT DISTINCT statement is a powerful tool used to retrieve unique values from a specific column in a table. It filters out duplicate records, ensuring only distinct values are returned.
Syntax:
The basic syntax for the SELECT DISTINCT statement is:
SELECT DISTINCT column_name(s)
FROM table_name;How it Works:
Let’s consider a table named employees with columns id, name, and department. If we want to fetch unique department names from this table, the SQL query would be:
SELECT DISTINCT department
FROM employees;This query will return a list of unique department names present in the employees table.
Use Cases:
Counting Unique Values: The SELECT DISTINCT statement is handy when you want to count the number of unique occurrences in a column.
SELECT COUNT(DISTINCT department) AS total_departments FROM employees;Filtering Unique Records: You can filter and display only distinct records based on certain conditions.
SELECT DISTINCT department FROM employees WHERE department <> 'HR';Benefits:
- Eliminates Duplicates: It ensures that only unique values are returned.
- Simplifies Analysis: Useful for summarizing data or finding unique entries in a column.
Conclusion:
The SELECT DISTINCT statement is a valuable asset in SQL queries, allowing you to retrieve unique values from columns and streamline data analysis. By eliminating duplicates, it simplifies result sets, aiding in various data manipulation tasks.




