Home > Database > Mysql Tutorial > Why Does My MySQL INSERT Query Fail with a WHERE Clause?

Why Does My MySQL INSERT Query Fail with a WHERE Clause?

Barbara Streisand
Release: 2025-01-19 06:26:13
Original
608 people have browsed it

Why Does My MySQL INSERT Query Fail with a WHERE Clause?

MySQL INSERT query conflicts with WHERE clause

When trying to insert data into a MySQL database using a query similar to:

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

You may receive an error message if a WHERE clause is present. This is because MySQL's INSERT syntax does not support a WHERE clause.

New line

If the intention is to create a new row with a specified ID, the correct query would look like this:

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

Update existing row

To modify the value in an existing row, the UPDATE statement should be used:

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

INSERT ... ON DUPLICATE KEY

Alternatively, you can use the INSERT ... ON DUPLICATE KEY syntax to insert or update rows based on a unique or primary key:

<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

Use auto-increment column

If the id column in the table is set to auto-increment, you can omit it from the INSERT query and let MySQL handle the increment:

<code class="language-sql">INSERT INTO Users SET weight=160, desiredWeight=145</code>
Copy after login

The above is the detailed content of Why Does My MySQL INSERT Query Fail with a WHERE Clause?. 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