Text Pattern Ops Prefix LIKE Index

Serve LIKE 'prefix%' queries from a btree index by declaring the text_pattern_ops operator class, because collation-ordered indexes cannot.

SqlData Fetching

Code

snippet
-- 默认 collation 的 btree 按语言规则排序,无法服务 LIKE 'abc%';
-- text_pattern_ops 操作符类按逐字符序建索引,前缀匹配才能走索引
CREATE INDEX idx_products_name_pattern
  ON products (name text_pattern_ops);

-- 前缀查询走该索引:LIKE 模式以常量开头
EXPLAIN
SELECT product_id, name FROM products WHERE name LIKE 'Widget%';

-- 代价:逐字符序不等于 collation 序,该索引服务不了 ORDER BY name
-- 需要按 name 排序时另建常规索引,两者各司其职
SELECT product_id, name FROM products WHERE name LIKE 'Widget%' ORDER BY product_id;

-- 局限:'%Widget'(前导通配)与 ILIKE 都用不上这个索引
SELECT product_id, name FROM products WHERE name ILIKE 'widget%';

How it works

Several statements share this file — SELECT / CREATE / EXPLAIN, with products among the objects involved.

What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

Applying it

Run it in the products database context.

Statements that matter

SELECT product_id, name FROM products WHERE name LIKE 'Widget%' ORDER BY product_id;
EXPLAIN
SELECT product_id, name FROM products WHERE name LIKE 'Widget%';
SELECT product_id, name FROM products WHERE name ILIKE 'widget%';

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`products` — referenced directly, no join needed.