ALTER TABLE ... ADD COLUMN adds a new field to an existing PostgreSQL table without recreating the table.
The command appends a new column definition to an existing table. PostgreSQL rewrites metadata, optionally back-fills default values, and preserves all existing data.
See the syntax section below. Square brackets denote optional keywords.
Run ALTER TABLE users ADD COLUMN bio text;
.Because no NOT NULL
or DEFAULT
is provided, the column starts as NULL for all rows.
Step 1: ALTER TABLE users ADD COLUMN is_active boolean DEFAULT true;
(back-fills value). Step 2: ALTER TABLE users ALTER COLUMN is_active SET NOT NULL;
. Splitting prevents table rewrites on large tables pre-PostgreSQL 11.
Yes.Separate definitions with commas: ALTER TABLE sales ADD COLUMN region text, ADD COLUMN created_at timestamptz DEFAULT now();
In PostgreSQL 12+, adding a NULLABLE column with no default is almost instant, requiring only a brief ACCESS EXCLUSIVE lock on metadata.Adding a column with a default before v11 rewrites the table, causing longer locks.
1) Add the column nullable; 2) back-fill in batches; 3) add constraints after data is populated; 4) use SET NOT NULL
later.Consider pg_backfill
or logical replication for very large tables.
• Store last login time
• Flag soft-deleted rows
• Track JSON configuration
If the new value is derived from other columns, declare GENERATED ALWAYS AS (expression) STORED
instead of triggers.
Use ALTER TABLE table_name DROP COLUMN column_name;
. Verify no views or functions depend on it.
.
Only briefly. A metadata lock is taken, but simple nullable columns are added almost instantly. Long locks occur only during table rewrites.
No. PostgreSQL always appends the column at the end. Use a view to reorder columns for client queries.
Execute the command on the partitioned table. PostgreSQL automatically propagates the new column to all child partitions.