lbj99
lbj99

Reputation: 3

Does a general InnoDB UPDATE lock the entire table and block incoming specific UPDATEs?

Suppose I ran this statement:

UPDATE Employees set country='AU'

On an InnoDB table, Employees, with about 10 million rows.

This table is also actively being updated by other users through SQL queries like the one below:

E.g. a User, ID = 20, changes their country to NZ:

UPDATE Employees set country='NZ' where id = 20
  1. In that case, will any further updates to this table block until the general update completes?
  2. If so, is there a way to allow specific updates and the general update to run concurrently, if they are not updating the same row? (To clarify what I mean here: suppose the general update finishes updating Employees with Id 1 - 50, and is now updating Emplyoees 51 - ~10 million, a singular update on Employee with id of 20 should go through without waiting for the general update to finish)

Upvotes: 0

Views: 2194

Answers (2)

Rick James
Rick James

Reputation: 142540

Let's "think out of the box"...

Have 2 columns. One with the counter; one (dy) with the DATE of the last increment of the counter. Then make the bumping of the counter a little more complex -- namely to reset it to 1 if the date is before today. Also (always) update the date to CURDATE().

Something like

UPDATE t
    SET counter = IF (dy = CURDATE(), counter + 1, 1),
        dy = CURDATE()
    WHERE id = 123

This eliminates the big, nightly, update.

To fetch the counter for the current day,

SELECT  IF (dy = CURDATE(), counter, 0) AS counter
    WHERE id = 123;

This technique also avoids having to run the big update at exactly midnight. And a second-order "bug" if the machine happened to be down at midnight (and the update fails to get run for the day).

Upvotes: 0

Shadow
Shadow

Reputation: 34294

  1. Yes, the first update will place exclusive locks on all records in the table, blocking other queries from updating it. The locks are held until the transaction is commited.

  2. No. The locks are held while the transaction is running and a released when the transaction is commited. You may want to update the table in chuncks, rather than in one big bang, avoiding the first update locking the entire table. Or execute the update outside of business hours, if possible.

Upvotes: 0

Related Questions