Sobes.tech
Junior — Middle

Can you explain what is meant by 'foreign key' in a relational database?

sobes.tech AI

Answer from AI

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

For example, if there is an Orders table with a CustomerID field that is a foreign key referencing the ID field in the Customers table, then each record in Orders must have a CustomerID that exists in Customers.

Example in SQL:

CREATE TABLE Customers (
  ID INT PRIMARY KEY,
  Name VARCHAR(100)
);

CREATE TABLE Orders (
  OrderID INT PRIMARY KEY,
  CustomerID INT,
  FOREIGN KEY (CustomerID) REFERENCES Customers(ID)
);

This helps maintain data integrity and relationships between tables.

Can you explain what is meant by 'foreign key' in a… - sobes.tech