Senior
What is a primary key and foreign key in databases?
sobes.tech AI
Answer from AI
Primary Key — is a unique identifier for a record in a database table. It guarantees that each row in the table can be uniquely identified. Usually, a primary key cannot contain NULL and must be unique.
Foreign Key — is a field (or set of fields) in one table that references the primary key of another table. A foreign key is used to establish and enforce referential integrity between two tables, meaning it guarantees that the value in this field exists in the related table.
Example:
- The
orderstable has acustomer_idfield, which is a foreign key referencing theidfield in thecustomerstable (the primary key).
This allows linking an order to a specific customer and ensures data integrity — you cannot add an order with a non-existent customer.