Know Before You ALTER: Comparing MySQL Schemas with pt-schema-diff

Share this Post:

Every MySQL team has more than one copy of its schema. There’s production, a staging server, a QA box, a developer’s laptop, the schema file in git and the dump someone took before last year’s migration. They’re all supposed to match, and they never quite do. A column was widened on production during an incident and nobody back-ported it. An index was added on staging for a test and never removed. Someone ran a migration twice, or not at all.

Finding those differences is the easy half. The hard half is the next question: what does it take to make one schema match the other, and is it safe to run on a server with real traffic? Some ALTERs are instant metadata changes. Some copy the whole table and block writes while they do. A few quietly cut off data.

I created pt-schema-diff to solve both problems. It compares two MySQL schemas and shows every difference. For each change, it tells you two things: whether you could lose data, and whether MySQL will block writes while it runs. Then it writes the SQL script to fix the differences. It can also test that script on an empty copy first, so you know it works before you run it on production. In this post, I explain why I built it, how it works, and how to use it.

Why diffing CREATE TABLE output isn’t enough

The simple way is to dump both schemas with mysqldump –no-data and compare the files with diff. This works for small changes, but it soon runs into problems:

  • Noise. AUTO_INCREMENT=1001 differs on every server. int(11) on 5.7 is int on 8.0. A hand-written id int PRIMARY KEY looks nothing like what MySQL prints back. A text diff reports all of that.
  • No script. diff tells you the lines differ. It doesn’t write the ALTER TABLE, and it certainly doesn’t put the foreign keys in the right order.
  • No risk. Two lines that look equally small can be very different on a live server. Adding a value to the end of an ENUM is instant. Changing a column’s character set copies the table and blocks writes until it’s done.
  • Renames look like drop-and-add. If a column was renamed, a naive tool drops the old column and adds a new, empty one. That’s data loss dressed up as a migration.

pt-schema-diff parses the CREATE TABLE statements instead of comparing text. It understands that INTEGER(11) and int are the same thing, that a primary key column is NOT NULL even when the DDL doesn’t say so, and that utf8 means utf8mb3. Only real differences make it into the report.

How pt-schema-diff works

You give it two schemas: a source, the one to match (usually production), and a target, the one the script will change (staging, a new replica, a fresh environment). Each side can be a live database, a SQL file or a saved snapshot. The tool then works in four steps:

  1. Read both schemas. For a live server, it reads SHOW CREATE TABLE for every table, plus row counts and sizes from information_schema.TABLES. It only reads. It never changes the source or the target.
  2. Compare. It matches tables by name and compares columns, indexes, foreign keys, CHECK constraints and table options (engine, character set, row format, comment, partitioning).
  3. Rate every change. Each change gets a severity (critical, warning, suggestion, ok) and the algorithm MySQL 8.0 uses for it: instant, online, online with a table rebuild, or a copy that blocks writes.
  4. Write the script. It writes one ALTER TABLE per table, in an order that works. Anything that deletes data is commented out unless you ask for it.

It’s a single static Go binary. It has no runtime dependencies: no Perl modules, no MySQL client libraries. It follows Percona Toolkit conventions (DSNs, –ask-pass, –defaults-file, exit codes), so it should feel familiar if you already use pt-online-schema-change or pt-table-checksum.

Getting started

Download the binary for your system from the releases page, and check it against the published checksums:

Use linux-amd64 on Intel and AMD servers and linux-arm64 on ARM servers. If you’re not sure, run uname -m: x86_64 means amd64 and aarch64 means arm64. If you manage both kinds of servers, download pt-schema-diff-0.1.0-linux.tar.gz instead. It contains both binaries and a pt-schema-diff command that runs the right one.

It’s a single static binary with no dependencies, so it runs on any Linux distribution. To build it yourself, you need Go 1.22 or newer: git clone the repository and run make build.

The login it uses needs only SELECT on the databases you compare. A read-only account is enough:

Connecting: DSNs

Servers are given as Percona Toolkit DSNs: comma-separated key=value pairs. The keys are h (host), P (port), u (user), p (password), S (socket), D (database), A (charset) and F (an option file to read).

Anything the target DSN leaves out is taken from the source DSN. So if both schemas live on the same server, the target only needs the database name:

And for two servers:

For passwords I’d avoid p= on the command line, since it shows up in ps and in shell history. Use –ask-pass, the MYSQL_PWD environment variable, or an option file with –defaults-file (it reads the [client] section).

A run, step by step

Here’s a real run. Production has a shop database. Staging has an older copy that has drifted: a renamed column, a missing table, some widened columns, a MyISAM table that production converted to InnoDB, and a table that only exists on staging. The output below is trimmed, but every line is what the tool printed.

The report starts with a summary:

Then it lists each table, worst first. Each heading shows the table’s overall rating and the worst way MySQL will run its ALTER:

Look at what each line gives you. It doesn’t just say “these differ”. It says what will happen to the data, which query to run first to find out whether the ALTER will fail, and how MySQL will execute it. Turning a signed id into int unsigned is critical because any negative value gets rejected, and the tool hands you the SELECT MIN(id), MAX(id) to check. Adding a value to the end of an ENUM is rated ok and instant. Inserting one in the middle would be a warning, because MySQL renumbers every stored value.

Reading the ratings

Every change gets two ratings. The severity is about your data:

Severity Meaning
CRITICAL Data can be lost or changed: a dropped column or table, a narrower type, a sign change, a character set that can’t hold every existing character
WARNING The data is safe, but the ALTER can fail (duplicates for a new unique key, NULLs for a new NOT NULL) or behave differently afterwards (new collation rules)
SUGGESTION Low risk, but worth a look: a dropped or added index, more fractional-second digits
OK Safe: new tables, new nullable columns, renames, appended ENUM values

The algorithm is about your traffic, based on how MySQL 8.0 runs each change:

Label What MySQL does
instant Updates the table definition only. Takes a moment whatever the table size
online Builds in place (for example, a secondary index). Reads and writes continue
online, rebuilds table Rebuilds the table in place. Reads and writes continue, but it takes time and disk space
blocks writes Copies the table. Writes wait until the copy finishes

A table’s ALTER runs as one statement, so the table is only as fast as its slowest change. One blocks writes change makes the whole ALTER block writes. That’s what the table heading shows, and it’s a good reason to split a risky change into its own ALTER.

The migration script

After the report comes the script:

A few design decisions are worth explaining:

  • The script runs in phases. Foreign keys that are going away are dropped first. Then new tables are created, existing tables altered, and tables only in the target dropped. Foreign keys are added last, once every table and index they need exists. You can run the script top to bottom without hitting “Cannot add foreign key constraint”.
  • Drops are commented out by default. DROP TABLE and DROP COLUMN are the two statements you can’t take back. They’re in the script so you can see them, but you have to uncomment them yourself or pass –include-drops.
  • Renames are kept as renames. If a column exists only in the target, another exists only in the source, and both have the same definition, the tool writes CHANGE COLUMN old new. That keeps the data instead of dropping one column and adding an empty one. Indexes with the same columns get RENAME INDEX, which is instant. The report says when it made that call, so you can override it if the two columns really are unrelated.
  • Foreign keys and CHECK constraints are matched by definition, not by name. An unnamed foreign key gets a generated name like orders_ibfk_1, which can differ between servers that are otherwise identical. pt-schema-diff doesn’t report those as differences.
  • Some differences are reported but not scripted. Column order and partitioning both mean copying the whole table, and moving columns rarely matters to an application that names its columns. You’ll see them in the report as separate, deliberate decisions.

Save the script to a file with –script migration.sql, or print only the script with –format sql.

Proving the script works: –verify

A generated script is only as good as the tool that wrote it. I didn’t want anyone running mine on trust, so the tool can test its own output.

Give –verify a DSN for a sandbox server, ideally running the same MySQL version as the target:

It then:

  1. creates a scratch database on the sandbox, named pt_schema_diff_<random>,
  2. builds the target’s tables there (structure only, no data),
  3. runs the migration script against it, statement by statement,
  4. reads the result back and compares it with the source again,
  5. drops the scratch database.

If every statement runs and the only remaining differences are the ones the script deliberately skipped, the test passes:

If a statement fails, you get the statement and MySQL’s error, and the exit code is 3.

The sandbox login only needs rights on the scratch databases, not on anything real:

The script is also checked before it’s run: only CREATE TABLE and ALTER TABLE statements are allowed, and anything that names another database, or uses DATA DIRECTORY, TABLESPACE or the FEDERATED engine, is refused. The sandbox can’t be used to reach outside the scratch database.

One thing –verify can’t do is test your data. The scratch copy is empty, so an ALTER that would fail on duplicate values or NULLs passes here. That’s what the “Check first” queries in the report are for: run them on the real target before the migration.

Large tables: when to reach for pt-online-schema-change

On a small table, a copying ALTER is over in seconds. On a 400 GB table it can run for hours, block writes the whole time, and leave every replica that much behind. pt-schema-diff reads each target table’s size and row count. When a table has 1 GB or more of data, or 1 million or more rows, and its ALTER rebuilds or copies it, the report says so and writes the pt-online-schema-change command for you. Here’s a 1.2-million-row table whose id needs to become a bigint:

The –alter clause is exactly what the script would run, so the two stay in step. Foreign keys are left to the main script, because pt-online-schema-change handles them through its own –alter-foreign-keys-method option and you should choose that deliberately.

Changes that are already instant or online don’t trigger this advice, however big the table is. There’s no point copying 400 GB through pt-osc to add a nullable column that MySQL 8.0 adds instantly.

The printed command names the database and table but not the server, so add your h=, u= and –ask-pass before running it. For a large production table, I suggest a controlled approach: check the new table first, then swap the tables yourself. This gives you more control and lowers the risk. I explain how in my blog post:Using Percona Toolkit to Alter Database Tables Online: A Controlled Approach.

