Tables, keys and constraints
Model real records in relational tables and use constraints to protect valid data.
Separate related records
A table groups rows with similar fields. Store each book once in a books table, then point reading entries at the book’s ID. Primary keys identify rows. Foreign keys ensure that a reference points to a row in the other table.
How it works
Give each record a stable way to be identified. The primary key identifies a row in its own table, while a foreign key links it to an existing row in another table. A database constraint can protect that relationship even when records come from different parts of the application.
Make important rules part of the schema
A required field can use NOT NULL. A CHECK can enforce an allowed range, and a unique constraint can prevent duplicate identifiers. Use parameterized SQL for inputs. A transaction groups related operations so the work can succeed or be rolled back together.
Check your understanding
An entry references an existing book and stores pages read. Identify the constraints needed to reject missing books and negative counts.
See the example and explanation
- Example 1
- Given
Book ID must exist - Answer
Foreign key - Example 2
- Given
Pages read must be zero or greater - Answer
Check constraint
Use a foreign key to reference the books table and a check constraint to require pages read to be at least zero.