similarity
pg_trgm extension available since PG 8.3+. GIN/GiST index support for the % operator introduced in PG 9.1+.→ realReturns a number between 0 and 1 representing how similar the two strings are, based on trigram overlap. Requires the pg_trgm extension.
Signature
similarity ( text, text ) → realParameters
| Parameter | Type | Description |
|---|---|---|
| string1 | text | First string to compare |
| string2 | text | Second string to compare |
Examples
SELECT similarity('hello world', 'hello word');0.625SELECT similarity('PostgreSQL', 'PostgreSQL');1.0SELECT name FROM products WHERE similarity(name, 'wrieless mouse') > 0.3 ORDER BY similarity(name, 'wrieless mouse') DESC;Fuzzy product search with typo toleranceSELECT user_input, query, similarity(user_input, query) AS score FROM search_log WHERE similarity(user_input, query) < 0.5 ORDER BY score;Audit log of low-confidence fuzzy matches for reviewThe `%` operator checks `similarity(a,b) >= pg_trgm.similarity_threshold` (default 0.3). Create a GIN index: `CREATE INDEX ON t USING GIN (col gin_trgm_ops)` for O(log n) fuzzy search instead of full table scan.
CREATE EXTENSION pg_trgm;
CREATE INDEX ON products USING GIN (name gin_trgm_ops);
SELECT name, similarity(name, $1) AS sim FROM products WHERE name % $1 ORDER BY sim DESC LIMIT 10;Fast fuzzy product search