Phase 07 · Lesson 03

Keys Relationships and Joins

≈ 3 min core reading · 582 source/companion words
Learning contract

What you should be able to do after this

  • Explain Keys Relationships and Joins without relying on framework buzzwords.
  • Connect the lesson to the phase outcome: Use relational modeling and SQL deliberately: keys, constraints, joins, transactions, indexes, and query reasoning.
  • Reproduce the relevant behavior and verify it with evidence.
  • Diagnose at least one representative failure instead of guessing.
Figure 7.3 — TaskFlow boundary map
Business invariant
table design
key/constraint
SQL query
query plan/index
transaction
durable rows
This lesson belongs to Phase 07. Keep the full request/data path visible even when today's code changes only one box.
Instructor workflow: predict first → implement the smallest slice → run it → inspect evidence → break one assumption → diagnose → explain it back. Do not copy the whole code block before understanding the first failing boundary.

FULL_STACK_DEVELOPER_2026_COMPLETE - Phase 07 Keys, Relationships and Joins

VOLUME 03 - DATABASE ENGINEERING

Keys, Relationships and Joins Identity, referential integrity and relational reads

Persistence becomes understandable when the database stops being magic.

Application SQL / ORM PostgreSQL

NestJS business logic database commands durable relational state

Phase 07 focus

understand the database before Prisma

Figure - Phase 07 isolates PostgreSQL fundamentals so later ORM code has a clear relational meaning.

Book 3 of Phase 07

FULL_STACK_DEVELOPER_2026_COMPLETE - Phase 07 Keys, Relationships and Joins

Primary keys answer: which row? A primary key identifies each row uniquely and cannot be NULL. PostgreSQL automatically creates a unique B-tree index for the primary-key columns. The key is both a data-integrity rule and an efficient lookup path. Primary key

CREATE TABLE projects ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL );

Foreign keys answer: does this relationship exist? A foreign key requires values in the referencing column to match a key in another table. This prevents a task from claiming to belong to a project that does not exist. Foreign key

CREATE TABLE tasks ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, project_id bigint NOT NULL REFERENCES projects(id), title text NOT NULL );

Relationships are data rules, not drawing decorations.

projects tasks comments

id PK id PK id PK name project_id FK task_id FK

one project many tasks many comments

Relational database

tables + constraints + relationships + transactions

Figure - A relational schema stores facts in tables and uses keys/constraints to preserve valid relationships.

Foreign-key actions are domain decisions Action Meaning Typical question

NO ACTION / RESTRICT Prevent parent change/delete when Should a project be deletable while tasks still exist? dependent rows would be invalid.

CASCADE Propagate parent delete/update to Are child rows meaningless without the parent? related rows.

SET NULL Remove the relationship while Can a task exist without a project? preserving the child row.

Do not cargo-cult CASCADE

Cascade behavior can be correct, but it can also turn one delete into a large irreversible data change. Choose referential actions from business meaning, not convenience.

FULL_STACK_DEVELOPER_2026_COMPLETE - Phase 07 Keys, Relationships and Joins

One-to-many and many-to-many A project has many tasks when tasks.project_id references projects.id. A many-to-many relationship usually becomes an explicit join table containing two foreign keys, often with a composite primary key or unique constraint. Many-to-many join table

CREATE TABLE task_labels ( task_id bigint NOT NULL REFERENCES tasks(id), label_id bigint NOT NULL REFERENCES labels(id), PRIMARY KEY (task_id, label_id) );

JOIN reads related facts Inner join

SELECT t.id, t.title, p.name AS project_name FROM tasks AS t JOIN projects AS p ON p.id = t.project_id ORDER BY t.id;

The join condition states how rows relate. An INNER JOIN returns rows that have matches on both sides. A LEFT JOIN keeps rows from the left side even when no right-side match exists. Choosing a join is therefore part of the question being asked, not merely SQL syntax.

Question Useful join

Show tasks only when their project exists INNER JOIN

Show every project, including projects with zero tasks LEFT JOIN from projects to tasks

Show every task and optional assignee details LEFT JOIN when assignee is nullable

Foreign keys and indexes are different responsibilities The referenced primary/unique key is indexed, but PostgreSQL does not automatically create an index on the referencing foreign-key column. If the application frequently joins, filters, updates or deletes through that foreign key, an index on the referencing column is often useful. We justify it from query patterns rather than from habit.

Executable lesson studio · sql

Now turn the explanation into engineering skill.

ORMs do not remove the database. SQL literacy lets you reason about correctness, constraints, query cost, transactions, and the evidence stored in PostgreSQL.

By the end, you should be able to

  • Explain Keys Relationships and Joins in terms of concrete inputs, ownership, outputs, and evidence.
  • Implement or reproduce the smallest TaskFlow slice that demonstrates this sql concept.
  • Diagnose one representative sql failure using observable evidence instead of trial-and-error.
Figure 7.3B — Mental model
application intent
SQL statement
query planner
table/index
rows returned
Read left-to-right while implementing. When debugging, walk right-to-left until the first observed fact differs from your prediction.
Code-along sequence

One coherent change at a time

  1. 01

    Restate the goal of “Keys Relationships and Joins” as one observable behavior. Write the success signal before touching code.

  2. 02

    Trace the boundary map: application intent → SQL statement → query planner → table/index → rows returned. Mark the one boundary this lesson changes.

  3. 03

    Inspect the current repository state and record the exact files, route, table, or runtime involved. Avoid creating an abstraction before you can name the existing owner.

  4. 04

    Implement the smallest vertical slice. Add one coherent change, run the narrowest verification command, and read the output before continuing.

  5. 05

    Connect the slice to TaskFlow’s phase artifact: A TaskFlow relational sketch plus SQL exercises that create, query, join, update, and constrain representative data.. Verify behavior from the outside as a user or API client would.

  6. 06

    Create one controlled failure that is safe to reproduce. Predict the symptom first, capture evidence, locate the earliest broken boundary, then fix only that cause.

  7. 07

    Close the reference and rebuild or explain the core change from memory. Record what you would monitor or test before trusting the same change in production.

sqlQuery from TaskFlow data directly
SELECT t.id, t.title, u.name AS assignee
FROM tasks AS t
LEFT JOIN users AS u ON u.id = t.assignee_id
WHERE t.workspace_id = $1
ORDER BY t.created_at DESC, t.id DESC;

Do not copy this as a finished answer. Predict what each boundary does, type the smallest useful slice, run it, then compare the result with your prediction.

Verification

Prove the happy path

  1. Run the narrowest relevant command or request and require a clean exit/status.
  2. Inspect the boundary-specific evidence: terminal output, Network panel, database row/query plan, test report, container health, or deployment logs.
  3. Repeat the behavior once after the change so a one-off cached or stale result cannot masquerade as success.
Break it on purpose

Build debugging memory

  1. N+1 query patterns hidden by application loops
  2. Change one assumption in the sql example—identity, input, configuration, ordering, connectivity, or state—and predict the exact symptom before running it.
SymptomInvestigation path
Query is correct but slow

Capture EXPLAIN ANALYZE, row counts, filters, sort keys, and indexes before adding an index.

Unexpected duplicate/missing rows

Inspect join cardinality and constraints; do not hide a modeling bug with DISTINCT until you understand it.

Closed-reference challenge

Can you transfer the idea?

Without copying the final source, create a second small scenario that applies “Keys Relationships and Joins” to a different TaskFlow resource or input. Write the acceptance criteria first, implement it, and provide the evidence that each criterion is satisfied.

Explain-back

Answer these without reopening the solution

  1. What problem does Keys Relationships and Joins solve in TaskFlow, and what would be observably wrong without it?
  2. Which part of the sql boundary owns the decision, and which neighboring layer must not own it?
  3. What evidence proves the happy path instead of merely suggesting it worked?
  4. Name one realistic failure or abuse case and the first place you would inspect.
  5. If requirements doubled tomorrow, which part of this design should stay stable and which part is allowed to change?
Lesson studio

Turn the reading into skill

01

Do it

Write joins by hand and predict row counts before executing them.

Use the smallest change that demonstrates this lesson. Stop after it works and capture evidence.
02

Break it safely

N+1 query patterns hidden by application loops

Predict the symptom before causing the failure. Then locate the earliest boundary where reality diverges from expectation.
03

Explain it back

Why does this responsibility live here, what input does it trust, what output proves success, and what would go wrong if another layer owned it?

If your explanation is vague, repeat the boundary trace before moving on.
Exit ticket

Before marking complete

Close the reference. Reproduce the core idea from memory or explain the exact request/data flow aloud. Then check your diff or notes for accidental shortcuts that bypass validation, authorization, error handling, or verification earned in earlier phases.