#9406·turso

optimizer: use an index range for LIKE and GLOB with a literal prefix

Author: penbergCreated Sep 29, 2026Updated Sep 29, 2026

The planner cannot use an index for col GLOB 'prefix*' or col LIKE 'prefix%'. SQLite adds two range conditions for such a pattern (f GLOB 'ghij*' gets f >= 'ghij' AND f < 'ghik') and searches the index with them. Turso scans the whole table or index instead.

Reproducer

sql
CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c, d, e, f TEXT, g);
CREATE INDEX t2b ON t2(b);
CREATE INDEX t2f ON t2(f);

EXPLAIN QUERY PLAN SELECT a FROM t2 WHERE f GLOB 'ghij*';
EXPLAIN QUERY PLAN SELECT a FROM t2 WHERE b = 1070 OR f GLOB 'ghij*';
Query sqlite3 tursodb
f GLOB 'ghij*' SEARCH t2 USING COVERING INDEX t2f (f>? AND f<?) SCAN t2 USING COVERING INDEX t2f
b = 1070 OR f GLOB 'ghij*' MULTI-INDEX OR using t2b (b=?) and t2f (f>? AND f<?) SCAN t2

The OR case hurts more. A multi-index OR works only if every branch can use an index. One GLOB branch makes the whole query read every row of the table.

Effect on the upstream TCL suite

sqlite/conformance/upstream/where7.test checks the number of full-scan steps (SQLITE_STMTSTATUS_FULLSCAN_STEP) for about 2,000 OR queries, and many of them have a GLOB prefix branch. The results are correct, but Turso reports scan 99 where SQLite reports scan 0. #8990 fixes the OR branches written in parentheses. Its description says 435 of the failures that remain after it come from this missing optimization.

What SQLite does

See isLikeOrGlob() and the code that calls it in exprAnalyze() in SQLite's whereexpr.c. SQLite adds the range conditions only when all of these are true:

  • The left side is a column with TEXT affinity. For a column with numeric affinity, a text range would not match the right rows.
  • The right side is a literal string, or a bound parameter when the statement is prepared again after the value is bound. It must start with at least one character that is not a wildcard.
  • The collation matches the operator. GLOB is case-sensitive and needs BINARY. LIKE is case-insensitive by default, so it needs a NOCASE index unless PRAGMA case_sensitive_like=ON.
  • For LIKE, the ESCAPE clause is handled. SQLite does not use the optimization when an ESCAPE character is given in some cases.
  • The upper bound is the prefix with its last character incremented. SQLite has special cases here, for example when that character is the largest possible byte, or a character whose upper and lower case forms sort differently.

The original GLOB/LIKE stays in the WHERE clause as a filter, because the range can include rows the pattern does not match.

Tests

  • Add .sqltest cases with snapshot-eqp plan snapshots next to the existing multi_index_* files. Cover a GLOB prefix alone, a GLOB prefix inside a multi-index OR, LIKE with a NOCASE index, LIKE with case_sensitive_like, and a column with numeric affinity (must not use the range).
  • where7.test should mostly pass once this and #8990 are both merged.