Common MySQL errors

We've gathered the common MySQL and MariaDB errors, from rejected logins to locks, large imports, encoding, and a full disk. For each error, you'll find the message as the server shows it, the common causes, how to check, and the fix, with commands for quick diagnosis further down the page.

Connecting to the server

  • ERROR 2002: Can't connect to local MySQL server through socket

    socket
    Common cause
    The service is stopped, or the client looks for the socket file at a different path than the server creates.
    How to check
    The systemctl status command for the service, and the query SHOW VARIABLES LIKE 'socket'.

    The message is followed by the socket file path and an operating system error number. According to the MySQL documentation, the error usually means the database server isn't running, or the client uses the wrong socket path. When you connect to localhost, the client uses a socket file rather than TCP, so the port doesn't matter here. Start the service if it's stopped, and make sure the socket setting is the same in the [mysqld] and [client] groups. For a quick test, connect with -h 127.0.0.1, which forces a TCP connection.

    systemctl commands

  • ERROR 2003: Can't connect to MySQL server on

    Port 3306
    Common cause
    The service is stopped, a firewall blocks port 3306, or the server listens only on 127.0.0.1.
    How to check
    The ss -tlnp command on the server, and a port test from the remote computer with nc -zv.

    The message names the server and the port, followed by an operating system error number in parentheses. According to the documentation, the network connection was refused: no server listens on that address and port, or something along the way blocks them. With bind-address set to 127.0.0.1, the server accepts TCP connections only from itself, and with skip-networking on, it accepts no TCP connections at all. Make sure the service runs and listens on the right address, and open port 3306 in the firewall only to the IP addresses that need access.

    Port 3306

  • ERROR 1045 (28000): Access denied for user

    Password and host
    Common cause
    A wrong password, an account defined for a different host, or an old password in the client's option file.
    How to check
    The query SELECT user, host, plugin FROM mysql.user, and the SHOW GRANTS command.

    The full message is Access denied for user 'user'@'host' (using password: YES), and it shows the user, the host the connection came from, and whether a password was sent. using password: NO means no password was sent at all. An account is a user name plus a host, so 'app'@'localhost' and 'app'@'%' are two separate accounts. According to the documentation, an anonymous ''@'localhost' account can take precedence over 'app'@'%' when you connect from the server itself. Create an account for the exact host, and reset the password with ALTER USER.

    MySQL commands

  • ERROR 1698 (28000): Access denied for user 'root'@'localhost'

    unix_socket
    Common cause
    The root account identifies users by their operating system user, not by a password.
    How to check
    Logging in with sudo mariadb or sudo mysql, and the plugin column in the mysql.user table.

    In MariaDB, the root@localhost account uses the unix_socket plugin by default: whoever is logged in to the operating system as root gets in without a password, and any other user is rejected. In MySQL, the equivalent plugin is called auth_socket, and some installations set up root with it. Connect with sudo, and for the website or a management tool, create a separate user with a password and privileges only on its own database. Switching root to password login can break maintenance and backup scripts that rely on logging in without a password.

  • ERROR 1040 (08004): Too many connections

    max_connections
    Common cause
    All allowed connections are in use, due to load, slow queries, or connections the application doesn't close.
    How to check
    SHOW FULL PROCESSLIST, and the max_connections and Max_used_connections values.

    The server accepts up to max_connections connections at the same time. In MySQL, one extra connection is reserved for an account with the CONNECTION_ADMIN privilege, so an administrator can log in and investigate even when the server is full. SHOW FULL PROCESSLIST shows who holds the connections: many connections in the Sleep state point to an application that doesn't close them, and long queries point to a performance problem. Fix the source first, and only then raise max_connections based on the server's memory, because every connection uses memory.

  • ERROR 1049 (42000): Unknown database

    Database
    Common cause
    A wrong database name in the application settings, or a database not yet created on the new server.
    How to check
    The query SHOW DATABASES, and the database name in the site's configuration file.

    The server can't find a database with the given name. This usually happens after moving a site to a new server, when the database hasn't been created yet, or when the control panel added the user name to the database name as a prefix. On Linux, database names are case-sensitive by default, so Shop and shop are two different names. Create the database with CREATE DATABASE, import the backup into it, and update the name in the site settings.

