Explain it simply
ALTER TABLE in plain language
CREATE TABLE builds a new table. ALTER TABLE reshapes a table that already exists: it adds a column, removes one you no longer need, changes a column's type or name, or attaches a new rule (a constraint). The important part is that the rows inside the table stay where they are.
Think of a shop's ledger book. If you needed a phone-number column, you would not buy a new book and copy every page by hand; that is slow and invites mistakes. ALTER TABLE is like ruling one more column onto the existing pages. Every line already written stays, and the new column simply starts out blank.
Problem → Why → Solution
The problem: the table already has data
The staff app has been running for a few months and the employees table is full of real rows. HR now wants to store each person's email and to drop the city column nobody uses. The first instinct is to DROP TABLE and write CREATE TABLE again, but that throws away every employee record.
The second attempt uses ALTER TABLE to add a phone column marked NOT NULL. PostgreSQL refuses, because the three rows that already exist have no phone value to put there.
-- employees already holds 3 rows
ALTER TABLE employees
ADD COLUMN phone text NOT NULL;
-- ERROR: column "phone" of relation "employees" contains null valuesWhy this happens
When you change a table's shape, PostgreSQL checks that every existing row also satisfies the new rules. Without a default, the new column holds NULL in the old rows, and NOT NULL forbids exactly that. Every ALTER TABLE should make you ask what the statement does to the data already stored, not only to future rows.
Core concept: reshaping without losing rows
Every ALTER TABLE statement starts with ALTER TABLE table_name and is followed by one action, or several actions separated by commas. Actions add, drop, alter or rename columns, and add or drop constraints. Each action affects the existing rows differently, so it pays to know the difference.
| Action | What happens to existing rows |
|---|---|
| ADD COLUMN email text | every row gets NULL in email |
| ADD COLUMN status text DEFAULT 'active' | every row receives 'active' |
| DROP COLUMN city | the city values are gone for good |
| ALTER COLUMN price TYPE numeric USING ... | every value is converted and the table is rewritten |
| ALTER COLUMN name SET NOT NULL | the table is scanned; any NULL makes it fail |
Adding a column with a default is cheaper than it sounds. Since PostgreSQL 11, a default that is not volatile (unlike now()) is stored as metadata and filled in when old rows are read, so the table is not rewritten. Changing a type is different: every value must be converted, so the whole table is rewritten. When no automatic cast exists, as from text to numeric, a USING expression tells PostgreSQL how to convert each old value.
In PostgreSQL, DDL is transactional: you can run several ALTER TABLE statements inside BEGIN and undo all of them with ROLLBACK if something goes wrong. MySQL and Oracle commit implicitly around each DDL statement, so there is no such safety net there. The syntax also varies by database: SQL Server writes ADD email ... without the COLUMN keyword, and MySQL changes a type with MODIFY COLUMN. Whatever the database, read the documentation for the exact form before running a change against data you care about.
- Pick the column or rule to change
- Ask what happens to old rows
- Supply a default, USING or a backfill
- Run it in a transaction, then verify
Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, so on a table with millions of rows a rewriting change blocks reads and writes until it finishes.
General pattern
ALTER TABLE table_name ADD COLUMN column_name data_type [DEFAULT value];
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE table_name ALTER COLUMN column_name TYPE new_type
[USING expression];
ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT value;
ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
ALTER TABLE table_name RENAME COLUMN old_name TO new_name;
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (condition);Each statement names one table and one action. You may also combine several actions in one statement, separated by commas, so the table is locked only once.
Worked example: add email, drop city
The employees table has employee_id, full_name and city columns and three people in it. The script below adds an email column, drops city, and then reads the table's new shape back from information_schema.columns, a set of standard views that describe tables and columns.
-- Add a new column: the existing rows get NULL
ALTER TABLE employees
ADD COLUMN email varchar(255);
-- Drop a column the application no longer uses
ALTER TABLE employees
DROP COLUMN city;
-- Check the table's new shape
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'employees'
ORDER BY ordinal_position;Code breakdown
- Add a column
ADD COLUMN email varchar(255);The new column is appended to the end of the table. No default is given, so all three employees start with email = NULL until the app fills it in.
- Drop a column
DROP COLUMN city;The column and all its values are removed. If an index, view or constraint depends on it, PostgreSQL refuses unless you add CASCADE, which drops those objects too.
- Read the new shape
FROM information_schema.columnsALTER TABLE returns no rows, so this view is how you confirm the shape. In psql, typing \d employees shows the same information.
- Keep column order
ORDER BY ordinal_position;ordinal_position is the column order. In PostgreSQL a new column always goes last; there is no syntax for inserting it in the middle (unlike MySQL's AFTER).
column_name | data_type
------------+------------------
employee_id | integer
full_name | text
email | character varyingChanging a type, a default and a name
The products table stored prices as text in its early days, so it contains values such as ' 10 ' with stray spaces. USING price::numeric(10, 2) converts each row's text into a number; numeric input accepts leading and trailing spaces. If a single value such as 'abc' cannot be converted, the whole statement fails and the table stays as it was.
-- Prices were stored as text; convert them in place
ALTER TABLE products
ALTER COLUMN price TYPE numeric(10, 2) USING price::numeric(10, 2);
-- Only future INSERTs use the new default
ALTER TABLE products
ALTER COLUMN stock SET DEFAULT 0;
-- Renaming touches the catalog, not the data
ALTER TABLE products RENAME COLUMN name TO product_name;
SELECT id, product_name, price FROM products ORDER BY id;The query returns (1, Green tea, 2.50), (2, Jasmine rice, 10.00) and (3, Old mug, 3.00). SET DEFAULT does not touch stock in existing rows; it only affects later INSERTs that leave stock out. RENAME COLUMN is instant, but it breaks every piece of application code that still uses the old name.
To try PostgreSQL's transactional DDL, the block below adds one column and drops another, then undoes both with ROLLBACK. The final SELECT lists only id, name, price, stock and discontinued; there is no sku.
BEGIN;
ALTER TABLE products ADD COLUMN sku text;
ALTER TABLE products DROP COLUMN stock;
ROLLBACK; -- both changes are undone
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'products'
ORDER BY ordinal_position;In real projects
ALTER TABLE in real projects
Real teams rarely type ALTER TABLE into a production database by hand. The statements live in migration files managed by tools such as Flyway, Liquibase, Rails or Django migrations, or Prisma Migrate; they are stored in git, tried on a staging copy first, and only then deployed. That way every change to the schema can be reviewed like code.
- Expand-contract: never drop an old column straight away. Add the new column, deploy an app that writes both, backfill the data, and drop the old column in a later release.
- On big tables, SET lock_timeout = '5s' first, so the ALTER TABLE gives up instead of queueing behind a long query and blocking everything that arrives after it.
- Add CHECK and foreign-key constraints with NOT VALID, then run VALIDATE CONSTRAINT separately: new rows are checked at once and old rows are checked later under a lighter lock.
Common mistakes
Common ALTER TABLE mistakes
Adding a NOT NULL column without a default to a filled table
The statement fails because the old rows have no value. If a sensible default exists, use ADD COLUMN ... NOT NULL DEFAULT .... If not, add the column as nullable, backfill it with UPDATE, and only then run SET NOT NULL.
Dropping a column the app still reads
Schema changes and app deploys do not happen at the same instant. If old servers still run SELECT city ..., they start failing with column does not exist the moment the column disappears. Deploy code that stops using the column first, then drop it.
Retyping a column without checking the data first
USING price::numeric fails on a single value such as 'N/A', and on a large table it may hold its lock for a long time before failing. Find the rows that cannot convert with a SELECT first, and clean them up.
Best practices
Best practices
- Write every schema change as a migration file and try it on staging first.
- In PostgreSQL, wrap related ALTER TABLE statements in BEGIN ... COMMIT so a failure undoes all of them.
- Confirm a backup exists before dropping or retyping a column.
- Name constraints, as in CONSTRAINT price_positive CHECK (...), so they are easy to drop later.
Mini challenge
Mini challenge: migrate the products table
The products table has id, name, price (text), stock and discontinued columns and three rows. Modernise its shape inside one transaction, then check the result through information_schema.
- Start with BEGIN and finish with COMMIT
- Add a sku varchar(20) column
- Convert price to numeric(10, 2) with USING
- Add in_stock boolean NOT NULL DEFAULT true and drop the discontinued column
- List column_name, data_type and is_nullable in ordinal_position order
BEGIN;
-- TODO: add a sku column (varchar, 20 characters)
-- TODO: change price from text to numeric(10, 2);
-- PostgreSQL needs to be told how to convert the old values
-- TODO: add in_stock (boolean, required, true for every existing row)
-- TODO: drop the discontinued column
COMMIT;
-- TODO: query information_schema.columns for the products tableExpected: Six columns are listed in this order: id (integer, NO), name (text, NO), price (numeric, YES), stock (integer, YES), sku (character varying, YES), in_stock (boolean, NO).
Show hint
A NOT NULL column added to a table with rows needs a DEFAULT. Text does not cast to numeric automatically, so the type change needs USING price::numeric(10, 2).
Show solution
BEGIN;
ALTER TABLE products
ADD COLUMN sku varchar(20);
ALTER TABLE products
ALTER COLUMN price TYPE numeric(10, 2) USING price::numeric(10, 2);
ALTER TABLE products
ADD COLUMN in_stock boolean NOT NULL DEFAULT true;
ALTER TABLE products
DROP COLUMN discontinued;
COMMIT;
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'products'
ORDER BY ordinal_position;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- ALTER TABLE reshapes a table without deleting its data: ADD, DROP, ALTER and RENAME COLUMN, plus ADD CONSTRAINT.
- A new column without a default is NULL in old rows; NOT NULL needs a default or a backfill first.
- A type change without an automatic cast needs USING, and it rewrites the whole table under a lock.
- PostgreSQL can roll back ALTER TABLE; MySQL and Oracle cannot.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group