Fuzzy match strings with Levenshtein distance in SQL
Typos in names defeat exact matching. Edit distance scores how many single-character edits separate two strings.
The task
The fuzzystrmatch extension provides levenshtein() and levenshtein_less_equal() for tolerant name matching.
The snippet
Written for PostgreSQL. Versions for SQL Server and Oracle are under Variations.
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;
SELECT a.name AS name_a, b.name AS name_b,
levenshtein(lower(a.name), lower(b.name)) AS edit_distance
FROM contacts a
JOIN contacts b
ON a.id < b.id
AND levenshtein(lower(a.name), lower(b.name)) <= 2;
工作原理
levenshtein returns the number of insertions, deletions and substitutions between two strings; a distance of 2 or less usually means a typo. The self-join pairs every candidate, which is O(n squared), so restrict one side first (same city, same first letter) before the distance check.
Variations
Oracle
OracleSELECT a.name AS name_a, b.name AS name_b,
UTL_MATCH.EDIT_DISTANCE_SIMILARITY(a.name, b.name) AS similarity_pct
FROM contacts a
JOIN contacts b ON a.id < b.id
WHERE UTL_MATCH.EDIT_DISTANCE_SIMILARITY(a.name, b.name) >= 80;
SQL Server: phonetic DIFFERENCE (0-4), not edit distance
SQL ServerSELECT a.name, b.name, DIFFERENCE(a.name, b.name) AS soundex_score
FROM contacts a
JOIN contacts b ON a.id < b.id
WHERE DIFFERENCE(a.name, b.name) >= 3;
Questions that come up
MySQL has no Levenshtein either?
Right: stock MySQL ships no edit-distance function, and stock SQLite does not either. Options are a stored function, a UDF, or computing candidates in application code. SQL Server 2025 adds EDIT_DISTANCE and EDIT_DISTANCE_SIMILARITY as preview features (enable with ALTER DATABASE SCOPED CONFIGURATION SET PREVIEW_FEATURES = ON); older versions only have the coarse phonetic SOUNDEX and DIFFERENCE.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.