Disconnects and imports

  • ERROR 2006 (HY000): MySQL server has gone away

    wait_timeout
    Common cause
    A connection idle longer than wait_timeout, a packet larger than max_allowed_packet, or a server restart.
    How to check
    SHOW VARIABLES LIKE 'wait_timeout', and the server's uptime with mysqladmin version.

    According to the MySQL documentation, the most common cause is that the server closed an idle connection, which by default happens after eight hours, per wait_timeout. A long script or a background process that opens a connection once and comes back to it much later runs into this error. Other causes are a query larger than max_allowed_packet, a connection closed with KILL, and a server crash. Reconnect after a long wait, and check the error log to see whether the server restarted at that time.

  • ERROR 2013 (HY000): Lost connection to MySQL server during query

    net_read_timeout
    Common cause
    A network problem, a query that transfers a very large amount of data, or a server process that stopped midway.
    How to check
    SHOW GLOBAL STATUS LIKE 'Aborted%', and the server's error log.

    According to the documentation, the error usually points to a network problem, especially when the message includes during query. When a query transfers millions of rows, raise net_read_timeout, which defaults to 30 seconds. When the disconnect happens right at login and the message includes reading authorization packet, raise connect_timeout. Values larger than max_allowed_packet cause this error in some clients. When the server itself restarted, the error log and the kernel log show whether the process was killed for lack of memory.

  • ERROR 1153 (08S01): Got a packet bigger than 'max_allowed_packet' bytes

    max_allowed_packet
    Common cause
    Importing a backup with large INSERT statements, or saving a large BLOB or text value.
    How to check
    SHOW VARIABLES LIKE 'max_allowed_packet' on the server, and the value set in the client.

    The server and the client program each have their own limit on the size of a single packet, so when you import a large backup, raise both. On the server, set max_allowed_packet in the [mysqld] group and restart the service, and on the client, add the --max_allowed_packet option to the command. According to the MySQL documentation, the largest possible packet is 1GB. When the server receives a packet larger than the limit, it closes the connection, so the client sometimes shows MySQL server has gone away instead of this error.

Queries and tables

  • ERROR 1064 (42000): You have an error in your SQL syntax

    Syntax
    Common cause
    A reserved word used as a column name, unclosed quotes, or syntax the server doesn't recognize.
    How to check
    The snippet after near in the message, and what comes right before it in the query.

    The message ends with near '...' at line and a line number: the server quotes the text from the point where it stopped understanding the query, so the mistake is usually just before that snippet. Wrap table and column names that are reserved words, such as order or group, in backticks (`order`), and wrap strings in single quotes. By default, double quotes also mark a string, unless ANSI_QUOTES mode is enabled. A query written for a newer version can fail on an older server that doesn't know the syntax.

    MySQL commands

  • ERROR 1146 (42S02): Table '...' doesn't exist

    lower_case_table_names
    Common cause
    A table that wasn't imported, the wrong database, or letter case that doesn't match in the table name.
    How to check
    SHOW TABLES LIKE with the table name, and the query SELECT @@lower_case_table_names.

    On Linux, table names are case-sensitive by default (lower_case_table_names=0), and on Windows they aren't. So a site moved from Windows that queries the table Users, when the database has users, gets this error. According to the MySQL documentation, lower_case_table_names can be set only when the server is initialized, and must not be changed afterward. The stable fix is lowercase-only names, in the code and in the database. When the table is missing entirely, restore it from a backup.

  • ERROR 1062 (23000): Duplicate entry '...' for key

    Unique key
    Common cause
    An attempt to insert a value that already exists in a PRIMARY KEY or UNIQUE column.
    How to check
    SELECT on the value shown in the message, and SHOW CREATE TABLE to check the key.

    The message shows the duplicate value and the key it belongs to. It happens when the same backup is imported again into a table that already has data, when a form is submitted twice, or when the code inserts an explicit ID that already exists. Decide what's right for the data: INSERT ... ON DUPLICATE KEY UPDATE updates the existing row, and INSERT IGNORE skips the duplicate row with a warning instead of an error. When you import a full backup, import it into an empty database.

    SQL data types

  • ERROR 1215 (HY000): Cannot add foreign key constraint

    Foreign key
    Common cause
    Column types that don't match, a missing index in the parent table, or tables in different storage engines.
    How to check
    The LATEST FOREIGN KEY ERROR section in the output of SHOW ENGINE INNODB STATUS.

    According to the documentation, the columns on both sides of a foreign key must have similar types: the same size and sign for integers, and the same character set and collation for text columns. The parent table columns need an index, and both tables must use the same storage engine. In newer MySQL versions, a column type mismatch shows up as error 3780 with the message are incompatible. In MariaDB, a malformed foreign key sometimes appears as error 1005 with errno: 150 "Foreign key constraint is incorrectly formed".

    SQL data types

  • ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

    Data integrity
    Common cause
    A row that refers to a record missing from the parent table, or tables imported in the wrong order.
    How to check
    SELECT on the value in the parent table, based on the key name shown in the message.

    Error 1452 appears when you insert or update a row that refers to a record that doesn't exist. Error 1451, Cannot delete or update a parent row, appears when you delete a record that other rows refer to. When you import tables in a different order, you can temporarily turn off the check for the current connection with SET foreign_key_checks = 0 and turn it back on at the end. According to the documentation, turning the check back on doesn't verify rows added in the meantime, so make sure the data is valid yourself.

