Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

How to find all tables with primary key SQL Server

26 May,2023 by Tom Collins

Question: How can I find tables in a SQL Server database that have a Primary Key ? 

Answer: To identify if a table has a Primary Key - you can use the OBJECTPROPERTY method with the property TableHasPrimaryKey.   This returns 1 or 0 depending on whether the table has a PRIMARY KEY or not .

 

Example 1 : Check if a table has a PRIMRY KEY

 

SELECT OBJECTPROPERTY(OBJECT_ID(N'myschema.myTable'),'TableHasPrimaryKey')

 

Example 2: Find all tables with Unique NonClustered Indexes and the table has no Primary Key 

 

select schema_name(t.schema_id) as schemaname,t.name as tablename,i.name as indexname,i.is_unique
from sys.indexes i, sys.tables t
where i.object_id = t.object_id
  and i.type_desc = 'NONCLUSTERED' and i.is_unique = 1
  and OBJECTPROPERTY(OBJECT_ID(N''+schema_name(t.schema_id)+'.'+t.name+''),'TableHasPrimaryKey') = 0

Example 3 : Find all tables with Primary Keys 

 

SELECT
SCHEMA_NAME(schema_id) AS schemaname, name AS tablename
FROM sys.tables
WHERE
OBJECTPROPERTY(object_id,'TableHasPrimaryKey') = 1
GO




read more about SQL Server object management 

List Foreign Keys referencing tables in SQL Server

What are the triggers in SQL Server

How to find all identity columns in SQL Server

How to find default values of all SQL Server columns

How to find computed columns on a SQL Server table

Find SQL Server LOB Columns

How to List all indexes of all SQL tables

How to find SQL Filtered Indexes

Find LOB tables with no PRIMARY KEY

How to find UDT on SQL Server columns?


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to find all tables with primary key SQL Server


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer