Pages

Thursday, February 7, 2013

UNION Example MySQL

There are 2 tables

Table A

id
1
2
3

Table B

id
1
2
3
4
5

Our job is to merge 2 tables to get following output

We fire our sql query as follows

SELECT  `a`.`id` AS `id` FROM `a` UNION SELECT `b`.`id` AS `id` FROM `b`
and get desired output

There are some rules that you need to follow in order to use the UNION operator:
  • The number of columns appears in the corresponding SELECT statements must be equal.
  • The columns appear in  the corresponding positions of each SELECT statement must have the same data type or at least convertible data type.
By default, the UNION operator eliminates duplicate rows from the result even if you don’t use DISTINCT keyword explicitly. Therefore it is said that UNION is the shortcut of UNION DISTINCT.
If you use UNION ALL explicitly, the duplicate rows, if available, remain in the result. The UNION ALL performs faster than the UNION DISTINCT.

No comments:

Post a Comment