Skip to main content
Quick Reference

MySQL Cheatsheet

MySQL 8 on one page — tables, inserts, selects, updates, joins, grouping, indexes, transactions, and the traps around NULL and DELETE.

10 sections 10 tables 14 code snippets

Connect & look around

Open the client

mysql -u app -p shop

See what is there

USE shop;
SHOW TABLES;
DESCRIBE books;

The names

NameMeaning
DatabaseA namespace. USE shop makes it the default for this session
TableRows of a fixed shape. books holds one row per book
ColumnOne field. title VARCHAR(200) is text up to 200 characters
Port 3306The local default
-pPrompts for the password. A password glued to -p shows up in the process list
SemicolonThe client sends the statement when it sees ;. Without it, the prompt waits

This page is MySQL 8 with InnoDB, the default engine. New databases use utf8mb4.

Create a table

A book row

CREATE TABLE books (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(200) NOT NULL,
  pages INT NOT NULL,
  price DECIMAL(8, 2) NOT NULL,
  published DATE NULL,
  CONSTRAINT pages_chk CHECK (pages > 0)
);

Column rules

PieceEffect
PRIMARY KEYUnique, and the row is found by it. One per table
AUTO_INCREMENTThe server fills the next integer when you omit id
NOT NULLThe column must have a value. NULL means unknown, not empty text
VARCHAR(200)A character limit, not a byte limit
DECIMAL(8, 2)Exact money. 8 is the total digits, 2 of them after the point
CHECKEnforced since MySQL 8.0.16. A result of FALSE rejects the row. NULL in the check is allowed

Insert

Name the columns

INSERT INTO books (title, pages, price)
VALUES ('Dune', 412, 18.50);

INSERT INTO books (title, pages, price)
VALUES
  ('Neuromancer', 271, 14.00),
  ('Foundation', 255, 12.50);

What the server fills in

You omitYou get
idThe next AUTO_INCREMENT value
A NULL columnNULL, unless the column has a DEFAULT
A NOT NULL column with no defaultThe insert fails
Column listValues line up by position with the names you wrote
INSERT with no column listYou must supply every column, in table order. A new column breaks it
String quotesSingle quotes hold text, as in the insert above. Double quotes are strings too, unless ANSI_QUOTES is on

Select

Filter, sort, page

SELECT title, pages
FROM books
WHERE pages >= 300
ORDER BY pages DESC
LIMIT 10;

Unknown dates

SELECT title
FROM books
WHERE published IS NULL;

The clause order

ClauseJob
SELECTThe columns in the result. AS sold renames one
WHEREKeeps rows before any grouping. Comparisons, IN, BETWEEN, LIKE
AND / ORAND binds tighter. Parentheses make a mix obvious
ORDER BY titleAscending. DESC flips that column
LIMIT 10 OFFSET 20Skip 20, then return 10
IS NULLThe only test for NULL. = NULL is never true

Update & delete

Change a price

UPDATE books
SET price = 19.00
WHERE title = 'Dune';

Remove the short ones

DELETE FROM books
WHERE pages < 100;

Write rules

StatementTouches
UPDATE ... SETThe named columns on rows that pass WHERE
DELETE FROMWhole rows that pass WHERE. The table stays
No WHEREEvery row. The client will not ask you to confirm
ROW_COUNT()How many rows the last statement actually changed or removed
DROP TABLE booksThe table itself, including its indexes
TRUNCATE TABLE booksEmpties the table and resets AUTO_INCREMENT. It implies a commit

Joins

Orders with their book

SELECT o.id, b.title, o.amount
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id;

SELECT o.id, b.title
FROM orders AS o
LEFT JOIN books AS b ON b.id = o.book_id;

Which rows survive

JoinKeeps
INNER JOINOnly rows that match on both sides
LEFT JOINEvery row from the left table. Missing right-side columns are NULL
ONThe match. A join without it is a syntax error
AS oA short name. Required when both tables have id
Filter a left-side NULLWHERE b.id IS NULL finds orders whose book is gone
A condition in WHEREIt runs after the join and can turn a LEFT JOIN back into an inner join

