Home > Database > Mysql Tutorial > How to Correctly Insert or Update Data in MySQL Using INSERT and WHERE Clauses?

How to Correctly Insert or Update Data in MySQL Using INSERT and WHERE Clauses?

Susan Sarandon
Release: 2025-01-19 06:45:10
Original
165 people have browsed it

How to Correctly Insert or Update Data in MySQL Using INSERT and WHERE Clauses?

MySQL data insertion and update: Correct usage of INSERT and WHERE clauses

MySQL's INSERT statement does not support the WHERE clause. Therefore, the following query:

<code class="language-sql">INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;</code>
Copy after login

will fail.

Insert new line

If you are trying to insert a new row with ID 1, use the following query:

<code class="language-sql">INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);</code>
Copy after login

Update existing row

If you want to change the weight/desiredWeight value of an existing row with ID 1, use the UPDATE statement:

<code class="language-sql">UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;</code>
Copy after login

INSERT ... ON DUPLICATE KEY Grammar

You can also use the INSERT ... ON DUPLICATE KEY syntax:

<code class="language-sql">INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145;</code>
Copy after login

or:

<code class="language-sql">INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145;</code>
Copy after login

Self-added column

If the id column is an auto-increment column, you can completely omit the INSERT column in the query: id

<code class="language-sql">INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );</code>
Copy after login
MySQL will automatically increment the

value. id

The above is the detailed content of How to Correctly Insert or Update Data in MySQL Using INSERT and WHERE Clauses?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template