I am wondering about how a covering index can help in the case where you first JOIN on a column, and then have BETWEEN constraints on a second and third column. Would a combined index on these three have a positive effect?
Example (fiddle).
CREATE TABLE tbl1(firstcol TEXT);
CREATE TABLE tbl2(firstcol TEXT, secondcol INTEGER, thirdcol INTEGER);
INSERT INTO tbl1 VALUES ('hello');
INSERT INTO tbl1 VALUES ('good morning');
INSERT INTO tbl2 VALUES ('hello', '1', '1');
INSERT INTO tbl2 VALUES ('hello', '5', '210');
INSERT INTO tbl2 VALUES ('bonjour', '999', '1');
INSERT INTO tbl2 VALUES ('hello', '4', '20');
CREATE INDEX myfirstindex ON tbl1 (firstcol);
CREATE INDEX mymultiindex ON tbl2 (firstcol, secondcol, thirdcol);
SELECT *
FROM tbl1
JOIN tbl2 USING(firstcol)
WHERE
tbl2.secondcol BETWEEN 0 AND 100
AND tbl2.thirdcol BETWEEN 0 AND 50
If I call for EXPLAIN QUERY PLAN
, then I see that it has an effect but only on the first and second col. So why isn't the third included here? Why does the optimizer choose to not make use of the joint index on all three columns?
id parent notused detail
3 0 0 SCAN tbl1
5 0 0 SEARCH tbl2 USING COVERING INDEX mymultiindex (firstcol=? AND secondcol>? AND secondcol<?)