EXCLUDE Constraint
Last updated: 2026-11-04
EXCLUDE Constraint
EXCLUDE is a PostgreSQL-only constraint kind that defines conflicts with a comparison operator rather than equality, which makes it possible to express rules that UNIQUE cannot: bookings may not overlap, a device may not be assigned to two tasks at once. It is backed by a GiST index, and scalar columns additionally require the btree_gist extension.
| Kind | constraint |
|---|---|
| Example Language | SQL |
📝 Syntax
`EXCLUDE USING gist (col WITH =, range_col WITH &&)`
Operators: `=` (equality), `&&` (range overlap), `@>` (contains)
Deferrable: `DEFERRABLE INITIALLY DEFERRED`
⚙️ Parameters
| col WITH = | A scalar column compared for equality. GiST support for scalar columns requires the btree_gist extension. |
|---|---|
| range_col WITH && | A range column compared for overlap; range types ship with GiST support and need no extension. |
Returns:An exclusion constraint has no return value. On conflict PostgreSQL raises `conflicting key value violates exclusion constraint "..."`.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT step, result FROM (
SELECT 1 AS ord, step, result FROM step_log
UNION ALL
SELECT 2, 'rows stored', (SELECT count(*)::TEXT FROM room_bookings)
) t ORDER BY ord
step | result
-----------------------------+-----------------------------------------------------------------------------------------
same room, overlapping time | conflicting key value violates exclusion constraint "room_bookings_room_id_during_excl"
different room, same time | OK
rows stored | 3
(3 rows)
📌 Key Points
- In browser PGlite it must be loaded on demand: import { btree_gist } from '@electric-sql/pglite/contrib/btree_gist', then new PGlite({ extensions: { btree_gist } }).
- Only range types ship with GiST support; scalar columns (integers, text, ...) rely on the operator classes btree_gist provides.
- An exclusion constraint can defer its check: with `DEFERRABLE INITIALLY DEFERRED`, conflicts are judged at commit time.
- On conflict the whole row is rejected, and the error names the exclusion constraint rather than a unique constraint.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhat exactly is the difference between UNIQUE and EXCLUDE?
AUNIQUE asks 'are the values identical?', while EXCLUDE asks 'do these rows conflict under this operator?'. Overlapping intervals or clashing time slots have different values yet conflict, so only EXCLUDE can express them.
QWhat error appears without btree_gist?
AYou get `data type integer has no default operator class for access method "gist"`, because scalar columns lack a GiST equality operator class. An exclusion constraint over range columns alone needs no extension at all.