简体   繁体   中英

why does Sqlite not use the index for this ORDER BY?

I have this query:

SELECT * FROM Events e 
  INNER JOIN Telemetry ss ON ss.Id = e.TelemetryId 
  INNER JOIN Services s ON s.Id = ss.ServiceId 
  WHERE s.AssetId = @AssetId AND e.TimestampTicks >= @StartTime 
  ORDER BY e.TimestampTicks LIMIT 1000

and I have this index:

CREATE INDEX [IX_Events_TelemetryId_TimestampTicks] ON [Events] ([TelemetryId],[TimestampTicks])

However, the index is not used for the ORDER BY clause. I get this query explanation:

0|0|2|SCAN TABLE Services AS s (~44 rows)
0|1|1|SEARCH TABLE Telemetry AS ss USING AUTOMATIC COVERING INDEX (ServiceId=?) (~5 rows)
0|2|0|SEARCH TABLE Events AS e USING INDEX IX_Events_TelemetryId_TimestampTicks (TelemetryId=? AND TimestampTicks>?) (~1816 rows)
0|0|0|USE TEMP B-TREE FOR ORDER BY

Why the B-TREE? If I reverse the index, I actually get worse performance. Here's that query plan:

0|0|0|SEARCH TABLE Events AS e USING INDEX IX_Events_TimestampTicks_TelemetryId (TimestampTicks>?) (~4031303 rows)
0|1|1|SEARCH TABLE Telemetry AS ss USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
0|2|2|SEARCH TABLE Services AS s USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)

I don't know why that ordering disallows use of the TelemetryId. I really need this query faster. Any help?

  • The specified index is on ([TelemetryId],[TimestampTicks]), not ([TimestampTicks]), and there is no filter criterai on [TelemetryId].
  • If the test DB does not have a full working data volumne, execution plans in test may not reflect execution plans in production.
  • DB engines attempt to model whther index usage is more efficient than a table scan before choosing to use the index. Often an index that looks useful might be ignored if the expected data volume > ~10% of the table. (Not likely in this case though.)
  • Chasing down imaginary performance problems is a great time waster. Is there a real performance problem in this instance?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM