adding-not-nullable-field
Use a check constraint instead of setting a column as NOT NULL
.
#
problemAdding a column as NOT NULL
is no longer covered by this rule. See "adding-required-field (set a non-volatile default)" for more information on how to add new columns with NOT NULL
.
Modifying a column to be NOT NULL
may fail if the column contains records with a NULL
value, requiring a full table scan to check before executing. Old application code may also try to write NULL
values to the table.
ALTER TABLE
also requires an ACCESS EXCLUSIVE
lock which will disable reads and writes while this statement is running.
#
solutions#
setting an existing column as non-nullableInstead of:
Use:
For each step, note that:
- Adding the constraint acquires an
ACCESS EXCLUSIVE
lock, but this is done extremely quickly. - You MUST backfill the column before validating the constraint
- Validating the constraint does require a full table scan, but only acquires a
SHARE UPDATE EXCLUSIVE
lock which allows for normal operations to continue. - If using postgres version 12 or later, it forgoes the full table scan by checking the existing constraint.
See "How not valid constraints work" for more information on adding constraints as NOT VALID
.
#
solution for alembic and sqlalchemyInstead of: