HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 11“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Relational Data Modeling with PostgreSQL
TechLearningPro's progress API was finally authorized and documented.
Course progress0%
Focus
15 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 11 · Full-Stack Engineering Foundations
Lesson Overview
TechLearningPro's progress API was finally authorized and documented. The data underneath it was not. enrollments had no unique key on learner and course, so the idempotent create from lesson 10 still raced. lesson_progress stored percent complete as text. Course completion was a column any update could flip. An export job joined on email addresses that learners can change. When an instructor asked for Monday's completion board, the query filtered nothing by organization and relied on the application to "drop the extra rows," which a second report forgot to do. The model had treated PostgreSQL as a place to drop JSON, and the product had treated constraints as optional.
Relational modeling is how you make those rules true even when a handler has a bug. PostgreSQL stores enrollments, progress, and organization membership as rows with keys, foreign keys, uniqueness, and checks. The Node service from Backend Engineering with Node.js talks to it with parameterized SQL. The contract from API Design with REST, OpenAPI and GraphQL Concepts is only as strong as the constraints that reject a second active enrollment or a progress row without a parent.
This lesson is the last one in Full-Stack Engineering Foundations. The running system is the TechLearningPro Learning Platform: organizations, learners, courses, enrollments, and lesson progress. AI features will later store embeddings, prompt versions, and job metadata. Those belong in tables with the same discipline—typed columns, foreign keys to the learner and the course, and no trust that a model picked a valid id. Vector search with pgvector is a later lesson. Here you design the relational core those features attach to.
Planning assumptions, labeled so they are not a capacity plan:
Enrollment week is write-heavy on a small set of tables. The Monday board reads aggregates and can lag interactive progress by a defined interval.
Learner email is an attribute, not a primary key.
Illustrative index choices are starting points. Confirm them with EXPLAIN on your data volume before you call them production tuning.
Credentials for the app_rw role live outside git. Examples use role names and host names only.
Learning Objectives
By the end of this lesson you will be able to:
Model organizations, learners, courses, enrollments, and lesson progress with keys that match the API.
Explain primary keys, foreign keys, unique constraints, and check constraints as product rules.
Choose natural uniqueness (learner_id, course_id) separately from a surrogate id used in URLs.
Normalize the core so completion state is not copied into conflicting columns, and justify a deliberate denormalized cache when you add one.
Index the access paths the API and the Monday board actually use.
Write multi-statement changes inside a transaction with an explicit commit or rollback.
Use parameterized statements from Node, including ANY($1) lists, and keep identifiers on an allow-list.
Grant the application a role that can only touch the tables and columns it needs.
Prevent cross-tenant reads by putting organization_id in the predicate, with row-level security as a later hardening step.
Store sparse AI metadata in jsonb without replacing relational keys.
Read a basic EXPLAIN plan well enough to see a sequential scan you did not expect.
Leave Module 1 with a schema Module 2 can extend when models, tokens, and embeddings arrive.
Prerequisites
Lessons 9 and 10: a Node pool, bound parameters, and the enrollment and progress resources. /learn/nodejs is the process context.
SQL comfort with SELECT, INSERT, UPDATE, and JOIN. /learn/postgresql is the companion primer for the engine: types, indexes, and administration that this lesson applies to the learning platform.
You can run PostgreSQL locally or in a disposable container and drop a database. Use a current supported major version and confirm syntax in the PostgreSQL docs for that version.
You understand that the client is untrusted. Schema design does not replace authorization; it makes the remaining mistakes smaller.
If your tables are created by an ORM "sync" against production, stop that practice before you add constraints. Migrations are the change path.
Detailed Core Concepts
Why a relational model exists here
The platform's questions are relational. Which learners in this organization are enrolled in this course? Which lesson progress rows belong to that enrollment? Who may see the row? Those questions want keys, joins, and constraints that stay true under concurrency. A document blob per learner can store the same facts and still allow two active enrollments, a progress record for a course that was deleted, and a completion flag that disagrees with the lessons. PostgreSQL can store documents in jsonb when the shape is sparse. The facts you join, authorize, and bill on stay in columns.
A table is a set of rows of one type. A primary key identifies a row inside the table. A foreign key says a value must exist in another table. A unique constraint says a combination appears at most once. A check constraint limits the domain, such as percent complete between 0 and 100. Together they are the part of the product that remains enforced when a new route forgets a rule.
Surrogate keys and natural keys
enrollments.id is a UUID the API puts in URLs. It is a surrogate: it identifies the row and does not change when a course slug changes. The natural rule "one active enrollment per learner per course" is a unique constraint, not the primary key. Using email as a primary key fails when a learner changes email and when two identity providers disagree about casing. Store email as a column with a unique index on a normalized form if the product requires unique emails, and keep learners.id as the key other tables reference.
UUIDs avoid central allocation and leak less sequence information than serial integers. They are larger indexes. Either is acceptable if you choose deliberately. This course uses UUIDs generated in the database with gen_random_uuid() so clients cannot mint another learner's id by guessing a small integer. Authorization still filters by the session; unguessable ids are not authorization.
Normalization, stated as bugs you refuse
First normal form: a cell holds one value. A lesson_slugs text column packed with commas cannot be foreign-keyed and breaks as soon as a slug contains a comma. Use lesson_progress rows.
Second and third normal form, in practical terms: facts about a course live on courses, not copied onto every progress row. If the course title changes, one update fixes it. Copying title onto progress "for speed" creates stale titles on the Monday board. If a report is too slow, add an index or a deliberate rollup table you refresh, and name it as a cache with a refresh rule.
Denormalize when you have measured a hot path and you accept a refresh strategy. Do not denormalize in the first migration because a diagram looked flatter.
Tenancy
TechLearningPro sells to organizations. Almost every learner-scoped row needs a path to organization_id. Put organization_id on learners and on enrollments if queries should not have to join through three tables to enforce tenancy. The duplicate must be checked: a trigger or a composite foreign key can require that enrollments.organization_id matches the learner's organization. The application predicate uses the organization from the session, not from the query string.
Row Level Security (RLS) can force the predicate inside PostgreSQL even when a handler forgets it. It is worth enabling when you are ready to set session variables on every connection checkout and test every role, including migrations and admin jobs. Lesson 49 of this course covers multi-tenant isolation in product architecture. This lesson gets the keys right and writes the predicate in SQL. RLS is the hardening step, not an excuse to skip the column.
Transactions and isolation
A transaction groups statements so they commit together or not at all. Creating an enrollment and the empty progress rows for required lessons belongs in one transaction. If the process crashes after the enrollment insert and before the progress inserts, the learner must not see a half-built course. BEGIN, work, COMMIT, or ROLLBACK on failure. In pg, take a client from the pool, run the transaction, and release() in finally.
PostgreSQL's default isolation is Read Committed. Each statement sees rows committed before that statement started. It does not automatically prevent two transactions from inserting the same logical enrollment; the unique constraint does. Repeatable Read and Serializable isolate broader anomalies and can raise serialization failures you must retry. Use them when a read-modify-write cannot be expressed as a single constrained write. Do not sprinkle SERIALIZABLE on every route and then ignore the error.
SELECT ... FOR UPDATE locks rows you intend to change. It is appropriate for a narrow state transition, such as withdrawing an enrollment only if it is active, when a single conditional UPDATE ... WHERE status = 'active' is not enough. Holding that lock while calling a model provider will stall other writers. Keep locks short.
Indexes
An index speeds a predicate, a join, or an order by using extra storage and extra cost on writes. Start with indexes that match the API:
Primary keys are indexed.
Unique (learner_id, course_id) on enrollments supports the idempotent create and the lookup "is this learner already enrolled?"
(enrollment_id, lesson_slug) unique on progress supports the PUT.
(organization_id, created_at DESC, id) supports an instructor list with cursor pagination.
A query that filters organization_id and then sorts by created_at wants those columns in one index if the table is large. A query that applies a function to a column, such as lower(email), needs an expression index on that function or it will not use a plain email index. Confirm with EXPLAIN (ANALYZE, BUFFERS) on realistic data. A plan from an empty laptop database will cheerfully sequential-scan and teach the wrong lesson. This course does not invent millisecond claims.
jsonb for sparse AI metadata
Prompt versions, token counts, and provider response ids are real columns if you filter or bill on them. A small jsonb column is appropriate for a provider payload you must retain for debugging and do not join on. Constrain its size in the application. Do not store the entire lesson body, secrets, or another learner's data inside it. Avoid using jsonb as a junk drawer that hides a missing table: if you query "all jobs for this enrollment," that is a summary_jobs table with a foreign key.
Roles and privileges
Create app_rw for the API. Grant SELECT, INSERT, UPDATE on the specific tables. Grant DELETE only where the product withdraws rows; many withdrawals are status changes, not deletes. Do not grant app_rw the ability to create roles, read pg_authid, or bypass RLS later. Run migrations as a different role, migrator, that is not the runtime connection string. The Node DATABASE_URL uses app_rw. An operator URL uses an admin role and is not shipped in the app image.
statement_timeout and idle_in_transaction_session_timeout on app_rw cancel runaway queries and transactions that forgot to commit. Those settings are part of the model because a bad query is a production behavior, not only a code review comment.
What the model deliberately does not do
It does not call a language model. It does not embed lesson text. It does not decide authorization by reading a prompt. When Module 2 adds generation, a summary_jobs row will reference enrollment_id and store status as a checked enum: queued, running, succeeded, failed. The model output is data. The foreign key is the rule that the job belongs to an enrollment the caller could already see.
Architecture and Design Diagrams
erDiagram
organizations ||--o{ learners : has
organizations ||--o{ enrollments : scopes
learners ||--o{ enrollments : owns
courses ||--o{ enrollments : offers
enrollments ||--o{ lesson_progress : tracks
courses ||--o{ lessons : contains
organizations {
uuid id PK
text slug
}
learners {
uuid id PK
uuid organization_id FK
text email
}
courses {
uuid id PK
text slug
}
lessons {
uuid id PK
uuid course_id FK
text slug
}
enrollments {
uuid id PK
uuid organization_id FK
uuid learner_id FK
uuid course_id FK
text status
}
lesson_progress {
uuid id PK
uuid enrollment_id FK
text lesson_slug
int percent_complete
boolean completed
}
flowchart TB
subgraph app [Node API as app_rw]
Handler[Authorized handler]
Txn[Short transaction]
end
subgraph pg [PostgreSQL]
Cons[Constraints and FKs]
Idx[Indexes]
Rows[(Tables)]
end
Handler --> Txn
Txn -->|"parameters $1..$n"| Cons
Cons --> Idx
Idx --> Rows
text
session organization_id and learner_id
-> transaction begin
-> INSERT enrollment (unique learner+course)
-> INSERT progress rows for required lessons
-> commit
-> release connection
on any error -> rollback -> release
The trust boundary stays in Node for "who is this session?" and moves into PostgreSQL for "can this row exist?" Both are required. A constraint cannot know which HTTP caller you intended. A handler check cannot stop a second connection from inserting a duplicate if the unique index is missing.
Technical Explanation
Core tables
Types below match a current PostgreSQL that provides gen_random_uuid(). If you are on a version that still needs pgcrypto for that function, enable the extension in a migration and record why. Confirm the function in your version's docs.
ON enrollments (organization_id, created_at DESC, id);
UNIQUE (learner_id, course_id) encodes the product rule from the API lesson. If withdrawn learners may re-enroll, the unique rule is more precise as a partial unique index on active rows:
sql
CREATEUNIQUEINDEX enrollments_one_active
ON enrollments (learner_id, course_id)
WHEREstatus='active';
Pick one rule and document it. A table unique constraint and a partial index that disagree will confuse the 23505 handler. The partial index is the better product rule when re-enrollment is real. The examples in lesson 9 and 10 assumed one row forever; if you adopt the partial index, update the API conflict text to say "an active enrollment already exists."
Email uniqueness inside an organization uses a pair of columns so two customers may legally employ the same address string only if your product says so. Many B2B platforms unique email globally. Write the rule in the migration comment either way.
Transaction from Node
ts
// src/enroll.ts
importtype{ Pool }from"pg";
typeEnrollInput={
organizationId:string;
learnerId:string;
courseId:string;
lessonSlugs:string[];
};
exportasyncfunctionenrollLearner(pool: Pool, input: EnrollInput){
const client =await pool.connect();
try{
await client.query("BEGIN");
const inserted =await client.query(
`INSERT INTO enrollments (organization_id, learner_id, course_id, status)
`INSERT INTO lesson_progress (enrollment_id, lesson_slug, percent_complete)
SELECT $1, slug, 0
FROM unnest($2::text[]) AS slug`,
[enrollmentId, input.lessonSlugs],
);
await client.query("COMMIT");
return{ enrollmentId };
}catch(err){
await client.query("ROLLBACK");
throw err;
}finally{
client.release();
}
}
The insert selects the learner only when organization_id matches the session's organization. A client that passes another organization's learner id inserts nothing. Lesson slugs travel as a bound text array, not as concatenated values. If the slug list is empty, decide whether that is a 400 before you open the transaction. ROLLBACK after a failed BEGIN can itself throw if the connection is dead; in a production helper, guard rollback and always release().
Map err.code === "23505" to the API's already_enrolled conflict, as in lesson 9. Map foreign-key violations (23503) to a 400-level "unknown course" only if that message does not help a caller enumerate courses they should not see. Often a 404 on the course lookup before the transaction is clearer, with the foreign key as a backstop.
Authorization predicate on read
sql
SELECT e.id, c.slug AS course_slug, e.status
FROM enrollments e
JOIN courses c ON c.id = e.course_id
WHERE e.id = $1
AND e.learner_id = $2
AND e.organization_id = $3;
Three parameters: the URL id, the session learner, and the session organization. Dropping any one of them is a review failure. Instructors use a different statement that checks a membership table:
sql
SELECT1
FROM memberships m
WHERE m.learner_id = $1
AND m.organization_id = $2
AND m.role ='instructor';
memberships is the table that makes "instructor" a stored fact rather than a string in a token you never recheck. Token roles can be a cache of this table. The table remains the source you can revoke.
Reading a plan without folklore
sql
EXPLAIN(ANALYZE, BUFFERS)
SELECT id
FROM enrollments
WHERE organization_id = $1
ORDERBY created_at DESC, id DESC
LIMIT50;
Run this on a staging copy with a realistic number of rows, not on an empty schema. Look for a sequential scan on a large table, a sort that spills, or a row estimate wildly different from the actual rows. Those are reasons to revisit the index or to run ANALYZE. They are not reasons to disable sequential scans globally. Put the redacted plan in the design note. Do not paste production row samples that include emails.
Migrations
Each change is a file applied in order: 001_core.sql, 002_enrollments_partial_unique.sql. Migrations run as migrator before the new Node version starts, or as a release step you can roll forward. Editing an already-applied migration is how environments diverge. Destructive changes—dropping a column the old app still reads—happen after the new app is deployed and the compatibility window closes, the same way API versions overlap.
Seed data for local courses can live in a seed script. It is not a migration that runs in production unless you intend those exact rows in production.
Enterprise Real-World Scenarios
Scenario A: Duplicate enrollments under retry
Two requests inserted two rows because uniqueness lived in a if (!exists) check in Node. Both checks passed before either insert committed.
What good looks like. A unique index closes the race. The handler translates 23505. The API documents the conflict. Application checks are optional UX, not the rule.
Scenario B: Monday board leaked another tenant
The report joined enrollments to learners and forgot organization_id after a refactor. The CSV included another customer's completion counts.
What good looks like. The board query takes organization_id from the instructor membership, as a bound parameter. A test fixture with two organizations fails the build if row counts mix. RLS is scheduled as defense in depth, with a test that uses a role which cannot BYPASSRLS.
Scenario C: Progress percent as text
"100%" and "100" and "complete" all appeared. The average completion query threw or, worse, ignored rows.
What good looks like.int plus a check constraint. The API schema only accepts integers. Bad historical rows are cleaned in a migration before the constraint is validated.
Scenario D: Email as primary key during a rename
A learner changed email. Progress updates broke because child rows stored the email. Support updated one table and missed another.
What good looks like.learners.id is the foreign key. Email is mutable. Child tables do not store it. Audit history, if required, is an append-only table, not a reused primary key.
Scenario E: AI payload replaced the schema
A prototype stored the whole enrollment as jsonb so the model could "add fields." Billing could not find a reliable status. A prompt injection in a notes field was later selected into a dashboard query via string concatenation.
What good looks like. Status, ids, and organization remain typed columns. jsonb holds only the provider blob, size-limited. Queries against it are still parameterized. The model never supplies table or column names.
Use surrogate ids in URLs and natural unique keys for business rules.
Keep email, slug, and title off the primary-key path when they can change.
Put organization_id on tables you authorize by tenant, and compare it to the session.
Bind every value from HTTP in $1 style parameters, including arrays.
Allow-list any dynamic identifier. Constraints do not stop ORDER BY injection.
Open transactions only around the writes that must commit together, then release the client.
Map 23505 and 23503 to stable API codes. Do not send PostgreSQL messages to clients.
Index the predicates and sort orders you run. Revisit with EXPLAIN on realistic data.
Grant app_rw table privileges only. Migrate with a different role.
Set statement and idle-in-transaction timeouts on the application role.
Ship schema changes as ordered migrations. Do not hand-edit production.
Prefer status transitions to hard deletes when history matters.
Use partial unique indexes when the rule applies only to active rows, and document the predicate.
Keep jsonb for sparse payloads you do not join. Promote fields to columns when you filter on them.
Refuse to store secrets, raw session tokens, or full lesson bodies in progress tables.
Test with two organizations and two learners. Assert row counts and error codes.
Validate constraints on cleaned data. A constraint that fails mid-deploy needs a backfill plan.
Comment the migration with the product rule in a sentence a reviewer can challenge.
Design summary_jobs later with a foreign key to enrollments and a checked status, so AI does not invent a second source of truth for completion.
Separate the Monday board's aggregate query from the interactive PUT path so a report cannot take row locks on hot progress rows.
Redact emails and lesson notes from slow-query logs if the statement text might include them through a mistake; parameters should not be logged at info.
Common Mistakes and Anti-Patterns
Check-then-insert without a unique index. Symptom: duplicate enrollments under concurrency. Cause: the race is invisible in a single-threaded test. Fix: unique or partial unique index; test with parallel inserts.
Email or slug as a foreign key. Symptom: broken joins after a rename. Cause: confusing a label with an identity. Fix: UUIDs as references; labels on the parent only.
Missing organization_id predicate. Symptom: cross-tenant report. Cause: join looked "complete" in code review. Fix: predicate plus a two-tenant test. Plan RLS as a backstop.
String-built SQL beside a careful schema. Symptom: injection despite nice constraints. Cause: one export route. Fix: parameters everywhere; constraints are not a sanitizer.
jsonb junk drawer. Symptom: unqueryable product facts and weak validation. Cause: speed of prototyping. Fix: columns for facts you authorize and bill; jsonb for the residue.
Long transactions. Symptom: locks, pool exhaustion, idle-in-transaction sessions. Cause: work or a model call inside BEGIN. Fix: shorten the transaction; set idle_in_transaction_session_timeout.
GRANT ALL to the app role. Symptom: the app can drop tables or read other schemas after a bug. Cause: convenience in local setup copied forward. Fix: explicit DML grants; separate migrator.
Editing applied migrations. Symptom: "works on my machine" schema drift. Cause: alter-in-place habit. Fix: new migration files only.
Indexes for every column. Symptom: slow writes, large storage, no read improvement. Cause: folklore. Fix: index real predicates; verify with EXPLAIN.
Using an empty-database EXPLAIN as proof. Symptom: production sequential scans you did not see locally. Cause: tiny tables always scan. Fix: stage with volume or accept uncertainty and revisit before launch.
Storing percent complete as text or as both a boolean and a conflicting percent. Symptom: board totals disagree with the player. Cause: two sources of truth. Fix: one representation and a check. Derive "course complete" from progress rows or update it in the same transaction with a stated rule.
Logging full rows. Symptom: personal data in logs. Cause: console.log(rows). Fix: log ids and counts.
Troubleshooting and Design Review
23505 on a path the UI called create. Confirm which constraint fired (err.constraint in server logs, not in the client). If it is the active-enrollment index, return the documented conflict and the existing id if the caller owns it. If it is an unexpected key, you have a product rule you did not design.
23503 on progress insert. The lesson slug or enrollment id does not match a parent. Decide whether the API should have rejected the slug before the write. Backfills can fail the same way when lessons are renamed; rename with a migration that updates lesson_progress.lesson_slug in the same transaction as lessons.slug, or stop embedding slug and reference lesson_id.
Slow instructor list. Capture EXPLAIN (ANALYZE, BUFFERS) on staging. Check that organization_id is selective and indexed with the sort columns. Watch for a filter on a non-indexed expression. Add an index in a new migration; do not CREATE INDEX by hand only on one server unless it is CONCURRENTLY and then codified.
Idle in transaction sessions pile up. Find the code path that BEGINs and waits. The Node finally { release() } might be missing, or a transaction might span a remote call. The role timeout is the safety net; the fix is the code.
Two environments disagree. Compare migration history tables, not a verbal description. Someone edited an applied file or ran a hot fix. Restore the discipline of forward migrations.
Design review checklist
Which product rules are constraints, and which exist only in a handler?
Does every API write include learner_id or a proven instructor membership, plus organization_id?
Are unique conflicts mapped to API codes?
Is app_rw forbidden from DDL and from other tenants' rows by predicate and privilege?
Where will AI job rows attach, and which column remains the source of truth for completion?
Do migrations roll forward, with a backfill plan before new constraints validate?
What does a two-organization test assert?
Knowledge Check
1. What problem does relational modeling solve for TechLearningPro?
It makes enrollment uniqueness, progress bounds, and parent-child existence true in the database, including under retries and concurrent requests. Handlers and OpenAPI document the rules. PostgreSQL enforces the ones you declare as constraints. Reports and future AI jobs then join stable keys instead of parsing blobs.
2. When would you choose a partial unique index, jsonb, or a stricter isolation level?
Use a partial unique index when only active enrollments must be unique and withdrawn rows may repeat the same learner and course. Use jsonb for a sparse provider payload you retain and rarely filter. Use SERIALIZABLE or an explicit lock when a read-modify-write can do the wrong thing under Read Committed and you cannot express the rule as one constrained write. For the common enroll path, Read Committed plus a unique index is the right pair.
3. Which identity and trust boundaries matter?
The session supplies learner_id and organization_id. Those values are parameters, not SQL fragments. The app_rw role can only change granted tables. A client-supplied organization id is untrusted and must match the session before it is written. A model, later, may propose a lesson slug; the foreign key or the join to lessons decides whether that slug exists. Logs and exports are a data boundary: a query that returns another tenant's rows is already an incident.
4. What fails, and how should the system respond?
Unique violations roll back and become already_enrolled. Foreign-key violations roll back and become a client error you have mapped. Deadlocks and serialization failures roll back and may be retried if the transaction is short and idempotent. Timeouts cancel the statement and return 503. A missing organization predicate is a defect, not a runtime error; tests must catch it because PostgreSQL will happily return the extra rows.
5. How do you test quality, security, and performance?
Apply migrations on a disposable database. Assert the second active enrollment fails. Assert percent 120 fails the check. Assert a second organization is invisible to the first caller's query. Assert a quote-laden slug is stored as data or rejected by a format check, and that the statement text in code does not concatenate it. Run EXPLAIN on the instructor list with enough rows to make a bad plan visible. Confirm app_rw cannot DROP TABLE. None of these tests need production data or a real password in the repository.
Interview Questions and Answers
Q1. Why not store each learner's progress as one JSON document?
You can, and you will struggle to enforce one active enrollment, transactional seeding of lesson rows, concurrent PUTs on different lessons, and tenant-scoped SQL that stays indexed. Documents fit sparse, write-one-read-whole aggregates. Progress is many rows updated independently and joined to courses. PostgreSQL still lets you keep a jsonb payload beside the relational keys when a provider response is truly unstructured.
Q2. What does a unique constraint give you that application code does not?
It is enforced for every connection, including a second API instance and a one-off script, and it closes the race between two check-then-insert transactions. Application code still maps the error to a kind response. The constraint is the rule. The handler is the translation.
Q3. Primary key versus unique key on enrollments?
The primary key identifies the row (id) for URLs and foreign keys from progress. The unique key on (learner_id, course_id) or the partial index on active rows enforces the business rule. One index does not replace the other unless you are willing to put the natural key in every URL and foreign key, which couples you to a key that may not stay singular across re-enrollment.
Q4. How do you stop SQL injection if the schema is well constrained?
Constraints limit values that land in columns. They do not parse the statement. Injection changes the statement. Keep SQL text constant and send values as parameters through pg. Allow-list sort columns and table names. A check constraint on status will not save a query that concatenates status into the SQL string before the check ever runs.
Q5. What is the practical meaning of Read Committed here?
Each statement sees committed data as of its start. Two concurrent inserts can both believe they are first unless a unique index aborts one of them. A single UPDATE ... WHERE status = 'active' is atomic for that row. A multi-statement "read the row in application code, decide, then write" is not, unless you lock or raise isolation and handle retries.
Q6. How should the application connect?
As app_rw, through a pool, with a connection string supplied from the environment and never committed. Privileges are DML on known tables. Migrations use migrator. Timeouts live on the role. The pool's max fits inside max_connections once you multiply by process count, as lesson 9 described.
Q7. When is an index the wrong fix?
When the query is rare and the table is small, when the predicate is not selective, when the real bug is N+1 round trips from the API, or when the index duplicates one you already have. EXPLAIN on realistic data tells you. Adding indexes slows writes and vacuums. The Monday board might need a rollup if it aggregates the entire history every page view; an index alone may not make a bad access pattern cheap.
Q8. How would you model course completion?
Prefer deriving it: an enrollment is complete when every required lesson has completed = true, computed in SQL or maintained by a trigger or by the same transaction that writes the last progress row. If you store enrollments.status = 'completed', update it in that same transaction and add a test where the status and the rows disagree. Two writable sources without a transaction will drift.
Q9. What is row-level security for, if queries already filter?
It enforces a tenant predicate even when a new report forgets the WHERE clause, as long as the role cannot bypass RLS and the session variable is set on every checkout. It is defense in depth. It is also easy to misconfigure into "no rows" or "all rows." Adopt it with tests. Do not treat it as a substitute for an explicit predicate in the main handlers, which remain easier to read.
Q10. How do embeddings fit this model later?
As a child table, for example lesson_chunks, with a foreign key to lessons, an organization id, and a vector column when you enable pgvector. The chunk does not replace lessons. Retrieval filters by the organizations the caller may see before nearest-neighbor search. That design is lesson 27's neighborhood. The keys you add now are what make that filter possible.
Q11. What belongs in a migration review?
The product rule in prose, the constraint or index that encodes it, the backfill for existing rows, the privileges granted to app_rw, the API error mapping, and the rollback or forward-fix plan. Reviewers should reject a migration that drops a column the running app still selects, and a migration that copies production emails into a seed file.
Q12. Why can SELECT * hurt a relational design?
It couples clients to physical column order and leaks new columns the day you add them: internal notes, email, organization ids you did not mean to put on that representation. The model can be correct and the API still over-exposes it. List columns in the queries that feed HTTP responses.
Hands-On Exercises
Lab note. Use a disposable PostgreSQL. Apply SQL as migrator and connect the app as app_rw. Keep passwords in an uncommitted env file. Do not load real learner data.
Exercise 1: Enrollment schema and race
Problem. Model organizations, learners, courses, enrollments, and lesson progress so two concurrent active enrollments cannot exist, progress percent must be in range, and a learner from another organization cannot be enrolled by binding the wrong id.
Tasks.
Write a forward migration with the tables, checks, foreign keys, and a partial unique index on active enrollments.
Create app_rw with DML grants only. Put the URL in a gitignored env file. Commit a sample URL without a password.
Implement enrollLearner as a short transaction with parameterized SQL, including the organization check via INSERT ... SELECT.
Tests on a disposable database: second active enrollment fails; percent 120 fails; a learner in organization B is not enrolled when the session organization is A; two parallel inserts yield one success and one unique violation.
Run EXPLAIN on an organization-scoped enrollment list and paste the plan node types into your notes, with a sentence on whether you trust the plan given your row count.
Cleanup: drop the disposable database and confirm no credentials are in git.
Deliverables. Migration, Node transaction, tests, short EXPLAIN note, privilege list for app_rw.
Challenge. Add a summary_jobs table with a foreign key to enrollments, a status check constraint, and organization_id. Do not call a model. Insert one job in the same style of parameterized SQL. Explain which column remains authoritative for course completion, and which fields you would refuse to accept from a model response (organization_id, learner_id, status of the enrollment).
Lesson Summary
PostgreSQL holds TechLearningPro's product rules in keys, foreign keys, uniqueness, and checks. The Node API still authenticates and authorizes, and it sends parameters rather than concatenated SQL. Transactions make enrollment and initial progress atomic. Indexes exist for the paths you can defend with a plan. Privileges keep the runtime role smaller than a migration role. Sparse AI payloads can sit in jsonb later; they do not replace the enrollment row as the source of truth.
This lesson closes Full-Stack Engineering Foundations. You have a UI path, a Node boundary, an HTTP contract, and a relational model. /learn/postgresql continues the engine details when you need types, locking, and operations in more depth. /learn/nodejs remains the runtime companion. Next, the course changes subject from deterministic product data to models: Generative AI, LLMs and Transformer Fundamentals. You will learn what a language model is actually doing, where it is uncertain, and how those properties must sit beside the schema you just made enforceable—jobs, foreign keys, and authorization included—rather than in place of it.
Further Reading
PostgreSQL documentation for constraints, transactions, indexes, EXPLAIN, roles, and row-level security on the major version you run.
Later in this course: multi-tenant isolation, and vector columns on top of the keys you designed here. Check pgvector's current documentation before you enable it; do not treat this lesson as that setup guide.
Ready to mark this lesson complete?Track your journey across the entire course.