A MySQL cheat sheet is a single-page reference of the most common MySQL commands and SQL syntax, grouped by what you are trying to do: log into the server, create databases and tables, manipulate rows, join across tables, manage users, take backups, debug a stuck query. This one covers MySQL 5.5 through 8.4 and 9.x. Every category has copy-paste syntax, an "as of which version" note where it matters, and an input box at the top to swap the placeholder names (mydb, users, etc.) for your own table and column names — the rest of the card updates as you type.
What is the MySQL cheat sheet for?
This cheat sheet is the one-page lookup for the MySQL commands you reach for most often: logging in (mysql -u root -p), database operations (SHOW DATABASES, CREATE DATABASE, USE mydb), backup and restore (mysqldump --single-transaction --routines --events), table operations (CREATE TABLE, ALTER TABLE, DESCRIBE), data manipulation (INSERT, UPDATE, DELETE, SELECT), joins (INNER, LEFT, RIGHT), indexes (CREATE INDEX, EXPLAIN), user management (CREATE USER, GRANT), and transactions (START TRANSACTION, COMMIT, ROLLBACK). Each entry has the copy-paste syntax plus a one-line explanation; the version-compatibility table further down spells out which features (window functions, CTEs, ALGORITHM=INSTANT, the caching_sha2_password auth plugin, the new VECTOR type in 9.0) require MySQL 8.0 or later. Use it as a single-page reference when you remember the shape of a command but not the exact flags.
MySQL Cheat Sheet
MySQL Cheat Sheet reference covering essential CLI commands, database operations, functions, joins, indexes, and best practices. Includes practical examples and syntax for common MySQL operations.
Step-by-step walkthroughs by task
The cheat sheet above is the one-line syntax. For the cases where the syntax is not enough — picking between three correct methods, dealing with edge cases like NULL values or huge tables, or migrating between MySQL versions — there is a deeper walkthrough for every common task. Linked by the search intent that brings people here.
Finding and removing duplicate rows
Duplicate rows are almost always the result of a missing UNIQUE constraint, and they show up in customer lists, webhook event logs, mail queues, anywhere data gets imported repeatedly. There are three correct ways to identify them and three correct ways to remove them.
- How to find duplicate rows in MySQL —
GROUP BY ... HAVING COUNT(*) > 1,ROW_NUMBER()window function (MySQL 8.0+), and the self-join pattern that works on every MySQL version. With NULL handling, case- and whitespace-insensitive matching, and the index that makes it fast. - How to delete duplicate rows in MySQL — Delete extras while keeping one per group, using
DELETEwith a self-join,DELETEwith aROW_NUMBER()CTE, or the safer temp-table swap for huge tables. Includes the dry-run-first pattern and adding theUNIQUEconstraint afterwards.
Schema changes on a live table
ALTER TABLE is the workhorse, and on a production table that is being read and written constantly, the version matters. MySQL 8.0.12 introduced ALGORITHM=INSTANT for column additions, which finishes in milliseconds even on tables with hundreds of millions of rows.
- How to add a column to a MySQL table —
ALTER TABLE ADD COLUMNwithDEFAULTvalues, the three-step pattern forNOT NULLon a table that already has rows,AFTERpositioning, andALGORITHM=INSTANTfor online changes that do not lock. - How to change a MySQL column type — Widening
INTtoBIGINT, growing aVARCHAR, narrowing safely, and converting between text and numeric columns without losing data. WithMODIFYvsCHANGEand a rollback strategy.
Exporting and importing data
Two of the most-asked operational questions: how do I get this data out of MySQL into a file, and how do I get a CSV from somewhere else loaded back in.
- How to export a MySQL table to CSV —
SELECT INTO OUTFILE,mysqldump --tab, themysqlclient piped to a file (for managed databases where you do not have theFILEprivilege), and a Python-based pipeline that correctly handles commas and quotes inside the data. - How to import a CSV file into MySQL —
LOAD DATA INFILE,LOAD DATA LOCAL INFILEfor client-side files,mysqlimportfor batch jobs. With header-row handling, character-encoding fixes, and column-list mapping when the CSV does not match the table.
Joining and comparing across tables
JOINs are where most non-trivial queries live. The right join type for your question matters more than syntax fluency.
- How to JOIN two MySQL tables —
INNER JOIN,LEFT JOIN,RIGHT JOIN, when each matches, and the row-multiplication mistake that produces unexpected duplicates. - How to find rows in one MySQL table not in another — The anti-join pattern:
LEFT JOIN ... IS NULL,NOT EXISTS,NOT IN(and the NULL trap that makes the last one return zero rows when you least expect it).
Server administration
The two things you Google for at 3 a.m. when the server is acting up.
- How to reset a forgotten MySQL root password —
--skip-grant-tables,--init-file, and themy.cnfpermanent reset. Step-by-step for 5.7, 8.0, and the auth-plugin changes that landed in 8.4.
Formatting datetime columns
- How to format a MySQL DATETIME in a SELECT —
DATE_FORMATwith the specifiers you actually use (%Y-%m-%d %H:%i:%s,%W, %M %D, %Y, etc.), common presets for ISO 8601, RFC 2822, and human-readable output, plusCONVERT_TZfor timezone-correct dashboards.
MySQL version compatibility quick reference
Some commands and features behave differently across MySQL versions. The headline differences are window functions and common table expressions (8.0), instant column additions (8.0.12), and the authentication plugin change in 8.4.
| Version | GA release | Window functions | CTEs (WITH) | ALGORITHM=INSTANT | Default auth plugin | VECTOR type |
|---|---|---|---|---|---|---|
| MySQL 5.5 | Dec 2010 | No | No | No | mysql_native_password | No |
| MySQL 5.6 | Feb 2013 | No | No | No | mysql_native_password | No |
| MySQL 5.7 | Oct 2015 | No | No | No | mysql_native_password | No |
| MySQL 8.0 | Apr 2018 | Yes | Yes | 8.0.12+ | caching_sha2_password | No |
| MySQL 8.4 LTS | Apr 2024 | Yes | Yes | Yes | caching_sha2_password | No |
| MySQL 9.0+ Innovation | Jul 2024 | Yes | Yes | Yes | caching_sha2_password | Yes |
If a SQL pattern in this cheat sheet uses ROW_NUMBER(), RANK(), WITH ... AS, or ALGORITHM=INSTANT, the minimum version is 8.0. The VECTOR data type and the matching DISTANCE() function for similarity search are 9.0+ only (innovation track, not yet in an LTS release). For applying that in practice, see How to Add Semantic Search to a MySQL App. Everything else works on 5.5 and later.
Modern MySQL syntax worth knowing
A few patterns that are easy to miss because they post-date the 5.7 documentation most people learned from:
- Common Table Expressions (CTEs) since 8.0.
WITH active AS (SELECT * FROM users WHERE status = 'active') SELECT COUNT(*) FROM active;. Recursive CTEs (WITH RECURSIVE) traverse hierarchies (employee/manager, category trees) without chained self-joins. - JSON path expressions since 5.7, with more operators in 8.0.
SELECT payload->>'$.user.email' FROM events;extracts a JSON value as text. The->operator returns a JSON value;->>returns it unquoted as text.JSON_TABLE()(8.0+) turns a JSON array into a relational rowset for joining. ALGORITHM=INSTANTfor column additions since 8.0.12.ALTER TABLE users ADD COLUMN last_seen DATETIME, ALGORITHM=INSTANT;finishes in milliseconds even on tables with hundreds of millions of rows because it only updates metadata. Walked through in detail in How to Add a Column to a MySQL Table.- The
VECTORtype andDISTANCE()function since 9.0.CREATE TABLE docs (id INT PRIMARY KEY, embedding VECTOR(1536));stores an OpenAI-shaped embedding;SELECT id FROM docs ORDER BY DISTANCE(embedding, ?, 'COSINE') LIMIT 10;runs the nearest-neighbour query. Full walkthrough at How to Add Semantic Search to a MySQL App. mysqldump --single-transaction --routines --eventsas the right default. The flag combination dumps a consistent snapshot of InnoDB data without holding write locks, plus the stored procedures, functions, and event scheduler entries that a baremysqldumpskips. Detail in How to Export or Back Up All MySQL Databases.
Common MySQL error codes and quick fixes
These are the eight error codes that account for most "MySQL is broken" questions. Each one has a single common cause and a single common fix.
| Error code | Message | Most common cause | Quick fix |
|---|---|---|---|
| 1045 | Access denied for user | Wrong password, wrong host in user grant, or expired password | Verify with SELECT user, host FROM mysql.user; check IDENTIFIED BY or reset the password |
| 1062 | Duplicate entry for key | An INSERT violated a UNIQUE constraint | Use INSERT ... ON DUPLICATE KEY UPDATE or pre-check with SELECT |
| 1146 | Table doesn't exist | Wrong database selected with USE, or table was dropped | SHOW TABLES and SHOW DATABASES to confirm |
| 1205 | Lock wait timeout exceeded | Another transaction holding the row lock for too long | Find with SHOW PROCESSLIST and SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX; kill the blocking transaction |
| 1364 | Field doesn't have a default value | NOT NULL column inserted without value, in strict SQL mode | Provide a value, add a DEFAULT, or relax the column to nullable |
| 1452 | Cannot add or update child row: foreign key constraint fails | Referenced row missing in parent table | Insert the parent row first or fix the foreign-key value |
| 1366 | Incorrect integer value | String being inserted into an INT column, with strict mode on | Cast in the query or clean the source data |
| 2002 | Can't connect to local MySQL server through socket | mysqld is not running, or the socket path is wrong | Check systemctl status mysql; verify socket= in my.cnf matches |
For the full list of MySQL error codes and their server-side detail, the official reference is the MySQL server error message reference.
Frequently asked questions
External MySQL references
For anything not on this page, the canonical sources are the official Oracle-maintained docs and the curated landing pages:
- Official MySQL Reference Manual (8.0) — the long form for every clause, function, and system variable
- Official MySQL Reference Manual (8.4 LTS) — the long-term-support release manual for 8.4 specifics
- MySQL server error message reference — every numeric error code and what it means
- Regex Cheat Sheet on TechEarl — pattern syntax for
WHERE col REGEXP ...queries inside MySQL, with engine compatibility for the PCRE-like form MySQL 8.0+ uses - Elasticsearch Cheat Sheet on TechEarl — the companion search engine you typically index FROM MySQL into when full-text search, faceted browsing, or vector / kNN retrieval outgrows what MySQL can do
- MySQL Online Schema Change Tools — when ALGORITHM=INSTANT does not cover the change, the pt-online-schema-change and gh-ost tools that rewrite the table online
- MySQL to MariaDB Migration — when you outgrow MySQL and want to switch, the version-compatibility map and the dump-and-load path
- Database category on TechEarl — the rest of the MySQL writeups on this site, plus PostgreSQL and MongoDB notes





