ALTER TABLE
Schemas evolve. ALTER TABLE lets you change an existing table's structure — add or remove columns, change a column's type, rename things, and add or drop constraints — without dropping and recreating the table (and losing its data) from scratch.
Adding a column
ADD COLUMN
ALTER TABLE users ADD COLUMN phone_number VARCHAR(20); -- With a default applied to existing rows ALTER TABLE users ADD COLUMN is_verified BOOLEAN NOT NULL DEFAULT FALSE;
Dropping a column
DROP COLUMN
ALTER TABLE users DROP COLUMN phone_number;
Changing a column's type
The syntax for changing a column's type differs by dialect. PostgreSQL uses ALTER COLUMN ... TYPE; MySQL uses MODIFY COLUMN.
Changing a column type (PostgreSQL)
ALTER TABLE users ALTER COLUMN phone_number TYPE VARCHAR(30);
Changing a column type (MySQL)
ALTER TABLE users MODIFY COLUMN phone_number VARCHAR(30);
Renaming a column or table
Renaming
-- Rename a column ALTER TABLE users RENAME COLUMN full_name TO display_name; -- Rename the table itself ALTER TABLE users RENAME TO app_users;
Adding and dropping constraints
Constraints via ALTER TABLE
-- Add a NOT NULL constraint retroactively ALTER TABLE users ALTER COLUMN display_name SET NOT NULL; -- Add a named CHECK constraint ALTER TABLE users ADD CONSTRAINT age_non_negative CHECK (age >= 0); -- Drop a named constraint ALTER TABLE users DROP CONSTRAINT age_non_negative;
ALTER TABLE on large production tables
Adding a nullable column (or one with a constant default in modern PostgreSQL/MySQL) is usually fast even on large tables.
Adding a
NOT NULLcolumn without a default, or one that requires computing a value per row, is typically the slowest and most locking-prone change.Always test structural changes against a copy of production-scale data before running them on the real thing.
Keep a rollback plan (a script that reverses the change) ready for any non-trivial
ALTER TABLEin a live system.