This article is half-done without your Comment! *** Please share your thoughts via Comment ***
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:
1 2 3 4 5 6 7 8 9 |
CREATE TABLE dbo.tbl_Students ( StudID INT IDENTITY(1,1) ,FirstName VARCHAR(50) ,LastName VARCHAR(50) ,DOB DATETIME ,CONSTRAINT pk_tbl_Students_StudID PRIMARY KEY(StudID) ) GO |
Create duplicate indexes on LastName column:
1 2 3 4 5 6 7 8 9 10 11 |
CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName_FirstName_DOB ON dbo.tbl_Students (LastName,FirstName,DOB) GO CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName_FirstName ON dbo.tbl_Students (LastName,FirstName) GO CREATE NONCLUSTERED INDEX idx_tbl_Students_LastName ON dbo.tbl_Students (LastName) GO |
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.
1 2 3 4 |
SELECT *FROM dbo.tbl_Students WHERE LastName ='Patel' AND FirstName = 'Anvesh' GO SELECT *FROM dbo.tbl_Students WHERE LastName ='Patel' GO |
Script to find Duplicate Indexes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
SELECT 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 CROSS APPLY ( SELECT ind.index_id ,ind.name 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 ) DupliIDX ORDER BY s.name,t.name,i.index_id GO |
The Result: