← Blog
A fan of similar purple paint swatches joined by an orange pin.
Published on
2026-11-25

Find misspelled product names in PostgreSQL with pg_trgm

A customer types coper kettle. Your catalog contains a copper kettle, its replacement lid, a copper bottle and a travel kettle. Which results belong on the screen? PostgreSQL’s pg_trgm extension can find all four from the spelling alone. Whether it should show all four is a catalog decision you can test.

Look up product codes exactly and names approximately

If the customer scans a barcode or types a complete SKU, start with equality on the identifier. In our example, the primary key P-104 identifies the kettle. Its lid has a different SKU. Offering the lid as a spelling correction for a valid product code would turn a successful lookup into a wrong order.

CREATE EXTENSION IF NOT EXISTS pg_trgm;

SELECT sku, name
FROM catalog
WHERE sku = 'P-104';

Use trigram search for the name field. PostgreSQL splits words into overlapping groups of three characters, including padding at word boundaries. A missing letter disrupts some groups while leaving others intact. similarity() scores the overlap on a scale from zero to one. A score of 0.8 describes the two strings. It does not mean an 80% chance that the shopper wants that item. The PostgreSQL pg_trgm reference explains how spaces, punctuation and word boundaries affect the comparison.

Filter candidates before showing the best matches

The % operator tests each name against the active similarity threshold. Rank the surviving names by their unrounded score and use the SKU to break ties. Round only the value you display. In a pooled connection, SET LOCAL inside a transaction keeps one search’s threshold from changing the next customer’s results.

PREPARE candidates(text) AS
SELECT sku, name, round(similarity(name, $1)::numeric, 3) AS score
FROM catalog
WHERE name % $1
ORDER BY similarity(name, $1) DESC, sku
LIMIT 5;

BEGIN;
SET LOCAL pg_trgm.similarity_threshold = 0.30;
EXECUTE candidates('coper kettle');
COMMIT;

We ran three labeled searches on PostgreSQL 18.6. The table held five named products and 20,000 synthetic workshop parts. For the first two queries, the intended item was the kettle itself. The third query described an item the shop did not carry.

  • coper kettle. At 0.30 the results were Copper kettle (0.800), Copper kettle lid (0.632), Copper bottle (0.421) and Travel kettle (0.350), in that order. At 0.60 only the kettle and its lid qualified. A stricter cutoff still admitted the accessory.
  • copr ketl. The intended kettle was the only match at 0.30, scoring 0.333. At 0.60 the query returned nothing. Raising the cutoff to clean up the first search would lose this customer’s best result.
  • quartz violin. Neither threshold returned a product. For this catalog, an empty result was correct.

Use the differences to decide what your interface should do. A suggestions list can display both the kettle and the clearly labeled lid. Automatically adding the top result to a cart demands stronger evidence. Collect real misspellings and confusing pairs such as a product and its spare part, label the expected result, then count missed items and unwanted suggestions separately.

Choose an index for the query you actually run

For a threshold filter, we compared the same query at 0.60 before and after adding a GIN index. PostgreSQL initially scanned all 20,005 rows. With the index, it used a bitmap index scan, rechecked three candidates and returned the same two rows. Run the following comparison with the same threshold and up-to-date statistics on your own table.

CREATE INDEX catalog_name_gin
ON catalog USING gin (name gin_trgm_ops);

EXPLAIN (ANALYZE, BUFFERS)
SELECT sku FROM catalog WHERE name % 'coper kettle';

A different question is “Which three names are closest?” The distance operator <-> orders names from closest to farthest. A GiST trigram index supported an ordered index scan for this query in our test.

CREATE INDEX catalog_name_gist
ON catalog USING gist (name gist_trgm_ops);

SELECT sku, name
FROM catalog
ORDER BY name <-> 'coper kettle'
LIMIT 3;

Distance ordering alone supplies no relevance cutoff. Asked for the three nearest names to quartz violin, PostgreSQL returned three workshop parts, each at a rounded distance of 0.982. Use a threshold when “no match” is a valid answer. Start with the index that fits your query and measure its read benefit and write cost before adding another.

Know when spelling is the wrong signal

A customer searching for “something to boil water” may want the kettle without sharing much of its spelling. That is a different retrieval problem. The guide to hybrid search covers combining keyword and meaning-based matches. If spelling is the problem, test your catalog and expected query mix on a CPU instance from Compute with Hivenet. Record whether the right products appear before comparing latency under concurrent traffic. The local plans above show how PostgreSQL found particular rows in this fixture.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.