List all the Primary and Foreign keys in SQL Server database

To list all the Primary keys in a SQL Server database run:

USE Database_name
SELECT * FROM information_schema.table_constraints
WHERE constraint_type = 'Primary Key'

To list the Primary key in a table in a SQL Server database run:

USE Database_name
SELECT * FROM information_schema.table_constraints
WHERE constraint_type = 'Primary Key' and Table_Name = 'Table_name'

To list all the Foreign keys in a SQL Server database run:

USE Database_name
SELECT * FROM information_schema.table_constraints
WHERE constraint_type = 'Foreign Key'

To list all the Foreign keys in a table in a SQL Server database run:

USE Database_name
SELECT * FROM information_schema.table_constraints
WHERE constraint_type = 'Foreign Key' and Table_Name = 'Table_name'

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">