Skip to content

MySQL Cheatsheet ​

Dense quick reference for MySQL 8.4 LTS (InnoDB): connect, define, query, index, lock, monitor, back up, and wire it into Go and Laravel. Chapters behind it: MySQL storage engines, Indexing, Isolation levels, Locks & concurrency.

How to use this page ​

  • This is a lookup page: find the task in the first column, copy the command, and read the note before running it on production.
  • For why, and for query and index examples, read the chapters linked in the summary above and the SQL Queries & Indexes Cheatsheet.
  • Written for MySQL 8.4 LTS; anything marked with a version (for example 8.0+) is absent below that version.

Page map ​

SectionUse it when
ConnectionConnecting, TLS, login paths and checking the connection
Meta-commands (mysql client)Meta-commands in the mysql client: SHOW statements, pager, source
DDLCreating and altering tables, online DDL and partitions
DMLInserts, upserts, CTEs, windows, JSON and pagination
IndexesChoosing, building and auditing indexes
Transactions & isolationIsolation levels, row and named locks, timeouts and retries
Admin & monitoringThreads, locks, statements, sizes, replication and the slow log
Diagnostic queriesLong SQL moved out of the tables, ready to paste
Config knobsDefaults and sizing hints for the main settings
Backup & restoreDumps, restores, clone and point-in-time recovery
Users, roles & grantsAccounts, grants, roles and resource limits
Common errorsError numbers and what to do about them
Go snippetsdatabase/sql driver, DSN parameters and transactions
Laravel snippetsConfig, raw queries, locks, upsert and read replicas
ReferencesOfficial documentation

Connection ​

TaskCommandNotes
Connect with flagsmysql -h db.example.com -P 3306 -u app -p shop-p with no value prompts for the password; no space between -p and an inline password
Secure connectionmysql -h db -u app -p --ssl-mode=VERIFY_IDENTITY shopModes: DISABLED, PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY
Run one statementmysql -e "select now()" shop-e executes and exits
Run a filemysql shop < schema.sqlAdd --force to continue after errors
Script-friendly outputmysql -B -N -e "select id,email from users" shop-B batch tab-separated, -N skips column names
Vertical outputmysql -e "select * from users limit 1\G" shop\G ends the statement with a vertical layout
Credentials without a password flagmysql_config_editor set --login-path=prod --host=db --user=app --password then mysql --login-path=prodStored encrypted in ~/.mylogin.cnf
Charsetmysql --default-character-set=utf8mb4 shopUse utf8mb4, not the legacy utf8 alias
Unix socketmysql -S /var/run/mysqld/mysqld.sock -u root -pLocal connections skip TCP
Check connectionselect current_user(), database(), version(), @@hostname;current_user() is the account that matched, user() the one you asked for

Meta-commands (mysql client) ​

TaskCommandNotes
List databasesshow databases;
Switch databaseuse shop;Or \u shop
List tablesshow tables; / show full tables where table_type = 'BASE TABLE';
Describe tabledescribe users; / show columns from users;Short form desc
Show DDLshow create table users\GAuthoritative: engine, charset, constraints
Show indexesshow index from users;Cardinality and visibility
Show variablesshow variables like 'innodb%'; / show global variables like 'max_conn%';% wildcard; SESSION vs GLOBAL scope
Show status countersshow global status like 'Threads%';Counters since start
Show warningsshow warnings;Run right after a statement that reports a note
Pagerpager less -S / nopagerWide result sets
Tee output / statustee /tmp/out.log / notee; status (\s)status prints connection info and uptime
Run a filesource /path/file.sql or \. file.sql
Switch userconnect or \rReconnects with the current settings
Helphelp contents / \h
Quitexit / \q

DDL ​

TaskCommandNotes
Create tablesee Diagnostic queriesInnoDB and utf8mb4 are the defaults in 8.4
Add / drop columnalter table orders add column note varchar(255) null; / drop column note;Add algorithm=instant where supported to avoid a rebuild
Online DDLalter table orders add index idx_u (user_id), algorithm=inplace, lock=none;Fails loudly if the combination is not allowed, which is the point
Change typealter table orders modify total decimal(14,2) not null;Many type changes rebuild the table
Renamerename table orders to sales; / alter table t rename column a to b;rename table is atomic and can swap two tables
Primary / uniquealter table t add primary key (id); / add unique key uq_email (email);InnoDB clusters rows by the primary key
Foreign keyalter table orders add constraint fk_u foreign key (user_id) references users(id) on delete restrict;Needs an index on the referencing column (created automatically)
Check constraintalter table orders add constraint pos check (total >= 0);Enforced from 8.0.16
Default expressioncreate table t (id char(36) default (uuid()));Expression defaults go in parentheses
Generated columnalter table orders add column gross decimal(12,2) generated always as (total * 1.2) stored;virtual computes on read and can be indexed
Enum / setstatus enum('new','paid') not nullAppending a value at the end is an instant change
JSON columndata jsonIndex with a generated column or a functional index
Range partitionsee Diagnostic queriesThe partition key must be in every unique key
List / hash / keypartition by list (region) / partition by hash (id) partitions 8 / partition by key (id)
Partition maintenancealter table ev drop partition p1; / reorganize partition pmax into (...)drop partition is a fast delete
Temporary tablecreate temporary table t (...)Per session
Drop / truncatedrop table if exists t; / truncate table t;truncate resets AUTO_INCREMENT and commits implicitly
DDL transactionsDDL causes an implicit commitAtomic DDL in 8.0+ means a single DDL is all-or-nothing, but not part of your transaction

DML ​

TaskCommandNotes
Insert, fetch idinsert into users (email) values ('a@x.io'); select last_insert_id();MySQL has no RETURNING; drivers expose LastInsertId
Multi-row insertinsert into t (a,b) values (1,'x'),(2,'y');Batch for throughput
Upsertinsert into kv (k,v) values ('a',1) as new on duplicate key update v = new.v;Alias form; the VALUES(col) function is deprecated
Insert ignoreinsert ignore into kv (k,v) values ('a',1);Turns errors into warnings, which can hide real problems
Replacereplace into kv (k,v) values ('a',1);Deletes then inserts, fires delete triggers and changes ids
Update with joinupdate orders o join payments p on p.order_id = o.id set o.status='paid';Multi-table update syntax
Delete with joindelete s from sessions s join users u on u.id = s.user_id where u.banned;Names the table to delete from
Update limitupdate jobs set state='x' where state='new' order by id limit 10;ORDER BY and LIMIT allowed on single-table update and delete
CTEwith recent as (select * from orders where created_at > now() - interval 1 day) select count(*) from recent;Since 8.0
Recursive CTEwith recursive t(n) as (select 1 union all select n+1 from t where n < 5) select * from t;Bounded by cte_max_recursion_depth (default 1000)
Window functionselect *, row_number() over (partition by user_id order by created_at desc) rn from orders;Latest-per-group: filter rn = 1 in an outer query
Running totalsum(total) over (order by created_at rows between unbounded preceding and current row)Also lag, lead, rank, ntile
JSON accessselect data->'$.a.b', data->>'$.a.b' from docs;-> returns JSON, ->> unquoted text
JSON searchselect * from docs where json_contains(data, '"admin"', '$.roles');Also json_extract, json_search, member of
JSON modifyupdate docs set data = json_set(data, '$.a', 2);json_insert, json_replace, json_remove
JSON tableselect * from json_table(@j, '$[*]' columns (id int path '$.id')) t;Turns JSON into rows
Keyset paginationselect * from orders where (created_at, id) < (?, ?) order by created_at desc, id desc limit 50;Beats OFFSET on deep pages
Explainexplain analyze select ...;analyze runs the query; plain explain format=tree does not
Bulk loadload data local infile 'u.csv' into table users fields terminated by ',' ignore 1 lines;Needs local_infile enabled on both sides
GROUP BY / HAVING, window and pagination patternsSQL Queries & Indexes Cheatsheetworked examples with plan lines

Indexes ​

TaskCommandNotes
Createcreate index idx_o_u on orders (user_id, created_at);B-tree; leftmost-prefix rule applies
Online createalter table orders add index idx_o_u (user_id), algorithm=inplace, lock=none;Concurrent DML allowed for secondary indexes
Uniquecreate unique index uq_email on users (email);
Descendingcreate index idx on orders (user_id, created_at desc);Real descending indexes since 8.0
Prefixcreate index idx on docs (title(32));Required for TEXT/BLOB, may not cover the query
Functionalcreate index idx on users ((lower(email)));Double parentheses; query must use the same expression
Coveringcreate index idx on orders (user_id, total);No INCLUDE; add trailing columns; Extra: Using index in EXPLAIN
Full-textcreate fulltext index ft on docs (title, body); then match(title, body) against ('x' in natural language mode)InnoDB full-text
Invisiblealter table orders alter index idx_o_u invisible;Test dropping an index safely, then drop index
Dropdrop index idx_o_u on orders;
Index sizessee Diagnostic queriessize is in pages
Unused indexesselect * from sys.schema_unused_indexes;Based on performance_schema counters since startup
Redundant indexesselect * from sys.schema_redundant_indexes;Includes the dominating index and a ready DROP statement
Tables without a PKsee Diagnostic queriesEvery InnoDB table should have a primary key
Refresh statisticsanalyze table orders;Updates index cardinality
Worked examplesSQL Queries & Indexes Cheatsheetcomposite order, sort path, "is the index used?", GROUP BY / HAVING

Transactions & isolation ​

TaskCommandNotes
Startstart transaction; / begin;start transaction with consistent snapshot; pins the snapshot at once
Read-onlystart transaction read only;Slightly cheaper; read write is the default
Set level (next txn)set transaction isolation level serializable;Applies to the next transaction only
Set level (session)set session transaction isolation level read committed;GLOBAL for new connections
Levelsread uncommitted, read committed, repeatable read (default), serializableVariable is transaction_isolation
Autocommitset autocommit = 0;Default is 1; each statement commits by itself
Savepointssavepoint a; rollback to savepoint a; release savepoint a;
Commit / rollbackcommit; / rollback;
Row lockselect * from accounts where id = 1 for update;Locks index records; gap locks under REPEATABLE READ
Shared lockselect * from accounts where id = 1 for share;Replaces the old LOCK IN SHARE MODE
Fail fastselect ... for update nowait;Error 3572 if the row is locked
Queue workerselect * from jobs where state='new' order by id limit 10 for update skip locked;8.0+; skipped rows are not locked or returned
Lock only one tablefor update of ordersRequired when joining
Named lockselect get_lock('invoice-42', 5); ... select release_lock('invoice-42');Application-level, returns 1 on success
Table locklock tables t write; ... unlock tables;Rarely right with InnoDB
Global read lockflush tables with read lock;Blocks writes server-wide
Lock wait timeoutset session innodb_lock_wait_timeout = 5;Default 50 seconds; error 1205
Retry ruleRetry on 1213 (deadlock) and sometimes 1205Retry the whole transaction
Current locksselect * from performance_schema.data_locks;One row per held or requested lock

Admin & monitoring ​

TaskCommandNotes
Running threadsshow full processlist;Same data in information_schema.processlist and performance_schema.processlist
Long runningsee Diagnostic queries
Killkill query 123; / kill 123;kill query stops the statement, kill closes the connection
Who blocks whomselect * from sys.innodb_lock_waits\GShows waiting and blocking queries and a sql_kill_blocking_query
Raw lock waitsselect * from performance_schema.data_lock_waits;Join with data_locks
Open transactionssee Diagnostic queriesOld trx_started means a long transaction
Top statementssee Diagnostic queriesTimers are picoseconds
Friendlier top listsee Diagnostic queriessys schema formats times
Full table scansselect * from sys.statements_with_full_table_scans limit 10;
Reset digeststruncate table performance_schema.events_statements_summary_by_digest;
InnoDB statusshow engine innodb status\GSections: LATEST DETECTED DEADLOCK, TRANSACTIONS, BUFFER POOL AND MEMORY
Last deadlockLook in LATEST DETECTED DEADLOCKSet innodb_print_all_deadlocks=ON to log every one
Buffer pool hitshow global status like 'Innodb_buffer_pool_read%';reads / read_requests should be near zero
Table sizessee Diagnostic queriesEstimates; run analyze table first
Database sizesee Diagnostic queries
Connectionssee Diagnostic queriesCompare with max_connections
Replica statusshow replica status\GCheck Replica_IO_Running, Replica_SQL_Running, Seconds_Behind_Source, Last_Error
Source statusshow binary log status;Replaces SHOW MASTER STATUS
Replication threadsselect * from performance_schema.replication_applier_status_by_worker;Per-worker applier errors and lag
Binary logsshow binary logs;purge binary logs before '2026-11-01';
Slow query logset global slow_query_log = on; set global long_query_time = 0.5;Writes to slow_query_log_file

