The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← Data Management and SQL for Business

Unit 2

Keys and relational integrity

Learning objectives

  • Explain keys and relational integrity in your own words.
  • Apply the principle to the worked business case.
  • Evaluate the answer and identify an assumption that could change it.

Keys and relational integrity

A primary key uniquely identifies a record; a foreign key links to another entity. Normalization reduces avoidable repetition, while constraints preserve valid relationships. Human-readable names are often poor unique identifiers.

Worked example

Two customers share a surname. Stable customer IDs distinguish them even when names or addresses change.

Current on-site learning

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

Work through the reasoning

Define the business workflow, data, users, system boundary, and failure consequences. For this unit, connect the explanation of keys and relational integrity to the worked example before answering the practice question.

Check the limits

Test a representative case and identify controls, exceptions, recovery, and the accountable human owner. If the source model and the practical example use different assumptions, state the difference rather than applying the formula or rule mechanically.

Apply it independently

Which is the stronger customer key? Write an answer before opening the model response. Show the calculation or explain the causal or logical steps. Change one material assumption and say whether your conclusion changes. This practice is optional; you can read every part of the course without submitting work.

Original Academy expansion: keys, dependencies and enforceable integrity

A primary key uniquely identifies a row and must not be NULL. A foreign key constrains a child reference to match an allowed parent key, subject to the declared treatment of NULL. A uniqueness constraint enforces a candidate key. A CHECK constraint enforces a row-level condition expressible in that database's constraint language. These rules prevent particular invalid states; none proves that a real-world event was measured correctly. A payment can satisfy every constraint and still be entered against the wrong valid job.

In SQLite, enable foreign-key enforcement for the connection before starting the laboratory transaction: PRAGMA foreign_keys = ON. Verify the setting. Defining REFERENCES clauses while enforcement is disabled does not supply the protection assumed in these exercises. Engine configuration is part of the integrity design. Other database products have different defaults and features, so identify the engine and version when moving code between systems.

Consider jobs(job_id, customer_id, status, opened_date). job_id determines the remaining job attributes. customer_id determines customer-level attributes stored in customers, rather than in jobs. A functional dependency concerns the meaning of the data, not merely a pattern in a small sample. Five observed customers having different names does not make name a reliable key. Two different accounts can legitimately share a name, and one account can change its name.

Worked investigation: defend against four invalid states

The laboratory schema declares jobs.customer_id as NOT NULL and REFERENCES customers(customer_id). Attempting to insert a job for customer 999 fails when 999 is absent. Attempting to insert an existing job_id fails the primary-key rule. A status outside the declared set fails the CHECK rule. A line with negative unit_cents fails the nonnegative-price rule. Test all four deliberately in a disposable database. Merely reading the CREATE TABLE statement is weaker evidence than seeing the invalid states rejected.

A UNIQUE constraint can behave differently from an intuitive business rule when NULL values are involved. SQLite permits multiple NULL values in a UNIQUE column. If every customer must have an external_code and it must be unique, use both NOT NULL and UNIQUE. Do not rely on a generic phrase such as unique code without specifying missing-value behavior. Case and whitespace rules also matter: AB12, ab12, and AB12 followed by a space may represent the same business identifier while being different stored strings unless normalization or collation rules address the issue.

Referential actions need policy decisions. Deleting a customer who has historical jobs should not casually erase those jobs. The laboratory leaves deletion restricted by default. Some systems require archival or a separate inactive status. Cascading deletion is appropriate only when the child facts should cease to exist with the parent, and retention requirements have been considered. A convenient cleanup command is not a substitute for deciding what a historical record means.

Row-level checks have limits. A payment's amount_cents > 0 check rejects nonpositive receipts in this simplified model, but it does not ensure that total allocations across rows equal the payment header. A CHECK on one row normally cannot enforce every aggregate invariant across several rows. Such rules may require transaction logic, triggers, a different representation, and reconciliation. State which layer enforces each rule and test the failure path. An interface that checks a value can be bypassed by another writer unless the trusted data layer enforces it too.

Progressive practice

  1. Foundation: distinguish a primary key from a foreign key using job_id and customer_id.
  2. Application: design the constraints for a required unique external account code.
  3. Transfer: explain why nonnegative line amounts do not guarantee a correct invoice total.
  4. Critique: a team enables cascading customer deletion to simplify test cleanup. Explain the consequence for real historical jobs and propose a safer test practice.

Worked reasoning for the practice

job_id distinguishes jobs; customer_id refers to a permitted account, and it can repeat across jobs. The external code needs NOT NULL and UNIQUE, plus an explicit normalization policy. Correct totals also depend on quantities, included statuses, taxes or credits if supported, and preventing join fanout. Use isolated fixture databases for destructive tests. In a production design, select deletion, archival, or retention behavior intentionally. The correct default is not determined by which command makes a developer's cleanup easiest.

Reading alignment for this expansion

The earlier introductory links remain background reading. Use the complete current on-site studios; publisher links are optional provenance. The original Academy worked records above are not quotations from those sources.

Open the runnable laboratory

Extended text lesson

Continue with A valid key is not a complete definition of the reporting population for the full worked case, source readings and optional progressive practice.

Complete current conceptual preparation

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.

```sql 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.

Developed study chapters

Original explanation, worked analysis and progressive optional practice.

Apply the idea

Two customers share a surname. Stable customer IDs distinguish them even when names or addresses change.

Which is the stronger customer key? Explain your reasoning, then identify one changed fact that could alter the conclusion.

Expanded transfer investigation: A payment row has a valid positive amount and a valid foreign key. What remains possible?

Show the calculation or argument, identify the information available at the decision time, and state which assumption supports your conclusion. The four progressive tasks in the Learn stage provide additional practice.

Read the worked reasoning

A stable unique customer ID. A key must distinguish records independently of mutable descriptive fields. In an independent response, state the given facts, identify the governing relationship, work through the calculation or comparison, and distinguish the conclusion from assumptions that still need evidence.

Expanded transfer reasoning: Structural validity does not establish the accuracy of the recorded business event.

Progressive practice reasoning: job_id distinguishes jobs; customer_id refers to a permitted account, and it can repeat across jobs. The external code needs NOT NULL and UNIQUE, plus an explicit normalization policy. Correct totals also depend on quantities, included statuses, taxes or credits if supported, and preventing join fanout. Use isolated fixture databases for destructive tests. In a production design, select deletion, archival, or retention behavior intentionally. The correct default is not determined by which command makes a developer's cleanup easiest.

Check understanding

In the lab, why use NOT NULL together with UNIQUE for required external account codes?

  1. UNIQUE makes every stored value mandatory in SQLite
    Feedback

    Incorrect. Missing-value behavior must be specified separately.

  2. NOT NULL alone prevents two accounts sharing a code
    Feedback

    Incorrect. NOT NULL enforces presence, not uniqueness.

  3. SQLite can permit multiple NULL values under UNIQUE alone
    Feedback

    Correct. The two constraints express different rules: presence and uniqueness.

Further reading

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

My learning →