What are exclusion constraints in PostgreSQL?

Answer

Exclusion constraints are a generalization of unique constraints — they ensure that for any two rows in the table, at least one of a set of comparisons evaluates to false. While UNIQUE constraints only check equality (=), exclusion constraints can use any operator from a GiST or SP-GiST index. The classic use case is preventing overlapping time ranges: CREATE TABLE bookings (room_id INT, during TSTZRANGE, EXCLUDE USING GIST (room_id WITH =, during WITH &&)); — this prevents two bookings for the same room with overlapping time ranges. Requires btree_gist extension for combining scalar columns with range columns. Other uses: preventing overlapping geometric regions, ensuring no two network addresses overlap. Cannot be deferred (unlike foreign keys).