Mysql Locks

suggest change

Table locks can be an important tool for ENGINE=MyISAM**, but are rarely useful for ENGINE=InnoDB**. If you are tempted to use table locks with InnoDB, you should rethink how you are working with transactions.

MySQL enables client sessions to acquire table locks explicitly for the purpose of cooperating with other sessions for access to tables, or to prevent other sessions from modifying tables during periods when a session requires exclusive access to them. A session can acquire or release locks only for itself. One session cannot acquire locks for another session or release locks held by another session.

Locks may be used to emulate transactions or to get more speed when updating tables. This is explained in more detail later in this section.

LOCK TABLES table_name READ;
LOCK TABLES table_name WRITE;

One LOCK TABLES can lock several tables. Each table gets either READ or WRITE, not both.

Example (READ LOCK):

LOCK TABLES table_name READ;

Example (WRITE LOCK):

LOCK TABLES table_name WRITE;

SHOW OPEN TABLES shows an In_use count. It is a weak way to see locks. performance_schema data locks are clearer on MySQL 8.0.

SHOW OPEN TABLES;

To flush/remove all locks, use following command:

UNLOCK TABLES;

EXAMPLE:

LOCK TABLES products WRITE;
INSERT INTO products (id, product_name)
SELECT id, old_product_name FROM old_products;
UNLOCK TABLES;

A WRITE lock lets this session read and write products. Other sessions cannot read or write it until UNLOCK TABLES. The INSERT ... SELECT also reads old_products, so that table must be locked too, or the statement errors:

LOCK TABLES products WRITE, old_products READ;
LOCK TABLES products READ;
SELECT id, product_name FROM products;
UNLOCK TABLES;

A READ lock lets this session and other sessions read. Nobody, including this session, can write products until the lock is released. The INSERT that used to be in this example would fail.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents