Cardinality and optionality: enforce relationship bounds
Overview
Cardinality describes how many related instances are allowed; optionality describes whether participation can be absent. Read both ends of a relationship. Each course in this model has exactly one instructor; an instructor may teach zero or many courses. Each learner can have zero or one profile, and every profile belongs to exactly one learner. These are business rules, not facts inferred solely from example rows. Load er-training.sql before the queries.
First example
SELECT i.id, COUNT(c.id) AS coursesFROM er_instructor i LEFT JOIN er_course c ON c.instructor_id=i.idGROUP BY i.id ORDER BY i.id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 1 ], [ 3, 0 ]]How it works
The course foreign key is NOT NULL, so each course references an existing instructor. The profile uses learner_id as both primary key and foreign key, enforcing at most one profile per learner. A nullable foreign key would model optional participation on the referencing side. A foreign key alone does not ensure every parent has a child, and UNIQUE alone does not enforce presence; use a different model or a carefully designed transaction-level rule if mandatory participation in both directions is necessary. A self-reference such as instructor.mentor_id describes an optional recursive relationship; it does not prevent cycles by itself. Counts below show current participation, not the maximum possible participation. The SQLite fixture makes er_profile a WITHOUT ROWID table so its shared key cannot be silently auto-assigned when NULL is supplied.
Practical example
SELECT l.id, p.bioFROM er_learner l LEFT JOIN er_profile p ON p.learner_id=l.idORDER BY l.id;Observed SQLite result (rows in JSON):
[ [ 1, "SQL learner" ], [ 2, null ], [ 3, null ]]Practice and mistakes
Practice: explain why instructor 3 is valid even though the count is zero. Then try adding a second profile for learner 1 in a disposable copy: the key must reject it. Do not put UNIQUE on course.instructor_id unless a teacher may teach at most one course.