Computer >> Computer tutorials >  >> Programming >> MySQL

Insert record using MySQL SELECT?


To insert a record with select, use INSERT INTO SELECT statement. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(101,'Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1 values(NULL,'Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1 values(NULL,NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(102,'David');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | Chris     |
| NULL | Bob       |
| NULL | NULL      |
|  102 | David     |
+------+-----------+
4 rows in set (0.00 sec)

Here is the query to create the second table.

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

Here is the query to insert record using SELECT statement −

mysql> insert into DemoTable2
   -> select Id,FirstName from DemoTable1
   -> where Id IS NOT NULL and FirstName IS NOT NULL;
Query OK, 2 rows affected (0.17 sec)
Records: 2 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | Chris       |
|       102 | David       |
+-----------+-------------+
2 rows in set (0.00 sec)