Schema:
CREATE TABLE [Groups] ([Group] VARCHAR(50) NULL, [ArtNum] INTEGER NULL, [ID] VARCHAR(50) NULL, [Time] INTEGER);
CREATE INDEX [GroupTime] ON [Groups] ([Group], [Time] DESC);
CREATE INDEX [GroupArtNum] ON [Groups] ([Group], [ArtNum]);
I would like optimize the following query:
SELECT `ID` FROM `Groups` WHERE `Group`=? ORDER BY `Time` DESC LIMIT 1
The problem is that SQLite insists on using the GroupArtNum index instead of the GroupTime index. EXPLAIN QUERY PLAN prints the following:
SEARCH TABLE Groups USING INDEX GroupArtNum (Group=?) (~10 rows)
USE TEMP B-TREE FOR ORDER BY
What’s interesting is that if I try to sort by ArtNum instead of Time, it runs very quickly.
I have only (64-bit) integers in the Time column, same as with ArtNum.
ANALYZE(which might or might not help in any specific case); oruse the
INDEXEDclause to force using a specific index (although the documentation warns against doing this):GroupTimeis more efficient.