Modifying Table Structure
1. Adding Column
ALTER TABLE customers ADD COLUMN phone text;
ALTER TABLE customers ADD COLUMN status text NOT NULL DEFAULT 'active';
| Variant | Notes |
| Without DEFAULT | Instant metadata-only |
| DEFAULT constant | Instant since PG 11 (no rewrite) |
| DEFAULT volatile | Full table rewrite |
| NOT NULL + DEFAULT | Safe, instant |
2. Adding Multiple Columns
ALTER TABLE customers
ADD COLUMN phone text,
ADD COLUMN dob date,
ADD COLUMN notes text;
Note: Combine ALTER actions in one statement to avoid multiple table locks/rewrites.
3. Dropping Column
ALTER TABLE customers DROP COLUMN obsolete_field;
ALTER TABLE customers DROP COLUMN IF EXISTS obsolete_field CASCADE;
| Mode | Effect |
| RESTRICT | Default; error if dependents exist |
| CASCADE | Drop views/constraints referencing it |
4. Renaming Column
ALTER TABLE customers RENAME COLUMN email_address TO email;
| Impact | Detail |
| Locks | Brief ACCESS EXCLUSIVE |
| Views/Funcs | Rename automatically updates dependents only if defined by column ref |
5. Changing Column Type
ALTER TABLE orders ALTER COLUMN total_cents TYPE bigint;
ALTER TABLE customers ALTER COLUMN email TYPE citext USING email::citext;
| Aspect | Detail |
| USING | Required when cast not implicit |
| Rewrite | Triggered unless types are binary-compatible |
| Lock | ACCESS EXCLUSIVE for duration |
6. Setting Column Default
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'new';
7. Dropping Column Default
ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;
| Behavior | Notes |
| Existing rows | Unaffected |
| Future inserts | Must supply value or column allows NULL |
8. Setting Column NOT NULL
-- Backfill first to avoid violation
UPDATE customers SET phone = '' WHERE phone IS NULL;
ALTER TABLE customers ALTER COLUMN phone SET NOT NULL;
Warning: Adding NOT NULL scans the whole table; on large tables, validate via CHECK constraint with NOT VALID first.
9. Dropping NOT NULL Constraint
ALTER TABLE customers ALTER COLUMN phone DROP NOT NULL;
10. Setting Column Statistics Target
ALTER TABLE events ALTER COLUMN user_id SET STATISTICS 1000;
ANALYZE events;
| Value | Meaning |
| -1 | Use default_statistics_target |
| 100 | Default |
| 1000-10000 | For high-cardinality / skewed columns |
11. Setting Column Storage
ALTER TABLE docs ALTER COLUMN body SET STORAGE EXTERNAL;
ALTER TABLE docs ALTER COLUMN body SET COMPRESSION lz4;
| Mode | Effect |
| PLAIN | No TOAST/compression (fixed-width only) |
| EXTENDED | Compress + TOAST (default) |
| EXTERNAL | TOAST without compression |
| MAIN | Compress inline first |
| COMPRESSION lz4/pglz | Algorithm PG 14+ |