Skip to lesson

Changing a live schema with new migrations

ShopLite is live. A developer "fixes" a typo in V1, and now no database that already ran it will start. Real changes must reach live data, with the app running, and be easy to back out.

Never edit an applied migration

A checksum mismatch is the startup error Flyway raises when an applied migration file no longer matches the checksum stored in flyway_schema_history. The app refuses to start.

Example 1 edits V1 after it ran, and the app stops. Example 2 repairs the history after a comment-only change.

Example 1 · Editing V1 after it ran: checksum mismatch

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

SQL
-- V1__create_schema.sql, edited after it already ran on shoplite_labCREATE TABLE customers (  customer_id INT          NOT NULL AUTO_INCREMENT PRIMARY KEY,  full_name   VARCHAR(120) NOT NULL,          -- was VARCHAR(100)  email       VARCHAR(255) NOT NULL,  ...
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
ERROR o.s.boot.SpringApplication : Application run failed
...
Caused by: org.flywaydb.core.api.exception.FlywayValidateException: Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 1
-> Applied to database : 509004249
-> Resolved locally    : 1222396894
Either revert the changes to the migration, or run repair to update the schema history.

What this code does

  • Flyway compares the checksum stored when V1 ran (509004249) with the edited file's (1222396894) and stops before touching anything.
  • The database still has VARCHAR(100): editing an applied script never changes a database that already ran it.
  • The right fix: git checkout -- src/main/resources/db/migration/V1__create_schema.sql, then write V2__widen_customer_name.sql with ALTER TABLE customers MODIFY full_name VARCHAR(120) NOT NULL.

Example 2 · pom.xml: the Flyway Maven plugin, and repair after a comment-only change

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

XML
<!-- pom.xml, inside <build><plugins>: Flyway commands from the terminal --><plugin>    <groupId>org.flywaydb</groupId>    <artifactId>flyway-maven-plugin</artifactId>   <!-- version managed by Spring Boot -->    <configuration>        <url>${env.DB_URL}</url>        <user>${env.DB_USER}</user>        <password>${env.DB_PASSWORD}</password>        <locations>            <location>filesystem:src/main/resources/db/migration</location>        </locations>    </configuration>    <dependencies>        <dependency>            <groupId>org.flywaydb</groupId>            <artifactId>flyway-mysql</artifactId>            <version>${flyway.version}</version>        </dependency>        <dependency>            <groupId>com.mysql</groupId>            <artifactId>mysql-connector-j</artifactId>            <version>${mysql.version}</version>        </dependency>    </dependencies></plugin>
Sample output
# V1 reverted, then one comment line added on purpose:
#   -- Reviewed by Priya: matches the Section 12 design.
$ mvn flyway:repair
[INFO] --- flyway:12.4.0:repair (default-cli) @ shoplite-api ---
[INFO] Database: jdbc:mysql://localhost:3306/shoplite_lab (MySQL 8.4)
[INFO] Repair of failed migration in Schema History table `shoplite_lab`.`flyway_schema_history` not necessary. No failed migration detected.
[INFO] Repairing Schema History table for version 1 (Description: create schema, Type: SQL, Checksum: 1903040739)  ...
[INFO] Successfully repaired schema history table `shoplite_lab`.`flyway_schema_history` (execution time 00:00.144s).
[INFO] BUILD SUCCESS

What this code does

  • The plugin reads the same DB_URL, DB_USER and DB_PASSWORD variables as the app. Plugin dependencies are not managed by Spring Boot, so they use the parent's flyway.version and mysql.version properties.
  • A comment is part of the file, so it changes the checksum too. repair stores the new checksum (1903040739); the schema itself is not touched.
  • mvn flyway:info from the same plugin prints a table of every migration with its state (Success, Pending, Failed).

An applied migration is a script that already has a row in flyway_schema_history. Flyway recomputes its checksum at every start, so any edit, even a comment, stops the app with Migration checksum mismatch for migration version 1. Editing does nothing to databases that already ran the old version: your laptop would get VARCHAR(120), production keeps VARCHAR(100), and nobody knows. So the fix is almost always to revert the edit and write the change as a new script, V2__....

flyway repair is for the rare harmless edit, such as a fixed comment: it rewrites the stored checksums to match the files. It also removes rows of failed migrations, which the half-applied section needs.

V2 adds a column with a default; V3 adds an index

Example 3 adds a gst_rate column in V2 and an index in V3, each in its own small script.

Example 3 · V2 and V3: a column with a default, then an index

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

SQL
-- src/main/resources/db/migration/V2__add_gst_rate_to_products.sql-- V2: GST rate per product, in percent. Existing rows get 18.00, the most common slab.ALTER TABLE products  ADD COLUMN gst_rate DECIMAL(4,2) NOT NULL DEFAULT 18.00;
-- src/main/resources/db/migration/V3__add_index_on_product_name.sql-- V3: product search filters and sorts by nameCREATE INDEX idx_products_name ON products (name);
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
INFO o.f.core.internal.command.DbValidate : Successfully validated 3 migrations (execution time 00:00.080s)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 1
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "2 - add gst rate to products"
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "3 - add index on product name"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 2 migrations to schema `shoplite_lab`, now at version v3 (execution time 00:00.557s)
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 21.001 seconds (process running for 23.33)

mysql> SELECT product_id, sku, price, gst_rate FROM products WHERE product_id <= 3;
+------------+----------+----------+----------+
| product_id | sku      | price    | gst_rate |
+------------+----------+----------+----------+
|          1 | MOB-RN13 | 17999.00 |    18.00 |
|          2 | MOB-GM35 | 19999.00 |    18.00 |
|          3 | MOB-IP15 | 69900.00 |    18.00 |
+------------+----------+----------+----------+

What this code does

  • Two files, two versions: Flyway runs them in order in one start, and the app starts because Product does not map gst_rate yet (extra columns are fine for validate).
  • Every existing product got 18.00 from the DEFAULT; without it, NOT NULL would give every row 0.00.
  • SHOW INDEX FROM products now lists idx_products_name. Keeping the index in its own script means a slow index build cannot block the column change.

A table that already has rows needs a decision for the new column: a NOT NULL column needs a DEFAULT (MySQL fills every existing row with it) or must be nullable at first. ADD COLUMN gst_rate DECIMAL(4,2) NOT NULL DEFAULT 18.00 gives every product the standard 18% rate until an admin changes it.

On MySQL 8 both changes run as online DDL for most cases, so reads and writes continue, but on a table with millions of rows they still take time. The entity does not have to change at the same time: ddl-auto=validate checks only what the entities map, so an extra column is allowed. The reverse, an entity field without a column, stops the app.

Expand and contract: renaming a column without downtime

Expand and contract changes a column in small steps so the old and the new app version both work at every moment: add the new shape, run both, then remove the old one.

Example 4 expands: V4 adds mobile and the app writes both columns. Example 5 contracts: V5 drops phone, first too early and then right.

Renaming phone to mobile takes three releases. Release 1, expand, V4: add the mobile column and copy phone into it; the app still reads phone. Release 2: the app reads mobile and writes both columns.

Example 4 · Expand: V4 adds mobile, the app writes both columns

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

Java
/* src/main/resources/db/migration/V4__add_customers_mobile.sql   -- V4 (expand): add the new column next to the old one and copy the data.   -- The running app still uses phone, so nothing breaks.   ALTER TABLE customers ADD COLUMN mobile VARCHAR(15) NULL;
   UPDATE customers SET mobile = phone;*/
// src/main/java/com/shoplite/customer/Customer.java (the release that ships with V4)@Column(length = 15)private String phone;                       // old column: still written until V5 drops it
@Column(length = 15)private String mobile;                      // new column: read from here
public Customer(String fullName, String email, String phone) {    this.fullName = fullName;    this.email = email;    changeMobile(phone);}
/** Writes both columns while old and new app versions run side by side. */public void changeMobile(String mobile) {    this.mobile = mobile;    this.phone = mobile;}
public String getMobile() { return mobile; }
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 3
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "4 - add customers mobile"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_lab`, now at version v4 (execution time 00:00.131s)
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 23.713 seconds (process running for 25.427)

mysql> SELECT customer_id, full_name, phone, mobile FROM customers WHERE customer_id <= 3;
+-------------+------------+------------+------------+
| customer_id | full_name  | phone      | mobile     |
+-------------+------------+------------+------------+
|           1 | Asha Rao   | 9876543201 | 9876543201 |
|           2 | Ravi Kumar | 9876543202 | 9876543202 |
|           3 | Meena Iyer | NULL       | NULL       |
+-------------+------------+------------+------------+

What this code does

  • V4 only adds and copies, so the previous app version (which knows only phone) keeps working while this one rolls out.
  • The new entity maps both columns and every write goes through changeMobile, which fills both. Rows saved by either version stay complete.
  • The column is nullable on purpose: Meena has no number, and old app versions do not fill mobile at all.

Example 5 · Contract: V5 drops phone, too early and then right

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

SQL
-- src/main/resources/db/migration/V5__drop_customers_phone.sql-- V5 (contract): ships only after every running app version reads and writes mobile.-- Copy rows that an old app version wrote to phone only, then drop the old column.UPDATE customers SET mobile = phone WHERE mobile IS NULL AND phone IS NOT NULL;
ALTER TABLE customers DROP COLUMN phone;
Sample output
run 1: V5 shipped while Customer.java still maps phone        (log prefix trimmed)
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "5 - drop customers phone"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_lab`, now at version v5 (execution time 00:00.432s)
ERROR j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: ... Schema validation: missing column [phone] in table [customers]

run 2: phone removed from Customer.java (changeMobile sets only mobile)
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_lab`: 5
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite_lab` is up to date. No migration necessary.
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 24.217 seconds (process running for 26.445)

mysql> SELECT customer_id, full_name, mobile FROM customers WHERE customer_id <= 3;
+-------------+------------+------------+
| customer_id | full_name  | mobile     |
+-------------+------------+------------+
|           1 | Asha Rao   | 9876543201 |
|           2 | Ravi Kumar | 9876543202 |
|           3 | Meena Iyer | NULL       |
+-------------+------------+------------+

What this code does

  • Run 1: Flyway dropped the column first, then validation failed. The DROP cannot be undone, and any server still running the V4-era app breaks at its next query on customers.
  • Run 2: with the entity matching, the app starts; Flyway did not rerun V5 because it already succeeded.
  • Contract only when every running version has stopped using the old column; in a real team that is a later release, not the same afternoon.

During a deploy two versions often run together, for example while servers restart one by one, so a single RENAME COLUMN would break whichever version expects the other name. The three steps:

  • Expand (V4): add the new column mobile and copy the data from phone. The running app still uses phone.
  • Release the app that reads mobile and writes both columns, so rows saved by either version stay complete.
  • Contract (V5), in a later release once no old version runs: copy any rows written to phone only, then drop phone, and remove phone from the entity in the same release.
Contract too early and Example 5 happens: the column is gone while an app version still maps it, and that version cannot even start.

MySQL DDL is not transactional: a half-applied migration

A half-applied migration is a script that failed after some of its statements already ran. MySQL commits each DDL statement at once, so nothing is rolled back and the history row shows success = 0.

Example 6 shows V6 failing on its second statement, and the recovery that follows.

Example 6 · A half-applied V6 and how to recover

Runs in: migration-lab: a practice copy of shoplite-api on the shoplite_lab database (V1 applied, Section 12 rows loaded)

SQL
-- src/main/resources/db/migration/V6__whatsapp_opt_in.sql (first version, with a typo on line 4)-- V6: WhatsApp updates need the customer's consentALTER TABLE customers ADD COLUMN whatsapp_opt_in BOOLEAN NOT NULL DEFAULT FALSE;
CREATE INDEX idx_customers_mobile ON customer (mobile);
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
INFO  o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "6 - whatsapp opt in"
ERROR o.f.core.internal.command.DbMigrate : Migration of schema `shoplite_lab` to version "6 - whatsapp opt in" failed! Please restore backups and roll back database and code!
...
Caused by: org.flywaydb.core.internal.exception.FlywayMigrateException: Failed to execute script V6__whatsapp_opt_in.sql
------------------------------------------------
SQL State  : 42S02
Error Code : 1146
Message    : Table 'shoplite_lab.customer' doesn't exist
Location   : db/migration/V6__whatsapp_opt_in.sql (...)
Line       : 4

mysql> SELECT version, description, success FROM flyway_schema_history WHERE version = '6';
+---------+-----------------+---------+
| version | description     | success |
+---------+-----------------+---------+
| 6       | whatsapp opt in |       0 |
+---------+-----------------+---------+
mysql> SHOW COLUMNS FROM customers LIKE 'whatsapp%';      -- line 2 DID run
whatsapp_opt_in  tinyint(1)  NO  0

# typo fixed (ON customers), app started again:
Caused by: org.flywaydb.core.api.exception.FlywayValidateException: Validate failed: Migrations have failed validation
Detected failed migration to version 6 (whatsapp opt in).
Please remove any half-completed changes then run repair to fix the schema history.

# recovery
mysql> ALTER TABLE customers DROP COLUMN whatsapp_opt_in;
$ mvn flyway:repair
[INFO] Successfully repaired schema history table `shoplite_lab`.`flyway_schema_history` (execution time 00:00.201s).
[INFO] Manual cleanup of the remaining effects of the failed migration may still be required.
$ mvn spring-boot:run
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_lab` to version "6 - whatsapp opt in"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_lab`, now at version v6 (execution time 00:00.381s)

What this code does

  • The ALTER on line 2 committed at once; the CREATE INDEX on line 4 failed. MySQL cannot undo the first, so the database is half way and the history row says success 0.
  • Flyway then refuses to continue until you clean up: drop the half-added column, repair removes the failed row, and the fixed script runs from the top.
  • Flyway's error gives the file, the line (4) and MySQL's message, which is usually enough to find the bug.

In MySQL, every CREATE, ALTER and DROP commits immediately; a transaction cannot roll it back. The next start stops with Detected failed migration to version 6. Fixing the typo is not enough, because rerunning the script would hit "Duplicate column" on its first statement.

Two habits make this rare: one DDL statement per migration where you can, and run every new script on a copy of real data before it reaches production.

Order of execution

Recover from a failed migration

V6 failed on its second statement. Tap the recovery steps in the right order.

Team branches that pick the same version number

Out of order means a migration whose version is lower than the database's current version but that has not been applied yet. Flyway refuses it by default.

Two people on two branches both write V7__...sql. After the merge, Flyway refuses to start with Found more than one migration with version 7 and lists both files.

Terminal
# both branches merged: two V7 filesls src/main/resources/db/migrationmvn clean packagemvn spring-boot:run
Output
V1__create_schema.sql ... V6__whatsapp_opt_in.sql
V7__add_order_delivery_note.sql
V7__add_product_brand.sql

Caused by: org.flywaydb.core.api.FlywayException: Found more than one migration with version 7
Offenders:
-> ...\db\migration\V7__add_product_brand.sql (SQL)
-> ...\db\migration\V7__add_order_delivery_note.sql (SQL)

The fix is cheap before anything is deployed: rename the later one to the next free number (V8). The harder case is a branch merged after a higher version already ran somewhere: the database is at V8 and a new V7 file appears. Flyway stops with Detected resolved migration not applied to database: 7, because running scripts out of order can give a different schema than in-order databases. Rename the file to V9; use spring.flyway.out-of-order=true only when the script truly does not depend on V8.

Use mvn clean package after renaming or deleting a migration: a plain package can leave the old file in target/classes, and Flyway still finds it.

Next step

Check your understanding

12 quick questions