How do you handle database migrations during deployments?

Handling database migrations during deployment means using a version-controlled migration tool to apply incremental, repeatable schema changes as part of the CI/CD pipeline, rather than running ad-hoc SQL by hand.

Key Points: • Tools like Flyway or Liquibase track applied migrations in a metadata table so each script runs exactly once, in order. • Migration scripts live in the application repository and are versioned alongside the code that depends on them. • The CI/CD pipeline runs migrations automatically as a deployment step, before or alongside the new application version starting up. • Rollback scripts or a documented rollback plan should exist for emergencies, since not every schema change is trivially reversible. • Migrations should be backward-compatible with the previous app version during rolling deployments, so old and new instances can both run against the database briefly.

Example: A team adds a new nullable column via a Flyway script named V12__add_last_login_column.sql; the pipeline runs flyway migrate before the new app version starts, and Flyway records that version 12 has been applied so it never runs twice.

Code Example:

-- V12__add_last_login_column.sql
ALTER TABLE users ADD COLUMN last_login TIMESTAMP NULL;

Interview Tip: A concise interview answer is:

"I use a migration tool like Flyway or Liquibase, checked into the repo, so schema changes are versioned and applied automatically as a pipeline step. I write migrations to be backward-compatible during rolling deploys and keep rollback scripts ready in case something goes wrong."