Thursday, 13 June 2013

difference between primary key and foreign key

Primary Key:

the below created table is created by using the primary key
CREATE TABLE   Student
(
          P_Id int NOT NULL,
          LastName varchar(255) NOT NULL,
          FirstName varchar(255),
          Address varchar(255),
          City varchar(255),
          PRIMARY KEY (P_Id)
)





 1 Primary key is used to avoid the duplication of records under same column
2 Primary key is used to uniquely identify the each record from table
3 You can use only one primary key at a time on single table
4 It does not allow any null value or duplicate value



Foreign Key

       The below table is created by using the foreign key
CREATE TABLE Orders
(
       O_Id int NOT NULL,
       OrderNo int NOT NULL,
       P_Id int,
       PRIMARY KEY (O_Id),
       FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

 It  is used to give the reference of another table primary key..when i update the child table record then it does not allow me..first i need to update from parent table then it is updated in child table

0 comments:

Post a Comment