ALTER TABLE — Evolving Schema in SQL
Add columns safely, change types carefully
ALTER TABLE changes structure after creation: ADD COLUMN (with DEFAULT so old rows stay valid), DROP COLUMN, ALTER COLUMN TYPE (may rewrite the table), RENAME, ADD/DROP CONSTRAINT. Big-table alters can lock — production prefers online variants, backfill in batches, and testing on a copy first.
ADD with DEFAULT
New column arrives populated for old rows — no NULL surprise.
Backfill then constrain
NOT NULL on a full table: add nullable → batch-fill → SET NOT NULL.
TYPE changes rewrite
Widening types can rewrite every row — off-peak + copy-tested.
Constraints validate history
ADD CHECK/UNIQUE scans old rows first. PG low-lock: NOT VALID then VALIDATE.
1ALTER TABLE employees ADD COLUMN bonus NUMERIC(12,2) DEFAULT 0;2ALTER TABLE employees ALTER COLUMN salary TYPE NUMERIC(14,2);
| id | name | salary | bonus |
|---|---|---|---|
| 1 | Alice | 85000 | 5000 |
| 2 | Bob | 52000 | 0 |
Bonus arrives defaulted to 0 for existing rows (no NULL surprise). The type widening from (10,2) to (14,2) rewrites the column to hold larger payrolls.
Safe column add
Old rows stay valid because the default fills them.
1ALTER TABLE employees ADD COLUMN bonus NUMERIC(12,2) DEFAULT 0;
| id | name | bonus |
|---|---|---|
| 1 | Alice | 5000 |
| 2 | Bob | 0 |
NOT NULL on dirty table
Three-step dance avoids the failed ALTER.
1-- 1. add nullable2ALTER TABLE employees ADD COLUMN band TEXT;3-- 2. backfill in batches4UPDATE employees SET band = 'junior' WHERE band IS NULL;5-- 3. constrain6ALTER TABLE employees ALTER COLUMN band SET NOT NULL;
| pattern | detail |
|---|---|
| step | nullable → fill → constrain |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.