Sobes.tech
Junior — Middle

What is the difference between a primary key and a foreign key in a database?

sobes.tech AI

Answer from AI

A Primary Key is a unique identifier for a record in a database table. It guarantees the uniqueness of each row and is usually used for quick lookup and linking to other tables.

A Foreign Key is a field in one table that references the primary key of another table. It ensures data integrity by linking records between tables.

Example:

  • The users table has a primary key id.
  • The orders table contains a user_id field, which is a foreign key referencing users.id.

Thus, the primary key is unique within its table, and the foreign key is used to establish relationships and ensure data consistency between tables.