Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Implement product search on name and description in PostgreSQL that handles word stems, ranks results and is fast on 5 million rows. Show the column, index and query.

We add a stored generated tsvector column that combines name with weight A and description with weight B, put a GIN index on it, and query with search @@ websearch_to_tsquery('english', :q), ordered by ts_rank and limited to 20 rows. The english text search configuration handles stemming and stop words, and pg_trgm with a trigram GIN index covers substring and typo matching, which LIKE '%term%' with a B-tree index cannot do.

Why this question is asked

Product search is one of the first features where a plain LIKE query stops being good enough. Users type "running shoe" and expect to find "Runners' Shoes", they expect the best matches first, and on five million rows they expect it in milliseconds. Interviewers ask this coding question because it shows whether we know PostgreSQL's built-in full-text search well enough to build it correctly: the column, the index and the query all have to fit together. In this answer, we will recap how text search turns words into searchable tokens, build the generated column, add the index, write the ranked query, see why LIKE is slow, and add trigram matching for typos.

1A Quick Recap of tsvector and tsquery

PostgreSQL full-text search works on two types. A tsvector is a document turned into a sorted list of lexemes, the normalized forms of words, with their positions. A tsquery is a search turned into lexemes joined by operators such as & (and), | (or) and ! (not). The @@ operator asks whether a tsvector matches a tsquery.

The text search configuration, such as 'english', decides how words become lexemes. It lowercases them, removes stop words, common words like "the" and "and" that carry no meaning for search, and stems the rest, which means reducing "running" and "runs" to "run". A different configuration, such as 'german' or 'simple', gives different results, so the configuration is part of the design, not a detail.

SQL
SELECT to_tsvector('english', 'The Running Shoes for runners');
-- 'run':2,5 'shoe':3 "the" and "for" are stop words; running and runners both become run
SELECT websearch_to_tsquery('english', 'running shoes -red');
-- 'run' & 'shoe' & !'red'
SELECT to_tsvector('english', 'Running shoes') @@ websearch_to_tsquery('english', 'run shoe');
-- true

Notice that the stemmer works on both sides. The document and the query are reduced the same way, so "running shoes" matches "run shoe". That is the stem handling the question asks for.

2Adding the Search Column

We could compute to_tsvector inside every query, but on five million rows that means parsing every description on every search. Instead we store the result in a generated column, which PostgreSQL keeps up to date on every insert and update. We combine both fields and give them weights with setweight: A for the name and B for the description, so a match in the name will rank higher.

SQL
ALTER TABLE product ADD COLUMN search tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
setweight(to_tsvector('english', coalesce(description, '')), 'B')
) STORED;
SELECT search FROM product WHERE id = 1;
-- 'run':1A,7B 'shoe':2A 'light':5B 'trail':6B

Two details matter here. The coalesce calls are needed because concatenating a NULL tsvector makes the whole result NULL, so a product without a description would vanish from search. And we must pass the configuration name explicitly: the two-argument to_tsvector('english', ...) is immutable, which a generated column requires, while the one-argument form depends on a server setting and is refused. Adding the column rewrites the table once, so on a live system we run it in a maintenance window or add a plain column and fill it in batches.

3Indexing It With GIN

A GIN index on the tsvector column is an inverted index: for every lexeme it keeps the list of rows that contain it. To answer 'run' & 'shoe', PostgreSQL reads two lists and intersects them, without touching rows that match neither word.

SQL
CREATE INDEX CONCURRENTLY product_search_idx ON product USING gin (search);

CONCURRENTLY builds the index without blocking writes, at the cost of a slower build. On five million products, the index makes finding the matching rows a matter of milliseconds for selective words.

4Writing the Ranked Query

Now the query. websearch_to_tsquery accepts the kind of text people type into a search box, with quoted phrases and a minus sign for exclusion, and it never raises a syntax error, which plain to_tsquery does on input like 'shoe &'. ts_rank scores each match, giving more weight to A lexemes than B lexemes, and we keep the best 20.

