Skip to content

Use SQLite indexes for simple Boolean counts and list queries - #39711

Open
emremenekse wants to merge 3 commits into
dotnet:mainfrom
emremenekse:investigate/sqlite-boolean-index
Open

emremenekse wants to merge 3 commits into
dotnet:mainfrom
emremenekse:investigate/sqlite-boolean-index

Conversation

@emremenekse

Copy link
Copy Markdown
Contributor

Contributes to #30709.

Changes

A query such as Where(row => row.Flag) can scan an entire SQLite table even when its Boolean column has an index. This change handles a single table with a plain Boolean predicate, a native INTEGER mapping and a modeled index that begins with the filtered column.

  • Counts and covering projections read the positive and negative index ranges separately. The positive range retains the original Boolean predicate because SQLite also sorts text and blobs above numbers.
  • When the projection needs columns outside the index, the provider checks for a 1,025th row. Smaller tables use the original query. Larger tables use indexed lookups or a table scan depending on whether more than one eighth of the rows are candidates. Both plans evaluate the original filter, including for stored values such as 2 and -1.
  • The size check adds one observable scalar command to eligible noncovering list queries. It uses the same connection and active transaction, and performs at most 1,024 scan steps. Ordering, pagination, composed predicates and value converters retain their existing translation. ToQueryString() produces an executable standalone query. Ahead-of-time pregenerated commands that retain only this SQL also use the standalone plan. The small-table shortcut runs when EF executes a template from the SQLite command builder.

Local validation

  • All 49 focused SQLite regression cases passed, including synchronous and asynchronous queries, noncanonical values, data changes, the 1,024/1,025-row boundary, rollback, connection cleanup after an error and standalone tagged SQL.
  • The full SQLite functional suite passed with 39,088 successes and 282 skips. All 934 SQLite unit tests passed.

Median AsNoTracking().Where(...).ToListAsync() times on an in-memory SQLite 3.53.4 database, with command interception enabled. All three arms used the same physical index and database. The middle column of timings replays the preceding experimental SQL; the last uses the provider's normal query path.

Table and matches Original translation Previous local candidate This change
Empty 40.9 µs 76.7 µs 58.9 µs
10 of 10 75.0 µs 109.3 µs 88.1 µs
1,000 of 100,000 7.078 ms 1.499 ms 1.589 ms
50,000 of 100,000 48.271 ms 49.348 ms 49.737 ms
99,000 of 100,000 97.694 ms 99.488 ms 99.844 ms

The three-way comparison rotates execution order and uses 501 timed samples per arm for small tables and 45 for large tables. Each arm returned identical IDs, Boolean values and payloads. Each timed operation verified cardinality, ID checksum and command counts. The small-table change reduced the excess over the original translation from 34.3 µs to 13.1 µs for ten rows. At 1% selectivity the final implementation was 4.46× as fast as the original translation. The 50% and 99% cases took 3.0% and 2.2% longer than the original translation in this run.

In a separate two-arm run without command interceptors, the ten-row median was 45.3 → 51.6 µs. The 1% case took 6.265 → 1.692 ms (3.70×). On a warm file-backed database with interception, the 1% case took 17.171 → 4.590 ms (3.74×). In the separate 13% boundary run the async median increased by 7.1%. At 1,024 rows and 1% selectivity the medians were 43.1 / 53.0 / 58.8 µs for original / previous / final.

The cutoffs are performance heuristics. Measurements cover a warmed local connection, a Boolean-only index and a projected 256-character payload. They include EF materialization and the extra scalar command. Cold-start and concurrent workloads were outside the measurement.

Read disjoint index ranges for counts and covering projections. Use a bounded size probe for noncovering lists and retain SQLite truth-value semantics when selecting the access path.

Contributes to dotnet#30709.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The density probe can scan roughly one eighth of a large index before yielding the first streamed row, so it needs a table-size-independent bound or a streaming-friendly plan plus first-row and early-disposal regression coverage.

1 open issue
What changed in this PR

This PR addresses #30709 by enabling SQLite index use for eligible simple Boolean filters while preserving noncanonical stored values.

