In SQL Server DISTINCT keyword is use get distinct (unique) record selected result.

We can find out the distinct records from one column or combination of tow or multiple columns.

When we apply the distinct on combinations of columns then SQL returns the distinct value of combination of selected columns.


Select DISTINCT record

Syntax

SELECT DISTINCT < column1 > , < column 2 >.. FROM < table name >
WHERE < condition if required >

Let consider below list of student with there class, marks, city and contact details.

select statement for distinct in sql server

Select DISTINCT on single columns

Select distinct city from where student belong.
Let see below example.

Example

SELECT DISTINCT City FROM tblStudent

Output

select distinct record from table example in sql server


Select DISTINCT on combination of columns

Select distinct class and city from where student belong and order the result set by city.
Let see below example.

Example

SELECT DISTINCT Class, City FROM tblStudent
ORDER BY City

Output

select distinct record from table with order by clause


Select DISTINCT with TOP and ORDER BY keyword

Select ordered top 3 distinct city.
Let see below example.

Example

SELECT DISTINCT TOP 3 City FROM tblStudent
ORDER BY City ASC

Output

select distinct top record with order by in sql server