Changing Tables: ALTER TABLE, DROP and Foreign Key Actions
How to change existing tables safely: adding, renaming and dropping columns, changing types with USING, adding constraints to existing data with NOT VALID and VALIDATE, foreign key actions such as CASCADE and SET NULL, DROP and CASCADE, transactional DDL, and migrations on live databases.
kvi5hnuCode Sprout team member10 min readOn this page
Tables change throughout an application's life: new features need new columns, rules tighten into constraints, types turn out to be wrong, old tables are retired. ALTER TABLE makes those changes in place, without recreating the table or losing its data. DROP removes objects. Both affect data that already exists and applications that are running, so they need more care than creating new tables.
This article covers the common changes, foreign key actions that decide what happens to child rows when a parent row is deleted, and how to change tables on a live database. The examples change the shop's tables, each on a fresh copy.
Adding, renaming and changing columns
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Adding, renaming and changing columns
ALTER TABLE customers ADD COLUMN email VARCHAR(254);
ALTER TABLE customers ADD COLUMN marketing_ok BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE customers RENAME COLUMN city TO home_city;
ALTER TABLE customers ALTER COLUMN home_city SET DEFAULT 'Unknown';
INSERT INTO customers (customer_id, name) VALUES (7, 'Gita Bose');
SELECT customer_id, name, home_city, email, marketing_ok
FROM customers
WHERE customer_id IN (1, 6, 7)
ORDER BY customer_id;
customer_id | name | home_city | email | marketing_ok
-------------+--------------+-----------+--------+--------------
1 | Asha Rao | Pune | (null) | f
6 | Farah Haddad | (null) | (null) | f
7 | Gita Bose | Unknown | (null) | f
(3 rows)
The basic column operations:
| Change | Statement |
|---|---|
| add a column | ALTER TABLE t ADD COLUMN c type [DEFAULT ...] [NOT NULL] |
| drop a column | ALTER TABLE t DROP COLUMN c |
| rename a column | ALTER TABLE t RENAME COLUMN old TO new |
| rename a table | ALTER TABLE t RENAME TO new_name |
| set or drop a default | ALTER TABLE t ALTER COLUMN c SET DEFAULT ... / DROP DEFAULT |
| add or remove NOT NULL | ALTER TABLE t ALTER COLUMN c SET NOT NULL / DROP NOT NULL |
| change the type | ALTER TABLE t ALTER COLUMN c TYPE new_type [USING expr] |
Things to notice in the example:
- A new column is NULL in every existing row, unless it has a
DEFAULT.emailis NULL for everyone. - A new
NOT NULLcolumn needs aDEFAULT, which fills the existing rows: everyone hasmarketing_ok = false. Without a default, adding aNOT NULLcolumn to a table with rows fails. Since PostgreSQL 11, adding a column with a constant default is instant, even on huge tables: the default is stored once and the rows aren't rewritten. - Renaming
citytohome_citykeeps the data. Views that use the column are updated automatically in PostgreSQL, but functions written in PL/pgSQL (stored as source text) and application code aren't, so renames break running applications. - A new default applies only to future inserts: Gita gets
'Unknown', while Farah's existing NULL stays.
Syntax varies between databases. MySQL uses MODIFY COLUMN, CHANGE COLUMN and (since 8.0) RENAME COLUMN, SQL Server uses ALTER COLUMN for types and the sp_rename procedure for renames, and Oracle uses MODIFY. SQLite supports only renaming, adding and dropping columns: other changes need the table recreated.
Changing a column's type
\pset null '(null)'
-- Changing a column's type: the existing values must convert
CREATE TABLE imports (sku TEXT, qty TEXT);
INSERT INTO imports VALUES ('TEN-0001', '12'), ('TEN-0002', ' 3'), ('LGT-0003', 'n/a');
-- Fails: 'n/a' isn't an integer, and nothing is changed
ALTER TABLE imports ALTER COLUMN qty TYPE INTEGER USING CAST(trim(qty) AS INTEGER);
-- Clean the data first, then convert; USING says how to compute the new values
UPDATE imports SET qty = NULL WHERE trim(qty) !~ '^\d+$';
ALTER TABLE imports ALTER COLUMN qty TYPE INTEGER USING CAST(trim(qty) AS INTEGER);
SELECT sku, qty, pg_typeof(qty) AS type FROM imports ORDER BY sku;
psql:/workspace/solution.sql:8: ERROR: invalid input syntax for type integer: "n/a"
sku | qty | type
----------+--------+---------
LGT-0003 | (null) | integer
TEN-0001 | 12 | integer
TEN-0002 | 3 | integer
(3 rows)
Changing a type converts every existing value. When there's no automatic conversion, as from text to integer, USING gives the expression that computes the new value from the old one. If any value can't be converted, the whole statement fails and nothing changes: 'n/a' isn't a number. The fix is to clean the data first, here by setting non-numeric quantities to NULL, then convert.
Type changes usually rewrite the whole table and hold a lock that blocks reads and writes while they run. Some changes are cheap, such as increasing a VARCHAR length or changing VARCHAR(n) to TEXT in PostgreSQL, but most aren't.
Adding constraints to existing data
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Adding a constraint checks the existing rows: one product has stock 0
ALTER TABLE products ADD CONSTRAINT products_stock_positive_ck CHECK (stock > 0);
-- NOT VALID: enforce the rule for new and changed rows now, check old rows later
ALTER TABLE products ADD CONSTRAINT products_price_ck CHECK (price >= 20) NOT VALID;
INSERT INTO products VALUES (8, 'Tent peg', 'tents', 'Alpina', 2.50, 100, 10);
-- Fix the old rows that break the rule, then validate
SELECT name, price FROM products WHERE price < 20;
UPDATE products SET price = 20.00 WHERE product_id = 7;
ALTER TABLE products VALIDATE CONSTRAINT products_price_ck;
SELECT conname, convalidated FROM pg_constraint WHERE conname = 'products_price_ck';
psql:/workspace/solution.sql:63: ERROR: check constraint "products_stock_positive_ck" of relation "products" is violated by some row
psql:/workspace/solution.sql:67: ERROR: new row for relation "products" violates check constraint "products_price_ck"
DETAIL: Failing row contains (8, Tent peg, tents, Alpina, 2.50, 100, 10).
name | price
--------------+-------
Merino socks | 16.00
(1 row)
conname | convalidated
-------------------+--------------
products_price_ck | t
(1 row)
Adding a constraint checks every existing row: stock > 0 fails because the Day 18 backpack has stock 0. Either fix the data first, or adjust the rule.
On large tables, checking every row takes time while the table is locked. PostgreSQL's NOT VALID option splits the work:
ADD CONSTRAINT ... NOT VALIDadds the constraint without checking existing rows. From that moment, new and updated rows must satisfy it: the 2.50 tent peg is rejected.- Find and fix the existing rows that break it, such as the socks priced under 20.
VALIDATE CONSTRAINTchecks the existing rows, with a much lighter lock that doesn't block normal reads and writes.
NOT VALID works for CHECK and foreign key constraints, and PostgreSQL 18 extended it to NOT NULL. SQL Server's WITH NOCHECK is similar, but leaves the constraint marked as untrusted until it's re-checked. To add a UNIQUE constraint without a long lock, create the unique index with CREATE UNIQUE INDEX CONCURRENTLY first, then add the constraint USING INDEX (article 55).
Foreign key actions
When a row is deleted, or its key updated, rows in other tables may still refer to it. The foreign key's referential action decides what happens:

