SQL LEVENSHTEIN function
Returns the minimum number of single-character edits needed to turn one string into another.
- Kategorie
- Strings
- Returns
integer- In this category
- 118 of 172
Syntax
levenshtein(str1, str2)
levenshtein(str1, str2, ins_cost, del_cost, sub_cost)
Each block is a separate form. The support table and the examples show which engine takes which.
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Different name or syntax | EDIT_DISTANCE in SQL Server 2025, a preview feature (PREVIEW_FEATURES = ON). |
| PostgreSQL | Ja | Requires the fuzzystrmatch extension. |
| MySQL | Not built in | No built-in; stored functions or application code. |
| SQLite | Different name or syntax | editdist3 in the spellfix1 extension, with different default costs. |
| Oracle | Different name or syntax | UTL_MATCH.EDIT_DISTANCE(s1, s2). |
Beispiele
PostgreSQL
SELECT levenshtein('kitten', 'sitting') AS distance; -- 3
PostgreSQL
SELECT name, levenshtein(lower(name), 'smith') AS d FROM people ORDER BY d LIMIT 5;
Gut zu wissen
- The distance is case-sensitive: levenshtein('abc', 'ABC') is 3. Lower both sides first when casing should not count.
- The optional cost arguments weight insertions, deletions and substitutions separately. They do not add transpositions, so swapping two letters ('teh' to 'the') still costs 2.
- fuzzystrmatch rejects inputs longer than 255 characters. For threshold filters, levenshtein_less_equal(a, b, max) stops once the distance passes max and runs much faster.
Questions about LEVENSHTEIN
What counts as one edit?
Inserting, deleting or substituting one character. 'kitten' to 'sitting' is distance 3: k to s, e to i, then insert g.
How do I make Levenshtein ignore case?
Lower both inputs: levenshtein(lower(a), lower(b)). The function itself does not fold case.
Which engines have Levenshtein built in?
PostgreSQL via fuzzystrmatch, Oracle via UTL_MATCH.EDIT_DISTANCE, SQL Server 2025 via EDIT_DISTANCE once preview features are enabled, and SQLite via spellfix1's editdist3. MySQL has nothing built in.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.