Before continuing: This entry is part of the ALTER TABLE guide. If you are new to the topic, start with ALTER TABLE.
ALTER TABLE on large tables: example
ALTER TABLE orders
ADD COLUMN channel VARCHAR(20);Adding a column that allows NULL first usually makes compatibility easier. The application can start writing the new value without having to fill in every old row in the same deployment.
Differences and trade-offs
Three kinds of cost
| Kind | What can happen | Possible examples |
|---|---|---|
| Metadata | Changes the catalogue without going through every row | Adding certain columns or changing a default |
| Validation | Reads rows to check a rule | Add CHECK or NOT NULL |
| Rewrite or copy | Transforms the data and saves it again | Changing some types, dropping columns or reordering them |
The exact kind depends on the engine, the version, the column type, defaults, constraints, indexes and configuration.
Phased migration plan
- Measure: size, write rate, indexes and dependencies.
- Rehearse: on a copy with a similar volume and distribution.
- Expand: add a structure that works with both versions of the application.
- Fill in: migrate data in batches you can monitor, where needed.
- Restrict: validate and add the final rules afterwards.
- Remove: drop the old columns in a later deployment.
Key differences between engines
- Current PostgreSQL versions: adding a column with a constant default can avoid updating every row at that point; a volatile default may require every row to be filled in. Changing types and validating rules can take more work.
- MySQL 8.4 with InnoDB:
INSTANTis the default algorithm when the operation supports it. Changing the type of a column is documented as an operation that requiresCOPY, while certain enlargements ofVARCHARcan be done in place. - Current SQLite versions: renaming a table or column, and adding a column with no constraints that need checking, can be independent of the number of rows. Since SQLite 3.53.0 there is also
ALTER COLUMN ... SET/DROP NOT NULL; settingNOT NULLhas to check the existing data. Operations that validate constraints or drop a column may scan or rewrite the contents, so their cost grows with the table. - SQL Server: operations and options depend on the edition and the object; a column change can block access, and some operations offer online or resumable variants.
Key differences between engines
- The algorithm actually chosen, and whether it can be forced or alternatives rejected.
- Type and duration of locks.
- Extra space for copies, indexes and logs.
- Impact on replicas, backups and recovery.
- How to cancel, and a rollback plan.
- Metrics that tell you to continue or abort.