Locks and transactions

  • ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

    innodb_lock_wait_timeout
    Common cause
    Another transaction holds a lock on the same rows for a long time, such as one that never ran COMMIT.
    How to check
    The information_schema.INNODB_TRX table, and the SHOW ENGINE INNODB STATUS command.

    An InnoDB transaction waits for a row lock for up to innodb_lock_wait_timeout seconds, 50 by default. According to the MySQL documentation, when the time runs out, only the last statement is rolled back, not the whole transaction, unless the server was started with innodb_rollback_on_timeout. So the application has to decide whether to roll back the transaction or retry. Look in INNODB_TRX for long-running open transactions, such as a connection left open mid-transaction in a management tool, and keep transactions in the code short.

  • ERROR 1213: Deadlock found when trying to get lock; try restarting transaction

    Deadlock
    Common cause
    Two transactions, each waiting for a lock the other one holds.
    How to check
    The LATEST DETECTED DEADLOCK section in the output of SHOW ENGINE INNODB STATUS.

    InnoDB detects the situation immediately, rolls back one of the transactions, and returns this error to it. According to the documentation, a Deadlock isn't dangerous, and the application should be ready to run the transaction again. To reduce them, keep transactions short, update tables and rows in the same order throughout the code, and add indexes so queries lock fewer rows. The innodb_print_all_deadlocks setting writes every Deadlock to the error log, not just the latest one.

Encoding and characters

  • ERROR 1366 (HY000): Incorrect string value: '...' for column

    utf8mb4
    Common cause
    An emoji or another four-byte character saved in a column with the utf8mb3 encoding, also called utf8.
    How to check
    SHOW CREATE TABLE on the table, and SHOW VARIABLES LIKE 'character_set%'.

    The utf8mb3 encoding stores up to three bytes per character and doesn't support characters outside the BMP, such as most emoji. According to the MySQL documentation, the recommended encoding is utf8mb4. Convert the table with ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4, and make sure the application's connection is set to utf8mb4 too. Back up the table first, because the conversion rewrites it. The same error, with another word in place of string, also appears when you insert a value of the wrong type, such as text into a numeric column.

    Character encodings

  • ERROR 1267 (HY000): Illegal mix of collations

    collation
    Common cause
    A comparison or JOIN between columns with different collations, often after importing some tables from elsewhere.
    How to check
    SHOW FULL COLUMNS FROM on both tables, in the Collation column.

    The message names the two character set and collation pairs and the operation that failed, such as = or UNION. The server doesn't know which rule to use to compare the values. The stable fix is to bring all tables to the same character set and collation with ALTER TABLE ... CONVERT TO CHARACTER SET. For a one-off fix, add COLLATE with the name you want to the query. When you move a database between MySQL and MariaDB, check that the collation in the backup also exists on the target server.

    Character encodings

