AI chat

A full conversation with an assistant: folded-away thinking, a tool it used, code with a copy button, numbered sources and a reply box. Send a message and the answer arrives a word at a time.

Get Pro

How do I add a NOT NULL column to a table with forty million rows without locking it?

Thought for 4s

A plain ALTER with a default rewrites the table on older versions and holds a lock while it does. The safe route is three small steps: add the column as nullable, fill it in batches, then add the constraint.

Queried orders40,213,880 rows

Do it in three steps, so no single statement holds a lock for long. Add the column as nullable, fill it in batches, then make it NOT NULL once every row has a value.1

sql
ALTER TABLE orders ADD COLUMN region text;

UPDATE orders SET region = 'eu'
WHERE id BETWEEN 1 AND 5000;

ALTER TABLE orders ALTER COLUMN region SET NOT NULL;

Run each ALTER with a short lock_timeout, such as 2s, so a statement stuck behind a long query gives up instead of queueing every write behind it.2

How long will the backfill take at 5,000 rows per batch?

Thought for 2s

Rows divided by batch size gives the number of batches. The time per batch has to be measured, so I will give a range.

About 23 minutes. The table has 40,213,880 rows, so 5,000 rows per batch makes 8,043 batches. At roughly 170 ms a batch, with no pause between them, that is a little under 23 minutes.

Options

Screen
Colour

Code

The React code is part of Pro

Preview AI chat as much as you like. Pro members can copy the code.

How do I add a NOT NULL column to a table with forty million rows without locking it?

Thought for 4s

A plain ALTER with a default rewrites the table on older versions and holds a lock while it does. The safe route is three small steps: add the column as nullable, fill it in batches, then add the constraint.

Queried orders40,213,880 rows

Do it in three steps, so no single statement holds a lock for long. Add the column as nullable, fill it in batches, then make it NOT NULL once every row has a value.1

sql
ALTER TABLE orders ADD COLUMN region text;

UPDATE orders SET region = 'eu'
WHERE id BETWEEN 1 AND 5000;

ALTER TABLE orders ALTER COLUMN region SET NOT NULL;

Run each ALTER with a short lock_timeout, such as 2s, so a statement stuck behind a long query gives up instead of queueing every write behind it.2

How long will the backfill take at 5,000 rows per batch?

Thought for 2s

Rows divided by batch size gives the number of batches. The time per batch has to be measured, so I will give a range.

About 23 minutes. The table has 40,213,880 rows, so 5,000 rows per batch makes 8,043 batches. At roughly 170 ms a batch, with no pause between them, that is a little under 23 minutes.