Lawfare Academy · Complete Data Management and SQL edition 6

From a business model to an enforced relational schema

What a relational database represents

A relation has named attributes and rows representing facts at a declared grain. Mathematical relations are sets; practical SQL query results can contain duplicate rows unless constraints or query operations remove them. That difference matters when counting events. A domain describes permitted attribute values and meanings. An identifier determines a row within its scope; an invoice number unique only within a company needs the company in its key or a separate globally unique internal identity. A field called id does not establish either uniqueness or business authority by itself.

Distinguish the schema, the definitions and constraints, from an instance, the current stored data. A schema can allow many valid future states beyond today's three observations. A functional dependency X→Y says two valid rows agreeing on X must agree on Y. It is a domain rule, not a correlation inferred from a tiny export. A candidate key is a minimal set determining the row. A primary key selects one candidate for ordinary reference, while other genuine candidate keys need their own constraints. Adding a surrogate key does not automatically prevent duplicate business events.

The DBMS catalog stores structural metadata; the business dictionary supplies units, grain, status definitions, time basis, owner and correction rules. A logical model must also specify optional and mandatory relationships. Views can present a derived subset without duplicating all base facts; whether a view can be updated is engine- and query-dependent. A view is not automatically a permission boundary, immutable historical snapshot or materialized copy. A DBMS may provide users and role grants; an embedded SQLite file instead relies heavily on application and operating-system access controls. Name the actual enforcement layer.

Derive a normalized design

Use an independent export Enrollment(student_code, student_name, course_code, course_title, mentor_code, mentor_name, grade), with one row per student-course enrollment. This is a fictional example, not Academy learner data. Suppose student_code→student_name, course_code→course_title and mentor_code, mentor_code→mentor_name, and the pair(student_code,course_code)→grade. The pair is the enrollment key under these rules. A grade is not determined by student alone or course alone.

First normal form requires one value from the chosen domain at each attribute position rather than an uncontrolled comma-separated list of course codes. What counts as an atomic domain depends on the declared operations: an address can be stored as one display value if it is never decomposed, but region-level querying may require separate fields with explicit rules. Second normal form removes non-key attributes depending on only part of a composite candidate key. Move student_name to Students and course_title/mentor_code to Courses. Third normal form addresses transitive non-key dependencies: mentor_name belongs in Mentors, linked by mentor_code, rather than repeated on every course.

This yields Students(student_code,name), Mentors(mentor_code,name), Courses(course_code,title,mentor_code), and Enrollments(student_code,course_code,grade). Enforce the keys and appropriate references. A join reconstructs the intended facts only when keys and references preserve the stated cardinalities. A decomposition should be lossless with respect to the modeled original facts; dependency preservation means relevant rules remain enforceable without recombining everything. Those are distinct goals. Boyce–Codd normal form strengthens determinant requirements: every nontrivial functional dependency has a superkey determinant. Some designs require tradeoffs between dependency preservation and stronger normal forms. Normalization is reasoning about dependencies, not a contest to create more tables.

Worked reconstruction and update anomalies

Take rows(S 1,Ana,C 1,SQL,M 1,Lee,80),(S 2,Bo,C 1,SQL,M 1,Lee,90),(S 1,Ana,C 2,Models,M 1,Lee,70). The original has three enrollments, two students, two courses and one mentor. The sum of the three grades is 240 and their simple enrollment-weighted mean 80. The student-level means are 75 for S 1 and 90 for S 2; their equally weighted mean 82.5 answers a different question. Normalizing must retain all three keyed enrollments and their grades, not just the grand mean.

Changing mentor M 1's current name requires one Mentors update instead of three export updates. A new course can exist before any enrollment, solving an insertion anomaly. Deleting S 2's enrollment does not erase the course or mentor. But if a certificate must preserve the mentor name printed when issued, a current-name join is insufficient; add the appropriate historical snapshot or version relationship. This is the same semantic distinction as the preserved order-line transaction-price example: normalization of current master data cannot rewrite historical facts.

Make the constraints executable

In the stated SQLite dialect, the following disposable schema expresses required identities and bounded grades. Execute it only in an isolated synthetic database for study; it is not a migration for this site.

