SQL Server error 304—*"Out of range for index statistics"*—occurs when the query optimizer cannot use statistical data for an index because the stored statistics are too old, incomplete, or skewed. This prevents the engine from selecting the best execution plan, often resulting in suboptimal performance or even query failures. The fix is simple: manually update the statistics for the affected indexes, and the optimizer will rerun them. Below, you’ll get a clear, actionable workflow to diagnose and resolve this issue without disrupting production.
What You'll Need
- A SQL Server instance (Standard, Enterprise, or Express) with administrative access to the database.
- SSMS (SQL Server Management Studio), SQL CLI, or a script editor capable of running DDL/TQL commands.
- Identification of the problematic query or table (often found via query store, execution plans, or error logs).
- Optional: A backup of the database (optional but recommended if you’re testing script changes in production).
- Permissions to alter statistics on the affected tables (typically requires database owner or sysadmin roles).
Step-by-Step
-
Identify the query or table causing the error.
Use one of these methods to pinpoint the issue:
- Check the SQL Server error logs for the specific error 304 and note the table/index involved.
- Enable query store (if available) and analyze recent query performance. Look for queries marked as "unoptimized" or with plans that exclude index usage.
- Run this query in a new SSMS query window to list statistics for each table:
SELECT OBJECT_NAME(object_id) AS TableName, STATISTICS_COMPUTED_DESCRIPTION FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) WHERE index_id > 0;Filter the results for tables with aStatistics computedflag offalseorStats collected manually. - Search execution plans for queries that display the error 304 message, such as:
Msg 304, Level 16, State 1, Line 1 Out of range for index statistics Table 'MyDB.MyTable'. Can't get statistics for this table.These often appear in queries involving large tables or complex joins.
-
Recalculate statistics for the problematic indexes.
Use one of these methods to manually update statistics, depending on the table size and complexity:
- For small to medium tables (recommended for most cases):
- Right-click the table in SSMS > Design > Statistics tab > Select the problematic index > Click Recompute.
- Alternatively, run this script in a query window:
EXEC sp_updatestats @EstimateForALLRows = 1;This recalculates statistics for all indexes in the database. For targeted updates, use:EXEC sp_updatestats 'MyDatabase', 'MyTable', 'MyIndexName'Replace placeholders with your actual table/database/index names. - For large tables (avoid
sp_updatestats @EstimateForALLRows = 1in production): - Usesp_updatestatswith@EstimateForALLRows = 0and specify only the index with the missing statistics:EXEC sp_updatestats @EstimateForALLRows = 0, @IncludedColumns = '*' -- or specify columns explicitly FROM 'MyDatabase', 'MyTable', 'MyIndexName'- This prevents the optimizer from estimating statistics for every row, which can be slow and inaccurate for large tables. - For clustered indexes:
Some indexes (especially clustered) may not support manual statistics updates via
sp_updatestats. In this case, update statistics after runningALTER TABLE ... WITH (REBUILD):ALTER TABLE MyTable REBUILD (INDEX MyClusteredIndex)Then verify statistics are recomputed:EXEC sp_helptext 'MyTable'
- For small to medium tables (recommended for most cases):
- Right-click the table in SSMS > Design > Statistics tab > Select the problematic index > Click Recompute.
- Alternatively, run this script in a query window:
-
Verify the fix.
Check that the error 304 no longer appears in queries:
- Run the same queries that previously triggered error 304. If they now complete, the fix succeeded.
- Recheck the query store or execution plans for updated statistics:
SELECT name, description FROM sys.dm_db_partition_stats WHERE index_id > 0;Look forStats collected manuallyentries. - If using
sp_updatestats @EstimateForALLRows = 1, monitor performance: statistics updates can temporarily impact throughput as the optimizer recalculates values.
Common Mistakes
- Skipping backup before updating statistics.
While
sp_updatestatsis safe, large updates can fail silently or crash the engine. Always take a full database backup before running it in production. - Overestimating the impact of
@EstimateForALLRows = 1. This flag forces the optimizer to useNULLstatistics for all rows, which is often right but can lead to suboptimal plans in some scenarios. Reserve it for troubleshooting. - Ignoring clustered index updates.
Rebuilding clustered indexes after updating other statistics can resolve lingering 304 errors. Clustered indexes require explicit
ALTER TABLE REBUILD. - Running updates during peak workload. Statistics recalculation can cause temporary I/O spikes. Schedule updates during off-hours unless the issue is urgent.
- Assuming all indexes need updating. Only update statistics for indexes involved in the problematic queries. Unnecessary updates waste time and resources.
Tips
- Automate statistics updates.
For production databases, create a scheduled job (using
sp_store_routineor T-SQL) to update statistics for high-impact tables weekly or monthly. Example:IF OBJECT_ID('dbo.UpdateStatsJob') IS NOT NULL DROP PROCEDURE dbo.UpdateStatsJob; CREATE PROCEDURE dbo.UpdateStatsJob AS BEGIN EXEC sp_updatestats @EstimateForALLRows = 0, @IncludedColumns = '*' -- or specify columns FROM 'MyDatabase', 'MyTable', 'MyIndexName'; END; - Use
OPTION (RECOMPILE)sparingly. If error 304 persists, query plans may need recompilation. AddOPTION (RECOMPILE)to the query to bypass the optimizer’s reliance on statistics. - Monitor query execution counts.
After updating statistics, run queries repeatedly to verify the optimizer picks the correct plan. Use
SET STATISTICS TIME, IO ONto profile performance. - Consider
sp_estimate_estimator. For complex queries, runsp_estimate_estimatorto manually test the optimizer’s decisions before applyingsp_updatestats. - Watch for skewed statistics.
If
sp_updatestatsstill fails, the statistics may be skewed (e.g., due to uneven data distribution). Rebuild the indexWITH (FILLFACTOR = xx)or useINCLUDEcolumns to limit skew impact.
Troubleshooting
If you run sp_updatestats or ALTER TABLE REBUILD but error 304 persists, try these steps:
-
Check for other missing statistics.
Run:
SELECT OBJECT_NAME(object_id), STATISTICS_COMPUTED_DESCRIPTION FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) WHERE STATISTICS_COMPUTED_DESCRIPTION IS NULL;and update all missing statistics at once. Error 304 can cascade if other statistics are unavailable. -
Force-recalculate statistics for specific rows.
For large tables, run:
EXEC sp_updatestats @EstimateForALLRows = 0, @EstimateForAllRowsIncluded = 1, @EstimateForAllRowsIncludedColumn = 'ColumnName'to recalculate only the columns involved in the problematic query. -
Verify the table is not locked.
Use
sys.dm_tran_locksto check for blocking:SELECT * FROM sys.dm_tran_locks WHERE resource_type = 'KEY' AND resource_database_id = DB_ID();If locked, contact your DBA to release the locks. -
Test with
OPTION (OPTIMIZE FOR). If the query involves unknown data distribution, add:OPTION (OPTIMIZE FOR UNKNOWN)to force the optimizer to use sample statistics. - Restore from backup if the issue recurs. If statistics updates keep failing, the database may be corrupted. Restore from a known-good backup and recreate statistics manually.
Frequently Asked Questions
Why does SQL Server need index statistics?
Index statistics provide the optimizer with data distribution information (e.g., how often values appear, their cardinality). Without accurate stats, the optimizer cannot choose the best index or plan, leading to errors like 304 or poor performance.How often should I update statistics?
For most databases, update statistics weekly or monthly. For critical tables, recalculate after major data changes (e.g., inserts/deletes) or when query plans degrade. Automate updates for stability.Can I update statistics for a single column?
Yes. Use:EXEC sp_updatestats @EstimateForALLRows = 0,
@IncludedColumns = 'ColumnName'
to update only the specified column(s). This prevents recalculating unrelated statistics.
What if sp_updatestats fails with "Statistics collection failed"?
The error may indicate a permissions issue or resource contention. Try:
- Running as sysadmin.
- Running during low-traffic periods.
- Increasing the database’s memory allocation if the server is memory-constrained.
Is it safe to run sp_updatestats @EstimateForALLRows = 1 in production?
It is safe but can impact performance. Reserve it for troubleshooting. For large databases, use @EstimateForALLRows = 0 with targeted indexes.
Why do clustered index statistics update differently?
Clustered index statistics require rebuilding the index to update, as they are stored physically with the table data. UseALTER TABLE REBUILD instead of sp_updatestats for clustered indexes.