Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display SQL Server table indexes?

I need to list/display all the clustered and non clustered indexes contained by a table.

How can I do that using SQL Server 2008 R2?

like image 874
Sarfaraz Makandar Avatar asked Sep 29 '14 06:09

Sarfaraz Makandar


1 Answers

How about this:

SELECT 
    TableName = t.Name,
    i.*
FROM 
    sys.indexes i
INNER JOIN 
    sys.tables t ON t.object_id = i.object_id
WHERE
    T.Name = 'YourTableName'

If you need more information (like columns contained in the index, their datatype etc.) - you can expand your query to something like this:

SELECT 
    TableName = t.Name,
    IndexName = i.Name, 
    IndexType = i.type_desc,
    ColumnOrdinal = Ic.key_ordinal,
    ColumnName = c.name,
    ColumnType = ty.name
FROM 
    sys.indexes i
INNER JOIN 
    sys.tables t ON t.object_id = i.object_id
INNER JOIN 
    sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
INNER JOIN 
    sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
INNER JOIN 
    sys.types ty ON c.system_type_id = ty.system_type_id
WHERE 
    t.name = 'YourTableName' 
ORDER BY
    t.Name, i.name, ic.key_ordinal

These system catalog views contain a wealth of information about your system....

like image 60
marc_s Avatar answered Nov 08 '22 08:11

marc_s