Skip to content

Lesson 29 of 29Beyond relational, and interviews

Wrap-Up: SQL & Databases

Tie the whole SQL track together: one realistic feature taken from a schema you did not write to a migration, an index and a safe concurrent write in production, a mixed review, and where to go next.

14 min read0/6 questions

You started this course with one question from a product manager and a handful of tables you had never seen. Since then you have learned to query those tables, join and aggregate them, design new ones, make them fast, keep them correct when many requests hit them at once, and run Postgres in production. On the job, none of that arrives one lesson at a time. This lesson lines the units up once more and then uses them together on one feature.

The path you took

The SQL & Databases course, unit by unit
  1. Unit 1

    Querying basics

    Tables, SELECT, NULL, column types and safe writes gave you the vocabulary every later query is built from.

  2. Unit 2

    Joining and aggregating

    Joins, GROUP BY, CTEs, recursion and window functions let you answer real business questions across several tables.

  3. Unit 3

    Designing schemas

    Modelling, normal forms and constraints taught you to build tables that keep bad data out, which the performance unit then has to make fast.

  4. Unit 4

    Indexes and query performance

    B-trees, composite indexes, sargable predicates, EXPLAIN and scalable query patterns showed you why a query is slow and how to prove the fix.

  5. Unit 5

    Transactions and concurrency

    ACID, isolation levels and locks made your writes correct when two requests touch the same row at the same moment.

  6. Unit 6

    Postgres in production

    Zero-downtime migrations, JSON, search, pooling, backups and replicas covered what changes once real users depend on the database.

  7. Unit 7

    Beyond relational, and interviews

    NoSQL families showed where Postgres stops being the answer, and the interview lesson replayed the whole course as classic questions.

How it fits together

The ticket: "Marketing is launching a loyalty programme. Rank customers by what they have spent in each city, give the top spender in each city the Gold tier, show the tier on the admin customer list, and award one point per pound when an order ships." It sounds like one query. It is really the whole course, in the order you would meet it.

Reading the schema. Before writing anything, you list the tables and their foreign keys, as in Tables, Rows and the Relational Model, and sketch how customers, orders and order_items connect. Money is stored as integer cents, the choice Choosing Column Types argued for, so spend is a sum of quantity * unit_price_cents, never a float.

Writing the ranking. Spend per customer needs a join and an aggregate. Customers with no orders still need a row, so it is a LEFT JOIN, and the "not cancelled" condition has to live in the ON clause. Put it in WHERE and you have turned the LEFT JOIN back into an inner one, the trap from Joins of Every Kind. You also group by customer before ranking, so the line items do not fan out the totals, which Aggregation, GROUP BY and HAVING warned about. One customer has no city, and NULL cities would group together as their own unlabelled bucket, so you label them with COALESCE from NULL and Three-Valued Logic. The spend step becomes a named CTE (Subqueries, CTEs and Set Operations), and the ranking is a window function from Window Functions, the same top-N-per-group pattern you drilled in SQL Interview Questions.

Python
from shopdb import connect, showdb = connect()show(db, """WITH spend AS ( SELECT c.id, c.name, COALESCE(c.city, 'Unknown') AS city, COALESCE(sum(i.quantity * i.unit_price_cents), 0) AS spent_cents FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.status <> 'cancelled' LEFT JOIN order_items i ON i.order_id = o.id GROUP BY c.id, c.name, c.city)SELECT city, name, spent_cents, RANK() OVER (PARTITION BY city ORDER BY spent_cents DESC) AS city_rankFROM spendORDER BY city, city_rank""")
Output
Press Run (⌘ Enter) to see what happens.

All eight customers come back. Alan Turing's only order was cancelled, so he shows 0 and ranks second in London instead of disappearing. Move the status check into WHERE and only five rows survive. Using RANK rather than ROW_NUMBER is a product decision too: two customers tied at the top of a city would both get Gold.

Designing the new tables. Tier is a fact about a customer, so it becomes a column with a CHECK limiting it to known values. Points are different. Marketing will ask "why do I have 340 points?", so you store a ledger of awards, one row per shipped order, rather than a single number you overwrite. That is the history question from Modelling Data: Entities and Relationships. The balance is derivable from the ledger, so storing it on the customer as well is a deliberate denormalisation, the trade-off from Normal Forms and When to Denormalise. A UNIQUE constraint on the ledger's order_id and a foreign key to orders come from Constraints: Let the Database Say No. They mean an order can never earn points twice, however buggy the calling code is.

Shipping the schema change. The customers table is busy, so the migration follows Zero-Downtime Migrations: set a lock_timeout, add the column as nullable, deploy code that writes it, then backfill. The backfill updates customers in batches by primary key, with a WHERE clause you checked with a SELECT first and inside a transaction, as Changing Data Safely taught. Only when every row has a value do you add the NOT NULL constraint, using the validate-later steps from the constraints lesson.

Awarding points safely. When an order ships, inserting the ledger row and adding to the balance happen in one transaction, so a crash between them cannot leave the two disagreeing (Transactions and ACID). Two workers may process the same shipment event. The UNIQUE constraint plus ON CONFLICT DO NOTHING makes the second one a no-op, the idempotency idea from the same lesson. The balance update is SET points = points + 120, not "read the balance in Python, add, write it back", because the read-modify-write version loses updates under Read Committed, the anomaly from Isolation Levels and Anomalies. If shipments are queued in a table, workers claim them with FOR UPDATE SKIP LOCKED from Locks, Deadlocks and Safe Concurrency.

