Non Clustered Primary Keys in current database

Creating a Primary Key in SQL Server, by default creates a Clustered Index. The following statement shows all Primary Keys in current database that are using nonclustered indexes instead of clustered. This might not be necessarily wrong, as a clustered key should be chosen on the column that the data is ordered most frequently while the primary key enforces row uniqueness.

with 
pk as (select name ,parent_object_id from sys.objects where type='PK'),
ut as (select name ,object_id from sys.objects where type='U'),
ix as (select name,object_id  from sys.indexes where type!=1)
select ut.name as [Table], pk.name as [Primary Key] from ut join pk on pk.parent_object_id=ut.object_id join ix on ix.object_id=ut.object_id and ix.object_id=pk.parent_object_id
where ix.name is null

Leave a Reply

Your email address will not be published. Required fields are marked *