Skip to content

Alter a large MySQL table with pt-online-schema-change

How pt-online-schema-change alters a multi-gigabyte MySQL or MariaDB table without a long metadata lock: the shadow table and trigger mechanism, the throttling flags that matter in production, replication safety, cleaning up after an abort, and when native online DDL or gh-ost is the better answer.

pt-online-schema-change alters a large table by never altering it. It builds an empty copy called _yourtable_new, applies your ALTER to that copy, installs three triggers on the original so every live INSERT, UPDATE and DELETE is mirrored into the copy, then walks the original in small chunks copying rows across. When the copy has caught up, a single RENAME TABLE statement swaps the two. The original table is readable and writable the whole time — but read the next sentence before you reach for the tool. On MySQL 8.0, a large share of everyday ALTER statements now run as ALGORITHM=INSTANT in under a second with no copy at all, and running pt-osc against them is a slow, risky way to get the same result.

What you’ll accomplish

  • Decide whether native online DDL already covers your ALTER before reaching for a copy tool.
  • Confirm the table meets the tool’s hard requirements: a PRIMARY or UNIQUE key, disk headroom for a second full copy, no pre-existing triggers on older servers.
  • Run a --dry-run and read what it actually proves, then run the real change with load and replication-lag throttles that make it safe on a busy primary.
  • Recover cleanly from an abort — leftover _tbl_new tables and pt_osc_* triggers included.
  • Choose honestly between pt-osc, gh-ost, and doing nothing special at all.

Prerequisites

  • Percona Toolkit 3.x on a host that can reach the primary. Install from Percona’s repositories rather than a distribution package, which is often several years behind.
  • MySQL 5.7 or 8.0, or MariaDB 10.x. The tool works on both, but MariaDB is the weaker case: MariaDB’s INSTANT support is narrower than MySQL 8.0’s, and gh-ost — the usual trigger-free alternative — does not support MariaDB, so on MariaDB pt-osc is often the only copy tool available. MariaDB 10.2 and later allow multiple triggers per event, so the “existing triggers” blocker below does not apply there.
  • A database user with PROCESS, REPLICATION SLAVE, SUPER, SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, LOCK TABLES and TRIGGER on the target schema. Missing TRIGGER is the most common permission failure and it surfaces only after the new table has already been created.
  • A PRIMARY KEY or a UNIQUE index on the table. The DELETE trigger needs a stable way to name a single row. Without one, the tool refuses to start.
  • Free disk equal to the table’s data plus index size, with margin. During the copy the schema holds two complete copies. Add the binary logs the copy generates — a 40 million row copy on a ROW-format primary can produce tens of gigabytes of binlog.
  • Knowledge of your replication topology, including whether replicas apply the change through the binlog or are excluded by replication filters. See MySQL replication lag triage for the measurement side of that.

How it works

The mechanism has four moving parts and each of them can fail independently, so it is worth knowing exactly what runs where.

Diagram of the pt-online-schema-change mechanism: the application keeps writing to the original shop.orders table, three pt_osc triggers mirror every write into a shadow copy called _orders_new that carries the new schema, rows are copied across in throttled chunks, and a single atomic RENAME swaps the two tables at the end

The shadow table. CREATE TABLE _orders_new LIKE orders produces an empty table with the same structure, then your --alter clause is applied to that empty table. Applying an ALTER to an empty table is instant regardless of what the clause does, which is the whole point.

The triggers. Three AFTER triggers go on the original table, named after a pt_osc_<db>_<table>_<event> pattern. They mirror each write into the shadow table: inserts become REPLACE, updates become DELETE plus REPLACE, deletes become DELETE IGNORE. Every write on the original now does roughly twice the work, which is the tool’s real cost — not the copy, the write amplification for the duration of the copy.

The chunked copy. Rows are copied in ranges over the primary key with INSERT LOW_PRIORITY IGNORE ... SELECT. The IGNORE is what makes the triggers and the copy safe together: if a trigger already mirrored a row the copy is about to read, the copy’s insert is discarded rather than conflicting. Chunk size is recalculated continuously to keep each chunk near a target execution time, and the copy pauses whenever your load thresholds are exceeded.

The swap. One statement — RENAME TABLE orders TO _orders_old, _orders_new TO orders — performs the switch atomically. No session ever sees a moment where orders does not exist. This step does take a metadata lock, and it will wait behind any long-running query holding a read lock on the table, so a runaway analytics query can stall the swap and pile up connections behind it. pt-osc reduces locking dramatically; it does not eliminate it.

Step-by-step

1. Check the table qualifies before doing anything else. Size, keys, triggers and foreign keys, in that order.

mysql -e "SELECT engine, ROUND(data_length/1073741824,1) AS data_gb, \
ROUND(index_length/1073741824,1) AS idx_gb, table_rows \
FROM information_schema.tables WHERE table_schema='shop' AND table_name='orders'"
+--------+---------+--------+------------+
| engine | data_gb | idx_gb | table_rows |
+--------+---------+--------+------------+
| InnoDB |     6.1 |    2.3 |   41983204 |
+--------+---------+--------+------------+

That is 8.4 GB you need free, and df -h on the datadir has to show comfortably more than that. Now the keys and the triggers:

mysql -e "SHOW KEYS FROM shop.orders WHERE Key_name='PRIMARY'; \
SELECT trigger_name, action_timing, event_manipulation FROM information_schema.triggers \
WHERE event_object_schema='shop' AND event_object_table='orders'"
+-------------+------------+----------+--------------+-------------+
| Table       | Non_unique | Key_name | Seq_in_index | Column_name |
+-------------+------------+----------+--------------+-------------+
| orders      |          0 | PRIMARY  |            1 | id          |
+-------------+------------+----------+--------------+-------------+

An empty trigger result is what you want. Finally, check whether other tables point at this one:

mysql -e "SELECT table_schema, table_name, constraint_name FROM information_schema.key_column_usage \
WHERE referenced_table_schema='shop' AND referenced_table_name='orders'"
+--------------+-------------+-----------------------+
| table_schema | table_name  | constraint_name       |
+--------------+-------------+-----------------------+
| shop         | order_items | fk_order_items_order  |
+--------------+-------------+-----------------------+

A child table means you will have to pick an --alter-foreign-keys-method, covered in troubleshooting.

2. Try the change as native DDL first. This costs one command and frequently ends the exercise.

mysql -e "ALTER TABLE shop.orders ADD COLUMN fulfilled_at DATETIME NULL, ALGORITHM=INSTANT"
ERROR 1845 (0A000) at line 1: ALGORITHM=INSTANT is not supported. Reason: ADD COLUMN with
secondary index. Try ALGORITHM=COPY/INPLACE.

If that had succeeded, you would be done in under a second. It failed here because the change also needs an index, so try INPLACE with LOCK=NONE next. If both refuse, you have a genuine copy on your hands. MySQL online DDL strategies walks through which operations qualify for which algorithm.

3. Dry-run the change. --dry-run creates the shadow table, applies the ALTER to it, and drops it. It proves your --alter clause is syntactically valid and compatible with the table, and nothing more.

pt-online-schema-change \
  --alter "ADD COLUMN fulfilled_at DATETIME NULL, ADD INDEX idx_fulfilled (fulfilled_at)" \
  D=shop,t=orders --dry-run
Operation, tries, wait:
  analyze_table, 10, 1
  copy_rows, 10, 0.25
  create_triggers, 10, 1
  drop_triggers, 10, 1
  swap_tables, 10, 1
  update_foreign_keys, 10, 1
Starting a dry run.  `shop`.`orders` will not be altered.  Specify --execute instead of --dry-run to alter the table.
Creating new table...
Created new table shop._orders_new OK.
Altering new table...
Altered `shop`.`_orders_new` OK.
Not creating triggers because this is a dry run.
Not copying rows because this is a dry run.
Not swapping tables because this is a dry run.
Not dropping old table because this is a dry run.
Not dropping triggers because this is a dry run.
Dropping new table...
Dropped new table OK.
Dry run complete.  `shop`.`orders` was not altered.

Note the --alter value never contains the words ALTER TABLE — only the clause that follows them.

4. Run it with throttles. The defaults are conservative but not tuned for your server. Set the load ceilings explicitly.

pt-online-schema-change \
  --alter "ADD COLUMN fulfilled_at DATETIME NULL, ADD INDEX idx_fulfilled (fulfilled_at)" \
  D=shop,t=orders \
  --max-load "Threads_running=40" \
  --critical-load "Threads_running=120" \
  --chunk-size-limit 3.0 \
  --check-interval 2 \
  --no-drop-old-table \
  --execute
Found 2 slaves:
  replica-a -> 10.0.4.21:3306
  replica-b -> 10.0.4.22:3306
Will check slave lag on:
  replica-a -> 10.0.4.21:3306
  replica-b -> 10.0.4.22:3306
Operation, tries, wait:
  analyze_table, 10, 1
  copy_rows, 10, 0.25
  create_triggers, 10, 1
  drop_triggers, 10, 1
  swap_tables, 10, 1
  update_foreign_keys, 10, 1
Altering `shop`.`orders`...
Creating new table...
Created new table shop._orders_new OK.
Altering new table...
Altered `shop`.`_orders_new` OK.
2026-07-29T02:14:06 Creating triggers...
2026-07-29T02:14:07 Created triggers OK.
2026-07-29T02:14:07 Copying approximately 41983204 rows...
Copying `shop`.`orders`:  18% 24:31 remain
Copying `shop`.`orders`:  46% 15:02 remain
Copying `shop`.`orders`:  79% 05:48 remain
2026-07-29T02:42:17 Copied rows OK.
2026-07-29T02:42:17 Analyzing new table...
2026-07-29T02:42:19 Swapping tables...
2026-07-29T02:42:19 Swapped original and new tables OK.
2026-07-29T02:42:19 Not dropping old table because --no-drop-old-table was specified.
2026-07-29T02:42:19 Dropping triggers...
2026-07-29T02:42:20 Dropped triggers OK.
Successfully altered `shop`.`orders`.

The two thresholds do different jobs. --max-load pauses the copy until the server calms down; --critical-load aborts outright. Set --critical-load well above --max-load — if the two are close, ordinary load spikes turn into aborts. --chunk-size-limit 3.0 caps how far the tool may overshoot its chunk-size target when rows are unevenly sized, which stops a single chunk from becoming a long-running statement.

5. Keep replicas in the picture. By default pt-osc discovers replicas through SHOW PROCESSLIST, which finds nothing when replicas connect through a proxy or from a different network. Name them explicitly.

pt-online-schema-change \
  --alter "MODIFY COLUMN status VARCHAR(32) NOT NULL DEFAULT 'new'" \
  D=shop,t=orders \
  --recursion-method=none \
  --check-slave-lag h=10.0.4.21,u=osc,p=secret \
  --max-lag 3 \
  --execute
Will check slave lag on:
  10.0.4.21 -> 10.0.4.21:3306
Altering `shop`.`orders`...
2026-07-29T03:05:11 Copying approximately 41983204 rows...
Replica lag is 7 seconds on 10.0.4.21.  Waiting.
Replica lag is 5 seconds on 10.0.4.21.  Waiting.
Copying `shop`.`orders`:  62% 09:11 remain

If any replica uses replicate-do-db or replicate-ignore-db filters, pt-osc stops with an error rather than risk a topology where the ALTER reaches some replicas and not others. --nocheck-replication-filters skips that safety check — use it only when you have read the filters yourself and confirmed the target schema is unaffected.

6. Drop the old table on purpose. --no-drop-old-table left _orders_old behind as your rollback.

mysql -e "SHOW TABLES FROM shop LIKE '\_%'"
+---------------------+
| Tables_in_shop (_%) |
+---------------------+
| _orders_old         |
+---------------------+

Verify the application first, then remove it in a low-traffic window — dropping a 6 GB InnoDB table is itself an I/O event.

Validate it works

Confirm the new definition landed, on the primary and on every replica:

mysql -e "SHOW CREATE TABLE shop.orders\G" | grep -E 'fulfilled_at|idx_fulfilled'
  `fulfilled_at` datetime DEFAULT NULL,
  KEY `idx_fulfilled` (`fulfilled_at`)

Confirm nothing was left installed:

mysql -e "SELECT trigger_name FROM information_schema.triggers WHERE trigger_name LIKE 'pt\_osc\_%'"

Empty output is the pass condition. Then confirm the row count is what it should be, and that the primary and replicas agree — pt-table-checksum, covered in Percona Toolkit essentials, compares chunk by chunk against a live table rather than requiring it to be still.

Troubleshooting

