How to fix ‘Error Code: 2013 Lost connection to MySQL server during query’

Content migrations usually involve running complex MySQL queries that take a long time to complete. I’ve found the WordPress wp_postmeta table especially troublesome because a site with tens of thousands of posts can easily have several hundred thousand postmeta entries.

If your query ends up taking more than a few minutes to complete, you may encounter the following error:

Error Code: 2013. Lost connection to MySQL server during query

This happens because the connection between your MySQL client and database server times out. Essentially, it took too long for the query to return data so the connection gets dropped. The MySQL documentation suggests increasing the net_read_timeout or connect_timeout values on the server. If this doesn’t solve the problem, you may need to increase your MySQL client’s timeout values.

MySQL Workbench

You can edit the SQL Editor preferences in MySQL Workbench:

  1. In the application menu, select Edit > Preferences > SQL Editor.
  2. Look for the MySQL Session section and increase the DBMS connection read time out value.
  3. Save the settings, quite MySQL Workbench and reopen the connection.

Navicat

How to edit Navicat preferences:

  1. Control-click on a connection item and select Connection Properties > Edit Connection.
  2. Select the Advanced tab and increase the Socket Timeout value.

Command line

On the command line, use the connect_timeout.

Python script

If you’re running a query from a Python script, use the connection argument:
con.query('SET GLOBAL connect_timeout=6000')