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).
Previous
How do you perform zero-downtime schema migrations in PostgreSQL?
Next
How do you use pg_dump and pg_restore for backup and restore?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What causes poor query plans and how do you fix them?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?