Making the admin list fast. The list filters by tier and sorts by spend. On a test copy with real volume it takes two seconds. You read the plan with Reading EXPLAIN and EXPLAIN ANALYZE, see a sequential scan feeding a sort, and add a composite index on (tier, spent_cents, id), ordered equality first and then sort columns, as Composite, Covering and Partial Indexes described. You build it with CREATE INDEX CONCURRENTLY, knowing from How Indexes Work that it also adds a cost to every write. The search box had wrapped lower(email) around an indexed column, which Why the Database Ignored Your Index explains, so it gets an expression index. Pages use keyset pagination instead of OFFSET, from Query Patterns That Scale.

Running it in production. The nightly ranking job is a heavy read, so it runs on a replica. The admin page that shows a tier right after a change reads from the primary, because replicas lag, which Connections, Backups and Replicas covered. Campaign settings that change shape every month go in a jsonb column, while tier stays a real column because you filter and index on it (JSON and JSONB in Postgres). Someone suggests moving points to a key-value store. After NoSQL Families and When to Use Them, you can explain why a ledger that needs transactions and unique constraints belongs in Postgres.

No lesson was used alone. The constraint made the retry safe, the ledger made the backfill rerunnable, and the plan told you which index to build. That is what database work looks like.

Check yourself

Predict the outputPython

Customers 6, 7 and 8 live in NULL, Geneva and Boston. What does this print?

print(db.execute("""
SELECT count(*) FROM customers
WHERE city NOT IN (SELECT city FROM customers WHERE id > 5)
""").fetchone())
Need a nudge? Hints walk you through it.
Predict the outputPython

Ada Lovelace has three orders with 2, 1 and 2 line items. What does this print?

print(db.execute("""
SELECT count(*), count(DISTINCT o.id)
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.customer_id = 1
""").fetchone())
Need a nudge? Hints walk you through it.
Quick check
The admin list runs WHERE tier = 'gold' ORDER BY spent_cents DESC, id DESC LIMIT 20. Which single index serves it best?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/6 matched

Match each problem to the tool from the course that solves it.

Choose an item, then its match on the other side.
Put it in order5 steps

Order the steps to add a required loyalty_tier column to a busy customers table without an outage.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Two workers award points for different orders by the same customer at the same moment. Each reads the balance, adds in Python and writes the result back. Under Read Committed, what can happen?
Need a nudge? A hint rules out a wrong answer.

What you can do now

  • Read an unfamiliar schema and write correct queries across it: joins, aggregates, CTEs, recursive queries and window functions, with NULLs handled on purpose.
  • Solve the common SQL interview problems on a whiteboard and explain the edge cases.
  • Design tables for a feature with sensible types, keys and constraints, and say when you are denormalising and why.
  • Read a Postgres plan, find the bad estimate or missing index, and prove the fix with numbers.
  • Write data changes that are safe under concurrency and safe to retry.
  • Ship a schema change to a busy table without taking the site down.

That is solid working knowledge for a backend or data-adjacent developer. You have not yet tuned a database under real production load, run a failover, or owned an on-call rotation. That comes from doing it, ideally next to someone who has.

Mistakes that still catch people

  • Comparing with NULL. = NULL, <> 'x' dropping NULL rows, and NOT IN against a nullable subquery all return less than you expect. Revisit NULL and Three-Valued Logic.
  • Double-counted totals. Joining two child tables before aggregating inflates every SUM. Revisit Joins of Every Kind and Aggregation, GROUP BY and HAVING.
  • Checking rules only in application code. Two requests race past the check, and a duplicate gets in. Revisit Constraints: Let the Database Say No and Isolation Levels and Anomalies.
  • Guessing at performance. Adding indexes without a plan, or wrapping an indexed column in a function. Revisit Reading EXPLAIN and EXPLAIN ANALYZE and Why the Database Ignored Your Index.
  • Long transactions. Holding a transaction open across an HTTP call keeps locks and blocks migrations. Revisit Transactions and ACID and Locks, Deadlocks and Safe Concurrency.
  • A "quick" migration. An ALTER that waits for a lock and freezes every query behind it. Revisit Zero-Downtime Migrations.

Where to go next

The natural next course is Python Backend. It puts this database behind a FastAPI service, with SQLAlchemy, Alembic migrations, Redis caching and transactions in real request handlers, so every lesson here gets a second, practical outing. Later, System Design builds on replicas, partitioning, caching and the NoSQL trade-offs at the scale of whole systems. If interviews are close, Interview Prep puts the SQL round next to the coding and behavioural rounds.

Real practice matters as much as the next course. If you skipped Project: Product Reviews for the Shop, build it first, then take on its stretch goals:

  • Model and query a dataset you care about. Load a public dataset into Postgres, design the schema yourself, write ten questions you want answered and make the slowest one fast.
  • Read real schemas. Open-source apps such as Mastodon or Discourse ship their migrations. Reading years of schema changes teaches modelling and migration habits fast.
  • Read the official docs. The PostgreSQL manual, especially the chapters on queries, indexes, concurrency control and EXPLAIN, will keep answering questions for years.
Key terms
three-valued logic
SQL's TRUE, FALSE and UNKNOWN, where any comparison with NULL is UNKNOWN and WHERE keeps only TRUE.
fan-out
When a join repeats each parent row once per matching child row, inflating counts and sums computed afterwards.
sargable
A predicate written so an index can be used to find the rows, without a function or cast wrapped around the indexed column.
idempotent
Safe to run more than once with the same effect as running it once, usually enforced with a unique key.
lost update
A concurrency anomaly where two read-modify-write transactions overlap and one change silently overwrites the other.
expand and contract
Changing a schema in backward-compatible steps: add the new shape, migrate code and data, then remove the old shape.
replication lag
The delay before a write on the primary becomes visible on a replica.