Design and best practice · Designing databases

ALTER TABLE on large tables

The cost of ALTER TABLE depends on whether it changes metadata, rewrites data or blocks access. Rehearse the specific operation and version with a realistic data volume.

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

A simple schema change
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

KindWhat can happenPossible examples
MetadataChanges the catalogue without going through every rowAdding certain columns or changing a default
ValidationReads rows to check a ruleAdd CHECK or NOT NULL
Rewrite or copyTransforms the data and saves it againChanging 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

  1. Measure: size, write rate, indexes and dependencies.
  2. Rehearse: on a copy with a similar volume and distribution.
  3. Expand: add a structure that works with both versions of the application.
  4. Fill in: migrate data in batches you can monitor, where needed.
  5. Restrict: validate and add the final rules afterwards.
  6. 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: INSTANT is the default algorithm when the operation supports it. Changing the type of a column is documented as an operation that requires COPY, while certain enlargements of VARCHAR can 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; setting NOT NULL has 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.