Finding Missing Primary Keys in SQL Server

Primary keys are unique identifier for each row of database table, as a good practice each table should have primary key defined. Here is a handy script which will run on SQL Server 2000 and SQL Server 2005 databases to get the list of tables with or with out primary key defined. It uses sysobjects table in 2000 and sysobjects view in 2005. There are other easy ways of doing it specific to each database but i personally like scripts which can run on both versions.

Tables with out or missing primary key.

SELECT
USER_NAME(ObjectProperty(id,'OwnerID')) AS Owner
, [name] AS Table_Name
FROM sysobjects
WHERE OBJECTPROPERTY(id,'TableHasPrimaryKey') = 0
AND
OBJECTPROPERTY(id,'IsMSShipped') = 0 
AND [type] = 'U'
ORDER BY [name]

List of tables with primary key defined.

SELECT
USER_NAME(ObjectProperty(id,'OwnerID')) AS Owner
, [name] AS Table_Name
FROM sysobjects
WHERE OBJECTPROPERTY(id,'TableHasPrimaryKey') = 1
AND
OBJECTPROPERTY(id,'IsMSShipped') = 0 
AND [type] = 'U'
ORDER BY [name]

The above script is using OBJECTPROPERTY TableHasPrimaryKey property to check if table has primary key or not, it also checks if the object is shipped by Microsoft. You do not have to use [type] = 'U' because it will skip stored procedures and other objects automatically as they can not have Primary Key(s) defined, but i have put it in my T-SQL script to make the script clear.


SQL Server DBA

I am a SQL Server DBA with almost 9 years of experience in database technologies.

Right now I am in process of redesigning this website in ASP.NET 2.0 and AJAX. The main purpose of new SQL DBA website is to offer more help to database professionals and make it easy for me to update contents on regular basis.