brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a partial index in SQLite only covers the rows your queries ask for

Sqlite
~/tips/tip-sqlite-partial-index

CREATE INDEX users_active_email ON users(email) WHERE active = 1;

Indexes only rows that match a WHERE clause, so the index stays small and fast.

When nearly every query filters on the same condition, like active users or open orders, an index over the whole table carries a lot of rows you never look up. SQLite can index just the part you use.

CREATE INDEX users_active_email ON users(email) WHERE active = 1;
EXPLAIN QUERY PLAN SELECT * FROM users WHERE active = 1 AND email > 'a';
`--SEARCH users USING INDEX users_active_email (email>?)

The index only holds rows where active = 1. It is smaller, faster to search, and writes to inactive rows do not touch it. The plan shows the query uses it.

Another use I like: a unique rule that only applies to some rows. CREATE UNIQUE INDEX ... ON users(email) WHERE deleted_at IS NULL lets a soft-deleted user keep its old address while a new account takes the same one.

The planner has to see that your query’s WHERE implies the index condition, and its logic for that is simple. active = 1 in the query matches. The docs give examples of what does not: SQLite does no algebra, so b=6 in the index is not matched by b=3+3 or b BETWEEN 6 AND 6 in the query, and the index is silently skipped. Write the condition in the query exactly as in the index, and check with EXPLAIN QUERY PLAN. Partial indexes need SQLite 3.8.0 or newer, which anything current has.

Further reading: SQLite partial indexes

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) sqlite> .once users.csv All Sqlite tips (27) All topics

Link