Retrieve List of Primary Key and Foreign Key

In this blog we will learn how to retrieve the list of Primary Key and Foreign Key for a particular table and for the whole database.

List of Primary Key and Foreign Key for Whole Database:

Query:

  1. SELECT  
  2.   
  3. DISTINCT  
  4.   
  5. Constraint_Name AS [Constraint],  
  6.   
  7. Table_Schema AS [Schema],  
  8.   
  9. Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE  
  10.   
  11. GO  

Output:


List of Primary Key and Foreign Key for a particular table:

Query:

  1. SELECT  
  2.   
  3. DISTINCT  
  4.   
  5. Constraint_Name AS [Constraint],  
  6.   
  7. Table_Schema AS [Schema],  
  8.   
  9. Table_Name AS [TableName] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE  
  10.   
  11. WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_NAME='tblCompany_General_Info'  
  12.   
  13. GO  

Output: