MySQL commands cheat sheet

This cheat sheet brings together the most useful commands for working with MySQL and MariaDB, from connecting and basic queries to managing privileges, backup, restore, and troubleshooting, with a short explanation of each command. You can search for a command, filter by section, and copy it with one click.

Connecting

  • mysql -u user -p

    Connect to the database server as the user named user and prompt for the password. The password is not shown on the screen while you type it.

  • mysql -u user -p example_db

    Connect to the server and select the example_db database right away, so you do not need to run the USE command.

  • mysql -h db.example.com -u user -p

    Connect to a remote database server by hostname or IP address. The remote server must allow external connections, and the user must be defined with a host that matches the address you connect from.

  • mysql -h 127.0.0.1 -P 3307 -u user -p

    Connect to a server that listens on a port other than the default port 3306. The -P option (uppercase) sets the port. Specify the address 127.0.0.1 and not the name localhost, because with localhost the client connects through a socket file and ignores the port.

  • mysql -u user -p -e "SHOW DATABASES;"

    Run a single SQL statement and exit, without opening the interactive shell. This form is useful in scripts and scheduled tasks.

  • sudo mysql

    Connect as the database root user without a password, on installations where this user is authenticated by the operating system user. On MariaDB installations, the mariadb command is also available and works the same way.

  • mysql --version

    Show the version of the client program, including whether it is MySQL or MariaDB. The version of the server itself is shown by the SELECT VERSION() query.

  • SELECT * FROM users WHERE id = 1\G

    Show the requested row as a vertical list of column names and values, instead of a wide table. The \G ending replaces the semicolon, and this view makes tables with many columns easier to read.

  • \c

    Cancel a partly typed statement in the interactive shell without running it.

  • \s

    Show the details of the current connection, including the user, the selected database, the server version, and the character set.

  • exit

    Close the interactive shell and return to the system command line. The quit command and the Ctrl+D key combination do the same thing.

Databases

  • SHOW DATABASES;

    List the databases that the connected user is allowed to see.

  • CREATE DATABASE example_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

    Create a new database with the utf8mb4 character set, which supports all languages and emoji. New tables in the database get this character set by default. The utf8mb4_unicode_ci collation is supported by both MySQL and MariaDB, unlike newer collations that exist in only one of them, so it suits backups that move between servers.

  • CREATE DATABASE IF NOT EXISTS example_db;

    Create the database only when it does not exist, without an error when it already exists. This form suits scripts that run more than once.

  • USE example_db;

    Select the database that the following statements in the current connection run on.

  • SELECT DATABASE();

    Show the name of the database selected in the current connection, or NULL when no database is selected.

  • SHOW CREATE DATABASE example_db;

    Show the statement that creates the database, including its character set and collation.

  • DROP DATABASE example_db;

    Caution: delete the database with all its tables and data, without asking for confirmation. You cannot undo this, so back up the database before you delete it.

