SQLite Full-Text Search (FTS5) Cheatsheet

FTS5 virtual tables, MATCH queries, prefix search, phrase search, bm25 ranking, snippets, and highlighting patterns for SQLite search features.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Create FTS5 tables
Create an FTS5 virtual table
CREATE VIRTUAL TABLE docs USING fts5(title, body);

# Store searchable text in an FTS5 index.

Insert searchable content
INSERT INTO docs (title, body)
VALUES ('SQLite WAL guide', 'Write-ahead logging improves concurrency for many app workloads.');

# Add rows to an FTS5 table.

Use an external content table pattern
CREATE TABLE articles (
  id INTEGER PRIMARY KEY,
  title TEXT,
  body TEXT
);
CREATE VIRTUAL TABLE articles_fts USING fts5(
  title,
  body,
  content='articles',
  content_rowid='id'
);

# Separate storage from the FTS index when needed.

## Search, rank, and highlight
Search with MATCH
SELECT rowid, title FROM docs WHERE docs MATCH 'sqlite';

# Find rows containing a term.

Rank results with bm25()
SELECT rowid, title, bm25(docs) AS rank
FROM docs
WHERE docs MATCH 'sqlite wal'
ORDER BY rank;

# Sort by relevance score.

Highlight matches or return snippets
SELECT title,
       highlight(docs, 1, '<mark>', '</mark>') AS highlighted_body,
       snippet(docs, 1, '<b>', '</b>', '…', 12) AS excerpt
FROM docs
WHERE docs MATCH 'sqlite';

# Decorate matched terms in search output.

Recommended next

No recommendations yet.