Difference between Primary Key and Foreign Key ? - TestingQ.com

-->Exclusive Portal for Testing Jobs

Difference between Primary Key and Foreign Key ?



Primary Key:
1) Primary key uniquely identify a record in the table.
2) Primary Key can't accept null values.
3) By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.
4) We can have only one Primary key in a table.

Foreign Key:
1) Foreign key is a field in the table that is primary key in another table.
2) Foreign key can accept multiple null value.
3) Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.
4) We can have more than one foreign key in a table.

Define Primary key and Foreign key:
## Create Parent Table

CREATE TABLE Department
 (
   DeptID int PRIMARY KEY, --define primary key
   Name varchar (50) NOT NULL,
   Address varchar(100) NULL
  )
   GO

## Create Child Table

CREATE TABLE Employee
 (
   EmpID int PRIMARY KEY, --define primary key
   Name varchar (50) NOT NULL,
   Salary int NULL,
   DeptID int FOREIGN KEY REFERENCES Department(DeptID)
--define foreign key
  ) 



To receive daily posted JOBS & Interview Questions
Just enter your email address below and click 'Submit'
Enter your email address:

Make sure to activate your subscription by clicking on the activation link sent to your email