adding-field-with-default
#
problemAdding a field with a default can cause table rewrites, which will take an ACCESS EXCLUSIVE
lock on the table, blocking reads / writes while the statement is running.
In Postgres version 11 and later, adding a field with a non-VOLATILE
DEFAULT
will not require a table rewrite. Adding a field with a VOLATILE
DEFAULT
will cause a table rewrite.
#
solutions#
adding a non-volatile default in Postgres 11+note
This statement is only safe when your default is non-volatile.
#
adding a volatile defaultAdd the field as nullable, then set a default, backfill, and remove nullabilty.
Instead of:
Use:
We add our column as nullable, set a default for new rows, backfill our column (ideally done in batches to limit locking), and finally remove nullability.
See "How not valid constraints work" for more information on adding constraints as NOT VALID
.
#
solution for alembic and sqlalchemyInstead of:
Use: