AI and Automation in Practice

Patrick Wahlmueller

All Indexes of a Table with a TSQL Script
Technical Insights 1 min read

All Indexes of a Table with a TSQL Script

A T-SQL script to view all current indexes of a SQL Server table, including index names, types, key ordinals, and column names.

SQL TSQL SQL Server Database Performance

Recently I had to optimise the speed of an SQL database. To do this, I wanted to view the current indices of the table in advance. As I like scripts, I wrote a T-SQL script for this.

DECLARE @Tablename nvarchar(255) = 'Tablename'

SELECT
    i.name AS IndexName,
    ic.key_ordinal,
    i.type_desc AS IndexType,
    COL_NAME(ic.object_id, ic.column_id) AS ColumnName
FROM
    sys.indexes AS i
JOIN
    sys.index_columns AS ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE
    OBJECT_NAME(i.object_id) = @Tablename
ORDER BY
    i.name, ColumnName