The SQL SELECT DISTINCT Statement retrieves unique records (by removing the duplicates) from the specified column in the SELECT Statement. The syntax of the SQL Server SELECT DISTINCT is:
SELECT DISTINCT [Column Names] FROM Source WHERE Conditions -- This is Optional
- DISTINCT: Returns Unique Columns
- Columns: It allows us to pick the number of columns from the tables. It may be one or more.
- Source: One or more tables in the Database. JOINS are used to join multiple tables in SQL Server.
We use the below data to explain the SQL Server Select Distinct unique.
SQL Select Distinct Single Column
In this example, We Select the unique records present in the Education Column.
SELECT DISTINCT [Education] FROM [Employees]
SQL Select Distinct Multiple Columns
When we use this one on multiple columns, the SELECT Statement returns the unique combination of multiple columns instead of unique individual records. In this example, we select the unique combination records present in the Education Column and Yearly Income Column.
SELECT DISTINCT [Education] ,[YearlyIncome] FROM [Employees]
Although we used the Keyword in the SELECT Statement, it is returning duplicates because
- Bachelors and 70000 is a Unique Combination
- Bachelors and 80000 is a Unique Combination
- and Bachelors and 90000 is a Unique Combination
SQL DISTINCT WHERE Clause
Using the distinct along with WHERE Clause. The following unique statement will return the unique Education values whose Yearly Income is greater than 50000
SELECT DISTINCT [Education] ,[YearlyIncome] FROM [Employees] WHERE YearlyIncome > 50000
The DISTINCT considers the NULL records as a valid distinctive record. So, Please use any Not Null function (NOT NULL) functions to remove NULLS
SQL Distinct Group By Example
The also allows us to use Aggregate Functions along with Group By Clause. The following unique query groups the employees by Education. Next, it finds the Sum of unique Yearly Income for each Education group.
SELECT [Education] ,SUM(DISTINCT YearlyIncome) AS [Total Income] FROM [Employees] GROUP BY [Education]
Let us remove the Keyword from the above query.
SELECT [Education] ,SUM(YearlyIncome) AS [Total Income] FROM [Employees] GROUP BY [Education]
See the difference in yearly Income. Because it is finding the sum of all the records (not the distinctive ones).
This SQL Select Distinct Count is one of the most commonly asked questions. This example counts and returns the distinctive employee Ids in each Education group.
SELECT [Education] ,COUNT(DISTINCT EmpID) AS [Total Employees] FROM [Employees] GROUP BY [Education]
Here, we used Count Function with the Distinct Keyword, and without. This unique example shows the difference between the result set.
SELECT [Education] ,COUNT(DISTINCT DeptID) AS [Total Dept Ids] ,COUNT(DeptID) AS [Total Ids] FROM [Employees] GROUP BY [Education]
The SQL Server Select Distinct statement considers NULL as a distinctive keyword one.
SELECT DISTINCT DeptID FROM [Employees]