Can you explain what a primary key is and its importance in a database?

Instruction: Define a primary key and discuss its role within a database.

Context: This question aims to assess the candidate's understanding of database key concepts and their ability to explain how primary keys enforce entity integrity.

Updated

Official answer

A primary key is the chosen unique, non-NULL identifier for rows in a table. It may contain one column or a combination; a table has at most one declared primary key, but may have additional candidate keys enforced with unique constraints.

For an order-line table, (order_id, line_number) can be the primary key. Line number 1 can appear in several orders, while the pair must be unique. A surrogate line_id is another option, but the business rule may still require a unique constraint on (order_id, line_number).

Stable keys let updates and relationships target a precise row. Avoid mutable descriptive values when a change would require widespread relationship updates. A foreign key can reference an eligible unique key to check that the related row exists.

Key uniqueness is narrower than overall data quality. Two customer IDs can still refer to the same person, and a valid ID says nothing about access permission. Engines commonly use an index to enforce the key, but that does not guarantee every query's speed or result ordering. Define ORDER BY when display order matters.

Related Questions