Can you explain what a foreign key is and its purpose in a database?

Instruction: Define a foreign key and discuss its role in enforcing referential integrity between tables.

Context: This question aims to assess the candidate's understanding of relational database principles, specifically the concept of foreign keys and their importance.

Updated

Official answer

A foreign key enforces a reference to an eligible unique key in another table, or in the same table. Many child rows may reference one parent; the child foreign-key value need not be unique.

This PostgreSQL example requires every order to reference an existing customer:

CREATE TABLE practice_customers (
  customer_id integer PRIMARY KEY,
  name text NOT NULL
);
CREATE TABLE practice_orders (
  order_id integer PRIMARY KEY,
  customer_id integer NOT NULL
    REFERENCES practice_customers(customer_id)
);

Two orders may share a customer. A nonexistent customer ID is rejected. Here NULL is rejected because of NOT NULL; a nullable foreign key would normally permit an absent reference.

PostgreSQL does not automatically index the referencing column. Choose indexes from the workload and deletion/update costs. A join is still possible without a foreign-key constraint, but the constraint independently protects the relationship. Decide deletion behavior from the business meaning rather than adding cascading deletion by default.

Source

PostgreSQL 16: foreign keys.

Related Questions