Skip to main content
Our Tech Ideas

How to get all statistics information for a database in SQL Server

Introduction:

Sometimes your query gives you very bad performance because of statistics as SQL database engine Query optimizer uses statistics to create query plans. Updated statistics will give you good performance.

To get the statistics information for a particular database, you can use the below script. You can update the statistics by using the below stored procedure.

exec sp_updatestats

Script:

-- ============================ --
-- Owner: SOYELUDDIN BISWAS     --
-- Created Date: 03/10/2019     --
-- Email: st.biswas99@gmail.com --
-- ============================ --
--select OBJECT_ID('#AllStatistics')
--Please run this query to specifc database to get all the statistics informations
DECLARE @TableName NVARCHAR(100);
DECLARE @StatName NVARCHAR(100);
DECLARE @UpdateDate DateTime;
DECLARE @NoOfRows BigInt

IF OBJECT_ID('tempdb..#AllStatistics') IS NOT NULL DROP TABLE #AllStatistics
CREATE TABLE #AllStatistics
(
TableName NVARCHAR(100),
StatName NVARCHAR(100),
UpdateDate DateTime,
NoOfRows BigInt
)
INSERT INTO #AllStatistics exec sp_MSforeachtable 
'SELECT OBJECT_NAME(stat.object_id),  
stat.name, 
last_updated,
rows
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(''?'') and stat.name not like ''_WA_%'''

SELECT 
TableName AS [Table Name],
StatName as [Statistics Name],
UpdateDate as[Last Update Time],
NoOfRows as [No of rows] 
from #AllStatistics Order by 1 ASC

DROP TABLE #AllStatistics
-- rows= Total number of rows in the table or indexed view when statistics were last updated. 

Result:

SQL Database statistics
SQL Database statistics