5

If my table looks like this:

id | colA   | colB | colC
===========================
1  | red    | blue | yellow
2  | orange | red  | red
3  | orange | blue | cyan

What SELECT query do I run such that the results returned are:

blue, cyan, orange, red, yellow

Basically, I want to extract a collective list of distinct values across multiple columns and return them in alphabetical order.

I am not concerned with performance optimization, because the results are being parsed to an XML file that will serve as a cache (database is hardly updated). So even a dirty solution would be fine.

Thanks for any help!

2 Answers 2

8
(SELECT DISTINCT colA AS color FROM table) UNION
(SELECT DISTINCT colB AS color FROM table) UNION
(SELECT DISTINCT colC AS color FROM table)
ORDER BY color
Sign up to request clarification or add additional context in comments.

1 Comment

Using DISTINCT is optional, UNION returns distinct rows only.
3

Just do it the normal way:

create table new_tbl(col varchar(50));


insert into new_tbl(col)
select cola from tbl
union
select colb from tbl
union
select colc from tbl

Then sort:

select col from new_tbl order by col

Or if you don't want staging table, just do:

select cola as col from tbl
union
select colb from tbl
union
select colc from tbl
order by col

Note: UNION automatically remove all duplicates, if you want to include duplicates, change the UNION to UNION ALL

5 Comments

UNION only removes duplicates shared between the unioned tables. If either of the tables includes duplicates unique to its own sub-select, those duplicates won't be removed, you need SELECT DISTINCT or GROUP BY to do that.
Also not 100% sure, but I think that your ORDER BY col only applies to the last select, not the whole unioned result-set. You should use parenthesis around the select statements to clarify the purpose.
reko_t: on the contrary, each of those select, the duplicate in each of them are also removed across all of them
Ah, it seems that's the case, just tried it. Thanks for the correction.
reko_t: regarding ORDER BY. i've been programming with SQL for long, i've used MySQL, SQL Server, Postgresql. the ORDER BY applies on the whole UNIONed set

Your Answer

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.