views:

41

answers:

1

How to rewrite this query NOT to use UNION (UNION ALL) clause:

SELECT
  c
FROM a
UNION
SELECT
 c
FROM b

expected result (recordset should be the same):

SELECT
  c
FROM ....
+4  A: 

To get the same results as your query above, you can do this:

SELECT COALESCE(a.c, b.c) AS c
FROM a
FULL OUTER JOIN b
    ON b.c = a.c

However, this will give you the same results as a UNION which is not quite the same as a UNION ALL (as duplicates will be removed). To do a UNION all, you'd need to do the same but have the join condition fail:

SELECT COALESCE(a.c, b.c) AS c
FROM a
FULL OUTER JOIN b
    ON 1 = 0

In either case, I'm not sure it would be much faster than doing it using UNION.

Bennor McCarthy
Bennor, it's cool! (1 = 0) - the best! performance is not an issue in this question. i could ask this question from other side: "how to avoid of using FULL (OUTER) JOIN..." i think, it's nothing to add to your answer.
igor