Tuesday, March 1, 2016

how to get table count for all tables in a schema/user using simple methods ......

Getting a table count might be looking simple but if you want to get table count for all tables in the database..which is time consuming...
you can get this by below methods.... use as you think is better..

1) you can get the count of all tables using dba_tables using NUM_ROWS. but this will not give right count as this tables gets updated with the dictionary job/stats job update only....
select table_name,num_rows from dba_tables where owner='ABC' order  by table_name;


2)  you can write a small sql generated sql to get the statements and spool the output.
set heading off;
Select 'Select '''||table_name||' : ''||count(*) from '||table_name||';'
from user_tables
order by table_name;

3) you can use pl/sql query to get the correct count of all tables at any given time....it directly queries the table as you do... you need to be in that specific schema.

set SERVEROUTPUT ON
DECLARE
sql_stmt varchar2(256);
v_b varchar2(100);
cursor c_f is SELECT TABLE_NAME from DBA_TABLES where owner = 'ABC';
  v_a DBA_TABLES.TABLE_NAME%type;

BEGIN
open c_f;
  loop
    fetch c_f into v_a;
    exit when c_f%notfound;

sql_stmt :='SELECT count(*)  from '|| v_a ||'';

execute immediate sql_stmt into v_b;
--execute immediate sql_stmt into tab_count;
---    execute immediate 'SELECT max(v_b) into tab_count from v_a where current of c_f';
--DBMS_OUTPUT.PUT_LINE ( ' || abc.table_name ||  ',' tab_count ');

DBMS_OUTPUT.PUT_LINE ( v_a   || ': ---> ' ||    v_b );

  END LOOP;
END;
/


use below script if above doesnt work. you can run this as sys owner too..



set SERVEROUTPUT ON size 1000000
set feedback on echo off verify off
DECLARE
sql_stmt varchar2(256);
tab_count varchar2(100);

cursor c_f is (SELECT owner,TABLE_NAME from DBA_TABLES where owner = '&owner');
  v_a DBA_TABLES.TABLE_NAME%type;

BEGIN
for abc in c_f
  loop
   
sql_stmt := '(SELECT count(*)  from  '||abc.owner||'.'||abc.table_name||')';
execute immediate sql_stmt into tab_count;

DBMS_OUTPUT.PUT_LINE ( ''||abc.table_name||'' || ': ------>   ' ||  ''||tab_count||'');
  END LOOP;
END;
/






Hope this helps and saves some time....

No comments:

Post a Comment

PostgreSql: Useful Commands-

 1)   ************************* Users ***************************  -- List of users with roles assigned: SELECT usename AS role_name,   CASE...