difference
PG 8.0+→ integerReturns the number of matching Soundex codes between two strings (0–4). Higher is more similar.
Signature
difference ( text, text ) → integerParameters
| Parameter | Type | Description |
|---|---|---|
| string1 | text | First string |
| string2 | text | Second string |
Examples
SELECT difference('hello', 'hello');4 (exact match)SELECT difference('Anne', 'Ann');4SELECT difference('hello', 'world');2 or lessSELECT name, difference(name, 'Johnson') AS score FROM contacts WHERE difference(name, 'Johnson') >= 3 ORDER BY score DESC;Contacts with high phonetic similarity to JohnsonDIFFERENCE() returns 0-4 but the meaningful threshold varies by name length and origin. Using a fixed cutoff (e.g. >= 3) will miss valid matches for longer names and produce false positives for short names.
✓ Instead: Use difference() as one signal among several (combine with levenshtein and similarity) rather than a standalone match decision.
A difference of 4 means identical Soundex codes. Use `difference(a, b) >= 3` for fuzzy phonetic matching. Combined with Levenshtein for typo tolerance.
SELECT name FROM users WHERE difference(name, $1) >= 3;Names with high phonetic similarity