Waiting for metadata lock

A “Waiting for metadata lock” state occurs when a database session tries to change a table’s structure (like ALTER TABLE or DROP TABLE) while another session is still using that table. To keep the data consistent, the database prevents any structural changes until all active transactions on that table are finished.
Why This Happens
  • Active Transactions: A session started a transaction (even just a SELECT statement) and hasn’t committed or rolled it back yet.
  • Long-Running Queries: A heavy report or slow data modification is still running on the target table.
  • Unclosed Connections: Applications or ORMs (like Django) may leave connections open in a “Sleep” state while still holding a lock.
How to Fix It
Prevention Tips
  • Set Timeouts: Lower the lock_wait_timeout to prevent structural changes from hanging indefinitely.
  • Commit Often: Ensure your application code always commits or rolls back transactions, especially after SELECT statements in non-autocommit mode.
  • Batch DDL: Perform structural changes during low-traffic periods to minimize the chance of conflicting with active users.

Nishant Vaity

Knowledgeable and skilled Technology Lead with an ability of software development and supervision. Possess a Bachelor of Science (BS) in Information Technology along with 11+ years of experience with hands-on coding and team management. By profession, I am a Software Engineer, Technology Mentor & Entrepreneur. Passionate about the technologies I use and always eager to share & learn more from that passion.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.