Tables

  • SHOW TABLES;

    List all the tables in the current database.

  • SHOW TABLES LIKE 'order%';

    List only the tables whose names start with order. The % character stands for any sequence of characters.

  • DESCRIBE users;

    Show the table structure: the column names, the data types, whether NULL is allowed, the keys, and the default values.

  • SHOW FULL COLUMNS FROM users;

    Show the table structure in full detail, including the collation of each column and the comments set for it.

  • SHOW CREATE TABLE users;

    Show the full CREATE TABLE statement of the table, including the indexes, the foreign keys, the storage engine, and the character set. The statement is useful for creating an identical table on another server.

  • CREATE TABLE users (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, name VARCHAR(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    Create a table with an auto-incrementing numeric ID, a unique email address, and a creation time that is set automatically. The InnoDB engine supports transactions and foreign keys, and it is the recommended engine in most cases.

  • CREATE TABLE users_backup LIKE users;

    Create an empty table with the same structure as the users table, including the columns and indexes but without the foreign keys. To copy the data, run the INSERT INTO users_backup SELECT * FROM users statement afterward.

  • ALTER TABLE users ADD COLUMN phone VARCHAR(20) AFTER email;

    Add a new column named phone to the table and place it after the email column. In existing rows, the new column gets the default value, or NULL when no default is set.

  • ALTER TABLE users MODIFY COLUMN name VARCHAR(150) NOT NULL;

    Change the data type and settings of an existing column. The new definition fully replaces the previous one. Caution: shortening the length or changing the type may truncate or change existing data, so back up the table before the change.

  • ALTER TABLE users CHANGE COLUMN name full_name VARCHAR(150);

    Rename the column, and in the same statement you can also change its data type. Specify the full column definition, otherwise settings such as NOT NULL and the default value are removed from it. In recent versions of both systems, you can change just the name with the ALTER TABLE users RENAME COLUMN name TO full_name statement, which does not require the full definition.

  • ALTER TABLE users DROP COLUMN phone;

    Caution: permanently delete the column and all the data in it. Before you delete it, back up the table and make sure the code of the site or application no longer uses the column.

  • ALTER TABLE logs ENGINE=InnoDB;

    Convert a table to the InnoDB storage engine, for example an old MyISAM table. Caution: the statement rebuilds the table, and while it runs, which may take a long time on large tables, you cannot write to the table.

  • RENAME TABLE users TO customers;

    Rename the table. You can rename several tables in one statement, for example RENAME TABLE users TO users_old, users_new TO users, and so swap a live table for a new table in a single step.

  • SHOW TABLE STATUS LIKE 'users';

    Show the storage engine, the character set, the size, the number of rows, and the next AUTO_INCREMENT value. In InnoDB tables, the row count shown is only an estimate.

  • TRUNCATE TABLE logs;

    Caution: delete all the rows in the table and reset the AUTO_INCREMENT counter, but keep the table structure. The operation is faster than DELETE, but you cannot undo it, even inside a transaction.

  • DROP TABLE logs;

    Caution: delete the table with all its data, without asking for confirmation. You cannot recover the table without a backup.

Queries

  • SELECT * FROM users LIMIT 10;

    Show ten rows from the table, in no guaranteed order when ORDER BY is not specified. When you check a large table, add LIMIT so the query does not return millions of rows.

  • SELECT id, email FROM users WHERE status = 'active' ORDER BY created_at DESC LIMIT 20;

    Show selected columns of the active users, from newest to oldest, and limit the result to 20 rows.

  • SELECT COUNT(*) FROM users;

    Show the number of rows in the table.

  • SELECT DISTINCT country FROM users;

    Show the distinct values in the column, with each value listed only once.

  • SELECT * FROM users WHERE email LIKE '%@example.com';

    Find rows by a text pattern, here all the addresses in the example.com domain. The % character stands for any sequence of characters, and the _ character stands for a single character. A pattern that starts with % cannot use an index, so on a large table the query may be slow.

  • SELECT * FROM orders WHERE status IN ('paid', 'shipped');

    Find rows where the column value matches one of the values in the list.

  • SELECT * FROM users WHERE phone IS NULL;

    Find rows with no value in the phone column. The comparison phone = NULL returns no results, so use IS NULL or IS NOT NULL.

  • SELECT status, COUNT(*) FROM orders GROUP BY status;

    Group the rows by the column value and show the number of rows in each group, for example the number of orders in each status.

  • SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;

    Find duplicate values in the column. The HAVING clause filters the groups after grouping, while the WHERE clause filters the rows before grouping.

  • SELECT SUM(total), AVG(total), MAX(total) FROM orders WHERE status = 'paid';

    Calculate the sum, the average, and the highest value in the column for the rows that match the condition.

  • SELECT o.id, u.email, o.total FROM orders o JOIN users u ON u.id = o.user_id;

    Join two tables on a shared column and show each order together with the user's email address. The result includes only rows that have a match in both tables.

  • SELECT u.email FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.id IS NULL;

    Show the users who have no orders at all. LEFT JOIN returns all the rows from the first table, even when they have no match in the second table.

  • INSERT INTO users (email, name) VALUES ('user@example.com', 'John Smith');

    Add a new row to the table. You can add several rows in one statement, with the groups of values in parentheses separated by commas.

  • INSERT INTO settings (name, value) VALUES ('theme', 'dark') ON DUPLICATE KEY UPDATE value = 'dark';

    Add a new row, and when a row with the same value in a unique key already exists, update the existing row instead of returning an error. The statement requires a unique index or a primary key on the name column.

  • UPDATE users SET status = 'inactive' WHERE id = 42;

    Update the status column in the rows that match the condition. Caution: without WHERE, the statement updates every row in the table, so run a SELECT with the same condition first.

  • DELETE FROM sessions WHERE last_seen < NOW() - INTERVAL 30 DAY;

    Delete the rows that match the condition, here records in the sessions table whose last activity was more than 30 days ago. Caution: without WHERE, the statement deletes every row in the table, so first check the number of rows with SELECT COUNT(*) and the same condition.

  • UPDATE posts SET content = REPLACE(content, 'http://example.com', 'https://example.com');

    Replace text in the content column in every row of the table. The replacement is case-sensitive. Caution: in data stored in serialized format, as in some WordPress tables, a replacement that changes the length of the text corrupts the data, so back up the table before you run it.

  • SET SQL_SAFE_UPDATES = 1;

    Block UPDATE and DELETE statements in the current connection that have no WHERE condition on a key column and no LIMIT. This setting protects you from updating or deleting a whole table by mistake.

  • START TRANSACTION;

    Start a transaction, so changes made after it are not saved permanently until you run COMMIT. Transactions are supported in InnoDB tables and not in MyISAM tables. Statements that change the structure, such as ALTER TABLE, permanently save everything done in the transaction up to that point.

  • COMMIT;

    Permanently save all the changes made since the start of the transaction.

  • ROLLBACK;

    Undo all the changes made since the start of the transaction and return the data to its previous state.

Users and privileges

  • SELECT User, Host FROM mysql.user;

    List all the users on the server and the host each user is allowed to connect from. The statement requires read access to the mysql database.

  • CREATE USER 'user'@'localhost' IDENTIFIED BY 'StrongPassword';

    Create a user that is allowed to connect only from the server itself. A user is defined by the combination of a name and a host, so 'user'@'localhost' and 'user'@'%' are two separate users.

  • CREATE USER 'user'@'203.0.113.10' IDENTIFIED BY 'StrongPassword';

    Create a user that is allowed to connect only from a specific IP address. The % sign instead of the address allows connections from any address, and for security, limit access to known addresses only.

  • GRANT ALL PRIVILEGES ON example_db.* TO 'user'@'localhost';

    Grant the user all privileges on all the tables in the example_db database only. This is the common setup for the user of a website or an application, and the user must exist before you run the statement.

  • GRANT SELECT, INSERT, UPDATE, DELETE ON example_db.* TO 'user'@'localhost';

    Grant privileges to read and change data only, without permission to change the table structure or to drop tables.

  • GRANT SELECT ON example_db.* TO 'report'@'localhost';

    Grant read-only access, for example to a user that produces reports or to a monitoring tool.

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

    Show all the privileges granted to the user. Without FOR, the statement shows the privileges of the connected user.

  • REVOKE INSERT, UPDATE, DELETE ON example_db.* FROM 'user'@'localhost';

    Remove privileges granted to the user. In this example, a user that had privileges to read and change data keeps only the read privilege.

  • ALTER USER 'user'@'localhost' IDENTIFIED BY 'NewStrongPassword';

    Change the user's password, and after the change, update the password in the configuration files of the website or application that uses this user. For a user authenticated by the operating system user, such as root on some installations, the statement may also replace the authentication method, so afterward check that logging in with sudo mysql still works.

  • DROP USER 'user'@'localhost';

    Delete the user and all its privileges. The databases and tables the user worked with are not deleted. Caution: a website or application that connects with this user loses access to the database.

  • FLUSH PRIVILEGES;

    Reload the grant tables. You need this statement only after editing the tables in the mysql database directly, and statements such as GRANT, REVOKE, CREATE USER, and ALTER USER take effect without it.

Backup and restore

  • mysqldump -u user -p example_db > example_db.sql

    Export the database to an SQL file that includes the table structure and the data. On MariaDB installations, the mariadb-dump command is also available and works the same way.

  • mysqldump -u user -p --single-transaction example_db > example_db.sql

    Export a consistent copy of InnoDB tables without locking the tables, so the site keeps running normally during the backup. The option does not guarantee consistency for MyISAM tables.

  • mysqldump -u user -p --single-transaction --routines --events example_db > example_db.sql

    Export the database together with stored procedures, functions, and scheduled events, which are not included in the backup by default. Triggers are included in the backup even without an extra option.

  • mysqldump -u user -p --single-transaction example_db | gzip > example_db.sql.gz

    Export the database and compress the output straight into a gz file, without creating an uncompressed intermediate file. SQL files compress well, so the file is usually several times smaller.

  • mysqldump -u user -p example_db users orders > tables.sql

    Export only the users and orders tables, listed after the database name.

  • mysqldump -u user -p example_db orders --where="status = 'paid'" > paid_orders.sql

    Export only the rows of the orders table that match the condition. Caution: by default, the file includes a statement that drops the table and creates it again, so restoring it into the original database leaves only the exported rows in the table, unless you add the --no-create-info option.

  • mysqldump -u user -p --no-data example_db > schema.sql

    Export only the table structure, without data, for example to create an empty development environment.

  • mysqldump -u user -p --databases example_db shop_db > databases.sql

    Export several databases to one file. The file includes statements that create and select the databases, so you do not need to specify a database name when you restore it.

  • mysqldump -u user -p --single-transaction --all-databases > all.sql

    Export all the databases on the server, including the mysql database, which holds the users and privileges. Caution: restoring the file on another server may overwrite the users and privileges that exist there.

  • mysql -u user -p example_db < example_db.sql

    Restore an SQL file into an existing database. Caution: by default, a file created with mysqldump drops existing tables with the same name, so back up the current state before you restore.

  • zcat example_db.sql.gz | mysql -u user -p example_db

    Restore a compressed backup directly, without extracting the file to disk. Caution: as with restoring an uncompressed file, the restore overwrites existing tables with the same name.

  • SOURCE /home/user/example_db.sql;

    Run all the statements in an SQL file from the interactive shell, on the selected database. A relative path is resolved from the directory the client was started in. Caution: a backup file run this way overwrites existing tables with the same name, exactly like a restore from the command line.

  • mysql -u user -p -B -e "SELECT id, email FROM users" example_db > users.tsv

    Export the result of a query to a text file with tab-separated columns, which you can open in a spreadsheet program. The -N option leaves out the header row.

Indexes and performance

  • SHOW INDEX FROM orders;

    Show all the indexes on the table, the columns in each index, and the estimated number of distinct values in each column.

  • CREATE INDEX idx_orders_user_id ON orders (user_id);

    Create an index on the column, which speeds up queries that filter, sort, or join on it. Every index slightly slows down writes and takes up disk space, so create indexes only on columns that queries actually use.

  • CREATE INDEX idx_orders_status_created ON orders (status, created_at);

    Create a composite index on two columns. The column order matters: the index also serves queries that filter on status alone, but usually not queries that filter on created_at alone.

  • CREATE UNIQUE INDEX idx_users_email ON users (email);

    Create an index that prevents duplicate values in the column. Creating the index fails when the table already contains duplicate values.

  • DROP INDEX idx_orders_user_id ON orders;

    Drop an index from the table. The data itself is not affected, but queries that relied on the index may slow down.

  • EXPLAIN SELECT * FROM orders WHERE user_id = 42;

    Show the plan the server uses to run the query, without running it. The value ALL in the type column marks a full table scan, and the key column shows the index that was chosen.

  • SHOW FULL PROCESSLIST;

    Show the active connections, the query each connection runs, and how long it has been running in seconds. The statement helps you find slow queries or stuck connections, and a user without the PROCESS privilege sees only their own connections.

  • KILL 12345;

    Close the connection with the specified ID, from the Id column in the SHOW PROCESSLIST output. Caution: uncommitted changes in the connection are rolled back. The KILL QUERY 12345 statement stops only the current query and keeps the connection open.

  • SET GLOBAL slow_query_log = 'ON';

    Turn on the slow query log until the server restarts. To turn it on permanently, set slow_query_log in the server configuration file. In MySQL, you can also use SET PERSIST, which does not exist in MariaDB.

  • SET GLOBAL long_query_time = 1;

    Log every query that takes longer than one second in the slow query log. The value applies to new connections only.

  • SHOW VARIABLES LIKE 'slow_query%';

    Show whether the slow query log is on and the path of the log file.

  • SHOW ENGINE INNODB STATUS\G

    Show a detailed report on the state of the InnoDB engine. The LATEST DETECTED DEADLOCK section lists the queries involved in the most recent deadlock.

  • ANALYZE TABLE orders;

    Update the index statistics of the table, which the server uses to choose how to run queries. The statement is useful when a query slows down after a large change in the data.

  • OPTIMIZE TABLE orders;

    Rebuild the table and free the space left after deleting a lot of data. For InnoDB tables, a message says that the table does not support optimize and is recreated instead, which is normal. The operation needs free disk space equal to the size of the table, and on large tables it may take a long time.

  • CHECK TABLE orders;

    Check the table for errors and report them. The value OK in the Msg_text column means the table is fine.

  • mysqlcheck -u user -p --check --all-databases

    Check all the tables in all the databases from the command line, without opening the interactive shell.

  • mysqlcheck -u user -p --analyze example_db

    Update the index statistics of all the tables in the database. The --optimize option rebuilds the tables, and on a large database this may take a long time.

Information and variables

  • SELECT VERSION();

    Show the version of the database server. On a MariaDB server, the version includes the word MariaDB.

  • SHOW ENGINES;

    List the storage engines the server supports and the engine set as the default.

  • SHOW VARIABLES LIKE 'max_connections';

    Show the maximum number of simultaneous connections the server allows. You can show any configuration variable the same way, and the % character in the pattern lets you show a group of variables, for example LIKE 'innodb_buffer%'.

  • SHOW GLOBAL STATUS LIKE 'Threads_connected';

    Show the number of connections currently open to the server.

  • SHOW GLOBAL STATUS LIKE 'Max_used_connections';

    Show the highest number of simultaneous connections since the server last started. Comparing this value with max_connections shows whether the server is getting close to the limit.

  • SHOW GLOBAL STATUS LIKE 'Uptime';

    Show the number of seconds since the server last started.

  • SELECT NOW(), @@global.time_zone, @@session.time_zone;

    Show the current time in the connection's time zone, and the time zones of the server and of the connection. The value SYSTEM means the server uses the time zone of the operating system.

  • SHOW WARNINGS;

    Show the warnings produced by the last statement, for example values that were truncated during an insert or update.

  • SELECT table_schema AS db, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables GROUP BY table_schema;

    Show the size of each database in megabytes, including data and indexes.

  • SELECT table_name, ROUND((data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE table_schema = 'example_db' ORDER BY size_mb DESC;

    Show the size of each table in the database, from largest to smallest. The figures help you spot log or cache tables that have grown unusually large.

  • SELECT table_name, engine FROM information_schema.tables WHERE table_schema = 'example_db' AND engine = 'MyISAM';

    Find tables that still use the MyISAM engine, which does not support transactions, for example before you convert them to InnoDB.

Character encoding

  • SHOW VARIABLES LIKE 'character_set%';

    Show the character sets of the server, the current database, and the connection. For text in every language to display correctly, make sure the client, connection, and results values are utf8mb4.

  • SHOW VARIABLES LIKE 'collation%';

    Show the collation, which sets how text is compared and sorted, for example whether uppercase and lowercase letters are treated differently.

  • SET NAMES utf8mb4;

    Send and receive text in the current connection in the utf8mb4 character set. When the connection character set does not match the data, non-Latin text may be stored or shown as question marks.

  • mysql -u user -p --default-character-set=utf8mb4 example_db

    Connect to the server with utf8mb4 as the connection character set, so non-Latin text is typed and shown correctly in the interactive shell.

  • mysqldump -u user -p --default-character-set=utf8mb4 example_db > example_db.sql

    Export the database explicitly in the utf8mb4 character set, so non-Latin text and special characters are kept in the backup without corruption.

  • SELECT table_name, table_collation FROM information_schema.tables WHERE table_schema = 'example_db' AND table_collation NOT LIKE 'utf8mb4%';

    Find tables in the database that are not set to the utf8mb4 character set.

  • ALTER DATABASE example_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

    Change the default character set of the database. The change applies only to new tables, and existing tables keep their previous character set.

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

    Convert an existing table and all its text columns to utf8mb4, and rebuild the table. Caution: back up the table before the conversion. The conversion does not fix text that was already stored corrupted.

Service and troubleshooting

  • systemctl status mariadb

    Show whether the database service is running and the latest lines of its log. The service name varies between installations, and it may be mariadb, mysql, or mysqld.

  • sudo systemctl restart mariadb

    Restart the database service, for example after a change in the configuration file. Caution: all active connections are closed, and the sites that use the server are unavailable until the restart finishes.

  • journalctl -u mariadb -n 50 --no-pager

    Show the last 50 lines of the service log, which helps you find why the service failed to start.

  • SHOW VARIABLES LIKE 'log_error';

    Show the path of the server's error log file. On many installations, an empty value or stderr means the log is written to the system journal, which the journalctl command shows.

  • mysqladmin -u user -p status

    Show a short summary of the server status, including the uptime, the number of connections, and the average number of queries per second. The mysqladmin ping command only checks whether the server responds.

  • SELECT User, Host, plugin FROM mysql.user WHERE User = 'user';

    Show which hosts the user is allowed to connect from and with which authentication method, which helps you resolve an Access denied error. A connection from localhost does not match a user defined only with an IP address, and the reverse is also true.

  • SELECT USER(), CURRENT_USER();

    Show the user the client gave when connecting and the account the server actually matched it to. A difference between the two values explains cases where privileges do not apply as expected.

  • SET GLOBAL max_connections = 300;

    Raise the connection limit of the server until the server restarts, for example when the Too many connections error appears. The usual cause of the error is slow queries or connections that are not closed, so also check the output of SHOW FULL PROCESSLIST.

  • SHOW VARIABLES LIKE 'max_allowed_packet';

    Show the maximum size of a single statement or a single row sent to the server. A low value may cause the MySQL server has gone away error during an import of a large file or of a row with a lot of data.

  • REPAIR TABLE logs;

    Repair a damaged MyISAM table, or an Aria table in MariaDB, for example when the Table is marked as crashed error appears. The InnoDB engine does not support this statement. Caution: the repair may remove damaged rows, so back up the table before you run it.

  • SHOW VARIABLES LIKE 'socket';

    Show the path of the socket file the client uses to connect to the local server. The path helps you resolve connection errors that contain the phrase through socket, when the client looks for the file in a different location.

  • ss -ltnp | grep 3306

    Check whether the database server listens on port 3306, and on which address. The address 127.0.0.1 means the server accepts connections only from the server itself.

MySQL and MariaDB are relational database management systems, and many websites and applications store their content, users, and orders in them. Most of the commands in this cheat sheet work the same way in both systems, and where there is a difference, the explanation of the command notes it. On MariaDB installations, the tools are also available as mariadb and mariadb-dump, alongside the familiar names.

This page includes two types of commands: SQL statements, which you run inside the interactive shell and end with a semicolon, and commands such as mysql, mysqldump, and mysqlcheck, which you run from the server's command line. To lay out a long query in lines and indentation before you check or run it, use the SQL formatter. To replace URLs in a WordPress site without corrupting data stored in serialized format, use the WP-CLI commands cheat sheet.

Two simple rules prevent many problems when you work with databases. Before any command that deletes or changes data, such as DROP, TRUNCATE, DELETE, or UPDATE, back up the database with mysqldump. In addition, before you run UPDATE or DELETE, run SELECT with the same WHERE condition to confirm which rows will be affected.

Did you know?

With Linux hosting, you can create as many MySQL and MariaDB databases as you need and manage them with phpMyAdmin.

Linux hosting plans

MySQL commands FAQ

What is the difference between MySQL and MariaDB?

In everyday use, the two systems are almost identical: MariaDB was forked from MySQL, and both use the same SQL language, the same tools, and the same backup format. The differences appear in advanced features, such as collations, authentication methods, and persistent settings, so in those cases check the documentation of the installed system.

How do I back up and restore a database?

You back up the database with the mysqldump -u user -p --single-transaction example_db > example_db.sql command, which creates an SQL file with the structure and the data. You restore it into an existing database with the mysql -u user -p example_db < example_db.sql command. Because the restore overwrites tables with the same name, back up the current state first.

What do I do when I get an Access denied error?

In most cases, the cause is a wrong password or a connection address that does not match the host defined for the user. The SELECT User, Host FROM mysql.user statement shows which hosts each user is allowed to connect from, and a user defined with localhost cannot connect from another address. When you can log in but a specific action is blocked, the SHOW GRANTS statement shows the privileges granted to the user, so you can find which privilege is missing.

Why does text show up as question marks or garbled characters?

In most cases, the cause is a mismatch between the character sets of the table, the connection, and the application. The recommended setting is utf8mb4 in every layer: in the database, in the tables, in the connection with SET NAMES utf8mb4, and in the application settings. When text was already stored corrupted, converting the table does not fix it, so restore the data from a good backup or fix it with a dedicated conversion process.

What is the difference between DELETE, TRUNCATE, and DROP?

The difference is the scope of the deletion. DELETE deletes rows by a condition, and you can undo it inside a transaction. TRUNCATE quickly deletes all the rows but keeps the table structure. DROP deletes the whole table, including its structure. You cannot undo TRUNCATE or DROP, and you can recover the data only from a backup.

How do I reset a lost root password?

On many installations, you can log in with the sudo mysql command without a password, because the root user is authenticated by the operating system user, and then set a new password with the ALTER USER statement. When that is not possible, follow the reset procedure in the official MySQL or MariaDB documentation, and on a managed server, contact your server provider.

Shopping cart

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

Site search

Accessibility

Text size
100%
Accessibility statement