Listing Tables and Indexes

,

Once in a while, a DBA or SQL developer is in the need of listing all the indexes of one or more tables in a given database.

Though the indexes can be viewed by using sp_help <table name> for a table, it does not help when it comes for multiple tables. Here the DBA's nice-to-have query is one to list Tables and Indexes.

Let's go and derive the query to list all the tables and their indexes.

For testing these queries in the test database, it is nice to have few tables created.

See the script for examples./

- sysobjects consists of all the objects in the database, while sysindexes has only index details.

Now, let's write the query in step by step fashion.

Query 1 - List all indexes in a database

Query 2 - Now let's exclude dtproperties table (indid = 255) and each tablename itself (indid =0) stored in sysindexes

Query 3 - List objects created by users

Query 4 - Let's build the complete query by joining both sysobjects and sysindexes.

CREATE TABLE Items ( 
ItemId int NOT NULL CONSTRAINT pk_Items primary key,
ItemName varchar(50) NOT NULL,
Qty_On_Hand numeric(10),
LastUpdate DateTime NOT NULL)
GO

CREATE INDEX idx_Items on Items (ItemName)
GO

CREATE TABLE Supplier (
SupplierId int NOT NULL CONSTRAINT pk_Supplier PRIMARY KEY,
SupplierName varchar(50) NOT NULL,
Contact varchar(15),
LastUpdate DateTime NOT NULL)
GO

CREATE INDEX idx_Supplier on Supplier (SupplierName)
GO
-- Query 1
SELECT INDID, ID, NAME FROM sysindexes
GO
-- Query 2
SELECT ID, indid, NAME 
FROM sysindexes
WHERE indid NOT IN (0, 255)
GO
-- Query 3
SELECT ID, NAME 
FROM sysobjects
WHERE type = 'U'

GO
-- Query 4
SELECT b.name 'Table', a.name 'Index'
FROM sysindexes a, sysobjects b
WHERE a.id = b.id AND 
 b.type = 'U' AND 
 indid NOT IN (0, 255)
GO
 


GO

Rate

3.5 (4)

Share

Share

Rate

3.5 (4)