Topic 060 / Core
SQL and relational databases
Chapter 5.1 · Data Modeling and Relational Databases
What and why
The relational model stores data as tables of rows with typed columns and lets a client state what result it wants in a declarative language — SQL — while the query engine (→ 66) decides how to get it. Competent SQL (joins, aggregation, subqueries, window functions) is the baseline skill this whole part assumes. Builds on: → 59 (data modeling and entity relationships).
Diagram
| Join type | Keeps |
|---|---|
| INNER JOIN | rows that match on both sides |
| LEFT JOIN | all left rows, matched right columns or NULL |
| FULL JOIN | all rows from both sides, unmatched columns NULL |
How it works
Practical example
Total spend per customer in the last 30 days, with a running rank:
SELECT c.id, c.email,
SUM(oi.quantity * p.price_cents) AS spend_cents,
RANK() OVER (ORDER BY SUM(oi.quantity * p.price_cents) DESC) AS spend_rank
FROM customer c
JOIN "order" o ON o.customer_id = c.id
JOIN order_item oi ON oi.order_id = o.id
JOIN product p ON p.id = oi.product_id
WHERE o.created_at > now() - INTERVAL '30 days'
GROUP BY c.id, c.email;
One join-aggregate-window query replaces what would otherwise be several round trips and in-application loops.
When to use it
- Use when: data is structured, relationships and ad hoc queries matter, and transactional guarantees (→ 69) are needed.
- Avoid when: the data is deeply nested, schema-variable, or accessed only by a single key with no relational queries — consider NoSQL (→ 61).
- Failure scenarios: N+1 queries (looping in application code instead of one join);
writing application logic that re-implements what a single
GROUP BYwould do. - Simpler alternative: an ORM for routine CRUD — but know the SQL it generates well enough to fix it when it's wrong.
Practice
(20–30 min, lab Postgres). Against the schema from topic 59, seed a few
rows and write three queries: an inner join across three tables, an aggregate with
GROUP BY, and a window function (RANK() or ROW_NUMBER()). Done when each returns the
expected rows without an application-side loop.
Key takeaway
SQL is declarative — state the result, let the engine find the plan. Done when you can: write a multi-table join, an aggregate, and a window function from scratch. Used next in → 64 (indexing what these queries filter and join on), → 66 (reading the plan), → 70 (transactions around writes).
References
None — this topic makes no external claims.
Source directory