In this topic, we described about the Select Distinct with detailed example.
SELECT DISTINCT used to fetch identical/distinct column values from existing table without duplicate values. By using SELECT DISTINCT command, we can fetch distinct values from existing table in result-set.
Syntax for DISTINCT -
SELECT DISTINCT column_name FROM table_name;
Syntax for DISTINCT with multiple columns -
SELECT DISTINCT Column1, Column2, Column3, …, ColumnN FROM table_name;
Syntax for DISTINCT with aggregate function -
SELECT aggregate_function( DISTINCT column_name )FROM Table_name ;
- column_name - Represents the column name on which DISTINCT applies.
Let us consider below table(s) as an example table(s) to frame the SQL query for getting the desired results.
Scenario – Fetching identical values from table.
Requirement – Fetch distinct manager_id from employee_details table. The query was as follows-
SELECT DISTINCT manager_id FROM employee_details;
By executing above query, we can get output like as shown in below –
Scenario – Fetching identical values from table by using DISTINCT with multiple columns .
Requirement – Fetch distinct employee names from employee_details table. The query was as follows -
SELECT DISTINCT emp_name, manager_id FROM employee_details;
By executing above query, we can get distinct values of emp_name and the corresponding manager_id.
Scenario – Fetching identical values from table by using DISTINCT with aggregate function.
Requirement – get the total distinct deprtments count from employee_details table. The query was as follows –
SELECT COUNT(DISTINCT dept_id) AS 'Total departments' FROM employee_details;
By executing above query, we can get distinct departments in employee_details. The output was as shown in below -