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.
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.
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?
- 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.
- NULL always multiplies money
Feedback
NULL semantics are distinct from cardinality mistakes.
Further reading
Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Complete CS50 SQL Querying, Relating and Designing. Work the full associated problem sets. Draw entity relationships before writing your application schema.
- 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