Sobes.tech
Junior — Middle

Can you explain what it means to use a foreign key in a relational database?

sobes.tech AI

Answer from AI

A foreign key in a relational database is a field (or set of fields) in one table that references the primary key of another table. It is a mechanism to ensure referential integrity of the data, meaning it guarantees that the value in the foreign key exists in the related table.

For example, if there is an Orders table with a customer_id field that is a foreign key referencing the id field in the Customers table, then you cannot add an order with a customer_id that does not exist in the Customers table.

This helps to:

  • Link data between tables.
  • Prevent errors and data inconsistency.
  • Ensure database integrity.

Example in SQL:

CREATE TABLE Customers (
    id INT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE Orders (
    id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE,
    FOREIGN KEY (customer_id) REFERENCES Customers(id)
);