// référence gratuite

MySQL cheat sheet

Everyday MySQL in the syntax MySQL 8.0 and 8.4 accept: backticked names, AUTO_INCREMENT, ON DUPLICATE KEY UPDATE and utf8mb4. MariaDB runs most of it; the row-alias upsert and functional indexes are MySQL-only.

sqlly.app/sql-cheat-sheets/mysql

SELECT basics

Everything from a table
SELECT * FROM customers;
First 10 rows, ordered
SELECT * FROM customers ORDER BY last_name LIMIT 10;
Expression with an alias
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM customers;
Unique values
SELECT DISTINCT country FROM customers;
Quote a name that is a reserved word
SELECT `order`, `status` FROM jobs;

Jointures

Inner join
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;
Left join keeps unmatched rows
SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;
Join on equal column names with USING
SELECT i.order_id, s.shipped_at FROM order_items i JOIN shipments s USING (order_id);
Self join
SELECT e.name, manager.name FROM employees e JOIN employees manager ON manager.id = e.manager_id;

Filtrage

Combined conditions
SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';
Range and lists
SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');
Pattern match
SELECT * FROM customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';
Full-text search
SELECT * FROM products WHERE MATCH (name, description) AGAINST ('laptop');
Exists elsewhere
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Aggregation

Count per group
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;
Groups after filtering with HAVING
SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;
Aggregate text with GROUP_CONCAT
SELECT country, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') FROM customers GROUP BY country;
Rank within a partition
SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;
Every selected column must be grouped
SELECT country, status, COUNT(*) FROM orders GROUP BY country, status;

Insert, update, delete

Single and multi-row insert
INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace'), ('Grace', 'Hopper');
Insert or skip duplicates
INSERT IGNORE INTO subscribers (email) VALUES ('[email protected]');
Upsert with ON DUPLICATE KEY UPDATE (row alias: 8.0.19+)
INSERT INTO stock (sku, count) VALUES ('A1', 5) AS new ON DUPLICATE KEY UPDATE count = stock.count + new.count;
Update through a join
UPDATE customers c JOIN totals t ON t.customer_id = c.id SET c.tier = 'gold' WHERE t.spent >= 1000;
Delete in batches
DELETE FROM audit_events WHERE archived = 1 LIMIT 100;

Create, alter, drop

Create a table
CREATE TABLE orders (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, customer_id BIGINT UNSIGNED NOT NULL, total DECIMAL(10,2) NOT NULL DEFAULT 0, placed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
Add a column
ALTER TABLE customers ADD COLUMN tier VARCHAR(20) NOT NULL DEFAULT 'standard';
Change a column type
ALTER TABLE customers MODIFY COLUMN tier VARCHAR(40) NOT NULL DEFAULT 'standard';
Drop if it exists
DROP TABLE IF EXISTS temp_results;

Index

Index a join key
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
Composite index
CREATE INDEX idx_orders_placed ON orders (placed_at DESC, customer_id);
Unique index
CREATE UNIQUE INDEX ux_customers_email ON customers (email);
Full-text index
CREATE FULLTEXT INDEX ft_products_text ON products (name, description);
Functional index (8.0.13+, note the double parentheses)
CREATE INDEX idx_users_email_lc ON users ((LOWER(email)));

String functions

Length and case
SELECT CHAR_LENGTH(name), LOWER(email), UPPER(code) FROM customers;
Substring and position
SELECT SUBSTRING(name, 1, 3), LOCATE('@', email) FROM customers;
Concatenate
SELECT CONCAT(first_name, ' ', last_name) FROM customers;
Trim and replace
SELECT TRIM(name), REPLACE(code, '-', '') FROM customers;

Date functions

En ce moment
SELECT NOW(), CURDATE();
Subtract an interval
SELECT DATE_SUB(NOW(), INTERVAL 7 DAY);
Recent rows
SELECT * FROM orders WHERE placed_at >= NOW() - INTERVAL 30 DAY;
Difference in days
SELECT DATEDIFF(NOW(), placed_at) FROM orders;
Format and extract
SELECT DATE_FORMAT(placed_at, '%Y-%m-%d'), EXTRACT(YEAR FROM placed_at) FROM orders;

NULL handling

Substitute a default
SELECT IFNULL(nickname, first_name) FROM customers;
First non-NULL of many
SELECT COALESCE(nickname, first_name, 'unknown') FROM customers;
Guard a division by zero
SELECT total / NULLIF(quantity, 0) FROM orders;
Null-safe equality (NULL <=> NULL is 1)
SELECT * FROM products p JOIN supplies s ON s.sku = p.sku WHERE NOT (p.price <=> s.price);

Paging

Page 3, 10 rows per page
SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;
Shorter LIMIT offset, count form
SELECT * FROM orders ORDER BY placed_at DESC LIMIT 20, 10;

MySQL quirks worth knowing

  • Identifiers get backticks. `order` et `group` are quoted names because they are reserved words. In the default SQL mode double quotes are strings, not identifiers.
  • Row counts use LIMIT. LIMIT 10 OFFSET 20, or the shorter LIMIT 20, 10. There is no TOP and no OFFSET/FETCH.
  • Keys are AUTO_INCREMENT. Declare an integer key AUTO_INCREMENT and MySQL fills it in; read back the new value with LAST_INSERT_ID() on the same connection.
  • Case sensitivity lives in the collation. String comparison and LIKE are case-insensitive under the default utf8mb4 collations; COLLATE utf8mb4_bin ou un _cs collation forces exact matching.
  • utf8mb4, not utf8. MySQL's utf8 charset stores only three bytes and cannot hold every character; new tables use CHARACTER SET utf8mb4.

Other SQL cheat sheets

To run this sheet against a live database, get the SQLly desktop app for MySQL, ou parcourez toutes les fonctionnalités.

MySQL cheat sheet FAQ

How do I limit rows in MySQL?

Append LIMIT 10, and OFFSET 20 to skip rows; LIMIT 20, 10 is the same thing in offset-then-count order. TOP and FETCH FIRST are other engines' syntax.

How do I get the ID of the row I just inserted?

Call LAST_INSERT_ID() on the same connection right after the INSERT. It returns the first auto-generated key of the statement, even for a multi-row insert.

Why is my WHERE comparison case-insensitive?

The default utf8mb4 collations compare case-insensitively, so 'ada' = 'Ada'. Write WHERE name COLLATE utf8mb4_bin = 'Ada', or declare the column with a binary or _cs collation when it matters. Database and table names are a separate matter: they map to files, so they are case-sensitive on Linux by default (lower_case_table_names = 0). Column names are never case-sensitive.

Should I use utf8 or utf8mb4?

utf8mb4. MySQL's utf8 is an alias for utf8mb3, which stores at most three bytes per character and cannot hold anything outside the Basic Multilingual Plane, emoji included. utf8mb4 is the default from MySQL 8.0, with utf8mb4_0900_ai_ci as its default collation; older schemas often still carry utf8mb3 columns.

// the sheet is the start

Run these against your own database

SQLly is a native SQL workbench for macOS, Windows and Linux. It connects to all five engines on these sheets, and its IntelliSense completes from your real schema.