PostgreSQL Alter Table

ALTER TABLE changes the structure of an existing table - adding, removing, or renaming columns - without you having to drop and recreate it.

The ALTER TABLE Statement

ALTER TABLE modifies a table's definition rather than its data. With it you can add a new column, drop a column you no longer need, rename a column or the table itself, or change a column's data type. The general form is ALTER TABLE table_name followed by one or more actions, such as ADD COLUMN, DROP COLUMN, or RENAME COLUMN.

Add a new column

ALTER TABLE employees
ADD COLUMN phone VARCHAR(20);

New columns often need a default value and a NOT NULL constraint so existing rows aren't left blank. PostgreSQL fills in the default for every existing row as part of the same statement, and any future INSERT that omits the column uses that default automatically.

Add a column with a default and constraint

ALTER TABLE employees
ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
Note: Since PostgreSQL 11, adding a column with a constant DEFAULT is a fast, metadata-only operation - it no longer rewrites every row in the table, even on tables with millions of rows.

Dropping and Renaming Columns

DROP COLUMN removes a column and all of its data permanently. RENAME COLUMN changes a column's name without touching its data or type, which is useful when a name no longer reflects what it stores. You can also rename the entire table with ALTER TABLE ... RENAME TO.

Drop one column and rename another

ALTER TABLE employees
DROP COLUMN phone;

ALTER TABLE employees
RENAME COLUMN department TO dept_name;
Note: DROP COLUMN deletes the column's data immediately and cannot be undone outside a transaction. Any view, function, or application query that still references the dropped column will break, so search for dependencies before running it.
  • ADD COLUMN name TYPE - add a new column, optionally with DEFAULT and NOT NULL.
  • DROP COLUMN name - permanently remove a column and its data.
  • RENAME COLUMN old TO new - rename a column without affecting its data.
  • RENAME TO new_name - rename the table itself.
  • ALTER COLUMN name TYPE new_type - change a column's data type.
ActionSyntaxNotes
Add a columnADD COLUMN name TYPEFails if the column already exists unless you use IF NOT EXISTS.
Drop a columnDROP COLUMN nameIrreversible outside a transaction; use IF EXISTS to avoid an error on a missing column.
Rename a columnRENAME COLUMN old TO newData and type are unchanged; only the name changes.
Change a column typeALTER COLUMN name TYPE new_typeMay require a USING expression to convert existing values.

Exercise: PostgreSQL Alter Table

What must you typically provide when adding a NOT NULL column to a table with existing rows?