Sub topic 3
Writing versioned SQL migrations
This chapter assumes you already know basic Spring Boot configuration, SQL DDL and DML, and how to add a Maven or Gradle dependency. It also assumes you have added flyway-core and the database module for your database to a Spring Boot project, as shown in the previous chapter. Here you write the migrations themselves. You will learn the naming rules, how Flyway orders files, and which mistakes cause startup failures.
What a versioned migration is
A versioned migration is a SQL file that Flyway applies exactly once, in version order. Flyway records each applied file in its history table. On later startups it skips files it has already applied and runs only the new ones.
Versioned migrations are the main tool for evolving a schema. They create tables, add columns, add indexes, and change data. Flyway also supports repeatable and Java migrations, which later chapters cover.
The naming convention
Flyway finds migrations by file name. The pattern is:
V<version>__<description>.sqlThe parts are:
Vis the prefix. It must be an uppercase V by default.<version>is one or more numbers separated by dots or single underscores, such as1,2,1.1or2024.03.15.__is two underscores. This separator is the most common source of naming errors. One underscore does not work.<description>is free text. Underscores are shown as spaces in Flyway's output..sqlis the suffix.
Here are some valid and invalid names:
| File name | Valid? | Reason |
|---|---|---|
| `V1__create_app_user.sql` | Yes | Version 1 |
| `V1.1__add_index.sql` | Yes | Version 1.1 |
| `V2_add_column.sql` | No | One underscore after the version |
| `v3__add_table.sql` | No | Lowercase prefix |
| `V4__add_table.txt` | No | Wrong suffix |
A file whose name does not match any pattern is not always reported. Flyway may ignore it silently, so a typo can mean your migration never runs. Check the startup log or the history table after adding a file.
Your first migration
Spring Boot's default location is classpath:db/migration, which maps to src/main/resources/db/migration. Create this file there:
-- src/main/resources/db/migration/V1__create_app_user.sql
CREATE TABLE app_user (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The identity column syntax works on PostgreSQL. Other databases use different syntax for auto-generated keys, so adjust it for yours.
Start the application. Flyway sees that the database has no history yet, creates the history table, runs V1, and records it. The next time the application starts, V1 is already recorded, so Flyway does nothing.
Changing the schema: add a new file
Suppose you want a display name on each user. Do not edit V1. Add a new, higher-numbered file:
-- src/main/resources/db/migration/V2__add_display_name.sql
ALTER TABLE app_user ADD COLUMN display_name VARCHAR(200);The rule is simple. Once a migration has been applied to any database other than your own scratch copy, treat the file as frozen. Editing it changes its checksum, and Flyway will refuse to start the next time it validates (see the checksum chapter). It would also leave databases that already ran the old version different from databases that run the new version.
How Flyway orders versions
Flyway sorts versions numerically, part by part. It does not compare file names as text.
1 < 1.1 < 1.2 < 2 < 10 < 10.1So V10__... runs after V2__..., as you would expect. With a text sort, V10 would come before V2. Flyway avoids that mistake.
Two files with the same version are an error. Flyway stops with a message that names both files. This often happens when two developers add V5 on different branches, which is covered in the team workflow chapter.
Versions do not have to be consecutive. You can use V1, V5, V10 and leave room between them. Many teams instead use timestamps such as V20261201_0935__add_orders.sql. A timestamp reduces collisions between branches, at the cost of longer names.
What the database does with a migration
Flyway runs each versioned migration in its own transaction when the database supports transactional DDL. PostgreSQL does. If any statement in the file fails, the whole file is rolled back and Flyway does not record it. Startup fails with the error.
MySQL and Oracle commit implicitly after most DDL statements. A failure halfway through a file there can leave the schema partly changed, with no record in the history table. The next start then fails again, because the first statements already ran. Keep migrations small on those databases, ideally one logical change per file, so a failure is easy to repair.
The following diagram shows the sequence for one new migration file.
Writing a good migration
A few habits prevent most problems.
- One purpose per file. A file that creates a table and also rewrites a million rows is hard to retry or review. Separate schema changes from data changes.
- Name the description for the change.
V7__add_orders_status_index.sqlhelps someone reading the history table months later.V7__changes.sqldoes not. - Use explicit constraint and index names. Generated names differ between databases and between runs. An explicit name lets a later migration drop it reliably.
- Do not depend on application code. A migration is SQL against a known schema. It should not assume anything about entity classes that may change later.
- Keep it deterministic. The same file must produce the same result on a developer laptop, in CI, and in production.
Here is a migration that adds a table with a foreign key, a named index, and some seed data:
-- src/main/resources/db/migration/V3__create_orders.sql
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'NEW',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES app_user (id)
);
CREATE INDEX idx_orders_user_id ON orders (user_id);Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Migration never runs, no error | File name does not match the pattern, or the file is in the wrong folder | Check the double underscore, the `V` prefix, and the `locations` setting |
| `Found more than one migration with version N` | Two files share a version | Renumber the newer file before it is applied anywhere |
| `Validate failed: Migration checksum mismatch` | An applied file was edited | Restore the original file, and put the change in a new migration |
| `Detected resolved migration not applied to database` | A file with a lower version than the latest applied one appeared later | See the team workflow chapter on out-of-order migrations |
| Startup fails on a syntax error | The SQL is wrong for the target database | Fix the SQL. On a transactional database, nothing was recorded, so you can edit the failed file |
The last row has a nuance. A file that failed and was rolled back was never applied, so editing it is safe. On a database without transactional DDL, a failed file may leave a failed entry or partial changes, and you must repair the state by hand before retrying.
A worked example of the whole cycle
- Start with an empty database. Run the application.
V1andV2apply, and the history table has two rows. - Add
V3__create_orders.sql. Restart. OnlyV3runs. - Realize
orders.statusneeds a length of 30. Do not editV3. AddV4__widen_orders_status.sqlwithALTER TABLE orders ALTER COLUMN status TYPE VARCHAR(30);on PostgreSQL. - Restart. Only
V4runs.
Every change is a small, reviewable file, and the order is the same everywhere.
Exercise
A teammate renames V2__add_display_name.sql to V2_add_display_name.sql while cleaning up file names, and the migration has already run in production. What problems can this cause, and what should be done?
Show answer
The single underscore means the name no longer matches the versioned migration pattern, so Flyway may ignore the file. If it is ignored, Flyway sees the history row for version 2 with no matching file, and validation can report an applied migration that is missing locally. Even if the pattern matched, renaming changes the description, which Flyway also validates. Restore the original name V2__add_display_name.sql with two underscores. Do not rename applied migrations.
Exercise
You have V1, V2, and V9 applied. Where does a new file named V10__add_index.sql run, and where does V9.5__fix.sql run if you add it afterwards?
Show answer
V10 runs after V9, because Flyway compares versions numerically, not as text. V9.5 has a lower version than the applied V10 would have, but the key point is that it is higher than 9. If V10 is already applied, V9.5 is lower than the latest applied version and is reported as an unapplied migration that is out of order, so validation fails unless out-of-order is enabled. If V10 has not been applied yet, V9.5 runs before it.