Sobes.tech
Junior — Middle

Could you explain what a foreign key is in a database management system?

sobes.tech AI

Answer from AI

A foreign key is a field or a set of fields in one database table that references the primary key of another table. It establishes a link between the tables and maintains data integrity by ensuring that the foreign key value 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 is linked to a specific customer 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)
);
Could you explain what a foreign key is in a database… - sobes.tech