I want know if there is a way to search a database and find out which tables are empty and which have data. I will be migrating some data to another system and it would be nice to know which tables I should export. I'm using Oracle SQL Developer.
3 Answers
One way to do it, aside from running a silly pl/sql block to count(*)
for each table, is to run this:
SELECT num_rows FROM ALL_TAB_STATISTICS WHERE OWNER = 'user name';
(Alternate tables: DBA_TAB_STATISTICS
, USER_TAB_STATISTICS
)
But then, it's valid only if you recently gathered statistics with the DBMS_STATS
package.
-
This is it! Thanks a lot Sebas, this helped a lot. I was able to get a nice list from Oracle Developer and export to excel to review with table names. Jul 28, 2015 at 23:31
Yes, You can select count for all tables in a database with a query like
select table_name,
to_number(
extractvalue(
xmltype(
dbms_xmlgen.getxml('select count(*) c from '||table_name))
,'/ROWSET/ROW/C')) count
from user_tables;
Heres a demo
The Accepted answer is incorrect given that the statistics need to have been gathered subsequent to the last table modification in order to guarantee that the query will yield the correct result.
Shreyas Chavan's answer is correct but performance may be poor. The following query gives an accurate answer but should perform better where there are many tables.
select owner, table_name,
case
to_number(
extractvalue(
xmltype(
dbms_xmlgen.getxml('select count(1) c
from '||owner||'.'||table_name||'
where rownum<2'))
,'/ROWSET/ROW/C'))
when 1 then 'Y' else 'N' END has_data
from all_tables
ORDER BY owner, table_name;
where rownum = 1
this will return 1 if the table has data, and zero if not, and runs faster than aselect count(*)
on the whole table.