“The new table does not have a PRIMARY KEY or a unique index which is required for the DELETE trigger.” The tool checks the table it is about to build, not the one you have, so this also fires when your --alter drops the only unique key. If the table genuinely has no unique key, add one first with a separate change — usually an AUTO_INCREMENT surrogate — and only then run the real alteration. There is no flag that makes this work without a key, and there should not be: without one, the mirrored DELETE cannot identify which row to remove.

“You cannot add triggers to a table that has triggers.” On MySQL 5.6 and earlier a table can carry only one trigger per event, so any application trigger blocks pt-osc entirely. MySQL 5.7 and MariaDB 10.2 lifted that restriction, and modern pt-osc will proceed — but your triggers then fire on the shadow table during the copy as well, which can be wrong or expensive. Read them before you assume it is fine. If they cannot be temporarily removed, gh-ost is the correct tool, because it reads the binary log instead of installing triggers.

Foreign keys point at the table. After the rename, child tables’ constraints still reference _orders_old. --alter-foreign-keys-method=rebuild_constraints runs an ALTER on each child to repoint it, which is safe but means those children get rebuilt too — fine for small children, punishing for large ones. drop_swap disables foreign key checks and swaps without rebuilding: much faster, but the original table is dropped rather than renamed, so there is no rollback copy and there is a brief window where the table is missing. auto picks between them by child-table size. none leaves constraints pointing at a table that no longer exists and is not a production answer. If you cannot accept any of these, do the alteration during a window where the child tables are quiet.

--critical-load aborted and left debris behind. The output ends with something like Threads_running=132 exceeds its critical threshold 120 and the copy stops mid-flight. The triggers and _orders_new are still installed, and every write to the original is still paying double. Clean up immediately, triggers first:

mysql -e "SELECT CONCAT('DROP TRIGGER IF EXISTS shop.', trigger_name, ';') \
FROM information_schema.triggers WHERE trigger_name LIKE 'pt\_osc\_%'"
+-----------------------------------------------------+
| DROP TRIGGER IF EXISTS shop.pt_osc_shop_orders_ins;  |
| DROP TRIGGER IF EXISTS shop.pt_osc_shop_orders_upd;  |
| DROP TRIGGER IF EXISTS shop.pt_osc_shop_orders_del;  |
+-----------------------------------------------------+

Run those statements, then DROP TABLE shop._orders_new. Order matters: drop the triggers before the shadow table, or writes to the original will start failing because the triggers reference a table that has vanished. There is no resume — a re-run starts from row one.

Disk fills during the copy. ERROR 1114 (HY000): The table '_orders_new' is full or an out-of-space error from the filesystem. The copy dies with the same debris as an abort, plus a partially written shadow table. Clean up in the same order, reclaim space, and remember that dropping _orders_new returns space to the filesystem only if innodb_file_per_table is on — in a shared tablespace it returns space to InnoDB and nothing to df. Before the retry, size the requirement honestly: data plus indexes plus binary logs plus your existing free-space alarm threshold.

When this is the wrong approach

Decision tree for large MySQL schema changes: if the ALTER supports ALGORITHM=INSTANT use native DDL, otherwise if it runs INPLACE with LOCK=NONE and no table rebuild use native DDL, otherwise choose gh-ost when triggers already exist or replication lag is the binding constraint, and pt-online-schema-change in the remaining cases

  • The ALTER qualifies for ALGORITHM=INSTANT. On MySQL 8.0 that covers adding a column, renaming a column, changing a column’s default, and several more. It rewrites metadata only and finishes in a moment. Copying eight gigabytes to achieve the same thing is not caution, it is waste.
  • The ALTER runs INPLACE with LOCK=NONE and no table rebuild — adding or dropping a secondary index is the common case. Native DDL keeps the work inside InnoDB, with no triggers, no write amplification, and no cleanup story.
  • Triggers already exist on the table, or replication lag is your binding constraint. gh-ost reads the binary log instead of installing triggers, so it adds no write amplification to the original table, can throttle on replica lag more precisely, and can be paused and resumed. It requires ROW binary logging and does not support MariaDB.
  • The table is small. Under a few hundred megabytes, a plain ALTER TABLE in a quiet window is simpler, faster, and has no debris to clean up if it fails.
  • You cannot afford the write amplification at all. During the copy, every write on the original table also writes to the shadow table. On a primary already near its I/O ceiling, that is the change that causes the incident rather than avoiding it.

The reference for every flag is the pt-online-schema-change documentation, and the wider toolkit is covered in Percona Toolkit essentials.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.