Tuesday, October 8, 2019

Difference between Primary Key and Foreign Key

Primary key and foreign key are the two constraint which are used to uniqueness of data in sql. Primary key creates the identity of each one row and foreign key defines the relation between the two table.

Suppose create a book and customer table which is given below


Now insert the record in both the table. Remember one thing while inserting the record the value of book_id in customer table is same as the book_id in Book table.


Then select the both the table and analyze the result.
Analyse
Customer 1, 3, 5  have Book_A.
Customer 2 have Book_B
Customer 4 have Book_C

Comparison Table

Primary Key Foreign Key
A table can have a single primary key column. A table can have more than one foreign key column.
A table can't have two same value of primary key in a column. A table can have a same value of foreign key in a column.
Primary key doesn't allow us a null value. Foreign key can contain a null value.
For dropping the table or constraints, Primary key table must have to remove the references of foreign of the same table. Foreign key table can be removed happily table or constraint.

No comments:

Post a Comment