AlphaPress Publishing
P.O. Box 5942 Albany, NY 12205
Tel: 518-250-3890
Email: alphapress@hotmail.com  


  
Click to buy this book from Amazon

Section Menu 

News

Pindaro is now working on a comprehensive book on SQL Server 2014.  For any comments you can email the author at alphapress@hotmail.com.

  

 

 

How to Use DISTINCT on Multiple Columns

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


Use DISTINCT on multiple columns

Finding unique customer names in various states

Discussion:

Experience indicates that DISTINCT works at its best when applied on a single column.  However, if we want to apply DISTINCT on multiple columns, we need to know exactly what to expect.  Let’s work with our customers table and go through some examples to fully understand this concept. 

Code Case 1:

If we run a simple SELECT statement such as:

SELECT firstname, state

FROM customers

WHERE (firstname="John") 

We will get four customers with a first name John.  Actually, these are all the Johns we have in our customers table. 

Result:

 

Code Case 2:

If we include the DISTINCT clause such as:

SELECT DISTINCT firstname, state

FROM customers

WHERE (firstname="John") 

We will get only three customers with a first name John.  This is because we told the database to return unique combinations of first names and states.  In the previous result set, we have two Johns in Texas.  When we use DISTINCT on both firstname and state, only one of the two appear.  This is a problem with DISTINCT on multiple columns.  We cannot exactly control which ones will appear in the result set, and we might get results that we haven’t intended.  So, be very careful when using DISTINCT on multiple columns. 

Result: