Lawfare Academy

CS 220 — Web Applications, SQL and Software Engineering · Weeks 6–8

Relational design, keys and queries

Full teaching sequence and cumulative subject work

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.

Exercise a real HTTP route and its database boundary — primary material, constructed-response tasks, complete worked model and changed-case examination →

Relational grain, joins and aggregation

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.

Trace the complete reasoning
  1. Each of the two lines appears once for each of three payments, producing six rows. The line total is repeated three times.

  2. 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.

  3. Aggregate lines by order_id and payments by order_id independently, then join those summaries to orders.

  4. Test with duplicate-valued lines, no payments and no matching child rows. Choose explicit NULL-to-zero behavior for report totals.

Independent transfer problem

Two order lines are both 500 cents and there are two payments. Why does SUM(DISTINCT line_amount) still fail?

Compare the transfer solution

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.

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.

Study the mechanism

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 example

CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  cents INTEGER NOT NULL CHECK(cents >= 0)
);
SELECT c.id, c.name, COUNT(o.id) AS orders, COALESCE(SUM(o.cents), 0) AS cents
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;

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.

Check your understanding

What causes a threefold total after joining orders to three line items?

  1. The join changes the row grain and repeats the order total
  2. Primary keys guarantee every joined total is unique
  3. NULL always multiplies money
Answer and reasoning for every option

Correct: The join changes the row grain and repeats the order total One-to-many joins repeat parent fields in their result.

Reconsider: Primary keys guarantee every joined total is unique Uniqueness in a base table does not prevent join multiplication.

Reconsider: NULL always multiplies money NULL semantics are distinct from cardinality mistakes.

Transfer laboratory: Join multiplication and the report grain

One order has total 12000 cents, three lines and two payments. A query joins both child tables and sums the order total. Predict the wrong total and repair the query plan.

Work through the full solution

The joined order produces 3×2=6 rows, so summing its repeated total gives 72000. Aggregate each one-to-many child at the order grain before joining, or query the authoritative order total without joining unrelated detail. DISTINCT on the numeric total is not a general fix because different orders can share an amount.

Evidence of understanding

Compute 72000, name the many-to-many multiplication and explain why numeric DISTINCT is unsafe.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 2.2. Concepts # · The PostgreSQL Global Development Group and The Regents of the University of California
  2. 2.3. Creating a New Table # · The PostgreSQL Global Development Group and The Regents of the University of California
  3. 2.4. Populating a Table With Rows # · The PostgreSQL Global Development Group and The Regents of the University of California
  4. 2.5. Querying a Table # · The PostgreSQL Global Development Group and The Regents of the University of California
  5. 2.6. Joins Between Tables # · The PostgreSQL Global Development Group and The Regents of the University of California
  6. 2.7. Aggregate Functions # · The PostgreSQL Global Development Group and The Regents of the University of California
  7. 5.5. Constraints # · The PostgreSQL Global Development Group and The Regents of the University of California
  8. 7.2. Table Expressions # · The PostgreSQL Global Development Group and The Regents of the University of California
  9. 7.3. Select Lists # · The PostgreSQL Global Development Group and The Regents of the University of California
  10. 7.4. Combining Queries ( UNION , INTERSECT , EXCEPT ) # · The PostgreSQL Global Development Group and The Regents of the University of California
  11. 7.8. WITH Queries (Common Table Expressions) # · The PostgreSQL Global Development Group and The Regents of the University of California
  12. Django Tutorial: The Local Library website · Mozilla Contributors
  13. Django Tutorial Part 2: Creating a skeleton website · Mozilla Contributors
  14. Django Tutorial Part 3: Using models · Mozilla Contributors
  15. Django Tutorial Part 4: Django admin site · Mozilla Contributors

Open in My Learning to record progress →