Find all tables missing a primary key or that have no relationship in a SQL database

Today this question came up for a fair-sized database: Which tables don't have a primary key?  Rather than click around forever in Enterprise Manager or Management Studio, I decided to write a query to quickly find all the offending tables:

-- Find all tables that don't have a Primary Key
select name FROM SysObjects WHERE xtype='U' AND id NOT IN
(SELECT parent_obj FROM SysObjects WHERE xtype='PK')

How does it work?  SysObjects contains a row for every object in the database, including views, stored procedures, system tables, etc.  The 'U' refers to user tables, and 'PK' refers to Primary Keys.

Here's a similar query that brings in the SysRelationships table to find all tables that don't participate in any relationship:

-- Find lone tables that don't participate in any relationships
SELECT name FROM SysObjects WHERE xtype='U' AND id NOT IN

(SELECT fkeyID FROM SysForeignKeys

UNION

SELECT rkeyID FROM SysForeignKeys)

There's some good validation you can do very quickly with these kinds of queries.

If anyone has a request for a similar query then just add a comment, and I'll try to figure it out for ya.


Feedback

# re: Find all tables missing a primary key or that have no relationship in a SQL database

Thanks for sharing :) 12/20/2006 8:03 PM | ram

# re: Find all tables missing a primary key or that have no relationship in a SQL database

Hi can any one please help me in finding out all the column names with the table name who has primary key and foreign key.

your help make my life lot more easier. 7/8/2007 1:48 PM | priya

# re: Find all tables missing a primary key or that have no relationship in a SQL database

Fantastic. . .exactly what I needed. 7/16/2007 12:57 PM | Peter

# re: Find all tables missing a primary key or that have no relationship in a SQL database

great yaar.. 8/7/2008 7:16 PM | vinitha

Post a comment





 

Please add 8 and 3 and type the answer here:

News


Welcome to my blog.
Here's what we've got on the menu today:

Tag Cloud


Article Categories

Archives

Post Categories

Image Galleries

Syndication: