What is the difference between a primary key and a foreign key?
What is the difference between a primary key and a foreign key?
Blog Article
A primary key is a unique identifier for a record in a database table. It ensures that each record can be uniquely identified and is often an auto-incrementing integer or a UUID. For example, a User
table might use id
as the primary key.
A foreign key is a field in one table that references the primary key of another table. It establishes a relationship between two tables, such as a one-to-many relationship. For example, an Order
table might have a user_id
foreign key that references the id
field in the User
table.
In full-stack development, primary and foreign keys are essential for maintaining data integrity and relationships. They are used in relational databases like PostgreSQL and MySQL to enforce constraints and ensure consistency.