// SQL snippet

Make a column NOT NULL safely

Adding NOT NULL to a column that still holds NULLs fails immediately, and adding it while some code path still writes NULLs breaks those inserts later. Check, backfill, then enforce.

Main statement
PostgreSQL
次もカバーします
SQL Server MySQL

The task

The column should always carry a value, but switching the constraint on in one step either trips over the rows that lack one or locks a big table for the scan. Work up to it in stages.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
-- 1. find offending rows
SELECT id FROM users WHERE last_name IS NULL;

-- 2. backfill them (choose the right value for your data)
UPDATE users SET last_name = '' WHERE last_name IS NULL;

-- 3. enforce
ALTER TABLE users
  ALTER COLUMN last_name SET NOT NULL;

仕組み

Step 1 shows how many rows are affected before anything changes; step 2 decides what a missing value means (empty string, a sentinel, or deleting the rows). Step 3 fails if any NULL is left, and on PostgreSQL it scans the whole table while holding an ACCESS EXCLUSIVE lock, so reads and writes wait for the scan. On PostgreSQL 12+ the big-table path is a CHECK (col IS NOT NULL) added NOT VALID and validated under a weaker lock; SET NOT NULL then sees the valid constraint and skips its own scan.

Variations

PostgreSQL: big table, validated constraint

PostgreSQL
ALTER TABLE users
  ADD CONSTRAINT users_last_name_required
  CHECK (last_name IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT users_last_name_required;
-- SET NOT NULL now skips the table scan (PostgreSQL 12+)
ALTER TABLE users ALTER COLUMN last_name SET NOT NULL;
ALTER TABLE users DROP CONSTRAINT users_last_name_required;

SQL Server

SQL Server
-- fails if NULLs exist; backfill first
ALTER TABLE dbo.Users
    ALTER COLUMN LastName NVARCHAR(100) NOT NULL;
-- note: ALTER COLUMN restates the full type

MySQL

MySQL
UPDATE users SET last_name = '' WHERE last_name IS NULL;
ALTER TABLE users
  MODIFY COLUMN last_name VARCHAR(100) NOT NULL;
-- MODIFY restates the type. Strict mode makes the ALTER fail
-- on leftover NULLs; without it they silently become empty strings

Questions that come up

Why did my NOT NULL change time out on a busy table?

ALTER COLUMN ... SET NOT NULL needs an ACCESS EXCLUSIVE lock. It first waits for every running query on the table, and every new query queues behind it, then it holds the lock for the full scan. Set lock_timeout so the attempt gives up instead of stalling traffic, and use the CHECK-constraint route so the scan happens under a lock that does not block reads or writes.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.