Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
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.
- Turn the input into a tsquery
websearch_to_tsquery('english', 'running shoes') - Look up lexemes in the GIN indexlists for 'run' and 'shoe'
- Intersect the listscandidate rows only
- Rank each candidatets_rank, name weight A beats description B
- 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.
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.
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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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/