btree_gist: Let Scalar Columns Join GiST Exclusion Constraints
Last updated: 2026-11-04
btree_gist: Let Scalar Columns Join GiST Exclusion Constraints
GiST natively covers only a handful of types — geometries and ranges — so plain int or text columns cannot join an EXCLUDE USING gist constraint. btree_gist adds GiST operator classes for scalar types, which lets a rule such as "no overlapping time ranges within the same room number" be expressed as a single exclusion constraint instead of a hand-written trigger. It also makes scalar columns usable in GiST indexes over range types.
| Kind | extension |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE t_booking (
id int PRIMARY KEY,
room int NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room WITH =, during WITH &&)
);
Returns:CREATE EXTENSION returns success on completion. The extension itself returns nothing useful: it installs a set of operator classes (int4_ops, text_ops, numeric_ops and friends), and its effect shows up as working GiST indexes and exclusion constraints.
▶ 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 id, room, during, status FROM t_gist_attempt ORDER BY id
id | room | during | status
----+------+----------------------------------------------------------+-------------------
1 | 101 | ["2026-01-01 00:00:00+00","2026-02-01 00:00:00+00") | OK
2 | 202 | ["2026-01-01 00:00:00+00","2026-03-01 00:00:00+00") | OK
3 | 101 | ["2026-01-15 00:00:00+00","2026-02-15 00:00:00+00") | rejected: overlaps id=1
(3 rows)
Note: row 3 shares room 101 with row 1 and overlaps its time range, so the exclusion constraint rejected it; a PL/pgSQL EXCEPTION block caught the violation and logged it to the audit table.
📌 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 } }).
- Size: btree_gist is about 22 KB, a lightweight contrib extension like pg_trgm (~15 KB) and uuid-ossp (~17 KB); pgcrypto at ~1.1 MB is a different order of magnitude.
- Without btree_gist, `EXCLUDE USING gist (room WITH =, ...)` fails outright with: data type integer has no default operator class for access method "gist".
- The exclusion constraint pairs = with &&: within one room value the during ranges must not overlap. PostgreSQL names the constraint automatically, something like t_gist_booking_room_during_excl, and you can look it up in pg_constraint.
- A violation raises exclusion_violation (SQLSTATE 23P01); the example catches it in a PL/pgSQL EXCEPTION block and records the reason in an audit table.
- The extension adds operator classes only, no new types; DROP EXTENSION btree_gist also removes the constraints that depend on it.