In this tutorial, you will see the difference between SQL Server Primary Key and foreign key.
The below are the some points which defines primary key:
The following example create a table with constraints for the columns: FirstName when the Employee table is created:
CREATE TABLE Employee ( Eid int PRIMARY KEY IDENTITY(1,1), FirstName varchar(100) NOT NULL, LastName varchar(100), Emailid varchar(100), Age int, Departmentid int );
The IDENTITY property is used for the Eid column to automatically generate unique integer values.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables or A foreign key means that values in one table must also appear in another table. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
We will create two new tables to understand the FOREIGN KEY constraint functionality. The first table will act as the parent table with the ID column defined as a PRIMARY KEY column. The second table will act as the child table, with the ID column defined as the FOREIGN KEY column that references the ID column on the parent table.
Look at the following two tables:
CREATE TABLE ConstraintParentTable ( ParentID INT PRIMARY KEY, Name VARCHAR(100) NULL ) GO CREATE TABLE ConstraintChildTable ( ChildID INT PRIMARY KEY, ID INT FOREIGN KEY REFERENCES ConstraintParentTable(ParentID) )
Difference between the Primary Key vs Foreign Key
|SNo.||Primary Key||Foreign Key|
|1||It is a combination of UNIQUE and Not Null constraints.||It can contain duplicate values and a table in a relational database.|
|2||Primary key cannot be null||Foreign keys can contain null|
|3||Only one Primary Key allowed in table||Whereas more than one foreign key are allowed in a table.|
|4||A Primary key supports auto increment value.||Foreign key only support primary key column values.|
|5||We cannot delete values from parent table.||We can delete values from child table.|