I am trying to recall some of the interview questions that I was being asked during my job hunting and would like to share some studies or findings which I read from the experts regarding these questions. The first one that I remember is the differences between UNION and UNION ALL.
I believe in many cases we do use both of these commands in our queries. And, what are their differences and in term of performance which one is better?
UNION command is used in the queries to select data from two or more tables similarly to JOIN command, except UNION command selected columns need to be same data types and same number of columns to be selected. It returns the distinct data of both tables. It does the SELECT DISTINCT on the results set.
UNION ALL command is same as the UNION command except it returns all the data from the selected tables. In other words, UNION ALL includes duplicated rows.
However, the UNION ALL gives the faster results when we execute the queries. You can check it from the execution plan to compare both. Reason is UNION command will do the filtering during the execution. If you are sure that your return results are unique, it would be a good idea to use UNION ALL for better performance.