Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - How to find if clustered index exists

Tags:

sql

sql-server

We got 500+ tables and want to identify which tables doesn't have primary keys. Because creating index on large table will help to improve performance.

Required Command - to identify table which are HEAPS (as they dont have clustered index)

Regards

like image 286
Conrad Jagger Avatar asked Oct 09 '22 21:10

Conrad Jagger


1 Answers

SELECT OBJECT_NAME(object_id)
FROM sys.indexes 
WHERE index_id=0 
  AND OBJECTPROPERTY(object_id, 'IsUserTable') = 1

Finds all heaps. This issue is orthogonal to whether or not a PK exists though. A heap can have a non clustered PK and a clustered index isn't necessarily the PK. To find tables without a PK you can use.

SELECT *
FROM sys.tables t
WHERE NOT EXISTS
(
SELECT *
FROM sys.indexes i
WHERE is_primary_key=1 AND i.object_id = t.object_id
) 
like image 82
Martin Smith Avatar answered Oct 18 '22 17:10

Martin Smith