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 Open the client mysql -u app -p shop See what is there USE shop;
SHOW TABLES;
DESCRIBE books; This page is MySQL 8 with InnoDB, the default engine. New databases use utf8mb4. 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)
); 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); 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; Change a price UPDATE books
SET price = 19.00
WHERE title = 'Dune'; Remove the short ones DELETE FROM books
WHERE pages < 100; 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; 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; 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)
); EXPLAIN SELECT title FROM books WHERE title = 'Dune' shows the plan. type: ALL is a full table scan. 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; 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. |