← all rules

add-exclusion-constraint

error

ADD EXCLUDE constraint

Why it's unsafe

ALTER TABLE ... ADD CONSTRAINT ... EXCLUDE builds an index under an ACCESS EXCLUSIVE lock, scanning the whole table.

Safe rewrite

Adding an exclusion constraint locks the table while it builds the index. Add it during a low-traffic window; on a large table, weigh whether the constraint is necessary.

Example

Try it in the playground →

Unsafe

ALTER TABLE rooms ADD CONSTRAINT no_overlap EXCLUDE USING gist (room WITH =, during WITH &&);

Related