Which is faster? Multiple update queries in a cursor loop, or a single query?
Neither -- You need to present a 3rd option.
Option 1 is slow because it is going back and forth between the Stored Routine and the server. (This is not as bad as between the Client and Server, but it is still extra effort.)
Option 2 is slow because of the tmp table and subquery.
Option 3 is something like
UPDATE table2
JOIN table1 ON table1.id = table2.id
SET table2.column = 0
WHERE table1.column = 0;
(I assume id
is the PRIMARY KEY
in each table?)
Important: table1
needs INDEX(column)
.
See "multi-table update" in the online reference manual.
It depends on a lot of factors:
- your table definition
- your index definitions
- your transaction isolation level
- your general database load
- the available memory
- ...
If you have enough memory, processor power and temporary table space then your second statement should be the fastest, but with the drawback of having a lot of locking occurring at once.
Locks Set by Different SQL Statements in InnoDB
Running your first statement will probably incur less locking for all the other users, but then again depends on the transaction isolations levels of the users connected to the database.
Transaction Isolation Levels
As you can see there are a multitude of factors that can impact the execution of an update statement.
Without further details I would prefer to use the second statement for speed and your first statement would be used in a environment under load.
A similar question has been asked here:
How to update a (very) large table without locking in MySQL