MySQL Cheat Sheet
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A one-page reference for everyday MySQL work, using the shop example (see
Getting Started). The commands in the sections below were run on
mysql:latest (server 26.10.0), except where a line says it is a format only. Each section links to the page that
explains it in depth; the full list of pages is at the end.
Client and connection
mysql -h 127.0.0.1 -P 3306 -u root -p shop # TCP; -p prompts, or -psecret (insecure)
mysql -uroot -psecret --default-character-set=utf8mb4 shop
mysql -uroot -psecret shop -e "SELECT 1" # run one statement and exit
mysql -uroot -psecret -E shop -e "SELECT * FROM customers LIMIT 1" # vertical output
mysql -uroot -psecret --commands shop < script.sql # allow \ commands in batch input
mysqlsh --sql --uri root:secret@127.0.0.1:3306/shop -e "SELECT DATABASE()" # MySQL Shell, URI form
Connection string forms (format only, not executed as written): URI mysql://user:password@host:3306/shop, JDBC
jdbc:mysql://host:3306/shop?sslMode=REQUIRED&serverTimezone=UTC. In this version the mysql client in
the image processed backslash commands only with --commands in batch mode (interactive sessions use them directly), and
its default client character set was latin1, so pass --default-character-set=utf8mb4 for non-ASCII data.
| Client command | Meaning |
|---|---|
|
connection, server version, character sets, uptime |
|
switch database |
|
vertical output, one column per line |
|
run a script |
|
start / stop copying output to a file (tee); interactive use, not run here |
|
built-in help for a statement |
SELECT DATABASE(), CURRENT_USER(), VERSION();
SHOW DATABASES;
SHOW TABLES;
SHOW FULL TABLES WHERE Table_type='BASE TABLE';
DESCRIBE customers;
SHOW CREATE TABLE customers\G
SHOW INDEX FROM orders;
DATABASE() returned shop, CURRENT_USER() returned root@localhost and VERSION() 26.10.0 in the test.
See Getting Started.
DDL idioms
CREATE TABLE IF NOT EXISTS notes (
id int AUTO_INCREMENT PRIMARY KEY,
body text,
created_at timestamp DEFAULT CURRENT_TIMESTAMP,
upd timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
kind enum('a','b') NOT NULL DEFAULT 'a',
label varchar(10) AS (CONCAT('n-', kind)) STORED -- generated column
);
ALTER TABLE notes ADD COLUMN flag tinyint(1) NOT NULL DEFAULT 0, ALGORITHM=INSTANT;
ALTER TABLE notes ADD INDEX idx_kind (kind) INVISIBLE;
ALTER TABLE notes ALTER INDEX idx_kind VISIBLE;
CREATE INDEX idx_created_desc ON notes (created_at DESC);
CREATE FULLTEXT INDEX ft_body ON notes (body);
CREATE TABLE notes_copy LIKE notes; -- structure only
CREATE TABLE notes_ctas AS SELECT * FROM notes; -- structure and rows
RENAME TABLE notes_ctas TO notes_old;
TRUNCATE TABLE notes_old;
DROP TABLE IF EXISTS notes_old, notes_copy;
All of the above ran without error. A generated column cannot refer to an AUTO_INCREMENT column (error 3109). See
DDL and Administration for online DDL.
DML idioms
INSERT INTO notes (body) VALUES ('hello world'), ('mysql notes');
INSERT INTO customers (id,name,email,city,tier,created_at)
VALUES ('c-9','Test','t@example.com','X','free',NOW())
ON DUPLICATE KEY UPDATE name = VALUES(name); -- upsert (VALUES() form)
INSERT INTO customers (id,name,email,city,tier,created_at)
VALUES ('c-9','Test2','t@example.com','X','free',NOW()) AS new
ON DUPLICATE KEY UPDATE name = new.name; -- upsert (row alias form)
INSERT IGNORE INTO customers VALUES ('c-9','Dup','dup@example.com','X','free',NOW());
REPLACE INTO notes (id, body) VALUES (1, 'replaced'); -- delete then insert
UPDATE orders o JOIN customers c ON c.id = o.customer_id SET o.status='open' WHERE c.tier='free' AND o.status='open';
DELETE FROM customers WHERE id='c-9' ORDER BY id LIMIT 1;
SELECT LAST_INSERT_ID(), ROW_COUNT();
Selected queries and their results from the same session:
SELECT id, body FROM notes WHERE MATCH(body) AGAINST ('mysql' IN NATURAL LANGUAGE MODE); -- 2, mysql notes
WITH t AS (SELECT customer_id, COUNT(*) n FROM orders GROUP BY customer_id) SELECT * FROM t WHERE n > 1;
SELECT customer_id, id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) rn FROM orders;
SELECT GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') FROM customers;
SELECT IFNULL(NULL,'x'), COALESCE(NULL,NULL,'y'), IF(1>0,'t','f'), DATE_FORMAT(NOW(),'%Y-%m'),
DATE_ADD('2026-01-31', INTERVAL 1 MONTH), TIMESTAMPDIFF(DAY,'2026-01-01','2026-03-01');
c-1 3, c-2 2, c-3 2 (customers with more than one order) Ada Lovelace, Alan Turing, Grace Hopper, Linus Torvalds x | y | t | 2026-11 | 2026-02-28 | 59
DATE_ADD('2026-01-31', INTERVAL 1 MONTH) gives 2026-02-28: month arithmetic clamps to the last day. See
Data modification, Queries and
Aggregate & window functions.
Data types
| Group | Types |
|---|---|
Integers |
|
Exact decimals |
|
Approximate |
|
Strings |
|
Binary |
|
Date and time |
|
JSON |
|
Spatial |
|
Details: Data Types & MySQL-specific SQL and JSON.
Index types
| Kind | Syntax |
|---|---|
Primary key |
|
Unique |
|
Secondary (B-tree) |
|
Prefix |
|
Descending |
|
Functional |
|
Multi-valued (JSON array) |
|
Full-text |
|
Invisible |
|
Spatial |
|
These forms were run, the functional and multi-valued ones against the items table of the JSON page and the
others against notes, orders and a small geo table. Composite indexes serve the leftmost prefix only. See
Indexing.
EXPLAIN forms
EXPLAIN SELECT * FROM orders WHERE customer_id='c-1'; -- default format on this server: TREE
EXPLAIN FORMAT=TRADITIONAL SELECT * FROM orders WHERE customer_id='c-1'; -- table with type, key, rows, Extra
EXPLAIN FORMAT=JSON SELECT * FROM orders WHERE customer_id='c-1';
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id='c-1'; -- runs the query, adds actual times
-> Index lookup on orders using fk_orders_customer (customer_id = 'c-1') (cost=0.8 rows=3) -> Index lookup on orders using fk_orders_customer (customer_id = 'c-1') (cost=0.8 rows=3) (actual time=0.0234..0.0247 rows=3 loops=1)
In the traditional format look at type (ALL is a full scan, ref, range, const use an index), key, rows and
Extra (Using filesort, Using temporary, Using index for covering). The first two outputs above are the TREE and
ANALYZE forms. See Query Planning & EXPLAIN.
Isolation levels and locking reads
| Level | Notes |
|---|---|
|
dirty reads possible |
|
each statement sees the latest committed data |
|
default; one snapshot per transaction, with next-key locks |
|
plain reads become shared locking reads |
SELECT @@transaction_isolation, @@autocommit; -- REPEATABLE-READ, 1
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
SELECT * FROM customers WHERE id='c-1' FOR UPDATE; -- exclusive row lock
SELECT * FROM customers WHERE id='c-1' FOR SHARE; -- shared lock
SELECT * FROM customers WHERE id='c-1' FOR UPDATE NOWAIT; -- fail at once if locked
SELECT * FROM orders WHERE status='open' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job-queue pattern
SAVEPOINT s1;
UPDATE customers SET tier='pro' WHERE id='c-1';
ROLLBACK TO SAVEPOINT s1;
COMMIT;
All ran; the SKIP LOCKED query returned order 1002. Inspect locks with performance_schema.data_locks and
sys.innodb_lock_waits. See Transactions, Isolation & Locking and
Transactions.
JSON functions
SELECT JSON_EXTRACT(attrs,'$.color') c, attrs->>'$.color' c2 FROM products WHERE sku='A-1'; -- "oak" | oak
SELECT sku FROM products WHERE 'sale' MEMBER OF (tags); -- A-2, C-3
SELECT JSON_ARRAYAGG(sku) FROM products; -- ["A-1", "A-2", "B-7", "C-3", "C-9"]
| Task | Function |
|---|---|
Read |
|
Change |
|
Test |
|
Build |
|
Shred |
|
Validate |
|
Paths: $, $.key, $[0], $[last], $[*], $**.key. See JSON.
Administration and monitoring
SHOW FULL PROCESSLIST;
KILL QUERY 26; -- or KILL CONNECTION 26
SHOW GLOBAL STATUS LIKE 'Threads%';
SHOW GLOBAL VARIABLES LIKE 'max_connections';
SET GLOBAL max_connections = 300; -- until restart
SET PERSIST max_connections = 300; -- survives restart (mysqld-auto.cnf)
RESET PERSIST max_connections;
SELECT * FROM sys.innodb_lock_waits;
SELECT * FROM sys.statements_with_full_table_scans WHERE db='shop';
SELECT * FROM sys.schema_unused_indexes WHERE object_schema='shop';
SELECT * FROM sys.waits_global_by_latency LIMIT 3;
SELECT event_name, current_alloc FROM sys.memory_global_by_current_bytes LIMIT 4;
SELECT table_name, ROUND((data_length+index_length)/1048576,1) AS mib FROM information_schema.tables
WHERE table_schema='shop' ORDER BY (data_length+index_length) DESC LIMIT 3;
ANALYZE TABLE orders; CHECK TABLE orders; OPTIMIZE TABLE sales;
CREATE USER 'app'@'%' IDENTIFIED BY '...'; CREATE ROLE 'shop_read';
GRANT SELECT ON shop.* TO 'shop_read'; GRANT 'shop_read' TO 'app'@'%'; SET DEFAULT ROLE ALL TO 'app'@'%';
SHOW GRANTS FOR 'app'@'%';
SHOW PRIVILEGES;
The table-size query listed sales (61.6 MiB), t_dur (0.3) and notes (0.1). SHOW ENGINE INNODB STATUS\G prints the
InnoDB monitor (transactions, I/O, buffer pool, latest deadlock). Online DDL: add ALGORITHM=INSTANT|INPLACE|COPY to
force a method. Binary logs: SHOW BINARY LOGS;, FLUSH BINARY LOGS;, PURGE BINARY LOGS TO 'binlog.000003';. Server
tools: mysqladmin -uroot -psecret ping printed mysqld is alive and mysqladmin ... status printed uptime, threads and
query counts. See Administration and DCL.
Backup and restore
mysqldump -uroot -psecret --single-transaction --routines --triggers --events --source-data=2 --databases shop > shop-full.sql
mysqldump -uroot -psecret --single-transaction --no-data shop customers # structure of one table
mysql -uroot -psecret < shop-full.sql # restore
mysqlsh --js --uri root:secret@localhost -e "util.dumpSchemas(['shop'], '/backup/shell-dump', {threads: 2})"
mysqlsh --js --uri root:secret@localhost -e "util.loadDump('/backup/shell-dump', {threads: 2})"
mysqlbinlog --start-position=1795 --stop-position=2781 binlog.000004 | mysql -uroot -psecret # point-in-time replay
mysqlbinlog --start-position=1795 --exclude-gtids=UUID:78 binlog.000004 | mysql -uroot -psecret # skip one GTID
CHECKSUM TABLE shop.orders, shop.customers; -- compare a restore with the original
INSTALL PLUGIN clone SONAME 'mysql_clone.so';
CLONE LOCAL DATA DIRECTORY = '/var/lib/mysql-files/clone1'; -- physical copy of a running server
In the mysql:latest image mysqlbinlog is installed at /usr/libexec/mysqlsh/mysqlbinlog. A full mysqldump of the shop
data with the extra tables was 70,738,653 bytes after the large sales table was added. See
Backup & Restore.
Replication checks
SHOW BINARY LOG STATUS; -- file, position, Executed_Gtid_Set on a source
SHOW REPLICAS; -- on the source
SHOW REPLICA STATUS\G -- on a replica: Replica_IO_Running, Replica_SQL_Running, Seconds_Behind_Source
CHANGE REPLICATION SOURCE TO SOURCE_HOST='my-b', SOURCE_USER='repl', SOURCE_PASSWORD='repl-pass',
SOURCE_AUTO_POSITION=1, GET_SOURCE_PUBLIC_KEY=1;
START REPLICA; STOP REPLICA; RESET REPLICA ALL;
SELECT GTID_SUBTRACT('uuid:1-21', @@global.gtid_executed) AS pending;
SELECT * FROM performance_schema.replication_group_members; -- Group Replication
SELECT group_replication_set_as_primary('member-uuid');
SELECT @@global.read_only, @@global.super_read_only, @@global.gtid_mode, @@global.log_bin, @@global.server_id;
On a standalone server SHOW REPLICA STATUS returns an empty set, SHOW BINARY LOG STATUS returned a binlog.000002 position
with the executed GTID set, and the last query returned 0, 0, ON, 1, 1. See
Replication & High Availability.
Key variables
| Variable | Default seen | Purpose |
|---|---|---|
|
128 MiB |
main memory cache; first thing to size |
|
100 MiB |
total redo log size, dynamic |
|
1 |
1 durable per commit, 2 and 0 faster and riskier |
|
1 |
binary log flush per commit group |
|
O_DIRECT |
bypass the OS cache for data files |
|
151 |
connection ceiling |
|
9 |
reuse connection threads |
|
256 KiB |
per-session buffers |
|
16 MiB |
in-memory internal temporary table limit |
|
REPEATABLE-READ |
session isolation level |
|
ROW |
deprecated setting; keep ROW |
|
ON |
GTID replication (in this image) |
|
TREE |
default |
|
|
default authentication plugin for new accounts |
|
0 |
|
See Performance Tuning for what each does and measured effects.