Lesson 23. Selecting Unique Values

This is not an advanced technique. However, it was a left-over toaster part from the basic section because it offended my sense of good order to have an odd number of lessons. So, I stuck it here.

Values in a table often repeat. This is especially true of data warehouse dimension tables because they are what is called denormalized. They are flat representations of relationships, so column values often repeat.

Sometimes whole records will repeat. Sometimes you need to perform an analysis on what makes a record unique.

The bottom line is, sometimes you just want to look at unique values. You can do that with the DISTINCT function.

DISTINCT is used in conjunction with the SELECT clause.

When you use DISTINCT, SQL Server will only retrieve unique values from the table. If you use more than one column, the result set will be the unique combination of all those columns.

DISTINCT Syntax

SELECT DISTINCT [column1], ...[columnN]
FROM TableName

Examples

DISTINCT With One Column

USE AdventureWorks2016

SELECT DISTINCT ProductID
FROM Sales.SalesOrderDetail

DISTINCT With More Than One Column

USE AdventureWorks2016

SELECT DISTINCT CarrierTrackingNumber, ProductID, SpecialOfferID
FROM Sales.SalesOrderDetail

Last updated