6

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?

Evan Carroll
65.7k50 gold badges259 silver badges510 bronze badges
asked Mar 9, 2018 at 0:17
2
  • 4
    See: postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT Commented Mar 9, 2018 at 0:19
  • 3
    Unrelated, but: a common misconception that I see is that distinct (col1), col2 is something different than distinct col1, col2. The parentheses won't change anything Commented Mar 9, 2018 at 6:27

1 Answer 1

11

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.

answered Mar 9, 2018 at 0:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.