This section discusses internal locking; that is, locking performed within the MySQL server itself to manage contention for table contents by multiple sessions. This type of locking is internal because it is performed entirely by the server and involves no other programs. For locking performed on MySQL files by other programs, see Section 10.11.5, “External Locking”.
MySQL uses row-level
locking for InnoDB tables to support
simultaneous write access by multiple sessions, making them
suitable for multi-user, highly concurrent, and OLTP
applications.
To avoid deadlocks when
performing multiple concurrent write operations on a single
InnoDB table, acquire necessary locks at
the start of the transaction by issuing a SELECT ...
FOR UPDATE statement for each group of rows expected
to be modified, even if the data change statements come later
in the transaction. If transactions modify or lock more than
one table, issue the applicable statements in the same order
within each transaction. Deadlocks affect performance rather
than representing a serious error, because
InnoDB automatically
detects
deadlock conditions by default and rolls back one of the
affected transactions.
On high concurrency systems, deadlock detection can cause a
slowdown when numerous threads wait for the same lock. At
times, it may be more efficient to disable deadlock detection
and rely on the
innodb_lock_wait_timeout
setting for transaction rollback when a deadlock occurs.
Deadlock detection can be disabled using the
innodb_deadlock_detect
configuration option.
Advantages of row-level locking:
Fewer lock conflicts when different sessions access different rows.
Fewer changes for rollbacks.
Possible to lock a single row for a long time.
MySQL uses table-level
locking for MyISAM,
MEMORY, and MERGE
tables, permitting only one session to update those tables at
a time. This locking level makes these storage engines more
suitable for read-only, read-mostly, or single-user
applications.
These storage engines avoid deadlocks by always requesting all needed locks at once at the beginning of a query and always locking the tables in the same order. The tradeoff is that this strategy reduces concurrency; other sessions that want to modify the table must wait until the current data change statement finishes.
Advantages of table-level locking:
Relatively little memory required (row locking requires memory per row or group of rows locked)
Fast when used on a large part of the table because only a single lock is involved.