How to create a new table from merging two tables with MySQL union?


The following is the syntax to merge two tables using MySQL union

create table yourTableName
(
   select *from yourTableName1
)
UNION
(
   select *from yourTableName2
);

To understand the above syntax, let us create a table. The query to create first table is as follows

mysql> create table Old_TableDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)

The query to create second table is as follows

mysql> create table Old_TableDemo2
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the first table using insert command. The query is as follows −

mysql> insert into Old_TableDemo(UserName) values('John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into Old_TableDemo(UserName) values('Carol');
Query OK, 1 row affected (0.15 sec)

Display all records from the first table using select statement. The query is as follows −

mysql> select *from Old_TableDemo;

The following is the output

+--------+----------+
| UserId | UserName |
+--------+----------+
|      1 | John     |
|      2 | Carol    |
+--------+----------+
2 rows in set (0.00 sec)

Now you can insert some records in the second table using insert command. The query is as follows −

mysql> insert into Old_TableDemo2(UserName) values('Larry');
Query OK, 1 row affected (0.22 sec)
mysql> insert into Old_TableDemo2(UserName) values('Sam');
Query OK, 1 row affected (0.10 sec)

Display all records from the second table using select statement. The query is as follows −

mysql> select *from Old_TableDemo2;

The following is the output

+--------+----------+
| UserId | UserName |
+--------+----------+
|      1 | Larry    |
|      2 | Sam      |
+--------+----------+
2 rows in set (0.00 sec)

Here is the query to create a new table from merging two tables with union

mysql> create table UserTableDemo
   -> (
   -> select *from Old_TableDemo
   -> )
   -> UNION
   -> (
   -> select *from Old_TableDemo2
   -> );
Query OK, 4 rows affected (1.18 sec)
Records: 4 Duplicates: 0 Warnings: 0

Let us check the table records of new table. The query is as follows −

mysql> select *from UserTableDemo;

The following is the output

+--------+----------+
| UserId | UserName |
+--------+----------+
|      1 | John     |
|      2 | Carol    |
|      1 | Larry    |
|      2 | Sam      |
+--------+----------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements