Sub topic 14
Running Schema Changes Inside Transactions
This chapter assumes you know BEGIN, COMMIT and ROLLBACK for DML, and that you have met ALTER TABLE and DROP TABLE in earlier chapters. You will learn which databases let you undo a schema change, which ones commit it behind your back, and how to write migration scripts that stay safe either way.
Why transactions matter for DDL
A transaction groups statements so they succeed or fail as one unit. With INSERT, UPDATE and DELETE, you take this for granted. If a script fails halfway, ROLLBACK returns the data to its earlier state.
Schema changes are riskier than data changes. A migration often runs several statements in order: add a column, copy data into it, drop the old column, add a constraint. If the third statement fails and the first two have already taken effect, the table is stuck in a half-migrated state. Application code written for either the old or the new schema may break against it.
If the database supports transactional DDL, you can wrap the whole migration in one transaction. Any failure then leaves the schema exactly as it was.
Transactional DDL by database
Support differs a lot between systems. Check this before you rely on ROLLBACK.
| Database | DDL inside a transaction | What happens |
|---|---|---|
| PostgreSQL | Fully transactional | `ALTER TABLE` and `DROP TABLE` can be rolled back. |
| SQLite | Transactional | Schema changes roll back with the rest of the transaction. |
| SQL Server | Transactional | Most DDL can be rolled back in an explicit transaction. |
| MySQL (InnoDB) | Not transactional | Each DDL statement causes an implicit commit. |
| Oracle | Not transactional | DDL commits the current transaction before and after it runs. |
There are exceptions inside each system. PostgreSQL cannot run CREATE INDEX CONCURRENTLY or DROP INDEX CONCURRENTLY inside a transaction block. SQL Server has a few statements that are not allowed in a user transaction. Read the documentation for any unusual statement before you wrap it.
A rollback in PostgreSQL
This example shows the PostgreSQL behavior. The change is visible inside the transaction and disappears after ROLLBACK.
-- PostgreSQL
BEGIN;
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
ALTER TABLE customers DROP COLUMN phone;
ROLLBACK;Here the column is added and dropped, so the example is harmless. The point is that both statements, and any others between BEGIN and ROLLBACK, are undone together. A more realistic case is a destructive change you want to inspect before committing:
-- PostgreSQL
BEGIN;
ALTER TABLE customers DROP COLUMN email;
-- Inspect the result. This query fails if the column is gone.
SELECT id, name FROM customers LIMIT 5;
-- Decide: COMMIT; if correct, ROLLBACK; if not.
ROLLBACK;After ROLLBACK, the email column and all its data are back. This is the main benefit of transactional DDL: you can rehearse a destructive change on the real table.
What happens in MySQL
MySQL commits the current transaction when it meets most DDL statements. Running the same script there gives a different result.
-- MySQL
START TRANSACTION;
ALTER TABLE customers ADD COLUMN phone VARCHAR(30); -- implicit commit happens here
ALTER TABLE customers DROP COLUMN phone; -- implicit commit happens here
ROLLBACK; -- nothing left to roll backThe ROLLBACK has no effect on the schema. Both changes are already permanent, and ROLLBACK raises no error to warn you. Any DML you ran earlier in the same transaction was also committed by the first DDL statement.
Failure in the middle of a migration
The difference shows up when a statement fails. Suppose a migration has three steps, and step 2 fails.
-- PostgreSQL
BEGIN;
ALTER TABLE customers ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';
ALTER TABLE customers ADD CONSTRAINT uq_customers_name UNIQUE (name); -- fails if names repeat
ALTER TABLE customers ADD COLUMN notes TEXT;
COMMIT;In PostgreSQL, when step 2 fails, the transaction enters an aborted state. Every later statement is rejected with an error such as "current transaction is aborted, commands ignored until end of transaction block". Running COMMIT at that point performs a rollback. The status column from step 1 does not remain.
In MySQL, the same three statements would leave status in place. The failed UNIQUE constraint would not be applied, and the script would stop or continue depending on your client. You would then need a manual cleanup step.
Writing safe migration scripts
Use these habits so scripts behave well on any database.
- Keep each migration small. On a non-transactional database, a migration with one DDL statement cannot be left half done.
- Make steps re-runnable. Use
IF EXISTSandIF NOT EXISTSwhere your database supports them, so you can run the script again after fixing an error. For example,DROP TABLE IF EXISTS orders;. - Wrap multi-step changes in a transaction where it is supported. Put
BEGINbefore the first statement andCOMMITafter the last. - Write a reverse script. For each change, keep the statement that undoes it. Note that a dropped column's data cannot be restored by a reverse script, only by a backup.
- Test on a copy first. Run the whole migration on a restored backup or a staging database.
Transactions and locks
Transactional DDL has a cost. In PostgreSQL, ALTER TABLE takes an ACCESS EXCLUSIVE lock on the table for most operations. That lock is held until the transaction ends, not until the statement ends. This blocks every other query on the table, including plain SELECT.
This means a long transaction around DDL keeps the lock for the whole time. Do not leave a transaction open while you think about the result. Do not put slow data copies in the same transaction as a lock-taking ALTER TABLE unless you accept the downtime. The next chapters on locking and large tables cover this in more detail.
SQL Server specifics
SQL Server supports DDL in transactions, but you must start the transaction explicitly. By default it runs in autocommit mode, where each statement commits on its own.
-- SQL Server
BEGIN TRANSACTION;
ALTER TABLE customers ADD phone VARCHAR(30);
ROLLBACK TRANSACTION;Also, a runtime error does not always abort the transaction automatically. Use SET XACT_ABORT ON; at the start of the script so that any error rolls back the whole transaction.
Common errors
- Assuming
ROLLBACKworks everywhere. It does not on MySQL and Oracle. Check the table above. - Continuing after an error in PostgreSQL. After a failure, the transaction is unusable until you
ROLLBACK. Let your migration tool stop at the first error. - Mixing DML and DDL in MySQL. Earlier
INSERTorUPDATEstatements are committed by the next DDL statement. - Leaving a transaction open. In PostgreSQL, an open transaction that has run
ALTER TABLEblocks all access to that table. - Using
CONCURRENTLYoperations insideBEGIN. PostgreSQL rejects them. Run them outside a transaction block.
Exercise
You run this script on MySQL: START TRANSACTION; ALTER TABLE customers DROP COLUMN email; ROLLBACK; Is the email column still in the table, and why?
Show answer
No, the column is gone. MySQL issues an implicit commit when it executes the ALTER TABLE statement, so the drop is permanent before ROLLBACK runs. The ROLLBACK then has nothing to undo. The same script on PostgreSQL would restore the column.
Exercise
In PostgreSQL, a three-statement migration inside BEGIN ... COMMIT fails on statement 2. What is the state of the schema after the session ends the transaction, and what must you do before running more statements in the same session?
Show answer
The schema is unchanged, because statement 1 is rolled back too. Before running more statements you must end the aborted transaction with ROLLBACK (a COMMIT also results in a rollback), then start a new transaction.
Exercise
Why is it a bad idea to leave a PostgreSQL transaction open after an ALTER TABLE while you check the result for ten minutes?
Show answer
ALTER TABLE takes an ACCESS EXCLUSIVE lock on the table and holds it until the transaction ends. For ten minutes, every other query on that table, including SELECT, has to wait.