Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query that returns the size of a table in a SQLite database

Tags:

I have a SQLite database that contains a number of tables. We are writing a maintenance tool that will remove "stale" data from a table until that table's size is a certain percentage of the total database file or smaller.

I know how to determine the size of the database file -- I do it by executing

PRAGMA PAGE_SIZE; 

and

PRAGMA PAGE_COUNT; 

in two separate queries and multiplying the two to get the file size in bytes. Yes, I know I can just take the size of the file in bytes, but this is similar to the way I've done it in other databases and I want to stick with it, at least for now.

My problem is I don't know how to get the size of a TABLE. There has to be some way to do this. Can anyone point me in the right direction?

like image 957
Tony Vitabile Avatar asked Dec 19 '14 19:12

Tony Vitabile


People also ask

What is the size of SQLite?

The maximum size of a database file is 4294967294 pages. At the maximum page size of 65536 bytes, this translates into a maximum database size of approximately 1.4e+14 bytes (281 terabytes, or 256 tebibytes, or 281474 gigabytes or 256,000 gibibytes).

What is DESC in SQLite?

The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.


1 Answers

If SQLite is compiled with SQLITE_ENABLE_DBSTAT_VTAB, you can query the dbstat table. This should return the table size (in bytes) of table TABLENAME:

SELECT SUM("pgsize") FROM "dbstat" WHERE name='TABLENAME'; 

https://www.sqlite.org/dbstat.html

This is what is used by the sqlite3_anazlyer CLI tool, which can also be used for this purpose.

like image 81
Christopher K. Avatar answered Sep 19 '22 13:09

Christopher K.