Diagnostic queries ​

Long queries moved out of the tables above, in table order; each table row points here.

Create table. InnoDB and utf8mb4 are the defaults in 8.4.

sql
CREATE TABLE orders (
    id bigint unsigned AUTO_INCREMENT PRIMARY KEY,
    user_id bigint unsigned NOT NULL,
    total decimal(12,2) NOT NULL DEFAULT 0,
    created_at datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Range partition. The partition key must be in every unique key.

sql
CREATE TABLE ev (
    id bigint,
    at datetime NOT NULL,
    PRIMARY KEY (id, at)
) PARTITION BY RANGE (to_days(at)) (
    PARTITION p1 VALUES LESS THAN (to_days('2026-12-01')),
    PARTITION pmax VALUES LESS THAN MAXVALUE
);

Index sizes. size is in pages.

sql
SELECT index_name, round(stat_value * @@innodb_page_size / 1024 / 1024) mb
FROM mysql.innodb_index_stats
WHERE database_name = 'shop' AND table_name = 'orders' AND stat_name = 'size';

Tables without a PK. Every InnoDB table should have a primary key.

sql
SELECT t.table_schema, t.table_name
FROM information_schema.tables t
LEFT JOIN information_schema.table_constraints c
       ON c.table_schema = t.table_schema
      AND c.table_name = t.table_name
      AND c.constraint_type = 'PRIMARY KEY'
WHERE t.table_type = 'BASE TABLE'
  AND c.constraint_name IS NULL
  AND t.table_schema NOT IN ('mysql','sys','information_schema','performance_schema');

Long running.

sql
SELECT id, user, time, state, left(info,80)
FROM information_schema.processlist
WHERE command <> 'Sleep'
ORDER BY time DESC;

Open transactions. Old trx_started means a long transaction.

sql
SELECT trx_id, trx_started, trx_mysql_thread_id, trx_rows_locked
FROM information_schema.innodb_trx
ORDER BY trx_started;

Top statements. Timers are picoseconds.

sql
SELECT digest_text, count_star, round(sum_timer_wait/1e12,2) total_s, round(avg_timer_wait/1e9,2) avg_ms
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC
LIMIT 10;

Friendlier top list. sys schema formats times.

sql
SELECT query, exec_count, total_latency, avg_latency
FROM sys.statement_analysis
LIMIT 10;

Table sizes. Estimates; run analyze table first.

sql
SELECT table_name, round((data_length+index_length)/1024/1024) mb
FROM information_schema.tables
WHERE table_schema = 'shop'
ORDER BY mb DESC
LIMIT 10;

Database size.

sql
SELECT table_schema, round(sum(data_length+index_length)/1024/1024) mb
FROM information_schema.tables
GROUP BY 1;

Connections. Compare with max_connections.

sql
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';

Role. Roles must be activated.

sql
CREATE ROLE 'readonly';
GRANT SELECT ON shop.* TO 'readonly';
GRANT 'readonly' TO 'app'@'10.%';
SET DEFAULT ROLE ALL TO 'app'@'10.%';

Config knobs ​

TaskCommandNotes
innodb_buffer_pool_sizeDefault 128MBResizable online; the 50 to 75 percent of RAM sizing rule is not verified
innodb_redo_log_capacityDefault 100MBReplaces innodb_log_file_size; the 1-8GB sizing advice is not verified
innodb_flush_log_at_trx_commitDefault 11 is fully durable; 2 flushes once per second to the OS
sync_binlogDefault 1Keep 1 with the above for crash-safe replication
max_connectionsDefault 151Raise only with enough memory; use a pooler or a per-app limit
innodb_lock_wait_timeoutDefault 50 (seconds)Lower for interactive apps
transaction_isolationDefault REPEATABLE-READREAD-COMMITTED reduces gap locking
innodb_io_capacityDefault 10000 (8.4)innodb_io_capacity_max defaults to twice this value
tmp_table_sizeDefault 16MBPer in-memory temp table; with max_heap_table_size
max_allowed_packetDefault 64MBRaise for large blobs or bulk inserts
binlog_expire_logs_secondsDefault 2592000 (30 days)Match your backup and replica catch-up window
wait_timeoutDefault 28800 (8 hours)Pool max lifetime must be shorter
long_query_timeDefault 10Lower to 0.5 or 1; with slow_query_log=ON
slow_query_logDefault OFFTurn on in production
character_set_serverDefault utf8mb4Pair with collation_server, for example utf8mb4_0900_ai_ci

Backup & restore ​

TaskCommandNotes
Consistent logical dumpmysqldump --single-transaction --routines --triggers --events shop > shop.sql--single-transaction gives an InnoDB snapshot without locking
All databasesmysqldump --all-databases --single-transaction > all.sqlIncludes the mysql system schema
With binlog positionmysqldump --single-transaction --source-data=2 shop > shop.sqlReplaces the old --master-data; records the coordinates for a new replica
Schema onlymysqldump --no-data shop > schema.sql
One tablemysqldump --single-transaction shop orders > orders.sql
Compressed streammysqldump --single-transaction shop | gzip > shop.sql.gz
Restoremysql shop < shop.sql / gunzip -c shop.sql.gz | mysql shopCreate the database first
GTID dumps--set-gtid-purged=OFFUse when restoring into a server with its own GTIDs
Physical copyClone plugin: clone local data directory = '/backup/clone';Needs install plugin clone soname 'mysql_clone.so'
Point in timemysqlbinlog --start-datetime='2026-11-25 10:00:00' binlog.000042 | mysqlReplay binary logs after restoring a full dump

Users, roles & grants ​

TaskCommandNotes
Create usercreate user 'app'@'10.%' identified by 'secret';The host part is part of the identity
Grantgrant select, insert, update, delete on shop.* to 'app'@'10.%';Since 8.0 grant does not create users
Show grantsshow grants for 'app'@'10.%';
Revokerevoke insert on shop.* from 'app'@'10.%';
Rolesee Diagnostic queriesRoles must be activated
Require TLSalter user 'app'@'10.%' require ssl;
Change passwordalter user 'app'@'10.%' identified by 'new';Default plugin is caching_sha2_password
Resource limitsalter user 'app'@'10.%' with max_user_connections 20;
Lock / dropalter user 'x'@'%' account lock; / drop user 'x'@'%';
Grant optiongrant select on shop.* to 'a'@'%' with grant option;Lets the user pass the privilege on
Who am Iselect current_user(), @@global.version;

Common errors ​

TaskCommandNotes
1062 ER_DUP_ENTRY (23000)Duplicate entry for keyUse ON DUPLICATE KEY UPDATE or map to 409
1213 ER_LOCK_DEADLOCK (40001)Deadlock found; try restarting transactionOrder locks consistently; retry the transaction
1205 ER_LOCK_WAIT_TIMEOUT (HY000)Lock wait timeout exceededFind the blocker in sys.innodb_lock_waits
3572 ER_LOCK_NOWAIT (HY000)Statement aborted because lock(s) could not be acquired immediatelyNOWAIT hit; retry later
1452 ER_NO_REFERENCED_ROW_2 (23000)Cannot add or update a child rowParent row missing
1451 ER_ROW_IS_REFERENCED_2 (23000)Cannot delete or update a parent rowChild rows exist
1045 ER_ACCESS_DENIED_ERROR (28000)Access denied for userCheck host part of the account and auth plugin
1040 ER_CON_COUNT_ERROR (08004)Too many connectionsPool, or raise max_connections
1049 ER_BAD_DB_ERROR (42000)Unknown database
1146 ER_NO_SUCH_TABLE (42S02)Table does not exist
1054 ER_BAD_FIELD_ERROR (42S22)Unknown column
1064 ER_PARSE_ERROR (42000)You have an error in your SQL syntax
1406 ER_DATA_TOO_LONG (22001)Data too long for columnStrict mode turns truncation into an error
2006 / 2013 (client)MySQL server has gone away / Lost connection during queryCheck wait_timeout, max_allowed_packet, restarts

Go snippets ​

go
// go get github.com/go-sql-driver/mysql
import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

db, err := sql.Open("mysql", "app:secret@tcp(db:3306)/shop?parseTime=true&loc=UTC&charset=utf8mb4&collation=utf8mb4_0900_ai_ci&timeout=5s&readTimeout=30s")
if err != nil { return err }
db.SetConnMaxLifetime(3 * time.Minute) // below wait_timeout and proxy idle limits
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
if err := db.PingContext(ctx); err != nil { return err }

// Query one row
var email string
err = db.QueryRowContext(ctx, "select email from users where id = ?", id).Scan(&email)

// Query many rows
rows, err := db.QueryContext(ctx, "select id, email from users where active = ?", 1)
if err != nil { return err }
defer rows.Close()
for rows.Next() { /* rows.Scan(...) */ }

// Transaction
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
if err != nil { return err }
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "update accounts set balance = balance - ? where id = ?", amt, from); err != nil { return err }
return tx.Commit()
TaskCommandNotes
DSN shapeuser:password@tcp(host:3306)/dbname?param=valueParam values must be URL-escaped, for example loc=Europe%2FBerlin
Time valuesparseTime=trueReturns time.Time instead of bytes; add loc=
Timeoutstimeout (dial), readTimeout, writeTimeoutDuration strings such as 5s
Duplicate keyvar me *mysql.MySQLError; errors.As(err, &me); me.Number == 1062Compare against error numbers
Multi statementsmultiStatements=trueOff by default; widens SQL-injection impact
PlaceholdersinterpolateParams=trueClient-side interpolation, saves a round trip

