SQL UNION

SQL UNION can be  used to combine the result  two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

Syntax

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

MySQL Table – user1

+—-+——+
| id | name |
+—-+——+
|  1 | AAAA |
|  2 | BBBB |
|  3 | CCCC |
|  4 | DDDD |
+—-+——+

MySQL Table – user2

+—-+——+
| id | name |
+—-+——+
|  1 | PPPP |
|  2 | QQQQ |
|  3 | RRRR |
|  4 | RRRR |
+—-+——+

Example

mysql> SELECT * FROM user1 UNION SELECT * FROM user2 ;
+—-+——+
| id | name |
+—-+——+
|  1 | AAAA |
|  2 | BBBB |
|  3 | CCCC |
|  4 | DDDD |
|  1 | PPPP |
|  2 | QQQQ |
|  3 | RRRR |
|  4 | RRRR |
+—-+——+
8 rows in set (0.00 sec)


Share