Hey everyone,
I'm a long time "lurker" on these forums and I need some help with some of my Queries.
So I need to find out the average percentage of fragmentation on each Index. So I ran this Query:
SELECT dbschemas.[name] as 'Schema', dbtables.[name] as 'Table', dbindexes.[name] as 'Index', indexstats.avg_fragmentation_in_percent, indexstats.page_count FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id] INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id] INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id] AND indexstats.index_id = dbindexes.index_id WHERE indexstats.database_id = DB_ID() ORDER BY indexstats.avg_fragmentation_in_percent desc
Then I ran this Query to either rebuild indexes with fragmentation higher than 30% and reorganize indexes with fragmentation higher than 10%.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED CREATE TABLE #FragmentedIndexes ( DatabaseName SYSNAME , SchemaName SYSNAME , TableName SYSNAME , IndexName SYSNAME , [Fragmentation%] FLOAT ) INSERT INTO #FragmentedIndexes SELECT DB_NAME(DB_ID()) AS DatabaseName , ss.name AS SchemaName , OBJECT_NAME (s.object_id) AS TableName , i.name AS IndexName , s.avg_fragmentation_in_percent AS [Fragmentation%] FROM sys.dm_db_index_physical_stats(db_id(),NULL, NULL, NULL, 'DETAILED') s INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id INNER JOIN sys.objects o ON s.object_id = o.object_id INNER JOIN sys.schemas ss ON ss.[schema_id] = o.[schema_id] WHERE s.database_id = DB_ID() AND i.index_id != 0 AND s.record_count > 0 AND o.is_ms_shipped = 0 DECLARE @RebuildIndexesSQL NVARCHAR(MAX) SET @RebuildIndexesSQL = '' SELECT @RebuildIndexesSQL = @RebuildIndexesSQL + CASE WHEN [Fragmentation%] > 30 THEN CHAR(10) + 'ALTER INDEX ' + QUOTENAME(IndexName) + ' ON '+ QUOTENAME(SchemaName) + '.'+ QUOTENAME(TableName) + ' REBUILD;' WHEN [Fragmentation%] > 10 THEN CHAR(10) + 'ALTER INDEX ' + QUOTENAME(IndexName) + ' ON '+ QUOTENAME(SchemaName) + '.'+ QUOTENAME(TableName) + ' REORGANIZE;' END FROM #FragmentedIndexes WHERE [Fragmentation%] > 10 DECLARE @StartOffset INT DECLARE @Length INT SET @StartOffset = 0 SET @Length = 4000 WHILE (@StartOffset < LEN(@RebuildIndexesSQL)) BEGIN PRINT SUBSTRING(@RebuildIndexesSQL, @StartOffset, @Length) SET @StartOffset = @StartOffset + @Length END PRINT SUBSTRING(@RebuildIndexesSQL, @StartOffset, @Length) EXECUTE sp_executesql @RebuildIndexesSQL DROP TABLE #FragmentedIndexes
What was returned:
(710 row(s) affected) ALTER INDEX [cndx_PrimaryKey_SolutionComponent] ON [dbo].[SolutionComponentBase] REORGANIZE; ALTER INDEX [ndx_Solution_Component] ON [dbo].[SolutionComponentBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SolutionComponentBase] REBUILD; ALTER INDEX [UQ_SdkMessageRequestBase_SdkMessageRequestIdUnique] ON [dbo].[SdkMessageRequestBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageRequestBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_Template] ON [dbo].[TemplateBase] REORGANIZE; ALTER INDEX [PK_SdkMessageResponseBaseIds] ON [dbo].[SdkMessageResponseBaseIds] REBUILD; ALTER INDEX [PK_SdkMessageRequestBaseIds] ON [dbo].[SdkMessageRequestBaseIds] REBUILD; ALTER INDEX [ndx_entity_logicalname] ON [MetadataSchema].[Entity] REBUILD; ALTER INDEX [ndx_entity_name] ON [MetadataSchema].[Entity] REBUILD; ALTER INDEX [ndx_entity_physicalname] ON [MetadataSchema].[Entity] REBUILD; ALTER INDEX [PK_SdkMessagePairBaseIds] ON [dbo].[SdkMessagePairBaseIds] REBUILD; ALTER INDEX [UQ_SdkMessageRequestFieldBase_SdkMessageRequestFieldIdUnique] ON [dbo].[SdkMessageRequestFieldBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageRequestFieldBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_PluginType] ON [dbo].[PluginTypeBase] REBUILD; ALTER INDEX [PK_SdkMessageBaseIds] ON [dbo].[SdkMessageBaseIds] REBUILD; ALTER INDEX [cndx_PrimaryKey_ReportCategory] ON [dbo].[ReportCategoryBase] REBUILD; ALTER INDEX [XPKRelationshipIds] ON [dbo].[RelationshipIds] REBUILD; ALTER INDEX [cndx_PrimaryKey_PrivilegeObjectTypeCodes] ON [dbo].[PrivilegeObjectTypeCodes] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[PrivilegeObjectTypeCodes] REBUILD; ALTER INDEX [ndx_Unique_PrivilegeObjectTypeCodePrivilegeId] ON [dbo].[PrivilegeObjectTypeCodes] REBUILD; ALTER INDEX [ndx_for_cascaderelationship_FK_PrivilegeObjectTypeCodes] ON [dbo].[PrivilegeObjectTypeCodes] REBUILD; ALTER INDEX [ndx_Cover] ON [dbo].[PrivilegeObjectTypeCodes] REBUILD; ALTER INDEX [PK_SdkMessageProcessingStepBaseIds] ON [dbo].[SdkMessageProcessingStepBaseIds] REBUILD; ALTER INDEX [PK_SdkMessageFilterBaseIds] ON [dbo].[SdkMessageFilterBaseIds] REBUILD; ALTER INDEX [UQ_RibbonRuleBase_UniqueRowId] ON [dbo].[RibbonRuleBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[RibbonRuleBase] REBUILD; ALTER INDEX [XPKLocalizedLabel] ON [MetadataSchema].[LocalizedLabel] REBUILD; ALTER INDEX [cndx_PrimaryKey_Report] ON [dbo].[ReportBase] REORGANIZE; ALTER INDEX [cndx_PrincipalObjectAccess] ON [dbo].[PrincipalObjectAccess] REBUILD; ALTER INDEX [ndx_WebResourceNames] ON [dbo].[WebResourceBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_Privilege] ON [dbo].[PrivilegeBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[PrivilegeBase] REBUILD; ALTER INDEX [ndx_SystemManaged_Privilege] ON [dbo].[PrivilegeBase] REBUILD; ALTER INDEX [ndx_AttributePicklistValue_MetadataCache] ON [MetadataSchema].[AttributePicklistValue] REORGANIZE; ALTER INDEX [fndx_for_cascaderelationship_PickListMapping_ColumnMapping] ON [dbo].[PickListMappingBase] REBUILD; ALTER INDEX [UQ_SystemFormBase_FormIdUnique] ON [dbo].[SystemFormBase] REBUILD; ALTER INDEX [ndx_Type_ObjectType_Default] ON [dbo].[SystemFormBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SystemFormBase] REBUILD; ALTER INDEX [ndx_SystemManaged_SystemForm] ON [dbo].[SystemFormBase] REBUILD; ALTER INDEX [NDX_AttrLookupValAttrIdEntityIdCompState] ON [MetadataSchema].[AttributeLookupValue] REORGANIZE; ALTER INDEX [PK__IndexAttributes__3B8BB150] ON [MetadataSchema].[IndexAttributes] REORGANIZE; ALTER INDEX [UQ_IndexIdAttributeId] ON [MetadataSchema].[IndexAttributes] REORGANIZE; ALTER INDEX [ndx_Relationship_MetadataCache] ON [MetadataSchema].[Relationship] REORGANIZE; ALTER INDEX [UQ_AttributeMapBase_AttributeMapIdUnique] ON [dbo].[AttributeMapBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[AttributeMapBase] REBUILD; ALTER INDEX [ndx_for_cascaderelationship_entity_map_attribute_maps] ON [dbo].[Attr ibuteMapBase] REBUILD; ALTER INDEX [fndx_for_cascaderelationship_attribute_map_attribute_maps] ON [dbo].[AttributeMapBase] REBUILD; ALTER INDEX [ndx_names] ON [dbo].[AttributeMapBase] REORGANIZE; ALTER INDEX [cndx_RecordCountSnapshot_ObjectTypeCode] ON [dbo].[RecordCountSnapshot] REBUILD; ALTER INDEX [cndx_PrimaryKey_lookupmapping] ON [dbo].[LookUpMappingBase] REBUILD; ALTER INDEX [ndx_EntityRelationship_MetadataCache] ON [MetadataSchema].[EntityRelationship] REORGANIZE; ALTER INDEX [cndx_PrimaryKey_ComplexControl] ON [dbo].[ComplexControlBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_BulkDeleteOperation] ON [dbo].[BulkDeleteOperationBase] REBUILD; ALTER INDEX [XPKEntityRelationshipIds] ON [dbo].[EntityRelationshipIds] REORGANIZE; ALTER INDEX [XPKStoredProcedureCatalog] ON [MetadataSchema].[StoredProcedureCatalog] REBUILD; ALTER INDEX [ndx_EntityRelationshipRelationships_MetadataCache] ON [MetadataSchema].[EntityRelationshipRelationships] REORGANIZE; ALTER INDEX [cndx_primarykey_timezonerule] ON [dbo].[TimeZoneRuleBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[TimeZoneRuleBase] REBUILD; ALTER INDEX [ndx_for_cascaderelationship_timezonerule_timezonedefinitionid] ON [dbo].[TimeZoneRuleBase] REBUILD; ALTER INDEX [ndx_timezoneruleversionnumber_timezonerule] ON [dbo].[TimeZoneRuleBase] REBUILD; ALTER INDEX [ndx_ViewAttribute_MetadataCache] ON [MetadataSchema].[ViewAttribute] REORGANIZE; ALTER INDEX [ndx_AttributeId] ON [MetadataSchema].[ViewAttribute] REORGANIZE; ALTER INDEX [cndx_PrimaryKey_SdkMessageResponse] ON [dbo].[SdkMessageResponseBase] REBUILD; ALTER INDEX [UQ_SdkMessageResponseBase_SdkMessageResponseIdUnique] ON [dbo].[SdkMessageResponseBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageResponseBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_SavedQueryVisualization] ON [dbo].[SavedQueryVisualizationBase] REORGANIZE; ALTER INDEX [cndx_PrimaryKey_ReportVisibility] ON [dbo].[ReportVisibilityBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_TransformationMapping] ON [dbo].[TransformationMappingBase] REBUILD; ALTER INDEX [UQ_SdkMessageFilterBase_SdkMessageFilterIdUnique] ON [dbo].[SdkMessageFilterBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageFilterBase] REBUILD; ALTER INDEX [ndx_Cover_SdkMessageFilter] ON [dbo].[SdkMessageFilterBase] REORGANIZE; ALTER INDEX [UQ_SdkMessagePairBase_SdkMessagePairIdUnique] ON [dbo].[SdkMessagePairBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessagePairBase] REBUILD; ALTER INDEX [ndx_Core] ON [dbo].[ColumnMappingBase] REBUILD; ALTER INDEX [fndx_for_cascaderelationship_ColumnMapping_ImportMap] ON [dbo].[ColumnMappingBase] REBUILD; ALTER INDEX [UQ_SdkMessageProcessingStepBase_SdkMessageProcessingStepIdUnique] ON [dbo].[SdkMessageProcessingStepBase] REORGANIZE; ALTER INDEX [UQ_SdkMessageBase_SdkMessageIdUnique] ON [dbo].[SdkMessageBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageBase] REBUILD; ALTER INDEX [ndx_Name] ON [dbo].[SdkMessageBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_KbArticleTemplate] ON [dbo].[KbArticleTemplateBase] REBUILD; ALTER INDEX [UQ_RibbonCommandBase_UniqueRowId] ON [dbo].[RibbonCommandBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[RibbonCommandBase] REORGANIZE; ALTER INDEX [ndx_Core] ON [dbo].[SavedQueryBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SavedQueryBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_AsyncOperation] ON [dbo].[AsyncOperationBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_ImportEntityMapping] ON [dbo].[ImportEntityMappingBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_ReportEntity] ON [dbo].[ReportEntityBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_StatusMap] ON [dbo].[StatusMapBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_StringMap] ON [dbo].[StringMapBase] REORGANIZE; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[StringMapBase] REORGANIZE; ALTER INDEX [cndx_PrimaryKey_MailMergeTemplate] ON [dbo].[MailMergeTemplateBase] REBUILD; ALTER INDEX [U Q_RibbonDiffBase_UniqueRowId] ON [dbo].[RibbonDiffBase] REORGANIZE; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[RibbonDiffBase] REBUILD; ALTER INDEX [XPKOptionSetIds] ON [dbo].[OptionSetIds] REBUILD; ALTER INDEX [UQ_SdkMessageResponseFieldBase_SdkMessageResponseFieldIdUnique] ON [dbo].[SdkMessageResponseFieldBase] REBUILD; ALTER INDEX [fndx_Sync_VersionNumber] ON [dbo].[SdkMessageResponseFieldBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_EntityMap] ON [dbo].[EntityMapBase] REBUILD; ALTER INDEX [PK_OptionSet] ON [MetadataSchema].[OptionSet] REORGANIZE; ALTER INDEX [ndx_OptionSet_Name] ON [MetadataSchema].[OptionSet] REORGANIZE; ALTER INDEX [cndx_PrimaryKey_RibbonCustomization] ON [dbo].[RibbonCustomizationBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_DisplayStringMap] ON [dbo].[DisplayStringMapBase] REORGANIZE; ALTER INDEX [ndx_for_cascaderelationship_DisplayString_DisplayStringMaps] ON [dbo].[DisplayStringMapBase] REORGANIZE; ALTER INDEX [cndx_primarykey_timezonedefinition] ON [dbo].[TimeZoneDefinitionBase] REBUILD; ALTER INDEX [ndx_SystemManaged_TimeZoneDefinition] ON [dbo].[TimeZoneDefinitionBase] REBUILD; ALTER INDEX [cndx_PrimaryKey_TransformationParameterMapping] ON [dbo].[TransformationParameterMappingBase] REBUILD;
I need to make sure of a few things. My database is small and does not have a lot of fragmentation's so I can figure out if this works or not. I know that the percentage will not go down in indexes that have low page counts. I also figured that it is the industries best practice to not run this unless their are over 1000 pages in a specific index (correct me if I am wrong).
Both strings work and it does state that amount of rows affected once I run the Rebuild/Reorganize. But I need to make sure. I am relatively new to being a DBA and I don't want to mess up our project. I'm using a mock data that I created with CRM. This is currently being used in a virutalbox. I would really appreciate if someone has a string I can run or a database .mdi file with a lot of fragmentation to see if this works or not.
Thank you in advance for everything. I posted my result after each Query to show what returned.