Unaccent Needs An Immutable Wrapper Index
Expression indexes reject non-immutable functions, so wrap unaccent in an immutable wrapper pinned to its dictionary and index names for accent-free search.
Code
CREATE EXTENSION IF NOT EXISTS unaccent;
-- 表达式索引要求函数 IMMUTABLE;unaccent() 依赖字典查找不满足,
-- 直接对 unaccent(name) 建索引会被拒绝。包一层钉死字典名的不可变包装
CREATE OR REPLACE FUNCTION f_unaccent(text)
RETURNS text
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURN unaccent('unaccent', $1);
CREATE TABLE authors (name text NOT NULL);
INSERT INTO authors VALUES ('Jürgen Habermas'), ('Hélène Cixous'), ('Karel Čapek');
CREATE INDEX authors_name_unaccent ON authors (f_unaccent(name));
-- 查询无重音关键词也能命中带重音的名字
SELECT name FROM authors WHERE f_unaccent(name) = f_unaccent('Karel Capek');How the snippet works
What runs here is SELECT / INSERT / CREATE — authors are the objects involved.
Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns.
Applying it
Point it at the authors table.
Statements that matter
SELECT name FROM authors WHERE f_unaccent(name) = f_unaccent('Karel Capek');
CREATE OR REPLACE FUNCTION f_unaccent(text)
RETURNS text
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURN unaccent('unaccent', $1);
INSERT INTO authors VALUES ('Jürgen Habermas'), ('Hélène Cixous'), ('Karel Čapek');
Interactive Tools for This Topic
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.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.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 tables or CTEs does it reference?
- `authors`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.