Introduction:
In this article I have
explained the difference between Primary key and Foreign Key. This is most commonly asked in the interview
in case of Freshers.
Primary Key vs Foreign Key.
Primary
Key
|
Foreign
Key
|
A primary key is a column or a set of columns that can be used to
uniquely identify a row in a table.
|
A foreign key is a column(s) in one table that references a unique
column usually the primary key of another table. The purpose of the foreign
key is to ensure referential integrity of the data. The referenced table is
called the parent table while the table with the foreign key is
called the child table.
|
Primary Key can't accept null values.
|
Foreign key can accept
multiple null value.
|
A table can have a single
primary key.
|
We can have multiple foreign keys in a table that can reference
different tables.
|
Primary Key can’t be duplicate. It means same value cannot be entered in
the primary key column.
|
Foreign key can be duplicated. It means same value can be entered in
foreign key column.
|
By default primary key implicitly
creates a clustered index on the column and data in the table is physically organized in the sequence of
clustered index.
|
Foreign key do not automatically create an index (clustered or
non-clustered) but we can explicitly create an index on foreign key column.
|
We can define primary key constraint on temporary table
|
We can’t define foreign key constraint on temporary table
|
We can define primary key constraint on table variable
|
We can't define foreign key constraint on table variable
|
We can insert a value in primary key column that may or may not be
present in child table containing the foreign key.
|
We can't insert a value in foreign key column that is not present in
the primary key column in the referenced parent table.
|
We can't delete primary key value from the parent table which is
used as a foreign key in child table. To delete we first need to delete that
primary key value from the child table.
|
We can delete the foreign key value from the child table even though
that refers to the primary key of the parent table.
|
0 comments:
Post a Comment