Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two UPDATE Commands - Performance?

If I want to update two rows in a MySQL table, using the following two command:

UPDATE table SET Col = Value1 WHERE ID = ID1

UPDATE table SET Col = Value2 WHERE ID = ID2`

I usually combine them into one command, so that I do not to have to contact the MySQL server twice from my C client:

UPDATE table SET Col = IF( ID = ID1 , Value1 , Value2) WHERE ID=ID1 OR ID=ID2

Is this really a performance gain?

Background Information: I am using a custom made fully C written high-performance heavily loaded webserver.

like image 351
Johannes Avatar asked Feb 05 '26 16:02

Johannes


1 Answers

The single server request is typically a good idea since the round trips between client and server are often the most costly part of many queries (as Will Hartung already pointed out).

However, it might be useful to examine the optimization of that particular query. The condition id = id1 or id = id2 sounds like it will use a range search (see OR Relations). I'm not completely sure, but might result in an index scan from ID1 to ID2, which could be expensive if they are logically "far" apart in the index. It may be more efficient to use the IN operator: where ID in (ID1, ID2). Or possibly use two individual statements.

like image 183
Mark Wilkins Avatar answered Feb 08 '26 04:02

Mark Wilkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!