How to Unlock Tables in MySQL: Syntax and Examples
To unlock tables in MySQL, use the
UNLOCK TABLES command. This releases all table locks held by the current session, allowing other sessions to access those tables again.Syntax
The UNLOCK TABLES command releases all locks that the current session holds on tables. It does not require any arguments.
Use it after you have locked tables with LOCK TABLES to allow other sessions to access those tables.
sql
UNLOCK TABLES;
Example
This example shows locking a table, performing a simple query, and then unlocking the tables to release the lock.
sql
LOCK TABLES employees WRITE; -- Perform operations on the employees table SELECT * FROM employees LIMIT 1; UNLOCK TABLES;
Output
Query OK, 0 rows affected (0.00 sec)
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | John | Doe |
+----+------------+-----------+
Query OK, 0 rows affected (0.00 sec)
Common Pitfalls
- Forgetting to unlock tables after locking them can cause other sessions to hang waiting for the lock to be released.
- Using
UNLOCK TABLESreleases all locks for the current session, so you cannot selectively unlock tables. - Locks are session-specific; unlocking tables in one session does not affect locks held by other sessions.
sql
/* Wrong: Forgetting to unlock tables */ LOCK TABLES employees WRITE; -- Operations here -- No UNLOCK TABLES; command /* Right: Always unlock after locking */ LOCK TABLES employees WRITE; -- Operations here UNLOCK TABLES;
Quick Reference
| Command | Description |
|---|---|
| LOCK TABLES table_name [READ|WRITE] | Locks a table for reading or writing. |
| UNLOCK TABLES | Releases all table locks held by the current session. |
| SHOW OPEN TABLES | Shows tables that are currently open and locked. |
| LOCK TABLES ... | Must be followed by UNLOCK TABLES to release locks. |
Key Takeaways
Use
UNLOCK TABLES to release all locks held by your session.Always unlock tables after locking to avoid blocking other sessions.
Locks are session-specific and do not affect other sessions.
You cannot unlock individual tables;
UNLOCK TABLES releases all locks at once.