Query statistics for a single table

SQL Server Table Statistics

sys.stats : Contains a row for each statistics object that exists for the tables, indexes, and indexed views in the database in SQL Server.

sys.dm_db_stats_properties: Returns properties of statistics for the specified database object (table or indexed view) in the current SQL Server database.

-->>Execute the following query to check the statistics 
SELECT sp.stats_id, 
       name, 
       filter_definition, 
       last_updated, 
       rows, 
       rows_sampled, 
       steps, 
       unfiltered_rows, 
       modification_counter
FROM sys.stats AS stat
     CROSS APPLY sys.dm_db_stats_properties(stat.object_id, stat.stats_id) AS sp
WHERE stat.object_id = OBJECT_ID('HumanResources.Employee');
--Stats_ID: It is the unique ID of the statistics object
--Name: It is the statistics name
--Last_updated: It is the date and time of the last statistics update
--Rows: It shows the total number of rows at the time of the last statistics update
--Rows_sampled: It gives the total number of sample rows for the statistics
--Unfiltered_rows: In the screenshot, you can see both rows_sampled and unfiltered_rows value the same because we did not use any filter in the statistics
--Modification_counter: It is a vital column to look. We get the total number of modifications since the last statistics update

Use the following query to identify statistics auto-created by SQL Server

--->> Use the following query to identify statistics auto-created by SQL Server
SELECT sp.stats_id, 
       name, 
       filter_definition, 
       last_updated, 
       rows, 
       rows_sampled, 
       steps, 
       unfiltered_rows, 
       modification_counter
FROM sys.stats AS stat
     CROSS APPLY sys.dm_db_stats_properties(stat.object_id, stat.stats_id) AS sp
WHERE stat.object_id = OBJECT_ID('HumanResources.Employee')
and name like '_WA%';

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql?view=sql-server-ver15

The following example returns all tables, indexed views, and statistics in the current database for which the leading column was modified more than 1000 times since the last statistics update.

SELECT obj.name, obj.object_id, stat.name, stat.stats_id, last_updated, modification_counter  
FROM sys.objects AS obj   
INNER JOIN sys.stats AS stat ON stat.object_id = obj.object_id  
CROSS APPLY sys.dm_db_stats_properties(stat.object_id, stat.stats_id) AS sp  
WHERE modification_counter > 1000;  

Spread the love

Leave a Comment