Monday, March 10, 2014

Difference between Primary key vs Foreign key in table

Main difference between Primary key and Foreign key in a table is that, it’s the same column which behaves as primary key in parent table and foreign key in child table.

For example in departments and employees relationship, dept_id is primary key in departments
table but foreign key in employees table.

Hence the table which contains foreign key (Column ) is known as child table.

Hence in employees and departments table , employees table is child table and departments table is parent table.

1) Difference between primary and foreign key is that unlike primary key, foreign key can be null e.g. in our example you can have an Employee record for which dept_id can be null, this shows that no corresponding record in Department table.

3) One more difference between primary key and foreign key is that foreign key can be duplicate opposite to primary key which is always unique.

4) By using foreign key constraints, we can introduce referential integrity in multiple table relationship in SQL. Referential integrity guarantees data integrity.

5) Foreign key mostly work as link between two table when we join tables using INNER JOIN and
OUTER JOIN. For example when we INNER JOIN both Employee with Department table,
we can use dept_id as joining column.

6) Table on which a column is declared as primary key is known as parent table in relationship and foreign key table is known as child table in relationship.

For example in Employee and Department relationship, Department is parent table because dept_id is primary key there and Employee is child table  because dept_id is foreign key in this table.


Cheers
Rajani

No comments:

Post a Comment