14

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?

Zack
  • 151
  • 1
  • 1
  • 4
  • 3
    Downvoted. As it stands, either the title is wrong, or the accepted answer. Anyway, Google leads me here for *insert*, but the accepted answer is about *update*. – Stijn de Witt May 30 '17 at 11:45

8 Answers8

30

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';
broschb
  • 4,976
  • 4
  • 35
  • 52
15

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)
gerrit_hoekstra
  • 509
  • 6
  • 8
6

To add a WHERE clause inside an INSERT statement simply;

INSERT INTO table_name (column1,column2,column3)
SELECT column1, column2, column3 FROM  table_name
WHERE column1 = 'some_value'
Saty
  • 22,443
  • 7
  • 33
  • 51
Jonathan
  • 148
  • 5
  • 21
  • 1
    er, could you add some information as to what is going on here? Why does the insert need a WHERE? – Martin Sep 22 '15 at 17:53
2

I think you are looking for UPDATE and not insert?

UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1
jasonbar
  • 13,333
  • 4
  • 38
  • 46
2

Try this:

Update users
Set username = 'Jack', password='123'
Where ID = '1'

Or if you're actually trying to insert:

Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
2
INSERT INTO users (id,username, password) 
VALUES ('1','Jack','123')
ON DUPLICATE KEY UPDATE username='Jack',password='123'

This will work only if the id field is unique/pk (not composite PK though) Also, this will insert if no id of value 1 is found and update otherwise the record with id 1 if it does exists.

nawfal
  • 70,104
  • 56
  • 326
  • 368
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
1

For Empty row how we can insert values on where clause

Try this

UPDATE table_name SET username="",password="" WHERE id =""
Prasad MCN
  • 19
  • 3
0
UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

Martin
  • 22,212
  • 11
  • 70
  • 132
Rajeev
  • 442
  • 1
  • 5
  • 18