patternsqlMinor
Does update lock the row or the entire table?
Viewed 0 times
theupdateentiredoesrowtablelock
Problem
Basic question: When I update a row in a database table, does it lock the current row or the entire table?
I am using MySQL. When I update column which is not unique.
Is the locking different from one database engine to another? I have read this article but I am still confused.
I am using MySQL. When I update column which is not unique.
Is the locking different from one database engine to another? I have read this article but I am still confused.
Solution
The links go into gory details, but this question seems to need a simple yes/no answer.
For
For
Think of it this way -- It locks every row it had to look at.
-
No index on the column -- It had to check every row, so all rows are locked. That effectively locks the entire table.
-
-
In between... A non-unique
PS: the
Some other vendors have different index definitions, and some do have "table locks". Some "escalate" a bunch of row locks to a "table lock".
Bottom line:
For
ENGINE=MyISAM or MEMORY, the only lock is a table lock.For
ENGINE=InnoDB:Think of it this way -- It locks every row it had to look at.
-
No index on the column -- It had to check every row, so all rows are locked. That effectively locks the entire table.
-
UNIQUE index on the column -- Only one row need be touched, hence, locked.-
In between... A non-unique
INDEX on the column -- It must lock all the rows with that value. (Possibly the 'next' row will get locked, too.)PS: the
PRIMARY KEY is a UNIQUE index in MySQL.Some other vendors have different index definitions, and some do have "table locks". Some "escalate" a bunch of row locks to a "table lock".
Bottom line:
- Add an
INDEX, eitherUNIQUEor not, as appropriate.
- If you need to look at the row before potentially
UPDATEingit, use a transaction andSELECT ... FOR UPDATE.
Context
StackExchange Database Administrators Q#271197, answer score: 5
Revisions (0)
No revisions yet.