Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 14 / Topic 10 of 10

Fuzzy matching with pg_trgm

Full-text search still demands correctly-spelled words. Users type postgre, labtop. pg_trgm (a contrib extension shipped with Postgres) compares strings by their three-letter shingles — resilient to typos by construction:

CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT similarity('Laptop Pro 14', 'labtop pro') AS sim_typo,
       similarity('Laptop Pro 14', 'coffee')     AS sim_unrelated;
CREATE EXTENSION
  sim_typo  | sim_unrelated 
------------+---------------
 0.47058824 |             0
(1 row)
SELECT name,
       similarity(name, 'labtop')      AS whole_string,
       word_similarity('labtop', name) AS best_word
FROM products
WHERE word_similarity('labtop', name) > 0.3
ORDER BY best_word DESC, name;
     name      | whole_string | best_word 
---------------+--------------+-----------
 Laptop Air 13 |   0.23529412 |       0.4
 Laptop Pro 14 |   0.23529412 |       0.4
(2 rows)

Note the two measures: whole-string similarity scores labtop low against Laptop Pro 14 (the Pro 14 dilutes it — its % operator with the default 0.3 threshold would find nothing here), while word_similarity compares the typo against the best-matching word and sees the match plainly. Short lookups against long names want the word form (its operator is <%, threshold 0.6). pg_trgm also GIN-indexes — famously including LIKE '%middle%' patterns that B-trees can't touch (Stage 4 context). The practical search stack for an app, in one line: full-text for meaning, trigrams for typos, both GIN-indexed, both inside the database you already run.

🧪 Quick quiz — answer from memory, then check.

  1. What does name % 'labtop' test?
  2. What famously un-indexable pattern can a trigram GIN index serve?
Show the answers
  1. Trigram similarity above the threshold (default 0.3) — typo-tolerant matching.
  2. LIKE '%substring%' — leading-wildcard searches.

Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.

Search the guide