Files, disk, and recovery

  • ERROR 1290: The MySQL server is running with the --secure-file-priv option

    secure_file_priv
    Common cause
    LOAD DATA or SELECT ... INTO OUTFILE with a file outside the directory set in secure_file_priv.
    How to check
    The query SHOW VARIABLES LIKE 'secure_file_priv'.

    The message ends with so it cannot execute this statement, and in MariaDB it includes the word MariaDB. The secure_file_priv setting limits server-side file import and export: an empty value means no limit, a directory name restricts these operations to that directory, and NULL blocks them. Copy the file into the directory in the setting, or import from the client with LOAD DATA LOCAL INFILE when the local_infile option is enabled. The same error with --read-only means the server is in read-only mode.

  • ERROR 1030: Got error 28 - 'No space left on device' from storage engine

    Full disk
    Common cause
    The database partition, or the partition for temporary files (tmpdir), is full.
    How to check
    The df -h and df -i commands, and the query SHOW VARIABLES LIKE 'tmpdir'.

    Code 28 is an operating system code, and it means there's no free disk space. The perror 28 command shows what such a code means. Queries with large sorts or GROUP BY create temporary files, so the error sometimes appears even when the database partition has room but the tmpdir partition is full. Free up space, for example old logs, local backups, or old binary logs with PURGE BINARY LOGS, and never delete files from the data directory by hand.

    Linux directories and logs

  • Service won't start after a crash (InnoDB)

    innodb_force_recovery
    Common cause
    Corrupted data files after an unclean shutdown, a disk failure, or a full disk.
    How to check
    The server's error log, and the journalctl -u command with the service name.

    InnoDB usually recovers on its own at startup after a crash. If the service still won't start, read the error log first. innodb_force_recovery is for emergencies only, to bring the server up and export the data. According to the documentation, back up first, start at 1, and go higher only as needed. Caution: values of 4 and up can corrupt the data files permanently, so use them only after testing on a separate copy of the data. While the value is above 0, the server blocks INSERT, UPDATE, and DELETE. Then export the data and restore it to a healthy server.

Quick diagnostic commands

Service and logs

  • systemctl list-units --type=service | grep -i -E 'mysql|mariadb'

    Finds the exact service name on the server. In MariaDB, the service is called mariadb, and in MySQL, it's called mysqld on Red Hat family distributions and mysql on Debian and Ubuntu.

  • systemctl status mariadb

    Shows whether the service is running, when it started, and the latest lines in its log. Replace mariadb with the service name on your server.

    Example: systemctl status mysqld

  • journalctl -u mariadb --since "1 hour ago"

    Shows the service's entries from the last hour, including messages from a failed startup.

  • SHOW VARIABLES LIKE 'log_error';

    Shows the error log path. When the value is empty or stderr, the messages go to the service output, and you find them with journalctl.

  • my_print_defaults mysqld server mariadb | grep -i log

    Shows the log settings from the [mysqld], [server], and [mariadb] groups in the option files, even when the service won't start and you can't run queries.

  • mysqladmin version

    Shows the server version and uptime. A short uptime reveals that the server restarted recently. In MariaDB, the command is also called mariadb-admin.

  • journalctl -k | grep -i "out of memory"

    Searches the kernel log for processes killed when the server ran out of memory. A database process killed this way explains sudden disconnects.

