Skip to content

Lesson 28 of 29Beyond relational, and interviews

Project: Product Reviews for the Shop

Build product reviews into the shop database end to end: tables with constraints, a migration that can fail safely, reporting queries with joins, aggregates and window functions, an index proved with EXPLAIN QUERY PLAN, and a write path wrapped in a transaction.

17 min read0/5 questions

In this project you build one feature end to end on the shop data. The ticket is short: "Customers who received an order can rate each product in it from 1 to 5 and leave a comment. Show the average and the latest reviews on the product page. Moderators can hide spam. Marketing wants a monthly ratings report."

You will design the tables, migrate, write the reports, index the product page and make the write path safe. Each stage is a runnable block that repeats its own setup, so any stage runs alone. The blocks run SQLite 3.39 in your browser, and connect() from shopdb gives a fresh copy of the shop tables each time. Each stage ends with a note on where Postgres differs.

How a review moves through the feature
Customer: submits a reviewCustomersubmits a reviewadd_review: stage 5add_reviewstage 5reviews: stages 1 and 2reviewsstages 1 and 2products counters: stage 2products countersstage 2Reports and page: stages 3 and 4Reports and pagestages 3 and 4Shoppers and marketing: read the resultsShoppers and marketingread the resultsrating, textINSERTUPDATEjoins, windowsaveragesrows

The app calls one function. It checks that the order is the customer's and has shipped.

1/4

Stage 1: design the tables

Start from the entities, as Modelling Data: Entities and Relationships taught. A review belongs to one customer and one product, and it points at the order it came from. One customer gets one review per product, not one per order. Moderators hide reviews rather than delete them, so status is a column, the soft delete idea from Changing Data Safely.

Then turn each rule into a constraint. Constraints: Let the Database Say No argued that an application check is never enough, because the next script or admin console skips it:

  • Rating from 1 to 5: a CHECK.
  • One review per customer per product: a UNIQUE (customer_id, product_id).
  • Only for something in that order: a composite foreign key to order_items (order_id, product_id). That pair is the primary key of order_items, so it is a valid target.
  • No empty or huge comments: a CHECK on length(body).
  • A known status: a CHECK ... IN.

Types come from Choosing Column Types: an integer rating and ISO 8601 date text. The table is STRICT, a SQLite 3.37 feature, so a value of the wrong type is refused instead of being stored the way SQLite's loose type affinity would normally allow.

