Suppose every price row also stored its stock's name and sector. Then 6,699 AAPL rows hold the same sector, a typo makes "Technology" and "Tecnology" two sectors, and changing a classification means rewriting thousands of rows. A good model removes that risk before the first row is loaded.
The idea in plain words
Where we are. The previous nine topics used tables someone else had designed. Here you design them. This is also the last topic before the capstone, which builds a returns and factor warehouse and needs every earlier idea: aggregation, windows, as-of joins, time buckets, plans and now keys.
A rule the database checks on every insert and update and enforces by refusing the row: NOT NULL, PRIMARY KEY, REFERENCES (a foreign key) and CHECK. A rule in the schema cannot be forgotten by one careless script.
Facts in one place
Split by what each fact depends on. A stock's name and sector depend only on the stock, so they go in securities, one row each. A close depends on the stock and the day, so it goes in prices, keyed by (symbol, date), with symbol pointing at securities. The database now knows what can repeat and what cannot.
# One row per stock in securities, one row per stock per day in pricesdb = duckdb.connect()db.execute(create_securities("securities"))db.executemany("INSERT INTO securities (symbol, name, sector) VALUES (?, ?, ?)", SECURITIES)db.execute(create_prices("prices", "securities"))print(db.sql("SELECT symbol, name, sector, currency FROM securities ORDER BY symbol"))1
┌─────────┬─────────────────────────┬──────────────────┬──────────┐ │ symbol │ name │ sector │ currency │ │ varchar │ varchar │ varchar │ varchar │ ├─────────┼─────────────────────────┼──────────────────┼──────────┤ │ AAPL │ Apple Inc. │ Technology │ USD │ │ JNJ │ Johnson & Johnson │ Health Care │ USD │ │ JPM │ JPMorgan Chase & Co. │ Financials │ USD │ │ KO │ The Coca-Cola Company │ Consumer Staples │ USD │ │ XOM │ Exxon Mobil Corporation │ Energy │ USD │ └─────────┴─────────────────────────┴──────────────────┴──────────┘
- 1The currency was never given: the default filled in USD.
Let the database say no
Constraints turn assumptions into checks. A high below a low, a negative close, a second bar for the same day and a bar for an unknown symbol are all errors in the data, and the database stops them at the door instead of letting them reach a back-test.
# Three bad bars: each one is refused, and the table stays cleanbad = [("AAPL", "2026-08-22", 5, 1, 2, 3, 10, "high below low"), ("ZZZ", "2026-08-22", 1, 2, 1, 1.5, 10, "unknown symbol"), ("AAPL", "2026-08-22", 1, 2, 1, -5, 10, "negative close")]for *row, why in bad: try: db.execute("INSERT INTO prices VALUES (?, ?, ?, ?, ?, ?, ?)", row) except duckdb.Error as error: print(why, "->", type(error).__name__)print(db.sql("SELECT count(*) AS bars FROM prices"))
high below low -> ConstraintException unknown symbol -> ConstraintException negative close -> ConstraintException ┌───────┐ │ bars │ │ int64 │ ├───────┤ │ 0 │ └───────┘
Loads you can run twice
A nightly job fails halfway and is run again; a vendor sends a corrected close for yesterday. With a plain INSERT the second run hits the primary key and stops. ON CONFLICT (symbol, date) DO UPDATE makes the load idempotent: a new bar is added, an existing one is replaced, and running it twice leaves the same table as running it once.
# Loading everything twice changes nothing; a correction replaces the old KO barfor _ in range(2): for symbol in SYMBOLS: db.executemany(upsert_bars("prices"), bar_rows(symbol, 200))print(db.sql("SELECT count(*) AS bars FROM prices"))db.execute(upsert_bars("prices"), ["KO", "2026-08-21", 90.85, 91.5, 90.7, 91.25, 15534719])print(db.sql("SELECT date, close FROM prices WHERE symbol = 'KO' ORDER BY date DESC LIMIT 2"))
┌───────┐ │ bars │ │ int64 │ ├───────┤ │ 1000 │ └───────┘ ┌────────────┬────────┐ │ date │ close │ │ date │ double │ ├────────────┼────────┤ │ 2026-08-21 │ 91.25 │ │ 2026-08-20 │ 90.5 │ └────────────┴────────┘
Views: a saved question
A view stores a query, not rows. latest below is defined once, and every time you read it, it reads the current table, so a bar loaded a minute ago appears in it with no refresh. A copy made with CREATE TABLE AS would be stale the moment new data arrives.
# The view follows the table: a newer KO bar appears with no refreshdb.execute(latest_view("latest", "prices"))print(db.sql("SELECT * FROM latest WHERE symbol = 'KO'"))db.execute("INSERT INTO prices VALUES ('KO', '2026-08-24', 91.2, 91.9, 91.0, 91.7, 1000)")print(db.sql("SELECT * FROM latest WHERE symbol = 'KO'"))
┌─────────┬────────────┬────────┐ │ symbol │ date │ close │ │ varchar │ date │ double │ ├─────────┼────────────┼────────┤ │ KO │ 2026-08-21 │ 91.25 │ └─────────┴────────────┴────────┘ ┌─────────┬────────────┬────────┐ │ symbol │ date │ close │ │ varchar │ date │ double │ ├─────────┼────────────┼────────┤ │ KO │ 2026-08-24 │ 91.7 │ └─────────┴────────────┴────────┘
Values go through quote(); table and column names cannot be passed as ? parameters, so they go through ident(). A name with a double quote or a space breaks a hand-built statement, and a name taken from user input is a way in for an attacker.
What the tasks ask
- 1`create_securities` and `create_prices`Keys,
NOT NULL, a default, a foreign key andCHECKrules. The grader tries to break them with bad rows. - 2`upsert_bars`
INSERT ... ON CONFLICT (symbol, date) DO UPDATEwith seven placeholders. - 3`latest_view`
CREATE VIEWwithrow_number()andQUALIFY, so it follows the table.
INSERT into a table with PRIMARY KEY (symbol, date). What happens?Lab · what's graded
4 tasks · 100 pts- Keys and defaults:
create_securities25 pts - Constraints:
create_prices25 pts - A repeatable load:
upsert_bars25 pts - A view:
latest_view25 pts