Logging in and privileges

  • mysql -h 127.0.0.1 -u appuser -p

    Connects over TCP instead of the socket file. When this connection works and localhost fails, the problem is the socket path.

  • mysql --no-defaults -u appuser -p

    Connects without the client option files, to check whether an old password in my.cnf causes Access denied.

  • sudo mariadb

    Connects as root through unix_socket, without a password. In MySQL, use sudo mysql.

  • SELECT USER(), CURRENT_USER();

    USER() shows the user and host the client sent, and CURRENT_USER() shows the account the server actually matched. A difference between them reveals an anonymous account or an account with %.

  • SELECT user, host, plugin FROM mysql.user;

    Shows all accounts, the host of each one, and its authentication plugin.

  • SHOW GRANTS FOR 'appuser'@'localhost';

    Shows the account's privileges. An account is identified by both its name and its host, so specify both.

  • ALTER USER 'appuser'@'localhost' IDENTIFIED BY 'new-password';

    Resets the account's password. Update the password in the site settings too.

  • CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strong-password'; GRANT ALL PRIVILEGES ON shop.* TO 'appuser'@'localhost';

    Creates a user for the site with privileges only on its own database, instead of connecting as root.

  • SHOW VARIABLES LIKE 'socket';

    Shows the path of the socket file the server creates. Compare it with the socket setting of the client or the application.

  • sudo ss -tlnp | grep ':3306 '

    Shows which address the server listens on: 127.0.0.1 for local connections only, and 0.0.0.0 or * for all addresses.

Connections and limits

  • SHOW FULL PROCESSLIST;

    Shows all connections, their state, and the query running in each one. Many connections in the Sleep state point to connections the application doesn't close.

  • SHOW GLOBAL STATUS LIKE 'Max_used_connections';

    The highest number of simultaneous connections since the server started. When it equals max_connections, the server has reached the limit.

  • SHOW VARIABLES WHERE Variable_name IN ('max_connections', 'wait_timeout', 'max_allowed_packet');

    Shows, all at once, the three limits behind the common connection errors.

  • SET GLOBAL max_connections = 300;

    Changes the limit right away, until the next service restart. To keep the change, also add it to the option file in the [mysqld] group.

  • KILL 12345;

    Closes the connection with the ID shown in the Id column of SHOW PROCESSLIST. Caution: an open transaction on that connection is rolled back.

  • SHOW GLOBAL STATUS LIKE 'Aborted_connects';

    Counts failed connection attempts. A number that keeps rising points to a wrong password in the application or a network problem.

  • [mysqld] max_allowed_packet=256M

    In the server's option file: raises the maximum size of a single packet. Takes effect after the service restarts.

  • mysql --max_allowed_packet=256M -u appuser -p shop < backup.sql

    Imports a large backup with a high packet limit on the client side too.

Locks and transactions

  • SHOW ENGINE INNODB STATUS\G

    Shows the InnoDB status, including the LATEST DETECTED DEADLOCK and LATEST FOREIGN KEY ERROR sections. The \G ending shows the output as rows rather than a table.

  • SELECT trx_id, trx_state, trx_started, trx_mysql_thread_id, trx_query FROM information_schema.INNODB_TRX ORDER BY trx_started;

    Shows the open transactions, from oldest to newest. The trx_mysql_thread_id value is the ID for the KILL command.

  • SET SESSION innodb_lock_wait_timeout = 120;

    Extends the lock wait time for the current connection only, for example for a long maintenance task.

  • SET GLOBAL innodb_print_all_deadlocks = ON;

    Writes every Deadlock to the error log, not just the latest one. Turn it off when you finish checking.

