Sobes.tech
Middle

Tell about Foreign Key: why is it needed and what are its disadvantages?

sobes.tech AI

Answer from AI

Foreign Key — a constraint in relational databases that links a column (or set of columns) in one table to the primary key of another table.

Why is a Foreign Key needed:

  • Ensures data integrity by guaranteeing that values in the child table correspond to existing records in the parent table.
  • Helps model relationships between entities (e.g., order and customer).
  • Automatically maintains cascading operations (deletion, update).

Disadvantages of Foreign Key:

  • Can reduce performance with large volumes of data due to integrity checks.
  • Complicates migrations and schema changes as dependencies must be considered.
  • In some cases, limits flexibility, for example, when working with distributed or NoSQL databases.

Example:

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

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

Thus, a Foreign Key is an important mechanism for maintaining relationships and data integrity, but requires careful use in large and complex systems.