Full-Text Search
Full-text search in SQL is finding rows whose text contains certain words, matching different forms of each word and ranking the results by relevance, the way a search box on a website does. It is used to search notes, descriptions, articles and messages. LIKE '%word%' looks similar but only matches characters: it finds "art" inside "start", misses "studies" when you search for "study", and can't say which result is best. In this lesson, we will see exactly where LIKE fails, then use PostgreSQL's tsvector and tsquery to search by words, rank the results, highlight matches and index the search.
In One Minute
to_tsvector('english', text)turns text into lexemes: normalized word stems such asstudifor "study" and "studies".to_tsqueryorwebsearch_to_tsqueryturns a search into a query of lexemes.vector @@ queryis true when the text matches.ts_rankscores matches so the best come first;ts_headlinehighlights them.- A GIN index on a
tsvectormakes search fast on large tables.
The Course Notes
The examples search six short notes, one per course:
CREATE TABLE course_notes (
course_id INTEGER PRIMARY KEY REFERENCES courses (course_id),
body TEXT NOT NULL
);
INSERT INTO course_notes VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(2, 'Classes and objects. We model a party of students as objects and study inheritance.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(4, 'Querying tables with SELECT and joining them. Joins connect students to payments.'),
(5, 'Functions and the DOM. Students join a weekly coding club.'),
(6, 'Commits, branches and merging. Start small and commit often.');Why LIKE Is Not Search
CREATE TABLE course_notes (course_id INTEGER PRIMARY KEY REFERENCES courses (course_id), body TEXT NOT NULL);
INSERT INTO course_notes VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(2, 'Classes and objects. We model a party of students as objects and study inheritance.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(4, 'Querying tables with SELECT and joining them. Joins connect students to payments.'),
(5, 'Functions and the DOM. Students join a weekly coding club.'),
(6, 'Commits, branches and merging. Start small and commit often.');
SELECT course_id FROM course_notes WHERE body ILIKE '%art%' ORDER BY course_id;
SELECT course_id FROM course_notes WHERE body ILIKE '%study%' ORDER BY course_id;CREATE TABLE
INSERT 0 6
course_id
-----------
1
2
6
(3 rows)
course_id
-----------
1
2
(2 rows)Explanation: No note is about art, yet '%art%' matches "Start" and "party". And '%study%' misses note 3, because "Studies" doesn't contain the letters "study". LIKE compares characters, not words. It also can't rank results, and a pattern starting with % can't use a B-tree index, as LIKE and Wildcards showed.
Words, Stems and Queries
to_tsvector breaks text into words, drops common "stop words" like and and the, and reduces each word to its stem:
SELECT to_tsvector('english', 'Students study small programs every week.') AS lexemes;
SELECT to_tsquery('english', 'studies') AS query; lexemes
----------------------------------------------------------------
'everi':5 'program':4 'small':3 'student':1 'studi':2 'week':6
(1 row)
query
---------
'studi'
(1 row)Explanation: "Students" became student, "study" became studi, "programs" became program, and "every" became everi: stems are a search key, not always a real word. Each lexeme keeps its position in the text (:1, :2...). The query "studies" reduces to the same stem, studi, so it matches "study", "studies" and "studied". The 'english' configuration chooses English stemming rules and stop words; PostgreSQL ships with configurations for about 30 languages.
Searching with @@
@@ tests whether a text search vector matches a query:
CREATE TABLE course_notes (course_id INTEGER PRIMARY KEY REFERENCES courses (course_id), body TEXT NOT NULL);
INSERT INTO course_notes VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(2, 'Classes and objects. We model a party of students as objects and study inheritance.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(4, 'Querying tables with SELECT and joining them. Joins connect students to payments.'),
(5, 'Functions and the DOM. Students join a weekly coding club.'),
(6, 'Commits, branches and merging. Start small and commit often.');
SELECT course_id FROM course_notes
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'study')
ORDER BY course_id;
SELECT course_id FROM course_notes
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'students join -club')
ORDER BY course_id;CREATE TABLE
INSERT 0 6
course_id
-----------
1
2
3
(3 rows)
course_id
-----------
4
(1 row)Explanation: The first search finds all three notes about studying, including "Studies" in note 3. The second uses websearch_to_tsquery, which understands search-box syntax: words are combined with AND, -club excludes a word, and "quoted phrases" must appear together. Note 4 matches "students" and "joining"; note 5 is excluded by -club.
to_tsquery syntax | Means |
|---|---|
study & map | Both words |
study | map | Either word |
!club | Not this word |
inner <-> join | "inner" followed by "join" |
stud:* | Words starting with stud |
Ranking and Highlighting
ts_rank scores how well each row matches, and ts_headline marks the matching words:
CREATE TABLE course_notes (course_id INTEGER PRIMARY KEY REFERENCES courses (course_id), body TEXT NOT NULL);
INSERT INTO course_notes VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(2, 'Classes and objects. We model a party of students as objects and study inheritance.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(4, 'Querying tables with SELECT and joining them. Joins connect students to payments.'),
(5, 'Functions and the DOM. Students join a weekly coding club.'),
(6, 'Commits, branches and merging. Start small and commit often.');
SELECT course_id,
round(ts_rank(to_tsvector('english', body), q)::NUMERIC, 4) AS rank,
ts_headline('english', body, q, 'StartSel=[, StopSel=]') AS snippet
FROM course_notes, websearch_to_tsquery('english', 'join') AS q
WHERE to_tsvector('english', body) @@ q
ORDER BY rank DESC, course_id;CREATE TABLE
INSERT 0 6
course_id | rank | snippet
-----------+--------+---------------------------------------------------------------------------------------
4 | 0.0760 | Querying tables with SELECT and [joining] them. [Joins] connect students to payments.
5 | 0.0608 | Functions and the DOM. Students [join] a weekly coding club.
(2 rows)Explanation: Note 4 mentions joining twice ("joining" and "Joins"), so it ranks above note 5, which mentions it once. ts_headline wraps each matching word, here in square brackets, which a web page could turn into bold text. Putting the query in the FROM clause as q lets the query be written once and used three times.
Indexing Search
Computing to_tsvector for every row on every search is slow on big tables. Store the vector in a generated column and index it with GIN:
CREATE TABLE course_notes (
course_id INTEGER PRIMARY KEY REFERENCES courses (course_id),
body TEXT NOT NULL,
search TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', body)) STORED
);
INSERT INTO course_notes (course_id, body) VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(6, 'Commits, branches and merging. Start small and commit often.');
CREATE INDEX course_notes_search_idx ON course_notes USING GIN (search);
SET enable_seqscan = off;
EXPLAIN (COSTS OFF)
SELECT course_id FROM course_notes WHERE search @@ to_tsquery('english', 'study');CREATE TABLE
INSERT 0 3
CREATE INDEX
SET
QUERY PLAN
------------------------------------------------------
Bitmap Heap Scan on course_notes
Recheck Cond: (search @@ '''studi'''::tsquery)
-> Bitmap Index Scan on course_notes_search_idx
Index Cond: (search @@ '''studi'''::tsquery)
(4 rows)Explanation: The search column is computed from body automatically on every insert and update; Generated Columns and Domains explains how. The GIN index lists every lexeme with the rows containing it, so the Bitmap Index Scan finds matching notes without reading the rest. As in JSON in SQL, enable_seqscan = off is only here because a three-row table would otherwise just be scanned.
Full-Text Search in Other Databases
| Database | Set up | Search |
|---|---|---|
| PostgreSQL | GIN index on a tsvector | search @@ websearch_to_tsquery('english', 'study') |
| MySQL | FULLTEXT INDEX (body) | MATCH (body) AGAINST ('study' IN NATURAL LANGUAGE MODE) |
| SQL Server | A full-text catalog and full-text index | CONTAINS(body, 'study'), FREETEXT(body, 'study') |
| Oracle | An Oracle Text CONTEXT index | CONTAINS(body, 'study') > 0 |
Tabs showing each database's version are coming to this course.
Common Mistakes
Using LIKE '%word%' for search. It matches parts of words, misses word forms and can't rank.
Mixing configurations. A vector built with 'english' and a query with 'simple' won't match stems. Use the same configuration on both sides.
Passing user input to to_tsquery. Text like java & is a syntax error there; use websearch_to_tsquery.
Computing to_tsvector on every search. Store it in an indexed column.
Interview Corner
Why not use LIKE for searching text?
LIKE matches characters, so it finds words inside other words, misses different forms of a word, can't rank results, and can't use a normal index with a leading %.
What are tsvector and tsquery?
A tsvector is text processed into normalized lexemes with positions; a tsquery is a search expression of lexemes with AND, OR, NOT and phrase operators. @@ tests whether they match.
How do you make full-text search fast in PostgreSQL?
Store the tsvector (for example, in a generated column) and create a GIN index on it.
Practice
Challenge: Find the notes that mention starting or committing, using to_tsquery with |, and show each match highlighted, ordered by course.
Show solution
CREATE TABLE course_notes (course_id INTEGER PRIMARY KEY REFERENCES courses (course_id), body TEXT NOT NULL);
INSERT INTO course_notes VALUES
(1, 'Start here: variables, loops and methods. Students study small programs every week.'),
(2, 'Classes and objects. We model a party of students as objects and study inheritance.'),
(3, 'Lists, sets and maps. Studies show practice with maps pays off.'),
(4, 'Querying tables with SELECT and joining them. Joins connect students to payments.'),
(5, 'Functions and the DOM. Students join a weekly coding club.'),
(6, 'Commits, branches and merging. Start small and commit often.');
SELECT course_id,
ts_headline('english', body, q, 'StartSel=[, StopSel=]') AS snippet
FROM course_notes, to_tsquery('english', 'start | commit') AS q
WHERE to_tsvector('english', body) @@ q
ORDER BY course_id;CREATE TABLE
INSERT 0 6
course_id | snippet
-----------+---------------------------------------------------------------------------------------
1 | [Start] here: variables, loops and methods. Students study small programs every week.
6 | [Commits], branches and merging. [Start] small and [commit] often.
(2 rows)Note 1 starts with "Start", and note 6 has "Commits", "Start" and "commit". Note 2's "party" isn't a match this time, because search compares whole words.
Key Takeaways
| You want to | Write |
|---|---|
| Search words | to_tsvector('english', body) @@ websearch_to_tsquery('english', 'study') |
| Rank results | ORDER BY ts_rank(vector, query) DESC |
| Highlight | ts_headline('english', body, query) |
| Index search | search TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', body)) STORED + USING GIN (search) |
Was this tutorial helpful?