nick nick - 22 days ago 12
MySQL Question

MySQL update CASE WHEN/THEN/ELSE

I am trying to update a LARGE MyISAM table (25 million records) using a CLI script. The table is not being locked/used by anything else.

I figured instead of doing single UPDATE queries for each record, I might as well utilize the CASE feature.

The

id
field is PRIMARY. I suspect the following query should take milliseconds.

UPDATE `table` SET `uid` = CASE
WHEN id = 1 THEN 2952
WHEN id = 2 THEN 4925
WHEN id = 3 THEN 1592
END


Lo and behold, the query hogs the CPU and doesn't finish in forever.

Then, to my surprise, I found out that the query is updating all the 25 million rows, placing a NULL on rows that I didn't specify.

What is the purpose of that? Can I just do a MASS update on specific rows without updating 25 million rows every time I execute this query? Or do I have to do individual updates and then commit?

rs. rs.
Answer

Try this

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)