In this post, I am going to share one T-SQL script to find duplicate and redundant Indexes of the SQL Server.
I have found some of the junior and intermediate Database Developers, who are creating multiple duplicates indexes which are decreasing the overall performance of the database.
Now the job of the Database Administrator is to find and remove duplicate indexes from the database.
I have prepared a small demonstration by creating some of duplicate indexes and provided script to find that duplicate indexes.
First, create a sample table:
CREATE TABLE dbo.tbl_Students
StudID INT IDENTITY(1,1)
,CONSTRAINT pk_tbl_Students_StudID PRIMARY KEY(StudID)
Create duplicate indexes on LastName column:
CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName_FirstName_DOB
ON dbo.tbl_Students (LastName,FirstName,DOB)
CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName_FirstName
ON dbo.tbl_Students (LastName,FirstName)
CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName
ON dbo.tbl_Students (LastName)
Sample SELECT statements:
Below, both SELECT statements are using only one index (idx_tbl_Students_LastName_FirstName_DOB) because LastName column is duplicated in all the indexes.
SELECT *FROM dbo.tbl_Students WHERE LastName ='Patel' AND FirstName = 'Anvesh'
SELECT *FROM dbo.tbl_Students WHERE LastName ='Patel'
Script to find Duplicate Indexes:
s.Name + '.' + t.Name AS TableName
,i.name AS IndexName1
,DupliIDX.name AS IndexName2
,c.name AS ColumnNae
FROM sys.tables AS t
JOIN sys.indexes AS i
ON t.object_id = i.object_id
JOIN sys.index_columns ic
ON ic.object_id = i.object_id
AND ic.index_id = i.index_id
AND ic.index_column_id = 1
JOIN sys.columns AS c
ON c.object_id = ic.object_id
AND c.column_id = ic.column_id
JOIN sys.schemas AS s
ON t.schema_id = s.schema_id
FROM sys.indexes AS ind
JOIN sys.index_columns AS ico
ON ico.object_id = ind.object_id
AND ico.index_id = ind.index_id
AND ico.index_column_id = 1
WHERE ind.object_id = i.object_id
AND ind.index_id > i.index_id
AND ico.column_id = ic.column_id
Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.
If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.
I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.