Sub topic 8
GiST: geometry, ranges, nearest-neighbor search, and exclusion constraints
This chapter assumes you can read a basic EXPLAIN plan and know how B-tree indexes work. It also assumes you are comfortable with CREATE EXTENSION and with PostgreSQL range types such as tstzrange. You will learn what a GiST index stores, which queries it speeds up, how nearest-neighbor ordering works, and how to use GiST to enforce rules that a unique index cannot.
What GiST stores
GiST stands for Generalized Search Tree. It is a balanced tree, like a B-tree, but it does not assume values sort into one line. Each entry in an internal page holds a key that describes everything beneath it. For a point or box column, that key is a bounding box. For a range column, it is a range that covers all child ranges.
A search descends only into children whose key could contain a match. Two children may have overlapping keys, so a search can visit more than one path. This is the main difference from a B-tree, where each value has exactly one place.
GiST is a framework. The index code is generic, and an operator class (see the earlier chapter on operator classes) supplies the type-specific logic. The operator class provides these functions:
consistentdecides whether a key could match the query.unionbuilds a parent key from child keys.penaltypicks the best child for a new entry.picksplitdivides a full page in two.distanceis optional and powers nearest-neighbor search.
Many GiST operator classes are lossy. The index may say a row might match, and PostgreSQL then rechecks the real value in the heap. In EXPLAIN ANALYZE this shows up as Rows Removed by Index Recheck.
Geometry operators
The built-in geometric types (point, box, circle, polygon) have default GiST operator classes. They support position and containment operators instead of < and >.
| Operator | Meaning |
|---|---|
| `&&` | The two shapes overlap |
| `@>` | The left shape contains the right |
| `<@` | The left shape is contained in the right |
| `<<`, `>>` | Strictly left of, strictly right of |
| `<->` | Distance between the two shapes |
Here is a table of places with a GiST index and some sample data:
CREATE TABLE places (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
location point NOT NULL
);
INSERT INTO places (name, location)
SELECT 'place ' || g, point(random() * 100, random() * 100)
FROM generate_series(1, 100000) AS g;
CREATE INDEX places_location_gist_idx
ON places USING gist (location);
ANALYZE places;
-- Everything inside a rectangle
SELECT id, name
FROM places
WHERE location <@ box '((0,0),(5,5))';
-- Everything within 5 units of (10, 20)
SELECT id, name
FROM places
WHERE location <@ circle '((10,20),5)';A B-tree on a point column does not help here. A point has no useful single sort order for "inside this rectangle", so without GiST the planner reads the whole table.
For real geographic data you usually want the PostGIS extension, which adds geography types and GiST operator classes for them. The built-in point uses flat plane distance. It does not model the curvature of the Earth.
Range types
Range columns such as int4range, daterange, and tstzrange have a default GiST operator class. It supports these operators:
&&for overlap@>and<@for containment<<and>>for strictly before and after-|-for adjacent=for equality
CREATE EXTENSION IF NOT EXISTS btree_gist;
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);
-- Which reservations touch this window?
SELECT id, room_id
FROM reservations
WHERE during && tstzrange('2026-12-01 09:00+00', '2026-12-01 12:00+00');Range bounds are half-open by default: [start, end). A booking from 09:00 to 10:00 and one from 10:00 to 11:00 do not overlap. Keep this in mind when you write overlap queries and constraints.
GiST has no leading-column rule like a B-tree's. In a multicolumn GiST index, a condition on any indexed column can use the index. The search is still cheapest when your conditions narrow the result on several columns.
Nearest-neighbor search
A B-tree can return rows in sorted order, so ORDER BY created_at LIMIT 10 needs no sort. GiST can do something similar for distance. If the operator class defines a distance function, the planner can walk the tree in order of increasing distance and stop after LIMIT rows. This is a k-nearest-neighbor (KNN) search.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name, location <-> point '(10, 20)' AS dist
FROM places
ORDER BY location <-> point '(10, 20)'
LIMIT 5;Without the index, PostgreSQL computes the distance for all 100,000 rows and sorts them. With the index, the plan is a Limit over an Index Scan using places_location_gist_idx, with an Order By: (location <-> '(10,20)'::point) line. Buffer counts drop from the size of the table to a handful of pages.
The index only helps when the query has a particular shape:
- The
ORDER BYexpression must be an indexed column, the distance operator, and a constant or parameter. Wrapping it in a function, or sorting bydist + 1, prevents the index from being used for ordering. - The query needs a
LIMIT. Without one, PostgreSQL has to produce every row anyway, and the planner may prefer a sequential scan plus a sort. - Extra
WHEREfilters are applied after rows come out of the index in distance order. If the filter is very selective, the scan can walk a long way before it finds enough matches.
Exclusion constraints
A UNIQUE constraint says no two rows may be equal on some columns. An exclusion constraint generalizes this: no two rows may satisfy a given operator on all listed columns. With the = operator it behaves like a unique constraint. With && it can say "no two ranges may overlap".
PostgreSQL enforces an exclusion constraint with an index, and GiST is the usual choice because it supports &&. A B-tree cannot express overlap.
The room-booking rule needs = on an integer and && on a range. The built-in GiST classes do not cover plain integer equality. The btree_gist extension adds GiST operator classes for common scalar types, so you can mix both in one index.
CREATE EXTENSION IF NOT EXISTS btree_gist;
DROP TABLE IF EXISTS reservations;
CREATE TABLE 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 &&)
);
INSERT INTO reservations (room_id, during)
VALUES (1, tstzrange('2026-12-01 09:00+00', '2026-12-01 10:00+00'));
-- Fails: same room, overlapping time
INSERT INTO reservations (room_id, during)
VALUES (1, tstzrange('2026-12-01 09:30+00', '2026-12-01 11:00+00'));
-- Succeeds: starts exactly when the first booking ends
INSERT INTO reservations (room_id, during)
VALUES (1, tstzrange('2026-12-01 10:00+00', '2026-12-01 11:00+00'));
-- Succeeds: different room, same time as the first booking
INSERT INTO reservations (room_id, during)
VALUES (2, tstzrange('2026-12-01 09:00+00', '2026-12-01 10:00+00'));The second insert fails with conflicting key value violates exclusion constraint "no_double_booking" and SQLSTATE 23P01. Application code can catch that code and report a friendly "room already booked" message.
Because the check goes through the index, it is safe under concurrency. Two sessions that insert conflicting rows at the same time cannot both succeed. One waits for the other and then fails or proceeds.
Some details to know:
- The constraint creates its index automatically. You do not run a separate
CREATE INDEX, and the same index serves overlap queries onduring. - You can add a
WHEREclause to make the constraint partial. For example, you can apply it only to rows wherestatus = 'confirmed'. - The constraint can be declared
DEFERRABLE. - Unlike a unique constraint, an exclusion constraint cannot be the target of a foreign key.
- The operators must be commutative, meaning
a OP bequalsb OP a.=and&&both qualify.
If you forget btree_gist, the table creation fails with data type integer has no default operator class for access method "gist". The fix is CREATE EXTENSION btree_gist;.
Costs and trade-offs
GiST is flexible, but it has a price compared with a B-tree:
- Lossy matches. Rechecks add heap access. Polygons, for example, are indexed by their bounding boxes, so the index finds candidates and the heap confirms them.
- Build time and size. GiST builds are usually slower than B-tree builds, and the index is often larger. Because keys overlap, a search can visit several branches. A poorly clustered data set makes this worse.
- Write cost. Every insert must choose a path with
penaltyand may split pages withpicksplit. Updates to the indexed column are not cheap. - Index-only scans. These work only for operator classes that store the full value, and not for lossy ones such as polygon.
- No uniqueness. There is no
CREATE UNIQUE INDEX ... USING gist. Use an exclusion constraint instead.
Compared with GIN, GiST is usually smaller and cheaper to update, but often slower to search for membership-style queries. For jsonb and arrays, GIN is normally the better fit. For ranges and geometry, GiST is the standard choice.
Exercise
You have a taxis table with a position point column. A query runs SELECT id FROM taxis ORDER BY position <-> point '(3, 4)' LIMIT 10; and EXPLAIN shows a sequential scan followed by a Sort. Name two changes that could let PostgreSQL use an index for this query.
Show answer
Create a GiST index on the column with CREATE INDEX ON taxis USING gist (position);, because a B-tree cannot order rows by the <-> distance operator. Then keep the query in the supported shape, which is the indexed column, <->, a constant, and a LIMIT. On a small table the planner may still pick a sequential scan because it is cheaper, so test on realistic data and run ANALYZE first.
Exercise
Write a table definition that prevents two rows with the same employee_id from having overlapping daterange values in a column named period. Which extension do you need, and why?
Show answer
CREATE EXTENSION IF NOT EXISTS btreegist;
CREATE TABLE assignments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
employeeid integer NOT NULL,
period daterange NOT NULL,
EXCLUDE USING gist (employeeid WITH =, period WITH &&)
);
You need `btreegist because the integer column employee_id has no default GiST operator class for =` without it.
Exercise
A booking from 14:00 to 15:00 exists for room 3. Does an insert for room 3 from 15:00 to 16:00 violate an exclusion constraint on (room_id WITH =, during WITH &&), assuming during is built with the default range bounds?
Show answer
No. Default range bounds are [), so the first booking includes 14:00 but excludes 15:00. The two ranges touch but do not overlap, so && is false and the insert succeeds.