How do you change the schema of a huge MySQL table online?
Native online DDL
InnoDB supports many changes with ALGORITHM=INSTANT (metadata only: adding a column, since 8.0.29 at any position; renaming columns; changing defaults) or ALGORITHM=INPLACE, LOCK=NONE (adding indexes while allowing reads and writes). Always state the algorithm and lock you expect, so MySQL errors instead of silently copying the table:
ALTER TABLE orders ADD COLUMN note VARCHAR(255), ALGORITHM=INSTANT;
Caveats
- In-place operations still need a short metadata lock at the start and end; a long-running query on the table makes the ALTER wait, and every new query queues behind it. Set
lock_wait_timeoutlow and retry. - Replicas apply the DDL single-threaded after the primary finishes, so a 2-hour ALTER becomes 2 hours of replica lag.
- Changing a column type, the primary key, or the character set usually requires a full table copy.
Online schema change tools
- gh-ost (GitHub): creates a shadow table, copies rows in chunks, applies ongoing changes by reading the binlog, throttles on replica lag, and swaps tables atomically at the end. Pausable and testable.
- pt-online-schema-change (Percona): similar, but uses triggers to capture changes.
- Vitess / PlanetScale deploy requests run this workflow for you.
Example
sql
-- Cheap: instant metadata change
ALTER TABLE orders ADD COLUMN gift_message VARCHAR(255) NULL, ALGORITHM=INSTANT;
-- Online index build that fails fast if it cannot run without blocking writes
SET SESSION lock_wait_timeout = 5;
ALTER TABLE orders ADD INDEX idx_orders_status_created (status, created_at), ALGORITHM=INPLACE, LOCK=NONE;bash
# Expensive change (column type) with gh-ost, throttled by replica lag
gh-ost --host=replica-1 --database=shop --table=orders \
--alter="MODIFY amount DECIMAL(12,2) NOT NULL" \
--max-lag-millis=1500 --chunk-size=2000 \
--cut-over=default --executeFollow-up questions interviewers ask
Try answering each one before you open it.
Why test migrations against production-sized data?
Whether an ALTER is instant, in-place or a full copy, and how long it takes, depends on the version, row format and table size. Running it against a restored production snapshot (and checking ALGORITHM explicitly) shows the real lock behaviour and duration before it hits users.