Explain the difference between a primary key and a foreign key.

Instruction: Provide definitions for both primary key and foreign key, and discuss how they relate to one another in the context of relational databases.

Context: This question assesses the candidate's fundamental understanding of key concepts in database design and how they are applied to enforce data integrity and establish relationships between tables.

Updated

Official answer

A primary key identifies a row using one or more columns; the key is unique and non-NULL. A foreign key checks that a referencing value matches an eligible unique key in a referenced table, which may be the same table. The target need not be the primary key specifically.

For PostgreSQL:

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

Several orders may reference one customer. Each order_id remains unique, and an order cannot reference a missing customer. NOT NULL makes the customer relationship mandatory; foreign-key NULL behavior otherwise depends on the declared columns and match rule.

A foreign key does not make its child column unique or prove authorization. A primary key does not detect every business duplicate: two different customer IDs could still represent the same person. Additional business constraints and identity-resolution rules may be needed. Choose update/delete actions deliberately and measure index needs rather than treating key declarations as a guarantee of fast queries.

Related Questions