Skip to content

Generate Gather Statistics Statements (gather_stats.gen)

This generator script creates DBMS_STATS.GATHER_TABLE_STATS procedure calls to collect optimizer statistics on tables. Uses CASCADE to include indexes and AUTO_SAMPLE_SIZE for optimal sampling.

rem gather_stats.gen
rem
select 'exec dbms_stats.gather_table_stats(''' || owner || ''',''' ||
table_name || ''',cascade=>true,estimate_percent=>dbms_stats.auto_sample_size);'
from sys.dba_tables
where owner like upper('&owner')
and table_name like upper('&table_name')
and temporary = 'N'
and owner not in ('SYS','SYSTEM','MDSYS','CTXSYS','XDB','ORDDATA','APEX_040200')
order by owner, table_name
/
-- Basic usage
@gather_stats.gen
-- When prompted, enter:
-- owner: Schema owner pattern (use % for wildcard)
-- table_name: Table name pattern (use % for wildcard)

The script prompts for:

  • &owner - Schema owner pattern (use % for wildcard)
  • &table_name - Table name pattern (use % for wildcard)
SELECT ANY DICTIONARY
-- OR --
SELECT ON DBA_TABLES
-- Plus ANALYZE ANY privilege or ownership of tables
exec dbms_stats.gather_table_stats('HR','EMPLOYEES',cascade=>true,estimate_percent=>dbms_stats.auto_sample_size);
exec dbms_stats.gather_table_stats('HR','DEPARTMENTS',cascade=>true,estimate_percent=>dbms_stats.auto_sample_size);
exec dbms_stats.gather_table_stats('SCOTT','EMP',cascade=>true,estimate_percent=>dbms_stats.auto_sample_size);
  • CASCADE Option: Automatically gathers statistics on associated indexes
  • AUTO_SAMPLE_SIZE: Oracle determines optimal sample size
  • Temporary Table Exclusion: Skips temporary tables
  • System Schema Protection: Excludes critical system schemas

Gather Stats for All Tables in Schema

@gather_stats.gen
-- Enter: HR for owner, % for table_name

Gather Stats After Data Load

@gather_stats.gen
-- Enter: % for owner, %_STAGING for table_name