Sobes.tech
Junior — Middle

What is the difference between using a foreign key and directly using an identifier from another table in a database?

sobes.tech AI

Answer from AI

A foreign key is a constraint in a database that guarantees referential integrity between two tables. It indicates that the value in one column (or set of columns) must exist in another table.

Differences:

  • Foreign key provides automatic data integrity checks: you cannot insert a value that does not exist in the related table.
  • When directly using an identifier without a foreign key, the database does not guarantee that the reference is correct — you can accidentally insert a non-existent ID.
  • A foreign key allows cascade operations (e.g., deleting related records), which simplifies data maintenance.

Example:

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

Here, CustomerID in Orders must exist in Customers, preventing data errors.

What is the difference between using a foreign key… - sobes.tech