Liquibase database migrations: changelogs to CI
Liquibase applies database schema changes from version-controlled files, in order, exactly once per database, and records what it applied. It turns “run these SQL scripts in the right order on every environment and hope nobody forgot one” into a repeatable step a pipeline can run. This page follows an invented OrdersPortal orders table from its first changeset to a rollback and a GitLab pipeline.
All command samples were run with Liquibase 5.0.4 (the liquibase-core jar from Maven Central with Java 21) against a local H2 2.5 database file, so they need no database server. Output is trimmed to the relevant lines. With the Liquibase CLI installed, run the same commands as liquibase <command> from the folder that holds liquibase.properties. The GitLab CI job at the end was checked for YAML syntax only.
Topics on this page
Section titled “Topics on this page”| Topic | What it answers |
|---|---|
| How Liquibase works | Changelogs, changesets, the tracking tables and checksums. |
| Changelogs | Formats, a master changelog, and how to organize files. |
| Running updates safely | validate, status, update-sql and update. |
| Contexts and labels | Running a changeset only in some environments or releases. |
| Rollbacks | Rollback blocks, tags, rollback commands and testing rollbacks. |
| GitLab CI integration | Validating on merge requests and updating from the default branch. |
How Liquibase works
Section titled “How Liquibase works”A changelog is the file Liquibase reads. It lists changesets, each identified by the combination of its id, its author and the changelog file path. A changeset is the unit of deployment: Liquibase runs it once per database, inside a transaction where the database supports transactional DDL, and records it.
The record lives in two tables Liquibase creates in the target database. DATABASECHANGELOG has one row per applied changeset with its identity, execution time, order, checksum, tag, contexts and labels. DATABASECHANGELOGLOCK holds a lock while an update runs, so two deployments cannot apply changes concurrently.
The checksum protects history. If someone edits a changeset that has already run, its checksum no longer matches and Liquibase refuses to continue. This run edited a column length in an applied changeset:
ERROR: Exception Primary Class: ValidationFailedExceptionERROR: Exception Primary Reason: Validation Failed: 1 changesets check sum db/changelog/changes/001-create-orders.yaml::001-create-orders::ordersportal-team was: 9:1033d42f468effc462ff189d715a5a3b but is now: 9:01898eba2db9a15bdb2159b728164eb0The fix is almost always a new changeset that alters the column, not an edit to the old one. runOnChange (rerun when changed, useful for views and stored procedures) and validCheckSum (accept a known new checksum) exist for the cases where changing an applied changeset is intended.
Liquibase 5.0 (2025) split the product into the Community edition, licensed under the Functional Source License (FSL), and the commercial Liquibase Secure edition. The Community edition and its liquibase/liquibase Docker image no longer bundle database drivers or extensions; you add them with the Liquibase Package Manager (lpm).
Pitfalls:
- Editing applied changesets. It breaks every environment that already ran them. Add a new changeset.
- Running Liquibase and manual DDL side by side. The tracking table no longer describes the schema. Route every schema change through changelogs.
Changelogs
Section titled “Changelogs”Changelogs can be written in SQL, XML, YAML or JSON. Formatted SQL is plain SQL with comment annotations, convenient for teams that think in SQL; XML, YAML and JSON use Liquibase’s database-independent change types (createTable, addColumn, createIndex), which can generate rollback statements automatically and target several database engines from one file. Mixing formats is fine.
Use a master changelog that only includes other files, so each change lives in its own small file and merge conflicts are rare:
databaseChangeLog: - includeAll: path: changes/ relativeToChangelogFile: trueincludeAll runs files in alphabetical order, so name them with a sortable prefix. Teams that want explicit control list each file with include instead.
databaseChangeLog: - changeSet: id: 001-create-orders author: ordersportal-team changes: - createTable: tableName: orders columns: - column: name: id type: BIGINT autoIncrement: true constraints: primaryKey: true - column: name: customer_email type: VARCHAR(255) constraints: nullable: false - column: name: created_at type: TIMESTAMP defaultValueComputed: CURRENT_TIMESTAMP-- db/changelog/changes/002-add-order-status.sql--liquibase formatted sql
--changeset ordersportal-team:002-add-order-statusALTER TABLE orders ADD COLUMN status VARCHAR(20) DEFAULT 'NEW' NOT NULL;--rollback ALTER TABLE orders DROP COLUMN status;
--changeset ordersportal-team:003-index-status context:!testCREATE INDEX ix_orders_status ON orders(status);--rollback DROP INDEX ix_orders_status;Connection settings go in liquibase.properties (or LIQUIBASE_COMMAND_* environment variables, as in CI below):
# liquibase.properties - local H2 database for the sampleschangelog-file=db/changelog/db.changelog-master.yamlurl=jdbc:h2:file:./ordersportalusername=sapassword=Pitfalls:
- Renaming or moving changelog files. The file path is part of each changeset’s identity, so Liquibase treats moved changesets as new. Set
logicalFilePathbefore moving files. - One changeset with many statements. If the third statement fails on a database without transactional DDL, the first two stay applied and the changeset is not recorded. Keep one logical change per changeset.
Running updates safely
Section titled “Running updates safely”The commands form a natural sequence, and a pipeline should use them in this order:
validatechecks the changelog for errors (syntax, duplicate identities, checksum mismatches) without changing the database.status --verboselists changesets not yet applied.update-sqlprints the SQLupdatewould run, for review or for a DBA to apply by hand.updateapplies pending changesets.
Run against an empty database after the first changeset was applied and tagged (see Rollbacks), status shows the two pending changesets and update applies them:
$ liquibase validateNo validation errors found.
$ liquibase status --verbose2 changesets have not been applied to SA@jdbc:h2:file:./ordersportal db/changelog/changes/002-add-order-status.sql::002-add-order-status::ordersportal-team db/changelog/changes/002-add-order-status.sql::003-index-status::ordersportal-team
$ liquibase updateUPDATE SUMMARYRun: 2Previously run: 1Filtered out: 0-------------------------------Total change sets: 3Running Changeset: db/changelog/changes/002-add-order-status.sql::002-add-order-status::ordersportal-teamRunning Changeset: db/changelog/changes/002-add-order-status.sql::003-index-status::ordersportal-teamLiquibase: Update has been successful. Rows affected: 0update-sql on a fresh database showed the tracking tables and the generated DDL, for example CREATE TABLE PUBLIC.orders (id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, ...) for H2: the YAML change types are translated into each database’s dialect.
Schedule schema changes for zero-downtime releases with the expand and contract pattern: first add new columns or tables in a backward-compatible way, deploy the application that uses them, and only in a later release drop what the old version needed. Then the database change and the application deployment do not have to happen at the same instant, and an application rollback does not need a database rollback.
Pitfalls:
- Long locks on large tables. Adding an index or a non-null column can lock a busy table. Review
update-sqloutput and use online DDL options where your database supports them. - A stuck lock after a crash. If a run is killed,
DATABASECHANGELOGLOCKcan stay locked.liquibase release-locksclears it, after confirming no other update is running.
Contexts and labels
Section titled “Contexts and labels”Contexts and labels filter which changesets run. A changeset has a context or label expression, and the command line supplies --context-filter or --label-filter. Contexts are typically environments (test, prod); labels are typically features or releases (orders-2.4). Both support expressions with and, or, ! and parentheses, and the expression can sit on either side.
In the sample, the index changeset has context:!test, so a test database skips it:
$ liquibase update --context-filter=testRun: 1Filtered out: 1Running Changeset: db/changelog/changes/002-add-order-status.sql::002-add-order-status::ordersportal-teamA changeset without a context runs in every context, and running without a filter runs every changeset, so filters only exclude what you mark. Seed data for test environments (context: test) and data fixes for one release (labels: orders-2.4) are common uses.
Pitfalls:
- Forgetting the filter in one pipeline. Without
--context-filter, test-only data reaches production. Set the filter explicitly in every environment’s job. - Using contexts for schema differences between environments. Schemas should be identical everywhere; keep contexts for data and operational changes.
Rollbacks
Section titled “Rollbacks”A rollback undoes applied changesets in reverse order. For many change types (createTable, addColumn, createIndex), Liquibase generates the undo statement automatically. For formatted SQL and changes such as dropTable or data updates, it cannot, so write a rollback: a --rollback comment in SQL, or a rollback block in XML or YAML. A changeset can also declare an empty rollback when undoing is intentionally impossible.
Tags mark a point to roll back to. Tag the database after each release, either with the tag command or a tagDatabase changeset. In the sample run, 001-create-orders was applied and tagged v1.0.0, then the status changesets were applied, then rolled back to the tag:
$ liquibase updateRunning Changeset: db/changelog/changes/001-create-orders.yaml::001-create-orders::ordersportal-team$ liquibase tag --tag=v1.0.0Successfully tagged 'SA@jdbc:h2:file:./ordersportal'$ liquibase update...$ liquibase rollback --tag=v1.0.0Rolling Back Changeset: db/changelog/changes/002-add-order-status.sql::003-index-status::ordersportal-teamRolling Back Changeset: db/changelog/changes/002-add-order-status.sql::002-add-order-status::ordersportal-teamLiquibase command 'rollback' was executed successfully.liquibase history afterwards showed only 001-create-orders, carrying the v1.0.0 tag. The other rollback commands are rollback-count --count=N (undo the last N changesets) and rollback-to-date. Each has a -sql variant that prints the statements instead of running them; rollback-sql --tag=v1.0.0 printed DROP INDEX ix_orders_status;, ALTER TABLE orders DROP COLUMN status; and the matching deletes from DATABASECHANGELOG.
update-testing-rollback applies pending changesets, rolls them back and applies them again, which proves in CI that every rollback actually works:
$ liquibase update-testing-rollbackRunning Changeset: db/changelog/changes/002-add-order-status.sql::003-index-status::ordersportal-teamLiquibase: Update has been successful. Rows affected: 0Liquibase command 'update-testing-rollback' was executed successfully.Remember that a rollback of a destructive change cannot restore data: rolling back an addColumn drops the column and its contents. For production incidents, a forward fix (a new changeset) is often safer than a rollback, and backups remain the real safety net.
Pitfalls:
- Missing rollback statements for SQL changesets. The rollback fails when you need it most. Require
--rollbackin code review, and runupdate-testing-rollbackin CI. - No tags. Without a tag per release, you must count changesets under pressure. Tag after every deployment.
GitLab CI integration
Section titled “GitLab CI integration”A pipeline makes database changes reviewable and repeatable: validate and preview on merge requests, apply automatically to test environments, and apply to production after approval. Because the Liquibase 5 Community image ships without JDBC drivers, build a small image that adds the driver once:
FROM liquibase/liquibase:5.0.4RUN lpm add postgresql --globalThe pipeline then uses that image and passes connection settings through LIQUIBASE_COMMAND_* variables, defined as protected, masked CI/CD variables per environment (verified locally: Liquibase 5 reads LIQUIBASE_COMMAND_URL, LIQUIBASE_COMMAND_USERNAME, LIQUIBASE_COMMAND_PASSWORD and LIQUIBASE_COMMAND_CHANGELOG_FILE). This file was checked for YAML syntax only and not run on GitLab:
# .gitlab-ci.yml (database jobs)variables: LIQUIBASE_COMMAND_CHANGELOG_FILE: db/changelog/db.changelog-master.yaml
.liquibase: image: name: $CI_REGISTRY_IMAGE/liquibase:5.0.4 # Bypass the image's entrypoint script so GitLab Runner starts a plain shell. entrypoint: [""]
db_validate: extends: .liquibase stage: test environment: name: staging action: verify script: - liquibase validate - liquibase update-sql > update.sql artifacts: paths: [update.sql] expose_as: "Database changes" rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
db_update_staging: extends: .liquibase stage: deploy environment: staging script: - liquibase update --context-filter=staging - liquibase tag --tag="$CI_COMMIT_SHORT_SHA" rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
db_update_production: extends: .liquibase stage: deploy environment: production script: - liquibase update --context-filter=prod - liquibase tag --tag="$CI_COMMIT_SHORT_SHA" rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH when: manualThe update.sql artifact appears on the merge request, so reviewers read the actual SQL rather than the change types. Run the database job before the application deployment job in the same pipeline, and keep changes backward compatible (expand and contract) so the order can never break the running version. Environment-scoped variables give each job the right connection string without conditionals.
Pitfalls:
- Relying on the image’s entrypoint script in GitLab jobs. The
liquibase/liquibaseimage startsdocker-entrypoint.sh, which decides whether its arguments are a shell command or Liquibase arguments. Settingimage:entrypointto an empty value, as shown, gives the runner a plain shell and avoids surprises. - The same credentials for every environment. Use environment-scoped, protected variables, and a database user with only the rights migrations need.
Choosing between them
Section titled “Choosing between them”| You need | Use |
|---|---|
| Reviewable SQL written by people who think in SQL | Formatted SQL changelogs with --rollback comments |
| Database-independent changes with generated rollbacks | YAML or XML change types |
| Test-only data or one-off fixes | Contexts and labels |
| A named point to return to | tag after each release, then rollback --tag |
| Proof that rollbacks work | update-testing-rollback in CI |
| DBA review before production | update-sql as a merge request artifact |
Interview questions
Section titled “Interview questions”How does Liquibase know which changesets to run?
It compares the changesets in the changelog, identified by id, author and file path, with the rows in DATABASECHANGELOG, and runs those not yet recorded. DATABASECHANGELOGLOCK prevents concurrent runs.
What happens if someone edits a changeset that already ran?
Its checksum changes, and validation fails with a checksum error on every database that applied the original. The correct fix is a new changeset; runOnChange and validCheckSum are for deliberate exceptions.
What is the difference between contexts and labels?
Both filter changesets. Contexts usually describe the environment or run type and are supplied with --context-filter; labels usually describe features or releases and are supplied with --label-filter. Either side can hold an expression.
When is a rollback not enough? When the change destroyed data (a dropped column or table, an overwriting update). Rollback recreates structure, not contents. Use backups, and prefer backward-compatible expand and contract changes so application rollbacks do not need database rollbacks.
Senior scenario: OrdersPortal’s releases need a 30-minute outage because the API and schema change together, and last month a hand-run script was applied twice. How do you change the process?
Put every schema change in Liquibase changelogs with one logical change per changeset and mandatory rollbacks, validated and previewed with update-sql on merge requests, and applied only by the pipeline, which removes double application. Adopt expand and contract: add new structures in a release before the code uses them and remove old ones a release later, so deployments need no outage and the order of database and application deploys no longer matters. Tag after each release, test rollbacks with update-testing-rollback, and review large-table changes for locking.
Related pages
Section titled “Related pages”- DevOps overview
- GitLab CI/CD pipelines: rules, protected environments and artifacts used above.
- TeamCity: running database updates as part of a build chain.
- Docker images, containers and registries: building the custom Liquibase image.