Scenario:
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.
Solution:
Select distinct can be used to get different records from a table. The syntax for Select distinct isSelect 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') ,(2,'Raza',Null) ,(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
OR
Select distinct ID,Name,Address From dbo.Customer
How to get distinct records from SQL Server Table - SQL Server / TSQL Tutorial |
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 |
No comments:
Post a Comment