Tutorialspoint

1 Answer
Ankith Reddy

To concatenate two tables, UNION ALL in MySQL. Let us create a table −

mysql> create table DemoTable1
   (
   Id int,
   FirstName varchar(20)
   );
Query OK, 0 rows affected (1.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(10,'John');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1 values(20,'Carol');
Query OK, 1 row affected (0.28 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

Output

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 10   | John      |
| 20   | Carol     |
+------+-----------+
2 rows in set (0.00 sec)

Create second table.

mysql> create table DemoTable2
   (
   Id int,
   FirstName varchar(20)
   );
Query OK, 0 rows affected (1.22 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(20,'David');
Query OK, 1 row affected (1.28 sec)
mysql> insert into DemoTable2 values(40,'Chris');
Query OK, 1 row affected (0.38 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

Output

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 20   | David     |
| 40   | Chris     |
+------+-----------+
2 rows in set (0.00 sec)

Following is the query to concatenate two tables −

mysql> select *from DemoTable1 where Id=20
   union all select *from DemoTable2 where Id=20;

Output

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 20   | Carol     |
| 20   | David     |
+------+-----------+
2 rows in set (0.43 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.