views:

45

answers:

2

Is anyone aware of a T-SQL script that can detect redundant indexes across an entire database? An example of a redundant index in a table would be as follows:

Index 1: 'ColumnA', 'ColumnB', 'ColumnC'
Index 2: 'ColumnA', 'ColumnB'

Ignoring other considerations, such as the width of columns and covering indexes, Index 2 would be redundant.

Thanks.

A: 

There are situations where the redundancy doesn't hold. For example, say ColumnC was a huuge field, but you'd sometimes have to retrieve it quickly. Your index 1 would not require a key lookup for:

select ColumnC from YourTable where ColumnnA = 12

On the other hand index 2 is much smaller, so it can be read in memory for queries that require an index scan:

select * from YourTable where ColumnnA like '%hello%'

So they're not really redundant.

If you're not convinced by my above argument, you can find "redundant" indexes like:

;with ind as (
    select  a.object_id
    ,       a.index_id
    ,       cast(col_list.list as varchar(max)) as list
    from    (
            select  distinct object_id
            ,       index_id
            from    sys.index_columns
            ) a
    cross apply
            (
            select  cast(column_id as varchar(16)) + ',' as [text()]
            from    sys.index_columns b
            where   a.object_id = b.object_id
                    and a.index_id = b.index_id
            for xml path(''), type
            ) col_list (list)
)
select  object_name(a.object_id) as TableName
,       asi.name as FatherIndex
,       bsi.name as RedundantIndex
from    ind a
join    sys.sysindexes asi
on      asi.id = a.object_id
        and asi.indid = a.index_id
join    ind b
on      a.object_id = b.object_id
        and a.object_id = b.object_id
        and len(a.list) > len(b.list)
        and left(a.list, LEN(b.list)) = b.list
join    sys.sysindexes bsi
on      bsi.id = b.object_id
        and bsi.indid = b.index_id

Bring cake for your users in case performance decreases "unexpectedly" :-)

Andomar
@Andomar - Thanks - But I'm not interested in whether, in your opinion, you think index 2 is redundant with index 1. I'm interested in a T-SQL script that gives me a heads up that an index might be redundant with another index.
Randy Minder
@Andomar - The issue isn't whether I believe you or not. And my question was not about what constitutes a redundant index. It would be nice if more people would just answer the question, as posted, and not try to answer a question that wasn't asked. I simply wanted a query that gave me a heads up on what indexes might be redundant, and then we will evaluate each one to decide what action to take.BTW - nice query!
Randy Minder
A: 

Check this link.

www.sql-server-performance.com .

SP249
@SP249 - I searched Google before I posted this question, and found this same article. It doesn't help me. When I run this on my schema, I get NULL values in col1 through col16 for all my indexes.
Randy Minder