Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 220 — Web Applications, SQL and Software Engineering
Weeks 6–8
Relational design, keys and queries
Learning objectives
- Explain and trace the mechanisms in relational design, keys and queries.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.
A relational schema makes entities and relationships explicit. Customers and orders are different entities: one customer may own several orders. A primary key identifies a row, while a foreign key expresses a relationship. A person's name is usually a poor identifier because names can change or collide. Store each fact at the level where it belongs rather than repeating customer details inconsistently on every order.
A join combines related rows according to a condition. Its result can have more rows than either a casual visual interpretation suggests. Joining an order to three line items produces three joined rows; summing the order total in that result counts it three times. Declare the grain of each table and intermediate result. Aggregation changes that grain, and GROUP BY does not automatically repair every earlier duplication.
NULL represents missing or inapplicable information, not zero or an empty string. SQL comparisons use three-valued logic, so amount = NULL does not select missing amounts; use IS NULL. COUNT(*) counts rows, while COUNT(column) counts non-NULL values. These distinctions affect denominators and can silently change an average. Constraints provide a second defense for application rules, but still require correct validation and meaningful error handling.
Worked reasoning The left join retains customers with no orders. COUNT(o.id) is zero for a missing joined order, whereas COUNT(*) would count the retained customer row. SUM returns NULL when no non-NULL amounts exist, so COALESCE converts that report value to zero. SQLite requires foreign-key enforcement to be enabled on the connection; declaring a reference alone is insufficient for that engine.
Extended teaching and laboratory
A relational schema requires a declared grain: one row per order, order line, payment or customer. Joining two one-to-many relationships can multiply rows. SUM over the joined result may then double count perfectly valid stored amounts. Aggregate each child relation to the intended parent grain before joining, or use a query whose grouping matches the business question.
Keys identify entities and foreign keys describe relationships, while constraints enforce only the rules actually declared and enabled. A correctly formatted foreign key does not establish authorization. Query correctness and permission checking need separate evidence.
Worked problem Order 10 has two line amounts, 300 and 700 cents, and three payment records. A join of order, lines and payments reports a line sum of 3000. Explain and repair it.
Step-by-step reasoning 1. Each of the two lines appears once for each of three payments, producing six rows. The line total is repeated three times.
- The true line amount is 300+700=1000 cents. SUM(DISTINCT amount) is not a general repair because two legitimate lines could have equal prices.
- Aggregate lines by order_id and payments by order_id independently, then join those summaries to orders.
- Test with duplicate-valued lines, no payments and no matching child rows. Choose explicit NULL-to-zero behavior for report totals.
Design the facts before the query
The original join-grain investigation assumes that tables already exist. Begin one step earlier. A relation represents rows with named attributes and a declared meaning for one row. For this fictional service, customers contains one row per customer, orders one per work order, and lines one per charged item. Customer names are descriptive values, not stable unique identities. A primary key identifies a row; a foreign key connects a row to an identified parent. An order's customer_id belongs in orders, while repeating the customer's current address in every order can create inconsistent copies unless the application deliberately stores a historical address snapshot.
Normalization is a way to examine dependencies among facts. If customer_id determines the customer's current name, store that name with the customer rather than allowing separate order rows to disagree about it. A line price charged at the time of an order is different from a product's current catalogue price, so keeping both need not be an accidental duplicate. State the historical policy before “normalizing away” a fact needed for reconstruction. A many-to-many relationship, such as orders assigned to several technicians and technicians assigned to several orders, needs an association relation with the intended uniqueness rule.
```sql CREATE TABLE customer ( id INTEGER PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE work_order ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customer(id), state TEXT NOT NULL CHECK (state IN ('open', 'closed')) ); CREATE TABLE line_item ( id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES work_order(id), cents INTEGER NOT NULL CHECK (cents >= 0) ); INSERT INTO customer(id,name) VALUES (1,'Aster'),(2,'Birch'); INSERT INTO work_order(id,customer_id,state) VALUES (10,1,'open'),(11,1,'closed'); INSERT INTO line_item(id,order_id,cents) VALUES (101,10,500),(102,10,500),(103,11,200); ```
This is a small common SQL teaching subset; engine-specific identity generation and migrations are separate choices. For SQLite, enable foreign-key enforcement on each relevant connection before relying on it. A declared foreign key is not a permission check, and a nonnegative amount rule does not authorize the person proposing it. NOT NULL excludes missing values, CHECK constrains accepted values and UNIQUE constrains a selected identity relation. A nullable CHECK expression can evaluate unknown rather than false, so use NOT NULL as well when absence is forbidden. Application validation gives useful feedback; database constraints protect against other writers and races within the rules actually enforced.
Build and change rows deliberately
INSERT proposes new rows. UPDATE changes rows selected by its WHERE predicate; DELETE removes selected rows. Omitting a WHERE can affect every row, so preview the intended predicate and test on disposable fixtures. A successful statement does not mean the intended row existed: inspect the affected-row result and the business postcondition. Use parameters for values through the driver rather than formatting visitor text into SQL. Placeholder syntax is driver-specific; the question-mark convention in the preserved SQLite examples is not a universal SQL protocol.
A query begins with the intended output grain. To list open order identities, use `SELECT id FROM work_order WHERE state='open' ORDER BY id;`. Filtering selects rows; projection chooses expressions for the output. SQL does not promise a stable result order without an appropriate ORDER BY. LIMIT restricts the returned rows but does not turn an unspecified order into a meaningful “first.” Give pagination a stable ordering and tie-breaker; concurrent insertions and updates can otherwise change pages between requests.
For the fixture, open orders are [10]. Joining open orders to their line items gives two rows, both carrying order_id 10 and one 500-cent line. A sum over line values gives 1000. Selecting DISTINCT order_id yields one order identity, but SUM(DISTINCT cents) gives 500 and loses a legitimate line. These operators act on the expressions specified, not on an implicit business intention. The existing native join-multiplication investigation extends this reasoning when payments add another one-to-many relationship.
NULL, grouping and join choices
NULL participates in SQL's three-valued logic. A comparison such as `value = NULL` is unknown, so it does not select missing values through WHERE. Use IS NULL or IS NOT NULL. WHERE keeps true rows rather than every row that is not explicitly false. AND, OR and NOT therefore require attention to unknown conditions. COALESCE selects the first non-NULL expression, useful when the report explicitly interprets an absent aggregate as zero. It should not silently convert an unknown price into a known free service.
COUNT(*) counts rows; COUNT(expression) counts non-NULL results. SUM over no qualifying non-NULL inputs is normally NULL, not an independently observed zero. GROUP BY produces one group per chosen grouping values. HAVING filters groups after aggregation; WHERE filters input rows before it. For example, counting all customers' orders and retaining groups with at least two orders differs from filtering orders to open ones first and then counting. In the fixture, Aster has two orders overall but only one open order.
An inner join returns matching combinations. A left join also preserves unmatched left rows, supplying NULLs for the missing right side. To retain Birch with zero orders, join customers to orders on customer identity and count the right order ID. COUNT(*) would count the preserved unmatched row as one. A right-side predicate in WHERE, such as `WHERE o.state='open'`, removes that NULL-extended row; putting the state condition inside the ON predicate preserves a customer with no matching open order.
```sql SELECT c.id, COUNT(o.id) AS open_orders FROM customer AS c LEFT JOIN work_order AS o ON o.customer_id=c.id AND o.state='open' GROUP BY c.id ORDER BY c.id; ```
The output is (1,1),(2,0). The result counts matching order identities, not line items or customers. Add an order without any lines and this count still increases; a total of billed cents requires a separate line aggregate and an explicit treatment of no lines. A cross join creates all combinations, and an accidental missing join predicate can have that effect. Inspect cardinality as well as the displayed numeric result.
Set operations, subqueries and common table expressions
UNION combines compatible result columns and removes duplicate result rows; UNION ALL retains multiplicity. INTERSECT gives rows present in both results, and EXCEPT gives rows from the first not present in the second, under the engine's documented semantics. Align column count and compatible types. These are result-row operations, so removing duplicates is appropriate only when the query asks for unique results. An event stream generally should not lose two legitimate equal-valued records merely because their selected columns match.
A subquery can express an existence test or provide an intermediate result. EXISTS asks whether a qualifying row exists; it need not count every matching child to answer a yes/no question. NOT IN can produce surprising unknown results if its subquery includes NULL; a carefully correlated NOT EXISTS often expresses an anti-match more directly. Correlation means that the inner condition refers to the outer row. Always include the relationship that gives that reference its meaning.
A WITH clause names an intermediate query. It makes a report's stages inspectable; it is not automatically an optimizer fence, a persistent table or a guarantee about evaluation count. Materialization and inlining depend on engine/version and query properties. Begin with nonrecursive CTEs for independently aggregated lines and payments. A recursive CTE has an initial term and a recursive expansion that references earlier results; use it for a stated hierarchical/graph question with a termination and cycle policy, not as permission to recurse through arbitrary cycles forever. Engine syntax and duplicate-elimination behavior require their own verification.
```sql WITH totals AS ( SELECT order_id, SUM(cents) AS cents FROM line_item GROUP BY order_id ) SELECT o.id, COALESCE(t.cents,0) AS cents FROM work_order AS o LEFT JOIN totals AS t ON t.order_id=o.id ORDER BY o.id; ```
The fixture produces (10,1000),(11,200). The CTE establishes one row per represented order before the join. It is not a claim that every order must already have lines. If absence means “not yet priced” rather than zero, return that state explicitly instead of the COALESCE policy shown here. Separate schema truth from presentation choices.
From a framework project to an actual request
Django is a framework for composing routes, request handling, templates, models and related application services. A project holds site-level configuration; an application groups a coherent capability. A local project skeleton alone is not an implemented feature. Keep settings, environment-specific configuration and secrets distinct, install a pinned compatible framework version in an isolated development environment, and verify the actual interpreter/package versions before reproducing commands. A virtual environment isolates dependencies; it is not a sandbox or a production authentication boundary.
A browser request reaches a configured URL dispatcher. A matching route calls a view with a request and route parameters. The view validates input, applies permission policy, accesses models/services and returns a response. A template can render a representation from supplied context. A route parameter such as order_id selects a candidate object; it does not establish that the requester owns it. The existing native ownership investigation supplies the required authorization relationship, which belongs in the actual route/service path.
An ORM model describes fields and relationships through Python classes. A model instance represents an application object; a query set describes database work and can be evaluated later, so constructing it is not always proof that a query has run. A foreign-key field expresses many child objects referring to one parent. Use the framework's relationship API without confusing the model attribute, the stored foreign-key value and an already loaded related object. Repeatedly loading a parent inside a child loop can produce an N+1 query pattern; deliberate eager-loading or a better query plan can remove unnecessary round trips while preserving permissions and output grain.
Migrations version schema transitions. Generating a migration records a proposed model change; applying it changes a selected database. Neither operation proves existing data satisfy a new constraint or makes an irreversible deletion safe to roll back. The original expand-and-contract case remains the preparation for mixed-version deployments. Keep migrations in version control, review generated operations and test both valid historical rows and the proposed compatibility path on a disposable copy before production changes.
The admin site provides a configured management interface for registered models. It is not the ordinary customer's public interface. Staff status, object policy, editable fields and query scopes must match the actual management role. Registering a model does not automatically create a customer-safe order page, nor does a hidden admin link protect the backend. Build a separate visitor view/form where needed. Seed only fictional development fixtures in these exercises; do not populate production or learner databases for a teaching test.
For a concrete route trace, suppose `/orders/10` is resolved to an order-detail view. The authenticated Aster principal is mapped to customer 1 by trusted server-side state. The view queries for order 10 AND customer 1, obtains its line rows, calculates 1000 cents under the line-grain policy and renders a template with escaped descriptions. Birch's request for the same ID finds no authorized order. A template-only test cannot establish that this query includes ownership. A direct request under Birch must verify denial and absence of private details. Model and route tests answer different questions.
Optional changed record and complete reasoning
Add order 12 for Birch without lines. Then add two independent 300-cent lines to that order. Predict the open-order counts and totals before and after the lines, explain COUNT(*) versus COUNT(o.id) for a customer with no qualifying orders, and show why SUM(DISTINCT cents) fails. Finally propose a model migration that makes a description mandatory when existing orders lack it, and trace which component authorizes a request for order 12.
**Model reasoning.** Give order 12 state open and customer_id 2 explicitly; otherwise the record is underspecified. Open-order counts become one for Aster and one for Birch whether order 12 has lines or not. Before the lines, its billed total is zero only under the shown reporting policy; it could instead be unknown/not priced under another stated policy. Afterward the sum is 600, while DISTINCT on the two equal amounts yields 300. For a retained customer with no qualifying order, COUNT(*) counts the preserved join row while COUNT(o.id) gives zero. The description migration needs an explicit, justified backfill or a compatible nullable stage; inventing descriptions merely to satisfy a constraint fabricates data. Apply and test the staged migration only on disposable fixtures first. The authorized view derives the customer from trusted authentication and filters order 12 by that identity before building a response; routing, model registration and a guessed ID do not authorize access.
Evaluate on four equal criteria: schema/grain/constraint reasoning; exact SQL/NULL/join/set/CTE interpretation; framework request/model/migration boundary trace; and authorized changed-record behavior with evidence and resource limits. The original join and authorization models remain intact. The retained PostgreSQL and Django references are optional provenance and further examples once this original preparation is published.
Apply the idea
Order 10 has two line amounts, 300 and 700 cents, and three payment records. A join of order, lines and payments reports a line sum of 3000. Explain and repair it.
Two order lines are both 500 cents and there are two payments. Why does SUM(DISTINCT line_amount) still fail?
Read the worked reasoning
The actual line total is 1000, but DISTINCT collapses the two equal 500 values and returns 500. Distinct values are not distinct line identities. Group the actual line rows before joining the payment summary; test the join’s cardinality rather than treating DISTINCT as a universal correction.
Check understanding
What causes a threefold total after joining orders to three line items?
- NULL always multiplies money
Feedback
NULL semantics are distinct from cardinality mistakes.
- The join changes the row grain and repeats the order total
Feedback
One-to-many joins repeat parent fields in their result.
- Primary keys guarantee every joined total is unique
Feedback
Uniqueness in a base table does not prevent join multiplication.
Further reading
Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.
Use the complete original preparation chapter, preserved investigation and optional changed-record reasoning for this unit. Earlier source directions remain in immutable edition 4.
- Original Academy preparation — SQL and application models
- 2.2. Concepts #
- 2.3. Creating a New Table #
- 2.4. Populating a Table With Rows #
- 2.5. Querying a Table #
- 2.6. Joins Between Tables #
- 2.7. Aggregate Functions #
- 5.5. Constraints #
- 7.2. Table Expressions #
- 7.3. Select Lists #
- 7.4. Combining Queries ( UNION , INTERSECT , EXCEPT ) #
- 7.8. WITH Queries (Common Table Expressions) #
- Django Tutorial: The Local Library website
- Django Tutorial Part 2: Creating a skeleton website
- Django Tutorial Part 3: Using models
- Django Tutorial Part 4: Django admin site