PRAGMA foreign_keys = ON;
CREATE TABLE students(
 student_code TEXT PRIMARY KEY NOT NULL,
 name TEXT NOT NULL
);
CREATE TABLE mentors(
 mentor_code TEXT PRIMARY KEY NOT NULL,
 name TEXT NOT NULL
);
CREATE TABLE courses(
 course_code TEXT PRIMARY KEY NOT NULL,
 title TEXT NOT NULL,
 mentor_code TEXT NOT NULL REFERENCES mentors(mentor_code)
);
CREATE TABLE enrollments(
 student_code TEXT NOT NULL REFERENCES students(student_code),
 course_code TEXT NOT NULL REFERENCES courses(course_code),
 grade INTEGER CHECK(grade BETWEEN 0 AND 100),
 PRIMARY KEY(student_code,course_code)
);

SQLite has historical primary-key nullability exceptions, so the explicit NOT NULL text keys are intentional. A CHECK evaluating NULL is not a substitute for NOT NULL; the nullable grade here means a grade may not yet be known. Ordinary SQLite type affinity is not rigid type enforcement. A declared INTEGER may need a STRICT-table or explicit typeof/domain policy if storage class must be constrained. An integer-cent convention does not alone prove every inserted amount is an integer. Check the actual engine/version and required domain, including rounding and currency, before treating a declaration as a complete rule.

Enable foreign keys before the transaction and verify the actual connection setting. A foreign key rejects an invalid non-null parent reference when enforced; a separate NOT NULL enforces presence. It cannot prove that the referenced student or customer is the correct real-world entity. Do not use cascading deletion by convenience where historical records must survive. The preserved foreign-key application demonstrates deferred constraints, legacy violations and failed commit handling in detail and remains part of the teaching.

Changing data without changing the question

INSERT creates rows, UPDATE changes selected attributes, and DELETE removes eligible rows under the schema's rules. A missing WHERE on an UPDATE can change every row. Use a transaction, inspect the intended key set, parameterize values and verify exact postconditions. Placeholders bind data, not arbitrary table names or sort expressions; allowlist identifiers when needed. A transaction does not grant authority to update a record. A reusable application must authenticate the caller and authorize the specific entity on the trusted server boundary independently of SQL syntax safety.

For schema evolution, inventory views, triggers, indexes and foreign-key dependents; prove exact keyed facts survive rather than comparing only count and sum. A failed SQL statement may leave an active transaction whose earlier changes still need rollback. The existing migration case proves these failure paths for its isolated fixture. No part of this written exercise authorizes production deletion or alteration.

Optional progressive practice

Guided model: identify the real key

The enrollment key is(student_code,course_code), not student name or grade. S 1 can enroll in both C 1 and C 2, while C 1 has S 1 and S 2. Changed fact: repeat enrollment attempts must be retained. The original pair no longer identifies an attempt; introduce an attempt identity or a justified additional key component, and specify which attempt a report uses. Do not overwrite the prior grade merely to maintain the old key.

Independent model: reconcile after decomposition

Retain the three pairs(S 1,C 1)=80,(S 2,C 1)=90,(S 1,C 2)=70. Their total 240 and enrollment mean 80 are useful checks, but compare every keyed row and uniqueness as well. Changed fact: grades become 85,85,70. Count 3 and total 240 remain while two original facts change. A totals-only migration test would miss the corruption.

Transfer model: required grade or unknown grade

The nullable grade with a range CHECK admits an as-yet unknown grade. If the business transition to finalized requires a grade, enforce that transition rule at the appropriate trusted layer or revise the schema. Changed fact: every saved enrollment must already be graded. Add NOT NULL as part of a reviewed migration that handles existing unknown values explicitly, rather than silently replacing them with zero. Zero is a known outcome, not a missingness code.

Unit rubric: 20 points

Four points each for grain/candidate keys and dependencies; justified normalization and historical boundaries; enforced dialect-specific domains/references; exact reconstruction and migration failure tests; and changed-fact/authority reasoning. Complete model gives four relations with three preserved enrollments, total 240, mean 80 and distinct student-weighted 82.5, while retaining unknown grade semantics and rejecting unsafe identity or deletion shortcuts.

Optional source summary: SQLite CREATE TABLE was read for primary keys, nullability, type affinity and constraint behavior. This studio's schema and enrollment reconstruction are original. The existing detailed foreign-key and normalization applications are retained; publisher and official links are optional provenance, and no real learner table is accessed.