简体   繁体   中英

SQLite: fastest way to check if a table has more than x rows

What is the fastest way to check if a SQLite table has more than 100,000 rows?


The test table has 26 columns and 200,000,000 rows.

SELECT COUNT(*) FROM ( SELECT * FROM table LIMIT 100001 )

took 0.27 seconds.

The following three needed 12 and a half minutes

SELECT COUNT(*) FROM table
SELECT COUNT(*) FROM table LIMIT 100001
SELECT CASE WHEN COUNT(Id) >= 100000 THEN 1 ELSE 0 END FROM table
select count(*) from (
 select top 100001 ID from T
) x

We need to scan an index to answer the query. This at least restricts the index scan to the first 100001 rows. If the table has 1m rows, this saves 90% of the work.

(Using SQL Server syntax here - please translate yourself because I can't do it).

Instead of ID you can choose some indexed column. I don't know if the optimizer can do that itself.

Note, that clever tricks like looking at identity or ID column values do not work in general.

To support the above query, create a dummy column of type bit and index it. The index will be very compact and the fastest to scan.

SELECT COUNT(indexed_column) FROM TableName

现在索引列部分是重要的,你不想做像计数*这样的事情,你希望尽可能具体,强制SQL使用该表上每行存在的索引。

SELECT COUNT will bite you, when you have a lot of rows. It works - but you are asking for the fastest way in sqlite.

Use:

SELECT max(rowid) AS rowcount

As NoLifeKing pointed out this only works correctly if you do not have any deletions. Otherwise it will get inconsistent and you would have a higher rowcount as is actually in the table.

Check out http://www.sqlite.org/autoinc.html about the rules, how Sqlite creates rowid.

If you don't have any indexed column, I think fastest way would be (for N = 100000)

select 1 from test1 limit 1 offset 100000;

It's because you will get only N + 1 rows. No count, no max.

you can try it here sqlfiddle

SELECT COUNT (Column) FROM TABLE

确保所选列被索引,最好是INT。

SELECT CASE WHEN COUNT(indexed_column) >= 100000 THEN 1 ELSE 0 END FROM table

Shouldn't that do it? Reports 1 if it is over 100.000 and 0 otherwise

select count(*) from table      
select max(id) from table  

if table has a primary key id, second on

select count(*) from table

- 查询优化器自动选择索引列。

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