识别 SQL Azure 上未使用的索引

Eoi*_*ell 6 index sql-server database-size azure-sql-database index-maintenance

我有一个大型 SQL Azure 数据库(P6 大小接近 1TB)。我想清理/删除任何未使用的索引。在过去的 30 天里,我们捕获了以下 2 组信息。

参见:https : //gist.github.com/eoincampbell/3fe775d43e86ad342f9c6eba10f350f9

  • sys.dm_db_index_physical_statsjoin 到收集的索引统计数据sys.tablessys.schemas以及sys.indexes
  • 索引使用收集自 sys.dm_db_index_usage_stats

我对sys.dm_db_index_usage_stats. 从文档中不清楚何时/是否在 SQL Azure 环境中发生以下情况(与单实例 MSSQLServer 相比)。

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-usage-stats-transact-sql?view=azuresqldb-current的每当 SQL Server (MSSQLSERVER) 服务启动时,计数器都会初始化为空。此外,无论何时分离或关闭数据库(例如,因为 AUTO_CLOSE 设置为 ON),与该数据库关联的所有行都将被删除。

这是我用于随后识别未使用索引的查询。它

  1. 获取数据库中所有索引的最新索引信息(812条记录)
  2. 获取所有索引的最新使用信息(558条记录)
  3. LEFT OUTER 将它们连接在一起
  4. 排除任何聚集/PK 索引
  5. 返回任何没有使用统计信息或任何用户读取统计信息为零的内容。

返回的总行数约为 219 行

这种方法看起来有效吗?

询问


WITH MostRecentStats (
    SchemaName, TableName, IndexName, IndexType, AllocUnitType, Pages, MostRecentAt
)
AS (
    SELECT      SchemaName, TableName, IndexName
                , IndexTypeDescription, AllocUnitTypeDescription
                , Max(PageCount) , Max(RecordDate)
    FROM        DBStats.IndexStats
    GROUP BY    SchemaName, TableName, IndexName
                , IndexTypeDescription, AllocUnitTypeDescription
    -- ****** Returns 812 Indexes across all tables ******
)
, AllCombinedUsage (
    SchemaName, TableName, IndexName
    ,user_seeks, user_scans, user_lookups, user_updates 
    , system_seeks, system_scans, system_lookups, system_updates
)
AS (
    SELECT      SchemaName, TableName, IndexName
                , sum(user_seeks), sum(user_scans), sum(user_lookups), sum(user_updates)    
                , sum(system_seeks), sum(system_scans), sum(system_lookups), sum(system_updates)
    FROM        DBStats.IndexUsage
    GROUP BY    SchemaName, TableName, IndexName
    -- Only Returns 558 Index with Usage Statistics... 
)
SELECT      a.SchemaName, a.TableName, a.IndexName, a.Pages
            , b.*
FROM        MostRecentStats a
LEFT JOIN   AllCombinedUsage b
            ON a.SchemaName = b.SchemaName 
            AND a.TableName = b.TableName
            AND a.IndexName = b.IndexName
WHERE       a.IndexName NOT LIKE 'PK_%' --Filter out all Primary Keys
AND         a.IndexType <> 'CLUSTERED INDEX' --And Clusted Indexes
AND (
            b.IndexName IS NULL --Include everything that has no index usage data
            OR
            (b.user_seeks + b.user_scans + b.user_lookups) = 0
            --Include everything with 0 User Reads on the data
)
ORDER BY    a.Pages DESC
Run Code Online (Sandbox Code Playgroud)

小智 2

您可能还需要排除唯一索引