How to get record count for all tables?


Sometimes, when inspecting a database, you might want to get a quick glance over all the tables to see which ones actually have some data in them. There is no quick and easy way to get rough estimates, but you can always run brute-force "select count(*)" query on each table. Combining EXECUTE STATEMENT and EXECUTE BLOCK you can do this in a single SQL command:

set term !! ;
EXECUTE BLOCK
returns ( stm varchar(60), cnt integer )
as
BEGIN
for select cast('select count(*) from "'||trim(r.RDB$RELATION_NAME)||'"' as varchar(60))
from RDB$RELATIONS r
where (r.RDB$SYSTEM_FLAG is null or r.RDB$SYSTEM_FLAG = 0) and r.RDB$VIEW_BLR is null
order by 1
into :stm
DO
BEGIN
execute statement :stm into :cnt;
suspend;
END
END


If you use older version of Firebird that does not support EXECUTE STATEMENT or EXECUTE BLOCK, you can do it via 2-step process. First, SELECT from rdb$relations to get a list of select statements:

select 'select '''||trim(r.RDB$RELATION_NAME)||''', count(*) from "'||trim(r.RDB$RELATION_NAME)||'" union '
from RDB$RELATIONS r
where (r.RDB$SYSTEM_FLAG is null or r.RDB$SYSTEM_FLAG = 0)
and r.RDB$VIEW_BLR is null
order by 1

and then copy/paste the resulting statement and execute it in isql or your favorite administration tool (for example, FlameRobin). Make sure you remove the final "union" at the end.


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