SELECT UNION as DISTINCT

user1124535 picture user1124535 · Jan 9, 2012 · Viewed 45.7k times · Source

How do I perform a DISTINCT operation on a single column after a UNION is performed?

T1
--
ID Value 
1  1
2  2
3  3

T2
--
ID Value
1  2
4  4
5  5


I am trying to return the table:

ID Value
1  1
2  2
3  3
4  4
5  5

I tried:

SELECT DISTINCT ID, Value 
FROM (SELECT*FROM T1 UNION SELECT*FROM T2) AS T3

This does not seem to work.

Answer

Bohemian picture Bohemian · Jan 9, 2012

Why are you using a sub-query? This will work:

SELECT * FROM T1
UNION
SELECT * FROM T2

UNION removes duplicates. (UNION ALL does not)