Relational Data & SQL Primer
Django, FastAPI, analytics, and distributed systems all depend on data modelling. This bridge lesson moves from entities and keys to normalized tables, joins, aggregates, transactions, indexes, and query plans using one small store domain.
- Explain Relational modelling by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain SQL essentials by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Transactions and performance by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
How to use this chapter
For Relational Data & SQL Primer, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the data learning arc appropriate to this subject.
The problem this chapter solves
Django, FastAPI, analytics, and distributed systems all depend on data modelling. This bridge lesson moves from entities and keys to normalized tables, joins, aggregates, transactions, indexes, and query plans using one small store domain.
Relational modelling and SQL protect shared facts under concurrent access and let the database optimize set-based reads and changes from declared intent.
Learning outcomes
- Explain Relational modelling by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain SQL essentials by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Transactions and performance by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
The database parses and binds SQL, rewrites views and rules, chooses a costed plan, executes scans/joins/sorts/aggregates against transaction-visible versions, enforces constraints, and records committed changes in a recovery log. In Relational Data & SQL Primer, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The client begins a transaction and sends parameterized SQL.
- PostgreSQL parses, rewrites, and plans the statement using statistics and available indexes.
- The executor reads MVCC-visible rows and applies joins, filters, grouping, or changes.
- Constraints reject invalid state before commit; WAL records durable changes.
- EXPLAIN ANALYZE and tests verify result, plan, timing, and concurrency invariant.
Memory and performance lens
Indexes and table pages compete for cache; sorts and hashes use bounded working memory and may spill. Transactions retain snapshots and locks, while long-running work prevents cleanup of older row versions. For Relational Data & SQL Primer, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Relational Data & SQL Primer, measure rows and bytes scanned, plan estimates versus actuals, buffer hits/reads, spill, lock time, cache memory, and tail latency rather than optimizing from source-code appearance.
1. Relational modelling
The Relational modelling unit begins with entities, attributes and relationships: Relational modelling represents domain facts in tables whose keys identify rows and whose relationships are protected by constraints. Normalize transactional data through 3NF by default, then denormalize only for a measured read need with a refresh protocol. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Relational modelling
| Concept | Meaning | Engineering decision |
|---|---|---|
| entities, attributes and relationships | Relational modelling represents domain facts in tables whose keys identify rows and whose relationships are protected by constraints. | Normalize transactional data through 3NF by default, then denormalize only for a measured read need with a refresh protocol. |
| primary, foreign and candidate keys | Relational modelling represents domain facts in tables whose keys identify rows and whose relationships are protected by constraints. | Normalize transactional data through 3NF by default, then denormalize only for a measured read need with a refresh protocol. |
| normalization from 1NF through 3NF | Relational modelling represents domain facts in tables whose keys identify rows and whose relationships are protected by constraints. | Normalize transactional data through 3NF by default, then denormalize only for a measured read need with a refresh protocol. |
| constraints and domain invariants | SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
Storage, planning, and execution: Relational modelling
entities, attributes and relationships. Primary/candidate keys enforce identity, foreign keys enforce references, and normalization separates facts so one change is stored once. Joins reconstruct related views when queried.
primary, foreign and candidate keys. Primary/candidate keys enforce identity, foreign keys enforce references, and normalization separates facts so one change is stored once. Joins reconstruct related views when queried.
normalization from 1NF through 3NF. Primary/candidate keys enforce identity, foreign keys enforce references, and normalization separates facts so one change is stored once. Joins reconstruct related views when queried.
constraints and domain invariants. The database parses and plans a statement, scans access paths, applies joins/filters/groups, and enforces constraints inside the transaction. Parameter binding keeps data separate from SQL syntax.
Read these as one system: entities, attributes and relationships establishes the starting contract, primary, foreign and candidate keys changes how that contract is executed or represented, and constraints and domain invariants exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: Relational modelling
This Relational modelling slice makes entities, attributes and relationships observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward constraints and domain invariants, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: Relational modelling
| Risk | Why it matters |
|---|---|
| entities, attributes and relationships | Using mutable business text as identity or duplicating facts across rows creates update anomalies and broken references. |
| primary, foreign and candidate keys | Using mutable business text as identity or duplicating facts across rows creates update anomalies and broken references. |
| normalization from 1NF through 3NF | Using mutable business text as identity or duplicating facts across rows creates update anomalies and broken references. |
| constraints and domain invariants | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. |
Data investigation: Relational modelling
- Foundation: implement or demonstrate entities, attributes and relationships with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine entities, attributes and relationships with primary, foreign and candidate keys. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for constraints and domain invariants. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. SQL essentials
The SQL essentials unit begins with SELECT, WHERE and ORDER BY: SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: SQL essentials
| Concept | Meaning | Engineering decision |
|---|---|---|
| SELECT, WHERE and ORDER BY | SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
| INSERT, UPDATE and DELETE | SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
| INNER/LEFT joins | SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
| GROUP BY, HAVING and aggregates | SQL declares the rows to read or change; constraints protect valid state and set operations combine or summarize many rows at once. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
Storage, planning, and execution: SQL essentials
SELECT, WHERE and ORDER BY. The database parses and plans a statement, scans access paths, applies joins/filters/groups, and enforces constraints inside the transaction. Parameter binding keeps data separate from SQL syntax.
INSERT, UPDATE and DELETE. The database parses and plans a statement, scans access paths, applies joins/filters/groups, and enforces constraints inside the transaction. Parameter binding keeps data separate from SQL syntax.
INNER/LEFT joins. The database parses and plans a statement, scans access paths, applies joins/filters/groups, and enforces constraints inside the transaction. Parameter binding keeps data separate from SQL syntax.
GROUP BY, HAVING and aggregates. The database parses and plans a statement, scans access paths, applies joins/filters/groups, and enforces constraints inside the transaction. Parameter binding keeps data separate from SQL syntax.
Read these as one system: SELECT, WHERE and ORDER BY establishes the starting contract, INSERT, UPDATE and DELETE changes how that contract is executed or represented, and GROUP BY, HAVING and aggregates exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Query or command in context: SQL essentials
1SELECT order_id, total_amount, created_at2FROM purchase_order3WHERE customer_id = :customer_id4ORDER BY created_at DESC, order_id DESC5LIMIT :page_size;This SQL essentials slice makes SELECT, WHERE and ORDER BY observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward GROUP BY, HAVING and aggregates, predict its behavior for empty, invalid, repeated, and large input.
Correctness and performance traps: SQL essentials
| Risk | Why it matters |
|---|---|
| SELECT, WHERE and ORDER BY | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. |
| INSERT, UPDATE and DELETE | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. |
| INNER/LEFT joins | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. |
| GROUP BY, HAVING and aggregates | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. |
Data investigation: SQL essentials
- Foundation: implement or demonstrate SELECT, WHERE and ORDER BY with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine SELECT, WHERE and ORDER BY with INSERT, UPDATE and DELETE. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for GROUP BY, HAVING and aggregates. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Transactions and performance
The Transactions and performance unit begins with ACID and transaction boundaries: A transaction groups operations into one atomic outcome; isolation defines which effects of concurrent transactions can be observed. Keep transactions short and choose isolation plus constraints according to the invariant and expected contention. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The data model and its guarantees: Transactions and performance
| Concept | Meaning | Engineering decision |
|---|---|---|
| ACID and transaction boundaries | A transaction groups operations into one atomic outcome; isolation defines which effects of concurrent transactions can be observed. | Keep transactions short and choose isolation plus constraints according to the invariant and expected contention. |
| isolation anomalies overview | A transaction groups operations into one atomic outcome; isolation defines which effects of concurrent transactions can be observed. | Keep transactions short and choose isolation plus constraints according to the invariant and expected contention. |
| B-tree index basics | A B-tree is an ordered auxiliary structure that can accelerate equality, range, and ordering operations; EXPLAIN shows the plan chosen for a statement. | Measure with representative data and EXPLAIN ANALYZE, then add the smallest index that supports an important workload. |
| EXPLAIN and evidence-based optimization | A B-tree is an ordered auxiliary structure that can accelerate equality, range, and ordering operations; EXPLAIN shows the plan chosen for a statement. | Measure with representative data and EXPLAIN ANALYZE, then add the smallest index that supports an important workload. |
Storage, planning, and execution: Transactions and performance
ACID and transaction boundaries. Locks and MVCC snapshots coordinate readers and writers. Commit makes the transaction durable through the database log; rollback discards its uncommitted changes.
isolation anomalies overview. Locks and MVCC snapshots coordinate readers and writers. Commit makes the transaction durable through the database log; rollback discards its uncommitted changes.
B-tree index basics. The optimizer estimates row counts and costs for scans, joins, sorts, and aggregates. Index usefulness depends on column order, predicates, distribution, and table size.
EXPLAIN and evidence-based optimization. The optimizer estimates row counts and costs for scans, joins, sorts, and aggregates. Index usefulness depends on column order, predicates, distribution, and table size.
Read these as one system: ACID and transaction boundaries establishes the starting contract, isolation anomalies overview changes how that contract is executed or represented, and EXPLAIN and evidence-based optimization exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Correctness and performance traps: Transactions and performance
| Risk | Why it matters |
|---|---|
| ACID and transaction boundaries | Reading a value, deciding in application code, and writing later without an atomic guard permits lost updates and write skew. |
| isolation anomalies overview | Reading a value, deciding in application code, and writing later without an atomic guard permits lost updates and write skew. |
| B-tree index basics | Indexes increase storage and write/vacuum cost; an unused or badly ordered index can slow the system without improving reads. |
| EXPLAIN and evidence-based optimization | Indexes increase storage and write/vacuum cost; an unused or badly ordered index can slow the system without improving reads. |
Data investigation: Transactions and performance
- Foundation: implement or demonstrate ACID and transaction boundaries with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine ACID and transaction boundaries with isolation anomalies overview. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for EXPLAIN and evidence-based optimization. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1CREATE TABLE customer (2 customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3 email text NOT NULL UNIQUE4);5CREATE TABLE purchase_order (6 order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,7 customer_id bigint NOT NULL REFERENCES customer(customer_id),8 total numeric(12,2) NOT NULL CHECK (total >= 0),9 created_at timestamptz NOT NULL DEFAULT now()10);11CREATE INDEX order_customer_created_idx12 ON purchase_order (customer_id, created_at DESC);13SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent14FROM purchase_order15GROUP BY customer_id16HAVING SUM(total) > 1000;Expected result
1The schema protects identity, references, and non-negative totals; the query returns customers whose combined order total exceeds 1000.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | CREATE TABLE customer ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 2 | customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, | Implements the next sql statement in the example's data flow. |
| 3 | email text NOT NULL UNIQUE | Implements the next sql statement in the example's data flow. |
| 4 | ); | Implements the next sql statement in the example's data flow. |
| 5 | CREATE TABLE purchase_order ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 6 | order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, | Implements the next sql statement in the example's data flow. |
| 7 | customer_id bigint NOT NULL REFERENCES customer(customer_id), | Implements the next sql statement in the example's data flow. |
| 8 | total numeric(12,2) NOT NULL CHECK (total >= 0), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | created_at timestamptz NOT NULL DEFAULT now() | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 10 | ); | Implements the next sql statement in the example's data flow. |
| 11 | CREATE INDEX order_customer_created_idx | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 12 | ON purchase_order (customer_id, created_at DESC); | Implements the next sql statement in the example's data flow. |
| 13 | SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 14 | FROM purchase_order | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 15 | GROUP BY customer_id | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 16 | HAVING SUM(total) > 1000; | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
Step-by-step execution
- The client begins a transaction and sends parameterized SQL.
- PostgreSQL parses, rewrites, and plans the statement using statistics and available indexes.
- The executor reads MVCC-visible rows and applies joins, filters, grouping, or changes.
- Constraints reject invalid state before commit; WAL records durable changes.
- EXPLAIN ANALYZE and tests verify result, plan, timing, and concurrency invariant.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Relational modelling | Using mutable business text as identity or duplicating facts across rows creates update anomalies and broken references. | Normalize transactional data through 3NF by default, then denormalize only for a measured read need with a refresh protocol. |
| SQL essentials | Missing join predicates multiply rows, NULL changes three-valued logic, and string-built SQL permits injection. | Select only required columns, parameterize input, use explicit join conditions, and place aggregate filters in HAVING. |
| Transactions and performance | Reading a value, deciding in application code, and writing later without an atomic guard permits lost updates and write skew. | Keep transactions short and choose isolation plus constraints according to the invariant and expected contention. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Relational modelling: entities, attributes and relationships
- To do: Relational modelling: primary, foreign and candidate keys
- To do: Relational modelling: normalization from 1NF through 3NF
- To do: Relational modelling: constraints and domain invariants
- To do: SQL essentials: SELECT, WHERE and ORDER BY
- To do: SQL essentials: INSERT, UPDATE and DELETE
- To do: SQL essentials: INNER/LEFT joins
- To do: SQL essentials: GROUP BY, HAVING and aggregates
- To do: Transactions and performance: ACID and transaction boundaries
- To do: Transactions and performance: isolation anomalies overview
- To do: Transactions and performance: B-tree index basics
- To do: Transactions and performance: EXPLAIN and evidence-based optimization
Quick revision
- Relational modelling: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- SQL essentials: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Transactions and performance: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?