Full-Text Search in SQL (tsvector, tsquery, GIN Search Indexes)
Build ranked full-text search with tsvector/tsquery and GIN indexes.
In plain words
Full-text search breaks text into simple root words and looks those up, so searching "run" also finds "running".
Think of it like…
A book's index rather than reading every page: it lists each important word once, in its root form, with the pages it appears on, so "cooking", "cooked" and "cook" all lead to the same entries.
Where you’ve seen it
Searching help articles: SELECT id, title, ts_rank(search, q) AS rank FROM articles, websearch_to_tsquery('english', 'refund delayed payment') q WHERE search @@ q ORDER BY rank DESC LIMIT 20;, where search is a stored tsvector column with a GIN index.
Words you’ll hear
- tsvector
- A document as a sorted list of normalised lexemes (word stems), with positions.
- tsquery
- A search query of lexemes combined with & (and), | (or), ! (not) and <-> (followed by).
- @@
- The match operator: tsvector @@ tsquery.
- websearch_to_tsquery
- Turns user-style input (quotes, or, minus) into a tsquery safely (PostgreSQL 11+).
Visual diagram
Theory & example queries
tsvector, tsquery and matching
to_tsvector('english', text) lowercases the text, splits it into words, removes stop words and reduces each word to its stem using the English dictionary. to_tsquery('english', 'refund & delay') does the same to the query, so documents containing "refunds" and "delayed" match. plainto_tsquery and websearch_to_tsquery accept plain user input and are safer than to_tsquery, which errors on stray punctuation.
Rather than computing to_tsvector on every search, store it: search tsvector GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED, then CREATE INDEX ON articles USING gin (search). The weights let ts_rank rank title matches above body matches.
ALTER TABLE articlesADD COLUMN search tsvector GENERATED ALWAYS AS ( to_tsvector( 'english', coalesce(title, '') || ' ' || coalesce(body, '') )) STORED;CREATE INDEX articles_search_idx ON articles USING gin (search);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative PostgreSQL statuses; adding the STORED generated column rewrites or reads existing rows and index-build time depends on table size.
Key takeaway: Store a weighted tsvector, index it with GIN, query with websearch_to_tsquery.
Limits, and when to use a search engine
Full-text search matches words, not arbitrary substrings, so part-words and codes ("SKU-48" inside "SKU-4821") need LIKE with a trigram index. It doesn't correct typos by itself; pg_trgm's similarity functions add fuzzy matching. Each language needs the right text search configuration, and mixed-language content needs care.
PostgreSQL full-text search handles millions of documents well for typical app search. Dedicated engines such as Elasticsearch, OpenSearch or Meilisearch add faceting, typo tolerance, synonyms, analytics and horizontal scaling, at the cost of running and syncing another system. MySQL's FULLTEXT indexes with MATCH(title, body) AGAINST ('refund' IN NATURAL LANGUAGE MODE) provide a simpler built-in alternative.
SELECT title, ts_headline( 'english', body, websearch_to_tsquery('english', 'refund') ) AS snippetFROM articlesWHERE search @@ websearch_to_tsquery('english', 'refund')LIMIT 10;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output2 sample rows
| title | snippet |
|---|---|
| How to request a refund | ...request a <b>refund</b> within 30 days... |
| Refund status FAQ | ...check the <b>refund</b> status in your account... |
Note: Illustrative English full-text matches; highlighting tags, ranking and result count vary with ts_headline options and article content.
Key takeaway: Built-in search covers most apps; reach for a search engine for typos, facets and scale.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the searchable fields
Decide which columns to search and which matter most, such as title above body.
title (weight A) · body (weight B)
When to use it & trade-offs
What it is
Full-text search finds documents by the words they contain rather than exact substrings. PostgreSQL turns text into a tsvector (normalised word stems, so "running" and "runs" both become "run", with stop words like "the" removed) and searches it with a tsquery using the @@ operator. A GIN index makes it fast, and ts_rank orders results by relevance. MySQL has FULLTEXT indexes with MATCH … AGAINST.
Why it matters: Search boxes over articles, products or support tickets need to match words in any form and rank the best results first. LIKE '%word%' can't stem, rank or use a normal index. Built-in full-text search covers many apps without running a separate search engine, and knowing its limits helps you decide when you do need one.
When to reach for it
- Help centres, blogs and documentation search
- Product description search
- Searching support tickets or notes
When to avoid or be careful
- Computing to_tsvector in every query without a stored column and index
- Passing raw user input to to_tsquery
- Expecting full-text search to match parts of words or codes
LIKE vs PostgreSQL full-text search vs a search engine
Strengths: Matches any part of a string; trigram indexes make it fast.
Watch out: No stemming or relevance ranking.
Strengths: Stemming, ranking, GIN indexes; no extra system.
Watch out: No built-in typo tolerance, facets or synonyms tuning.
Strengths: Typo tolerance, facets, synonyms, scaling.
Watch out: Another system to run and keep in sync.
Interview signals & numbers to know
When this topic comes up
- “Add search to the help centre”
- “LIKE '%term%' is too slow”
- “Searching 'run' should find 'running'”
- Relevance ranking
- Elasticsearch vs Postgres
Benchmarks & rules of thumb
- @@
- match operator
- GIN
- index type for tsvector
- PostgreSQL 11
- websearch_to_tsquery added
Common mistakes & follow-ups
Common interview mistakes
- Using to_tsquery on user input and getting syntax errors on characters like ':' or '&'.
- Indexing to_tsvector(body) but querying to_tsvector('english', body), so the index isn't used.
- Expecting a search for 'SKU-48' to find 'SKU-4821'.
Likely interviewer follow-ups
- How does PostgreSQL full-text search differ from LIKE?
- How would you rank title matches above body matches?
- When would you move search to Elasticsearch?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Full-Text Search in SQL (tsvector, tsquery, GIN Search Indexes) with hands-on SQL practice and interview Q&A.