Ask the Expert

Distinct values of more than one column

How do I see distinct values of more than one column in a single SQL command?

    Requires Free Membership to View

We've been getting a number of this type of question lately: short, and simple on the surface. Short questions are wonderful, because they leave more room for the answer. Simple questions are even better, as long as they aren't too simple.

In this case, there are two ways to do it.

select distinct 
       col1
     , col2 
  from daTable

This method uses the standard SQL keyword DISTINCT. All distinct combinations of values in two columns are shown. (It could be two, or 10, or even just one column.) The "distinctness" applies to the entire row produced by the query. Every result row is completely distinct.

select col1
     , col2 
  from daTable
group
    by col1
     , col2

This method uses the standard SQL keywords GROUP BY. All distinct combinations of values in two columns are shown. (It could be two, or 10, or even just one column.) The "distinctness" applies to the columns in the GROUP BY. Every result row will be completely distinct in those two columns.

If you wanted distinct rows by those two columns, but with additional columns as well, then the question was indeed not as simple as it first appeared. In that case, perhaps the answer DISTINCT is not a function (26 September 2005) may help.

This was first published in April 2007

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: