Perform multiple inserts with INSERT INTO SELECT and UNION in MySQL

MySQLMySQLi Database

To perform multiple inserts, the syntax is as follows −

insert into yourTableName(yourColumnName1,yourColumnName2,yourColumnName3,..N)
   select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N
   union
   select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N
.
.
N

To understand the above syntax, let us create a table −

mysql> create table DemoTable1936
   (
   StudentId int,
   StudentName varchar(20),
   StudentCountryName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1936(StudentId,StudentName,StudentCountryName)
   select 1001 as StudentId,'Chris' as StudentName,'US' as StudentCountryName
   union
   select 1002 as StudentId,'Robert' as StudentName,'UK' as StudentCountryName
   union
   select 1003 as StudentId,'David' as StudentName,'AUS' as StudentCountryName;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1936;

This will produce the following output −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
|      1001 | Chris       |               US   |
|      1002 | Robert      |               UK   |
|      1003 | David       |              AUS   |
+-----------+-------------+--------------------+
3 rows in set (0.00 sec)
raja
Published on 30-Dec-2019 07:50:35
Advertisements