Table and Metadata Locks

Table Locks, Metadata Locks, and the Global Read Lock

LOCK TABLES products WRITE, categories READ takes explicit table locks: READ lets every session read but none write, WRITE gives the holder sole access, and UNLOCK TABLES or START TRANSACTION releases them. MyISAM needs them; InnoDB transactions make them unnecessary.

Every statement also takes a metadata lock (MDL) on each table it uses and holds it until its transaction ends, so no DDL can change the table underneath it. DDL needs an exclusive MDL, and a waiting exclusive request queues every later request behind it. In a test run, Session A updated one row of products and left its transaction open; B's ALTER TABLE products ADD isbn CHAR(13) then waited, and so did C's plain one-row SELECT, both shown in performance_schema.processlist as "Waiting for table metadata lock" until A committed. Before DDL on a busy table, look for old transactions in information_schema.INNODB_TRX, and lower lock_wait_timeout (a year by default) to a few seconds in the DDL session.

FLUSH TABLES WITH READ LOCK takes the global read lock: every write on the server waits until UNLOCK TABLES, and START TRANSACTION does not release it. Backup tools hold it briefly to record a consistent binary log position. LOCK INSTANCE FOR BACKUP is lighter: it blocks DDL and other file-changing statements but lets DML run (Administration covers backups).