ALTER TABLE example
CREATE TABLE customers_demo (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
INSERT INTO customers_demo (id, name)
VALUES (1, 'Amy'), (2, 'Liam');
ALTER TABLE customers_demo
ADD COLUMN active INTEGER NOT NULL DEFAULT 1;
SELECT id, name, active
FROM customers_demo
ORDER BY id;The new column has a valid default for the existing rows. The exact rules for required columns depend on the engine and the operation.
How ALTER TABLE is used
Do not run a list like this blindly. Check each operation against the documentation for your database and version.
What changes from case to case
- confirm the syntax for the version you actually run;
- review views, indexes, constraints and dependent applications;
- take a backup and rehearse restoring it;
- test the change with representative data;
- decide how to roll it back if validation fails;
- check the data and queries after applying it.
Common mix-ups with ALTER TABLE
Copying a variant from another engine
Expressions such as ALTER COLUMN, MODIFY COLUMN or certain forms of ADD CONSTRAINT are not interchangeable. SQLite, for example, offers a smaller set of direct changes than other engines and requires rebuilding the table for some of them.
Nor should you assume that a DDL operation can be rolled back the same way on every system.