Insert with a Select query in MySQL

MySQLMySQLi Database

For Insert with SELECT query, the syntax is as follows −

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

Let us first create a table −

mysql> create table DemoTable1603
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 101,'John',45;
Query OK, 1 row affected (0.17 sec)
Records: 1  Duplicates: 0  Warnings: 0
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 102,'Adam',76;
Query OK, 1 row affected (0.11 sec)
Records: 1  Duplicates: 0  Warnings: 0
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 103,'Bob',67;
Query OK, 1 row affected (0.31 sec)
Records: 1  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1603;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|       101 | John        |           45 |
|       102 | Adam        |           76 |
|       103 | Bob         |           67 |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)
raja
Published on 16-Dec-2019 12:08:01
Advertisements