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

Difference Between Primary Key and Unique Key in SQL


Difference Between Primary Key and Unique Key 



       Primary Key        Unique Key    
1
Primary Key Can't Accept Null Values.
Unique Key Can Accept Only One Null Value
2
Creates Clustered Index
Creates Non-Clustered Index
3
Only One Primary key in a Table
More than One Unique Key in a Table. 
4
Primary Key Can be Made Foreign Key Into Another Table.
Ex:
CREATE TABLE [country] (
       [id]    VARCHAR (50) NOT NULL,
    [country] VARCHAR (50) NOT NULL,     
    CONSTRAINT [PK_country] PRIMARY KEY CLUSTERED ([id]));
SQL Server, Unique Key Can be Made Foreign Key Into Another Table.
Ex:
CREATE TABLE [country] (    
    [name]    VARCHAR (50) NOT NULL,
    [country] VARCHAR (50) NOT NULL,  
    UNIQUE NONCLUSTERED ([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