Home > Database > Mysql Tutorial > How to Correctly Update Rows in MySQL Using CASE for Value Assignment?

How to Correctly Update Rows in MySQL Using CASE for Value Assignment?

Mary-Kate Olsen
Release: 2024-11-14 10:30:02
Original
271 people have browsed it

How to Correctly Update Rows in MySQL Using CASE for Value Assignment?

Updating Rows in MySQL Using CASE for Value Assignment

In order to update specific rows in a MySQL database using the CASE WHEN statement, the correct syntax must be followed. The provided query, which attempts to update prices based on ID values, demonstrates an incorrect usage of the CASE statement.

To resolve this, the correct update query should be as follows:

UPDATE ae44
SET price =
CASE
    WHEN ID = 'AT259793380' THEN
        '500'
    WHEN ID = 'AT271729590' THEN
        '600'
    WHEN ID = 'AT275981020' THEN
        '700'
END;
Copy after login

In this corrected query, note that:

  • The CASE WHEN statement is properly structured with individual WHEN clauses.
  • The assignment of the new value is done using := syntax.
  • The query ends with a semicolon (;).

Updating rows using CASE statement can be useful when assigning different values based on specific conditions. However, it's important to note that the provided query will update prices for all records, regardless of their ID. If the goal is to update only the specific IDs mentioned in the query, the following approach can be used:

UPDATE ae44
JOIN (
    SELECT 'AT259793380' AS oldval, '500' AS newval
    UNION ALL
    SELECT 'AT271729590' AS oldval, '600' AS newval
    UNION ALL
    SELECT 'AT275981020' AS oldval, '700' AS newval
) q ON ae44.id = q.oldval
SET price = q.newval;
Copy after login

The above is the detailed content of How to Correctly Update Rows in MySQL Using CASE for Value Assignment?. 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