Oracle: Find Tables with Outdated Statistics via DBA_TABLES

Purpose

You started a large ANALYZE run and need to know how many tables are still waiting. This query counts the tables in one schema whose last analyze date is before today.

SQL Code

1select	count(last_analyzed) left_to_do
2from	dba_tables
3where	owner = '&schema'
4and	trunc(last_analyzed) < trunc(sysdate)
5order	by 1
6/

Code Breakdown

1select count(last_analyzed) left_to_do from dba_tables where owner = '&schema' and trunc(last_analyzed) < trunc(sysdate) order by 1 / 

Key Components Explained

1. SELECT Clause

  • count(last_analyzed) left_to_do: Counts the number of tables with outdated statistics
  • Names the result column left_to_do.

2. FROM Clause

  • dba_tables: Oracle data dictionary view containing metadata about all tables in the database
  • Requires DBA privileges or SELECT_CATALOG_ROLE to access

3. WHERE Conditions

  • owner = '&schema': Filters tables by specific schema owner (uses substitution variable)
  • trunc(last_analyzed) < trunc(sysdate): Compares truncated analyze date with current date

4. Functions Used

  • TRUNC(): Removes time portion from dates for accurate day-level comparison
  • SYSDATE: Returns current database server date and time

When to Use This Query

  • Before starting analyze operations: Determine scope of work required
  • During long-running statistics jobs: Monitor progress and estimate completion time
  • Regular maintenance checks: Identify schemas with stale statistics
  • Performance troubleshooting: Find tables whose optimizer statistics are out of date

Important Considerations

1. NULL Values Handling

  • Tables never analyzed will have last_analyzed = NULL
  • The COUNT(last_analyzed) function excludes NULL values automatically
  • Consider using COUNT(*) if you want to include never-analyzed tables

2. Time Zone Considerations

  • SYSDATE reflects database server time zone
  • Run the query on the same database server, since SYSDATE uses that server's clock.

3. Performance Impact

  • Query accesses data dictionary views

Enhanced Variations

Include Never-Analyzed Tables

1select count(*) total_tables_needing_analysis from dba_tables where owner = '&schema' and (last_analyzed is null or trunc(last_analyzed) < trunc(sysdate))

Show Detailed Information

1select table_name, last_analyzed,  trunc(sysdate) - trunc(last_analyzed) days_old from dba_tables where owner = '&schema' and trunc(last_analyzed) < trunc(sysdate) order by last_analyzed nulls first

Integration with Maintenance Scripts

1-- Example integration in maintenance script DECLARE  v_count NUMBER; BEGIN  SELECT count(last_analyzed) INTO v_count FROM dba_tables WHERE owner = 'PRODUCTION_SCHEMA' AND trunc(last_analyzed) < trunc(sysdate);  DBMS_OUTPUT.PUT_LINE('Tables requiring analysis: ' || v_count); END; /

Posts in this series