SQL Server DISTINCT Keyword

SQL Server DISTINCT Keyword

In SQL Server, DISTINCT clause is used with SELECT statement to remove the duplicate rows fetched in the SQL query result.

DISTINCT Syntax

SELECT [ALL | DISTINCT] column_name1[, column_name2, ....]
FROM table_name
WHERE Filter_condition

Employee Table

Let us consider the example 'Employee' database table.

Employee table output

SELECT Statement with duplicate rows

Getting all the rows with duplicate rows. This is also similar like using ALL keyword in SELECT Statement.

SELECT DeptId, Country
FROM Employee
ORDER BY Country ASC
Output:
DISTINCT ORDER BY ASC output

DISTINCT Example

To get the distinct rows of columns DeptId and Country from Employee table in ascending order based on Country column.

SELECT DISTINCT DeptId, Country
FROM Employee
ORDER BY Country ASC
Output:
DISTINCT ORDER BY ASC output

To get particular column distinct values, here getting distinct country values.

SELECT DISTINCT Country
FROM Employee
ORDER BY Country ASC
Output:
DISTINCT ORDER BY ASC output

To get the distinct rows based on all the column in the database table.

SELECT DISTINCT *
FROM Employee
ORDER BY Country ASC
Output:
DISTINCT ORDER BY ASC output

SELECT Statement with ALL Keyword

Getting all the rows with duplication.

SELECT ALL Country
FROM Employee
ORDER BY Country ASC
Output:
ALL ORDER BY ASC output

DISTINCT with Function Parameter

Computing sum of salary's in SELECT Statement using SUM function with DISTINCT Keyword.

SELECT SUM(DISTINCT Salary) 'Total Salary'
FROM Employee
Output:
SUM function output

SUM Function with ALL

Computing average salary in SELECT Statement using SUM function with ALL Keyword.

SELECT SUM(ALL Salary) 'Total Salary'
FROM Employee
Output:
SUM function output



Python installation

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^