SQL
SELECT id, name, ts_rank(search, q) AS rank
FROM product, websearch_to_tsquery('english', :q) AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;
-- :q = 'running shoes'
-- 812 | Running Shoes Pro | 0.98
-- 77 | Trail Shoes | 0.61
-- 4021| Socks for running shoes| 0.24
Step throughHow one search runs
  1. Turn the input into a tsquerywebsearch_to_tsquery('english', 'running shoes')
  2. Look up lexemes in the GIN indexlists for 'run' and 'shoe'
  3. Intersect the listscandidate rows only
  4. Rank each candidatets_rank, name weight A beats description B
  5. Sort and keep 20top-N sort over the candidates

5 steps in order. Play them, or step through them one at a time.

Notice that we compute the tsquery once in the FROM clause and reuse it. The reason this is fast is that the WHERE clause uses the GIN index to find matching rows, and ts_rank is computed only for those. But there is a catch: if the search term is very common, say "black" with 800,000 matches, PostgreSQL must rank all 800,000 rows before it can return the top 20. For such cases we can require a minimum length of query, add a category filter, or accept ordering by a cheaper signal such as popularity.

5Why LIKE Is Slow and Where Trigrams Help

The query people write first is WHERE name ILIKE '%shoe%'. A B-tree index stores values sorted from their first character, so it can serve 'shoe%' but not a pattern that starts with a wildcard. PostgreSQL must read all five million rows. LIKE also knows nothing about stems or ranking.

Full-text search has its own gap: it matches whole lexemes, so "sho" or the typo "shoos" finds nothing. The pg_trgm extension fills that gap. It splits text into trigrams, groups of three characters, and a GIN trigram index can then serve LIKE '%sho%' and similarity searches that tolerate typos.

SQL
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX product_name_trgm ON product USING gin (name gin_trgm_ops);
SELECT name FROM product WHERE name ILIKE '%sho%' LIMIT 5; -- uses product_name_trgm
SELECT name, similarity(name, 'runing shoos') AS s
FROM product WHERE name % 'runing shoos'
ORDER BY s DESC LIMIT 5;
-- Running Shoes Pro | 0.45

In practice many shops combine them: full-text search first, and when it returns nothing, a trigram query on the name as a "did you mean" fallback.

6Follow-up questions

How would you support products in several languages?

Store the language per product and build the tsvector with that configuration, for example a regconfig column used in to_tsvector(lang, ...), and parse the query with the user's language. Mixing languages in one configuration gives poor stemming.

What is the difference between ts_rank and ts_rank_cd?

ts_rank scores by how often query lexemes appear and their weights. ts_rank_cd, cover density, also rewards matches that are close together, which suits phrase-like queries but needs position information and costs a little more.

When does PostgreSQL text search stop being enough?

When the product needs synonyms managed by merchandisers, facets with counts, learning-to-rank, or heavy typo tolerance across languages. Those are the strengths of a search engine such as Elasticsearch or OpenSearch.

7Conclusion

In this answer, we built product search in PostgreSQL. A stored generated tsvector column combines the name with weight A and the description with weight B, using the explicit english configuration that decides stemming and stop words. A GIN index finds matching rows quickly, and the query filters with search @@ websearch_to_tsquery, orders by ts_rank and takes 20 rows. We also saw that LIKE '%term%' cannot use a B-tree index and that pg_trgm with a trigram GIN index adds substring and typo-tolerant matching.

What to say in the interviewAbout 80 seconds aloud

Open with

I would add a stored generated column of type tsvector that concatenates setweight of to_tsvector english on the name with weight A and the same on the description with weight B, with coalesce around each field so a missing description does not make the whole vector NULL.

Then, if they want more

The configuration has to be explicit, because only the two-argument to_tsvector is immutable and allowed in a generated column, and it is the configuration that decides stemming and stop words, so running and runners both become run. Then I create a GIN index on that column, concurrently on a live table.

The query filters with search matches websearch_to_tsquery english of the user input, which accepts quotes and minus signs without syntax errors, orders by ts_rank descending and limits to 20. The GIN index finds the candidates quickly, and only those are ranked.

I would mention the catch that a very common term means ranking many rows, so I might add filters for that case. And I would explain that LIKE with a leading wildcard cannot use a B-tree index and scans everything, so for substring and typo matching I would add pg_trgm with a trigram GIN index, often as a did-you-mean fallback.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement product search on name and description in PostgreSQL that handles word stems...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/0233acc261/