HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Calling SELECT DISTINCT on multiple columns

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
distinctcolumnsmultipleselectcalling

Problem

I am unclear on exactly on,

SELECT DISTINCT col1, col2, ...
FROM table_name


When called on one column it gives back only distinct values of that column. What happens when we use it with multiple columns and should we ever do this?

Solution

How does this work exactly?

It gives you distinct combinations of all the expression in the SELECT list.

SELECT DISTINCT col1, col2, ... 
FROM table_name ;


is also equivalent to:

SELECT col1, col2, ... 
FROM table_name 
GROUP BY  col1, col2, ... ;


Another way to look at how it works - probably more accurate - is that it acts as the common bare SELECT (ALL) and then removes any duplicate rows. See Postgres documentation about SELECT: DISTINCT clause.


Should we ever do this?

Of course. If you need it, you can use it.

Code Snippets

SELECT DISTINCT col1, col2, ... 
FROM table_name ;
SELECT col1, col2, ... 
FROM table_name 
GROUP BY  col1, col2, ... ;

Context

StackExchange Database Administrators Q#199771, answer score: 11

Revisions (0)

No revisions yet.