SP-GiST Index Serves Prefix Search

Create a partitioned-tree index with USING spgist (url text_ops) so constant-prefix LIKE queries hit the index, while infix patterns still need trigram support.

SqlData Integrity

Code

snippet
-- SP-GiST: a space-partitioned tree index. text_ops supports prefix matching,
-- more space-efficient than btree when values share long prefixes (paths, serial numbers, domains)
CREATE TEMP TABLE endpoints (
    url text NOT NULL
);

INSERT INTO endpoints (url) VALUES
    ('/api/v2/orders'), ('/api/v2/orders/42'), ('/api/v2/users'),
    ('/api/v1/health'), ('/static/logo.svg');

CREATE INDEX idx_endpoints_url_spgist
    ON endpoints USING spgist (url text_ops);

-- LIKE with a constant prefix can use SP-GiST: the tree branches by prefix and lands directly on the right subtree
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '/api/v2/%';

-- infix '%...%' does not qualify: like btree, SP-GiST only serves patterns anchored at the front
-- for substring search, add a pg_trgm + GIN index separately
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '%orders%';

How the snippet works

What runs here is SELECT / INSERT / CREATE / EXPLAIN — endpoints are the objects involved.

endpoints is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns.

Applying it

Nothing outside the file is needed: the session-local tables it touches (endpoints) are created by the file itself — point it at a scratch database and run the whole thing.

Statements that matter

EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '/api/v2/%';
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '%orders%';
INSERT INTO endpoints (url) VALUES
    ('/api/v2/orders'), ('/api/v2/orders/42'), ('/api/v2/users'),
    ('/api/v1/health'), ('/static/logo.svg');

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`endpoints` — referenced directly, no join needed.