Saturday, February 18, 2012

Difference between Union and Union All

In SQL we have both UNION and UNION ALL.

Are there any differences?

Union simply returns all rows, however with no repetitions. So, in this sense, it works just like a set.

UNION ALL will return all rows, included any repeated ones.

So,

(1,2) (3,4) (4,5) UNION (1,2) (6,7) (8,9)
will return
(1,2) (3,4) (4,5)  (6,7) (8,9) 

while

(1,2) (3,4) (4,5) UNION ALL (1,2) (6,7) (8,9) 
will return
(1,2) (3,4) (4,5) (1,2) (6,7) (8,9) 

UNION ALL is obviously faster than UNION, since it does not do DISTINCT SORT, but please be careful, since their functionality is different.

No comments: