Home > Database > Mysql Tutorial > body text

Why is My MySQL CASE WHEN Update Slow and Affecting All Rows?

Susan Sarandon
Release: 2024-11-25 11:21:11
Original
871 people have browsed it

Why is My MySQL CASE WHEN Update Slow and Affecting All Rows?

MySQL Update Using CASE WHEN/THEN/ELSE

Problem:

When attempting to update a large MyISAM table using a CASE WHEN/THEN/ELSE statement, the query monopolizes the CPU and takes an excessive amount of time to complete. Moreover, it updates all rows in the table, even those not specified in the query.

Explanation:

The reason for this behavior is that MySQL interprets the CASE statement as updating all rows in the table. Rows that do not match any of the WHEN conditions are assigned a NULL value.

Solution:

To avoid this issue, the query should be modified to include an ELSE statement that assigns the existing value to rows that do not match any of the WHEN conditions. Additionally, a WHERE clause can be used to limit the update to only the specified rows.

The corrected query:

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

The above is the detailed content of Why is My MySQL CASE WHEN Update Slow and Affecting All Rows?. 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