Empty Tables with Allocated Storage (dstatzer.sql)
What This Script Does
Section titled “What This Script Does”This script identifies empty tables that still have allocated storage blocks, revealing opportunities for space reclamation and storage optimization. These tables consume disk space despite containing no data, which can occur after bulk deletions, failed data loads, or during development activities. The script is essential for database housekeeping and storage optimization initiatives.
The Script
Section titled “The Script”rem dstatzer.sqlremttitle 'Zero Row Table Statistics'remcol owner format a8 heading 'OWNER'col table_name format a21 heading 'TABLE NAME'col num_rows format 9999999990 heading 'ROWS'col chain_cnt format 9990 heading 'CHAIN|COUNT'col avg_row_len format 9990 heading 'AVG|ROW|SIZE'col blocks format 999999990 heading 'USED|BLOCKS'col empty_blocks format 9999990 heading 'EMPTY|BLOCKS'col avg_space format 9990 heading 'AVG|FREE|SPACE'rembreak on owner skip 1compute sum of num_rows blocks empty_blocks on ownerremselect owner, table_name, num_rows, chain_cnt, avg_row_len, blocks, empty_blocks, avg_space from sys.dba_tables where owner like upper('&owner') and table_name like upper('&table') and num_rows = 0 and blocks > 0 order by owner, table_name;Key Features
Section titled “Key Features”- Empty Table Detection: Finds tables with zero rows but allocated blocks
- Space Waste Identification: Highlights storage that can be reclaimed
- Schema and Table Filtering: Supports pattern matching for targeted analysis
- Storage Metrics: Shows detailed block allocation information
- Summary Statistics: Provides totals by owner for planning purposes
- Optimization Support: Enables informed space reclamation decisions
@dstatzer.sqlInput Parameters:
- owner: Schema owner pattern (use % for wildcards)
- table: Table name pattern (use % for wildcards)
Required Privileges
Section titled “Required Privileges”SELECT on SYS.DBA_TABLESSample Output
Section titled “Sample Output” Zero Row Table Statistics
OWNER TABLE NAME ROWS CHAIN AVG USED EMPTY AVG COUNT ROW BLOCKS BLOCKS FREE SIZE SPACE-------- --------------------- --------- ----- ---- --------- ------- ----DEV TEMP_LOAD_TABLE 0 0 0 125 45 8192 TEST_DATA_BACKUP 0 0 0 89 23 8192 STAGING_CUSTOMER_DATA 0 0 0 234 67 8192 --------- --------- ---------sum 0 448 135
SALES OLD_ORDERS_ARCHIVE 0 0 0 567 123 8192 TEMP_IMPORT_DATA 0 0 0 45 12 8192 --------- --------- ---------sum 0 612 135
TEST PERFORMANCE_TEST_TBL 0 0 0 789 234 8192 BULK_DELETE_TEST 0 0 0 345 89 8192 DATA_MIGRATION_TEMP 0 0 0 156 45 8192 --------- --------- ---------sum 0 1290 368Key Output Columns
Section titled “Key Output Columns”- OWNER: Schema owner of the table
- TABLE NAME: Name of the empty table
- ROWS: Number of rows (always 0 for this analysis)
- CHAIN COUNT: Number of chained rows (always 0 for empty tables)
- AVG ROW SIZE: Average row length (always 0 for empty tables)
- USED BLOCKS: Number of blocks still allocated to the table
- EMPTY BLOCKS: Number of empty blocks allocated
- AVG FREE SPACE: Average free space per block
Understanding Empty Table Storage
Section titled “Understanding Empty Table Storage”Why Empty Tables Consume Storage
Section titled “Why Empty Tables Consume Storage”Common Scenarios
Section titled “Common Scenarios”-- Reasons for empty tables with allocated blocks:-- Bulk deletions leaving allocated space-- Failed or interrupted data loads-- Test data creation and cleanup-- ETL process intermediate tables-- Development and testing activitiesStorage Allocation Behavior
Section titled “Storage Allocation Behavior”-- Oracle storage allocation:-- Initial extent allocation at table creation-- Minimum extent size requirements-- Block allocation for failed INSERT operations-- Space not automatically deallocated after DELETEStorage Impact Assessment
Section titled “Storage Impact Assessment”Space Consumption Analysis
Section titled “Space Consumption Analysis”-- Calculate storage waste:-- Total blocks = used_blocks + empty_blocks-- Storage waste = total_blocks * block_size-- Potential reclamation = blocks * block_size-- Percentage of total schema storagePerformance Implications
Section titled “Performance Implications”-- Impact on database operations:-- Unnecessary space consumption-- Backup size inflation-- Export/import time increase-- Statistics gathering overheadCommon Use Cases
Section titled “Common Use Cases”-
Storage Optimization
- Identify space that can be reclaimed
- Plan storage cleanup activities
- Reduce database storage footprint
- Optimize backup and recovery times
-
Database Housekeeping
- Clean up development and test artifacts
- Remove abandoned staging tables
- Eliminate failed data load remnants
- Support database maintenance programs
-
Capacity Planning
- Assess actual vs. allocated storage
- Identify storage waste patterns
- Plan storage reclamation projects
- Support infrastructure optimization
-
Environment Management
- Clean up development environments
- Standardize test environment procedures
- Implement automated cleanup processes
- Support environment refresh activities
Advanced Analysis
Section titled “Advanced Analysis”Storage Reclamation Assessment
Section titled “Storage Reclamation Assessment”Reclamation Calculations
Section titled “Reclamation Calculations”-- Calculate potential savings:-- Space per table = (used_blocks + empty_blocks) * block_size-- Total reclaimable space = SUM(space per table)-- Percentage of schema storage = reclaimable / total schema storage-- Cost-benefit analysis of cleanup effortPriority Assessment
Section titled “Priority Assessment”-- Prioritize reclamation efforts:-- Tables with largest block allocation-- Development/test schemas with high waste-- Production schemas with space pressure-- Tables affecting backup/recovery timesPattern Analysis
Section titled “Pattern Analysis”Common Patterns
Section titled “Common Patterns”-- Identify waste patterns:-- Temporary tables left from ETL processes-- Test data tables in production schemas-- Staging tables from failed migrations-- Archive tables after data purgingSchema-Specific Analysis
Section titled “Schema-Specific Analysis”-- Schema waste patterns:-- Development schemas: High waste from testing-- Production schemas: ETL and maintenance artifacts-- Test schemas: Incomplete cleanup procedures-- Archive schemas: Purged but not deallocatedSpace Reclamation Strategies
Section titled “Space Reclamation Strategies”Table Management Options
Section titled “Table Management Options”Immediate Reclamation
Section titled “Immediate Reclamation”-- Quick space reclamation methods:-- DROP TABLE (if table not needed)-- TRUNCATE TABLE (reset to initial state)-- ALTER TABLE DEALLOCATE UNUSED (partial reclamation)-- MOVE operation to reclaim all spaceConditional Reclamation
Section titled “Conditional Reclamation”-- Careful reclamation approaches:-- Verify table usage before dropping-- Check for dependencies and constraints-- Coordinate with application teams-- Plan rollback procedures if neededAutomated Cleanup Procedures
Section titled “Automated Cleanup Procedures”Cleanup Scripts
Section titled “Cleanup Scripts”-- Automated cleanup strategies:-- Regular identification of empty tables-- Automated DEALLOCATE UNUSED operations-- Scheduled cleanup of temporary tables-- Policy-based table lifecycle managementSafety Procedures
Section titled “Safety Procedures”-- Safety measures:-- Backup before major cleanup activities-- Test procedures in development first-- Implement approval processes for production-- Document cleanup activities and resultsFiltering Examples
Section titled “Filtering Examples”All Schemas Analysis
Section titled “All Schemas Analysis”-- Comprehensive database analysis:Enter value for owner: %Enter value for table: %Development Environment Cleanup
Section titled “Development Environment Cleanup”-- Focus on development schemas:Enter value for owner: %DEV%Enter value for table: %Temporary Table Analysis
Section titled “Temporary Table Analysis”-- Find temporary and staging tables:Enter value for owner: %Enter value for table: %TEMP%Enter value for table: %STAGING%Specific Schema Focus
Section titled “Specific Schema Focus”-- Single schema analysis:Enter value for owner: SALESEnter value for table: %Integration with Maintenance
Section titled “Integration with Maintenance”Regular Cleanup Procedures
Section titled “Regular Cleanup Procedures”Cleanup Schedule
Section titled “Cleanup Schedule”-- Regular maintenance:-- Daily cleanup of temporary tables-- Weekly analysis of development schemas-- Monthly production environment review-- Quarterly comprehensive assessmentCleanup Validation
Section titled “Cleanup Validation”-- Validation procedures:-- Verify table usage before cleanup-- Check application dependencies-- Confirm with development teams-- Document cleanup decisionsMonitoring and Alerting
Section titled “Monitoring and Alerting”Waste Monitoring
Section titled “Waste Monitoring”-- Monitor storage waste:-- Track empty table storage trends-- Alert on excessive waste accumulation-- Report cleanup results-- Measure storage reclamation successPolicy Implementation
Section titled “Policy Implementation”-- Cleanup policies:-- Automatic cleanup of specific table patterns-- Approval processes for production cleanup-- Documentation requirements-- Audit trail maintenanceBest Practices
Section titled “Best Practices”Cleanup Strategy
Section titled “Cleanup Strategy”Risk Assessment
Section titled “Risk Assessment”-- Assess cleanup risks:-- Verify table purpose and usage-- Check for hidden dependencies-- Coordinate with application owners-- Plan rollback proceduresImplementation Approach
Section titled “Implementation Approach”-- Systematic cleanup:-- Start with obvious temporary tables-- Progress to development environments-- Handle production tables carefully-- Document all cleanup activitiesPrevention Strategies
Section titled “Prevention Strategies”Development Practices
Section titled “Development Practices”-- Prevent future waste:-- Implement table naming conventions-- Establish cleanup procedures for testing-- Use temporary tablespaces appropriately-- Document table lifecycle expectationsAutomated Management
Section titled “Automated Management”-- Automation opportunities:-- Scheduled cleanup of temporary tables-- Policy-based table lifecycle management-- Automated space monitoring-- Integration with change managementRelated Scripts
Section titled “Related Scripts”- dstattr.sql - Table statistics report
- dtable.sql - Comprehensive table analysis
- dsegbig.sql - Large segment analysis
- dobject.sql - Database object analysis
Troubleshooting Applications
Section titled “Troubleshooting Applications”Storage Issues
Section titled “Storage Issues”Space Pressure
Section titled “Space Pressure”-- Address space constraints:-- Identify largest empty table contributors-- Prioritize reclamation by impact-- Plan immediate vs. scheduled cleanup-- Monitor space pressure reliefPerformance Impact
Section titled “Performance Impact”-- Performance considerations:-- Backup and recovery time impact-- Export/import efficiency-- Statistics gathering overhead-- Storage scan performanceCleanup Challenges
Section titled “Cleanup Challenges”Dependency Issues
Section titled “Dependency Issues”-- Handle dependencies:-- Foreign key constraints-- View dependencies-- Application code references-- Procedure and function usageCoordination Requirements
Section titled “Coordination Requirements”-- Team coordination:-- Application team approval-- Development team notification-- Operations team scheduling-- Documentation updatesSafety Considerations
Section titled “Safety Considerations”Backup and Recovery
Section titled “Backup and Recovery”Pre-Cleanup Backup
Section titled “Pre-Cleanup Backup”-- Backup strategies:-- Full backup before major cleanup-- Logical backup of affected schemas-- Table-level export for critical tables-- Recovery testing proceduresRollback Planning
Section titled “Rollback Planning”-- Rollback procedures:-- Recreation scripts for dropped tables-- Data restoration procedures-- Constraint recreation-- Application testing validationSummary
Section titled “Summary”This script is essential for:
- Storage Optimization - Identifying and reclaiming storage from empty tables that still consume space
- Database Housekeeping - Supporting regular cleanup of unused tables and storage waste
- Capacity Planning - Understanding actual vs. allocated storage utilization
- Environment Management - Cleaning up development, test, and production environments
- Cost Optimization - Reducing storage costs and improving backup/recovery efficiency