5

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
  • A select count should give you the number of record in the table.
    – innoSPG
    Jul 28, 2015 at 23:18
  • What's the downside of exporting all tables, regardless of whether they have data?
    – Dave Costa
    Jul 28, 2015 at 23:24
  • If you include a where rownum = 1 this will return 1 if the table has data, and zero if not, and runs faster than a select count(*) on the whole table.
    – mjsqu
    Jul 28, 2015 at 23:30

3 Answers 3

4

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.

1
  • 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.
    – smartinez7
    Jul 28, 2015 at 23:31
3

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

0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.