ALTER TABLE (Alter Table)
Last updated: 2026-11-04
ALTER TABLE (Alter Table)
ALTER TABLE changes the shape of an existing table: adding or dropping columns, changing column types, adding or dropping constraints, renaming, and setting table-level options. It is the workhorse of DDL. Since PostgreSQL 11, adding a column with a DEFAULT is a pure metadata operation that does not rewrite the table.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
ALTER TABLE <table>
ADD [COLUMN] <column> <data type> [DEFAULT <expression>],
ALTER [COLUMN] <column> [SET DATA] TYPE <new type> [USING <expression>],
ADD CONSTRAINT <name> <constraint definition> [NOT VALID],
DROP CONSTRAINT [IF EXISTS] <name>,
DROP [COLUMN] [IF EXISTS] <column> [CASCADE | RESTRICT],
RENAME TO <new name>;
⚙️ Parameters
| ADD COLUMN | Adds a column |
|---|---|
| ALTER COLUMN ... TYPE | Changes a column's data type |
| ADD CONSTRAINT | Adds a table-level constraint |
| DROP CONSTRAINT | Drops a table-level constraint |
| DROP COLUMN | Drops a column and its data |
| RENAME TO | Renames the table |
Returns:No return value. Once the statement succeeds the change is live in the system catalogs.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
CREATE TABLE
INSERT 0 2
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
id | name | age | email
---+-------+-----+------
1 | Alice | 30 | NULL
2 | Bob | 25 | NULL
📌 Key Points
- On PostgreSQL 11+, ADD COLUMN ... DEFAULT is a metadata-only change (the table's relfilenode is unchanged) — no rewrite.
- ALTER COLUMN ... TYPE normally rewrites the whole table under an ACCESS EXCLUSIVE lock; size the impact on large tables first.
- ADD CONSTRAINT ... NOT VALID adds the constraint without scanning existing rows; run VALIDATE CONSTRAINT afterwards.
- DROP COLUMN discards the column's data along with the column; a committed drop cannot be undone.
- ALTER TABLE is transactional: a failure rolls the whole statement back, leaving no half-changed table.
- When the new type cannot be converted automatically, supply an explicit USING expression.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QDoes changing a column type lock the table?
AYes. ALTER COLUMN ... TYPE takes an ACCESS EXCLUSIVE lock and rewrites the table, blocking reads and writes. On a large production table, add a new column, backfill it, and swap names instead.
QHow do I rename a table or a column?
AUse ALTER TABLE t RENAME TO t2; and ALTER TABLE t RENAME COLUMN a TO b; — both are metadata-only and fast.