虽然同意它不是恒定时间的其他答案,但一个有趣且不明显的性能改进select count(*)
是在没有索引的情况下添加索引。这可以在任意列上,并且在我的系统上将查询时间减少了 75%(ish)。
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.468003 sys 4.368028
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.561604 sys 4.290027
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.483603 sys 4.368028
sqlite> explain query plan select count(*) from TestTable;
0|0|0|SCAN TABLE TestTable (~1000000 rows)
sqlite> create index test_index on TestTable(Pointer);
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.062400 sys 0.780005
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.187201 sys 0.655204
sqlite> select count(*) from TestTable;
15035000
CPU Time: user 0.140401 sys 0.748805
sqlite> explain query plan select count(*) from TestTable;
0|0|0|SCAN TABLE TestTable USING COVERING INDEX test_index(~1000000 rows)