Laravel snippets ​

php
// config/database.php (env: DB_CONNECTION=mysql, DB_URL=mysql://app:secret@db:3306/shop)
'mysql' => [
    'driver' => 'mysql',
    'url' => env('DB_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'laravel'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => env('DB_CHARSET', 'utf8mb4'),
    'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
    'prefix_indexes' => true,
    'strict' => true,
],

$rows = DB::select('select * from users where active = ?', [1]);
DB::statement('drop table temp_users');
DB::transaction(function () {
    DB::update('update accounts set balance = balance - 10 where id = ?', [1]);
}, attempts: 3);

$acct = DB::table('accounts')->where('id', $id)->lockForUpdate()->first(); // inside a transaction
$rows = DB::table('posts')->where('votes', '>', 100)->sharedLock()->get();
TaskCommandNotes
Raw read / writeDB::select(), DB::insert(), DB::update(), DB::delete(), DB::statement()Always bind values with ?
Manual transactionDB::beginTransaction(); DB::commit(); DB::rollBack();DB::transaction($cb, $attempts) retries on deadlock
Pessimistic locks->lockForUpdate() / ->sharedLock()Map to FOR UPDATE and the shared lock clause; only valid inside a transaction
UpsertDB::table('kv')->upsert($rows, ['k'], ['v']);Generates ON DUPLICATE KEY UPDATE on MySQL
Log queriesDB::listen(fn ($q) => logger($q->sql, $q->bindings));Service provider
Read replicas'read' => ['host' => [...]], 'write' => ['host' => [...]], 'sticky' => truesticky reads your own writes within the request

References ​

Built by Morteza Negahi