Fuzzystrmatch Levenshtein Typo Ranking
Rank products against a misspelled query by levenshtein edit distance from the fuzzystrmatch extension, nearest match first.
Code
-- fuzzystrmatch's levenshtein: rank mistyped input by edit distance
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;
CREATE TABLE products (
product_id int PRIMARY KEY,
name text NOT NULL
);
INSERT INTO products (product_id, name) VALUES
(1, 'postgresql'),
(2, 'postgis'),
(3, 'pgbackrest'),
(4, 'patroni');
-- the user typed 'postgreql': ascending levenshtein distance puts the closest match first
SELECT product_id,
name,
levenshtein(lower(name), 'postgreql') AS edit_distance
FROM products
ORDER BY edit_distance
LIMIT 3;How the snippet works
Breaking the statements into their working parts: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Using it
Point it at the products table — the LIMIT keeps the probe cheap while you tune the predicates.
Key statements
SELECT product_id,
name,
levenshtein(lower(name), 'postgreql') AS edit_distance
FROM products
ORDER BY edit_distance
LIMIT 3;
INSERT INTO products (product_id, name) VALUES
(1, 'postgresql'),
(2, 'postgis'),
(3, 'pgbackrest'),
(4, 'patroni');
CREATE TABLE products (
product_id int PRIMARY KEY,
name text NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What relations does the SQL touch?
- The references are `products`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.