Pythonreviews_schema.py
import sqlite3from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE reviews ( id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), customer_id INTEGER NOT NULL REFERENCES customers(id), order_id INTEGER NOT NULL, rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5), body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('published', 'hidden')), created_at TEXT NOT NULL, UNIQUE (customer_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id)) STRICT;""") def try_insert(label, row): try: db.execute("""INSERT INTO reviews (product_id, customer_id, order_id, rating, body, created_at) VALUES (?, ?, ?, ?, ?, ?)""", row) print(f"{label:<22} ok") except sqlite3.IntegrityError as e: print(f"{label:<22} refused: {e}") try_insert("good review", (1, 1, 1, 5, "Fast and quiet.", "2025-02-10"))try_insert("rating of 6", (3, 1, 1, 6, "Best hub ever!!", "2025-02-11"))try_insert("rating as text", (3, 1, 1, "five", "Great.", "2025-02-11"))try_insert("half a star", (3, 1, 1, 4.5, "Nearly perfect.", "2025-02-11"))try_insert("empty body", (3, 1, 1, 4, "", "2025-02-11"))try_insert("second review", (1, 1, 1, 1, "Changed my mind.", "2025-03-01"))try_insert("never bought it", (6, 1, 1, 5, "Sounds great.", "2025-02-11"))try: db.execute("UPDATE reviews SET status = 'deleted' WHERE id = 1")except sqlite3.IntegrityError as e: print(f"{'status of deleted':<22} refused: {e}") show(db, "SELECT id, product_id, customer_id, rating, body, status FROM reviews")
Output
Press Run (⌘ Enter) to see what happens.

Every bad row is refused with a message that names the rule. The one rule the schema cannot express is "the order is yours and has shipped", so that check goes in the write path in stage 5.

What to check: all seven bad inserts and updates are refused, and the table holds one review. Then delete the word STRICT and run again. The text 'five' is still refused, but by the CHECK, and the rating 4.5 now goes in, because a loose INTEGER column happily stores a REAL that passes BETWEEN 1 AND 5. That is why the keyword is there.

Match the pairs0/5 matched

Match each business rule to the database feature that enforces it.

Choose an item, then its match on the other side.

Stage 2: migrate safely

The table ships as a migration. A runner must know which migrations have run, apply each one completely or not at all, and do nothing when run twice.

SQLite has a free version counter, PRAGMA user_version, and its DDL is transactional, so the change and the version bump sit in one transaction, the all-or-nothing idea from Transactions and ACID. Setting isolation_level = None stops Python opening or committing transactions behind your back.

The second migration adds rating_count and rating_sum to products, so the product page does not recompute averages on every view. That is a deliberate denormalisation from Normal Forms and When to Denormalise. Storing the sum rather than the average keeps it exact and easy to update. Reviews already exist by then, so the migration backfills the counters from published reviews.

Pythonmigrations.py
import sqlite3from shopdb import connect, showdb = connect()db.isolation_level = None # we write BEGIN and COMMIT ourselves MIGRATIONS = [ ("create reviews", """CREATE TABLE reviews ( id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), customer_id INTEGER NOT NULL REFERENCES customers(id), order_id INTEGER NOT NULL, rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5), body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('published', 'hidden')), created_at TEXT NOT NULL, UNIQUE (customer_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id)) STRICT;"""), ("rating counters on products", """ALTER TABLE products ADD COLUMN rating_count INTEGER NOT NULL DEFAULT 0;ALTER TABLE products ADD COLUMN rating_sum INTEGER NOT NULL DEFAULT 0;UPDATE products SET rating_count = (SELECT count(*) FROM reviews r WHERE r.product_id = products.id AND r.status = 'published'), rating_sum = (SELECT coalesce(sum(r.rating), 0) FROM reviews r WHERE r.product_id = products.id AND r.status = 'published');"""),] def migrate(db, migrations): current = db.execute("PRAGMA user_version").fetchone()[0] for version, (name, sql) in enumerate(migrations, start=1): if version <= current: continue try: db.executescript(f"BEGIN; {sql}; PRAGMA user_version = {version}; COMMIT;") print(f"applied {version}: {name}") except sqlite3.Error as e: db.execute("ROLLBACK") print(f"FAILED {version}: {name}: {e}") break print("schema version", db.execute("PRAGMA user_version").fetchone()[0]) # Release 1 ships the reviews table only.migrate(db, MIGRATIONS[:1]) # Customers write reviews for a few weeks.db.executemany("""INSERT INTO reviews (product_id, customer_id, order_id, rating, body, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)""", [ (1, 1, 1, 5, "Fast and quiet.", "published", "2025-02-10"), (3, 1, 1, 4, "Does the job.", "published", "2025-02-12"), (8, 2, 2, 5, "Changed how I design systems.", "published", "2025-02-20"), (9, 2, 2, 4, "Visit my shop for cheap copies!", "hidden", "2025-02-21"), (4, 5, 5, 5, "Lovely switches.", "published", "2025-04-09"), (5, 5, 5, 3, "Scroll wheel squeaks.", "published", "2025-04-09"), (3, 5, 5, 2, "Gets hot.", "published", "2025-04-10"), (5, 1, 8, 4, "Good battery life.", "published", "2025-06-28"), (9, 1, 8, 5, "Worth rereading.", "published", "2025-06-30"),]) # Release 2 adds the counters and backfills them from existing reviews.migrate(db, MIGRATIONS)migrate(db, MIGRATIONS) # running it again is a no-op show(db, """SELECT id, name, rating_count, rating_sum FROM products WHERE rating_count > 0 ORDER BY id""") # A broken migration: the index is created, then a typo fails the script.broken = MIGRATIONS + [("index and bad column", """CREATE INDEX reviews_by_product ON reviews (product_id);ALTER TABLE reviews ADD COLUMN helpful_votes INTEGER NOT NULL;""")]migrate(db, broken)show(db, "SELECT name FROM sqlite_schema WHERE name = 'reviews_by_product'")
Output
Press Run (⌘ Enter) to see what happens.

Read the output from the bottom. The broken third migration created an index and then failed on the next statement: SQLite cannot add a NOT NULL column without a default to a table that has rows. The ROLLBACK undid the index too, and user_version is still 2. Fix the migration, by adding DEFAULT 0, and the next run applies it cleanly. Without the transaction you would have half a migration applied and a runner that thinks nothing happened.

What to check: the counters match the seed reviews (the hub has 4 + 2 = 6 from two reviews), the hidden spam review on product 9 is not counted, the second migrate call prints only the version, and the broken migration leaves no index behind. Add DEFAULT 0 to helpful_votes and watch version 3 apply.

Put it in order6 steps

Put the steps of applying one pending migration in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Stage 3: the reporting queries

Ratings by product, ranked inside each category. Every product must appear, so products is LEFT JOINed to reviews. The status = 'published' condition goes in the ON clause. Put it in WHERE and the products with no reviews vanish, the trap from Joins of Every Kind. The per-product numbers come from GROUP BY, from Aggregation, GROUP BY and HAVING, and count(*) FILTER (WHERE ...) counts the low ratings in the same pass. Products with no reviews have a NULL average, as NULL and Three-Valued Logic predicts, so the ranking says NULLS LAST on purpose. The ranking itself is RANK() over a window partitioned by category, from Window Functions, computed in the outer query over a named CTE from Subqueries, CTEs and Set Operations.

Reviews per month. Group by month, then run window functions over the grouped rows: a running total with sum(reviews) OVER (ORDER BY month) and the change from the previous month with LAG.

Five-star share per reviewer. A window over an aggregate, sum(count(*)) OVER (), puts the grand total on every row, so each reviewer's share needs no second query.

Pythonreports.py
from shopdb import connect, showdb = connect()db.executescript("""CREATE TABLE reviews ( id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), customer_id INTEGER NOT NULL REFERENCES customers(id), order_id INTEGER NOT NULL, rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5), body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('published', 'hidden')), created_at TEXT NOT NULL, UNIQUE (customer_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id)) STRICT;INSERT INTO reviews (product_id, customer_id, order_id, rating, body, status, created_at) VALUES (1, 1, 1, 5, 'Fast and quiet.', 'published', '2025-02-10'), (3, 1, 1, 4, 'Does the job.', 'published', '2025-02-12'), (8, 2, 2, 5, 'Changed how I design systems.', 'published', '2025-02-20'), (9, 2, 2, 4, 'Visit my shop for cheap copies!', 'hidden', '2025-02-21'), (4, 5, 5, 5, 'Lovely switches.', 'published', '2025-04-09'), (5, 5, 5, 3, 'Scroll wheel squeaks.', 'published', '2025-04-09'), (3, 5, 5, 2, 'Gets hot.', 'published', '2025-04-10'), (5, 1, 8, 4, 'Good battery life.', 'published', '2025-06-28'), (9, 1, 8, 5, 'Worth rereading.', 'published', '2025-06-30');""") print("Report 1: ratings by product, ranked inside each category")show(db, """WITH stats AS ( SELECT p.id, p.name, c.name AS category, count(r.id) AS reviews, round(avg(r.rating), 2) AS avg_rating, count(*) FILTER (WHERE r.rating <= 2) AS low FROM products p JOIN categories c ON c.id = p.category_id LEFT JOIN reviews r ON r.product_id = p.id AND r.status = 'published' GROUP BY p.id, p.name, c.name)SELECT category, name, reviews, avg_rating, low, RANK() OVER (PARTITION BY category ORDER BY avg_rating DESC NULLS LAST) AS rank_in_catFROM statsORDER BY category, rank_in_cat, name""") print()print("Report 2: reviews per month, with a running total and the change")show(db, """WITH monthly AS ( SELECT substr(created_at, 1, 7) AS month, count(*) AS reviews, round(avg(rating), 2) AS avg_rating FROM reviews WHERE status = 'published' GROUP BY month)SELECT month, reviews, avg_rating, sum(reviews) OVER (ORDER BY month) AS running_total, round(avg_rating - LAG(avg_rating) OVER (ORDER BY month), 2) AS changeFROM monthlyORDER BY month""") print()print("Report 3: share of each customer's reviews that are 5 stars")show(db, """SELECT cu.name, count(*) AS reviews, round(100.0 * count(*) FILTER (WHERE r.rating = 5) / count(*)) AS pct_five, round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct_of_allFROM reviews rJOIN customers cu ON cu.id = r.customer_idWHERE r.status = 'published'GROUP BY cu.id, cu.nameORDER BY reviews DESC, cu.name""")
Output
Press Run (⌘ Enter) to see what happens.

In report 1, the keyboard beats the mouse on one review against two. A one-review average is weak evidence, which a stretch goal fixes. In report 2, March and May are missing because nobody wrote a review then. LAG compares April with February, not with March. When gaps matter, generate the months with a recursive CTE from Recursive CTEs and Hierarchies.

What to check: report 1 has ten rows, one per product. Report 2 shows the spam review is not counted in February. Report 3's pct_of_all adds up to 100. Now move r.status = 'published' from the ON clause into a WHERE clause and run report 1 again.

Quick check
In report 1 you move r.status = 'published' from the LEFT JOIN's ON clause into a WHERE clause. What changes?
Need a nudge? A hint rules out a wrong answer.
Predict the outputSQL

What does this print?

-- Books averages: Designing Data-Intensive Applications 5.0,
-- The Pragmatic Programmer 5.0, SQL Performance Explained NULL
SELECT name,
     RANK() OVER (ORDER BY avg_rating DESC NULLS LAST) AS r
FROM book_stats;
-- What is r for SQL Performance Explained?
Need a nudge? Hints walk you through it.

Stage 4: index the product page

The product page's hottest query fetches the ten latest published reviews for one product. Nine rows are always fast, so the block loads 60,000 fake reviews across 300 products, with foreign keys off because the fake orders do not exist. That is fine for test data only.

The UNIQUE (customer_id, product_id) index contains product_id, but it is sorted by customer_id first, so product 42's entries are scattered through it. How Indexes Work explains why that cannot be searched.

The index to add follows the workflow from Composite, Covering and Partial Indexes: equality columns first, then the sort column. The query filters on product_id = ? and status = 'published' and sorts by created_at DESC, id DESC. So the key is (product_id, status, created_at). SQLite stores the rowid, id, at the end of every index entry, so the tie-breaker is sorted for free.

Prove it with EXPLAIN QUERY PLAN, the runnable plan from Reading EXPLAIN and EXPLAIN ANALYZE. The block also counts virtual machine steps, which is steadier than a browser timer.

Pythonindex_product_page.py
import random, timefrom shopdb import connectdb = connect()db.executescript("""CREATE TABLE reviews ( id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), customer_id INTEGER NOT NULL REFERENCES customers(id), order_id INTEGER NOT NULL, rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5), body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('published', 'hidden')), created_at TEXT NOT NULL, UNIQUE (customer_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id)) STRICT;""") # Test data only: 60,000 fake reviews for 300 products, loaded with# foreign keys off because the fake orders do not exist.random.seed(7)db.execute("PRAGMA foreign_keys = OFF")pairs = random.sample(range(300 * 5000), 60_000)rows = []for n, pair in enumerate(pairs): product, customer = pair % 300 + 1, pair // 300 + 1 day = f"2025-{random.randint(1, 12):02d}-{random.randint(1, 28):02d}" status = "hidden" if random.random() < 0.05 else "published" rows.append((product, customer, n + 1, random.randint(1, 5), "Review text.", status, day))db.executemany("""INSERT INTO reviews (product_id, customer_id, order_id, rating, body, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)""", rows)db.commit()db.execute("PRAGMA foreign_keys = ON") PRODUCT_PAGE = """SELECT id, rating, body, created_atFROM reviewsWHERE product_id = ? AND status = 'published'ORDER BY created_at DESC, id DESCLIMIT 10""" steps = 0def tick(): global steps steps += 1 return 0db.set_progress_handler(tick, 100) def measure(label): global steps print(label) for row in db.execute("EXPLAIN QUERY PLAN " + PRODUCT_PAGE, (42,)): print(" ", row[3]) steps = 0 start = time.perf_counter() found = db.execute(PRODUCT_PAGE, (42,)).fetchall() ms = (time.perf_counter() - start) * 1000 print(f" {len(found)} rows, about {steps * 100:,} VM steps, {ms:.2f} ms\n") measure("Before: only the UNIQUE (customer_id, product_id) index") db.execute("""CREATE INDEX reviews_product_recent ON reviews (product_id, status, created_at)""")db.execute("ANALYZE")measure("After: index on (product_id, status, created_at)")
Output
Press Run (⌘ Enter) to see what happens.

Before the index, the plan scans every entry, either of the table or of the unique index depending on your SQLite version, and adds USE TEMP B-TREE FOR ORDER BY: it sorts every match to keep ten. After the index, the plan is a SEARCH on two equality columns with no sort step, and the work drops from hundreds of thousands of steps to about a hundred.

What to check: the second plan says SEARCH ... USING INDEX reviews_product_recent and has no temp B-tree line. Then try two variations. Build the index as (created_at, product_id, status). You may see ANY(created_at), a skip scan that hops through every distinct date. It only works because this data has a few hundred dates. With real timestamps it becomes a scan, which is why equality columns go first. Drop status from the index and the plan keeps a search on product_id but has to check status row by row. A partial index, ON reviews (product_id, created_at) WHERE status = 'published', is also a good answer.

Quick check
The table already has an index from UNIQUE (customer_id, product_id). Why does the product page query not use it to find product 42's reviews?
Need a nudge? A hint rules out a wrong answer.

Stage 5: a safe write path

add_review is the function the app calls on submit. It inserts the review and bumps the counters. If the process dies between those writes, the counters are wrong forever, so both go in one transaction. It also does the check the schema could not, that the order is yours and shipped, inside the same transaction.

Three details matter:

  • BEGIN IMMEDIATE takes SQLite's write lock at the start. A plain BEGIN takes it at the first write, and two connections that both read first can then block each other, the one-writer rule from Locks, Deadlocks and Safe Concurrency.
  • The counter update is rating_count = rating_count + 1, an atomic update in the database. Read, add in Python, then write would lose updates, the anomaly from Isolation Levels and Anomalies.
  • Constraint errors become a clean ReviewRejected message for the API. Any other error rolls back and is raised again.

The crash=True flag simulates the process dying after the insert and before the counter update.

Pythonadd_review.py
import sqlite3from shopdb import connect, showdb = connect()db.isolation_level = None # explicit BEGIN and COMMITdb.executescript("""CREATE TABLE reviews ( id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), customer_id INTEGER NOT NULL REFERENCES customers(id), order_id INTEGER NOT NULL, rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5), body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('published', 'hidden')), created_at TEXT NOT NULL, UNIQUE (customer_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id)) STRICT;ALTER TABLE products ADD COLUMN rating_count INTEGER NOT NULL DEFAULT 0;ALTER TABLE products ADD COLUMN rating_sum INTEGER NOT NULL DEFAULT 0;""") class ReviewRejected(Exception): pass def add_review(db, customer_id, order_id, product_id, rating, body, now, crash=False): db.execute("BEGIN IMMEDIATE") # take the write lock up front try: bought = db.execute(""" SELECT o.status FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = ? AND o.customer_id = ? AND i.product_id = ?""", (order_id, customer_id, product_id)).fetchone() if bought is None: raise ReviewRejected("you did not buy this product in that order") if bought[0] != "shipped": raise ReviewRejected("you can review once the order has shipped") review_id = db.execute(""" INSERT INTO reviews (product_id, customer_id, order_id, rating, body, created_at) VALUES (?, ?, ?, ?, ?, ?) RETURNING id""", (product_id, customer_id, order_id, rating, body, now)).fetchone()[0] if crash: raise RuntimeError("process killed between the two writes") db.execute("""UPDATE products SET rating_count = rating_count + 1, rating_sum = rating_sum + ? WHERE id = ?""", (rating, product_id)) db.execute("COMMIT") return review_id except sqlite3.IntegrityError as e: db.execute("ROLLBACK") if "UNIQUE" in str(e): raise ReviewRejected("you have already reviewed this product") from None raise ReviewRejected(f"invalid review ({e})") from None except BaseException: db.execute("ROLLBACK") raise def attempt(label, *args, **kwargs): try: new_id = add_review(db, *args, now="2025-07-20", **kwargs) print(f"{label:<24} saved as review {new_id}") except ReviewRejected as e: print(f"{label:<24} rejected: {e}") except RuntimeError as e: print(f"{label:<24} crashed: {e}") attempt("Ada, laptop, order 1", 1, 1, 1, 5, "Fast and quiet.")attempt("Ada again, same laptop", 1, 1, 1, 1, "Actually, no.")attempt("Ada, headphones, paid", 1, 3, 6, 4, "Arrives soon?")attempt("Grace, Ada's order", 2, 1, 3, 1, "Never got it.")attempt("Linus, rating of 9", 5, 5, 4, 9, "Ten out of ten.")attempt("Linus, keyboard, crash", 5, 5, 4, 5, "Lovely switches.", crash=True)attempt("Linus, keyboard, retry", 5, 5, 4, 5, "Lovely switches.") print()show(db, "SELECT id, product_id, customer_id, rating, body FROM reviews")print()print("Counters that disagree with the reviews table:")show(db, """SELECT p.id, p.rating_count, count(r.id) AS actual_count, p.rating_sum, coalesce(sum(r.rating), 0) AS actual_sumFROM products pLEFT JOIN reviews r ON r.product_id = p.id AND r.status = 'published'GROUP BY p.idHAVING p.rating_count <> count(r.id) OR p.rating_sum <> coalesce(sum(r.rating), 0)""")
Output
Press Run (⌘ Enter) to see what happens.

The crash run inserted a review, then died. The ROLLBACK removed it, so the retry succeeds, and the final check finds no product whose counters disagree with its reviews.

What to check: two reviews saved, five rejections or crashes, each with a clear reason, and an empty consistency report. Keep that consistency query as a nightly job: it catches any code path that skips add_review.

Make it yours

The core works. These turn it into something worth showing:

  • Hiding a review. Write hide_review(db, review_id). It must change the status and take the rating back out of the counters in one transaction, and do nothing if the review is already hidden.
  • A fairer ranking. Rank by a Bayesian average, (rating_sum + m * site_avg) / (rating_count + m) with m around 5, so one five-star review no longer beats twenty fours. Compare the rankings side by side.
  • Helpful votes. Add a review_votes table with a primary key on (review_id, customer_id), sort the product page by helpfulness, and design the index that query needs.
  • Gap-free monthly report. Generate every month of the year with a recursive CTE and LEFT JOIN the counts onto it, so LAG compares with the real previous month.
  • Keyset pagination. Replace "page 2" with "reviews older than this (created_at, id)", as in Query Patterns That Scale, and show with EXPLAIN QUERY PLAN that page 500 is as cheap as page 1.
  • Port it to Postgres. Run the same schema and queries on a local Postgres, apply the dialect notes, and compare EXPLAIN (ANALYZE, BUFFERS) before and after the index.

When you write it up, the Interview Prep lesson Writing Project Case Studies shows how to turn a project like this into a short case study.

Key terms
composite foreign key
A foreign key over several columns that must match a primary key or unique key with the same columns in another table.
STRICT table
A SQLite table, from version 3.37, that refuses values of the wrong type instead of storing them with loose type affinity.
schema version
A number recording which migrations have run, such as SQLite's user_version or a migrations table, used to skip work already done.
denormalised counter
A stored value, like rating_count, that could be computed from other rows but is kept up to date for fast reads.
EXPLAIN QUERY PLAN
SQLite's command that shows how a query would run, such as SCAN or SEARCH USING INDEX, without running it.
BEGIN IMMEDIATE
A SQLite transaction that takes the write lock at the start, so two writers cannot deadlock after both have read.
atomic update
An UPDATE that computes the new value inside the database, like count = count + 1, so concurrent writes cannot overwrite each other.

That is a reviews feature you could ship. The wrap-up next pulls the whole course together around one more feature, a loyalty programme, and closes with a mixed review.