The SQL Server DISTINCT Statement retrieves unique records (by removing the duplicates) from the specified column in the SELECT Statement.
The syntax of the SQL SELECT DISTINCT statement is:
SELECT DISTINCT [Column Names] FROM Source WHERE Conditions -- This is Optional
- 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 this.
SQL Select Distinct Single Column
In this example, we select the unique records present in the Education Column.
SELECT DISTINCT [Education] FROM [Employees]
Multiple Columns
When we use this one on multiple columns, the below query returns the unique combination of multiple columns instead of unique individual records. In this example, we select the unique combination of 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 Select Distinct Where Clause
Here, we are using it along with the WHERE Clause. The following 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 valid distinctive records. So, Please use any Not Null function (NOT NULL) functions to remove NULLS.
SQL Select 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).
DISTINCT Count Example
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 this 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]
Null Example
The SQL select distinct statement considers NULL as a distinctive keyword one.
SELECT DISTINCT DeptID FROM [Employees]
Comments are closed.