Difference Between Primary Key and Foreign Key in SQL


Difference Between Primary Key and Foreign Key 



       Primary Key        Foreign Key    
1
Primary Key Can Not Accept Null Values. 
Foreign Key Can Accept Multiple Null Values. 
2
Only One Primary Key in a Table. 
More than One Foreign Key in a Table. 
3
Primary Key Uniquely Identify a Record in the Table
Foreign Key is a Field in the Table that is Primary Key in Another Table
4
Primary Key is Clustered Index.
Ex:
CREATE TABLE [country] (
    [id]      INT          IDENTITY (1, 1) NOT NULL,   
    [name] VARCHAR (50) NOT NULL,  
  UNIQUE NONCLUSTERED ([name],
    CONSTRAINT [PK_country] PRIMARY KEY CLUSTERED ([id])

);
Foreign Key is Non-Clustered Index.
Ex:
CREATE TABLE [reg] (   
    [country]  VARCHAR (50) NOT NULL,
    [name]     VARCHAR (50) NOT NULL,
    CONSTRAINT [FK_reg_country] FOREIGN KEY ([name]) REFERENCES [dbo].[country] ([name])

);




0 comments:

Post a Comment