MySQL
medium 32 minMySQL is an open-source relational database whose InnoDB engine keeps each table's rows inside its primary key index.
Video lesson · Chapter 1 of 5
Find the book called Cats
MySQL in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
MySQL is a relational database server: an SQL layer that connects, parses and plans, above pluggable storage engines that keep the data. The default engine, InnoDB, has transactions, row locks, multi-version reads, crash recovery and foreign keys. The Community Edition is released under GPL version 2; Oracle also sells an Enterprise Edition.
Three logs explain most of it. The redo log lets InnoDB survive a crash, the undo log keeps old values for rollback and readers, and the binary log tells the rest of the world what changed.
Why it exists
Many applications read and write single rows by key, thousands of times a second. A table that is stored in key order answers these with one walk down one tree.
The second reason is copying. Replication, routing, failover and sharding tools around MySQL are old, well known and widely used, so there is a proven road from one server to many.
A short history
2010
Engineers at YouTube create Vitess when MySQL approaches its limits there.
April 2018
Version 8.0.11 is released, the first for general use in the 8.0 series, with window functions and common table expressions.
November 2019
Vitess graduates as a project of the Cloud Native Computing Foundation.
April 2026
Version 9.7.0 is released. 9.7 is a long-term support series, five years of premier and three of extended support.
July 2026
Innovation releases start to use the year and month as their number, beginning with 26.7.
Words to know
- InnoDB
- The default storage engine, with ACID transactions.
- Clustered index
- The primary key B-tree whose leaves hold the whole rows.
- Secondary index
- Any other index. Its entries hold the primary key, not an address.
- Buffer pool
- InnoDB's cache of 16 KB pages in memory.
- Redo log
- Write-ahead log of page changes, replayed after a crash.
- Undo log
- Old row values, for rollback and for readers with older snapshots.
- Binary log
- Ordered record of committed changes, for replicas and recovery.
- GTID
- Global transaction identifier: source id and a number.
- Next-key lock
- A lock on an index record and on the gap before it.
How it works
Step through the idea, or press Play.
Store by key. Rows live in the leaves of the primary key tree
Understand it
Start here
The bindery
Imagine a bindery where loose pages stand on one shelf in order of their page number. A diary lists every change, and a messenger carries copies of the diary to branch offices.
One shelf in one order, a diary for everyone else.
The product
What you get
Transactions
ACID with row locks, crash recovery and foreign keys in InnoDB.
Fast key access
Rows sit in the primary key tree, so a lookup or a key range is one walk.
Replication
Asynchronous, semi-synchronous, or a group with automatic failover.
Known operations
Backups, proxies, online schema changes and sharding tools with long experience.
Online changes
Adding a column is usually instant. Adding an index allows writes meanwhile.
Two tracks
Long-term support such as 9.7 for stability, Innovation releases for new features.
InnoDB limits
| What | Limit |
|---|---|
| One table, 16 KB pages | 64 TB |
| Columns per table | 1,017 |
| Secondary indexes | 64 |
| Columns in an index | 16 |
| Index key | 3,072 bytes with the DYNAMIC row format |
| Row without long fields | About 8,000 bytes |
Inside
From connection to engine
One server, two layers
- 1
Connect
Port 3306 by default, TLS available. Each connection gets a thread, often a cached one.
max_connectionsis 151 by default, and one more is kept for administrators. - 2
Parse and optimise
Text becomes a tree, rewrite plugins may change it, and a cost model picks indexes and the join order from statistics. There is no query result cache since 8.0.
- 3
Execute
The executor calls the engine's interface row by row or range by range.
- 4
Use an engine
InnoDB for everything that matters. MyISAM is legacy: no transactions, table locks. MEMORY tables vanish at restart.
- 5
Answer and log
Committed changes go to the binary log, and the client gets its result.
Through the layers
Inside
The table is an index
InnoDB keeps rows in the leaves of the clustered index, a B-tree on the primary key. Without a primary key it uses the first unique index on NOT NULL columns, and otherwise a hidden 6-byte row id. Every secondary index entry carries the primary key.
Two ways to a row
What a long primary key costs
BINARY(16). Random ones also scatter inserts over the whole tree.Good primary keys
- Short and never changed
- Growing: auto-increment or time-ordered
- Wide enough: BIGINT for tables that grow
- Compound by tenant when you read by tenant
Costly primary keys
- A long string or an email
- A random UUID as text
- No key at all
- INT on a table that may pass about 4.29 billion unsigned
Inside
Buffer pool and the path to disk
Pages of 16 KB are cached in the buffer pool. New pages enter at a midpoint: 3/8 of the list is the old part, so one large scan does not push out everything hot. The manual says that on dedicated servers up to 80% of memory is often given to it; 60% to 80% leaves room for connections. The default is only 128 MB.
Hit ratio
Innodb_buffer_pool_reads and Innodb_buffer_pool_read_requests. Look at disk reads per second as well: 0.2% of a huge number is still a lot.One commit
How durable is a commit?
innodb_flush_log_at_trx_commit | At commit | Can lose |
|---|---|---|
| 1 (default) | Write and flush | Nothing on a server crash |
| 2 | Write, flush about once a second | About a second on power loss |
| 0 | Nothing, write and flush about once a second | About a second even if only the process dies |
sync_binlog = 1 (also the default) when the data matters.The doublewrite buffer first writes flushed pages to a separate area, so a half-written page can be repaired after a crash. It does not cost twice the I/O, because that write is sequential. Redo space is set by innodb_redo_log_capacity, 100 MB by default and split over about 32 files. More space means calmer flushing and a longer recovery.
Correctness
Versions, isolation and locks
Each row carries the id of its last transaction and a pointer into the undo log. A reader with an older snapshot follows the pointer back. Readers do not block writers. A purge thread removes undo nobody needs, so a forgotten transaction makes undo grow.
The levels in InnoDB
| Level | Plain SELECT | Locking reads and updates |
|---|---|---|
| Read uncommitted | May see uncommitted rows | As read committed |
| Read committed | A fresh snapshot per statement | Record locks, gap locks only for foreign key and duplicate checks |
| Repeatable read (default) | One snapshot from the first read | Next-key locks on scanned ranges |
| Serializable | Becomes a shared locking read when autocommit is off | As repeatable read |
SELECT @@transaction_isolation; -- REPEATABLE-READSTART TRANSACTION;SELECT id, balance FROM accountsWHERE id IN (100, 200) ORDER BY id FOR UPDATE; -- same order everywhereUPDATE accounts SET balance = balance - 500 WHERE id = 100;UPDATE accounts SET balance = balance + 500 WHERE id = 200;INSERT INTO transfer_log (from_account, to_account, amount) VALUES (100, 200, 500);COMMIT; -- or ROLLBACKSHOW ENGINE INNODB STATUS shows the last one.Speed
Indexes and EXPLAIN
The type column, best to worst
| Type | Meaning |
|---|---|
| system, const | At most one row, by primary or unique key |
| eq_ref | One row per earlier row, by a unique key |
| ref | All rows with one index value |
| range | A part of an index |
| index | The whole index |
| ALL | The whole table |
Using index is covering, Using index condition filters inside the index, Using filesort sorts separately.EXPLAIN SELECT id, total FROM ordersWHERE customer_id = 123 AND created_at > '2026-01-01'; -- estimates onlyCREATE INDEX idx_customer_date ON orders (customer_id, created_at);EXPLAIN ANALYZE SELECT id, total FROM orders -- runs the queryWHERE customer_id = 123 AND created_at > '2026-01-01';SHOW INDEX FROM orders;-- Index an expression, for example only active orders.CREATE INDEX idx_active ON orders ((IF(status = 'active', created_at, NULL)));SET GLOBAL slow_query_log = ON; -- off by defaultSET GLOBAL long_query_time = 1; -- seconds, 10 by defaultmysqldumpslow or pt-query-digest.Common slow queries
| Pattern | Why | Better |
|---|---|---|
| One query per item in a loop | N+1 round trips | One join or IN list |
phone = 12345 on a text column | Type conversion defeats the index | Compare with a string |
| LIKE with a leading wildcard | No prefix to search | FULLTEXT index and MATCH |
| OFFSET 100000 | Counts through all rows | Remember the last id |
| SELECT * with long columns | Reads what nobody uses | Name the columns |
| Transaction around user input | Locks and undo stay | Validate first, then begin |
Operations
Schema and settings
CREATE TABLE users ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL, status ENUM('active','inactive','banned') NOT NULL DEFAULT 'active', created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY uq_email (email), KEY idx_status_created (status, created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;CREATE TABLE orders ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, total DECIMAL(10,2) NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id));-- Keyset pagesSELECT id, total FROM orders WHERE user_id = 123 AND id < 1000ORDER BY id DESC LIMIT 20;ALTER TABLE users ADD COLUMN nickname VARCHAR(50), ALGORITHM=INSTANT;utf8mb4 is full Unicode. Instant column changes are limited to 255 row versions and some table kinds.[mysqld]innodb_buffer_pool_size = 12G # a 16 GB dedicated serverinnodb_redo_log_capacity = 4G # replaces innodb_log_file_sizeinnodb_flush_log_at_trx_commit = 1sync_binlog = 1max_connections = 500slow_query_log = ONlong_query_time = 1binlog_expire_logs_seconds = 2592000 # 30 days, the defaultinnodb_dedicated_server can size the pool and redo log for you. In 9.7 the I/O capacity default is 10,000, the adaptive hash index is off, and O_DIRECT is used where supported, so old tuning guides mislead.Connections. A thread per connection is lighter than a process, but thousands still cost memory and scheduling; the manual speaks of 500 to 1,000 routinely and up to about 10,000 with much memory and light work. Use an application pool, and ProxySQL when many app servers add up: it multiplexes, routes and can cache. Multiplexing pauses for open transactions, table locks and some session state. A thread pool exists in the Enterprise Edition.
# Python with SQLAlchemyimport osfrom sqlalchemy import create_engine, textengine = create_engine( os.environ["DATABASE_URL"], # mysql+pymysql://... pool_size=10, max_overflow=20, pool_recycle=3600, pool_pre_ping=True)def get_user(user_id): with engine.connect() as conn: return conn.execute(text("SELECT id, name FROM users WHERE id = :id"), {"id": user_id}).fetchone()def transfer(src, dst, amount): # amount is a Decimal with engine.begin() as conn: # commits, or rolls back on an exception r = conn.execute(text("UPDATE accounts SET balance = balance - :a WHERE id = :id AND balance >= :a"), {"a": amount, "id": src}) if r.rowcount == 0: raise ValueError("insufficient funds") conn.execute(text("UPDATE accounts SET balance = balance + :a WHERE id = :id"), {"a": amount, "id": dst})SHOW STATUS LIKE 'Threads_%'; -- connected, running, cached, createdSELECT id, user, host, time, state, LEFT(info, 100) AS queryFROM performance_schema.processlistWHERE command = 'Query' AND time > 30 ORDER BY time DESC;SHOW STATUS LIKE 'Innodb_buffer_pool_read%';SHOW ENGINE INNODB STATUS;SELECT table_name, ROUND(data_length/1048576) AS data_mb, ROUND(index_length/1048576) AS index_mb, table_rowsFROM information_schema.tablesWHERE table_schema = DATABASE() ORDER BY data_length DESC;table_rows is an estimate for InnoDB.Copies
Replication
One source, two replicas
- 1
Source writes the binary log
Row events by default: the changed rows, not the statement.
binlog_formatis deprecated because other formats are going away. - 2
Receiver thread
On the replica it fetches events into a relay log.
- 3
Applier threads
They replay transactions, four workers by default, keeping commit order.
- 4
GTIDs
Every transaction has a name, so a replica can ask a new source for exactly what it lacks.
Kinds of replication
| Kind | Commit waits for | Limits |
|---|---|---|
| Asynchronous (default) | Nobody | A failover can lose the tail |
| Semi-synchronous | One replica to log the events | Not applied yet; falls back to asynchronous after 10 s by default |
| Group Replication, single-primary | A majority to agree on the order | At most 9 members, large transactions hurt |
| Group Replication, multi-primary | The same, and first commit wins | Conflicts roll back, more restrictions |
-- Both servers: server_id differs, gtid_mode = ON, enforce_gtid_consistency = ON-- On the source (the binary log is on by default)CREATE USER 'repl'@'10.0.0.%' IDENTIFIED BY '<choose one>' REQUIRE SSL;GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.0.0.%';SHOW BINARY LOG STATUS;-- On the replica (super_read_only = ON)CHANGE REPLICATION SOURCE TO SOURCE_HOST = 'source.internal', SOURCE_USER = 'repl', SOURCE_PASSWORD = '<same>', SOURCE_AUTO_POSITION = 1, SOURCE_SSL = 1;START REPLICA;SHOW REPLICA STATUS; -- Replica_IO_Running, Replica_SQL_Running, Seconds_Behind_Source-- Semi-synchronous: one plugin on each sideINSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so'; -- sourceSET GLOBAL rpl_semi_sync_source_enabled = 1;INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so'; -- replicaSET GLOBAL rpl_semi_sync_replica_enabled = 1;SHOW STATUS LIKE 'Rpl_semi_sync%';Copies
Reads, failover and backups
Read/write splitting by the app, ProxySQL or MySQL Router sends reads to replicas. Lag makes them stale, so send a user who just wrote to the source for a while, or wait on the replica for the GTID of their write with WAIT_FOR_EXECUTED_GTID_SET.
Choosing high availability
Replication is not a backup: a wrong DELETE reaches every replica. Take full backups from a replica, archive binary logs somewhere else, and restore them regularly.
# logical copy, consistent for InnoDB, with the log position as a commentmysqldump --single-transaction --routines --triggers --source-data=2 mydb | gzip > mydb.sql.gz# physical copy with a release of XtraBackup that supports your server versionxtrabackup --backup --target-dir=/backup/fullxtrabackup --prepare --target-dir=/backup/full# server stopped, empty data directory:xtrabackup --copy-back --target-dir=/backup/full# point-in-time recovery: restore, look, then replay up to just before the mistakemysqlbinlog --start-datetime="2026-11-18 10:55:00" --verbose binlog.000042 | lessmysqlbinlog --stop-position=4521 binlog.000041 binlog.000042 | mysql -u root -p--stop-position belongs to the last file named. Begin at the position or GTID set recorded in the backup. Then check tables and row counts.Growth
Scaling out
The order of moves
Splitting tables over servers (users here, orders there) is vertical and easier. Splitting one table's rows by a key is horizontal: see sharding. Signals are writes at the limit of one server, data much larger than memory, and schema changes or restores that take too long. Choose a key that spreads evenly and keeps what is read together, such as a tenant.
Vitess
| Part | Job |
|---|---|
| VTGate | Stateless proxy: speaks the MySQL protocol and routes by key |
| VTTablet | Sits beside each MySQL, pools and protects it |
| Topology service | Knows shards and primaries |
| Reshard | Copies and follows changes, checks, then switches traffic |
Decide
When to choose it, and what it costs
Choose it when
- Many short transactions by key
- Web, shop and social data, mostly reads
- You want a well-known road to replicas and shards
- The team and tools know it
Look elsewhere when
- Heavy analytics: see OLAP
- Rich types, partial indexes, extensions: PostgreSQL
- Writes in several regions: distributed SQL
- Documents without joins: MongoDB
- Great write volume and nobody to run shards
Neighbours
| Product | Difference | Choose it for |
|---|---|---|
| PostgreSQL | Heap tables, new versions and vacuum; more index types | Complex queries, JSONB, extensions |
| MongoDB | Documents, built-in sharding, transactions too | Data read as one document |
| Redis | In memory, data structures | A cache in front of MySQL |
| Aurora MySQL | Shared storage over three zones, up to 256 TiB in recent versions | Managed operation on AWS |
| TiDB | MySQL protocol, automatic sharding | Scale-out without choosing shards |
Summary
The whole topic in one minute.
In InnoDB the table is the primary key index. Short, growing keys keep pages full and every other index small. Reading by another index means two walks, unless that index covers the query.
Commit is durable through the redo log and travels through the binary log. Replicas are asynchronous by default. Scale by queries, memory, cache, replicas, and shard last, usually with Vitess.
- The table is the primary key tree. Keep that key short and growing.
- A secondary index gives the key, then a second walk finds the row.
- Undo serves readers, redo survives crashes, the binary log feeds copies.
- Default isolation is repeatable read, with next-key locks for locking reads.
- Semi-sync means logged on a replica, not applied, and it can fall back.
- Replicas are not backups.
- Shard last, and prefer Vitess to your own router.