0
votes

Here is the following code to create two tables and a view in SQLite:

CREATE TABLE foo(id TEXT);
CREATE INDEX `foo.index` ON foo(id);
CREATE TABLE bar(id TEXT);
CREATE INDEX `bar.index` ON bar(id);
CREATE VIEW baz AS SELECT id FROM foo UNION SELECT id FROM bar;

INSERT INTO foo VALUES('123');
INSERT INTO foo VALUES('1123');
INSERT INTO foo VALUES('2123');
INSERT INTO foo VALUES('3123');

INSERT INTO bar VALUES('44123');
INSERT INTO bar VALUES('441123');
INSERT INTO bar VALUES('442123');
INSERT INTO bar VALUES('443123');

The result of EXPLAIN QUERY PLAN SELECT * FROM baz WHERE id='123'; is:

SCAN TABLE foo (~1000000 rows)
SCAN TABLE bar (~1000000 rows)
COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (UNION)
SCAN SUBQUERY 1 (~200000 rows)

SQL Fiddle: http://sqlfiddle.com/#!7/b5e79/1 (use WebSQL)

As you can see, it is doing table scans when there is a perfectly usable index. Why? How do I fix this to use the index?

1
This SQL Fiddle shows the indexes being used? Is this the exact script you used to test? - GarethD
Your SQLFiddle shows me the same thing that I outputted...no usage of indexes. (And yes, that is the exact code I tested it with) - chacham15
Not in my browser, it shows SCAN TABLE foo USING COVERING INDEX foo.index (~1000000 rows) as the first step showing it is using foo.Index. - GarethD
Ah ok, WebSQL does not use the index, but SQL.js does. - GarethD
Curiously, UNION ALL will use the indexes... - Jordão

1 Answers

2
votes

Two things might happen here

  • The tables are too small. With just a few rows, all data fits in a block that is read anyway. So the optimizer sees no advantage in using an index. This is unlikely as all columns needed are in the index and therefore need less bytes to be fullfilled.

  • The union between the two selects is equal to union distinct means that all rows that are duplicate in the first and the second select are eliminated. To find them, the database must sort and merge both result sets. If you di a union all this sort step is not necessary as all rows, that fullfill the where clause are put in the result set.

Try union all. This should use the index.