Skip to content

Instantly share code, notes, and snippets.

@tcartwright
Last active October 22, 2025 14:10
Show Gist options
  • Save tcartwright/072297fd9ba1968e8dd9d4087f5e8ba4 to your computer and use it in GitHub Desktop.
Save tcartwright/072297fd9ba1968e8dd9d4087f5e8ba4 to your computer and use it in GitHub Desktop.
SQL SERVER: Index column analysis
/*
-- Brent Ozars script:
EXEC dbo.sp_BlitzIndex @SchemaName='dbo', @TableName='TableName', @fullOutput = 1
*/
-- makes it very easy to spot possible duplicates that can be combined.
SELECT
[i].[name] AS IndexName,
[i].[type_desc] AS IndexType,
STUFF(
(
SELECT ', ' + QUOTENAME([c2].[name])
FROM sys.[index_columns] AS [ic2] WITH (nolock)
INNER JOIN sys.[columns] AS [c2] WITH (nolock)
ON [ic2].[object_id] = [c2].[object_id]
AND [ic2].[column_id] = [c2].[column_id]
WHERE [ic2].[object_id] = [i].[object_id]
AND [ic2].[index_id] = [i].[index_id]
AND [ic2].[is_included_column] = 0
ORDER BY [c2].[column_id]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1, 2, ''
) AS KeyColumnList,
STUFF(
(
SELECT ', ' + QUOTENAME([c3].[name])
FROM sys.[index_columns] AS [ic3] WITH (nolock)
INNER JOIN sys.[columns] AS [c3] WITH (nolock)
ON [ic3].[object_id] = [c3].[object_id]
AND [ic3].[column_id] = [c3].[column_id]
WHERE [ic3].[object_id] = [i].[object_id]
AND [ic3].[index_id] = [i].[index_id]
AND [ic3].[is_included_column] = 1
ORDER BY [c3].[column_id]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1, 2, ''
) AS IncludedColumnList
FROM sys.[indexes] AS [i] WITH (nolock)
WHERE [i].[object_id] = OBJECT_ID('dbo.TableName')
AND [i].[type_desc] = 'NONCLUSTERED'
GROUP BY [i].[name],
[i].[type_desc],
[i].[object_id],
[i].[index_id]
ORDER BY [KeyColumnList],
[IncludedColumnList];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment