Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to count rows in a table in SQLite?

Tags:

sql

sqlite

I've always just used "SELECT COUNT(1) FROM X" but perhaps this is not the most efficient. Any thoughts? Other options include SELECT COUNT(*) or perhaps getting the last inserted id if it is auto-incremented (and never deleted).

How about if I just want to know if there is anything in the table at all? (e.g., count > 0?)

like image 907
tofutim Avatar asked Dec 17 '10 21:12

tofutim


People also ask

How can I COUNT the number of rows in a table in SQLite?

In SQLite the Count(*) function will return total number of rows available in a table, including the rows which contain NULL values. The Count(*) will not take any parameters other than the asterisk symbol (*).

How do you make a COUNT query faster?

So to make SELECT COUNT(*) queries fast, here's what to do:Get on any version that supports batch mode on columnstore indexes, and put a columnstore index on the table – although your experiences are going to vary dramatically depending on the kind of query you have.

How do I COUNT something in SQLite?

The function COUNT() is an aggregate function that returns the number of items in a group. For example, you can use the COUNT() function to get the number of tracks from the tracks table, the number of artists from the artists table, and so on.

How many rows can a SQLite table handle?

The max_page_count PRAGMA can be used to raise or lower this limit at run-time. The theoretical maximum number of rows in a table is 264 (18446744073709551616 or about 1.8e+19). This limit is unreachable since the maximum database size of 281 terabytes will be reached first.


2 Answers

The best way is to make sure that you run SELECT COUNT on a single column (SELECT COUNT(*) is slower) - but SELECT COUNT will always be the fastest way to get a count of things (the database optimizes the query internally).

If you check out the comments below, you can see arguments for why SELECT COUNT(1) is probably your best option.

like image 173
girasquid Avatar answered Sep 18 '22 08:09

girasquid


To follow up on girasquid's answer, as a data point, I have a sqlite table with 2.3 million rows. Using select count(*) from table, it took over 3 seconds to count the rows. I also tried using SELECT rowid FROM table, (thinking that rowid is a default primary indexed key) but that was no faster. Then I made an index on one of the fields in the database (just an arbitrary field, but I chose an integer field because I knew from past experience that indexes on short fields can be very fast, I think because the index is stored a copy of the value in the index itself). SELECT my_short_field FROM table brought the time down to less than a second.

like image 35
M Katz Avatar answered Sep 20 '22 08:09

M Katz