Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This doesn't work:

INSERT INTO users (username, password) VALUES ("Jack","123") WHERE id='1';

Any ideas how to narrow insertion to a particular row by id?

like image 961
Zack Avatar asked Feb 28 '10 03:02

Zack


People also ask

Can we use WHERE clause with insert statement in MySQL?

Copying specific rows from a table: We can copy specific rows from a table to insert into another table by using WHERE clause with the SELECT statement. We have to provide appropriate condition in the WHERE clause to select specific rows.

Can WHERE clause be used with insert statement?

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.

Can we use select in insert statement?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

How do you insert data into MySQL?

To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.


2 Answers

A conditional insert for use typically in a MySQL script would be:

insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
  from dual
 where [conditional predicate];

You need to use dummy table dual.

In this example, only the second insert-statement will actually insert data into the table:

create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
|    2 |
+------+
1 row in set (0.00 sec)
like image 138
gerrit_hoekstra Avatar answered Oct 24 '22 17:10

gerrit_hoekstra


In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?

update users set username='JACK' and password='123' WHERE id='1';
like image 29
broschb Avatar answered Oct 24 '22 17:10

broschb