Modifying Table Structure

1. Adding Column

ALTER TABLE customers ADD COLUMN phone text;
ALTER TABLE customers ADD COLUMN status text NOT NULL DEFAULT 'active';
VariantNotes
Without DEFAULTInstant metadata-only
DEFAULT constantInstant since PG 11 (no rewrite)
DEFAULT volatileFull table rewrite
NOT NULL + DEFAULTSafe, 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;
ModeEffect
RESTRICTDefault; error if dependents exist
CASCADEDrop views/constraints referencing it

4. Renaming Column

ALTER TABLE customers RENAME COLUMN email_address TO email;
ImpactDetail
LocksBrief ACCESS EXCLUSIVE
Views/FuncsRename 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;
AspectDetail
USINGRequired when cast not implicit
RewriteTriggered unless types are binary-compatible
LockACCESS 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;
BehaviorNotes
Existing rowsUnaffected
Future insertsMust 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;
ValueMeaning
-1Use default_statistics_target
100Default
1000-10000For 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;
ModeEffect
PLAINNo TOAST/compression (fixed-width only)
EXTENDEDCompress + TOAST (default)
EXTERNALTOAST without compression
MAINCompress inline first
COMPRESSION lz4/pglzAlgorithm PG 14+