Performance Engineering, FTS5 and JSON

Article · 4:00

EXPLAIN QUERY PLAN and what its three lines actually tell you, covering indexes, ANALYZE, full-text search with FTS5, and indexed JSON.

EXPLAIN QUERY PLAN is short and dense. Unlike PostgreSQL's plans it gives you a few lines, and the words in them matter precisely. SCAN table means every row was examined - acceptable on a small table, a problem on a large one. SEARCH table USING INDEX ix (col=?) means an index was used. USING COVERING INDEX is the best outcome: every column the query needed was in the index, so the table itself was never touched. USE TEMP B-TREE FOR ORDER BY means SQLite sorted at runtime because no index provided the order - frequently the cheapest thing to fix.

SQLite uses at most one index per table per query. This is a genuine architectural difference from PostgreSQL, which can combine two indexes with a bitmap. The practical consequence is that composite indexes matter more here: if you filter on two columns, one index on both beats two indexes on one each, every time.

ANALYZE collects statistics into sqlite_stat1, which the planner uses to choose between available indexes. On a database whose data distribution changed substantially since the last run, the planner is choosing on stale information. Run it after bulk loads.

FTS5 is a virtual table implementing a full-text index. It is fast, supports phrase queries, prefix matching, boolean operators and NEAR, and gives you bm25() ranking and snippet() highlighting. The standard pattern is an external content table: FTS5 indexes a column of an existing table rather than duplicating it, kept in sync by triggers. The trap is that external content tables do not update themselves - if you forget the triggers, search silently returns stale results.

JSON is stored in TEXT and queried with json_extract. -> and ->> operators arrived in 3.38. The important performance point: json_extract in a WHERE clause means a full scan unless you create an expression index on exactly the same expression.

Laboratory exercise 4 - a measured improvement.

Load at least 500,000 rows with a realistic distribution - skewed, not uniform, because uniform data makes every index look good. Declare a baseline: five queries from your capstone, measured for p50, p95 and p99 latency and throughput, with EXPLAIN QUERY PLAN captured for each.

Apply the techniques one at a time, re-measuring after each: a composite index chosen from the plan, a covering index, ANALYZE, an FTS5 index for the note search, and an expression index for a JSON predicate.

Include at least one change that did not help, and explain why from the query plan.

Deliverable: the benchmark report with all three percentiles at each step, before-and-after plans for every query, the file size after each index, and your explanation of the change that did not work.

-- ------------------------------------------------------------------
-- Reading the plan. Short, dense, and every word means something.
-- ------------------------------------------------------------------
EXPLAIN QUERY PLAN
SELECT e.spent_at, e.amount_minor, c.name
FROM expense e JOIN category c ON c.id = e.category_id
WHERE e.spent_at >= '2026-06-01' AND e.category_id = 2
ORDER BY e.spent_at DESC;

-- Before any index:
--   SCAN e                                    <- every row examined
--   SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
--   USE TEMP B-TREE FOR ORDER BY              <- sorted at runtime
--
-- SQLite uses AT MOST ONE INDEX PER TABLE PER QUERY. PostgreSQL can
-- combine two with a bitmap; SQLite cannot. So a composite index is
-- not an optimisation here, it is the only option:
CREATE INDEX expense_cat_date ON expense (category_id, spent_at DESC);
--                                        ^^^^^^^^^^^ equality first,
--                                        range/order last. Always.

-- After:
--   SEARCH e USING INDEX expense_cat_date (category_id=? AND spent_at>?)
--   SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
--   (the TEMP B-TREE is gone - the index supplies the order)

-- Covering index: add the payload so the table is never read at all.
CREATE INDEX expense_covering
    ON expense (category_id, spent_at DESC, amount_minor);
-- Plan now says USING COVERING INDEX. That is the best outcome
-- available, and on a wide table it is frequently 5-10x.

