I would like to temporarily lock a table to prevent other concurrent processes from making changes to it. The reason for this is that this table is going to be copied to a
Sorry for the long answer, but this will need to be answered in multiple parts.
1. On locking InnoDB tables with LOCK TABLES
in general
Using LOCK TABLES
with InnoDB does in fact work, and can be demonstrated with two instances of the MySQL CLI connected to the same server (denoted by mysql-1
and mysql-2
) in the below example. It should generally be avoided in any sort of production context because of the impact to clients, but sometimes it can be the only option.
Create a table and populate it with some data:
mysql-1> create table a (id int not null primary key) engine=innodb;
Query OK, 0 rows affected (0.02 sec)
mysql-1> insert into a (id) values (1), (2), (3);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
Lock the table:
mysql-1> lock tables a write;
Query OK, 0 rows affected (0.00 sec)
Try to insert from mysql-2
, which will hang waiting on the lock:
mysql-2> insert into a (id) values (4);
Now unlock the table from mysql-1
:
mysql-1> unlock tables;
Query OK, 0 rows affected (0.00 sec)
And finally mysql-2
unblocks and returns:
Query OK, 1 row affected (6.30 sec)
2. Using phpMyAdmin for testing
Your testing method using phpMyAdmin is invalid because phpMyAdmin does not maintain a persistent connection to the server between queries from its web interface. In order to use any sort of locking LOCK TABLES
, START TRANSACTION
, etc., you need to maintain a connection while the locks are held.
3. Locking all tables needed during work
The way that MySQL locks tables, once you have used LOCK TABLES
to explicitly lock anything, you will not be able to access any other tables that were not locked explicitly during the LOCK
... UNLOCK
session. In your above example, you need to use:
LOCK TABLES my_table WRITE, new_table WRITE, table2 READ;
(I am assuming table2
used in the subselect was not a typo.)
4. Atomic table swap using RENAME TABLE
Additionally, I should note that replacing the existing table using DROP TABLE
followed by RENAME TABLE
will cause a brief moment where the table does not exist, and this may confuse clients that expect it to exist. It is generally much better to do:
CREATE TABLE t_new (...);
<Populate t_new using some method>
RENAME TABLE t TO t_old, t_new TO t;
DROP TABLE t_old;
This will perform an atomic swap of the two tables.