Counting all of the rows in a schema can require code that
actually counts the table rows, and it's hard because rows are
constantly being added and deleted from the schema.
So, how do you count up all of the rows for all tables in a schema?
There are two sources of row counts, both of which can become stale:
- Counts as of time last analyzed: The num_rows column in dba_tables, current
only to the date-time of the last analyze with dbms_stats.
- Row count at SQL execution time: The "real" current row count, which requires that you actually
issue SQL to count the rows in all of the tables (time consuming).
To count all of the rows in real time, a simple SQL*Plus script will
suffice:
spool runme.sql
select 'select count(*) from '||table_name||';' from
dba_tables where owner = 'XXX';
spool off
@
runme
Here is a PL/SQL approach for counting all tables in a schema.
Here, you first vonnect as the schema owner:
DECLARE
val NUMBER;
BEGIN
FOR I IN (SELECT TABLE_NAME FROM USER_TABLES)
LOOP
EXECUTE
IMMEDIATE 'SELECT count(*) FROM ' || i.table_name INTO val;
DBMS_OUTPUT.PUT_LINE(i.table_name || ' ==> '
|| val );
END
LOOP;
END;
/
A less intensive approach for estimating the total number of rows in
a schema would query the num_rows column, much faster, but only
accurate to the time that dbms_stats last counted the rows:
compute sum of counter on report;
select
table_name,
num_rows counter
from
dba_tables
where
owner = 'XXX'
order by
table_name;
You can also write PL/SQL procedures to count up the number of rows
in a schema.
Count each number of table rows
Oracle ACE
Laurent Schneider has a more elegant solution for counting
tables, using dbms_xmlgen to store the row counts for multiple
tables in a single SQL query list:
set pages 999;
col count format 999,999,999;
spool countlist.txt
select
table_name,
to_number(
extractvalue(
xmltype(
dbms_xmlgen.getxml('select count(*) c from '||table_name))
,'/ROWSET/ROW/C')) count
from
user_tables
order by
table_name;
spool off;
TABLE_NAME COUNT
------------------------------ ------
DEPT 4
EMP 14
BONUS 0
SALGRADE 5