Home > Database > Mysql Tutorial > MySQL UPDATE with CASE: Why Does it Update All Rows and How to Fix It?

MySQL UPDATE with CASE: Why Does it Update All Rows and How to Fix It?

Susan Sarandon
Release: 2024-12-01 07:52:14
Original
291 people have browsed it

MySQL UPDATE with CASE: Why Does it Update All Rows and How to Fix It?

MySQL Update with CASE: Unexpected Behavior and Solution

When utilizing the CASE statement in MySQL UPDATE queries, it's important to understand its impact on data. In the provided example, the original query intended to update specific rows based on their id field. However, the query unexpectedly updated all 25 million rows, introducing NULL values.

This behavior stems from the nature of the CASE statement. Without an ELSE clause, MySQL interprets any missing conditions as equaling NULL. Therefore, all rows that did not match the specified id values were updated with NULL for the uid column.

To resolve this issue and selectively update specific rows while preserving other data, consider using an ELSE clause to provide a default value or maintain the existing value. Additionally, specify the rows that need to be updated using the WHERE clause.

For instance, the following modified query addresses these concerns:

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)
Copy after login

This query now updates only rows with id values of 1, 2, and 3, leaving the remaining rows unaffected. By combining the CASE statement with the ELSE clause and WHERE clause, you can efficiently update specific rows without inadvertently modifying other data in the table.

The above is the detailed content of MySQL UPDATE with CASE: Why Does it Update All Rows and How to Fix It?. 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