smartyfy.mrindigi.com

Databases & SQL Master Course — 196. Capstone Operational Queries

Lesson 196 Capstone Operational Queries

Prerequisites and objectives

Complete Lesson 195 and review the earlier concepts named in this lesson. You will retrieve an order safely, build a grain-correct work queue, and accept a guarded state change only when its preconditions hold. Review parameter binding, affected-row counts, existence tests, and SQLite writer transactions. The shared capstone is a fictional workshop-supply shop using one currency, USD cents. Every exercise scenario starts from a new copy of its displayed fixture; changes in another lesson are not assumed to persist.

Shared fixture dependency

Run the exact schema and seed from Lesson 193 in a new disposable SQLite database. The displayed setup is sufficient; no companion download is required. Any additional definition is shown below. Each exercise was verified from this baseline independently, not from the previous exercise’s final state.

Treat operational queries as explicit contracts

An operational query supports a particular action: inspect an order, list work waiting for attention, or request a state transition. Give each operation a defined input, result shape, authorization assumption, and failure response. A successful SQL execution is not automatically a successful business operation.

The lookup uses a bound order identity. The queue includes open orders and calculates their historical line totals. The transition changes an open order with at least one line to paid. It does not contact a payment provider, verify settlement, reserve inventory, or create a shipment. Those remain outside the capstone’s scope.

The schema allows an open order with no lines so a header can be created before its contents arrive. The controlled transition checks that a line exists. This requirement cannot be inferred from the foreign key in the opposite direction, which merely ensures every existing line has an order.

Observed operational outcomes
Operation Accepted baseline result Important limit
Lookup order 11 One INK line, 500 cents Bound identity does not replace authorization
Open-order queue Order 11, total 500 cents One row per order
Transition order 11 One changed row Recorded state only
Repeat transition Zero changed rows Inspect current state before responding

Separate values from query structure

Pass the order identity through the SQL client’s parameter mechanism rather than concatenating input into SQL text. This keeps a value from becoming query syntax. Binding does not prove that the caller is entitled to read or change that order; authorization belongs in the application’s controlled access path.

Select only the fields required by the operation, with explicit output names and ordering. A list screen may need an order identity and amount without exposing every customer attribute. Smaller, stable interfaces are easier to test and less likely to leak unrelated data when the schema grows.

For a queue, aggregate at order grain. An order with several lines should not appear several times as if it were several independent jobs. Use a left join if empty open headers are part of the queue contract, and label their zero total as an incomplete order rather than silently calling them ready for payment.

Exercise 1

Retrieve an order’s line detail with a bound identity.

Worked solution
-- Connection A
-- Bind values through the client API: [11]
SELECT l.line_no,p.sku,l.units,l.unit_cents,l.units*l.unit_cents AS line_cents FROM cap_line l JOIN cap_product p ON p.id=l.product_id WHERE l.order_id=? ORDER BY l.line_no;

The lookup returns one line for order eleven with a five-hundred-cent historical amount. The join adds the catalog SKU but does not replace the charged unit price. A missing order and an existing empty order both yield no line rows here, so an application needing that distinction should also inspect the order header.

Exercise 2

Produce one queue row per open order.

Worked solution
-- Connection A
SELECT o.id,COUNT(l.line_no),COALESCE(SUM(l.units*l.unit_cents),0) FROM cap_order o LEFT JOIN cap_line l ON l.order_id=o.id WHERE o.status='open' GROUP BY o.id ORDER BY o.id;

The queue contains one open order with one line. COUNT of the child line number correctly becomes zero for an empty header, unlike COUNT(*) over a NULL-extended outer-join row. A later readiness policy can distinguish those empty headers without changing the queue’s population.

Exercise 3

Accept once and inspect a repeated state-change attempt.

Worked solution
-- Connection A
BEGIN IMMEDIATE;
-- Bind values through the client API: [11]
UPDATE cap_order SET status='paid' WHERE id=? AND status='open' AND EXISTS(SELECT 1 FROM cap_line WHERE order_id=cap_order.id);
-- Bind values through the client API: [11]
UPDATE cap_order SET status='paid' WHERE id=? AND status='open' AND EXISTS(SELECT 1 FROM cap_line WHERE order_id=cap_order.id);
SELECT status FROM cap_order WHERE id=11;
SELECT COUNT(DISTINCT o.id),SUM(l.units),SUM(l.units*l.unit_cents) FROM cap_order o JOIN cap_line l ON l.order_id=o.id WHERE o.status='paid';
ROLLBACK;

