How to get Distinct Records from a table in SQL Server - SQL Server / TSQL Tutorial 112


You are working as SQL Server developer, you need to get distinct (different) records from a table. Which statement will you use to get unique records from a table.


Select distinct can be used to get different records from a table. The syntax for Select distinct is

Select distinct Column1,Column2, Column3.... from SchemaName.TableName.

Let's create sample dbo.Customer table and then insert test records by using below statements.

--Create dbo.Customer table
Create table dbo.Customer(
Id int,
Name VARCHAR(10),
Address VARCHAR(100))

--Insert records in dbo.Customer table
Insert into dbo.Customer
Values(1,'Aamir','XyZ Address')
,(1,'Aamir','XyZ Address')
,(3,'John','XyZ Address')

As you can see that we have duplicate record 1,'Aamir','XyZ Address. Now if we would like to get distinct records from this table, we can use below query. If all columns are involved in your select, you can use * as shown below or type the names of columns.

Select distinct * From dbo.Customer

Select distinct ID,Name,Address From dbo.Customer

How to get distinct records from SQL Server Table - SQL Server / TSQL Tutorial

As we can see that our query returned distinct records. We had duplicate records in table but it only display distinct as we have used Distinct in our Select statement.

You can always run distinct on single or more columns if you like. If I want to get only distinct Names from dbo.Customer table, I can use below query.

Select distinct Name From dbo.Customer
How to use Distinct in Select query in SQL Server to get distinct (difference) records