← Back to SQL, page 20

sql-0385 · Medium mid

Show full-text search in SQLite with the FTS5 module.

Create a virtual table with USING fts5(...), insert documents, and query with MATCH. FTS5 supports phrase queries, prefix searches such as 'data*', boolean operators and ranking with bm25 through the hidden rank column, ordered ascending because lower is better.

Full answer
sql
CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (rowid, title, body) VALUES (1, 'Indexes', 'An index speeds up lookups'), (2, 'Joins', 'A left join keeps unmatched rows'), (3, 'Tuning', 'Too many indexes slow writes');
sql
SELECT rowid, title FROM notes WHERE notes MATCH 'index*' ORDER BY rank;
rowidtitle
1Indexes
3Tuning

The prefix query index* matches 'index' and 'indexes', so documents 1 and 3 are returned, best match first by FTS5's built-in rank.

sql
SELECT rowid, title FROM notes WHERE notes MATCH '"left join"';
rowidtitle
2Joins

A quoted phrase must appear as consecutive words, so only document 2 matches. The default tokenizer (unicode61) is case-insensitive and does not stem; tokenize = 'porter unicode61' adds English stemming. For an existing table, an external-content FTS table plus triggers keeps the index in sync without storing text twice. These runs used the FTS5 module compiled into SQLite 3.46.1 here; some builds omit it.

sql
CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (rowid, title, body) VALUES (1, 'Indexes', 'An index speeds up lookups'), (2, 'Joins', 'A left join keeps unmatched rows'), (3, 'Tuning', 'Too many indexes slow writes');

SELECT rowid, title FROM notes WHERE notes MATCH 'index*' ORDER BY rank;

SELECT rowid, title FROM notes WHERE notes MATCH '"left join"';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FTS5 is a virtual table queried with MATCH
  • Prefix and phrase queries are supported
  • ORDER BY rank sorts by bm25 relevance
  • Porter tokenizer adds stemming
  • External-content tables avoid duplicate storage

Common mistakes

  • Using LIKE for search on large text in SQLite
  • Forgetting that FTS5 may be missing in some builds

Follow-ups

  • How would you keep an FTS index in sync with a normal table?
  • How would you highlight matches?

Tips

  • Show prefix and phrase queries