Tutorialsteacher

Follow Us

SQL - Select Distinct Records

A column in the database table may contain duplicate values. The SELECT DISTINCT statement is used to retrieve unique values of a column or combination of one or more columns.

Syntax:

SELECT DISTINCT column_name1, column_name2,... FROM table_name [WHERE Condition];

For the demo purpose, we will use the following Employee table in all examples.

EmpIdFirstNameLastNameEmailSalaryHireDate
1'John''King''[email protected]'330002018-07-25
2'James''Bond'2018-07-29
3'Neena''Kochhar''[email protected]'170002018-08-22
4'Lex''De Haan''[email protected]'150002018-09-8
5'Amit''Patel'180002019-01-25
6'Abdul''Kalam''[email protected]'250002020-07-14
3'Neena''Kochhar''[email protected]'170002018-08-22
4'Lex''De Haan''[email protected]'150002018-09-8
5'Amit''Khanna'180002019-01-25

The following query returns unique records from the Employee table.

SQL Script: Select Distinct Records
SELECT DISTINCT * FROM Employee;

The above query returns all the unique records even if at least one column has a unique value.

EmpIdFirstNameLastNameEmailSalaryHireDate
1'John''King''[email protected]'330002018-07-25
2'James''Bond'2018-07-29
3'Neena''Kochhar''[email protected]'170002018-08-22
4'Lex''De Haan''[email protected]'150002018-09-8
5'Amit''Patel'180002019-01-25
6'Abdul''Kalam''[email protected]'250002020-07-14
5'Amit''Khanna'180002019-01-25

The following query retrieves the unique FirstName values.

SQL Script: Distinct Columns
SELECT DISTINCT FirstName FROM Employee;
FirstName
'John'
'James'
'Neena'
'Lex'
'Amit'
'Abdul'

The following query retrieves the unique combination of FirstName and LastName values.

SQL Script: Distinct Columns
SELECT DISTINCT FirstName, LastName FROM Employee;
FirstNameLastName
'John''King'
'James''Bond'
'Neena''Kochhar'
'Lex''De Haan'
'Amit''Patel'
'Abdul''Kalam'
'Amit''Khanna'

The following counts the unique EmpId.

SQL Script: Count Distinct Values
SELECT count(DISTINCT EmpId) FROM Employee;
count(DISTINCT EmpId)
6