Sub topic 17
Planning safe, reversible schema changes
This chapter assumes you know the basic ALTER TABLE forms (add, drop, retype and rename columns, add and drop constraints), DROP TABLE with IF EXISTS, and the difference between CASCADE and RESTRICT. The examples use PostgreSQL. Where other databases behave differently, the text says so.
Why schema changes need a plan
A data change made with UPDATE or DELETE can often be undone from a backup or a transaction. A schema change is harder to undo for three reasons:
DROP COLUMNandDROP TABLEdestroy data. Recreating the column or table brings back the structure but not the rows.- Application code that is already running may expect the old structure. A renamed column breaks every query that still uses the old name.
- Many
ALTER TABLEforms take a lock on the table. On a large, busy table, that lock can block every other query.
Planning means deciding, before you run anything, how you will detect a problem and how you will go back.
Expand and contract
The safest pattern splits one risky change into small steps. Each step works with both the old and the new application code.
- Expand: add the new column or table. Nothing reads it yet.
- Migrate: copy or backfill the data, and deploy code that writes to both the old and new structure.
- Switch: deploy code that reads from the new structure.
- Contract: after a waiting period, drop the old structure.
Only the last step is destructive, and by then you have had time to notice problems.
Before you change anything
Take a backup of anything you might drop. For a single table, a copy is a quick safety net:
CREATE TABLE customers_backup AS SELECT * FROM customers;A copy made this way keeps the data but not indexes, constraints or defaults. A full database dump from your database's own tool is the stronger backup. Use the copy for fast, local recovery.
Then list what depends on the table. In PostgreSQL, this query finds foreign keys that point at customers:
SELECT conrelid::regclass AS referencing_table, conname AS constraint_name
FROM pg_constraint
WHERE confrelid = 'customers'::regclass
AND contype = 'f';This one finds views that use it:
SELECT table_schema, view_name
FROM information_schema.view_table_usage
WHERE table_name = 'customers';If either query returns rows, a plain DROP TABLE will be refused, and CASCADE would remove those objects. Decide deliberately. Prefer RESTRICT, which is the default, and remove each dependent object yourself so you see exactly what goes.
Use a transaction where the database supports it
PostgreSQL and SQL Server can roll back most DDL (schema-changing statements) inside a transaction. MySQL commits implicitly around each DDL statement, so a rollback does nothing. Oracle also commits implicitly. SQLite supports transactional DDL.
In PostgreSQL, wrap related changes together and check the result before you commit:
BEGIN;
ALTER TABLE customers RENAME COLUMN name TO full_name;
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
-- Inspect the result before committing
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'customers'
ORDER BY ordinal_position;
COMMIT; -- or ROLLBACK; if anything looks wrongIf any statement in the block fails, PostgreSQL marks the transaction as aborted. You must issue ROLLBACK, and nothing from the block is applied.
On MySQL, assume each statement is permanent. Split the work into small scripts, and write the undo statement for each one in advance.
Mind the locks
Most ALTER TABLE forms need an exclusive lock for at least a moment. The statement waits for running queries to finish. While it waits, new queries line up behind it. A quick change can therefore stall the whole table if one long query is already running.
In PostgreSQL, set a lock timeout so that the change gives up instead of queueing:
BEGIN;
SET LOCAL lock_timeout = '3s';
ALTER TABLE customers ADD COLUMN loyalty_points INTEGER;
COMMIT;If the lock is not available within three seconds, the statement fails and you can retry at a quieter time.
How long the lock is held depends on the operation:
| Operation | Typical cost on a large table |
|---|---|
| Add a nullable column with no default | Very fast, a metadata change |
| Add a column with a constant default | Fast in PostgreSQL 11 and later and in recent MySQL versions. Older versions rewrite the table. |
| Change a column's type | Often rewrites the whole table while holding a strong lock |
| Add a `NOT NULL` rule | Scans the table to check every row |
| Add a foreign key | Scans the table to check every row |
| Drop a column | Usually fast. PostgreSQL only marks the column as dropped. |
Check your database's documentation for the exact version you run. These costs changed between releases.
Adding NOT NULL in steps
Instead of adding a NOT NULL column with a default in one step on an old or very large table, you can split the change:
ALTER TABLE customers ADD COLUMN status VARCHAR(20);
-- Run this repeatedly until it updates 0 rows
UPDATE customers
SET status = 'active'
WHERE id IN (
SELECT id FROM customers WHERE status IS NULL LIMIT 1000
);
ALTER TABLE customers ALTER COLUMN status SET DEFAULT 'active';
ALTER TABLE customers ALTER COLUMN status SET NOT NULL;Small batches keep each transaction short, so locks are released quickly. The final SET NOT NULL still scans the table once.
PostgreSQL can also add a foreign key without blocking writes for the whole scan. It adds the constraint first without checking existing rows, then validates it separately:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;NOT VALID is PostgreSQL syntax. Other databases have their own equivalents or none.
Make destructive steps reversible
Instead of dropping a table, rename it first. Applications that still use it fail loudly, and you can undo the change in one statement:
ALTER TABLE orders RENAME TO orders_retired_20261127;
-- Undo, if something breaks:
-- ALTER TABLE orders_retired_20261127 RENAME TO orders;After a waiting period with no errors, drop it for good:
DROP TABLE IF EXISTS orders_retired_20261127;Do the same for columns. Rename email to email_retired, wait, then run ALTER TABLE customers DROP COLUMN email_retired;. A date in the new name tells the next person when it is safe to drop.
Write the way back
For each change, keep a pair of scripts: one that applies it and one that reverses it. Note what each reversal cannot restore.
| Change | Reverse | What is lost |
|---|---|---|
| `ADD COLUMN` | `DROP COLUMN` | Any data written to the new column |
| `RENAME COLUMN a TO b` | `RENAME COLUMN b TO a` | Nothing |
| `ADD CONSTRAINT` | `DROP CONSTRAINT` | Nothing |
| Widen `VARCHAR(100)` to `VARCHAR(200)` | Narrow it again | Fails if any value is now longer than 100 |
| `DROP COLUMN` or `DROP TABLE` | Recreate the structure | All the data, unless you restore it from a backup |
The last row is the reason for the backup and the rename-first habit. A reversing script for a drop is only useful when it also reloads the saved data.
Checklist
- Backup taken, and you have confirmed you can read it.
- Dependencies listed: foreign keys, views, and application code.
- Script tested on a copy of production-sized data.
- Transaction used where the database supports transactional DDL.
- Lock timeout set, and the change scheduled for a quiet period.
- Destructive step delayed until the new structure has been in use.
- Reverse script written, with its limits noted.
Exercise
You need to replace the column customers.email with a new column customers.contact_email on a large, busy PostgreSQL table. Give the order of steps and say which step is the only one that cannot be undone from the script alone.
Show answer
1) Back up the table and check dependencies such as views and application queries that use email. 2) Expand: ALTER TABLE customers ADD COLUMN contact_email VARCHAR(255); 3) Backfill contact_email from email in small batches, and deploy code that writes to both columns. 4) Switch reads to contact_email. 5) Rename email to email_retired and wait while you watch for errors. 6) Contract: ALTER TABLE customers DROP COLUMN email_retired;. The final drop is the only step that cannot be undone from the script alone, because it destroys the data. Only the backup can restore it.
Exercise
A colleague runs ALTER TABLE customers ADD COLUMN phone VARCHAR(30); followed by a failing statement inside BEGIN; ... COMMIT;. What is the state of customers after ROLLBACK on PostgreSQL, and what would it be on MySQL?
Show answer
On PostgreSQL the phone column does not exist, because the DDL was part of the transaction and is rolled back. On MySQL the ALTER TABLE committed implicitly when it ran, so phone stays and a ROLLBACK does not remove it.