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
userstable has a primary keyid. - The
orderstable contains auser_idfield, which is a foreign key referencingusers.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.