How to add a where clause in a MySQL Insert statement?


You need to use UPDATE statement for this.

The syntax is as follows

update yourTableName
set yourColumnName1=yourValue1,yourColumnName2=yourValue2,....N
where yourCondition;

Let us create a table for our example

mysql> create table addWhereClauseDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(30),
   -> StudentPassword varchar(40)
   -> );
Query OK, 0 rows affected (0.45 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('John','John123456');
Query OK, 1 row affected (0.14 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('Carol','99999');
Query OK, 1 row affected (0.24 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('Bob','OO7Bob');
Query OK, 1 row affected (0.16 sec)
mysql> insert into addWhereClauseDemo(StudentName,StudentPassword) values('David','David321');
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from addWhereClauseDemo;

The following is the output

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
| 1         | John        | John123456      |
| 2         | Carol       | 99999           |
| 3         | Bob         | OO7Bob          |
| 4         | David       | David321        |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)

Here is the query to add a where clause i.e. updating the records

mysql> update addWhereClauseDemo
-> set StudentName='Maxwell',StudentPassword='Maxwell44444' where StudentId=4;
Query OK, 1 row affected (0.18 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again.

The query is as follows

mysql> select *from addWhereClauseDemo;

The following is the output

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
| 1         | John        | John123456      |
| 2         | Carol       | 99999           |
| 3         | Bob         | OO7Bob          |
| 4         | Maxwell     | Maxwell44444    |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements