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.
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:
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.
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:
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.
Download the binary for your system from the releases page, and check it against the published checksums:
|
1 2 3 4 |
curl -fLO https://github.com/Percona-Lab/pt-schema-diff/releases/download/v0.1.0/pt-schema-diff-linux-amd64 curl -fLO https://github.com/Percona-Lab/pt-schema-diff/releases/download/v0.1.0/SHA256SUMS sha256sum --check --ignore-missing SHA256SUMS chmod +x pt-schema-diff-linux-amd64 |
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:
|
1 2 |
CREATE USER 'schema_audit'@'%' IDENTIFIED BY 'change_me'; GRANT SELECT ON *.* TO 'schema_audit'@'%'; |
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:
|
1 |
pt-schema-diff h=db-prod,u=schema_audit,D=shop D=shop_staging --ask-pass |
And for two servers:
|
1 |
pt-schema-diff h=db-prod,u=schema_audit,D=shop h=db-staging,D=shop --ask-pass |
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).
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.
|
1 |
pt-schema-diff h=db-prod,u=schema_audit,D=shop h=db-staging,D=shop --ask-pass |
The report starts with a summary:
|
1 2 3 4 |
# Source: db-prod:3306 · shop (the schema to match) # Target: db-staging:3306 · shop (the schema the script changes) # 6 tables: 1 to create, 4 to change, 1 only in the target, 0 identical. # Changes: 5 critical, 14 warnings, 6 suggestions, 7 safe. |
Then it lists each table, worst first. Each heading shows the table’s overall rating and the worst way MySQL will run its ALTER:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
CRITICAL customers — changed · MySQL: blocks writes CRITICAL Change column `id`: `int` → `int unsigned`. Values outside the new range are rejected (strict mode) or clipped. Check first: `SELECT MIN(id), MAX(id) FROM customers`. MySQL copies the whole table and blocks writes to it until the copy finishes. [MySQL: blocks writes] WARNING Rename column `name` → `full_name`. The data is kept. Treated as a rename because `name` exists only in the target, `full_name` only in the source, and both have the same definition. If they are really two different columns, replace this CHANGE COLUMN with a DROP COLUMN and an ADD COLUMN. MySQL only updates the table definition, so it is instant. OK Change column `status`: `enum('active','paused','closed')` → `enum('active','paused','closed','deleted')`. Safe for the data. Values are only added at the end of the list. MySQL only updates the table definition, so it is instant. CRITICAL Change column `notes`: `mediumtext` → `text`. Values longer than the new type allows are rejected (strict mode) or cut off. Check first: `SELECT MAX(LENGTH(notes)) FROM customers`. CRITICAL Drop column `legacy_flag` `tinyint`. Everything stored in this column is deleted for good. It exists only in the target. The script leaves this commented out unless --include-drops is given. WARNING Add unique index `uq_email` (`email`). The ALTER fails if the table already holds duplicate values. Check first: `SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1`. Reads and writes continue while it builds. [MySQL: online] ... |
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.
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.
After the report comes the script:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
-- Statements that delete data (DROP TABLE, DROP COLUMN) are commented out. Run with -- --include-drops to include them. USE `shop`; -- Create the tables that exist only in the source CREATE TABLE `audit_log` ( `id` bigint NOT NULL AUTO_INCREMENT, `order_id` bigint unsigned NOT NULL, `message` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `order_id` (`order_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- Change existing tables ALTER TABLE `customers` MODIFY COLUMN `id` int unsigned NOT NULL AUTO_INCREMENT, CHANGE COLUMN `name` `full_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '', MODIFY COLUMN `status` enum('active','paused','closed','deleted') ... NOT NULL DEFAULT 'active', ... ADD UNIQUE INDEX `uq_email` (`email`), ADD CONSTRAINT `chk_balance` CHECK ((`balance` >= 0)), COMMENT='Customer accounts'; -- ALTER TABLE `customers` -- DROP COLUMN `legacy_flag`; ALTER TABLE `orders` MODIFY COLUMN `customer_id` int unsigned NOT NULL, ... RENAME INDEX `customer_id` TO `idx_customer`, ENGINE=InnoDB, DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci, ROW_FORMAT=DYNAMIC; -- Drop the tables that exist only in the target -- DROP TABLE `old_stuff`; -- Add foreign keys (last, so the tables and indexes they need exist) ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_customer` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE; |
A few design decisions are worth explaining:
Save the script to a file with –script migration.sql, or print only the script with –format sql.
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:
|
1 2 |
pt-schema-diff h=db-prod,u=schema_audit,D=shop h=db-staging,D=shop --ask-pass \ --verify h=db-sandbox,u=sd_sandbox |
It then:
If every statement runs and the only remaining differences are the ones the script deliberately skipped, the test passes:
|
1 2 3 4 5 6 |
# Script test: Passed on MySQL 9.7.1 (scratch copy of the target): all 7 statements ran and the # result matches the source. # Expected (excluded drops or not scripted): `customers`: Drop column `legacy_flag` ... # Expected (excluded drops or not scripted): `events`: Column order differs (not changed by the script). # Expected (excluded drops or not scripted): `events`: Partitioning differs (not changed by the script). # Expected (excluded drops or not scripted): `old_stuff`: Drop table `old_stuff` ... |
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:
|
1 2 |
CREATE USER 'sd_sandbox'@'%' IDENTIFIED BY 'change_me'; GRANT ALL ON `pt\_schema\_diff\_%`.* TO 'sd_sandbox'@'%'; |
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.
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
WARNING page_views — changed · MySQL: blocks writes WARNING Change column `id`: `int` → `bigint`. Safe for the data. The new type holds every current value. MySQL copies the whole table and blocks writes to it until the copy finishes. SUGGESTION Add index `idx_seen` (`seen`). No data changes. Reads and writes continue while it builds. WARNING Large table: ~1,197,477 rows, 46.6 MB. This ALTER rebuilds or copies the table, which can take a long time and makes replicas fall behind. Run it with pt-online-schema-change or gh-ost instead (a ready pt-online-schema-change command is shown with this table's SQL), so writes are not blocked. Online alternative (Percona Toolkit; foreign keys are left to the main script): pt-online-schema-change --alter 'MODIFY COLUMN `id` bigint NOT NULL AUTO_INCREMENT, ADD INDEX `idx_seen` (`seen`)' \ D=shop,t=page_views --dry-run # then the same command with --execute instead of --dry-run |
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.
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:
|
1 |
pt-schema-diff h=db-prod,u=schema_audit h=db-staging --ask-pass |
You get an overview first, then the full report for each database that differs:
|
1 2 3 4 5 6 |
DATABASE STATUS DETAILS mdb_app differs 1 to create, 4 to change, 1 only in the target; 3 critical, 16 warnings mdb_crm identical mdb_empty only on the source · create 0 to create, 0 to change, 0 only in the target; 0 critical, 0 warnings mdb_legacy only on the target not dropped by the script mdb_new only on the source · create 1 to create, 0 to change, 0 only in the target; 0 critical, 0 warnings |
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.
Either side can also be a file. The tool reads:
– 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:
|
1 2 3 |
pt-schema-diff schema/shop.sql h=db-prod,u=schema_audit,D=shop --ask-pass mysqldump -h db-prod --no-data shop | pt-schema-diff - h=db-staging,u=schema_audit,D=shop --ask-pass pt-schema-diff shop_before.sql shop_after.sql |
Snapshots save a schema so you can compare against it later. Take one before a release, then check what the release actually changed:
|
1 2 |
$ pt-schema-diff --save-snapshot before-release h=db-prod,u=schema_audit,D=shop --ask-pass Saved snapshot 20261125-085913-c98845 ("before-release", 5 tables from db-prod:3306 · shop) Compare with it later as snapshot:20261125-085913-c98845 $ pt-schema-diff snapshot:latest h=db-prod,u=schema_audit,D=shop --ask-pass |
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.
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:
|
1 2 3 |
pt-schema-diff h=db-prod,u=schema_audit h=db-dr --defaults-file /etc/schema_audit.cnf \ --format markdown --output /var/tmp/drift.md [ $? -eq 2 ] && mail -s "Schema drift: prod vs DR" dba-team@example.com < /var/tmp/drift.md |
| 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 |
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.
Resources
RELATED POSTS