AlgoViz

MySQL

medium 32 min

MySQL 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

0:00 / 3:53

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

  1. 2010

    Engineers at YouTube create Vitess when MySQL approaches its limits there.

  2. 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.

  3. November 2019

    Vitess graduates as a project of the Cloud Native Computing Foundation.

  4. 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.

  5. 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.

Step 1 of 4

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.

Pages, a diary and a messenger
10203040Pages in order

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

WhatLimit
One table, 16 KB pages64 TB
Columns per table1,017
Secondary indexes64
Columns in an index16
Index key3,072 bytes with the DYNAMIC row format
Row without long fieldsAbout 8,000 bytes
From the 9.7 manual. Backup time and schema changes limit you much earlier.

Inside

From connection to engine

One server, two layers

An application talks to the SQL layer of one server, which parses, optimises and executes. It calls InnoDB, which uses the buffer pool and the redo log, and pages later reach the tablespaces. The server also writes the binary log.
The SQL layer owns the binary log. InnoDB owns redo, undo and data files.
  1. 1

    Connect

    Port 3306 by default, TLS available. Each connection gets a thread, often a cached one. max_connections is 151 by default, and one more is kept for administrators.

  2. 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. 3

    Execute

    The executor calls the engine's interface row by row or range by range.

  4. 4

    Use an engine

    InnoDB for everything that matters. MyISAM is legacy: no transactions, table locks. MEMORY tables vanish at restart.

  5. 5

    Answer and log

    Committed changes go to the binary log, and the client gets its result.

Through the layers

The pluggable engine is why the server has one log of its own and the engine has two more.

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

A covering index holds every column the query needs and can skip the second walk.

What a long primary key costs

(36−8) B×108 rows=2.8 GB per secondary index(36 - 8)\,\text{B} \times 10^{8} \text{ rows} = 2.8\,\text{GB per secondary index}
A UUID as 36 characters against an 8-byte BIGINT, before page overhead. Store UUIDs as 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

1−reads from diskread requests=1−20,00010,000,000=99.8%1 - \frac{\text{reads from disk}}{\text{read requests}} = 1 - \frac{20{,}000}{10{,}000{,}000} = 99.8\%
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

The two logs are tied by a two-phase commit inside the server, so after a crash both tell the same story.

How durable is a commit?

innodb_flush_log_at_trx_commitAt commitCan lose
1 (default)Write and flushNothing on a server crash
2Write, flush about once a secondAbout a second on power loss
0Nothing, write and flush about once a secondAbout a second even if only the process dies
Keep it at 1 with 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

LevelPlain SELECTLocking reads and updates
Read uncommittedMay see uncommitted rowsAs read committed
Read committedA fresh snapshot per statementRecord locks, gap locks only for foreign key and duplicate checks
Repeatable read (default)One snapshot from the first readNext-key locks on scanned ranges
SerializableBecomes a shared locking read when autocommit is offAs repeatable read
PostgreSQL defaults to read committed. Isolation levels has the anomalies.
SQL
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 ROLLBACK
If one transaction locks 100 then 200 and another 200 then 100, they deadlock. InnoDB detects it and rolls one back: retry it. SHOW ENGINE INNODB STATUS shows the last one.

Speed

Indexes and EXPLAIN

The type column, best to worst

TypeMeaning
system, constAt most one row, by primary or unique key
eq_refOne row per earlier row, by a unique key
refAll rows with one index value
rangeA part of an index
indexThe whole index
ALLThe whole table
Extra: Using index is covering, Using index condition filters inside the index, Using filesort sorts separately.
SQL
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 default
An index on (a, b, c) serves a, a with b, and all three. A range on a column stops the next columns from narrowing it. Summarise the slow log with mysqldumpslow or pt-query-digest.

Common slow queries

PatternWhyBetter
One query per item in a loopN+1 round tripsOne join or IN list
phone = 12345 on a text columnType conversion defeats the indexCompare with a string
LIKE with a leading wildcardNo prefix to searchFULLTEXT index and MATCH
OFFSET 100000Counts through all rowsRemember the last id
SELECT * with long columnsReads what nobody usesName the columns
Transaction around user inputLocks and undo stayValidate first, then begin
InnoDB creates an index for a foreign key if none fits, so an unindexed foreign key column is a problem of schemas without declared keys.

Operations

Schema and settings

SQL
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.
ini
[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 default
innodb_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
# 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})
The pool tests a connection before use and replaces it after an hour, shorter than the server's idle limit.
SQL
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

Applications send SQL to a router. Writes go to the source. The source sends its binary log to two replicas, which store it in a relay log and apply it. Reads go from the router to the replicas.
Writes meet on one server. The binary log does the copying.
  1. 1

    Source writes the binary log

    Row events by default: the changed rows, not the statement. binlog_format is deprecated because other formats are going away.

  2. 2

    Receiver thread

    On the replica it fetches events into a relay log.

  3. 3

    Applier threads

    They replay transactions, four workers by default, keeping commit order.

  4. 4

    GTIDs

    Every transaction has a name, so a replica can ask a new source for exactly what it lacks.

Kinds of replication

KindCommit waits forLimits
Asynchronous (default)NobodyA failover can lose the tail
Semi-synchronousOne replica to log the eventsNot applied yet; falls back to asynchronous after 10 s by default
Group Replication, single-primaryA majority to agree on the orderAt most 9 members, large transactions hurt
Group Replication, multi-primaryThe same, and first commit winsConflicts roll back, more restrictions
In a group the other members apply later, so reading from them can still be stale by default.
SQL
-- 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%';
The older words MASTER and SLAVE were removed from these statements in 8.4; the privilege keeps its name. Seconds behind can mislead when the receiver is behind too.

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

Orchestrator's original repository was archived in February 2025; it points to Percona's fork.

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.

Shell
# 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

Many systems never reach the last box.

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

PartJob
VTGateStateless proxy: speaks the MySQL protocol and routes by key
VTTabletSits beside each MySQL, pools and protects it
Topology serviceKnows shards and primaries
ReshardCopies and follows changes, checks, then switches traffic
A query without the sharding key goes to all shards. Most SQL works, yet check compatibility and design for single-shard transactions.

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

ProductDifferenceChoose it for
PostgreSQLHeap tables, new versions and vacuum; more index typesComplex queries, JSONB, extensions
MongoDBDocuments, built-in sharding, transactions tooData read as one document
RedisIn memory, data structuresA cache in front of MySQL
Aurora MySQLShared storage over three zones, up to 256 TiB in recent versionsManaged operation on AWS
TiDBMySQL protocol, automatic shardingScale-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.

Sources