Migrations that lock the table

Back to list2025-03-22
You

Adding a NOT NULL column locked our table for two minutes. How do people avoid that?

ChatGPT

Split it: add the column nullable, backfill in batches, add a validated check constraint, then set NOT NULL. Each step takes a brief lock instead of one long one, and the backfill can be paused if replication lag grows.

You

Is there a fast approximate count for a huge table?

ChatGPT

For monitoring, read reltuples from pg_class, which the planner keeps roughly current. It is off by a few percent between vacuums, which is fine for a dashboard and wrong for invoicing.