Sub topic 16
Locking and Large Tables
Prerequisites: you should know basic ALTER TABLE, transactions, primary keys, and foreign keys. This chapter assumes you can connect to a test database and inspect active sessions.
A schema change can affect users even when it changes no row values. Databases protect table definitions with locks. A lock controls which other sessions may read or change an object while the definition is being changed.
The cost of a change depends on two separate factors:
- Lock duration: how long other sessions must wait.
- Table work: how much data the database must scan, copy, or rewrite.
A small metadata-only change may hold a lock for only a moment. Changing a column type may rewrite millions of rows and hold a strong lock for much longer.
Why table size matters
Adding a nullable column often changes only the table metadata. The database does not need to visit every existing row because the new column can be treated as NULL until a value is stored.
Other changes need more work:
- Adding a
NOT NULLcolumn may require a value for every existing row. - Changing a type may rewrite the table or convert every value.
- Adding a constraint may scan existing data to prove that the constraint is valid.
- Dropping a column may require catalog work and can make old application code fail.
- Dropping a table needs a strong lock and removes the table for every session.
The exact behavior depends on the database and its version. Always check the documentation for the system you are using.
Choosing a safer execution time
Run changes during a period of low traffic when possible. First check for long-running transactions, idle sessions that still have an open transaction, and jobs that use the table continuously.
A migration tool should usually set a lock timeout. This makes the migration fail instead of waiting indefinitely and surprising application users.
-- PostgreSQL example
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
SET lock_timeout = '2s';
SET statement_timeout = '30s';
ALTER TABLE customers
ADD COLUMN last_seen_at TIMESTAMP;If the statement cannot obtain its lock within two seconds, PostgreSQL cancels it. The application can retry the migration later. A statement timeout limits the total execution time after the statement begins.
Do not blindly retry a change that may have partly completed. Confirm the current schema first. A migration system should record which steps succeeded.
Reducing work on large tables
For a large table, separate a change into smaller stages:
- Add a nullable column.
- Deploy application code that writes new values.
- Backfill old rows in small batches.
- Validate that no required values are missing.
- Add
NOT NULLor another constraint during a controlled window.
Batching keeps transactions smaller and reduces long-running locks. It also makes progress easier to monitor. However, each batch still consumes database resources and can compete with normal application traffic.
Some systems provide online or concurrent forms of specific operations. For example, PostgreSQL supports CREATE INDEX CONCURRENTLY, while MySQL and SQL Server provide different online DDL options. These options reduce blocking for particular operations, but they do not make every schema change online.
| Change | Typical risk on a large table | Safer approach |
|---|---|---|
| Add nullable column | Usually brief lock | Run during low traffic and set a lock timeout |
| Change column type | Possible table rewrite and long block | Test duration and use a staged migration |
| Add `NOT NULL` | May scan existing rows | Backfill first, then validate and enforce |
| Drop table | Destructive and strongly blocked | Confirm dependencies and use a controlled window |
Dialect-specific locking behavior
PostgreSQL ALTER TABLE often requests an ACCESS EXCLUSIVE lock, which can block reads and writes while the operation runs. MySQL uses metadata locks and can wait behind an open transaction, even when the DDL itself seems quick. SQL Server uses schema-modification locks that can conflict with queries using the table.
The same SQL text can therefore have different operational effects. Test the exact statement on a copy of production-sized data, not only on a small development table.
Exercise
You need to add a required status column to a table with 500 million rows. Why might adding it as NOT NULL DEFAULT 'active' be risky, and what staged plan could reduce the risk?
Show answer
The database may scan or rewrite many rows while holding a lock. Add the column as nullable, write active for new rows, backfill old rows in batches, verify that no values are missing, and enforce NOT NULL during a controlled maintenance window.