Design and best practice · Designing databases

Planning a structural change with ALTER TABLE

Plan a schema change in stages: add the new structure, migrate the data, adapt the queries and remove the old structure once nothing uses it.

Before continuing: This entry is part of the ALTER TABLE guide. If you are new to the topic, start with ALTER TABLE.

Example

Add a phone number to customers
ALTER TABLE customers
ADD COLUMN phone VARCHAR(30);

The operation adds the column at the end of the definition. Since it declares neither NOT NULL nor a DEFAULT, existing rows receive NULL. That lets you add the structure first and fill in the data later.

The statement was checked in SQLite against the teaching schema. In production, also check permissions, locks, dependencies and how the change is deployed.

Verification in SQLite
PRAGMA table_info(customers);

Checking the schema stops you from treating a deployment as finished just because the statement showed no error. Also check a sample of rows and the dependent objects.

Differences and trade-offs

Before writing the statement

  1. Describe the current state and the target state.
  2. Look for queries, views, constraints and indexes that depend on the column.
  3. Check whether the existing data meets the new rule.
  4. Review the syntax and the cost on your specific engine version.
  5. Prepare a backup, a test and a rollback.

Common operations

NeedKind of operationMain risk
Adding a new attributeADD COLUMNStarting values and constraints
Changing type or nullabilityALTER/MODIFY COLUMNConversion, scanning or rewriting
Removing an attributeDROP COLUMNData loss and dependencies
RenameRENAME or a dedicated toolCode that still uses the old name
Adding a ruleADD CONSTRAINTOld rows that break it

A safe sequence of changes

Expand, migrate and restrict is usually safer than forcing everything into a single statement: add a compatible column, adapt the application, fill in the data in batches and only then apply NOT NULL or constraints.

This sequence shortens the window in which an old application and a new structure are incompatible. Not every engine can roll back DDL in the same way; a transaction is no substitute for a backup or a fallback plan.

Avoid this confusion

Adding a rule that existing rows cannot meet

One column NOT NULL without a compatible value can fail when the table already contains rows. A CHECK constraint or a type conversion may also require checking all the data.

Another mistake is copying another engine's syntax: PostgreSQL uses ALTER COLUMN ... TYPE, MySQL uses MODIFY COLUMN for many changes, and SQL Server uses ALTER COLUMN.