Fuzzystrmatch Levenshtein Typo Ranking

Rank products against a misspelled query by levenshtein edit distance from the fuzzystrmatch extension, nearest match first.

SqlData Fetching

Code

snippet
-- 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

FAQ

What relations does the SQL touch?
The references are `products`.