pg_trgm GIN Index For Infix LIKE
Index infix LIKE searches with the pg_trgm extension: a GIN index on gin_trgm_ops serves %son% patterns and similarity ordering that a plain btree cannot.
Code
-- 前缀 LIKE 能走 btree(text_pattern_ops),但中缀(infix)匹配 %son% 没有索引可用;
-- pg_trgm 把文本切成三元组,GIN 索引让任意位置的模糊匹配都能走索引
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);
SELECT id, name
FROM products
WHERE name LIKE '%son%';
-- 相似度检索同样受益:% 按 pg_trgm.similarity_threshold 过滤,similarity 打分
SELECT name, similarity(name, 'jackson') AS sim
FROM products
WHERE name % 'jackson'
ORDER BY sim DESC;What the code does
Several statements share this file — SELECT / CREATE, with products among the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run it in the products database context.
Statements that matter
SELECT name, similarity(name, 'jackson') AS sim
FROM products
WHERE name % 'jackson'
ORDER BY sim DESC;
SELECT id, name
FROM products
WHERE name LIKE '%son%';
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `products`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.