Skip to the workspace
Pebellslearn by building
Data Definition Language (DDL)  ›  Lesson

ALTER TABLE

Alter Table 15 minALTER TABLE changes an existing table's shape by adding, dropping, renaming or retyping columns and constraints, and every change must account for the rows already stored.

sql / ALTER TABLE

Explore each scene at your own pace.

01 · The rule

The rule

ALTER TABLE

ALTER TABLE changes an existing table's shape by adding, dropping, renaming or retyping columns and constraints, and every change must account for the rows already stored.

Plan a structural change around the data and dependent code that already exist.

Three months after launch, the shop decides it needs customers' phone numbers. The customers table already holds thousands of rows. You do not rebuild it from scratch; you change its shape in place with ALTER TABLE, and the existing rows come along with you.

The rule

ALTER changes a table's shape in place: add, drop, rename, retype.

Every form starts with ALTER TABLE <name> and then says what to change:

ALTER TABLE customers ADD COLUMN phone VARCHAR(15);
ALTER TABLE customers DROP COLUMN phone;
ALTER TABLE customers RENAME COLUMN city TO town;
ALTER TABLE customers RENAME TO clients;

These four work in PostgreSQL, MySQL 8 and recent SQLite. Changing a column's type is where dialects differ most:

ALTER TABLE products ALTER COLUMN name TYPE VARCHAR(200);  -- PostgreSQL
ALTER TABLE products MODIFY COLUMN name VARCHAR(200);      -- MySQL

Notice that ALTER never touches the values in the rows you keep, apart from filling a new column; changing the data itself is UPDATE's job, which comes later in the course. You can also add or remove constraints, for example ALTER TABLE products ADD CONSTRAINT price_positive CHECK (price > 0);. The database checks existing rows first, and refuses if any of them already break the new rule.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.