PREP WITH PROOF
Menu
SQLITE & QUERY PERFORMANCE / PRACTICAL GUIDE

SQLite Partial Index Not Used? Check WHERE and Query Plans

Diagnose SQLite partial indexes with an executable lab. Compare equivalent predicates, bound values, broader filters, and EXPLAIN QUERY PLAN.

THE QUICK ANSWER

A SQLite partial index can serve a query only when SQLite can establish that the qualifying rows belong to the index subset. Equivalent-looking predicates can produce different plans. Compare the actual WHERE clause, bindings, and EXPLAIN QUERY PLAN while verifying that any rewrite still returns the required rows.

The index exists. Why does the query still scan?

A worker polls a jobs table for the next ready items for one tenant. You add an index restricted to ready jobs, and the first query uses it. Then a refactor wraps the state in coalesce, and the same eight jobs come back with a table scan and a temporary sort. The returned rows are correct; the optimizer’s access path changed.

Start with two questions. Does the query ask only for rows present in the index, and can SQLite establish that from the predicate it sees? If the answer is yes, the index becomes a candidate. The planner still chooses among eligible access paths. This separation is more useful than repeatedly rebuilding indexes or changing several query clauses at once.

The example below gives you a controlled way to compare those decisions. It uses one small in-memory SQLite database, tests exact rows and tie order, and prints plans for each query form. It does not use timing to infer that an index was chosen.

Read the WHERE clause as an index membership rule

In the index below, only jobs whose state equals ready enter the index. The columns in parentheses describe how those entries are ordered. The WHERE clause describes which rows are represented. A query can use the tenant equality and the creation-time ordering while relying on the membership rule to restrict the state.

In this case, tenant is the leading key. Once a tenant is fixed, the remaining key order matches created_at and id. The id makes the requested order explicit for jobs with the same timestamp; without a secondary order, an application should not assume which tied row comes first. Keep the same ORDER BY and limit when comparing query shapes.

The index does not include payload, so this query is not covered by the index alone. The lookup can still use the index to locate candidates and fetch payload from the table. Partial membership, useful key order, and coverage are separate properties. Do not widen an index just because a plan omits the word COVERING.

CREATE INDEX jobs_ready_tenant_time
ON jobs(tenant, created_at, id)
WHERE state = 'ready';

EXPLAIN QUERY PLAN
SELECT id, created_at, payload
FROM jobs
WHERE tenant = 2 AND state = 'ready'
ORDER BY created_at, id
LIMIT 8;

Source: SQLite: Partial index predicates and eligibility ↗

A predicate can be equivalent without looking equivalent to the planner

For an index on ready rows, the query’s conditions must imply that every qualifying row is ready. The direct equality is easy to recognize. In this fixture, replacing a NULL state with new before comparing it with ready excludes the same rows. Yet SQLite does not recognize every such expression as proof of the index predicate.

The broader two-state query is different: it genuinely needs blocked rows, which the ready-only index cannot supply by itself. Do not fix that case by quietly narrowing the filter. Either keep the wider result with an appropriate access path or change the business requirement explicitly. A faster query that drops blocked work is a different query.

Inspect the actual expression and bound values generated by your query builder. Compare the SQL before and after a refactor, including collation, NULL treatment and OR conditions. The fact that two predicates agree on a sample is not proof that they agree for every legal value. Write down the data assumptions and verify the result as well as the plan.

Source: SQLite: Partial index predicates and eligibility ↗

Run the plan and result checks together

Save this block as partial_index_lab.py and run python partial_index_lab.py. It creates 720 generated jobs and one extra ready job with the same creation time as job 22. Each variant queries tenant 2 and returns at most eight rows. An independent filter and sort over the input records checks the returned IDs, timestamps and payloads.

The same lab then creates a full index on the same key columns and rechecks the two-state query. It prints plan details for inspection without making them part of the application output contract. The actual local run used Python 3.12.14 and SQLite 3.53.1. The data and SQL are synthetic, so you can run the lab without access to an application database.

import sqlite3

def experiment():
    db = sqlite3.connect(":memory:")
    try:
        db.executescript("""
        CREATE TABLE jobs(
            id INTEGER PRIMARY KEY,
            tenant INTEGER NOT NULL,
            created_at INTEGER NOT NULL,
            state TEXT,
            payload TEXT NOT NULL
        );
        CREATE INDEX jobs_ready_tenant_time
        ON jobs(tenant, created_at, id) WHERE state = 'ready';
        """)
        rows = [
            (i, 1 + i % 3, i // 6,
             'ready' if i % 11 == 0 else 'blocked' if i % 13 == 0
             else None if i % 7 == 0 else 'done', f'job-{i}')
            for i in range(1, 721)
        ]
        rows.append((721, 2, 3, 'ready', 'same-time'))
        db.executemany("INSERT INTO jobs VALUES (?, ?, ?, ?, ?)", rows)
        db.execute("ANALYZE")

        variants = {
            'literal': ("state = 'ready'", ()),
            'equivalent wrapper': ("coalesce(state, 'new') = 'ready'", ()),
            'two states': ("state IN ('ready', 'blocked')", ()),
            'parameter ready': ("state = ?", ('ready',)),
            'parameter blocked': ("state = ?", ('blocked',)),
        }
        results = {}
        for label, (predicate, extra) in variants.items():
            query = f"""
                SELECT id, created_at, payload
                FROM jobs WHERE tenant = ? AND ({predicate})
                ORDER BY created_at, id LIMIT 8
            """
            parameters = (2, *extra)
            plan = [row[-1] for row in db.execute(
                "EXPLAIN QUERY PLAN " + query, parameters
            )]
            result = db.execute(query, parameters).fetchall()
            results[label] = (plan, result)
            print(f"{label}: {' | '.join(plan)}")
            print("  returned IDs:", [row[0] for row in result])

        def expected(states):
            selected = sorted(
                (r for r in rows if r[1] == 2 and r[3] in states),
                key=lambda r: (r[2], r[0])
            )[:8]
            return [(r[0], r[2], r[4]) for r in selected]

        for label, states in [
            ('literal', {'ready'}),
            ('equivalent wrapper', {'ready'}),
            ('two states', {'ready', 'blocked'}),
            ('parameter ready', {'ready'}),
            ('parameter blocked', {'blocked'}),
        ]:
            assert results[label][1] == expected(states), label
        assert [r[0] for r in results['literal'][1]][:2] == [22, 721]
        # A full index can serve the broader two-state query.
        db.execute("CREATE INDEX jobs_tenant_time ON jobs(tenant, created_at, id)")
        db.execute("ANALYZE")
        mixed = """
            SELECT id, created_at, payload FROM jobs
            WHERE tenant = ? AND state IN ('ready', 'blocked')
            ORDER BY created_at, id LIMIT 8
        """
        full_plan = [row[-1] for row in db.execute(
            "EXPLAIN QUERY PLAN " + mixed, (2,)
        )]
        assert db.execute(mixed, (2,)).fetchall() == expected({'ready', 'blocked'})
        print("two states, full index available:", " | ".join(full_plan))
        print("PASS: exact results and timestamp tie order", sqlite3.sqlite_version)
        return results
    finally:
        db.close()

