SELECT DISTINCT Statement

DISTINCT

DISTINCT clause is used to remove the duplicate records from result set, The DISTINCT clause is used only with SELECT statement.

Syntax

SELECT DISTINCT [ColumnNames]

FROM TableName

We will start with an example, we would like to display the column CardType on table CreditCard, This will proceed as:

SELECT [CardType]
FROM [Sales].[CreditCard]

Distinct_01

This query will return 19118 rows.

You’ve noticed that there are duplicates in the result.

Using DISTINCT on single column

DISTINCT clause allows us to eliminate duplicates in the result set.

SELECT DISTINCT [CardType]
FROM [Sales].[CreditCard]

Distinct_02

This query will return 4 rows.

Using DISTINCT on multiple columns

In the combination of multiple columns, DISTINCT eliminates the rows where all the selected rows are identical.

SELECT DISTINCT [CardType], [ModifiedDate]
FROM [Sales].[CreditCard]

Distinct_03

Note:

  • In SQL Server the DISTINCT clause doesn’t ignore NULL values. So when using the DISTINCT clause use NOT NULL functions to remove NULLS.
  • If possible, avoid using DISTINCT because DISTINCT impacts the performances.

Reference: [www.SQLServerLog.com]

You may also like

You may also like...

Leave a Reply