How can we use WHERE clause with MySQL INSERT INTO command?


We can use conditional insert i.e. WHERE clause with INSERT INTO command in the case of new row insertion. It can be done with following ways −

With the help of dummy table

In this case, we insert the value from dummy table along with some conditions. The syntax can be as follows −

INSERT INTO table_name(column1,column2,column3,…) Select value1,value2,value3,… From dual WHERE [conditional predicate];

Example

mysql> Create table testing(id int, item_name varchar(10));
Query OK, 0 rows affected (0.15 sec)

mysql> Insert into testing (id,item_name)Select 1,'Book' From Dual Where 1=1;
Query OK, 1 row affected (0.11 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+------+-----------+
| id   | item_name |
+------+-----------+
| 1    | Book      |
+------+-----------+

1 row in set (0.00 sec)

In the example above, we have created a table ‘testing’ and for inserting rows into it we have used dummy table dual with a condition. If the condition is true MySQL insert the row into table otherwise not.

With the help of same structure table

If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement.

mysql> Insert into dummy1(id,name)select id, name from dummy Where id =1;
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> select * from dummy;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
| 2    | Aarav |
+------+--------+

2 rows in set (0.00 sec)

mysql> select * from dummy1;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
+------+--------+

1 row in set (0.00 sec)

Here in the example above, we have inserted the values in table ‘dummy1’, having the same structure as table ‘dummy’, with a condition to insert only that row where ‘id = 1’.

Updated on: 20-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements