Sub topic 8
GiST: geometry, ranges, nearest-neighbor search, and exclusion constraints
This chapter assumes you know basic SELECT, WHERE, ORDER BY, table creation, and PostgreSQL types such as integer, point, and range types. You should also know that an index is an additional data structure that can reduce the rows PostgreSQL must inspect.
What GiST stores
GiST means Generalized Search Tree. It is an index framework for data types whose values do not fit neatly into ordinary sorted order. A GiST index stores summaries of groups of values and uses type-specific operators to decide which groups might contain a match.
For example, a group of geographic points can be summarized by a bounding box. A query for points near a location can skip boxes that are clearly far away.
GiST is not one single search algorithm for one data type. Its behavior depends on an operator class. The operator class defines how PostgreSQL groups values and which operators the index can support.
GiST indexes can be lossy. A summary may say that a group could match even when an individual row does not. PostgreSQL then rechecks candidate rows against the original condition. This extra check is normal.
Geometry and nearest-neighbor search
PostgreSQL's built-in point type has GiST support. The distance operator <-> can be used for nearest-neighbor ordering.
CREATE TABLE places (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
location point NOT NULL
);
CREATE INDEX places_location_gist_idx
ON places USING gist (location);
INSERT INTO places (name, location) VALUES
('North', point '(10, 22)'),
('South', point '(10, 15)'),
('West', point '(7, 20)'),
('East', point '(15, 20)');
SELECT id, name, location <-> point '(10, 20)' AS distance
FROM places
ORDER BY location <-> point '(10, 20)'
LIMIT 2;The index can produce nearby values without sorting every table row. This pattern is useful for spatial data, but a point is only a simple coordinate. It does not account for the Earth's curvature or distances over a real map. For geographic applications, use a suitable PostGIS type and operator class.
Range overlap and containment
PostgreSQL range types describe intervals such as time periods. GiST indexes support operators including:
&&: ranges overlap@>: the left value contains the right value<@: the left value is contained by the right value
CREATE TABLE reservations (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id integer NOT NULL,
during tstzrange NOT NULL
);
CREATE INDEX reservations_during_gist_idx
ON reservations USING gist (during);
SELECT id, room_id
FROM reservations
WHERE during && tstzrange(
'2026-12-01 10:00+00',
'2026-12-01 11:00+00',
'[)'
);The [) bounds mean that the start is included and the end is excluded. Consistent bounds prevent a booking ending at 11:00 from overlapping one beginning at 11:00.
Exclusion constraints
A unique B-tree index prevents equal values. It cannot express “these values must not overlap.” An exclusion constraint can combine operators and reject conflicting rows.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_reservations (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id integer NOT NULL,
during tstzrange NOT NULL,
CONSTRAINT no_double_booking
EXCLUDE USING gist (
room_id WITH =,
during WITH &&
)
);This constraint rejects two rows when both their room_id values are equal and their during ranges overlap. btree_gist supplies GiST operator support for scalar types such as integer; it does not replace ordinary B-tree indexes for general sorting and equality queries.
Choosing GiST
Choose GiST when the query uses a data type and operator class designed for GiST, especially for:
- Spatial or geometric searches
- Range overlap and containment
- Nearest-neighbor ordering with a supported distance operator
- Exclusion constraints
Use a B-tree for ordinary equality, range, and ordering queries on scalar columns. Use GIN when one row contains many independently searchable keys, such as jsonb, arrays, or full-text lexemes. A GiST index may be more flexible, but it can be larger or slower for a workload that a B-tree handles directly.
Check the actual plan instead of assuming the index is used.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM reservations
WHERE during && tstzrange(now(), now() + interval '1 hour', '[)');Exercise
Which index type and constraint would prevent overlapping reservations for the same room?
Show answer
Use a GiST-backed exclusion constraint with room_id WITH = and during WITH &&. Add btree_gist when the scalar room identifier needs GiST equality support.