Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all tables with no records

Tags:

sql

oracle

I need to display all tables that have zero records.

I tried,

select * from user_all_tables where (select count(*) from user_all_tables)=0;

But it doesn't seem to work. How should I go about redesigning this query? Thanks.

like image 603
sqlgrasshopper5 Avatar asked May 17 '10 10:05

sqlgrasshopper5


2 Answers

If all of your tables are analyzed, you can check the column num_rows of table user_tables.

Otherwise, you will need PL/SQL to make this work. This will output all tables of your current user without records (use all_tables if you need tables of other users):

Set Serveroutput On;

Declare
  cnt PLS_INTEGER;
Begin
  For c In ( Select table_name From user_tables ) Loop
    Execute Immediate 'Select Count(*) From "' || c.table_name || '" where rownum=1'
            Into cnt;
    If( cnt = 0 ) Then
      dbms_output.put_line( c.table_name );
    End If;
  End Loop;
End;
like image 157
Peter Lang Avatar answered Sep 29 '22 14:09

Peter Lang


You'd have to resort to PL/SQL and issue a select count(*) for every table. Or you can use dbms_xmlgen to do this for you in a tricky way:

select table_name
  from ( select table_name
              , extractvalue
                ( dbms_xmlgen.getxmltype('select count(*) c from '|| table_name)
                , '/ROWSET/ROW/C'
                ) cnt
              , rownum to_prevent_predicate_push
           from user_tables
       )
 where cnt = '0'

Regards, Rob.

like image 42
Rob van Wijk Avatar answered Sep 29 '22 16:09

Rob van Wijk