Sub topic 14
Running Schema Changes Inside Transactions
Prerequisites
You should know basic CREATE TABLE, ALTER TABLE, and transaction statements. A transaction is a group of database operations that succeeds together or is undone together.
Schema changes are called DDL, or data definition language. ALTER TABLE and DROP TABLE are DDL statements. INSERT, UPDATE, and DELETE are DML, or data manipulation language.
How transactional DDL works
A database that supports transactional DDL treats a schema change like other transaction work:
- Start a transaction with
BEGIN. - Run one or more schema changes.
- Use
COMMITto keep them. - Use
ROLLBACKto undo them.
The following PostgreSQL example adds a column and a constraint, then rolls both changes back:
DROP TABLE IF EXISTS customers;
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
BEGIN;
ALTER TABLE customers
ADD COLUMN phone VARCHAR(30);
ALTER TABLE customers
ADD CONSTRAINT customers_name_length
CHECK (length(name) >= 1);
ROLLBACK;
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'customers'
ORDER BY ordinal_position;After the rollback, the phone column does not exist. The check constraint does not exist either. The original table definition remains.
To keep a change, replace ROLLBACK with COMMIT:
BEGIN;
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';
COMMIT;A transaction protects the database from a partially applied group of compatible changes. For example, adding a column and then adding an index can be committed as one unit. If the index creation fails before the commit, the transaction can be rolled back.
Database support and migration tools
Transactional DDL is database-specific. PostgreSQL supports transactional changes for most DDL, so a migration can usually contain several statements inside one transaction.
MySQL commonly performs an implicit commit around many DDL statements, including ALTER TABLE. In that case, a later ROLLBACK may not undo the schema change. SQL Server and SQLite support transactions for many schema operations, but individual statements and database settings still matter.
Migration tools may start and commit transactions automatically. Check the tool and database documentation before assuming that a rollback works.
Locks and long-running changes
DDL often takes a lock on the table. The lock can block reads or writes, or it can wait for another transaction to finish. Large type conversions, index creation, and table rewrites can take a long time.
Plan changes during a suitable maintenance window, inspect active transactions, and test the expected lock behavior on a copy of production-sized data.
Exercise
In PostgreSQL, a migration adds a column and then fails while adding a constraint. Which command should normally undo the column addition?
Show answer
ROLLBACK. Because both DDL statements run in the same transaction, PostgreSQL restores the schema from before BEGIN.