Sub topic 16
Locking and large tables
This chapter assumes you can write basic ALTER TABLE statements (add, drop and retype columns), that you understand transactions, and that you have a PostgreSQL or MySQL test database. You have already seen that ALTER TABLE changes structure. Here the question is what it costs while it runs on a table that other sessions are using.
Why schema changes need locks
A schema change must stop other sessions from seeing a half-changed table. The database therefore takes a lock on the table, and the strength of that lock decides who has to wait.
On a small table the change finishes in milliseconds and nobody notices. On a table with hundreds of millions of rows, the same statement can hold its lock for minutes or hours. Every query that needs the table queues behind it, and the application appears to hang.
Two separate costs are involved:
- Lock strength. Which other statements (reads, writes) are blocked while the
ALTER TABLEruns. - Work done under the lock. Whether the database must rewrite every row (a table rewrite) or only change catalog metadata, which is the database's internal description of the table.
A metadata-only change is nearly instant regardless of table size. A table rewrite takes time proportional to table size, and it needs extra disk space for the new copy.
What blocks what in PostgreSQL
Most forms of ALTER TABLE in PostgreSQL take an ACCESS EXCLUSIVE lock. This is the strongest lock. It blocks every other statement on the table, including plain SELECT.
The important detail is the lock queue. Suppose a long-running report is reading the table. Your ALTER TABLE asks for ACCESS EXCLUSIVE and must wait for the report to finish. While it waits, every new query on that table queues behind your ALTER TABLE. A change that would take 50 ms can therefore stall the whole application for as long as the report runs.
The usual defence is to set a lock timeout, so the ALTER TABLE gives up instead of making everyone wait:
-- PostgreSQL
BEGIN;
SET LOCAL lock_timeout = '3s';
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
COMMIT;If the lock cannot be acquired within 3 seconds, the statement fails with an error and the transaction is rolled back. You then retry later, when the table is quieter. SET LOCAL limits the setting to the current transaction.
Metadata-only versus rewriting changes
Whether the table is rewritten depends on the change and on the database version. The table below describes typical behaviour in current releases. Check the documentation for your exact version before relying on it.
| Change | PostgreSQL (recent versions) | MySQL 8 (InnoDB) |
|---|---|---|
| Add nullable column, no default | Metadata only | Usually instant (`ALGORITHM=INSTANT`) |
| Add column with a constant default | Metadata only (11 and later) | Usually instant |
| Add column with a volatile default (such as `random()`) | Rewrites the table | Not applicable in the same way |
| Widen `VARCHAR` (increase the limit) | Metadata only | Depends on the length bytes; may rebuild |
| Change a column to an incompatible type | Rewrites the table | Rebuilds the table |
| Drop a column | Metadata only (space is reclaimed later) | Rebuilds in place (instant in 8.0.29 and later) |
| Add `NOT NULL` | Scans the table to verify | Rebuilds or scans |
The status column from the earlier chapter on defaults is a good example:
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';On PostgreSQL 11 and later, the constant default is stored in the catalog and applied when old rows are read, so this is quick even on a huge table. On PostgreSQL 10 and earlier it rewrote every row.
Choosing the algorithm in MySQL
MySQL lets you state what you require, so the statement fails instead of silently doing something expensive:
-- MySQL
ALTER TABLE customers
ADD COLUMN phone VARCHAR(30),
ALGORITHM=INSTANT;If the change cannot be done instantly, MySQL returns an error and leaves the table alone. You can also request ALGORITHM=INPLACE, LOCK=NONE, which allows concurrent reads and writes while the table is rebuilt in the background. This is a useful safety check: it turns a surprise outage into a clear error message.
Constraints and the validation scan
Adding a constraint usually forces the database to check every existing row. A foreign key or CHECK constraint on a large table holds a strong lock during that scan.
PostgreSQL lets you split the work into two steps:
-- PostgreSQL
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;The first statement adds the constraint without checking old rows. It still enforces the rule for new and changed rows, and it takes only a brief lock. The second statement checks the existing rows under a weaker lock that allows normal reads and writes. The same NOT VALID and VALIDATE CONSTRAINT pattern works for CHECK constraints.
Adding an index has a similar option. CREATE INDEX CONCURRENTLY in PostgreSQL builds the index without blocking writes, at the cost of taking longer and being unable to run inside a transaction block.
Locking and DROP
DROP TABLE also takes an ACCESS EXCLUSIVE lock in PostgreSQL, so it queues behind running queries and blocks new ones in the same way. The drop itself is fast because the database removes files rather than rows, so the risk is the wait for the lock, not the work. Use lock_timeout here as well.
Dropping a table that other tables reference with foreign keys also needs locks on those other tables to remove the constraints. A DROP TABLE ... CASCADE can therefore touch more tables than you expect.
Metadata locks and long transactions
MySQL uses metadata locks. An ALTER TABLE must wait for every open transaction that has touched the table, even a transaction that read one row and then sat idle. The queueing problem is the same as in PostgreSQL: new queries wait behind the pending ALTER.
In both databases, the practical rule is to check for long-running or idle-in-transaction sessions before you start a change. In PostgreSQL you can look at pg_stat_activity:
-- PostgreSQL
SELECT pid, state, now() - xact_start AS transaction_age, query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;A session that appears at the top with a large transaction_age is the one your ALTER TABLE will wait for.
Online approaches for heavy changes
When a change would rewrite a very large table, teams commonly use an expand and contract approach instead of one big statement:
- Add the new column as nullable (fast).
- Update the application to write to both columns.
- Copy existing data in small batches, committing after each batch so locks are short.
- Add the constraint with
NOT VALID, then validate it. - Switch reads to the new column.
- Drop the old column in a later release.
Tools such as pt-online-schema-change and gh-ost for MySQL do the copy in the background and swap tables at the end. They add operational complexity, so use them only when the built-in online options are not enough.
Request flow when an ALTER has to wait
Common errors
- Running a rewrite during peak hours. Check whether your change rewrites the table, and schedule it off-peak if it does.
- No lock timeout. Without one, a waiting
ALTER TABLEcan freeze the application behind it. - Forgetting idle transactions. A forgotten open session can block a change indefinitely.
- Running the change inside a long transaction. Locks are held until commit, so keep the transaction short and do only the schema change in it.
- Assuming behaviour carries across versions. PostgreSQL 10 and 11, and MySQL 5.7 and 8.0, differ materially.
Exercise
You run ALTER TABLE orders ADD CONSTRAINT ... FOREIGN KEY ... on a PostgreSQL table with 300 million rows, and the application freezes for several minutes. Name two changes that would reduce the impact, and explain how each helps.
Show answer
First, add the constraint with NOT VALID and then run VALIDATE CONSTRAINT separately. The first step takes only a brief lock and enforces the rule for new rows, and the validation scan of existing rows runs under a weaker lock that allows normal reads and writes. Second, set locktimeout (for example SET LOCAL locktimeout = '3s') inside the transaction, so the statement fails quickly instead of queueing behind a long query and blocking everyone else. You can then retry at a quieter time. Checking pgstatactivity for long-running transactions before starting also helps.
Exercise
Why can an ALTER TABLE that needs only 50 ms of actual work still cause a long outage?
Show answer
It must first acquire a strong lock. If a long-running query already holds a conflicting lock, the ALTER TABLE waits, and new queries that need the table queue behind the waiting ALTER TABLE. The outage lasts as long as the long query plus the ALTER TABLE itself, not just the 50 ms of work.