Friday, May 17, 2013

Distinct Keyword in SQL Server

Introduction

In this article I will explain how to use distinct keyword in SQL server. The DISTINCT keyword can be used to return only different values.

Query
 

CREATE TABLE [dbo].[Emp_Info](
      [Emp_Id] [int] NULL,
      [Name] [varchar](50) NULL,
      [Salary] [int] NULL,
      [City] [varchar](50) NULL
) ON [PRIMARY]
Insert some record in table. see the record by run this query
 

Select * from Emp_Info         


Now you will see in above fig table does not contain any primary key column because of that duplicate records exist in table.


Eliminates duplicate rows

The DISTINCT keyword can be used to return only different values. The DISTINCT keyword can be used with SELECT Statement.
Now If you want eliminate duplicate record. Run below query


Select distinct * from Emp_Info


DISTINCT use with multiple column values

In below query distinct will apply for all the mentioned columns it will return distinct column values of Name, Salary and City.

Select distinct Name,Salary,City from Emp_Info

Now you will see below image. table have some column record which specify in query

Suppose I use Distinct keyword with Top statement in SQL Server. 

Query

select distinct top 3 * from Emp_Info

you will see only 3 column value show in table