\pset null '(null)'
-- What happens to child rows when a parent row is deleted? The foreign key's action decides
CREATE TABLE authors (author_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE guides (
guide_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author_id INTEGER REFERENCES authors (author_id) ON DELETE SET NULL
);
CREATE TABLE chapters (
guide_id INTEGER REFERENCES guides (guide_id) ON DELETE CASCADE,
chapter INTEGER,
heading TEXT NOT NULL,
PRIMARY KEY (guide_id, chapter)
);
CREATE TABLE guide_sales (
sale_id INTEGER PRIMARY KEY,
guide_id INTEGER NOT NULL REFERENCES guides (guide_id) ON DELETE RESTRICT
);
INSERT INTO authors VALUES (1, 'Kofi Mensah'), (2, 'Lena Fischer');
INSERT INTO guides VALUES (10, 'Pitching a tent', 1), (11, 'Packing light', 2);
INSERT INTO chapters VALUES (10, 1, 'Choosing a site'), (10, 2, 'Guy lines'), (11, 1, 'The base weight');
INSERT INTO guide_sales VALUES (500, 11);
-- SET NULL: the guide stays, without an author
DELETE FROM authors WHERE author_id = 1;
SELECT guide_id, title, author_id FROM guides ORDER BY guide_id;
-- CASCADE: deleting a guide deletes its chapters too
DELETE FROM guides WHERE guide_id = 10;
SELECT guide_id, chapter, heading FROM chapters ORDER BY guide_id, chapter;
-- RESTRICT: a guide with sales can't be deleted
DELETE FROM guides WHERE guide_id = 11;
guide_id | title | author_id
----------+-----------------+-----------
10 | Pitching a tent | (null)
11 | Packing light | 2
(2 rows)
guide_id | chapter | heading
----------+---------+-----------------
11 | 1 | The base weight
(1 row)
psql:/workspace/solution.sql:34: ERROR: update or delete on table "guides" violates foreign key constraint "guide_sales_guide_id_fkey" on table "guide_sales"
DETAIL: Key (guide_id)=(11) is still referenced from table "guide_sales".
ON DELETE SET NULL: deleting author 1 keeps the guide, without an author. Use it when the child makes sense on its own.ON DELETE CASCADE: deleting guide 10 deletes its chapters too. Use it for rows that are part of the parent and meaningless without it: order lines, chapters, an invoice's items.ON DELETE RESTRICT(andNO ACTION, the default): deleting guide 11 fails, because a sale refers to it. Use it when child rows are records that must be kept, such as sales, payments and audit entries.NO ACTIONdiffers fromRESTRICTonly in timing: it's checked at the end of the statement and can be deferred (article 52), whileRESTRICTis checked immediately.ON DELETE SET DEFAULTsets the foreign key to the column's default, such as a placeholder "unassigned" row.
The same actions exist for ON UPDATE, applied when the parent's key changes. With surrogate keys that never change (article 50), the default is fine.
Two warnings. CASCADE can delete far more than intended: a cascade from customers to orders to order lines to shipments silently removes a customer's whole history. Prefer RESTRICT for anything with business value, and delete children explicitly when that's really intended. And index foreign key columns: deleting a parent row looks up its children, and without an index on the child's foreign key column, every parent delete scans the whole child table. PostgreSQL doesn't create these indexes automatically.
DROP
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- DROP refuses to break dependent objects unless told to
CREATE VIEW order_totals AS
SELECT order_id, SUM(qty * unit_price) AS total FROM order_items GROUP BY order_id;
DROP TABLE order_items;
DROP TABLE IF EXISTS no_such_table;
-- CASCADE also drops the view (and would drop foreign keys pointing at the table)
DROP TABLE order_items CASCADE;
SELECT COUNT(*) AS views_left FROM information_schema.views WHERE table_name = 'order_totals';
psql:/workspace/solution.sql:66: ERROR: cannot drop table order_items because other objects depend on it
DETAIL: view order_totals depends on table order_items
HINT: Use DROP ... CASCADE to drop the dependent objects too.
psql:/workspace/solution.sql:67: NOTICE: table "no_such_table" does not exist, skipping
psql:/workspace/solution.sql:70: NOTICE: drop cascades to view order_totals
views_left
------------
0
(1 row)
DROP TABLE, DROP VIEW, DROP INDEX and the like remove objects permanently, with their data:
- The database refuses to drop a table that other objects depend on, here the
order_totalsview, and names them in the error. IF EXISTSturns "doesn't exist" from an error into a notice, which is useful in scripts that must run more than once.CASCADEdrops the dependent objects too, and the notice lists them. For a table referenced by foreign keys,CASCADEdrops the foreign key constraints, not the referencing tables or their rows.
DROP COLUMN ... CASCADE works the same way for views and indexes that use the column. Read the error before adding CASCADE: it's telling you what else would disappear.
Transactional DDL
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- In PostgreSQL, DDL is transactional: a failed migration can be rolled back as a whole
BEGIN;
ALTER TABLE products ADD COLUMN colour TEXT;
ALTER TABLE products DROP COLUMN weight_g;
SELECT column_name FROM information_schema.columns
WHERE table_name = 'products' AND column_name IN ('colour', 'weight_g');
ROLLBACK;
SELECT column_name FROM information_schema.columns
WHERE table_name = 'products' AND column_name IN ('colour', 'weight_g');
column_name
-------------
colour
(1 row)
column_name
-------------
weight_g
(1 row)
In PostgreSQL, CREATE, ALTER and DROP take part in transactions like any other statement. Inside the transaction, colour exists and weight_g is gone; after ROLLBACK, both changes are undone. A migration that runs several statements can be wrapped in one transaction, so a failure halfway leaves the schema exactly as it was. SQL Server also supports transactional DDL.
MySQL and Oracle don't. Each DDL statement commits implicitly, before and after it runs, so a failed migration leaves the schema half changed, and any open transaction is committed too. Migrations for these databases must be written so that each step can be retried or reversed by hand.
Changing tables on a live database
Most ALTER TABLE forms take a lock that blocks other sessions' reads and writes on the table, briefly for metadata changes and for a long time when the table is rewritten. Worse, a waiting ALTER TABLE blocks every query that arrives after it. Production teams follow a few rules:
- Set a lock timeout, such as
SET lock_timeout = '5s', so a migration that can't get its lock fails quickly instead of queuing everyone behind it, and retry it later. - Prefer cheap operations: adding a nullable column or one with a constant default,
NOT VALIDconstraints followed byVALIDATE, andCREATE INDEX CONCURRENTLY. - Expand, then contract. To rename a column or change its type without downtime: add the new column, write to both, backfill the old rows in batches, switch reads to the new column, and only then drop the old one, each step in its own deployment. Running applications never see a column disappear.
- Use a migration tool such as Flyway, Liquibase, Alembic or a framework's built-in migrations, so every change is versioned, reviewed and applied the same way everywhere.
What's current
- PostgreSQL 18 allows
NOT NULLconstraints to be added asNOT VALIDand validated later, and to be named. - PostgreSQL 17 added
ALTER TABLE ... ALTER COLUMN ... SET EXPRESSIONfor changing a generated column's expression. - MySQL 8.0 made many changes instant (
ALGORITHM=INSTANT), including adding and dropping columns, but DDL still commits implicitly. - SQLite 3.35 added
ALTER TABLE ... DROP COLUMN.
Common questions
How do I add a NOT NULL column to a table that has rows?
Give it a DEFAULT, which fills the existing rows. Or add it as nullable, fill it, then SET NOT NULL.
Why did my type change fail?
Some existing value can't be converted. Find and fix those rows, or give a USING expression that handles them.
Which foreign key action should I use?
CASCADE for parts of the parent (order lines), SET NULL for optional links, and RESTRICT or the default NO ACTION for records that must be kept.
What does DROP TABLE ... CASCADE delete?
The table and the objects that depend on it, such as views. For foreign keys pointing at the table, it drops the constraints, not the other tables' rows.
Can I roll back an ALTER TABLE? In PostgreSQL and SQL Server, yes, inside a transaction. In MySQL and Oracle, no: DDL commits immediately.
Summary
ALTER TABLEadds, drops, renames and changes columns, defaults and constraints in place.- New columns are NULL in existing rows unless they have a default. A
NOT NULLcolumn needs one. - Type changes convert every value.
USINGsays how, and unconvertible data makes the whole change fail. - New constraints check existing rows.
NOT VALIDplusVALIDATEsplits that work on large tables. - Foreign key actions:
CASCADE,SET NULL,SET DEFAULT,RESTRICTand the defaultNO ACTION. Index foreign key columns. DROPrefuses to break dependencies unless you addCASCADE.IF EXISTSmakes scripts repeatable.- DDL is transactional in PostgreSQL and SQL Server, but commits implicitly in MySQL and Oracle.
- On live systems, use lock timeouts, cheap operations and expand-then-contract migrations.
Practice questions
Write statements that add a NOT NULL column loyalty_points with a default of 0 to customers, then rename it to points.
Answer
ALTER TABLE customers ADD COLUMN loyalty_points INTEGER NOT NULL DEFAULT 0;
ALTER TABLE customers RENAME COLUMN loyalty_points TO points;
order_items.order_id references orders. Which ON DELETE action makes deleting an order also delete its lines, and why might you choose not to use it?
Answer
ON DELETE CASCADE. You might prefer the default NO ACTION or RESTRICT so orders with lines can't be deleted by accident: orders are business records, and a mistaken delete would silently remove their lines too. Cancelling an order by changing its status keeps the history.
A migration on MySQL runs ALTER TABLE a ...; then ALTER TABLE b ...;, and the second fails. What state is the schema in, and how would PostgreSQL differ?
Answer
In MySQL, the first change is committed and stays, so the schema is half migrated. In PostgreSQL, wrapping both statements in a transaction would roll back the first change too, leaving the schema unchanged.
Why add a foreign key NOT VALID and validate it later on a large table?
Answer
Adding it normally checks every existing row while holding a lock that blocks writes. NOT VALID adds it instantly and enforces it for new rows, and VALIDATE CONSTRAINT then checks the old rows with a lighter lock that doesn't block normal reads and writes.
Previous: CREATE TABLE and Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT
Next: Generating Keys: Identity Columns, Sequences and UUIDs

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.