-- Statistics. The planner chooses between indexes using these, and
-- after a bulk load they are wrong.
ANALYZE;
SELECT * FROM sqlite_stat1;

-- ------------------------------------------------------------------
-- FTS5: real full-text search.
-- ------------------------------------------------------------------
CREATE VIRTUAL TABLE expense_fts USING fts5(
    description,
    content = 'expense',        -- EXTERNAL CONTENT: index the existing
    content_rowid = 'id',       -- table rather than duplicating it
    tokenize = 'porter unicode61'   -- porter: 'running' matches 'run'
);

-- External content tables DO NOT maintain themselves. Forget these
-- triggers and search silently returns stale results - no error, just
-- rows that are no longer there and rows that are missing.
CREATE TRIGGER expense_fts_insert AFTER INSERT ON expense BEGIN
    INSERT INTO expense_fts (rowid, description) VALUES (NEW.id, NEW.description);
END;
CREATE TRIGGER expense_fts_delete AFTER DELETE ON expense BEGIN
    INSERT INTO expense_fts (expense_fts, rowid, description)
        VALUES ('delete', OLD.id, OLD.description);
END;
CREATE TRIGGER expense_fts_update AFTER UPDATE ON expense BEGIN
    INSERT INTO expense_fts (expense_fts, rowid, description)
        VALUES ('delete', OLD.id, OLD.description);
    INSERT INTO expense_fts (rowid, description) VALUES (NEW.id, NEW.description);
END;

INSERT INTO expense_fts (expense_fts) VALUES ('rebuild');   -- initial build

-- Querying it. bm25() ranks; lower is better, so ORDER BY rank.
SELECT e.id, e.spent_at, e.amount_minor,
       snippet(expense_fts, 0, '[', ']', '...', 12) AS excerpt,
       bm25(expense_fts) AS rank
FROM expense_fts
JOIN expense e ON e.id = expense_fts.rowid
WHERE expense_fts MATCH 'coffee OR lunch'
ORDER BY rank
LIMIT 20;

-- The query syntax is richer than LIKE will ever be:
--   'coffee lunch'       both terms, anywhere
--   '"flat white"'       the exact phrase
--   'cof*'               prefix
--   'coffee NOT instant'
--   'NEAR(coffee shop, 5)'   within five tokens of each other
--   'description : coffee'   restricted to one column

-- ------------------------------------------------------------------
-- JSON, and the index it needs to be usable.
-- ------------------------------------------------------------------
SELECT id, metadata ->> '$.merchant' AS merchant        -- 3.38+
FROM expense
WHERE metadata ->> '$.reimbursable' = 'true';
-- Plan: SCAN expense. Every row's JSON is parsed. On 500k rows this
-- is seconds, not milliseconds.

-- An expression index on EXACTLY the same expression:
CREATE INDEX expense_merchant
    ON expense (json_extract(metadata, '$.merchant'));

EXPLAIN QUERY PLAN
SELECT id FROM expense WHERE json_extract(metadata, '$.merchant') = 'Pret';
--   SEARCH expense USING INDEX expense_merchant (<expr>=?)
--
-- The expression must MATCH. Indexing json_extract(...) and then
-- querying with ->> uses no index, because the planner matches on the
-- expression's text, not on its meaning.

-- ------------------------------------------------------------------
-- Bulk loading, which is a performance topic of its own.
-- ------------------------------------------------------------------
PRAGMA journal_mode = MEMORY;   -- temporarily; NOT crash-safe
PRAGMA synchronous = OFF;       -- temporarily; NOT crash-safe
BEGIN;
  -- ... many inserts in ONE transaction. Each autocommitted insert is
  -- its own fsync; 100k of them is 100k fsyncs and takes minutes.
COMMIT;
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
ANALYZE;
-- Create the indexes AFTER the load, not before. Building an index
-- once over sorted data beats maintaining it through 500k inserts.

Discussion

No questions on this topic yet. Sign in to ask the first one.