Question presented to candidate:
"Every table in our schema has an id column, and some tables also have columns like customer_id. Explain what a primary key is, what a foreign key is, how they work together, and what the database actually enforces for each."
What a strong answer should cover:
- A primary key uniquely identifies each row of its own table: unique, never NULL, one per table (it may span several columns)
- A foreign key is a column in a child table whose values must match a primary key (or unique) value in the parent table, or be NULL
- What each enforces: duplicates and NULLs are rejected for the primary key; orphan inserts and deletes of referenced parents are rejected for the foreign key
- Indexes: the primary key always gets one; in PostgreSQL the foreign key column does not, which matters for joins and parent deletes
- Engine detail: SQLite only enforces foreign keys after
PRAGMA foreign_keys = ON, and only allows NULL in a non-INTEGER primary key for legacy reasons - Cascade options (
ON DELETE CASCADE,SET NULL,RESTRICT) as the policy for what happens to children
Code / implementation expected: Optional β a two-table schema with PRIMARY KEY and REFERENCES, and one join that follows the key.
Schema used by the examples: