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


  

Section Menu 

Are you a University or College bookstore and want to order multiple books?  Email us at alphapress@hotmail.com or call us at 518-250-3890.  We will be happy to talk to you.  

Are you a professor and you need a sample copy?  We will be happy to send you a pdf or printed copy!  Email us at alphapress@hotmail.com.

Are you outside the United States?  We can ship multiple books worldwide in most countries.

  

 

 

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: