Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

What's wrong with this query:

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

It works without the WHERE clause. I've seemed to have forgotten my SQL...

1 Answer

0 votes
by (40.7k points)

MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail. Assuming your id column is unique or primary key:

If you want to insert a new row with ID 1 then you use the below query:

INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);

But, If want to change the weight/desiredWeight values for an existing row with ID 1 then, use the below query:

UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;

If you are trying to use INSERT .. ON DUPLICATE KEY syntax then, do like this:

INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

Or do this:

INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

Note: If the id column is an autoincrement column then you might as well omit it from your INSERT all together and let MySQL increment it as normal.

Related questions

0 votes
2 answers
0 votes
2 answers
asked Jul 22, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
asked Jan 6, 2021 in SQL by Appu (6.1k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...