In SQLite 3.20.1, I have an R*Tree index (dog_bounds
) and a temporary table (frisbees
) created as follows:
-- Changes infrequently and has ~100k entries
CREATE VIRTUAL TABLE dog_bounds USING rtree (
dog_id,
min_x, max_x,
min_y, max_y
);
-- Changes frequently and has ~100 entries
CREATE TEMPORARY TABLE frisbees (
frisbee_id,
min_x, max_x,
min_y, max_y
);
Queries are fast using this index, like so:
EXPLAIN QUERY PLAN
SELECT dog_id FROM dog_bounds AS db, frisbees AS f
WHERE db.max_x >= f.min_x AND db.max_y >= f.min_y
AND db.min_x < f.max_x AND db.min_y < f.max_y;
0|0|1|SCAN TABLE frisbees AS f
0|1|0|SCAN TABLE dog_bounds AS db VIRTUAL TABLE INDEX 2:D1D3C0C2
However, if I select DISTINCT(dog_id)
, the index is no longer used, and queries become slow, even after ANALYZE
:
EXPLAIN QUERY PLAN
SELECT DISTINCT(dog_id) FROM dog_bounds AS db, frisbees AS f
WHERE db.max_x >= f.min_x AND db.max_y >= f.min_y
AND db.min_x < f.max_x AND db.min_y < f.max_y;
0|0|0|SCAN TABLE dog_bounds AS db VIRTUAL TABLE INDEX 2:
0|1|1|SCAN TABLE frisbees AS f
0|0|0|USE TEMP B-TREE FOR DISTINCT
How can I get the R*Tree index used here as well? It would be a shame to duplicate dogs!