Gathering and Checking Optimizer Statistics
The optimizer estimates the row count of each step from statistics (row counts, the number of distinct values per column, value distribution) and chooses a plan. If the data has changed a lot but the statistics have not, the estimates are wrong and the plan gets worse. If the estimated and actual row counts in an execution plan differ greatly, suspect the statistics first.
All three DBs count changed rows and automatically re-gather once a threshold is exceeded. Problems arise right after a bulk load, when queries run between automatic gathering cycles, and when conditions involve several correlated columns.
Re-gathering statistics can change the plans of SQL that uses the table. Most of the time they improve, but they can also get worse.
Oracle
Required privileges: SELECT_CATALOG_ROLE to query. The owner gathers statistics for their own schema; for other schemas, the ANALYZE ANY privilege is needed.
Checking statistics state
SELECT owner, table_name, num_rows, blocks, last_analyzed, stale_stats, stattype_locked
FROM dba_tab_statistics
WHERE owner = 'SALES' AND object_type = 'TABLE'
ORDER BY last_analyzed NULLS FIRST;
stale_stats = 'YES': rows changed since the last gathering exceedSTALE_PERCENT(default 10%). NULL means there are no statistics.- If
stattype_lockedisALL, the statistics are locked and automatic gathering skips them. - DML change counts are kept in memory and flushed periodically. To include very recent changes, first run
EXEC DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO;, then look atinserts,updates,deletesinDBA_TAB_MODIFICATIONS.
-- Column statistics and histograms
SELECT column_name, num_distinct, num_nulls, density, histogram, num_buckets, last_analyzed
FROM dba_tab_col_statistics
WHERE owner = 'SALES' AND table_name = 'ORDERS';
Gathering statistics
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(
ownname => 'SALES',
tabname => 'ORDERS',
estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,
method_opt => 'FOR ALL COLUMNS SIZE AUTO',
cascade => TRUE,
no_invalidate => DBMS_STATS.AUTO_INVALIDATE,
degree => 4);
END;
/
-- Only stale or missing ones in the schema
EXEC DBMS_STATS.GATHER_SCHEMA_STATS('SALES', options => 'GATHER AUTO');
- Most of the arguments above equal the defaults. If you have not changed the defaults,
GATHER_TABLE_STATS('SALES', 'ORDERS')alone is enough. - With
no_invalidate => FALSE, related cursors are invalidated immediately and plans are rebuilt on the next execution. The default (AUTO_INVALIDATE) invalidates them gradually over a period of time. - Automatic gathering is the
auto optimizer stats collectionjob that runs in the maintenance window. Check its status inDBA_AUTOTASK_CLIENT.
WARNING Plans can change from the moment statistics are gathered. For important tables, first confirm that you can roll back using the history below (
RESTORE_TABLE_STATS). Gathering on large tables uses a lot of I/O.
Changing the gathering threshold
SELECT DBMS_STATS.GET_PREFS('STALE_PERCENT', 'SALES', 'ORDERS') FROM dual;
EXEC DBMS_STATS.SET_TABLE_PREFS('SALES', 'ORDERS', 'STALE_PERCENT', '5');
For large, frequently changing tables, lowering the threshold makes automatic gathering run more often.
Locking statistics
For tables whose values swing widely (such as temporary work tables), gather statistics at a representative point and then lock them.
EXEC DBMS_STATS.LOCK_TABLE_STATS('SALES', 'ORDERS_STAGE');
EXEC DBMS_STATS.UNLOCK_TABLE_STATS('SALES', 'ORDERS_STAGE');
Running GATHER_TABLE_STATS on a locked table raises ORA-20005 (it can be overridden with force => TRUE).
Restoring previous statistics
SELECT table_name, stats_update_time
FROM dba_tab_stats_history
WHERE owner = 'SALES' AND table_name = 'ORDERS'
ORDER BY stats_update_time DESC;
BEGIN
DBMS_STATS.RESTORE_TABLE_STATS(
ownname => 'SALES',
tabname => 'ORDERS',
as_of_timestamp => TIMESTAMP '2026-11-24 22:00:00 +09:00');
END;
/
- History is kept for 31 days by default (
DBMS_STATS.GET_STATS_HISTORY_RETENTION). - To keep the restored statistics from going stale again, lock them or fix the gathering settings that caused the problem.
WARNING Restored statistics may not match the current data. Use this as an emergency revert when a plan suddenly gets worse.
Relationships between columns (extended statistics)
For correlated columns such as WHERE city = 'Seoul' AND country = 'KR', multiplying their selectivities separately underestimates the row count. Create column group statistics.
SELECT DBMS_STATS.CREATE_EXTENDED_STATS('SALES', 'CUSTOMERS', '(city, country)') FROM dual;
EXEC DBMS_STATS.GATHER_TABLE_STATS('SALES', 'CUSTOMERS', method_opt => 'FOR COLUMNS (city, country) SIZE AUTO');
SELECT extension_name, extension FROM dba_stat_extensions WHERE table_name = 'CUSTOMERS';
PostgreSQL
Required privileges: ANALYZE requires the table owner, the database owner, or a superuser (in PostgreSQL 17+, the MAINTAIN privilege or the pg_maintain role also works).
Checking statistics state
SELECT s.relname, s.n_live_tup, s.n_mod_since_analyze,
s.last_analyze, s.last_autoanalyze, c.reltuples::bigint AS planner_rows
FROM pg_stat_user_tables s
JOIN pg_class c ON c.oid = s.relid
ORDER BY s.n_mod_since_analyze DESC
LIMIT 20;
n_mod_since_analyze: the number of rows changed since the last ANALYZE.reltuplesis the row count used by the planner. In PostgreSQL 14+, -1 means the table has never been VACUUMed or ANALYZEd.
-- Column statistics
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs,
histogram_bounds, correlation
FROM pg_stats
WHERE schemaname = 'public' AND tablename = 'orders';
A negative n_distinct is a ratio to the row count (-1 means all values are unique).
Gathering statistics
ANALYZE orders;
ANALYZE VERBOSE orders (customer_id, status); -- only some columns
-- For columns with skewed distribution, increase the sample and MCV count (default default_statistics_target = 100)
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders (status);
- ANALYZE reads only a sample (
300 × statistics targetrows), so even large tables do not take long. It does not block writes. - Right after a bulk load or bulk delete, run ANALYZE immediately instead of waiting for autovacuum.
- Autovacuum does not ANALYZE the parent of a partitioned table. If you need parent-level statistics, run
ANALYZE parent_table;yourself. - After upgrading a major version with
pg_upgrade, there are no statistics, so runvacuumdb --all --analyze-in-stages(17 and earlier).
WARNING After ANALYZE, the plans of queries that use the table can change immediately. There is no feature to restore previous statistics.
Automatic ANALYZE threshold
Autovacuum runs ANALYZE when changed rows exceed autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × reltuples (default 50 + 10%).
-- Lower the ratio for large tables
ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.02, autovacuum_analyze_threshold = 1000);
SELECT relname, reloptions FROM pg_class WHERE reloptions IS NOT NULL;
Relationships between columns (extended statistics)
CREATE STATISTICS customers_city_country (dependencies, ndistinct, mcv) -- mcv: 12+
ON city, country FROM customers;
ANALYZE customers;
SELECT statistics_name, attnames, kinds, n_distinct, dependencies
FROM pg_stats_ext
WHERE tablename = 'customers';
dependencies: the degree to which one column determines another.ndistinct: the number of distinct values of a column combination (forGROUP BYestimates).mcv: frequently occurring values per combination.- They are populated only after ANALYZE following creation. In 14+, they can also be created on expressions (
ON (lower(email)) FROM ...).
SQL Server
Required privileges: permission to view table metadata to query. UPDATE STATISTICS requires ALTER on the table; sp_updatestats requires sysadmin or the DB owner (dbo).
Checking statistics state
SELECT OBJECT_NAME(s.object_id) AS table_name, s.name AS stats_name,
s.auto_created, s.no_recompute,
sp.last_updated, sp.rows, sp.rows_sampled, sp.modification_counter, sp.steps
FROM sys.stats s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp
WHERE OBJECTPROPERTY(s.object_id, 'IsUserTable') = 1
ORDER BY sp.modification_counter DESC;
modification_counter: the number of times the leading column has changed since the last update.- If
rows_sampledis much smaller thanrows, the statistics are sampled. For columns with skewed distribution, a small sample makes the histogram inaccurate. - Names starting with
_WA_Sys_are automatically created column statistics.
-- Histogram
DBCC SHOW_STATISTICS ('dbo.orders', 'IX_orders_customer_id') WITH HISTOGRAM;
SELECT step_number, range_high_key, range_rows, equal_rows, distinct_range_rows
FROM sys.dm_db_stats_histogram(OBJECT_ID('dbo.orders'), 2); -- 2016 SP1 CU2+
Auto-update settings and threshold
SELECT name, is_auto_create_stats_on, is_auto_update_stats_on,
is_auto_update_stats_async_on, compatibility_level
FROM sys.databases;
- At compatibility level 130 (2016)+, the update threshold for large tables is the smaller of
500 + 20%andSQRT(1000 × row count). Below that level it is500 + 20%, so large tables go a long time without an update. - Automatic updates happen when a query that uses the statistics is compiled. With asynchronous updates (
AUTO_UPDATE_STATISTICS_ASYNC) on, the query runs first with the stale statistics and the update happens in the background.
Updating statistics
UPDATE STATISTICS dbo.orders; -- all statistics of the table, default sample
UPDATE STATISTICS dbo.orders IX_orders_customer_id WITH FULLSCAN; -- one statistic, with a full scan
UPDATE STATISTICS dbo.orders WITH SAMPLE 10 PERCENT, PERSIST_SAMPLE_PERCENT = ON;
EXEC sp_updatestats; -- only statistics with changed rows in the current DB, default sample
PERSIST_SAMPLE_PERCENT(2016 SP1 CU4+, 2017 CU1+) makes later automatic updates use the same sample percentage. Without it, automatic updates overwrite it again with the default sample.sp_updatestatsupdates every statistic that had even one row change, so it can take a long time on a large DB. Statistics built with a full scan (for example right after an indexREBUILD) are also overwritten with the default sample if rows have changed since.
WARNING Queries that use the updated statistics are recompiled and their plans can change. There is no feature to restore previous statistics, so for important tables, save the
DBCC SHOW_STATISTICSoutput before updating.FULLSCANuses a lot of I/O on large tables.
Preventing automatic updates
UPDATE STATISTICS dbo.orders_stage WITH FULLSCAN, NORECOMPUTE;
-- Allow again: update without NORECOMPUTE
UPDATE STATISTICS dbo.orders_stage WITH FULLSCAN;
A statistic given NORECOMPUTE is excluded from automatic updates (sys.stats.no_recompute = 1). This is similar to locking statistics in Oracle, but it does not block manual updates.
WARNING Statistics with automatic updates turned off stay as they are even when the data changes. Keep a record of which statistics you set this on and update them manually on a regular basis.
Relationships between columns
Multi-column statistics are created with CREATE STATISTICS. The histogram is built only on the first column; for the rest, only the density of the column combination (the ratio of distinct values) is stored.
CREATE STATISTICS st_customers_city_country ON dbo.customers (city, country) WITH FULLSCAN;