Technology

Difference between Primary Key and Foreign Key

Difference between Primary Key and Foreign Key

Difference between Primary Key and Foreign Key

The primary key consists of one or more columns whose data contained within are used to uniquely identify each row in the table. A foreign key is a set of one or more columns in a table that refers to the primary key in another table. Both are important database objects.

SQL Server, there are two keys – primary key and foreign key which seems identical, but actually, both are different in features and behaviors. Primary keys and foreign keys are two types of constraints that can be used to enforce data integrity in SQL Server tables.

Difference between Primary Key and Foreign Key –

Primary Key – It is a special key which uniquely identifies each record in a table.

  • Definition: Primary key uniquely identifies a record in the table.
  • Values: Primary Key can’t accept null values.
  • Index: By default, Primary key is clustered index and data in the database table is physically organized in the sequence of a clustered index.
  • Table: We can have only one Primary key in a table.

Foreign Key – It establishes a link between records in two different tables in a database.

  • Definition: Foreign key is a field in the table that is the primary key in another table.
  • Values: Foreign key can accept multiple null values.
  • Index: Foreign key does not automatically create an index, clustered or non-clustered. You can manually create an index on the foreign key.
  • Table: We can have more than one foreign key in a table.