The first update accepts the preconditions. The repeat changes zero rows because the order is no longer open, while the state query confirms paid. The temporary paid report rises to three orders, seven units, and thirteen hundred thirty cents. Rollback restores the original open order and baseline report.

Exercise 4

Reject an empty order without misreporting a SQL error as the only failure mode.

Worked solution
-- Connection A
BEGIN IMMEDIATE;
INSERT INTO cap_order VALUES(13,'EXT-13',3,'open','2026-10-03');
-- Bind values through the client API: [13]
UPDATE cap_order SET status='paid' WHERE id=? AND status='open' AND EXISTS(SELECT 1 FROM cap_line WHERE order_id=cap_order.id);
SELECT status FROM cap_order WHERE id=13;
-- Bind values through the client API: [99]
UPDATE cap_order SET status='paid' WHERE id=? AND status='open' AND EXISTS(SELECT 1 FROM cap_line WHERE order_id=cap_order.id);
ROLLBACK;

The empty order remains open, and the nonexistent identity also changes zero rows. Those outcomes are not identical business states even though their affected-row counts match. A controlled follow-up lookup can classify them without treating every zero as a successful retry.

Keep retries and concurrency bounded

BEGIN IMMEDIATE acquires the SQLite writer transaction before the controlled change. Handle busy outcomes deliberately and keep the transaction short. Do not wait for an external payment service while holding this transaction; the capstone’s recorded-state operation is intentionally local and bounded.

The repeated-update guard is not a complete request-idempotency protocol. If a caller needs a stable response for a retried external operation, store an appropriate operation identity and result under a designed contract. A current paid state alone may not prove which request caused it.

Every alternate write path must respect the same lifecycle rule. Direct SQL can still set status to paid without checking lines because the table CHECK validates only the allowed vocabulary. The handoff must state that enforcement boundary rather than claiming the workflow is an unbypassable database constraint.

If porting to a server engine, review isolation and locking under that engine’s concurrent-writer model. The predicate is useful logic, but the exact transaction guarantee does not transfer merely by copying the SQL text. SQLite execution evidence remains specific to the tested environment.

Pitfalls and summary

Bind values, preserve the required grain, and distinguish SQL success from accepted business state. Inspect affected rows and relevant current state, keep local transactions short, and document the boundary between schema constraints, controlled workflows, and unimplemented external processes.

Knowledge check

Question 1

Why can an empty open order exist but fail the transition?

  1. Foreign keys automatically delete empty orders
  2. The workflow requires a line before paid state, while header creation permits none
  3. The status CHECK forbids open orders
  4. The queue cannot represent zero line counts
Answer and explanation

B. Parent existence and minimum-child requirements point in different directions.

Question 2

What does the repeated transition’s zero row count establish?

  1. The original request definitely failed
  2. The order identity definitely does not exist
  3. The database postponed the update until rollback
  4. No row met the update predicate on that attempt
Answer and explanation

D. A follow-up state check distinguishes already-paid, empty, and missing cases.

Question 3

Which price is used in the line lookup?

  1. The latest catalog list_cents
  2. The mean price across all product appearances
  3. The historical unit_cents on cap_line
  4. The maximum available price for the SKU
Answer and explanation

C. The catalog join supplies descriptive identity without repricing history.

Question 4

Does binding an order identity authorize access to it?

  1. No; binding and authorization solve different problems
  2. Yes, because a prepared statement grants ownership
  3. Yes, whenever the identity is an integer
  4. Only filtering the result to paid orders is additionally required
Answer and explanation

A. Separating SQL code from values does not establish caller permissions.

Question 5

What is the temporary paid total after accepting order eleven?

  1. 830 cents because status cannot affect reports
  2. 500 cents because only the changed order remains
  3. 1330 cents
  4. 1830 cents because the order is counted twice
Answer and explanation

C. The original 830 plus the newly paid order’s 500 equals 1330.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references