Group & count

Revenue per book

SELECT b.id, b.title,
       COUNT(*) AS sold,
       SUM(o.amount) AS revenue
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id
GROUP BY b.id, b.title
HAVING SUM(o.amount) > 100
ORDER BY revenue DESC;

Aggregate rules

FormMeaning
COUNT(*)Rows in the group, including rows with NULL
COUNT(published)Rows where published is not NULL
SUM / AVGSkip NULL. AVG of an empty group is NULL, not zero
GROUP BY b.id, b.titleOne result row per pair. With ONLY_FULL_GROUP_BY, every selected column is grouped or aggregated
HAVINGFilters groups. WHERE cannot see SUM
SortGROUP BY does not sort in MySQL 8. Add ORDER BY

Indexes & foreign keys

Look up by title, point at a book

CREATE INDEX idx_books_title ON books (title);

CREATE TABLE orders (
  id INT PRIMARY KEY AUTO_INCREMENT,
  book_id INT NOT NULL,
  amount DECIMAL(8, 2) NOT NULL,
  CONSTRAINT fk_orders_book
    FOREIGN KEY (book_id) REFERENCES books (id)
);

What the planner can use

KeyServes
PRIMARY KEYUnique lookup and the row order InnoDB stores
INDEX (title)Equality, range, and sort on title
(title, pages)Queries on title, and on title plus pages. Not on pages alone
UNIQUERejects a second row with the same value. Several NULLs are allowed
FOREIGN KEYEvery book_id must exist in books.id. The types must match, including signed or unsigned
ON DELETE RESTRICTThe default. Deleting a book that still has orders fails. CASCADE deletes the orders too

EXPLAIN SELECT title FROM books WHERE title = 'Dune' shows the plan. type: ALL is a full table scan.

Transactions

Two writes, one outcome

START TRANSACTION;
UPDATE books SET price = price - 1.00 WHERE id = 1;
INSERT INTO orders (book_id, amount) VALUES (1, 17.50);
COMMIT;

When the work sticks

FactWhy it matters
Autocommit is onA single statement commits itself
START TRANSACTIONThe following statements stay open until COMMIT or ROLLBACK
ROLLBACKUndoes the open transaction. It cannot undo a commit
InnoDBThe engine that honors transactions and foreign keys
MyISAMIgnores transactions and foreign keys. It is not the default
CREATE / ALTERCause an implicit commit, even in the middle of a transaction

Interview traps

Traps worth memorising

TrapWhat happensPrefer
UPDATE or DELETE with no WHEREEvery row changesA WHERE you have already SELECTed
WHERE published = NULLNever matches. The comparison is unknownIS NULL or IS NOT NULL
COUNT(published)Skips NULL, so the total looks shortCOUNT(*) for rows
Selecting title while grouping by idRejected when ONLY_FULL_GROUP_BY is on, which is the defaultGroup by every plain column, or aggregate it
LIMIT 20, 10Offset 20, then 10 rows. The first number is not the page sizeLIMIT 10 OFFSET 20
Charset utf8That name is utf8mb3, three bytes per character. Emoji does not fitutf8mb4
INT(11)Does not limit the value to 11 digits. The range of INT is fixedINT, and DECIMAL for exact numbers
Dune and dune compare equalTrue under the default utf8mb4_0900_ai_ci collationA _bin or _as_cs collation when case matters
Left join, then WHERE b.title = 'Dune'Unmatched left rows disappear, because NULL fails the testPut that test in the ON clause
Foreign key to a column of another typeThe constraint is rejectedThe same type, including UNSIGNED
CHECK on MySQL 5.7The clause was parsed and ignoredMySQL 8.0.16 or newer, where it is enforced
TRUNCATE inside a transactionIt commits the open transactionDELETE when you still need ROLLBACK

The null test

WHERE published IS NULL

The page

LIMIT 10 OFFSET 20

How to use this page: connect with mysql -u app -p shop, create books, and insert one row. Then select it with a WHERE, and update the price with a WHERE you have already checked.