Category Archives: Performance Tuning

Index Maintenance Query, Rebuid (>40)or Reorganize (>10)

Below query will generated list of indexes to be re organized or rebuild based on 10-40 Rule.

>=40 % Rebuild

>=10 and <40 ReOrganize

— This query is tested on working fine.

 

 

  SELECT ‘ALTER INDEX [‘ + ix.name + ‘] ON [‘ + s.name + ‘].[‘ + t.name + ‘] ‘ +

       CASE WHEN ps.avg_fragmentation_in_percent >= 40 THEN ‘REBUILD’ ELSE ‘REORGANIZE’ END +

       CASE WHEN pc.partition_count > 1 THEN ‘ PARTITION = ‘ + cast(ps.partition_number as nvarchar(max)) ELSE ” END

FROM   sys.indexes AS ix

 

INNER JOIN sys.tables t  ON t.object_id = ix.object_id

       INNER JOIN sys.schemas s     ON t.schema_id = s.schema_id

       INNER JOIN(SELECT object_id, index_id, avg_fragmentation_in_percent, partition_number

                   FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL)) ps

           ON t.object_id = ps.object_id AND ix.index_id = ps.index_id

       INNER JOIN(SELECT object_id, index_id, COUNT(DISTINCT partition_number) AS partition_count

                   FROM sys.partitions

                   GROUP BY object_id, index_id) pc

           ON t.object_id = pc.object_id AND ix.index_id = pc.index_id

WHERE  ps.avg_fragmentation_in_percent >= 10 AND

       ix.name IS NOT NULL

 

 

Advertisements

SQL Server index related dynamic management views and functions

Microsoft SQL Server provides DBAs and Developers with several index related dynamic management views and functions, which they can use to maintain, modify, tune and identify missing indexes. Some of these dynamic management views (DMVs) and functions (DMFs) you might use are listed as follow:

  • sys.dm_db_index_operational_stats — Returns information about low level input/output (I/O) operations, locking and latching contention, and access methods.
  • sys.dm_db_index_usage_stats — Returns an index operations count, identifying operations performed and the last time each operation was performed.
  • sys.dm_db_index_physical_stats — Returns information about table and index size and fragmentation, including both in-row and LOB data.
  • sys.dm_db_missing_index_details — Returns detailed information about missing indexes, including the table, columns used in equality operations, columns used in inequality operations, and columns used in include operations.
  • sys.dm_db_missing_index_group_stats — Returns information about groups of missing indexes, which SQL Server updates with each query execution (not based on query compilation or recompilation).
  • sys.dm_db_missing_index_groups — Returns information about missing indexes contained in a missing index group.