Showing posts with label Foreign Key. Show all posts
Showing posts with label Foreign Key. Show all posts

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])

);




Set Primary Key,Unique Key,Foreign Key Sql Server Database Table in Visual Studio

Set Primary Key,Unique Key,Foreign Key


Set to Primary Key ,Foreign Key , Unique Key Sql Server DataBase Table Fields  Using Visual Studio


                                 DEMO




Primary Key


     CREATE TABLE [dbo].[country] (
    [id]      INT          IDENTITY (1, 1) NOT NULL,
    [name]    VARCHAR (50) NOT NULL,
    [country] VARCHAR (50) NOT NULL,
    [amount]  VARCHAR (50) NOT NULL,
    
   CONSTRAINT [PK_country] PRIMARY KEY CLUSTERED ([id] ASC),
   
  );


Unique Key


CREATE TABLE [dbo].[country] (

    [id]      INT          IDENTITY (1, 1) NOT NULL,
    [name]    VARCHAR (50) NOT NULL,
    [country] VARCHAR (50) NOT NULL,
    [amount]  VARCHAR (50) NOT NULL,

    CONSTRAINT [PK_country] PRIMARY KEY CLUSTERED ([id] ASC),

    UNIQUE NONCLUSTERED ([name] ASC)

);


Foreign Key



CREATE TABLE [dbo].[register] (

    [username] VARCHAR (50) NOT NULL,
    [password] VARCHAR (50) NOT NULL,
    [country]  VARCHAR (50) NOT NULL,
    [name]     VARCHAR (50) NOT NULL,

    CONSTRAINT [FK_reg_country] FOREIGN KEY ([name]) REFERENCES [dbo].[country] ([name])

);


First - Add - New Web Form - Create Database Tables - Fields 





Next - Set Primary Key To id Field - Select Field - Right Click - Set Primary Key






Next - Unique Key - Assign - name Field






Next - Assign Another Table - Same Field of Unique Field Set Foreign Key