Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 Redundant Indexes

Author  Topic 

cosaco
Starting Member

1 Post

Posted - 2004-08-26 : 11:33:40
The next script, gets redundant indexes, in a given database.
I run it in the query Analyzer, one statement at a time.

PLEASE: review the output, before drop any index.


USE ....

-- step 1
-- gets an tab,idx,col,order view
create view listaidxcols as
select SO.name as tabname,
SI.name as idxname,
IK.keyno as keyno,
SC.name as colname
from sysindexkeys IK,
syscolumns SC,
sysindexes SI,
sysobjects SO
where -- Link syscolumns
IK.id=SC.id
and IK.colid=SC.colid
-- Link sysindexes
and IK.id=SI.id
and IK.indid=SI.indid
-- Link sysObjects (tables)
and IK.id=SO.id
and SO.xtype='U'
-- no internal indexes
and SI.name not like '_WA_Sys_%'
and SI.name not like 'hind_%'

--step 2: view to get # of columns per index
create view cantcolsidx
as select tabname,
idxname,
count(*) as numllaves
from listaidxcols
group by tabname,idxname


-- step 3
-- the redundant index list
select A.tabname as tabla,A.idxname as Aidx, B.idxname as Bidx
from cantcolsidx A, cantcolsidx B
where A.tabname = B.tabname
and A.numllaves < B.numllaves
and A.idxname <> B.idxname
and A.numllaves in (
select count(*)
from listaidxcols C, listaidxcols D
where C.tabname=A.tabname
and C.idxname=A.idxname
and D.tabname=B.tabname
and D.idxname=B.idxname
and C.idxname<>D.idxname
and C.colname=D.colname
and C.keyno =D.keyno
)

--clean up
drop view listaidxcols;
drop view cantcolsidx;

kselvia
Aged Yak Warrior

526 Posts

Posted - 2004-08-26 : 18:50:51
Thanks, that's a useful script. Found 2 redundant indexes in one of my DB's.

--Ken
I want to die in my sleep like my grandfather, not screaming in terror like his passengers.
Go to Top of Page

coolerbob
Aged Yak Warrior

841 Posts

Posted - 2005-04-07 : 07:32:38
What is this actually doing? How does it decide what is "redundant"?
Go to Top of Page
   

- Advertisement -