views:

864

answers:

1

suppose I have two columns of integers, A and B. Now I want distinct values from these, meaning if both A and B have 1, I want 1 only once.

Note: I am NOT interested in getting distinct rows. I just want to get unique integer values from this table which could either be in A or B

I could insert values of A and B in one column of some temp table and do a select distinct over that column.

Anything more sophisticated (performancewise)?

+5  A: 

Something like that should work, I think:

select all the distinct A's, then all the distinct B' UNION ALL these two sets select DISTINCT from that unionized result set SELECT DISTINCT * FROM ( SELECT DISTINCT A FROM YourTable UNION ALL SELECT DISTINCT B FROM YourTable )

With Lukáš' help, you can simply write:

     SELECT A FROM YourTable
     UNION 
     SELECT B FROM YourTable

since as he rightfully points out, the regular UNION returns no duplicates. You don't even need to have a DISTINCT clause on your individual SELECTs - quite ingenious! Thanks, Lukáš!

Marc

marc_s
If you change `UNION ALL` to `UNION`, you can avoid the outer query as `UNION` itself will return only distinct values.
Lukáš Lalinský
@Lukas: very clever indeed - and totally right! :-)
marc_s
And you don't even need `DISTINCT` on the inner queries either.
Lukáš Lalinský
ah, interesting - that's new to me though - let me check - indeed! Interesting - so the UNION totally "distinctifies" the result set - thanks!
marc_s