Encoding, tables, and disk

  • SHOW CREATE TABLE orders\G

    Shows the table's full definition: columns, keys, storage engine, character set, and collation.

  • SHOW VARIABLES LIKE 'character_set%';

    Shows the character set of the server, the database, and the current connection. All of them must be utf8mb4 to store emoji.

  • SHOW FULL COLUMNS FROM orders;

    Shows the collation of each column, to find the columns that cause Illegal mix of collations.

  • ALTER TABLE orders CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

    Converts the table and all its text columns to utf8mb4. Caution: the table is rewritten, and on a large table the conversion takes time. Back up the table before converting it.

  • SELECT @@lower_case_table_names;

    Shows whether table names are case-sensitive: 0 means case-sensitive, and 1 means names are stored in lowercase.

  • SHOW VARIABLES LIKE 'secure_file_priv';

    Shows the directory that server-side file import and export is allowed from.

  • SET foreign_key_checks = 0;

    Turns off foreign key checks for the current connection only, for example when you import tables in a different order. Turn them back on with SET foreign_key_checks = 1;

  • CHECK TABLE orders;

    Checks the table for errors. Run it after a crash or after the disk filled up.

  • perror 28

    Shows what an operating system or server error code means, for example 28: No space left on device.

  • df -h && df -i

    Show the free space on each partition and the number of free inodes.

  • PURGE BINARY LOGS BEFORE NOW() - INTERVAL 7 DAY;

    Deletes binary logs created more than a week ago. Caution: on a server with replication, first make sure the replicas have already read them, and that you don't need them for point-in-time recovery.

Where to find the error log

The database server's error log is the first place to look for any problem the message itself doesn't explain. Its location differs between distributions and between MySQL and MariaDB, so check it on the server itself: the query SHOW VARIABLES LIKE 'log_error' shows the path. When the value is empty or stderr, the messages go to the service output, and you find them with journalctl and the service name. When the service won't start, the my_print_defaults mysqld command shows the log-error setting from the option files.

What's different in MariaDB

Most error numbers and messages are the same on both servers, because MariaDB grew out of MySQL. The differences that matter for troubleshooting:

  • The root account authenticates by the operating system user by default, with the unix_socket plugin.
  • Some messages show the name MariaDB instead of MySQL.
  • A malformed foreign key sometimes appears as error 1005 with errno: 150.
  • The tools are named mariadb, mariadb-admin, and mariadb-dump, and in many packages they're also available as mysql, mysqladmin, and mysqldump.

When you move a database between the two, check that the collation and the other settings in the backup are also supported on the target server.

Did you know?

On a Linux VPS, you get full root access and guaranteed resources, so you set max_connections, max_allowed_packet, and the other database settings yourself to fit your site's needs. For sites that don't need their own server, our web hosting plans include databases on fast, secure servers, with personal support via HelpDesk.

Linux VPS plans

MySQL errors FAQ

Why does my site say it can't connect to the database?

A message like Error establishing a database connection in WordPress hides a more specific database error. The common causes are a wrong password or user name in the site settings (error 1045), a database service that isn't running (error 2002), and a wrong database name (error 1049). Connect from the command line with the same details, and the message you get points to the cause. The Common WordPress errors page also covers the fixes specific to WordPress.

What's the difference between localhost and 127.0.0.1 when connecting to the database?

When the application connects to localhost, the client uses a local socket file rather than a port. When you specify 127.0.0.1, the connection goes over TCP through port 3306. So when one way works and the other doesn't, the problem is the socket path or TCP listening, not the password. Both ways suit a site whose database is on the same server, and according to the MySQL documentation, a socket connection is faster.

How do I import a large database backup without errors?

The reliable way is to import from the command line with the mysql client, not through a browser tool that limits time and file size. Before the import, raise max_allowed_packet on the server and in the client, import into an empty database, and make sure the database character set matches the one in the backup, usually utf8mb4. For an especially long import, run the command inside screen or tmux, so a dropped SSH connection won't stop it. The full commands are on the MySQL commands page.

When should I raise max_connections?

Raise it only after you check what's holding the connections. When most connections in SHOW PROCESSLIST are in the Sleep state, the application doesn't close its connections, and raising the limit only postpones the problem. When the connections are active and the load is real, raise the limit gradually and watch memory usage, because every connection uses memory on the server.

How do I know my database needs a server with more resources?

The common signs are Too many connections errors that keep coming back at peak hours even after the code is fixed, queries that slow down as traffic grows, lock waits, and memory running out. When the queries and indexes are already optimized, it's time for more resources. A Linux VPS gives you guaranteed resources and full root access, so you can tune the database to fit your site.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement