SQL SERVER – Finding Tables with Primary or Foreign Keys

If you want to know if a table has a primary key or foreign key, you can find out this in many ways. Here are simple queries for finding tables with primary or foreign keys.

Let us create these tables


CREATE TABLE product_master
(
prod_id INT PRIMARY KEY,
prod_name VARCHAR(100),
price DECIMAL(12,2)
)
GO
CREATE TABLE product_details
(
prod_id INT, 
sales_date DATETIME,
sales_qty INT,
sales_amount DECIMAL(16,2)
)
GO
CREATE TABLE company_master
(
compnay_id INT,
company_name VARCHAR(100),
address VARCHAR(1000)
)
GO

Now let us create foreign key:


ALTER TABLE product_details ADD CONSTRAINT ck_item FOREIGN KEY(prod_id) REFERENCES product_master(prod_id)

Now if you want to check if a table has a primary key, you can use the following methods

1) Use sp_pkeys system stored procedure


EXEC sp_PKEYS product_master

The result is

sp_pkeys result for product_master while checking primary or foreign keys.

2) Use OBJECTPROPERTY Function to Find Tables with Primary or Foreign Keys


SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASPRIMARYKEY')=1 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

Tempdb db.
if you want to check if a table has a foreign key, you can use the following method


SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASFOREIGNKEY')=1 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

The result is

Tempdb database.

If you want to check for the tables that do not have primary or foreign keys, you can use the following method


SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASPRIMARYKEY')=0 AND
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASFOREIGNKEY')=0 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

The result is
Tempdb database in SQL server.

A Safer and Newer Way

One caution about the queries above. OBJECT_ID(TABLE_NAME) uses a one part name, so SQL Server looks for the table only in your default schema and then in dbo. If a table lives in another schema, such as HumanResources in AdventureWorks, OBJECT_ID returns NULL and the table quietly drops out of the result. To be safe, pass the schema too: OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + ‘.’ + QUOTENAME(TABLE_NAME)).

These days I prefer the catalog views. sys.key_constraints lists primary key and unique constraints, and sys.foreign_keys lists foreign keys, each with its parent table:

SELECT OBJECT_SCHEMA_NAME(parent_object_id) AS SchemaName,
       OBJECT_NAME(parent_object_id) AS TableName, name AS KeyName, type_desc
FROM sys.key_constraints
WHERE type = 'PK'
UNION ALL
SELECT OBJECT_SCHEMA_NAME(parent_object_id), OBJECT_NAME(parent_object_id), name, type_desc
FROM sys.foreign_keys;

This returns one row per key, so you see the schema, the table and the key name together. It is a quick way to review primary or foreign keys across a whole database before a migration. If a table shows up in neither list, that is a good moment to ask why it has no key at all.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Constraint and Keys, SQL Scripts
Previous Post
SQL SERVER – Script: Knowing Data and Log Files Are On the Same Drive
Next Post
SQL SERVER – Recovering from Snapshots – Notes from the Field #078

Related Posts

4 Comments. Leave new

  • — find tables with FKs
    select OBJECT_SCHEMA_NAME(f.parent_object_id)+’.’+OBJECT_NAME(f.parent_object_id) AS TableName
    from sys.foreign_keys AS f

    Reply
  • ScottPletcher
    April 29, 2015 9:25 pm

    I’d recommend sys.objects where type in (‘f’, ‘pk’). If you prefer to use a system proc, use sp_helpindex. Avoid INFORMATION_SCHEMA views like the plague, as they are slow and can contribute to deadlocks.

    Reply

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.