Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 117/ 160
06. Database Design, Normalization & Semi-Structured SQL

Full-Text Search in SQL (tsvector, tsquery, GIN Search Indexes)

Build ranked full-text search with tsvector/tsquery and GIN indexes.

Advancedtsvector · tsquery3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Setting up a searchable columnQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE articles2ADD COLUMN search tsvector GENERATED ALWAYS AS (3  to_tsvector(4    'english',5    coalesce(title, '') || ' ' || coalesce(body, '')6  )7) STORED;89CREATE INDEX articles_search_idx ON articles USING gin (search);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ALTER TABLE CREATE INDEX

Note: Representative PostgreSQL statuses; adding the STORED generated column rewrites or reads existing rows and index-build time depends on table size.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Highlighting matchesQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  title,3  ts_headline(4    'english',5    body,6    websearch_to_tsquery('english', 'refund')7  ) AS snippet8FROM9  articles10WHERE11  search @@ websearch_to_tsquery('english', 'refund')12LIMIT13  10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
titlesnippet
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Built-in search covers most apps; reach for a search engine for typos, facets and scale.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Choose the searchable fields

Decide which columns to search and which matter most, such as title above body.

Focus at this step

title (weight A) · body (weight B)

What to watch at this step
Weights
A–D
Tip: use ← → to move between steps

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

LIKE / ILIKE (+ pg_trgm)
Best for: Substring and code lookups, autocomplete

Strengths: Matches any part of a string; trigram indexes make it fast.

Watch out: No stemming or relevance ranking.

PostgreSQL full-text search
Best for: Searching articles, descriptions and tickets inside the app database

Strengths: Stemming, ranking, GIN indexes; no extra system.

Watch out: No built-in typo tolerance, facets or synonyms tuning.

Elasticsearch / OpenSearch / Meilisearch
Best for: Large-scale or feature-rich search

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?
Interview tip: Describe the four pieces (tsvector column, GIN index, websearch_to_tsquery, ts_rank) and one limit. It's a complete, practical answer.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Working with SQL Arrays (ARRAY_AGG, UNNEST, ANY, Array Operators)
Next topic
Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries)