SQL and application models
Original on-site instruction. Practice and outside references are optional. Independent subject review and observed learner testing remain pending.
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.
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.
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.
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.
Compare the complete changed-record reasoning
**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.