Home Forums SQL Server 2008 T-SQL (SS2K8) how to find duplicate indexes in all the tables in a database RE: how to find duplicate indexes in all the tables in a database

  • I think that there are probably faster and better ways, but I think this is one way:

    ;WITH IndexColumns AS (

    SELECT DISTINCT a.object_id, a.name, a.type_desc, b.column_id, TABLE_NAME=c.name, [COL NAME]=d.name

    FROM sys.indexes a

    INNER JOIN sys.index_columns b ON a.object_id = b.object_id AND a.index_id = b.index_id

    INNER JOIN sys.tables c ON b.object_id = c.object_id

    INNER JOIN sys.columns d ON c.object_id = d.object_id AND b.column_id = d.column_id

    WHERE is_hypothetical = 0

    ),

    CombineCols AS (

    SELECT object_id, name, type_desc, table_name

    ,columns=STUFF((

    SELECT ',' + [COL NAME]

    FROM IndexColumns b

    WHERE a.object_id = b.object_id AND

    a.name = b.name AND

    a.type_desc = b.type_desc AND

    a.TABLE_NAME = b.TABLE_NAME

    ORDER BY [COL NAME]

    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')

    FROM IndexColumns a

    GROUP BY object_id, name, type_desc, table_name)

    SELECT b.type_desc, a.table_name, a.columns, b.name

    FROM (

    SELECT table_name, columns

    FROM CombineCols

    GROUP BY table_name, columns

    HAVING COUNT(name) > 1) a

    INNER JOIN CombineCols b

    ON a.table_name = b.table_name AND

    a.columns = b.columns

    ORDER BY a.table_name, a.columns

    It is not particularly fast but give it a chance and see what it gets you.

    Edit: Improved the query speed, added remarks below and removed "hypothetical" indexes.

    Remarks:

    1) If a CLUSTERED index exists on the same fields as a non-CLUSTERED index, both are listed.

    2) If two (or more) indexes exist involving the same fields but where the fields are ordered differently, these are also listed.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St