Part 10 / Topic 6 of 9
ALTER TABLE: evolving a live table
Schemas live for years; requirements don't hold still. ALTER TABLE is how structure changes in place — columns, constraints, names:
ALTER TABLE books ADD COLUMN pages integer CHECK (pages > 0);
ALTER TABLE books RENAME COLUMN added_on TO catalogued_on;
ALTER TABLE books ALTER COLUMN title SET NOT NULL;
ALTER TABLE
ALTER TABLE
ALTER TABLE
Adding a constraint to a table with existing rows validates them first — and refuses if any row breaks the new rule:
ALTER TABLE products ADD CONSTRAINT products_stock_sane CHECK (stock <= 150);
ERROR: check constraint "products_stock_sane" of relation "products" is violated by some row
The USB-C Cable (stock 200) vetoed the rule — the constraint is rejected whole, because a constraint that current data violates would be a lie. Clean the data first, or write a rule that's actually true:
ALTER TABLE products ADD CONSTRAINT products_stock_sane CHECK (stock <= 500);
ALTER TABLE products DROP CONSTRAINT products_stock_sane;
ALTER TABLE
ALTER TABLE
(That add-then-drop is the full lifecycle: constraints are managed objects, addressable by name.) One operational note for later: most ALTERs are quick metadata changes, but some — changing a column's type, adding NOT NULL to a huge table — rewrite or scan everything, holding locks while they do. Stage 4 gives you the tools to know which is which before you run it in production.
🧪 Quick quiz — answer from memory, then check.
- What happens when you ADD a CHECK that existing rows violate?
- How do you remove a constraint?
Show the answers
- The ALTER fails and the constraint is not added — existing data must satisfy a new rule.
ALTER TABLE t DROP CONSTRAINT name— which is why names matter.
Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.