Comparing every database on two servers

Leave D= off both DSNs and pt-schema-diff compares every database on the two servers. The system schemas (mysql, sys, information_schema, performance_schema) are skipped:

You get an overview first, then the full report for each database that differs:

The script covers all of them, one section per database with its own USE line. A database that exists only on the source gets a CREATE DATABASE IF NOT EXISTS with the same character set and collation. A database that exists only on the target is never dropped: DROP DATABASE appears commented out even with –include-drops.

Narrow the run with –databases app,crm or –ignore-databases scratch,tmp. To see what’s there first, use –list-databases h=db-prod,u=schema_audit.

This is the mode I use most after an upgrade or a migration to a new cluster. Point it at the old primary and the new one, and anything that didn’t make it across shows up in one report.

Files and snapshots: comparing without a live server

Either side can also be a file. The tool reads:

  • mysqldump –no-data output,
  • SHOW CREATE TABLE output, including the \G format copied straight out of a terminal (the *** 1. row ***, Table: and 1 row in set lines are stripped),
  • hand-written CREATE TABLE statements, like the schema file in your repository.

– reads from standard input. So you can check the schema in git against what’s actually deployed, or compare two dumps on a laptop with no database at all:

Snapshots save a schema so you can compare against it later. Take one before a release, then check what the release actually changed:

Snapshots are JSON files in ~/.pt-schema-diff/snapshots (or –snapshot-dir, or $PT_SCHEMA_DIFF_SNAPSHOT_DIR). List them with –list-snapshots and remove them with –delete-snapshot ID.

Reports for people, output for pipelines

The default text report is meant for a terminal. There are four other formats:

Format Use it for
–format sql Only the migration script
–format markdown Pasting into a ticket, pull request or change request
–format html A self-contained page (dark mode included) to attach to a change review
–format json Pipelines and other tools

Add –ddl-diff to see a unified diff of each changed table’s CREATE TABLE, and –show-same to list the identical tables too.

The exit codes follow Percona Toolkit’s style, so the tool drops straight into CI or a cron job:

Exit code Meaning
0 The schemas match
1 Error (connection, permissions, bad arguments)
2 Differences found
3 Differences found and the –verify test failed

For example, a nightly drift check that only speaks up when something changed:

Options at a glance

Option What it does Default
–format text, sql, markdown, html or json text
–output FILE Write the report to a file standard output
–script FILE Also write the migration script to a file none
–include-drops Put DROP TABLE and DROP COLUMN in the script instead of commenting them out off
–verify DSN Test the script on a scratch database on this sandbox server off
–tables / –ignore-tables Compare only, or skip, these tables all
–databases / –ignore-databases Without D=: compare only, or skip, these databases all
–ddl-diff Show a unified diff of each changed CREATE TABLE off
–show-same Also list identical tables off
–use-database / –no-use Change or remove the script’s USE line target database
–save-snapshot NAME Save a schema as a snapshot none
–list-snapshots / –delete-snapshot ID Manage snapshots none
–list-databases DSN List a server’s databases none
–ask-pass Prompt for the password off
–defaults-file FILE Read credentials from a MySQL option file none
–ssl-mode disabled, preferred, required or verify_identity preferred
–title Title for markdown and HTML reports none

Limits worth knowing

  • Tables only. Views, stored procedures, functions, triggers and events aren’t compared yet.
  • Ratings follow MySQL 8.0. The instant/online/copy ratings follow MySQL 8.0 and later. On 5.7, fewer changes are instant (ADD COLUMN, for instance), so expect more of them to copy the table.
  • MariaDB isn’t tested yet. MariaDB’s DDL differs in places (current_timestamp(), JSON as LONGTEXT, system-versioned tables). Treat results there with care until it’s tested.
  • Column order and partitioning are reported, not scripted. That’s deliberate, as covered above.
  • –verify tests structure, not data. Run the “Check first” queries against the real target.
  • Renames are a judgement call. A dropped column and an added column with identical definitions are treated as a rename. The report tells you when it did that, so read those lines.
  • The script is a draft for review. pt-schema-diff never runs anything against the source or the target. That’s on purpose. You decide when, where and how each ALTER runs.

Try it and tell me what breaks

The project is on GitHub at Percona-Lab/pt-schema-diff under the GPL-2.0 license, the same license as Percona Toolkit. The goal is for it to become part of the toolkit, so its options and output follow the toolkit’s conventions.

Real schemas are messier than test fixtures. If pt-schema-diff misreads a table, reports a difference that isn’t one, rates a change wrongly, or writes a script that fails under –verify, please open an issue with the two CREATE TABLE statements. Those reports are what make the tool better.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted

Far
Enough.

Said no pioneer ever.
MySQL, PostgreSQL, InnoDB, MariaDB, MongoDB and Kubernetes are trademarks for their respective owners.
© 2026 Percona All Rights Reserved