Steps to create Foriegn Key in SQL Server

A foreign key is a field in one table that refers to the primary key in another table. The table with primary key is called Parent table. The table with foreign key is called Child table.

FOREIGN KEY Diagram


FOREIGN KEY EXAMPLE:

  CREATE TABLE USERS (
      id int NOT NULL,  
      first_name varchar(255),
      last_name varchar(255) ,
      payment_mode varchar(55) ,
      user_type varchar(50) ,
      email varchar(50) ,
      mobile varchar(50) ,
      password varchar(255),
      gender varchar(25) ,     
     country_id  int,
      state_id int,
      city_id int,
      company_id int,
      status int NOT NULL,
      foreign key (country_id) references COUNTRY(country_id)  
) 
                        

  CREATE table COUNTRY
(
    country_id int primary key not null identity(1,1),
    countryname varchar(200)
)
                        

Create Foreign key on existing Table

Requirement: To create foreign key on Studentid field of Students Table.

ALTER TABLE Students ADD FOREIGN KEY (Studentid) REFERENCES Course(Studentid);

DROP FOREIGN KEY

ALTER TABLE Student DROP CONSTRAINT FK_StudentCourse;