if __name__ == "__main__":
    experiment()

Source: SQLite: EXPLAIN QUERY PLAN ↗

Compare the observations before changing a query

With only the partial index available, the literal and equivalent wrapper returned IDs 22, 721, 55, 88, 121, 154, 187 and 220. The direct predicate used the ready index. The wrapper scanned jobs and used a temporary B-tree for ORDER BY. That plan difference was observed with matching results, so it is a useful starting point for a rewrite.

The same bound state query selected the ready index when given ready and scanned when given blocked on the tested SQLite runtime. Keep using safe binding for variable data. Do not assume parameters always prevent partial-index use, or that a particular plan is guaranteed for all bindings and builds. Test the exact SQL, bindings and runtime your application uses.

After the full index was added, the two-state query used it for the tenant lookup and no temporary ORDER BY step appeared in this fixture. That index includes all states and can keep the requested order, while the state filter still limits the result. This is an observed access path, not a measured claim that the full index is faster in production.

Query formObserved plan in this labWhat to take away
Direct ready predicateSearch via jobs_ready_tenant_timeReady rows are represented and the predicate is recognized
coalesce wrapperScan and temporary sortMatching results do not imply matching access paths
Ready or blockedScan and temporary sort before the full indexA ready-only index cannot supply blocked rows
Bound ready / blockedReady index / scanInspect each representative binding
Ready or blocked, full index availableSearch via jobs_tenant_timeA broader access path preserves the result

Source: SQLite: EXPLAIN QUERY PLAN ↗

Check eligibility, key order and cost in that order

First compare the index definition with the filter that actually runs. A ready-only query should make its state requirement easy to see when the direct form is semantically correct. If the query must serve several states, consider a full index that serves the equality and order together. Separate narrow queries can be appropriate when the calling code already has separate operations.

Next inspect the plan in a representative environment. SEARCH identifies a constrained access path in SQLite’s plan output; it does not report elapsed time or how many rows the application will read. A temporary B-tree for ordering indicates additional sorting work. The format of EXPLAIN QUERY PLAN is intended for diagnosis and can change, so avoid wiring its text into production logic.

Finally account for statistics and distribution. The lab runs ANALYZE to make the fixture’s statistics available, but your real ready fraction, tenant skew, update rate and result limit may differ. An eligible partial index need not win on every dataset. Compare representative queries after collecting statistics appropriately for your deployment, and measure read latency and write costs before retaining overlapping indexes.

Source: SQLite: ANALYZE and planner statistics ↗

Verify the index that the application actually sees

Before editing the application query, inspect the live schema from the same database connection or an equivalent read-only copy. A migration may have created an index in a different database file, or the installed schema may not match the definition in source control. Retrieve its stored SQL and compare both the predicate and key order with the intended migration.

If the query plan names another index, look at its leading columns and the order it can deliver. A narrower index can be eligible and still lose to a different access path. Changing the filter to get a preferred name in the plan is not a useful fix unless the new filter preserves the caller’s contract. Compare first on a copy with representative statistics.

Keep two pieces of evidence in a regression investigation: the exact query and bindings that ran, and the plan plus returned rows for a known fixture. Redact private payloads when sharing diagnostics. A plan pasted without its SQL, runtime version and relevant schema can hide the difference between a missing index and an ineligible one.

SELECT name, sql
FROM sqlite_schema
WHERE type = 'index' AND name = 'jobs_ready_tenant_time';

Make the successful plan a consequence of the right query

Keep a small result test for ready, blocked and NULL states, including identical timestamps and a tenant with no matches. A rewrite that preserves the happy path can still change how missing states or ties behave. A plan screenshot alone will not catch that change.

When the ready-only predicate is part of the operation, express it clearly and let the planner consider the partial index. When the operation includes rows outside that subset, select an access path that can represent the broader query. Start from the rows the caller needs, then use the plan to confirm how SQLite finds them.

KEEP THESE THREE THINGS

Your next steps

  1. Read the partial index WHERE as membership, and its key columns as lookup and ordering.
  2. Keep the query result fixed when testing equivalent rewrites; a wider state filter is a different request.
  3. Check bound values and representative data rather than treating one observed plan as a guarantee.

Sources & official resources

Linked resources checked on 2026-11-07. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →