MySQL FLUSH TABLE – Resolving Active Locked Tables Issue

lockingMySQLmysql-5.6

If I execute these queries one by one, all fail except the first:

Query1 :

flush table tablename1 with read lock;

Works

Query2 :

flush table tablename2 with read lock;

Error : can't execute the given command because you have active locked tables mysql

If I execute, in below way, it works:

Query:

flush table tablename1,tablename2 with read lock;

What's happening inside?

Best Answer

This is because

flush table tablename1,tablename2 with read lock;

is contained within one transaction and

flush table tablename1 with read lock;

flush table tablename2 with read lock;

Is not.

In this second scenario the first table is locked for that session. That session can't acquire a second lock on another table because the session already has one table open. If you tried to access another different table by using a SELECT, within that same session, for example tablename2, that would also be refused.

MySQL [testlocks]> select * from tablename2;
ERROR 1100 (HY000): Table 'tablename2' was not locked with LOCK TABLES

So to make a long story short, by locking only one table you are saying that the current session only has access to that one table. At least that's how I understand MySQL's documentation.

Or you could just use

flush table tablename1,tablename2 with read lock;

as you already figured out and this is the syntax given by MySQL's documentation here