Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are SQL Server Index Usage Stats Updated?

I'm using SQL Server 2008 R2, and running the following query to try and see when an index was last updated in my database using the following SQL:

SELECT last_system_update, last_user_update,
OBJECT_NAME(object_id) AS tblName
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID('mydatabase')

The last_user_update field is correct, and contains NULL where no updates have been made to the table since the last restart of SQL Server.

When I run the following query to rebuild the index, I'd expect the last_system_update field to contain a date to indicate the index was rebuilt:

ALTER INDEX ALL ON dbo.MyTable
REBUILD

However this field remains NULL. In fact the last_system_update field is empty (NULL) for all indexes in all the databases on the server. last_user_update does not change either.

I also tried:

UPDATE STATISTICS dbo.MyTable

But no luck. So when is this field updated? And how can I force it to be updated?

like image 862
geographika Avatar asked May 18 '12 13:05

geographika


People also ask

Does SQL Server update statistics automatically?

By default, each SQL Server and Azure SQL Database has enabled Automatic statistics updates. We can verify the configuration using the is_auto_update_stats_on column value of sys.

Do we need to update stats after index creation?

No you do not need to update statistics immediately after creating index. When you create index, statistics are created with 100% of data. Running update statistics with default setting will overwrite it with sample.

When should you update statistics in SQL Server?

Updating statistics ensures that queries compile with up-to-date statistics. However, updating statistics causes queries to recompile. We recommend not updating statistics too frequently because there is a performance tradeoff between improving query plans and the time it takes to recompile queries.

When was the last time statistics is updated in SQL Server?

Well, in SQL Server, there are two ways to access the last modified date of a statistic, which are: Through the header information using DBCC SHOW_STATISTICS. Through STATS_DATE() function and sys. stats system catalog view.


1 Answers

You can use the following query to determine when the Indexes were last updated, which uses STATS_DATE():

USE your_db;
SELECT t.name AS Table_Name
      ,i.name AS Index_Name
      ,i.type_desc AS Index_Type
      ,STATS_DATE(i.object_id,i.index_id) AS Date_Updated
FROM sys.indexes i
JOIN sys.tables t
  ON t.object_id = i.object_id
WHERE i.type > 0 
ORDER BY t.name ASC
    ,i.type_desc ASC
    ,i.name ASC;

I believe this will only work with SQL Server 2005 or newer, since sys.indexes was not in SQL Server 2000.

like image 152
bhamby Avatar answered Sep 20 '22 20:09

bhamby