Changes:

  • Splits counts and covering projections into positive and negative index ranges.
  • Adds size and density checks to choose an access path for noncovering queries.
  • Adds regression coverage for results, query plans, transactions, and connection cleanup.
File Description
test/​EFCore.Sqlite.FunctionalTests/​Query/​BooleanPredicateIndexSqliteTest.cs Tests Boolean filtering, access paths, and execution lifecycle.
src/​EFCore.Sqlite.Core/​Storage/​Internal/​SqliteRelationalCommandBuilderFactory.cs Runs the size probe and selects the small-table fallback.
src/​EFCore.Sqlite.Core/​Query/​Internal/​SqliteQuerySqlGenerator.cs Generates adaptive noncovering SQL and probe commands.
src/​EFCore.Sqlite.Core/​Query/​Internal/​SqliteParameterBasedSqlProcessor.cs Identifies eligible filters and rewrites counts and covering projections.
src/​EFCore.Sqlite.Core/​Extensions/​SqliteServiceCollectionExtensions.cs Registers the SQLite-specific command builder factory.

Review effort: Balanced

Sql.Append("WITH ").Append(gate).AppendLine("(dense) AS (")
.Append(" SELECT EXISTS (SELECT 1 FROM ").Append(source).Append(" WHERE ").Append(column).AppendLine(" > 0")
.Append(" UNION ALL SELECT 1 FROM ").Append(source).Append(" WHERE ").Append(column).AppendLine(" < 0")
.Append(" LIMIT 1 OFFSET (SELECT COUNT(*) FROM ").Append(source).AppendLine(") / 8))");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 6ee7777. The probe stops at the 1,025th zero or NULL index entry. If it reaches that point, the density check samples at most 800 rows. The new regression test reads one row with AsAsyncEnumerable(), disposes the enumerator, and checks SQLite's VM step count.

Locally, all 54 focused tests and 934 SQLite unit tests passed. The SQLite functional suite passed with 39,124 passed and 282 skipped. On one million all-true rows, median time to read one row and dispose fell from 817 to 24 us. With 1% scattered matches, early disposal still took 150 us versus 21 us before the PR, while reading the full list took 12.9 ms versus 76.7 ms.

@cincuranet

Copy link
Copy Markdown
Contributor

I'd like the simple straightforward WHERE (Flag > 0 OR Flag < 0) AND Flag translation. But based on my measurements (SQLite 3.54.1, 1M rows with payload) it works only for up to roughly 20% of true rows. Then it starts to become slower (up to about 33% slower on 99% true rows).

The adaptive path in this PR is what I'm not so sure. It's a lot of hidden behavior for one predicate shape. It adds extra database command. Chooses a plan from a sample, which can misjudge unevenly distributed data. ToQueryString doesn't fully show what EF executes. It needs a custom SQLite command builder and has many edge cases to maintain.

I don't think we've ever done different query shapes based on probing of data. And I don't think we should.

Using partial index, like:

modelBuilder.Entity<Foo>()
    .HasIndex(r => r.Flag)
    .HasFilter("\"Flag\"");

is a better tradeoff - it uses SQLite's optimizer, doesn't change EF's SQL, and helps exactly when true values are sparse.

I think we should document this and it will be the classic targeted performance optimization like any other.

@cincuranet cincuranet self-assigned this Nov 19, 2026
@emremenekse

emremenekse commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, Jiri. I also tried a partial index on Id filtered by Flag, alongside the existing Flag index, with the existing SQLite provider and the same generated SELECT. On a local 100,000-row table with a payload and 1% matching rows, the median time to read the full list went from 3.26 ms to 0.37 ms. At 99% matches SQLite chose a table scan. The partial index also preserved the existing results for nonzero values such as 2 and -1.

I agree with your concern about probing. In a separate run with the adaptive implementation on one million rows and 1% scattered matches, the full list got faster, but reading just the first row and disposing the reader went from 21 to 150 µs. The caller pays for the probe before we know how much it will read.

Would documenting the partial index on the SQLite provider page, with a sparse-flag example, be the preferred way to address #30709?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants