Full answer
Test data:
sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE cities (name text);
INSERT INTO cities VALUES ('Bengaluru'), ('Bangalore'), ('Belgaum'), ('Mangaluru'), ('Chennai'), ('Bhubaneswar');
CREATE INDEX cities_name_trgm ON cities USING gin (name gin_trgm_ops);sql
SELECT name, round(similarity(name, 'Bengalru')::numeric, 2) AS score FROM cities WHERE name % 'Bengalru' ORDER BY score DESC, name;Result:
text
name | score
-----------+-------
Bengaluru | 0.58
(1 row)sql
SELECT name FROM cities ORDER BY name <-> 'Mangalore' LIMIT 2;Output:
text
name
-----------
Bangalore
Mangaluru
(2 rows)sql
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM cities WHERE name ILIKE '%galu%';PostgreSQL returns:
text
Bitmap Heap Scan on cities
Recheck Cond: (name ~~* '%galu%'::text)
-> Bitmap Index Scan on cities_name_trgm
Index Cond: (name ~~* '%galu%'::text)The misspelling 'Bengalru' still finds Bengaluru with a score of 0.58; Mangaluru and Bangalore share fewer trigrams and fall below the default 0.3 threshold. Ordering by the <-> distance operator ranks names by closeness to 'Mangalore', and Bangalore comes before Mangaluru because its spelling differs in fewer trigrams. The trigram index also serves the infix ILIKE search, as the bitmap index scan shows. Sequential scans were disabled only because the demo table is tiny. Trigram matching is spelling-based, so it does not know that Bangalore and Bengaluru are the same city; aliases need a lookup table.
sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE cities (name text);
INSERT INTO cities VALUES ('Bengaluru'), ('Bangalore'), ('Belgaum'), ('Mangaluru'), ('Chennai'), ('Bhubaneswar');
CREATE INDEX cities_name_trgm ON cities USING gin (name gin_trgm_ops);
SELECT name, round(similarity(name, 'Bengalru')::numeric, 2) AS score FROM cities WHERE name % 'Bengalru' ORDER BY score DESC, name;
SELECT name FROM cities ORDER BY name <-> 'Mangalore' LIMIT 2;
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM cities WHERE name ILIKE '%galu%';Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Trigrams measure spelling similarity
- % uses a threshold, similarity() returns a score
- <-> orders by distance
- gin_trgm_ops serves %, LIKE and ILIKE
- Spelling similarity is not meaning
Common mistakes
- Using LIKE '%x%' on large tables without a trigram index
- Expecting fuzzy search to know aliases
Follow-ups
- How would you tune the similarity threshold?
- When is GiST better than GIN for trigrams?
Tips
- Mention the threshold