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.

Kindconstraint
Example LanguageSQL

📝 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