Concept · Designing databases

ALTER TABLE

ALTER TABLE changes the definition of an existing table: depending on the engine, it can add columns, rename them or change constraints.

ALTER TABLE example

Verified SQL
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

  1. confirm the syntax for the version you actually run;
  2. review views, indexes, constraints and dependent applications;
  3. take a backup and rehearse restoring it;
  4. test the change with representative data;
  5. decide how to roll it back if validation fails;
  6. 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.