Select count(*) is slow


Reason is that Firebird doesn't keep information about number of records in database. Since query doesn't have WHERE clause, it cannot use index either, and has to go through all the records.

Keeping a count in a multiuser system is almost impossible as you would get different values for different transaction levels.

There are ways to get approximate count however:

You could add a table with two columns: a table name and record count, and then create triggers on all your tables (those you wish to track) to populate these. There might be problems with performance. Solution is to have a transaction table which only stores values +1 and -1, and to get the record count you just sum them up. Periodically, you would sum those up and insert as a single record, to keep the table small and fast.

There is another solution. This one is by Ivan Prenosil, a long time Interbase and Firebird hacker. This solution only returns an approximate record count. As Ann W. Harrison kindly explains: Any record that has had its primary key modified will appear twice if the old version has not been garbage collected and deleted records will continue in the count until they are garbage collected.

/* first update the statistics */
UPDATE RDB$INDICES SET RDB$STATISTICS = -1;
COMMIT;

/* Display table names and record counts */
SELECT RDB$RELATIONS.RDB$RELATION_NAME,
CASE
WHEN RDB$INDICES.RDB$STATISTICS = 0 THEN 0
ELSE CAST(1 / RDB$INDICES.RDB$STATISTICS AS INTEGER)
END
FROM RDB$RELATIONS
LEFT JOIN RDB$RELATION_CONSTRAINTS ON RDB$RELATIONS.RDB$RELATION_NAME = RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME AND RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
LEFT JOIN RDB$INDICES ON RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME = RDB$INDICES.RDB$INDEX_NAME
WHERE RDB$VIEW_BLR IS NULL AND RDB$RELATION_ID >= 128
ORDER BY 1;


This will only work on tables that have a primary key.


Do you find this FAQ incorrect or incomplete? Please e-mail us what needs to be changed. To ensure quality, each change is checked by our editors (and often tested on live Firebird databases), before it enters the main FAQ database. If you desire so, the changes will be credited to your name. To learn more, visit our add content page.



All contents are copyright © 2007-2024 FirebirdFAQ.org unless otherwise stated in the text.


Links   Firebird   News   FlameRobin   Powered by FB: Home Inventory   Euchre  
Add content   About  

Categories
 Newbies
 SQL
 Installation and setup
 Backup and restore
 Performance
 Security
 Connectivity and API
 HOWTOs
 Errors and error codes
 Miscellaneous