All About Primary Key And Its Basics

In this series of articles, we will go deep into SQL Server from scratch and will gain knowledge of queries, optimization, and database administration. This is the first article of the series where we will learn about general SQL queries and their functioning. Images have been used wherever necessary so as to make you understand every command properly.
  • All Queries which I am posting today you can use  directly on your query plan like copy, paste and execute this query.
  • Each query has a valid column name and similarly I have shown in the form of image for proper understanding and proper usage
Find all Primary key in Give Database in following format,
Find all Primary key in Give Database 
  1. SELECT AS IndexName,  
  2.     OBJECT_NAME(ic.OBJECT_ID) AS TableName,  
  3.     COL_NAME(ic.OBJECT_ID, ic.column_id) AS ColumnName  
  4. FROM sys.indexes AS i  
  5. INNER JOIN sys.index_columns AS ic  
  6. ON i.OBJECT_ID = ic.OBJECT_ID  
  7. AND i.index_id = ic.index_id  
  8. WHERE i.is_primary_key = 1   
Finding Constrains and Type of Constrain i.e. Primary and foreign key relation in the given database
Finding Constrains and Type of Constrain 
  1. SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,  
  2.     SCHEMA_NAME(schema_id) AS SchemaName,  
  3.     OBJECT_NAME(parent_object_id) AS TableName,  
  4.     type_desc AS ConstraintType  
  5. FROM sys.objects  
Detailed level relationship and description of primary key and foreign key
primary key and foreign key 
  1. SELECT AS ForeignKey,  
  2.     SCHEMA_NAME(f.SCHEMA_ID) SchemaName,  
  3.     OBJECT_NAME(f.parent_object_id) AS TableName,  
  4.     COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,  
  5.     SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,  
  6.     OBJECT_NAME(f.referenced_object_id) AS ReferenceTableName,  
  7.     COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName  
  8. FROM sys.foreign_keys AS f  
  9. INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id  
  10. INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id  
Use the above snippets as per your requirement.
In most of the cases it's is going to be used in the Database Analysis where Database size and table are large and high in number.
Thus, we learned about the basic queries of SQL. If you have some doubt, or want to add some more information in this article, please feel free to write me in the comments section.
We will dive deeper into SQL in the upcoming articles of this series. Stay tuned!

Similar Articles