Friday, February 1, 2013

Faster way to get a row count on a huge table...

We all know how to get a row count of a table:
select count(1)from table_name;

What if the table is so huge!!!
Quick way we generally tend to go around to get the count is from user_tables data dictionary NUM_ROWS column value... wait... that wont give you the accurate number of rows!!! meaning that value is updated in that dictionary when the stats were generated...

Gathering stats to get that value populated is an option? depends on how big the table how long that stats gathering takes place.

So, is there any other way to get number of records faster in a table!!!

Yes...

There is a data dictionary named all_tab_modifications. You can read more about this from the link below (from where i learned this):




Basically, once the insert opeartion is done you have to flush the statistics (which is what Oracle does every often) as below:

exec dbms_stats.flush_database_monitoring_info

Once the flush is done you can query all_tab_modifications table for the results:

select dbta.owner||'.'||dbta.table_name tab_name ,dbta.num_rows anlyzd_rows,
       to_char(dbta.last_analyzed,'yymmdd hh24:mi:ss')  last_anlzd,
  nvl(dbta.num_rows,0)+nvl(dtm.inserts,0) - nvl(dtm.deletes,0) tot_rows,
  nvl(dtm.inserts,0)+nvl(dtm.deletes,0)+nvl(dtm.updates,0) chngs,
  nvl(dtm.inserts,0)+nvl(dtm.deletes,0)+nvl(dtm.updates,0)) / greatest(nvl(dbta.num_rows,0),1) pct_c,
  dtm.truncated trn
  from dba_tables dbta
  -- replace below with all_tab_modifications if you need
       left outer join sys.dba_tab_modifications dtm
  on dbta.owner = dtm.table_owner
     and dbta.table_name = dtm.table_name
          and dtm.partition_name is null
 where dbta.table_name ='PERSON'
   and dbta.owner     ='TRAINER'
/

No comments:

Post a Comment