← Back to SQL, page 14

sql-0280 · Medium mid

How do you implement full-text search in SQLite, and why is LIKE '%word%' a poor substitute?

Create an FTS5 virtual table and query it with MATCH, which uses an inverted index of tokens, supports phrases, prefixes and boolean operators, and ranks results with bm25(). LIKE '%word%' scans every row, matches inside other words ('cat' in 'concatenate'), and offers no ranking.

Full answer
sql
CREATE VIRTUAL TABLE docs USING fts5(title, body);
INSERT INTO docs VALUES ('Indexes', 'An index speeds up lookups'), ('Joins', 'Join tables on keys'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text');
SELECT title FROM docs WHERE docs MATCH 'index' ORDER BY rank;
title
Indexes
Plans

MATCH 'index' found both posts with the word, ranked by relevance; ORDER BY rank uses bm25 by default. A substring LIKE would also match words that merely contain the letters:

sql
SELECT title FROM docs WHERE body LIKE '%cat%' ORDER BY title;
title
Strings

'concatenate' matched %cat%, which a word-based search would not do. FTS5 also supports "exact phrase", prefix* and NEAR.

PostgreSQL's equivalent is to_tsvector(...) @@ to_tsquery(...) with a GIN index:

sql
SELECT title FROM (VALUES ('Indexes', 'An index speeds up lookups'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text')) AS d(title, body)
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'index')
ORDER BY title;
title
Indexes
Plans
sql
CREATE VIRTUAL TABLE docs USING fts5(title, body);
INSERT INTO docs VALUES ('Indexes', 'An index speeds up lookups'), ('Joins', 'Join tables on keys'), ('Plans', 'Read the plan to see if an index is used'), ('Strings', 'Use concatenate to join text');
SELECT title FROM docs WHERE docs MATCH 'index' ORDER BY rank;

SELECT title FROM docs WHERE body LIKE '%cat%' ORDER BY title;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • FTS5 builds an inverted token index
  • MATCH supports phrases, prefixes and boolean operators
  • bm25 ranks results
  • LIKE '%x%' scans and matches inside words

Common mistakes

  • Building search on LIKE for large text
  • Forgetting to keep the FTS table in sync with the source

Follow-ups

  • How would you keep an FTS table in sync with triggers?
  • How do stemming and stop words change results?

Tips

  • Show a false positive from LIKE