▚ The AI Engineer's Field Manual
Module 01d · Act I — Foundations

SQL & the Data Lifecycle — From Raw Events to Answers You Can Defend

"A number you cannot trace back to rows is an opinion."

~9 hours (6 reading, 3 building) Builds on: Modules 01 and 01c Tools: PostgreSQL 18 · DuckDB · psycopg 3 · SQLAlchemy 2.0 · pandas Job-spec line it unlocks: "Strong SQL (joins, window functions, CTEs), PostgreSQL, ETL/ELT, Python–database integration"

01 · The hookTwo Revenue Numbers, One Board Meeting

SQL is the language you use to ask a database questions. Without it, every answer depends on someone's private copy of the data, and two copies give two answers.

Field report · Client memo

"The board meets on Friday. I need eight numbers out of our operational database: trips and revenue by month, revenue by city, when riders cancel, our best drivers, month-over-month growth, a smoothed daily trend, whether new riders come back, and what the promo codes cost us. Dev built them in a pandas notebook. It says completed trips earned 11.2 million rupees. The finance dashboard says we collected 9.3 million. One of those goes into the board pack. I do not know which one, and neither does Dev."

— Priya Nair, Finance Lead at "RideNow"

You met RideNow in Module 01c: a city ride-hailing company whose messy trip file you cleaned in pandas. This chapter picks up the same business one step earlier, at the place the file came from. The company's operational database holds six tables: riders, drivers, trips, payments, cities and promotions. Priya's eight questions are all answerable from them. The two revenue numbers disagree by about 1.9 million rupees.

The disagreement is the story of this chapter. We will learn SQL by hunting it, and then by building the pipeline that makes the right answer repeatable. By the end you will have written all eight board answers twice, once in SQL and once in pandas, and proven the two agree to the paisa.

The data here mirrors 01c's RideNow but does not depend on it. make_db.py builds the six tables from a fixed random seed (42), so your numbers match this page exactly. Every printed result below names the engine that produced it: DuckDB (works offline, nothing to install beyond the course environment) or PostgreSQL 18 (needs Docker).

1 Analyst's pandas notebook 11,226,811.56 2 Gross fares (trips table) 10,016,889.57 3 Cash collected (dashboard) 9,280,083.74 0 6 million rupees 12 million
Fig. 1d.1 — The three revenue numbers in the story, drawn from zero. All three come from the same database. They differ because they answer three different questions, and one of them answers none.
  1. The notebook: 11,226,811.56 rupees. The analyst joined trips to payments and summed the fare column. It is the longest bar, and it is wrong: it is bigger than anything the company ever billed. Finding out why is the first job of this chapter.
  2. Gross fares: 10,016,889.57 rupees. The sum of the fare on all 46,760 completed trips, counting each trip once. This is what riders were quoted, before promo discounts and refunds.
  3. Cash collected: 9,280,083.74 rupees. Successful payments minus refunds. This is the finance dashboard's number and the one that reaches the bank. The bar at marker 1 is 1,209,921.99 rupees longer than the bar at marker 2: money that exists only inside the join.
You already know this

Nine years of ORMs means you have written SQL indirectly: .filter() is WHERE, .group_by() is GROUP BY, .join() is a join, and a lazy-loaded relation inside a loop is the N+1 problem. You know indexes, transactions and foreign keys as things that keep an app fast and correct.

What changes in analytics is the direction of thought. An app asks "give me this one record". An analyst asks "tell me something true about 50,000 records". You stop looping over rows and start describing whole sets: which rows, grouped how, summed what. The database does the looping, in code that is faster than anything you will write.

02 · The relational modelTables, Rows and Keys

Priya has two numbers and no way to tell which is right. Before we can answer her eight questions we have to see what the database actually holds. The first thing to learn is how it stores facts, because the whole disagreement hides in one detail of that storage.

A relational database keeps facts in tables, and it keeps each fact in exactly one place. Keys are the labels that let one table point at a row in another. Without keys, tables are just piles of rows that cannot be connected.

Start tiny: one table, one row

A table is a list of records that all have the same columns. A row is one record. A column is one kind of fact, with one type for every row. The smallest table in RideNow's database is cities, with six rows. The block below also shows one row of trips, so you can see what "one fact per column" looks like.

sql/00_tables_tour.sqlruns offline
-- 1. A table is rows and columns. cities is the smallest one.
SELECT * FROM cities;

-- 2. One row of trips: every column is one fact about one trip.
SELECT * FROM trips WHERE trip_id = 158;

-- 3. A primary key is unique and never NULL: as many distinct values as rows.
SELECT COUNT(*) AS rows, COUNT(DISTINCT trip_id) AS distinct_trip_ids FROM trips;

-- 4. A foreign key only has to point at an existing row. It does not have to be unique.
SELECT COUNT(*) AS payment_rows, COUNT(DISTINCT trip_id) AS distinct_trip_ids FROM payments;

-- 5. Trip 158 appears three times in payments. Remember this.
SELECT payment_id, trip_id, attempt_no, status, amount FROM payments WHERE trip_id = 158 ORDER BY attempt_no;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed the same numbers)
>> SELECT * FROM cities
city_id  name       country
-------  ---------  -------
      1  Bengaluru  India
      2  Mumbai     India
      3  Delhi      India
      4  Hyderabad  India
      5  Chennai    India
      6  Pune       India

>> SELECT * FROM trips WHERE trip_id = 158
trip_id  rider_id  driver_id  city_id  promo_id  requested_at         status     distance_km  duration_min  surge  fare
-------  --------  ---------  -------  --------  -------------------  ---------  -----------  ------------  -----  ------
    158        17         60        1         4  2026-01-02 15:10:45  completed         5.27         16.10   1.00  136.20

>> SELECT COUNT(*) AS rows, COUNT(DISTINCT trip_id) AS distinct_trip_ids FROM trips
rows   distinct_trip_ids
-----  -----------------
60000              60000

>> SELECT COUNT(*) AS payment_rows, COUNT(DISTINCT trip_id) AS distinct_trip_ids FROM payments
payment_rows  distinct_trip_ids
------------  -----------------
       52380              46063

>> SELECT payment_id, trip_id, attempt_no, status, amount FROM payments WHERE trip_id = 158 ORDER BY attempt_no
payment_id  trip_id  attempt_no  status     amount
----------  -------  ----------  ---------  ------
       145      158           1  failed     115.77
       146      158           2  failed     115.77
       147      158           3  succeeded  115.77

Read the output from the top. Query 1 shows six cities, each with a small whole number called city_id. Query 2 shows one trip: rider 17 asked for a ride in city 1 on 2 January, it was completed, and the fare was 136.20 rupees. Notice that the trip row does not say "Bengaluru". It says city_id = 1. That choice is the heart of the relational model.

Why a trip stores a number instead of a name

Imagine trips stored the city name in every row. "Bengaluru" would appear 16,296 times. If the company renamed the city, you would have to change 16,296 rows and hope you missed none. Instead, the name lives once in cities, and each trip carries the small number that points to it. This habit is called normalisation: store every fact in one place, and point to it from everywhere else.

The price is that a question like "trips per city name" now needs two tables. Joining them back together is the skill the next two sections teach. Module 01c's RideNow file was a single flat export with the city name repeated on every row. Think of it as these six tables already joined and photocopied.

Primary keys and foreign keys

The pointer needs two rules. Each table needs a column whose value is different in every row, so a row can be named exactly. That column is the primary key (PK): trip_id in trips, city_id in cities. A column in another table that holds those numbers is a foreign key (FK): trips.city_id points at cities.city_id.

Queries 3 and 4 in the output above test the rules. In trips, the 60,000 rows hold 60,000 distinct trip_id values, which is what a primary key promises. In payments, the 52,380 rows hold only 46,063 distinct trip_id values. A foreign key is allowed to repeat. Query 5 shows why: trip 158 has three payment rows.

cities 6 rows city_id PK name country riders 4,000 rows rider_id PK city_id FK signup_date email referred_by FK drivers 300 rows driver_id PK city_id FK joined_date vehicle_type rating trips 60,000 rows trip_id PK rider_id FK driver_id FK city_id FK promo_id FK requested_at status distance_km duration_min surge fare promotions 5 rows promo_id PK code discount_pct start_date end_date payments 52,380 rows payment_id PK trip_id FK attempt_no status amount method paid_at 1 2 3 4 1 trip many payment rows 52,380 payment rows belong to 46,063 paid trips: some trips have a failed attempt first.
Fig. 1d.2 — RideNow's six tables with the real row counts. Arrows run from the table that holds a foreign key to the table whose primary key it points at.
  1. A primary key. trips.trip_id is marked PK: 60,000 rows, 60,000 different values, never empty. One trip number names exactly one trip, which makes it safe to point at.
  2. A foreign key arrow. trips.rider_id points at riders.rider_id. Every trip belongs to exactly one rider, but one rider owns many trips. This is a one-to-many relationship, and the arrow always points from the "many" side to the "one" side.
  3. The red arrow. payments.trip_id points at trips.trip_id, and it is also one-to-many: one trip, many payment rows. 52,380 payment rows belong to 46,063 paid trips, because a failed card attempt gets its own row. This arrow is where the 1.9 million rupees comes from.
  4. A table pointing at itself. riders.referred_by holds the rider_id of the rider who invited this one. A table can have a foreign key into itself. We will walk that chain with a recursive query later in this chapter.

"Six tables to answer a question that used to be one CSV? Isn't this just extra work for the database designer?"

— the analyst who owned the flat file in Module 01c, right about now

For one analyst reading data, a flat file is simpler, and you should not feel guilty about using one. The six tables exist for the writer. The app saves a trip, a payment attempt and a refund thousands of times a day, and normalisation guarantees that a city rename or a corrected fare changes in one place, never in a hundred thousand.

The honest downside lands on you, the reader of data: every question needs joins, and joins are where mistakes breed. Fig. 1d.2's red arrow is the proof. A flat CSV could never have double counted a fare this way, because there was only one row per trip to begin with.

Getting the database on your machine

Two engines run every query in this chapter. DuckDB is a database that lives inside your Python process and needs no server, which makes it the offline path. It is the same engine Module 01 used for its SQL section. PostgreSQL 18 is the production target. It is the current stable major version as of October 2026; version 19 is in release-candidate testing and is due in November. We run it in a Docker container on port 55432.

setup.shneeds PostgreSQL (docker) — DuckDB part runs offline
#!/usr/bin/env bash
# One-time setup for chapter 01d. Run from code/01d-sql-data-lifecycle/.
# Offline path (DuckDB only): skip the docker line, everything marked "duckdb" still runs.
set -euo pipefail

# PostgreSQL 18 in a throwaway container on port 55432 (stop it later with: docker stop ridenow-pg)
docker run -d --name ridenow-pg -e POSTGRES_PASSWORD=ridenow -e POSTGRES_DB=ridenow \
  -p 55432:5432 postgres:18-alpine

# python packages (course environment):  uv pip install "duckdb>=1.5" "psycopg[binary]>=3.2,<4" \
#   "sqlalchemy>=2.0,<2.1" pandas matplotlib "adbc-driver-postgresql>=1.7"

# build the six tables: CSV files, a DuckDB file, and (with --load postgres) the PostgreSQL copy
python make_db.py --load postgres
Step-by-step: what make_db.py does, in plain English
  1. It creates a random-number generator with the fixed seed 42, so every run produces the same data.
  2. It builds the small tables first: six cities, 4,000 riders (a quarter of them referred by an earlier rider), 300 drivers and five promo codes.
  3. It creates 60,000 trip requests across January to September 2026. Volume triples over the period, weekends are busier, and there are two rush hours. About 78% of trips complete, and the rest are cancelled by the rider, cancelled by the driver, or find no driver.
  4. It prices each completed trip from distance, duration and a surge multiplier, and attaches a promo code to some of them.
  5. It writes the payment rows. Most completed trips get one successful payment. A few percent get one or two failed attempts first, a few percent are refunded, and 1.5% have no payment row at all. These realistic quirks are the traps.
  6. It saves every table as a CSV file, builds a DuckDB file from schema.sql, and with --load postgres copies the same CSVs into PostgreSQL using its bulk COPY command.
terminalactual output
cities            6 rows
riders        4,000 rows
drivers         300 rows
promotions        5 rows
trips        60,000 rows
payments     52,380 rows
DuckDB file written: /home/iam100god/Desktop/AI_COURSE/code/01d-sql-data-lifecycle/data/ridenow.duckdb

The generator is in code/01d-sql-data-lifecycle/make_db.py, and schema.sql next to it holds the table definitions. Both engines accept the same schema file. One difference surfaced already: DuckDB 1.5 refuses a self-referencing foreign key during a bulk load, so riders.referred_by is declared without its REFERENCES clause. PostgreSQL would accept it. The dialect table near the end of this chapter collects every difference we hit.

Table / row / column
A list of same-shaped records; one record; one kind of fact.
Primary key (PK)
A column that is different in every row and never empty; it names one row exactly.
Foreign key (FK)
A column holding another table's primary key; it may repeat, which is what makes one-to-many.
Normalisation
Store each fact once and point to it. Good for writing, costs a join when reading.
One-to-many
One parent row, many child rows. One trip, many payment rows.
Why it matters here
A join from the "one" side to the "many" side multiplies rows. Remember trip 158.

03 · Asking questionsSELECT, WHERE, GROUP BY and HAVING

We know where the facts live. Priya's first question is the easiest: how many trips completed, and how much did they earn? That needs only the trips table, so it is the right place to learn the six clauses that every SQL question is built from, using numbers small enough to check by eye.

A SQL query describes the table you want back: which columns, which rows, how to collapse many rows into a few. You do not say how to loop. Without these clauses you would copy the table out and filter it yourself.

One idea per clause

The block below uses all six, in three small queries. Before you read the answers, try the pencil exercise.

You have not been taught the aggregate functions (COUNT, AVG, ROUND) yet. Guess from the words. The step-by-step list under the exercise explains each, and the section after the exercise reads the output line by line.

Sharpen your pencil

Ten lines lifted from sql/01_first_queries.sql. Three are annotated for you. In the blank rows, write in plain English what each line does, before you open the answers.

SELECT trip_id, city_id, requested_at, status, farepick five columns to show
FROM tripsread from the trips table
WHERE status = 'completed' AND fare > 500
ORDER BY fare DESC
LIMIT 5;
SELECT status, COUNT(*) AS trips, ROUND(AVG(fare), 2) AS avg_fare
GROUP BY status
SELECT city_id, COUNT(*) AS completed_tripsone output row per city, with a count
WHERE status = 'completed'
HAVING COUNT(*) > 8000
Check your answers
SELECT trip_id, city_id, requested_at, status, farepick five columns to show
FROM tripsread from the trips table
WHERE status = 'completed' AND fare > 500keep only rows where both tests are true: the trip finished and the fare is over 500 rupees
ORDER BY fare DESCsort the survivors with the biggest fare first (DESC means descending)
LIMIT 5;stop after five rows; the semicolon ends the statement
SELECT status, COUNT(*) AS trips, ROUND(AVG(fare), 2) AS avg_farefor each group, count its rows (named trips), average its fares, and round to two decimals
GROUP BY statusmake one group per distinct status value: four groups
SELECT city_id, COUNT(*) AS completed_tripsone output row per city, with a count
WHERE status = 'completed'throw away cancelled trips before grouping
HAVING COUNT(*) > 8000after counting, keep only cities with more than 8,000 completed trips

If you got WHERE and HAVING the right way round, you already understand the most common SQL interview trap: WHERE judges rows, HAVING judges groups.

Step-by-step: what sql/01_first_queries.sql does, in plain English
  1. Query 1 reads trips, keeps completed trips with a fare above 500, sorts them with the biggest fare first, and shows the top five.
  2. Query 2 puts every trip into a group by its status. For each group it counts the rows and averages the fares. ROUND(x, 2) keeps two decimals.
  3. COUNT(*) counts rows. AVG(fare) averages a column and silently skips empty (NULL) values.
  4. Query 3 first throws away every trip that is not completed. Then it groups the survivors by city and counts them.
  5. Only after counting does HAVING COUNT(*) > 8000 run. It removes the small cities, so just the big ones remain.
  6. Lines starting with -- are comments. Each statement ends with a semicolon.
sql/01_first_queries.sqlruns offline
-- 1. What is in the trips table? Pick columns, filter rows, order, limit.
SELECT trip_id, city_id, requested_at, status, fare
FROM trips
WHERE status = 'completed' AND fare > 500
ORDER BY fare DESC
LIMIT 5;

-- 2. GROUP BY collapses many rows into one row per group.
SELECT status, COUNT(*) AS trips, ROUND(AVG(fare), 2) AS avg_fare
FROM trips
GROUP BY status
ORDER BY trips DESC;

-- 3. WHERE filters rows BEFORE grouping, HAVING filters groups AFTER.
SELECT city_id, COUNT(*) AS completed_trips
FROM trips
WHERE status = 'completed'
GROUP BY city_id
HAVING COUNT(*) > 8000
ORDER BY completed_trips DESC;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed identical rows)
[engine: duckdb]

>> SELECT trip_id, city_id, requested_at, status, fare FROM trips WHERE status = 'completed' AND fare > 500 ORDER
trip_id  city_id  requested_at         status     fare
-------  -------  -------------------  ---------  --------
  32938        4  2026-06-30 18:09:32  completed  1,686.75
  19403        5  2026-05-03 19:25:09  completed  1,503.95
   2088        3  2026-01-18 17:39:37  completed  1,486.65
  23893        3  2026-05-24 18:44:39  completed  1,458.67
   5948        1  2026-02-16 17:35:29  completed  1,406.53

>> SELECT status, COUNT(*) AS trips, ROUND(AVG(fare), 2) AS avg_fare FROM trips GROUP BY status ORDER BY trips DE
status               trips  avg_fare
-------------------  -----  --------
completed            46760    214.22
cancelled_by_rider    7202  NULL
cancelled_by_driver   3647  NULL
no_driver             2391  NULL

>> SELECT city_id, COUNT(*) AS completed_trips FROM trips WHERE status = 'completed' GROUP BY city_id HAVING COUN
city_id  completed_trips
-------  ---------------
      1            12674
      2            11025
      3            10598

Reading the three answers

Query 1 shows that the biggest fare in the database is 1,686.75 rupees: a long trip in Hyderabad on 30 June at rush hour. Query 2 is the first real finding. The table holds 46,760 completed trips, 7,202 cancelled by the rider, 3,647 cancelled by the driver and 2,391 where no driver was found. The average fare is 214.22 for completed trips.

Look at avg_fare for the three cancelled groups: it says NULL. NULL means "no value here", which is different from zero. A trip that never happened has no fare, so the column is empty. AVG skips NULLs. If cancelled trips had been stored as fare 0, the average would have fallen to about 167, and nobody would have noticed.

Query 3 lists Bengaluru (12,674 completed trips), Mumbai (11,025) and Delhi (10,598). Hyderabad, Chennai and Pune are missing because their counts fall below 8,000, and HAVING removed them. If you had put the same test in WHERE, the database would have replied with an error, because the count does not exist yet at that point.

FROM trips 60,000 rows 1 WHERE status = 'completed' 46,760 rows 2 GROUP BY city_id 6 groups 3 HAVING COUNT(*) > 8000 3 groups 4 SELECT + ORDER BY city_id, COUNT(*) 3 rows out 5 You write SELECT first, but the engine runs it fifth. That is why WHERE cannot see a column alias made in SELECT, and why HAVING exists.
Fig. 1d.3 — The order the engine runs query 3 of the block above, with the real row counts after each step. The order is not the order you write the words in.
  1. FROM: 60,000 rows. The engine starts with the whole table. Nothing has been filtered yet.
  2. WHERE: 46,760 rows. Rows are judged one at a time. 13,240 cancelled or driverless trips are dropped here, before any grouping.
  3. GROUP BY: 6 groups. The surviving rows are sorted into one bucket per city, and each bucket gets its count.
  4. HAVING: 3 groups. Now whole groups are judged. Only cities with more than 8,000 completed trips stay. This is the one step that can see COUNT(*).
  5. SELECT and ORDER BY: 3 rows out. Only now are output columns computed and sorted. That is why a column alias made in SELECT cannot be used in WHERE: WHERE ran earlier.

"I can load the whole trips table into pandas and do all of this with a groupby. Why learn a second language for the same thing?"

— a nine-year engineer who is comfortable in Python, right about now

For 60,000 rows, pandas is fine, and the lab at the end of this chapter does every question both ways to prove it. SQL wins on three counts. The data already lives in the database, so you move 6 rows of answer instead of 60,000 rows of data. The database has indexes and a planner that pandas lacks. And SQL is the one language the finance team's dashboard, the data warehouse and your interviewer all share.

The honest downside: SQL is awkward for step-by-step exploration, plotting and anything that is not a table. Most real work uses both, with SQL shrinking the data and pandas shaping the last mile.

Clause order, as you write it
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
Order the engine runs it
FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. See Fig. 1d.3.
WHERE vs HAVING
WHERE judges rows before grouping. HAVING judges groups after totals exist.
COUNT(*) / COUNT(col)
Counts rows / counts non-NULL values in that column.
NULL
"No value", not zero. Aggregates skip it. Test with IS NULL, never = NULL.
Portable
These three queries printed identical rows on DuckDB and PostgreSQL 18.

04 · Joining tablesJoins, and the Join That Multiplied the Revenue

Priya's second question is revenue by city. City names live in cities, money lives in payments, and trips sit between them. We have to join three tables, and a join is exactly where Dev's notebook went wrong. We start with the four kinds of join on safe counts, then replay the bug on four toy trips before touching 52,380 real rows.

A join glues rows from two tables side by side wherever a key matches. Its danger is silent: if one side has several matching rows, the other side's row is repeated, and any total over it grows.

Four joins, and what each one keeps

Think of a join as a matching game. For each row on the left, the database looks for rows on the right with the same key. What happens to rows with no partner, and what happens to rows with several partners, is the difference between the kinds.

The four joins you will actually write, with the real RideNow counts from sql/02_joins.sql
JoinKeepsCan the row count grow?Reach for it whenRideNow result
INNER JOINOnly left rows that found a partnerYes, one output row per matching pairBoth sides must exist: a trip and its city60,000 trips, each with one city
LEFT JOINEvery left row; partner columns are NULL when none existsYes, same as innerYou must not lose left rows: all riders, even idle ones60,051 rows: 60,000 pairs plus 51 riders with no trip
EXISTS (semi join)Left rows that have at least one partner, without bringing partner columnsNo, never"Which riders did X at least once?"3,905 riders completed a trip
NOT EXISTS (anti join)Left rows that have no partnerNo, never"Which riders never did X?"95 riders never completed one
Step-by-step: what sql/02_joins.sql does, in plain English
  1. Query 1 joins each trip to its city by matching t.city_id = c.city_id, then counts trips per city name. t and c are short nicknames (aliases) for the tables.
  2. Query 2 keeps every rider and attaches that rider's trips. COUNT(*) FILTER (WHERE t.trip_id IS NULL) counts the output rows where no trip was found.
  3. Query 3 asks, for each rider, whether a completed trip exists. NOT EXISTS (SELECT 1 ...) is true when the inner search comes back empty. The 1 is a placeholder: only the existence matters.
  4. Query 4 is the same question turned around with EXISTS.
sql/02_joins.sqlruns offline
-- INNER JOIN: only rows that match on both sides (every trip has a city).
SELECT c.name AS city, COUNT(*) AS trips
FROM trips t
JOIN cities c ON c.city_id = t.city_id
GROUP BY c.name
ORDER BY trips DESC;

-- LEFT JOIN: keep every rider, even those with no trip (their trip columns are NULL).
SELECT COUNT(*) AS rows_after_join,
       COUNT(*) FILTER (WHERE t.trip_id IS NULL) AS riders_with_no_trips
FROM riders r
LEFT JOIN trips t ON t.rider_id = r.rider_id;

-- ANTI join: riders who never completed a trip. NOT EXISTS says it in words.
SELECT COUNT(*) AS never_completed
FROM riders r
WHERE NOT EXISTS (
    SELECT 1 FROM trips t WHERE t.rider_id = r.rider_id AND t.status = 'completed'
);

-- SEMI join: riders who completed at least one trip. EXISTS never multiplies rows.
SELECT COUNT(*) AS completed_at_least_once
FROM riders r
WHERE EXISTS (
    SELECT 1 FROM trips t WHERE t.rider_id = r.rider_id AND t.status = 'completed'
);
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed identical rows)
[engine: duckdb]

>> SELECT c.name AS city, COUNT(*) AS trips FROM trips t JOIN cities c ON c.city_id = t.city_id GROUP BY c.name O
city       trips
---------  -----
Bengaluru  16296
Mumbai     14127
Delhi      13622
Hyderabad   7590
Chennai     4483
Pune        3882

>> SELECT COUNT(*) AS rows_after_join, COUNT(*) FILTER (WHERE t.trip_id IS NULL) AS riders_with_no_trips FROM rid
rows_after_join  riders_with_no_trips
---------------  --------------------
          60051                    51

>> SELECT COUNT(*) AS never_completed FROM riders r WHERE NOT EXISTS ( SELECT 1 FROM trips t WHERE t.rider_id = r
never_completed
---------------
             95

>> SELECT COUNT(*) AS completed_at_least_once FROM riders r WHERE EXISTS ( SELECT 1 FROM trips t WHERE t.rider_id
completed_at_least_once
-----------------------
                   3905
A riders LEFT JOIN trips 1 60,000 rows with a trip INNER JOIN keeps only these 60,000 2 51 extra rows: riders with no trip, trip columns NULL (LEFT JOIN: 60,051) B 4,000 riders: EXISTS or NOT EXISTS? 3 3,905 completed a trip (semi join) 4 95 never completed one (anti join) 51 of the 95 never even requested; the other 44 only cancelled or found no driver.
Fig. 1d.4 — The same riders and trips, seen through the four joins. Both bars are drawn to scale, which is why the coloured slices are thin.
  1. Matched pairs. After riders LEFT JOIN trips, the output has 60,051 rows. The long grey bar is the 60,000 rows where a rider met a trip. An INNER JOIN would stop here.
  2. The 51 orange rows. Riders who signed up and never requested a ride. A LEFT JOIN keeps them, with every trip column NULL. Notice that the row count is a pair count, not a rider count: this join already has more rows than riders (4,000).
  3. EXISTS. A semi join answers a yes-or-no question per rider, so it cannot multiply rows. 3,905 of the 4,000 riders completed at least one trip.
  4. NOT EXISTS. The 95 riders in the red slice never completed a trip. The anti join is the clean way to find missing things, such as customers with no orders.

Replay the bug on four toy trips

Now the dangerous case. Here is the smallest version of RideNow's payment problem: four trips with fares 100, 200, 150 and 80, and eight payment rows between them. Trip 2 had a failed card attempt before it succeeded. Trip 3 failed twice. Trip 4 was paid and then refunded in full. Do the arithmetic yourself before reading the output.

BE the join

Play the database. Two trips, four payment rows:

  1. Trip A, fare 60. Payments: attempt 1 failed, attempt 2 succeeded.
  2. Trip B, fare 40. Payments: attempt 1 succeeded, attempt 2 refunded.

Run SELECT SUM(t.fare) FROM trips t JOIN payments p ON p.trip_id = t.trip_id in your head. How many rows does the join produce, and what does it sum to? What should the gross fares be?

Check your answer

The join produces four rows, because each payment row finds its trip: A, A, B, B. The sum is 60 + 60 + 40 + 40 = 200. The gross fares are 60 + 40 = 100. The query returns exactly twice the truth, and nothing in it looks wrong. No error, no warning, just a bigger number.

Step-by-step: what sql/00_toy_fanout.sql does, in plain English
  1. CREATE TEMP TABLE makes two small tables that vanish when the connection closes, so they never touch the real data.
  2. INSERT INTO ... VALUES fills them: four trips and eight payment rows.
  3. The first SELECT joins them and prints all eight output rows so you can see each fare repeat.
  4. The second counts those rows and sums the fare: the broken revenue.
  5. The third first collapses payments to one row per trip with GROUP BY trip_id and conditional sums, then joins. The four trips stay four rows.
sql/00_toy_fanout.sqlruns offline
-- Four trips and their payment rows, small enough to add up with a pencil.
CREATE TEMP TABLE toy_trips (trip_id INTEGER, fare INTEGER);
INSERT INTO toy_trips VALUES (1, 100), (2, 200), (3, 150), (4, 80);
CREATE TEMP TABLE toy_pay (trip_id INTEGER, attempt_no INTEGER, status TEXT, amount INTEGER);
INSERT INTO toy_pay VALUES
  (1, 1, 'succeeded', 100),
  (2, 1, 'failed', 200), (2, 2, 'succeeded', 200),
  (3, 1, 'failed', 150), (3, 2, 'failed', 150), (3, 3, 'succeeded', 150),
  (4, 1, 'succeeded', 80), (4, 2, 'refunded', 80);

-- The broken join: one output row per payment row.
SELECT t.trip_id, t.fare, p.attempt_no, p.status
FROM toy_trips t JOIN toy_pay p ON p.trip_id = t.trip_id
ORDER BY t.trip_id, p.attempt_no;

SELECT COUNT(*) AS rows_after_join, SUM(t.fare) AS revenue_wrong
FROM toy_trips t JOIN toy_pay p ON p.trip_id = t.trip_id;

-- Collapse first, then join: one row per trip stays one row per trip.
SELECT COUNT(*) AS rows_after_join, SUM(t.fare) AS gross_fares, SUM(p.net) AS cash
FROM toy_trips t
JOIN (SELECT trip_id,
             SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END)
           - SUM(CASE WHEN status = 'refunded'  THEN amount ELSE 0 END) AS net
      FROM toy_pay GROUP BY trip_id) p ON p.trip_id = t.trip_id;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed the same numbers)
>> SELECT t.trip_id, t.fare, p.attempt_no, p.status FROM toy_trips t JOIN toy_pay p ON p.trip_id = t.trip_id ORDE
trip_id  fare  attempt_no  status
-------  ----  ----------  ---------
      1   100           1  succeeded
      2   200           1  failed
      2   200           2  succeeded
      3   150           1  failed
      3   150           2  failed
      3   150           3  succeeded
      4    80           1  succeeded
      4    80           2  refunded

>> SELECT COUNT(*) AS rows_after_join, SUM(t.fare) AS revenue_wrong FROM toy_trips t JOIN toy_pay p ON p.trip_id
rows_after_join  revenue_wrong
---------------  -------------
              8           1110

>> SELECT COUNT(*) AS rows_after_join, SUM(t.fare) AS gross_fares, SUM(p.net) AS cash FROM toy_trips t JOIN (SELE
rows_after_join  gross_fares  cash
---------------  -----------  ----
              4          530   450
toy_trips (4 rows) trip_id fare trip 1 100 trip 2 200 trip 3 150 trip 4 80 toy_pay (8 rows) trip attempt status 1 1 succeeded 2 1 failed 2 2 succeeded 3 1 failed 3 2 failed 3 3 succeeded 4 1 succeeded 4 2 refunded 1 JOIN after the join (8 rows) trip fare counted 1 100 2 200 2 200 3 150 3 150 3 150 4 80 4 80 2 red = the same fare, again 3 4 trips: 100 + 200 + 150 + 80 = 530 the true gross fares 8 rows: 100+200+200+150+150+150+80+80 = 1,110 (2.09 times too big)
Fig. 1d.5 — The fan-out on the toy data. Left: four trips. Middle: their eight payment rows. Right: what the join hands to SUM.
  1. One trip, several payment rows. The blue box around trip 3 spans three payment rows: two failures and one success. The database does not care which row is "the real" payment. It simply creates one output row per matching pair.
  2. The red copies. Trip 2's fare of 200 appears twice, trip 3's 150 three times, trip 4's 80 twice. Each red row is a copy that did not exist in the trips table. SUM adds them all.
  3. The totals. The trips table says 530. The joined rows say 1,110, which is 2.09 times too big. The error is not random noise. It is exactly "extra payment rows times fare".

Read the terminal output against the figure. The first query prints the eight joined rows, with fares 100, 200, 200, 150, 150, 150, 80, 80. The second query reports rows_after_join = 8 and revenue_wrong = 1110. The true gross fares are 530. This effect has a name, fan-out: a join from the "one" side of a relationship to the "many" side fans each row out into several.

The same bug on the real tables

Now we run the notebook's exact logic on RideNow's real data: join completed trips to payments and sum the fare. First, how many payment rows does each completed trip have? The answer is the size of the problem.

Step-by-step: what sql/03_fanout.sql does, in plain English
  1. Query 1 finds the first trip with a third payment attempt, and prints its fare next to each of its payment rows.
  2. Query 2 counts payment rows per completed trip with a LEFT JOIN, so trips with no payment still appear as zero, then counts how many trips fall in each size.
  3. Query 3 is the notebook's mistake: join, then sum the fare.
  4. Query 4 sums the fare from trips alone: one row per trip, so no multiplication.
  5. Query 5 fixes it. A CTE named paid adds up successful payments and subtracts refunds, one row per trip. Joining to that keeps 46,760 rows.
sql/03_fanout.sqlruns offline
-- One completed trip, three payment rows: failed, failed, succeeded (+ maybe refunded).
SELECT t.trip_id, t.fare, p.attempt_no, p.status, p.amount
FROM trips t
JOIN payments p ON p.trip_id = t.trip_id
WHERE t.trip_id = (SELECT trip_id FROM payments WHERE attempt_no = 3 ORDER BY trip_id LIMIT 1)
ORDER BY p.attempt_no;

-- How many payment rows does each completed trip have?
SELECT n_rows, COUNT(*) AS trips
FROM (SELECT t.trip_id, COUNT(p.payment_id) AS n_rows
      FROM trips t LEFT JOIN payments p ON p.trip_id = t.trip_id
      WHERE t.status = 'completed'
      GROUP BY t.trip_id) x
GROUP BY n_rows ORDER BY n_rows;

-- THE BUG: sum the fare after joining. Every extra payment row repeats the fare.
SELECT COUNT(*) AS rows_after_join, ROUND(SUM(t.fare), 2) AS revenue_wrong
FROM trips t
JOIN payments p ON p.trip_id = t.trip_id
WHERE t.status = 'completed';

-- The truth in the trips table alone: one row per trip.
SELECT COUNT(*) AS completed_trips, ROUND(SUM(fare), 2) AS gross_fares
FROM trips WHERE status = 'completed';

-- THE FIX: collapse payments to one row per trip BEFORE joining.
WITH paid AS (
    SELECT trip_id,
           SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END)
         - SUM(CASE WHEN status = 'refunded'  THEN amount ELSE 0 END) AS net_paid
    FROM payments
    GROUP BY trip_id
)
SELECT COUNT(*) AS rows_after_join, ROUND(SUM(t.fare), 2) AS gross_fares, ROUND(SUM(p.net_paid), 2) AS cash_collected
FROM trips t
LEFT JOIN paid p ON p.trip_id = t.trip_id
WHERE t.status = 'completed';
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed identical numbers)
[engine: duckdb]

>> SELECT t.trip_id, t.fare, p.attempt_no, p.status, p.amount FROM trips t JOIN payments p ON p.trip_id = t.trip_
trip_id  fare    attempt_no  status     amount
-------  ------  ----------  ---------  ------
    158  136.20           1  failed     115.77
    158  136.20           2  failed     115.77
    158  136.20           3  succeeded  115.77

>> SELECT n_rows, COUNT(*) AS trips FROM (SELECT t.trip_id, COUNT(p.payment_id) AS n_rows FROM trips t LEFT JOIN
n_rows  trips
------  -----
     0    697
     1  40569
     2   4703
     3    759
     4     32

>> SELECT COUNT(*) AS rows_after_join, ROUND(SUM(t.fare), 2) AS revenue_wrong FROM trips t JOIN payments p ON p.t
rows_after_join  revenue_wrong
---------------  -------------
          52380  11,226,811.56

>> SELECT COUNT(*) AS completed_trips, ROUND(SUM(fare), 2) AS gross_fares FROM trips WHERE status = 'completed'
completed_trips  gross_fares
---------------  -------------
          46760  10,016,889.57

>> WITH paid AS ( SELECT trip_id, SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END) - SUM(CASE WHEN stat
rows_after_join  gross_fares    cash_collected
---------------  -------------  --------------
          46760  10,016,889.57    9,280,083.74

Read it top to bottom. Trip 158 has three payment rows, each for 115.77 (a 136.20 fare after a 15% promo). Of the 46,760 completed trips, 40,569 have exactly one payment row, 4,703 have two, 759 have three and 32 have four. 697 completed trips have none: they were paid in cash outside the app, so an inner join silently drops them.

The notebook's join produces 52,380 rows from 46,760 trips, and its sum is 11,226,811.56. The honest gross fares are 10,016,889.57. The notebook invented 1,209,921.99 rupees. The fixed query, in the last block, joins 46,760 rows to 46,760 rows, and reports gross fares and cash collected side by side.

0 rows 697 1 row 40,569 2 rows 4,703 3 rows 759 4 rows 32 1 2 3 payment rows per completed trip
Fig. 1d.6 — How many payment rows each of the 46,760 completed trips has, from the real table. Only the first bar is "normal".
  1. The multiplied trips. 4,703 trips have two payment rows, 759 have three and 32 have four. These 5,494 trips (red) are where the join copies a fare. Every one of them adds at least one extra copy to the sum.
  2. The vanished trips. 697 trips have no payment row (orange), so an inner join drops them and removes their fares from the total.
  3. The normal case. 40,569 trips have exactly one row. The join treats them correctly, which is why the bug is easy to miss: 87% of trips look fine.
Collapse payments first, then join toy_pay: 8 rows trip 1: +100 trip 2: +200 (failed row ignored) trip 3: +150 (two failed ignored) trip 4: +80 and -80 refund GROUP BY trip_id paid: 1 row per trip trip 1: net 100 trip 2: net 200 trip 3: net 150 trip 4: net 0 1 JOIN trips JOIN paid: 4 rows trip 1 fare 100 net 100 trip 2 fare 200 net 200 trip 3 fare 150 net 150 trip 4 fare 80 net 0 2 3 SUM(fare) = 530 gross fares, as the trips table says SUM(net) = 450 cash collected: trip 4 was refunded in full
Fig. 1d.7 — The repair on the toy data: collapse the many side to one row per trip, then join.
  1. The collapsed table. GROUP BY trip_id turns eight payment rows into four. Failed attempts add 0, successes add their amount, refunds subtract. Trip 4's +80 and −80 net to 0.
  2. The join. Trips meets one-row-per-trip. Four rows go in on each side, four rows come out. A join cannot multiply rows when the right side has at most one row per key.
  3. Two different totals from the same four rows. Gross fares are 530, what riders were quoted. Net cash is 450, what the company kept. Neither is wrong. They answer different questions.

So which revenue number goes to the board?

Both of the honest numbers can go, as long as each carries its name. They are connected by a short bridge, and finance will ask for it: start at gross fares, remove what was never paid, remove promo discounts, remove refunds, and you land on the dashboard. The next query builds that bridge from the real tables.

sql/10_reconcile_bridge.sqlruns offline
-- A reconciliation bridge: walk from the number the analyst wanted to the number the dashboard shows.
WITH paid AS (
    SELECT trip_id,
           SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END) AS succeeded,
           SUM(CASE WHEN status = 'refunded'  THEN amount ELSE 0 END) AS refunded
    FROM payments GROUP BY trip_id
), done AS (
    SELECT t.trip_id, t.fare, COALESCE(p.succeeded, 0) AS succeeded, COALESCE(p.refunded, 0) AS refunded,
           (p.trip_id IS NULL) AS no_payment_row
    FROM trips t LEFT JOIN paid p ON p.trip_id = t.trip_id
    WHERE t.status = 'completed'
)
SELECT 'gross fares (sum of trips.fare)'              AS step, ROUND(SUM(fare), 2) AS rupees FROM done
UNION ALL SELECT '  minus trips with no payment row',          ROUND(-SUM(fare) FILTER (WHERE no_payment_row), 2) FROM done
UNION ALL SELECT '  minus promo discounts on paid trips',      ROUND(-SUM(fare - succeeded) FILTER (WHERE NOT no_payment_row), 2) FROM done
UNION ALL SELECT '= succeeded payments',                       ROUND(SUM(succeeded), 2) FROM done
UNION ALL SELECT '  minus refunds',                            ROUND(-SUM(refunded), 2) FROM done
UNION ALL SELECT '= cash collected (the dashboard)',           ROUND(SUM(succeeded - refunded), 2) FROM done;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 printed identical numbers)
>> WITH paid AS ( SELECT trip_id, SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END) AS succeeded, SUM(CA
step                                   rupees
-------------------------------------  -------------
gross fares (sum of trips.fare)        10,016,889.57
  minus trips with no payment row        -150,351.34
  minus promo discounts on paid trips    -319,121.75
= succeeded payments                    9,547,416.48
  minus refunds                          -267,332.74
= cash collected (the dashboard)        9,280,083.74

Read the bridge as a ledger. Gross fares of 10,016,889.57 lose 150,351.34 on the 697 trips with no payment row, and 319,121.75 to promo discounts, landing on 9,547,416.48 of successful payments. Refunds of 267,332.74 bring the final cash to 9,280,083.74, exactly the finance dashboard. Priya now has a defensible answer: the dashboard was right, the notebook was wrong, and the gap is fully explained.

"That is a pandas bug, not a SQL bug. Dev should have used the right tool."

— the SQL purist on the data team, right about now

The bug lives in the shape of the data, not in the tool. SQL's JOIN and pandas' merge multiply rows in exactly the same way, and 03_fanout.sql reproduced the notebook's number in pure SQL. Switching language fixes nothing.

What differs is the guard rail. Pandas has one built in: merge(..., validate="one_to_one") raises an error when the right side repeats keys, and pandas_fanout.py shows it firing. SQL has no such switch, so a SQL pipeline needs a data test instead. We build those tests in the pipeline section.

Questions you might be asking now

The fan-out is the idea of this chapter, so these four questions slow it down. Every answer reuses the same four toy trips from Fig. 1d.5: fares 100, 200, 150 and 80, with 1, 2, 3 and 2 payment rows.

What does "fan-out" actually mean? Is it a SQL feature?

No, it is not a feature. It is a side effect. Fan-out means one row on the left side of a join gets copied once for every matching row on the right. Nothing is wrong with the join. The surprise is in what you then do with the copies.

Count the copies on the toy data. A trip's fare is copied once for each of its payment rows:

  1. Trip 1. 1 payment row, so its fare 100 appears 1 time.
  2. Trip 2. 2 payment rows, so 200 appears 2 times, which adds 400.
  3. Trip 3. 3 payment rows, so 150 appears 3 times, which adds 450.
  4. Trip 4. 2 payment rows, so 80 appears 2 times, which adds 160.
  5. Add up. 100 + 400 + 450 + 160 = 1,110. The true total is 100 + 200 + 150 + 80 = 530.

The honest limit: fan-out is harmless when you only look at rows, and harmful when you sum or count a column from the "one" side. Counting trips after the join would also report 8 instead of 4.

Before you add up a column after a join, ask: could this row have been copied?

Would a LEFT JOIN instead of a plain JOIN avoid the problem?

No. A LEFT JOIN differs from an inner join only for left rows with no partner. Every toy trip has partners, so both give the same eight rows and the same 1,110.

The difference between the two shows up only when a trip has no payment. Add a fifth trip, fare 90, with no payment row:

  1. Inner join. Trip 5 finds no partner and disappears. 8 rows, sum 1,110. It also silently drops 90 rupees of real fare.
  2. Left join. Trip 5 stays once, with NULL payment columns. 9 rows, sum 1,200.
  3. Collapse first, then join. 5 rows, sum 620 gross. This is the right shape.
Step-by-step: what sql/12_toy_left_join.sql does, in plain English
  1. Build five toy trips (the fifth, fare 90, has no payments) and the eight payment rows of the first four.
  2. Run three queries glued with UNION ALL, which stacks their result rows: an inner join, a left join, and a join to a list of distinct paid trip ids.
  3. Each query reports how many rows came out and what SUM(fare) says.
sql/12_toy_left_join.sqlruns offline
-- Five toy trips; trip 5 (fare 90) has no payment row. Three strategies, one true answer (620).
CREATE TEMP TABLE toy_trips (trip_id INTEGER, fare INTEGER);
INSERT INTO toy_trips VALUES (1, 100), (2, 200), (3, 150), (4, 80), (5, 90);
CREATE TEMP TABLE toy_pay (trip_id INTEGER, attempt_no INTEGER, status TEXT, amount INTEGER);
INSERT INTO toy_pay VALUES
  (1, 1, 'succeeded', 100),
  (2, 1, 'failed', 200), (2, 2, 'succeeded', 200),
  (3, 1, 'failed', 150), (3, 2, 'failed', 150), (3, 3, 'succeeded', 150),
  (4, 1, 'succeeded', 80), (4, 2, 'refunded', 80);

SELECT 'INNER JOIN' AS strategy, COUNT(*) AS rows_out, SUM(t.fare) AS sum_fare
FROM toy_trips t JOIN toy_pay p ON p.trip_id = t.trip_id
UNION ALL
SELECT 'LEFT JOIN', COUNT(*), SUM(t.fare)
FROM toy_trips t LEFT JOIN toy_pay p ON p.trip_id = t.trip_id
UNION ALL
SELECT 'collapse, then LEFT JOIN', COUNT(*), SUM(t.fare)
FROM toy_trips t LEFT JOIN (SELECT DISTINCT trip_id FROM toy_pay) p ON p.trip_id = t.trip_id;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 identical)
>> SELECT 'INNER JOIN' AS strategy, COUNT(*) AS rows_out, SUM(t.fare) AS sum_fare FROM toy_trips t JOIN toy_pay p
strategy                  rows_out  sum_fare
------------------------  --------  --------
INNER JOIN                       8      1110
LEFT JOIN                        9      1200
collapse, then LEFT JOIN         5       620
Five toy trips (fares 100, 200, 150, 80, 90) under three strategies
StrategyRows outSUM(fare)True grossError
INNER JOIN payments81,110620+490 (copies) and trip 5 lost
LEFT JOIN payments91,200620+580 (copies)
Collapse, then LEFT JOIN5620620none

The real data has this too: 697 completed trips have no payment row, so the notebook's inner join dropped their fares while multiplying others.

The kind of join decides who survives; only the number of matches decides who is copied.

Can I just write SUM(DISTINCT fare) to remove the copies?

No, and it is the most tempting wrong fix. DISTINCT removes repeated values, not repeated rows. Two different trips with the same fare lose one of them, so you swap one error for another.

Use a different tiny table for this one: trips 1, 2 and 5 with fares 100, 200 and 100, where trip 1 has two payment rows. The true gross is 400. The block below ran on both engines:

sql/11_distinct_trap.sqlruns offline
-- The tempting wrong fix: SUM(DISTINCT fare) after the join.
-- Toy data: trips 1 and 5 both cost 100, and trip 1 has two payment rows.
CREATE TEMP TABLE toy_trips (trip_id INTEGER, fare INTEGER);
INSERT INTO toy_trips VALUES (1, 100), (2, 200), (5, 100);
CREATE TEMP TABLE toy_pay (trip_id INTEGER, attempt_no INTEGER, status TEXT);
INSERT INTO toy_pay VALUES (1, 1, 'failed'), (1, 2, 'succeeded'), (2, 1, 'succeeded'), (5, 1, 'succeeded');

SELECT SUM(fare) AS true_total FROM toy_trips;

SELECT SUM(t.fare)          AS plain_sum_after_join,
       SUM(DISTINCT t.fare) AS distinct_sum_after_join
FROM toy_trips t JOIN toy_pay p ON p.trip_id = t.trip_id;

-- Same trap on the real tables: two different completed trips with the same fare collapse into one.
SELECT ROUND(SUM(DISTINCT t.fare), 2) AS distinct_sum_real,
       (SELECT ROUND(SUM(fare), 2) FROM trips WHERE status = 'completed') AS true_gross
FROM trips t JOIN payments p ON p.trip_id = t.trip_id
WHERE t.status = 'completed';
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 identical)
>> SELECT SUM(fare) AS true_total FROM toy_trips
true_total
----------
       400

>> SELECT SUM(t.fare) AS plain_sum_after_join, SUM(DISTINCT t.fare) AS distinct_sum_after_join FROM toy_trips t J
plain_sum_after_join  distinct_sum_after_join
--------------------  -----------------------
                 500                      300

>> SELECT ROUND(SUM(DISTINCT t.fare), 2) AS distinct_sum_real, (SELECT ROUND(SUM(fare), 2) FROM trips WHERE statu
distinct_sum_real  true_gross
-----------------  -------------
     5,784,200.69  10,016,889.57
  1. Plain sum after the join. Trip 1's 100 is copied twice: 100 + 100 + 200 + 100 = 500. Too big by 100.
  2. DISTINCT sum after the join. The distinct values are 100 and 200, so the sum is 300. Too small by 100, because trips 1 and 5 both cost 100 and one was erased.
  3. On the real tables. SUM(DISTINCT fare) gives 5,784,200.69 against a true 10,016,889.57. It is off by 42%.

DISTINCT forgets values, not duplicates. Collapse the many side before joining instead.

Does pandas merge do the same thing as a SQL JOIN?

Yes. left.merge(right, on="trip_id") is an inner join and how="left" is a left join. Both multiply rows exactly as SQL does. The one real difference is that pandas lets you ask for a safety check.

The block below is pandas_fanout.py, which reproduces the notebook on the real CSV files and then shows the guard that would have caught it.

Step-by-step: what pandas_fanout.py does, in plain English
  1. Read the trips and payments CSV files and keep completed trips.
  2. Merge trips with payments on trip_id and sum the fare: the notebook's line.
  3. Count how many rows are extra copies with duplicated().
  4. Repeat the merge with validate="one_to_one". pandas checks the key in both tables and raises MergeError because payments repeats trip_id.
  5. Collapse payments to one row per trip, merge again with validate="one_to_one", and print gross and cash.
pandas_fanout.pyruns offline
# pip install pandas        (reads the CSV files make_db.py wrote; no database needed)
# Reproduces the analyst's notebook: why pandas said 11.2M and the dashboard said 9.3M.
from pathlib import Path

import pandas as pd

DATA = Path(__file__).parent / "data"
trips = pd.read_csv(DATA / "trips.csv", parse_dates=["requested_at"])
payments = pd.read_csv(DATA / "payments.csv")
done = trips[trips.status == "completed"]

# the notebook's line: merge the two tables, then sum the fare
merged = done.merge(payments, on="trip_id")
print(f"completed trips: {len(done):,}   rows after merge: {len(merged):,}")
print(f"notebook revenue (sum of fare after merge): {merged.fare.sum():,.2f}")
print(f"fares counted twice or more: {merged.trip_id.duplicated().sum():,} extra rows")

# the guard that would have caught it: ask pandas to check the relationship
try:
    done.merge(payments, on="trip_id", validate="one_to_one")
except pd.errors.MergeError as err:
    print("validate='one_to_one' says:", err)

# the fix: one row per trip BEFORE merging
net = (payments.assign(signed=payments.amount.where(payments.status == "succeeded", 0)
                                - payments.amount.where(payments.status == "refunded", 0))
               .groupby("trip_id", as_index=False).agg(cash_collected=("signed", "sum")))
fixed = done.merge(net, on="trip_id", how="left", validate="one_to_one")
print(f"gross fares of completed trips: {fixed.fare.sum():,.2f}")
print(f"cash collected (dashboard):     {fixed.cash_collected.sum():,.2f}")
terminalactual output · pandas 3.0.5
completed trips: 46,760   rows after merge: 52,380
notebook revenue (sum of fare after merge): 11,226,811.56
fares counted twice or more: 6,317 extra rows
validate='one_to_one' says: Merge keys are not unique in right dataset; not a one-to-one merge
Duplicates in right:
  trip_id
      11
      20
      27
      45
      61 ...
gross fares of completed trips: 10,016,889.57
cash collected (dashboard):     9,280,083.74

The notebook number, 11,226,811.56, matches the SQL reproduction digit for digit: the same bug in two languages. The merge guard names the problem in plain words: "Merge keys are not unique in right dataset". The fixed merge reports 10,016,889.57 gross and 9,280,083.74 cash, matching the SQL.

Same join, same bug, same fix. In pandas, add validate=; in SQL, add a data test.

Count the rows before the join.

Count the rows after it.

If the number grew, stop and look.

Collapse the many side first.

Then join, then sum.

Line 1 and 2: the 4 toy trips become 8 rows in Fig. 1d.5, marker 2. Line 3: 8 is more than 4, the alarm. Line 4: marker 1 in Fig. 1d.7, the GROUP BY that turns 8 rows into 4. Line 5: marker 2 there, four rows in and four out.

INNER / LEFT JOIN
Both can multiply rows. LEFT additionally keeps unmatched left rows with NULLs.
EXISTS / NOT EXISTS
Semi and anti joins: a yes/no test per left row, never multiplies.
Fan-out
One left row copied once per matching right row; SUM and COUNT then over-count.
The fix
Collapse the many side to one row per key (GROUP BY in a CTE), then join.
What does not fix it
A LEFT JOIN, or SUM(DISTINCT ...).
The guard rails
pandas: validate="one_to_one". SQL: a test that the result has one row per key.
RideNow numbers
Notebook 11,226,811.56; gross fares 10,016,889.57; cash collected 9,280,083.74.

05 · Building answers in stepsAggregates, CTEs and One Recursive Query

The fan-out is explained and Priya has her bridge. Her first question, trips and revenue per month, is now easy to state, but it takes two steps: label each trip with its month, then total each month. Writing two steps as one nested query is how SQL becomes unreadable. A CTE gives each step a name, and one special kind lets a query walk a chain of referrals.

A CTE (common table expression) is a named, temporary result you build first and query next, so a long question reads from top to bottom. A recursive CTE repeats itself to follow chains, such as who referred whom.

Aggregates in one pass, then a named first step

An aggregate function turns many values into one: COUNT, SUM, AVG, MIN, MAX. Adding FILTER (WHERE ...) after an aggregate makes it count or sum only the rows that pass its own test. That lets one query answer several questions at once: all requests, completed trips, and the cancelled share, from a single scan.

A CTE starts with WITH name AS ( ... ). Everything inside the brackets is an ordinary query. Afterwards, name behaves like a table that exists only for this statement. You have already seen one: the paid CTE that repaired the fan-out in the last section.

Step-by-step: what sql/04_aggregates_ctes.sql does, in plain English
  1. Query 1 scans trips once and computes four numbers: total requests, completed trips (counted with FILTER), the cancelled share as a percentage, and the average distance. 100.0 * forces decimal arithmetic, so 18.1 does not round to 18 or 0.
  2. Query 2 builds a CTE called monthly. DATE_TRUNC('month', requested_at) snaps every timestamp to the first day of its month. The CTE groups by that month and totals completed trips and fares. GROUP BY 1 means "group by the first selected column".
  3. The final SELECT of query 2 reads from monthly, converts the month to a plain date, rounds, and sorts.
  4. Query 3 chains two steps. per_rider counts completed trips for each rider. The next step puts each rider into a bucket with CASE WHEN (SQL's if/else) and counts riders per bucket.
sql/04_aggregates_ctes.sqlruns offline
-- Several aggregates in one pass. FILTER counts only the rows that match its condition.
SELECT COUNT(*)                                          AS requests,
       COUNT(*) FILTER (WHERE status = 'completed')      AS completed,
       ROUND(100.0 * COUNT(*) FILTER (WHERE status LIKE 'cancelled%') / COUNT(*), 1) AS cancel_pct,
       ROUND(AVG(distance_km), 2)                        AS avg_km
FROM trips;

-- A CTE (WITH ...) gives a query a name, so the next step reads top to bottom.
WITH monthly AS (
    SELECT DATE_TRUNC('month', requested_at) AS month,
           COUNT(*) FILTER (WHERE status = 'completed') AS completed,
           SUM(fare) AS gross_fares
    FROM trips
    GROUP BY 1
)
SELECT CAST(month AS DATE) AS month, completed, ROUND(gross_fares, 0) AS gross_fares
FROM monthly
ORDER BY month;

-- Two CTEs chained: first one row per rider, then bucket riders by trip count.
WITH per_rider AS (
    SELECT rider_id, COUNT(*) AS trips
    FROM trips WHERE status = 'completed'
    GROUP BY rider_id
)
SELECT CASE WHEN trips = 1 THEN '1 trip'
            WHEN trips <= 5 THEN '2-5 trips'
            WHEN trips <= 20 THEN '6-20 trips'
            ELSE '21+ trips' END AS rider_bucket,
       COUNT(*) AS riders
FROM per_rider
GROUP BY 1
ORDER BY MIN(trips);
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 identical)
[engine: duckdb]

>> SELECT COUNT(*) AS requests, COUNT(*) FILTER (WHERE status = 'completed') AS completed, ROUND(100.0 * COUNT(*)
requests  completed  cancel_pct  avg_km
--------  ---------  ----------  ------
   60000      46760       18.10    8.01

>> WITH monthly AS ( SELECT DATE_TRUNC('month', requested_at) AS month, COUNT(*) FILTER (WHERE status = 'complete
month       completed  gross_fares
----------  ---------  ------------
2026-01-01       2917    633,302.00
2026-02-01       3144    672,720.00
2026-03-01       4024    850,518.00
2026-04-01       4523    965,095.00
2026-05-01       5325  1,158,933.00
2026-06-01       5724  1,223,062.00
2026-07-01       6494  1,377,614.00
2026-08-01       7206  1,558,556.00
2026-09-01       7403  1,577,089.00

>> WITH per_rider AS ( SELECT rider_id, COUNT(*) AS trips FROM trips WHERE status = 'completed' GROUP BY rider_id
rider_bucket  riders
------------  ------
1 trip           150
2-5 trips        921
6-20 trips      2294
21+ trips        540

Query 1 reports 60,000 requests, 46,760 completed, and 18.10% cancelled by a rider or driver, with an average distance of 8.01 km. Query 2 is Priya's first board answer. Completed trips rise from 2,917 in January to 7,403 in September, and gross fares from 633,302 to 1,577,089 rupees. Growth is steady, with a flatter September.

Query 3 shows how the riders split: 150 riders took exactly one trip, 921 took two to five, 2,294 took six to twenty, and 540 took more than twenty. Most of the business comes from regulars, a fact the retention question in the lab will test directly.

A query that calls itself

Some data is a chain. In riders, referred_by holds the rider who invited you, and that rider may themselves have been invited. To follow the chain you would need a join for every level, and you do not know how many levels exist. A recursive CTE solves this by repeating its own step until nothing new appears.

It has three parts. The anchor is the starting rows. UNION ALL glues on the second part, the step, which joins the CTE to itself. The engine runs the anchor, then runs the step on the previous pass's rows, again and again, and stops when a pass returns zero rows. The smallest example counts from 1 to 5.

Step-by-step: what sql/05_recursive_cte.sql does, in plain English
  1. The counter: the anchor SELECT 1 produces one row, n = 1. The step SELECT n + 1 FROM counter WHERE n < 5 reads the previous row and adds one. When n reaches 5 the WHERE test fails, the pass returns nothing, and the recursion ends. Output: 1 to 5.
  2. The referral chain, query 1: the anchor selects riders nobody referred (referred_by IS NULL) and labels them depth 0. The step joins riders to the rows found in the previous pass, matching r.referred_by = c.rider_id, and adds 1 to the depth.
  3. The outer query counts how many riders were found at each depth.
  4. Query 2 keeps the family root (root_id) through every pass, then totals the people below each root and reports the five biggest families.
sql/05_recursive_cte.sqlruns offline
-- 0. The smallest recursive CTE: count 1 to 5. Anchor = the first row, step = "add one", stop when WHERE fails.
WITH RECURSIVE counter(n) AS (
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;

-- Referral chains: who brought whom. A recursive CTE has a starting query (the anchor),
-- UNION ALL, and a step query that joins back to the CTE itself, until no new rows appear.
WITH RECURSIVE chain AS (
    SELECT rider_id, referred_by, 0 AS depth, rider_id AS root_id
    FROM riders
    WHERE referred_by IS NULL                      -- anchor: riders nobody referred
    UNION ALL
    SELECT r.rider_id, r.referred_by, c.depth + 1, c.root_id
    FROM riders r
    JOIN chain c ON r.referred_by = c.rider_id     -- step: riders referred by someone already in chain
)
SELECT depth, COUNT(*) AS riders
FROM chain
GROUP BY depth
ORDER BY depth;

-- The biggest referral family: root rider and everyone below them.
WITH RECURSIVE chain AS (
    SELECT rider_id, 0 AS depth, rider_id AS root_id FROM riders WHERE referred_by IS NULL
    UNION ALL
    SELECT r.rider_id, c.depth + 1, c.root_id FROM riders r JOIN chain c ON r.referred_by = c.rider_id
)
SELECT root_id, COUNT(*) - 1 AS people_below, MAX(depth) AS deepest
FROM chain
GROUP BY root_id
ORDER BY people_below DESC, root_id
LIMIT 5;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 identical rows)
[engine: duckdb]

>> WITH RECURSIVE counter(n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM counter WHERE n < 5 ) SELECT n FROM counte
n
-
1
2
3
4
5

>> WITH RECURSIVE chain AS ( SELECT rider_id, referred_by, 0 AS depth, rider_id AS root_id FROM riders WHERE refe
depth  riders
-----  ------
    0    3008
    1     743
    2     186
    3      43
    4      16
    5       4

>> WITH RECURSIVE chain AS ( SELECT rider_id, 0 AS depth, rider_id AS root_id FROM riders WHERE referred_by IS NU
root_id  people_below  deepest
-------  ------------  -------
     52            22        5
      2            13        3
     45            10        5
     79             9        4
     51             8        5
How the engine runs it anchor: riders where referred_by IS NULL pass 0 returns 3,008 rows 1 step: riders whose referred_by is a rider found in the previous pass repeat, each pass uses the last pass's rows 2 stop when a pass returns 0 rows pass 6 returns nothing: done 3 Riders found in each pass: the pass number is the referral depth pass 0 3,008 pass 1 743 pass 2 186 pass 3 43 pass 4 16 pass 5 4
Fig. 1d.8 — The referral recursion run for real. Left: the three parts of a recursive CTE. Right: how many riders each pass found.
  1. The anchor. Pass 0 returns the 3,008 riders nobody referred. This part has no reference to the CTE itself, so it runs exactly once.
  2. The step. Pass 1 joins riders to those 3,008 and finds 743 who were referred by one of them. Pass 2 uses the 743 to find 186 more, and so on: 43, 16, then 4. The loop arrow on the left is that repetition. The pass number is the rider's depth in the referral chain.
  3. The stop. Pass 6 finds nobody whose referrer was among the 4 riders of pass 5, so it returns zero rows and the recursion ends. The totals 3,008 + 743 + 186 + 43 + 16 + 4 add up to all 4,000 riders.

Read query 2's output beside the figure. Rider 52 started the largest family: 22 people below them, going five hops deep. Rider 2 has 13 people below. The honest warning: a recursive CTE on data with a loop (A referred B, B referred A) never terminates. PostgreSQL and DuckDB will run until you stop them, so real queries add a depth limit such as WHERE depth < 20.

Aggregate
Many values in, one out: COUNT, SUM, AVG, MIN, MAX.
FILTER (WHERE ...)
Restricts one aggregate to the rows passing its own test. Works the same in DuckDB and PostgreSQL.
CASE WHEN ... THEN ... END
SQL's if/else inside a query.
CTE
WITH name AS (query): a named step you can read like a table, for this statement only.
Recursive CTE
Anchor, UNION ALL, step. Repeats the step on the previous pass until a pass returns nothing.
The danger
A cycle in the data makes recursion endless. Add a depth limit.
RideNow numbers
2,917 trips in January, 7,403 in September; 3,008 anchor riders, 4 at depth 5.

06 · Comparing a row with its neighboursWindow Functions

Questions 4, 5 and 6 on Priya's list all compare a row with other rows: the top three drivers in each city, this month against last month, today against the average of the last week. GROUP BY cannot do this, because it throws the rows away to make totals. We need a tool that keeps every row and adds a column computed from its neighbours.

A window function adds a new column to every row, calculated from a group of related rows (the window), without collapsing anything. Without it you would need a self-join for every "compared with the previous row" question.

Six rows you can check with a pencil

Before real data, use six rows: trips per day for two cities over three days. Delhi had 30, 28 and 35. Pune had 10, 14 and 12. The query below adds six window columns to these rows. Every one has the same shape, function(...) OVER (...), and the part inside OVER decides which rows the function can see.

You have not been taught OVER, PARTITION BY or ROWS BETWEEN yet. The next figure draws each of them on these six rows, and the questions after it answer the usual confusions. Read the output first, then the figure.

Step-by-step: what sql/08_toy_windows.sql does, in plain English
  1. Create a temporary daily table of six rows: city, day number, trips.
  2. ROW_NUMBER() OVER (PARTITION BY city ORDER BY day) numbers the rows 1, 2, 3 inside each city. PARTITION BY splits the rows into separate windows, one per city. ORDER BY says what "previous" means.
  3. LAG(trips) returns the value from the previous row in the same window, or NULL on the first row.
  4. SUM(trips) OVER (PARTITION BY city ORDER BY day) adds up the trips from the first day to the current day: a running total.
  5. AVG(trips) OVER (... ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) averages only this row and the one before it. That is a frame: a moving window inside the window.
  6. SUM(trips) OVER (PARTITION BY city) with no ORDER BY adds the whole city. OVER () adds everything.
sql/08_toy_windows.sqlruns offline
-- Six rows: three days in two cities. Every window result below can be checked by hand.
CREATE TEMP TABLE daily (city TEXT, day INTEGER, trips INTEGER);
INSERT INTO daily VALUES ('Pune', 1, 10), ('Pune', 2, 14), ('Pune', 3, 12),
                         ('Delhi', 1, 30), ('Delhi', 2, 28), ('Delhi', 3, 35);

SELECT city, day, trips,
       ROW_NUMBER() OVER (PARTITION BY city ORDER BY day)                                   AS n,
       LAG(trips)   OVER (PARTITION BY city ORDER BY day)                                   AS prev_day,
       SUM(trips)   OVER (PARTITION BY city ORDER BY day)                                   AS running,
       AVG(trips)   OVER (PARTITION BY city ORDER BY day ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS avg_2day,
       SUM(trips)   OVER (PARTITION BY city)                                                AS city_total,
       SUM(trips)   OVER ()                                                                 AS all_total
FROM daily
ORDER BY city, day;
terminalactual output · engine: DuckDB 1.5 (PostgreSQL 18 identical values)
>> SELECT city, day, trips, ROW_NUMBER() OVER (PARTITION BY city ORDER BY day) AS n, LAG(trips) OVER (PARTITION B
city   day  trips  n  prev_day  running  avg_2day  city_total  all_total
-----  ---  -----  -  --------  -------  --------  ----------  ---------
Delhi    1     30  1  NULL           30     30.00          93        129
Delhi    2     28  2        30       58     29.00          93        129
Delhi    3     35  3        28       93     31.50          93        129
Pune     1     10  1  NULL           10     10.00          36        129
Pune     2     14  2        10       24     12.00          36        129
Pune     3     12  3        14       36     13.00          36        129
city day trips n prev_day running avg_2day window columns computed per row Delhi 1 30 1 NULL 30 30.0 Delhi 2 28 2 30 58 29.0 Delhi 3 35 3 28 93 31.5 Pune 1 10 1 NULL 10 10.0 Pune 2 14 2 10 24 12.0 Pune 3 12 3 14 36 13.0 1 2 3 4 PARTITION BY city: two separate windows frame: this row and the one before it, so (28 + 35) / 2 LAG(trips): the row above day 2's 28 appears in day 3's prev_day running: 30, 30+28, 30+28+35 restarts at the Pune partition Same six rows in, same six rows out: a window function adds columns, it never removes rows.
Fig. 1d.9 — The six toy rows with their window columns. Six rows go in and six come out; the dashed blue boxes are the two windows.
  1. PARTITION BY city. The two dashed boxes are the two windows. Delhi's rows never see Pune's. The Pune running total restarts at 10 instead of continuing from Delhi's 93.
  2. The frame. For Delhi day 3, the orange box covers this row (35) and one row before it (28). The average is (28 + 35) / 2 = 31.5, circled at the right. Day 1 has no row before it, so its average is just 30.
  3. LAG. Delhi day 3's prev_day is 28, the value from day 2. LAG is how "this month versus last month" is written without a self-join.
  4. The running total. Delhi: 30, then 30 + 28 = 58, then 58 + 35 = 93. With ORDER BY inside OVER, SUM means "added up so far".

Compare with GROUP BY. GROUP BY city would return two rows, Delhi 93 and Pune 36. The window version returns all six rows and writes 93 or 36 beside each one (the city_total column). That one difference is why window functions exist: you keep the detail and gain the comparison.

Sharpen your pencil

Month-over-month growth is (this month − last month) / last month × 100. Bengaluru's gross fares were 177,139 in January, 192,322 in February and 231,395 in March. Compute the growth percentage for February and March, to one decimal place, before opening the answer.

MonthGrowth % (to 1 decimal)
February: (192,322 − 177,139) / 177,139 × 100
March: (231,395 − 192,322) / 192,322 × 100
Check your answers
February: (192,322 − 177,139) / 177,139 × 10015,183 / 177,139 = 0.0857, so 8.6%
March: (231,395 − 192,322) / 192,322 × 10039,073 / 192,322 = 0.2032, so 20.3%

These are the first two rows of the growth_pct column in the real output below. The SQL does the same subtraction, with LAG(fares) supplying "last month".

Questions you might be asking now

Window functions confuse almost everyone for a day. These four answers reuse the six rows from Fig. 1d.9: Delhi 30, 28, 35 and Pune 10, 14, 12.

Is PARTITION BY just GROUP BY under another name?

They split rows into the same groups, but GROUP BY then replaces each group with one row, and PARTITION BY keeps every row and only decides which rows a window function may look at.

The same six rows through GROUP BY and through PARTITION BY
GROUP BY citySUM(trips) OVER (PARTITION BY city)
Rows in66
Rows out2 (Delhi, Pune)6 (every original row)
Delhi's value93, once93 beside each of three Delhi rows
Pune's value36, once36 beside each of three Pune rows
Can still show day?No, the day column is goneYes, the detail is kept

GROUP BY shrinks the table. PARTITION BY keeps it and annotates it.

Which rows are inside "ROWS BETWEEN 1 PRECEDING AND CURRENT ROW"? Compute it by hand.

The current row plus the one row directly before it, in the order given by ORDER BY, and never outside its partition. At the first row of a partition there is no row before, so the frame has just one row.

  1. Delhi day 1. Frame: day 1 only (nothing before it). Average of 30 is 30.0.
  2. Delhi day 2. Frame: days 1 and 2, values 30 and 28. Sum 58, divided by 2 is 29.0.
  3. Delhi day 3. Frame: days 2 and 3, values 28 and 35. Sum 63, divided by 2 is 31.5. Day 1 has dropped out.
  4. Pune day 1. The partition changed, so the frame restarts. Frame: Pune day 1 only. Average 10.0. Delhi day 3's 35 is not in it.

The real query in this section uses ROWS BETWEEN 6 PRECEDING AND CURRENT ROW: seven rows, so a 7-day moving average. For the first six days of the data it averages fewer than seven rows, which is why the early values in the real output wobble.

A frame is "this row and the N rows before it", counted inside the partition.

Why does RANK jump from 1 straight to 5? Did it skip numbers by mistake?

No mistake. RANK mimics a race: four runners tie for first, so nobody is second, third or fourth, and the next runner finishes fifth. DENSE_RANK gives the next runner second place instead. ROW_NUMBER refuses to tie at all.

The ties are in the real data: four Bengaluru drivers have a perfect 5.00 rating. Fig. 1d.10 shows what each function says about them.

Three ranking functions on the same eight ratings (sql/06_window_functions.sql, query 1)
FunctionFour drivers at 5.00 getThe 4.96 driver getsUse it when
ROW_NUMBER()1, 2, 3, 4 (ties broken arbitrarily)5You need exactly N rows, such as "top 3 per city"
RANK()1, 1, 1, 15 (positions skipped)Competition-style placing, where ties share a place
DENSE_RANK()1, 1, 1, 12 (no gaps)"Second-highest rating" questions

The honest warning: with ROW_NUMBER, the tie-break matters. The query orders by rating DESC, driver_id, so the same four drivers are numbered the same way every run. Without the second sort key the database may pick any order, and "top 3" could change between runs.

Ties share a rank in RANK and DENSE_RANK, never in ROW_NUMBER.

What changes if I leave ORDER BY out of the OVER clause?

The window stops being "up to this row" and becomes the whole partition. Delhi's SUM then returns 93 on all three rows instead of 30, 58 and 93. ORDER BY is what turns a total into a running total.

  1. With ORDER BY day. Delhi running totals: 30, 58, 93.
  2. Without ORDER BY. No order means no "so far", so every row sees all of Delhi: 93, 93, 93. That is the city_total column in the output.
  3. With no PARTITION BY either. OVER () sees all six rows: 129 beside every row (the all_total column).

One subtle rule: when you write ORDER BY but no frame, the default frame runs from the start of the partition to the current row, and rows that tie on the ORDER BY value are treated as one. On the toy data the days are all different, so the difference never shows. State the frame explicitly (ROWS BETWEEN ...) whenever ties are possible.

PARTITION BY chooses the groups. ORDER BY chooses the order inside them. The frame chooses how far back.

The same tools on RideNow

The real query block has three parts. The first ranks Bengaluru's drivers by rating. The second computes Bengaluru's month-over-month growth with LAG. The third builds a running total and a 7-day moving average of completed trips for the last eleven days of September.

Step-by-step: what sql/06_window_functions.sql does, in plain English
  1. Query 1 keeps rated drivers in city 1 and numbers them three ways by rating. The first ORDER BY inside OVER has a second key, driver_id, to make ROW_NUMBER repeatable.
  2. Query 2 builds a CTE of fares per city and month. Then LAG(fares) OVER (PARTITION BY city_id ORDER BY month) fetches last month's fares. Growth is the difference divided by last month, times 100. The first month has no previous row, so it prints NULL.
  3. Query 3 counts completed trips per day for 20 to 30 September. The running total uses ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the very first row to this one. The moving average uses 6 PRECEDING.
sql/06_window_functions.sqlruns offline
-- A window function keeps every row and adds a column computed over a "window" of related rows.
-- 1. Three ways to number the same ratings: ties are where they differ.
SELECT driver_id, rating,
       ROW_NUMBER() OVER (ORDER BY rating DESC, driver_id) AS row_number,
       RANK()       OVER (ORDER BY rating DESC)            AS rank,
       DENSE_RANK() OVER (ORDER BY rating DESC)            AS dense_rank
FROM drivers
WHERE city_id = 1 AND rating IS NOT NULL
ORDER BY rating DESC, driver_id
LIMIT 8;

-- 2. LAG looks one row back inside each partition (here: the previous month).
WITH monthly AS (
    SELECT city_id, CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month, SUM(fare) AS fares
    FROM trips WHERE status = 'completed' GROUP BY 1, 2
)
SELECT month, ROUND(fares, 0) AS fares,
       ROUND(LAG(fares) OVER (PARTITION BY city_id ORDER BY month), 0) AS prev_month,
       ROUND(100.0 * (fares - LAG(fares) OVER (PARTITION BY city_id ORDER BY month))
             / LAG(fares) OVER (PARTITION BY city_id ORDER BY month), 1) AS growth_pct
FROM monthly
WHERE city_id = 1
ORDER BY month;

-- 3. Running total and 7-day moving average. The FRAME says which rows count.
WITH daily AS (
    SELECT CAST(requested_at AS DATE) AS day, COUNT(*) AS trips
    FROM trips WHERE status = 'completed' AND requested_at >= '2026-09-20'
    GROUP BY 1
)
SELECT day, trips,
       SUM(trips) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
       ROUND(AVG(trips) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 1) AS avg_7d
FROM daily
ORDER BY day;
terminalactual output · engine: DuckDB 1.5
[engine: duckdb]

>> SELECT driver_id, rating, ROW_NUMBER() OVER (ORDER BY rating DESC, driver_id) AS row_number, RANK() OVER (ORDE
driver_id  rating  row_number  rank  dense_rank
---------  ------  ----------  ----  ----------
       42    5.00           1     1           1
      173    5.00           2     1           1
      200    5.00           3     1           1
      266    5.00           4     1           1
      165    4.96           5     5           2
      158    4.88           6     6           3
      121    4.87           7     7           4
      106    4.86           8     8           5

>> WITH monthly AS ( SELECT city_id, CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month, SUM(fare) AS fares
month       fares       prev_month  growth_pct
----------  ----------  ----------  ----------
2026-01-01  177,139.00  NULL        NULL
2026-02-01  192,322.00  177,139.00        8.60
2026-03-01  231,395.00  192,322.00       20.30
2026-04-01  258,677.00  231,395.00       11.80
2026-05-01  314,401.00  258,677.00       21.50
2026-06-01  326,069.00  314,401.00        3.70
2026-07-01  357,107.00  326,069.00        9.50
2026-08-01  428,607.00  357,107.00       20.00
2026-09-01  428,051.00  428,607.00       -0.10

>> WITH daily AS ( SELECT CAST(requested_at AS DATE) AS day, COUNT(*) AS trips FROM trips WHERE status = 'complet
day         trips  running_total  avg_7d
----------  -----  -------------  ------
2026-09-20    311            311  311.00
2026-09-21    227            538  269.00
2026-09-22    221            759  253.00
2026-09-23    244           1003  250.80
2026-09-24    259           1262  252.40
2026-09-25    236           1498  249.70
2026-09-26    289           1787  255.30
2026-09-27    303           2090  254.10
2026-09-28    242           2332  256.30
2026-09-29    242           2574  259.30
2026-09-30    237           2811  258.30
driver_id rating ROW_NUMBER RANK DENSE_RANK 42 5.00 1 1 1 173 5.00 2 1 1 200 5.00 3 1 1 266 5.00 4 1 1 165 4.96 5 5 2 158 4.88 6 6 3 121 4.87 7 7 4 106 4.86 8 8 5 1 2 four drivers tie at 5.00: ROW_NUMBER breaks the tie arbitrarily (by driver_id here) RANK skips: four people share place 1, so the next is place 5. DENSE_RANK does not skip: 2. Real rows: the first eight rated drivers in Bengaluru (city 1). Printed by sql/06_window_functions.sql.
Fig. 1d.10 — Query 1 of the real output, drawn with its ties. The same eight drivers get three different numberings.
  1. The tie. Four drivers (42, 173, 200 and 266) share a 5.00 rating. ROW_NUMBER gives them 1 to 4 by driver id. RANK and DENSE_RANK both give all four a 1.
  2. The jump. Driver 165 (4.96) is fifth person in line, so RANK says 5. DENSE_RANK counts distinct ratings, so it says 2. The orange box is the one cell where the two functions disagree.

Read query 2 with the growth column in mind. Bengaluru grew 8.6% in February and 20.3% in March, matching your pencil work. It slowed to 3.7% in June, then jumped 20.0% in August, and in September it dipped by 0.1%. Query 3 shows the moving average settling around 250 to 260 trips a day. The raw count swings between 221 and 311, and the 7-day average flattens that swing so a trend is visible.

One dialect surprise showed up here. In the third query the running total prints as 1003 in DuckDB but 1,003.00 in the PostgreSQL run: PostgreSQL's SUM of a whole number returns a numeric type, DuckDB's returns an integer. The values are equal. It matters when you compare results exactly, so cast (CAST(x AS BIGINT)) when types must match.

Window function
function(...) OVER (...): adds a column per row, computed from related rows, keeps every row.
PARTITION BY
Splits rows into separate windows. Without it, the window is the whole table.
ORDER BY inside OVER
Defines "previous" and "so far". Without it a SUM is the whole partition.
Frame
ROWS BETWEEN n PRECEDING AND CURRENT ROW: how many rows back the function may read.
ROW_NUMBER / RANK / DENSE_RANK
Unique numbers / ties share, gaps follow / ties share, no gaps.
LAG / LEAD
The value from the previous / next row in the window. NULL at the edge.
Leak warning
For model features, a frame that includes CURRENT ROW includes the answer. Use 1 PRECEDING as the frame end instead.

07 · Making it fast, keeping it correctIndexes, EXPLAIN and a Paragraph on Transactions

The eight answers are correct, but Priya's team also wants a support screen: type a rider id, see that rider's trips instantly. On 60,000 rows nothing is slow. On the full history, one million rows or ten, the same query would crawl. We will measure the crawl, fix it with one line, and learn to read the evidence the database gives us.

An index is a sorted side-list that lets the database jump straight to the rows you asked for instead of reading the whole table. Without one, a lookup in a table ten times bigger takes ten times longer.

The phone-book idea, then a measurement

Finding "Nair" in a phone book is quick because the book is sorted. Finding everyone who lives on Church Street is not: you must read every page. A table with no index is the second case. To find rider 1234's trips, the database must read every row and keep the matches. This is a sequential scan. An index on rider_id is a sorted list of rider ids, each with the address of its rows, so the lookup becomes the first case.

To make the difference visible we need more than 60,000 rows. The script below makes a one-million-row table inside PostgreSQL, runs the lookup, creates the index, and runs the lookup again. It uses EXPLAIN (ANALYZE, BUFFERS), which runs the query and reports the plan the database chose, the time it really took, and how many 8 KB pages it touched.

Step-by-step: what index_demo.py does, in plain English
  1. Connect to PostgreSQL and drop any old trip_log table.
  2. setseed(0.42) makes random() repeatable. generate_series(1, 1000000) produces a million numbers, and each becomes a row with a random rider id from 1 to 20,000 and a random fare. About 50 rows belong to each rider.
  3. ANALYZE refreshes the planner's statistics, so it chooses a plan on facts.
  4. explain() runs EXPLAIN (ANALYZE, BUFFERS) five times and keeps the fastest, which removes one-off noise from a cold cache.
  5. It measures once, runs CREATE INDEX ... ON trip_log (rider_id), refreshes statistics, measures again, and prints the ratio.
  6. The --engine sqlite path does the same on SQLite from Python's standard library, so you can reproduce the lesson with no server.
index_demo.pyneeds PostgreSQL (docker) — the sqlite path runs offline
"""One measured before/after for an index.  Table: 1,000,000 synthetic trip rows.
Question: "show me one rider's trips" (WHERE rider_id = 1234).

usage: python index_demo.py --engine postgres   # needs the docker container from the README
       python index_demo.py --engine sqlite     # offline stand-in, standard library only
"""
import argparse
import random
import sqlite3
import time

from db import connect

N = 1_000_000
QUERY = "SELECT trip_id, fare FROM trip_log WHERE rider_id = 1234"


def postgres() -> None:
    con = connect("postgres")
    cur = con.cursor()
    cur.execute("DROP TABLE IF EXISTS trip_log")
    # setseed makes random() repeatable; 20,000 riders so one rider has about 50 rows
    cur.execute("SELECT setseed(0.42)")
    cur.execute(f"""CREATE TABLE trip_log AS
        SELECT g AS trip_id, 1 + floor(random() * 20000)::int AS rider_id,
               round((50 + random() * 400)::numeric, 2) AS fare
        FROM generate_series(1, {N}) g""")
    cur.execute("ANALYZE trip_log")

    def explain(label):
        best, plan = None, None
        for _ in range(5):
            cur.execute("EXPLAIN (ANALYZE, BUFFERS) " + QUERY)
            lines = [r[0] for r in cur.fetchall()]
            ms = float([l for l in lines if l.startswith("Execution Time")][0].split()[2])
            if best is None or ms < best:
                best, plan = ms, lines
        print(f"\n--- {label}: best of 5 = {best:.3f} ms ---")
        for l in plan:
            print(l)
        return best

    before = explain("BEFORE (no index)")
    cur.execute("CREATE INDEX idx_trip_log_rider ON trip_log (rider_id)")
    cur.execute("ANALYZE trip_log")
    after = explain("AFTER  CREATE INDEX ... (rider_id)")
    print(f"\nspeed-up: {before / after:,.0f}x")


def sqlite() -> None:
    con = sqlite3.connect(":memory:")
    rnd = random.Random(42)
    con.execute("CREATE TABLE trip_log (trip_id INTEGER PRIMARY KEY, rider_id INTEGER, fare REAL)")
    con.executemany("INSERT INTO trip_log VALUES (?,?,?)",
                    ((i, rnd.randint(1, 20000), round(50 + rnd.random() * 400, 2)) for i in range(1, N + 1)))

    def explain(label):
        plan = [r[3] for r in con.execute("EXPLAIN QUERY PLAN " + QUERY)]
        best = min(_time(con) for _ in range(5))
        print(f"\n--- {label}: best of 5 = {best:.3f} ms ---")
        for p in plan:
            print(p)
        return best

    before = explain("BEFORE (no index)")
    con.execute("CREATE INDEX idx_trip_log_rider ON trip_log (rider_id)")
    after = explain("AFTER  CREATE INDEX ... (rider_id)")
    print(f"\nspeed-up: {before / after:,.0f}x")


def _time(con) -> float:
    t = time.perf_counter()
    con.execute(QUERY).fetchall()
    return (time.perf_counter() - t) * 1000


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--engine", choices=["postgres", "sqlite"], default="sqlite")
    {"postgres": postgres, "sqlite": sqlite}[ap.parse_args().engine]()
terminalactual output · engine: PostgreSQL 18 (docker postgres:18-alpine)
--- BEFORE (no index): best of 5 = 22.369 ms ---
Gather  (cost=1000.00..11653.43 rows=51 width=10) (actual time=1.374..22.328 rows=52.00 loops=1)
  Workers Planned: 2
  Workers Launched: 2
  Buffers: shared hit=2868 read=2572
  ->  Parallel Seq Scan on trip_log  (cost=0.00..10648.33 rows=21 width=10) (actual time=0.699..15.538 rows=17.33 loops=3)
        Filter: (rider_id = 1234)
        Rows Removed by Filter: 333316
        Buffers: shared hit=2868 read=2572
Planning Time: 0.069 ms
Execution Time: 22.369 ms

--- AFTER  CREATE INDEX ... (rider_id): best of 5 = 0.072 ms ---
Bitmap Heap Scan on trip_log  (cost=4.82..194.64 rows=51 width=10) (actual time=0.020..0.040 rows=52.00 loops=1)
  Recheck Cond: (rider_id = 1234)
  Heap Blocks: exact=52
  Buffers: shared hit=55
  ->  Bitmap Index Scan on idx_trip_log_rider  (cost=0.00..4.81 rows=51 width=0) (actual time=0.014..0.014 rows=52.00 loops=1)
        Index Cond: (rider_id = 1234)
        Index Searches: 1
        Buffers: shared hit=3
Planning Time: 0.021 ms
Execution Time: 0.072 ms

speed-up: 311x
terminalactual output · engine: SQLite (offline stand-in; plan wording differs)
--- BEFORE (no index): best of 5 = 35.763 ms ---
SCAN trip_log

--- AFTER  CREATE INDEX ... (rider_id): best of 5 = 0.037 ms ---
SEARCH trip_log USING INDEX idx_trip_log_rider (rider_id=?)

speed-up: 960x
BEFORE: no index Parallel Seq Scan on trip_log reads all 1,000,000 rows, three workers throws away 999,948 of them buffers touched: 5,440 pages Execution Time: 22.369 ms 1 AFTER: CREATE INDEX ON trip_log (rider_id) Bitmap Index Scan, then Bitmap Heap Scan the index lists the 52 matching row addresses only those 52 rows are fetched buffers touched: 55 pages Execution Time: 0.072 ms 2 Time on one scale (milliseconds) no index 22.369 ms with index 0.072 ms 3 311 times faster, and the gap grows with the table: the scan reads everything, the index reads 52 rows.
Fig. 1d.11 — The two PostgreSQL plans above, in words and on one time scale. The numbers are the ones printed in the terminal output.
  1. Before: a parallel sequential scan. Three workers read the whole table, 5,440 pages in total, test every row against rider_id = 1234, and throw away 999,948 rows to keep 52. The plan says Rows Removed by Filter: 333316 per worker. It finished in 22.369 ms.
  2. After: a bitmap index scan. The index (3 pages) lists where the 52 matching rows live, then only those pages are fetched (55 pages in all). The plan names the index, idx_trip_log_rider, so you can see it was used. It took 0.072 ms.
  3. The ratio. 311 times faster. It was 960 times faster on SQLite, which has no parallel workers to soften the scan. Treat the exact ratio as a property of this run on this laptop. The shape is what to trust: the scan grows with the table, the index lookup barely does.

Read the plans like a receipt. cost= is the planner's own estimate in arbitrary units, used to choose between plans. actual time= is what really happened. Buffers: shared hit=55 counts pages found in memory. If the estimated and the actual row counts differ by a large factor, statistics are stale: run ANALYZE. DuckDB, built for scanning whole columns fast, rarely needs this tool, which is why the index demo targets PostgreSQL.

The arithmetic behind "3 pages instead of 5,440" — optional depth

An index is stored as a tree (a B-tree). Each page of the tree holds many keys, and each key points to a child page. Looking up one value walks from the root down one page per level. The number of levels is roughly the logarithm of the row count, using the page's key capacity as the base.

d ≈ ⌈ logf N ⌉

Symbol key: d (depth) is the number of tree levels to walk, which is also the number of pages read to find the key; ⌈ ⌉ means round up to the next whole number; logf N is "how many times must you multiply f together to reach N"; N is the number of rows, here 1,000,000; f (fan-out) is how many keys fit on one page, a few hundred for a small integer key.

With f ≈ 300: log300 1,000,000 = ln 1,000,000 / ln 300 = 13.8 / 5.7 ≈ 2.4, rounded up to 3. The plan reported Buffers: shared hit=3 for the index scan: three pages, as predicted. A table ten times bigger, 10,000,000 rows, needs log300 10,000,000 ≈ 2.8, still 3 levels. The sequential scan would read ten times more pages. That is the whole argument for indexes.

The cost: every INSERT, UPDATE or DELETE must also update the tree, so each extra index slows writes and uses disk. Index the columns you filter or join on (foreign keys are the usual suspects), not every column.

"Indexes make everything faster, so I will index every column and be done."

— a nine-year engineer who has just seen a 311x number, right about now

Every index is a second copy of a column, kept in sorted order, and the database must update every copy on every write. Ten indexes on a table means every insert does eleven writes. On an analytics table loaded once a night, that cost is small. On the busy trips table of a live app, it is paid thousands of times a second.

An index also does nothing when the query reads most of the table anyway. Asking for all completed trips (78% of rows) is faster as a plain scan, and the planner knows it: it will ignore your index. Add an index when the evidence, an EXPLAIN showing a slow scan that returns few rows, says so.

Transactions, in one paragraph

A transaction groups statements so that all of them happen or none do. You open one with BEGIN, and end it with COMMIT to keep the changes or ROLLBACK to undo them. Meanwhile other connections never see half-finished work. This is what lets a payment debit a wallet and credit a driver without a crash in between creating or destroying money.

The block below shows the smallest case: a 120-rupee debit that is rolled back. For isolation levels, locking and how the database survives a crash, read the engineering track's database primer. We do not repeat it here.

Step-by-step: what sql/07_transaction.sql does, in plain English
  1. Make a one-row temporary table: rider 1 has a wallet balance of 500.
  2. BEGIN opens a transaction.
  3. The UPDATE subtracts 120. Inside the transaction the balance reads 380.
  4. ROLLBACK cancels the transaction. The change vanishes, and the final SELECT shows 500 again.
sql/07_transaction.sqlruns offline
-- A transaction groups statements so they all happen or none do.
CREATE TEMP TABLE wallet AS SELECT 1 AS rider_id, 500 AS balance;
BEGIN;
UPDATE wallet SET balance = balance - 120 WHERE rider_id = 1;
SELECT balance AS balance_inside_transaction FROM wallet;
ROLLBACK;
SELECT balance AS balance_after_rollback FROM wallet;
terminalactual output · engine: PostgreSQL 18 (DuckDB printed the same two balances)
>> SELECT balance AS balance_inside_transaction FROM wallet
balance_inside_transaction
--------------------------
                       380

>> ROLLBACK

>> SELECT balance AS balance_after_rollback FROM wallet
balance_after_rollback
----------------------
                   500

Analytics work is mostly reading, so you will use transactions rarely in this chapter, with one exception: the pipeline in the next section rebuilds each table with a drop and a create, and a production version would wrap each rebuild in a transaction so a dashboard never sees a half-built table.

Sequential scan
Read every row, keep the matches. Cost grows with table size.
Index
A sorted side-list: jump to matching rows. CREATE INDEX name ON table (column).
EXPLAIN / EXPLAIN ANALYZE
Show the chosen plan / run the query and show real time and pages touched.
Buffers
8 KB pages touched. The fewer, the less work: 5,440 before, 55 after.
Trade-off
Each index speeds reads and slows every write; skip it when the query reads most rows.
Transaction
BEGIN, then COMMIT (keep all) or ROLLBACK (undo all). Depth: the engineering primer, chapter e08.
Measured here
1,000,000 rows: 22.369 ms to 0.072 ms on PostgreSQL 18, a 311x difference.

08 · The data lifecycleETL, ELT and a Pipeline You Can Trust

Priya has her answer for Friday, and a new worry: "Next quarter I will ask the same questions. Will the number match, or will we do this again?" Today the fix lives in one person's head and one query. A pipeline turns it into something that runs the same way every time and shouts when the data breaks. That is the second half of this chapter.

A data pipeline is a repeatable path from the raw copy of the data to the tables people read, with automatic checks along the way. Without one, every report is a one-off, and every new analyst rediscovers the same bugs.

Six stages, one question each

The data lifecycle is the journey from an event to a decision. Group its stages by the question each one answers, and the whole thing fits in six rows. The RideNow column shows where each stage lives in this chapter.

The data lifecycle, one question per stage
StageThe question it answersRideNow example
CollectHow does the fact get recorded?The app writes a trip row and payment rows into the operational database
LoadWhere does an analytics copy live?Copy the six tables, untouched, into raw_* tables
CleanCan I trust the types and names?stg_trips: text becomes numbers and timestamps, statuses lower-cased
ModelWhat shape answers the business questions?mart_trip_facts and mart_daily_city: one row per trip, one per city-day
TestIs it still correct today?Seven checks, including "one row per trip" and "fares reconcile"
ServeWho reads it?The board pack and the finance dashboard

ETL and ELT: same letters, different order

ETL means Extract, Transform, Load: pull data out of the source, reshape it on a separate machine, and load only the finished result into the warehouse. ELT swaps the last two letters: load the raw data into the warehouse first, then transform it there with SQL. The only difference is where the cleaning happens and whether the original survives.

ETL: transform on a separate machine, load only the finished result Source database trips, payments extract Python job on its own server clean, join, aggregate 1 load Warehouse only the finished tables ELT: load the raw copy first, transform with SQL inside the warehouse Source database trips, payments raw_trips 60,000 rows, as text untouched copy 2 stg_trips 60,000 rows, typed cleaned names mart_trip_facts: 60,000 rows mart_daily_city: 1,637 rows what dashboards read 3 SQL statements run inside the warehouse Why ELT won: warehouses got cheap and fast, so keeping the raw copy lets you re-run the transform after a bug fix without going back to the source system.
Fig. 1d.12 — The two orders of work. In ETL (top) the warehouse only ever sees finished tables. In ELT (bottom) it holds the raw copy and every later layer, with RideNow's real row counts.
  1. ETL's transform step. A Python job on its own server cleans, joins and aggregates before the load. If it has a bug, such as the fan-out, the warehouse stores the wrong answer and the raw data is gone from the pipeline.
  2. ELT's raw copy. raw_trips holds all 60,000 rows exactly as the source gave them, every column as text. Nothing was decided yet, so nothing can be decided wrongly. When you find a bug, you fix the SQL and re-run.
  3. ELT's layers. Each layer is a SQL statement inside the warehouse: staging cleans types (60,000 rows still), the mart reshapes for questions (60,000 trip rows and 1,637 city-day rows). The dashed line shows that this entire stretch is SQL running where the data lives.
Decision table: ETL or ELT?
ChooseWhenAvoid whenTypical tools
ELTThe warehouse is a cloud or columnar engine you can scale; analysts write SQL; you want to re-run history after fixing a bugThe raw data holds personal or regulated fields that must never reach the warehouseFivetran or Airbyte to load; SQL, dbt or SQLMesh to transform
ETLYou must mask, drop or encrypt fields before they leave the source; the target is a small system that cannot run heavy SQL; the transform is not SQL, such as parsing images or calling a modelThe transform is plain joins and aggregates that SQL already does wellPython jobs, Spark, a managed ETL service
Both, in layersMost real systems: ETL-style masking at the edge, then ELT inside the warehouseYou have one table and one analystA mix

A small program first: one layer by hand

Before the full pipeline, here is the smallest ELT step: load one CSV with every column as text, then create a cleaned, typed copy. It is six lines of SQL.

Step-by-step: what sql/13_one_layer.sql does, in plain English
  1. read_csv(..., all_varchar = true) is DuckDB's file reader. all_varchar tells it not to guess types: every value stays text. This is the "raw" copy.
  2. The second CREATE TEMP TABLE ... AS SELECT builds the staging table. CAST(city_id AS INTEGER) turns text into a number. TRIM(name) strips stray spaces.
  3. The two typeof queries print the column type before and after, and city_id + 1 proves the staged column behaves as a number.
sql/13_one_layer.sqlruns offline (DuckDB syntax: read_csv, typeof)
-- DuckDB: the smallest ELT step. Load a CSV untouched (every column as text), then clean it into a typed table.
CREATE TEMP TABLE raw_cities AS
    SELECT * FROM read_csv('data/cities.csv', header = true, all_varchar = true);

CREATE TEMP TABLE stg_cities AS
    SELECT CAST(city_id AS INTEGER) AS city_id, TRIM(name) AS name
    FROM raw_cities;

SELECT typeof(city_id) AS raw_type FROM raw_cities LIMIT 1;
SELECT typeof(city_id) AS staging_type, city_id + 1 AS id_plus_one, name FROM stg_cities LIMIT 3;
terminalactual output · engine: DuckDB 1.5
>> SELECT typeof(city_id) AS raw_type FROM raw_cities LIMIT 1
raw_type
--------
VARCHAR

>> SELECT typeof(city_id) AS staging_type, city_id + 1 AS id_plus_one, name FROM stg_cities LIMIT 3
staging_type  id_plus_one  name
------------  -----------  ---------
INTEGER                 2  Bengaluru
INTEGER                 3  Mumbai
INTEGER                 4  Delhi

The raw column's type is VARCHAR (text), and the staged column's is INTEGER. PostgreSQL has no read_csv; it loads files with COPY and names the type function pg_typeof. That is a small dialect difference that the pipeline below hides inside one if.

Build the pipeline in five chunks

Build it in chunks: elt_pipeline.py

We build elt_pipeline.py in five chunks: load raw, clean to staging, build the mart, test, report. Each chunk runs on its own, and the whole file comes at the end. All outputs below came from DuckDB 1.5. Run it on PostgreSQL by adding the word postgres to the command.

  1. Chunk 1 — copy every CSV into a raw table, untouched, as text

    This comes first because everything later reads from it. If a later step is wrong, you re-run from here instead of going back to the source.

    Step-by-step: what chunk 1 does, in plain English
    1. Choose the engine from the command line: duckdb by default, or postgres.
    2. List the six table names and connect. For DuckDB the pipeline writes to its own file, warehouse.duckdb.
    3. For each table, read the CSV's header line to learn the column names.
    4. Drop any old raw_ table so the run can be repeated safely (this property is called idempotent).
    5. DuckDB: one CREATE TABLE ... AS SELECT * FROM read_csv(...). PostgreSQL: create an all-TEXT table, then stream the file in with COPY ... FROM STDIN.
    6. Print how many rows each raw table holds.
    elt_pipeline.py — chunk 1runs offline
    # pip install duckdb psycopg[binary]      (psycopg only for --engine postgres)
    # usage: python elt_pipeline.py [duckdb|postgres] [--poison]
    import csv
    import sys
    from pathlib import Path
    
    from db import DUCK_PATH, connect, fetch
    
    # ── chunk 1: load raw (the "L" of ELT: copy the files in untouched, everything as text) ──
    ENGINE = next((a for a in sys.argv[1:] if a in ("duckdb", "postgres")), "duckdb")
    DATA = Path(__file__).parent / "data"
    TABLES = ["cities", "riders", "drivers", "promotions", "trips", "payments"]
    con = connect(ENGINE, DUCK_PATH.with_name("warehouse.duckdb"))   # DuckDB: a separate warehouse file
    cur = con.cursor()
    
    
    def run(sql):
        cur.execute(sql)
    
    
    for t in TABLES:
        cols = next(csv.reader(open(DATA / f"{t}.csv")))
        run(f"DROP TABLE IF EXISTS raw_{t}")
        if ENGINE == "duckdb":
            run(f"CREATE TABLE raw_{t} AS SELECT * FROM read_csv('{DATA / (t + '.csv')}', header=true, all_varchar=true)")
        else:
            run(f"CREATE TABLE raw_{t} ({', '.join(c + ' TEXT' for c in cols)})")
            with cur.copy(f"COPY raw_{t} FROM STDIN WITH (FORMAT csv, HEADER true)") as cp:
                cp.write((DATA / f"{t}.csv").read_bytes())
        print(f"raw_{t:<10} {fetch(con, f'SELECT COUNT(*) FROM raw_{t}')[1][0][0]:>7,} rows")

    COPY ... FROM STDIN — PostgreSQL's bulk loader, far faster than inserting row by row. read_csv(all_varchar=true) — DuckDB's equivalent.

    Run python elt_pipeline.py. You should see six lines, ending raw_payments 52,380 rows:

    terminalactual output
    raw_cities           6 rows
    raw_riders       4,000 rows
    raw_drivers        300 rows
    raw_promotions       5 rows
    raw_trips       60,000 rows
    raw_payments    52,380 rows
  2. Chunk 2 — clean into staging, and collapse payments to one row per trip

    The raw tables are text, so nothing can be summed. Staging gives each column its proper type and, importantly, applies the fan-out fix once, in one place, so no later query can forget it.

    Step-by-step: what chunk 2 does, in plain English
    1. Drop and rebuild stg_trips from raw_trips. Each CAST turns text into the right type. NULLIF(driver_id, '') turns an empty string into a real NULL first, because an empty string cannot become a number.
    2. LOWER(TRIM(status)) guards against stray spaces and capital letters in the status text.
    3. Rebuild stg_payments_by_trip: group the raw payment rows by trip, count them, and compute successful amounts minus refunds. That is the collapse from Fig. 1d.7.
    4. Print the staging counts: all 60,000 trips, and 46,063 trips that have payments.
    elt_pipeline.py — chunk 2runs offline
    # ── chunk 2: staging (clean and type the raw text; one fix per line, no business logic yet) ──
    run("DROP TABLE IF EXISTS stg_trips")
    run("""CREATE TABLE stg_trips AS
        SELECT CAST(trip_id AS INTEGER)                  AS trip_id,
               CAST(rider_id AS INTEGER)                 AS rider_id,
               CAST(NULLIF(driver_id, '') AS INTEGER)    AS driver_id,
               CAST(city_id AS INTEGER)                  AS city_id,
               CAST(NULLIF(promo_id, '') AS INTEGER)     AS promo_id,
               CAST(requested_at AS TIMESTAMP)           AS requested_at,
               LOWER(TRIM(status))                       AS status,
               CAST(NULLIF(fare, '') AS NUMERIC(10,2))   AS fare
        FROM raw_trips""")
    # the fan-out fix lives here: payments collapsed to ONE row per trip, so no later join can multiply fares
    run("DROP TABLE IF EXISTS stg_payments_by_trip")
    run("""CREATE TABLE stg_payments_by_trip AS
        SELECT CAST(trip_id AS INTEGER) AS trip_id,
               COUNT(*)                 AS payment_rows,
               SUM(CASE WHEN status = 'succeeded' THEN CAST(amount AS NUMERIC(10,2)) ELSE 0 END)
             - SUM(CASE WHEN status = 'refunded'  THEN CAST(amount AS NUMERIC(10,2)) ELSE 0 END) AS cash_collected
        FROM raw_payments
        GROUP BY 1""")
    print("staging:", fetch(con, "SELECT COUNT(*) FROM stg_trips")[1][0][0], "trips,",
          fetch(con, "SELECT COUNT(*) FROM stg_payments_by_trip")[1][0][0], "trips with payments")

    CREATE TABLE ... AS SELECT builds a table from a query. NULLIF(x, '') returns NULL when x is the empty string.

    Run it again. After the six raw lines you should see one new line:

    terminalactual output
    staging: 60000 trips, 46063 trips with payments
  3. Chunk 3 — build the mart: one row per trip, one row per city and day

    Dashboards should not write joins. The mart does the joining once, correctly, and hands readers two plain tables.

    Step-by-step: what chunk 3 does, in plain English
    1. Build mart_trip_facts: every staged trip, joined to its city name and (with a LEFT JOIN) to the one-row-per-trip payment summary. COALESCE(x, 0) swaps a missing value for 0, so trips with no payment show cash 0 and are not dropped.
    2. Because the payments side has exactly one row per trip, the join cannot multiply rows.
    3. Build mart_daily_city from the fact table: for each city and day, count requests and completed trips, and total gross fares and cash. FILTER counts only completed trips.
    4. Print both row counts.
    elt_pipeline.py — chunk 3runs offline
    # ── chunk 3: mart (business-ready tables the board dashboards read) ──
    run("DROP TABLE IF EXISTS mart_trip_facts")
    run("""CREATE TABLE mart_trip_facts AS
        SELECT t.trip_id, t.rider_id, c.name AS city, CAST(t.requested_at AS DATE) AS day,
               t.status, COALESCE(t.fare, 0) AS fare,
               COALESCE(p.cash_collected, 0)  AS cash_collected,
               COALESCE(p.payment_rows, 0)    AS payment_rows
        FROM stg_trips t
        JOIN (SELECT CAST(city_id AS INTEGER) AS city_id, name FROM raw_cities) c ON c.city_id = t.city_id
        LEFT JOIN stg_payments_by_trip p ON p.trip_id = t.trip_id""")
    run("DROP TABLE IF EXISTS mart_daily_city")
    run("""CREATE TABLE mart_daily_city AS
        SELECT day, city,
               COUNT(*) AS requests,
               COUNT(*) FILTER (WHERE status = 'completed') AS completed,
               SUM(fare) AS gross_fares,
               SUM(cash_collected) AS cash_collected
        FROM mart_trip_facts
        GROUP BY day, city""")
    print("mart: trip_facts", fetch(con, "SELECT COUNT(*) FROM mart_trip_facts")[1][0][0],
          "rows, daily_city", fetch(con, "SELECT COUNT(*) FROM mart_daily_city")[1][0][0], "rows")

    COALESCE(a, b) returns the first non-NULL value. A LEFT JOIN to a pre-collapsed table is the safe join shape.

    Run it. The last new line should read:

    terminalactual output
    mart: trip_facts 60000 rows, daily_city 1637 rows
  4. Chunk 4 — add data tests that fail loudly

    The fan-out produced a wrong number with no error. Tests are how a pipeline turns a silent wrong answer into a loud failure. Each test is a query that counts bad rows: zero means pass.

    Step-by-step: what chunk 4 does, in plain English
    1. If you ran with --poison, insert a duplicate copy of trip 1 into stg_trips. This simulates an upstream bug so you can watch the tests catch it.
    2. TESTS is a dictionary: test name to a SQL query that returns the number of offending rows.
    3. The tests check: trip ids are unique, key columns are not NULL, status holds only known values, completed trips always have a fare, every trip has a known city, the mart has exactly one row per trip, and the mart's total fares equal the staging total.
    4. Loop over the tests, run each, print PASS or FAIL with the bad-row count, and count the failures.
    elt_pipeline.py — chunk 4runs offline
    # ── chunk 4: data tests (each query counts BAD rows; zero means pass) ──
    if "--poison" in sys.argv:       # simulate an upstream duplicate slipping into staging
        run("INSERT INTO stg_trips SELECT * FROM stg_trips WHERE trip_id = 1")
    TESTS = {
        "stg_trips.trip_id is unique": "SELECT COUNT(*) - COUNT(DISTINCT trip_id) FROM stg_trips",
        "stg_trips keys are not null": "SELECT COUNT(*) FROM stg_trips WHERE rider_id IS NULL OR city_id IS NULL OR requested_at IS NULL",
        "status has only known values": "SELECT COUNT(*) FROM stg_trips WHERE status NOT IN ('completed','cancelled_by_rider','cancelled_by_driver','no_driver')",
        "completed trips all have a fare": "SELECT COUNT(*) FROM stg_trips WHERE status = 'completed' AND fare IS NULL",
        "every trip has a known city": "SELECT COUNT(*) FROM stg_trips t WHERE NOT EXISTS (SELECT 1 FROM raw_cities c WHERE CAST(c.city_id AS INTEGER) = t.city_id)",
        "mart has one row per trip": "SELECT COUNT(*) - COUNT(DISTINCT trip_id) FROM mart_trip_facts",
        "mart fares reconcile to staging": "SELECT CASE WHEN ABS((SELECT SUM(fare) FROM mart_trip_facts) - (SELECT SUM(fare) FROM stg_trips)) > 0.005 THEN 1 ELSE 0 END",
    }
    failed = 0
    for name, sql in TESTS.items():
        bad = fetch(con, sql)[1][0][0]
        failed += bad != 0
        print(f"{'PASS' if bad == 0 else 'FAIL'}  {name}" + ("" if bad == 0 else f"   ({bad} bad rows)"))

    A test is just a query that should return 0. The last test is a reconciliation: two independent routes to the same total must agree.

    Run it: seven PASS lines. Then run python elt_pipeline.py duckdb --poison and two tests should FAIL:

    terminalactual output (normal run, lines 9 to 15)
    PASS  stg_trips.trip_id is unique
    PASS  stg_trips keys are not null
    PASS  status has only known values
    PASS  completed trips all have a fare
    PASS  every trip has a known city
    PASS  mart has one row per trip
    PASS  mart fares reconcile to staging
    terminalactual output (--poison run, tests only)
    FAIL  stg_trips.trip_id is unique   (1 bad rows)
    PASS  stg_trips keys are not null
    PASS  status has only known values
    PASS  completed trips all have a fare
    PASS  every trip has a known city
    PASS  mart has one row per trip
    FAIL  mart fares reconcile to staging   (1 bad rows)
    2 test(s) failed; not publishing the report
  5. Chunk 5 — publish the report, but only if every test passed

    The report is the last link: it reads the mart only, and refuses to print when any test failed, so a broken pipeline can never hand Priya a plausible wrong number.

    Step-by-step: what chunk 5 does, in plain English
    1. If any test failed, stop with an error message and exit with a non-zero code. Schedulers treat a non-zero exit as "this job failed".
    2. Otherwise query mart_daily_city, grouped by month, for completed trips, gross fares and cash collected.
    3. Print the table.
    elt_pipeline.py — chunk 5runs offline
    # ── chunk 5: report (the numbers finance asked for, read from the mart only) ──
    if failed:
        sys.exit(f"{failed} test(s) failed; not publishing the report")
    cols, rows = fetch(con, """
        SELECT CAST(DATE_TRUNC('month', day) AS DATE) AS month, SUM(completed) AS completed,
               ROUND(SUM(gross_fares), 0) AS gross_fares, ROUND(SUM(cash_collected), 0) AS cash_collected
        FROM mart_daily_city GROUP BY 1 ORDER BY 1""")
    print(f"\n[engine: {ENGINE}]  month       completed   gross_fares   cash_collected")
    for m, c, g, k in rows:
        print(f"{'':<16}{m}  {int(c):>9,}  {g:>12,.0f}  {k:>14,.0f}")

    sys.exit("message") prints the message to stderr and exits with code 1. Exit codes are how pipelines talk to schedulers.

    Run it normally: after the seven PASS lines, a month-by-month table. With --poison it prints 2 test(s) failed; not publishing the report and nothing else.

    terminalactual output
    [engine: duckdb]  month       completed   gross_fares   cash_collected
                    2026-01-01      2,917       633,302         591,659
                    2026-02-01      3,144       672,720         628,222
                    2026-03-01      4,024       850,518         791,245
                    2026-04-01      4,523       965,095         901,624
                    2026-05-01      5,325     1,158,933       1,079,620
                    2026-06-01      5,724     1,223,062       1,135,535
                    2026-07-01      6,494     1,377,614       1,281,127
                    2026-08-01      7,206     1,558,556       1,425,012
                    2026-09-01      7,403     1,577,089       1,446,040

The whole program

Lines 1–8 are the header and imports. Lines 9–31 are chunk 1 (load raw), 32–55 chunk 2 (staging), 56–77 chunk 3 (the mart), 78–95 chunk 4 (tests) and 96–105 chunk 5 (report). Every chunk starts with a # ── chunk n ── comment. The file also lives in code/01d-sql-data-lifecycle/elt_pipeline.py.

elt_pipeline.pyruns offline (add postgres to use the docker container)
# pip install duckdb psycopg[binary]      (psycopg only for --engine postgres)
# usage: python elt_pipeline.py [duckdb|postgres] [--poison]
import csv
import sys
from pathlib import Path

from db import DUCK_PATH, connect, fetch

# ── chunk 1: load raw (the "L" of ELT: copy the files in untouched, everything as text) ──
ENGINE = next((a for a in sys.argv[1:] if a in ("duckdb", "postgres")), "duckdb")
DATA = Path(__file__).parent / "data"
TABLES = ["cities", "riders", "drivers", "promotions", "trips", "payments"]
con = connect(ENGINE, DUCK_PATH.with_name("warehouse.duckdb"))   # DuckDB: a separate warehouse file
cur = con.cursor()


def run(sql):
    cur.execute(sql)


for t in TABLES:
    cols = next(csv.reader(open(DATA / f"{t}.csv")))
    run(f"DROP TABLE IF EXISTS raw_{t}")
    if ENGINE == "duckdb":
        run(f"CREATE TABLE raw_{t} AS SELECT * FROM read_csv('{DATA / (t + '.csv')}', header=true, all_varchar=true)")
    else:
        run(f"CREATE TABLE raw_{t} ({', '.join(c + ' TEXT' for c in cols)})")
        with cur.copy(f"COPY raw_{t} FROM STDIN WITH (FORMAT csv, HEADER true)") as cp:
            cp.write((DATA / f"{t}.csv").read_bytes())
    print(f"raw_{t:<10} {fetch(con, f'SELECT COUNT(*) FROM raw_{t}')[1][0][0]:>7,} rows")

# ── chunk 2: staging (clean and type the raw text; one fix per line, no business logic yet) ──
run("DROP TABLE IF EXISTS stg_trips")
run("""CREATE TABLE stg_trips AS
    SELECT CAST(trip_id AS INTEGER)                  AS trip_id,
           CAST(rider_id AS INTEGER)                 AS rider_id,
           CAST(NULLIF(driver_id, '') AS INTEGER)    AS driver_id,
           CAST(city_id AS INTEGER)                  AS city_id,
           CAST(NULLIF(promo_id, '') AS INTEGER)     AS promo_id,
           CAST(requested_at AS TIMESTAMP)           AS requested_at,
           LOWER(TRIM(status))                       AS status,
           CAST(NULLIF(fare, '') AS NUMERIC(10,2))   AS fare
    FROM raw_trips""")
# the fan-out fix lives here: payments collapsed to ONE row per trip, so no later join can multiply fares
run("DROP TABLE IF EXISTS stg_payments_by_trip")
run("""CREATE TABLE stg_payments_by_trip AS
    SELECT CAST(trip_id AS INTEGER) AS trip_id,
           COUNT(*)                 AS payment_rows,
           SUM(CASE WHEN status = 'succeeded' THEN CAST(amount AS NUMERIC(10,2)) ELSE 0 END)
         - SUM(CASE WHEN status = 'refunded'  THEN CAST(amount AS NUMERIC(10,2)) ELSE 0 END) AS cash_collected
    FROM raw_payments
    GROUP BY 1""")
print("staging:", fetch(con, "SELECT COUNT(*) FROM stg_trips")[1][0][0], "trips,",
      fetch(con, "SELECT COUNT(*) FROM stg_payments_by_trip")[1][0][0], "trips with payments")

# ── chunk 3: mart (business-ready tables the board dashboards read) ──
run("DROP TABLE IF EXISTS mart_trip_facts")
run("""CREATE TABLE mart_trip_facts AS
    SELECT t.trip_id, t.rider_id, c.name AS city, CAST(t.requested_at AS DATE) AS day,
           t.status, COALESCE(t.fare, 0) AS fare,
           COALESCE(p.cash_collected, 0)  AS cash_collected,
           COALESCE(p.payment_rows, 0)    AS payment_rows
    FROM stg_trips t
    JOIN (SELECT CAST(city_id AS INTEGER) AS city_id, name FROM raw_cities) c ON c.city_id = t.city_id
    LEFT JOIN stg_payments_by_trip p ON p.trip_id = t.trip_id""")
run("DROP TABLE IF EXISTS mart_daily_city")
run("""CREATE TABLE mart_daily_city AS
    SELECT day, city,
           COUNT(*) AS requests,
           COUNT(*) FILTER (WHERE status = 'completed') AS completed,
           SUM(fare) AS gross_fares,
           SUM(cash_collected) AS cash_collected
    FROM mart_trip_facts
    GROUP BY day, city""")
print("mart: trip_facts", fetch(con, "SELECT COUNT(*) FROM mart_trip_facts")[1][0][0],
      "rows, daily_city", fetch(con, "SELECT COUNT(*) FROM mart_daily_city")[1][0][0], "rows")

# ── chunk 4: data tests (each query counts BAD rows; zero means pass) ──
if "--poison" in sys.argv:       # simulate an upstream duplicate slipping into staging
    run("INSERT INTO stg_trips SELECT * FROM stg_trips WHERE trip_id = 1")
TESTS = {
    "stg_trips.trip_id is unique": "SELECT COUNT(*) - COUNT(DISTINCT trip_id) FROM stg_trips",
    "stg_trips keys are not null": "SELECT COUNT(*) FROM stg_trips WHERE rider_id IS NULL OR city_id IS NULL OR requested_at IS NULL",
    "status has only known values": "SELECT COUNT(*) FROM stg_trips WHERE status NOT IN ('completed','cancelled_by_rider','cancelled_by_driver','no_driver')",
    "completed trips all have a fare": "SELECT COUNT(*) FROM stg_trips WHERE status = 'completed' AND fare IS NULL",
    "every trip has a known city": "SELECT COUNT(*) FROM stg_trips t WHERE NOT EXISTS (SELECT 1 FROM raw_cities c WHERE CAST(c.city_id AS INTEGER) = t.city_id)",
    "mart has one row per trip": "SELECT COUNT(*) - COUNT(DISTINCT trip_id) FROM mart_trip_facts",
    "mart fares reconcile to staging": "SELECT CASE WHEN ABS((SELECT SUM(fare) FROM mart_trip_facts) - (SELECT SUM(fare) FROM stg_trips)) > 0.005 THEN 1 ELSE 0 END",
}
failed = 0
for name, sql in TESTS.items():
    bad = fetch(con, sql)[1][0][0]
    failed += bad != 0
    print(f"{'PASS' if bad == 0 else 'FAIL'}  {name}" + ("" if bad == 0 else f"   ({bad} bad rows)"))

# ── chunk 5: report (the numbers finance asked for, read from the mart only) ──
if failed:
    sys.exit(f"{failed} test(s) failed; not publishing the report")
cols, rows = fetch(con, """
    SELECT CAST(DATE_TRUNC('month', day) AS DATE) AS month, SUM(completed) AS completed,
           ROUND(SUM(gross_fares), 0) AS gross_fares, ROUND(SUM(cash_collected), 0) AS cash_collected
    FROM mart_daily_city GROUP BY 1 ORDER BY 1""")
print(f"\n[engine: {ENGINE}]  month       completed   gross_fares   cash_collected")
for m, c, g, k in rows:
    print(f"{'':<16}{m}  {int(c):>9,}  {g:>12,.0f}  {k:>14,.0f}")

Read the final output as the answer to Priya's question. All seven tests pass. Cash collected in September is 1,446,040 rupees from 7,403 completed trips, and the monthly table is identical to the one produced by the hand-written SQL earlier in the chapter. The same file run against PostgreSQL 18 printed every number identically. The pipeline's value is not the numbers. It is that next quarter the same command produces the same numbers, or refuses to.

The pipeline file is longer than anything you have read so far, but every statement in it is one you have already seen: CAST and GROUP BY from the first sections, LEFT JOIN and the collapse from the fan-out, FILTER from aggregates. Python is only the thin shell that runs them in order.

One trip, all the way through

A pipeline is easy to trust when you can follow one record through it. Trip 158 is the trip with three payment rows. The figure traces it from raw to mart, and the query file prints each stage so you can check every value.

raw (text) staging (typed) mart: one row per trip mart: one row per day raw_trips (all text) trip_id '158' city_id '1' status 'completed' fare '136.2' raw_payments: 3 rows 1 failed 115.77 2 failed 115.77 3 succeeded 115.77 one trip, three rows stg_trips trip_id 158 (integer) city_id 1 status completed fare 136.20 (numeric) stg_payments_by_trip trip_id 158 payment_rows 3 cash_collected 115.77 3 rows collapsed to 1 1 mart_trip_facts trip_id 158 city Bengaluru day 2026-01-02 fare 136.20 cash_collected 115.77 payment_rows 3 mart_daily_city Bengaluru 2026-01-02 requests 28 completed 25 gross_fares 4,921.83 cash_collected 4,571.08 2 3 Trip 158 is one of the 25 completed Bengaluru trips that day. Its fare 136.20 is counted once in 4,921.83.
Fig. 1d.13 — Trip 158 at every stage of elt_pipeline.py. Values are copied from the real tables.
  1. Three rows become one. raw_payments holds two failed attempts and one success, each 115.77. stg_payments_by_trip turns them into a single row: payment_rows = 3, cash_collected = 115.77. The failures contribute 0, so the trip is charged once.
  2. Text becomes types. In raw_trips the fare is the text '136.2'. In stg_trips it is the number 136.20, which can be added.
  3. One trip among 25. In mart_daily_city, Bengaluru on 2026-01-02 had 28 requests and 25 completed trips, with gross fares 4,921.83. Trip 158's 136.20 is in that total exactly once.
Fireside chat

Tonight's talk: the raw table and the mart table argue over the question, "Who's more important?"

raw_trips
mart_daily_city

I am the only one who remembers what really arrived. Look at marker 2 in Fig. 1d.13: the fare is still the text '136.2', exactly as the app wrote it. Burn me and you can never check anyone's work.

the raw table keeps the original facts, so any later layer can be rebuilt or audited. That is why ELT loads it first.

And nobody can read you. You are 60,000 rows of text with three payments per trip. Priya opens me: 1,637 rows, one per city and day, already correct. Fig. 1d.13, marker 3. People make decisions from me.

readers need small, shaped, trustworthy tables. The mart is the part of the pipeline that people actually look at.

I never lie, though. The day the fan-out bug shipped, you were wrong for weeks. I was the same on Monday as on Friday. When you break, they rebuild you from me.

a mart can contain a bug. Because the raw copy is unchanged, the fix is "correct the SQL, run again".

Fair, and the data tests are on my side of the wall now. Seven checks guard me. But who pays to store a full copy of everything, me and the staging tables included? We will revisit this when the bill arrives.

ELT trades storage cost for safety and flexibility. Whether that trade is worth it depends on how big the data is and how costly a bad number is.

The next table is the same big picture a second time, stage by stage with the real file names, so you can place any piece of the pipeline in one glance.

The pipeline, stage by stage: the naive way, the production way, and what flows out
StageThe naive versionThe production version hereWhat flows out
LoadAn analyst opens CSVs in a notebookraw_* tables, all text, rebuilt every run6 raw tables, 60,000 trip rows
CleanFix types inside the notebook cellstg_trips and stg_payments_by_tripTyped rows; payments one per trip
ModelA merge in each notebookmart_trip_facts, mart_daily_city60,000 and 1,637 rows
TestLook at the chart and hope7 query tests; exit code 1 on failurePASS/FAIL lines
ServePaste into slidesThe report reads the mart onlyMonthly trips, gross fares, cash

One last honesty note about scheduling. The pipeline is a script. Run it from cron, a Linux scheduler, and it works. At the next step you want retries, dependencies between jobs and a dashboard of runs. That is what orchestrators such as Airflow, Dagster and Prefect add, and the stack table below compares them. A tool such as dbt would replace our hand-written SQL layers with a framework of models and built-in tests. This course covers dbt properly in Module 16b.

ETL
Extract, Transform, Load: reshape before the warehouse sees it.
ELT
Extract, Load, Transform: copy raw first, reshape inside the warehouse with SQL.
Layers
raw (untouched), staging (typed and cleaned), mart (shaped for questions).
Idempotent
Safe to run twice: each table is dropped and rebuilt, so the result is the same.
Data test
A query counting bad rows. Zero means pass. A failing test stops the report.
Reconciliation
Two independent routes to one total must match: mart fares equal staging fares.
Why ELT won
Cheap warehouse compute plus a preserved raw copy means a bug fix is a re-run, not an archaeology dig.

09 · Python meets the databasepsycopg 3, SQLAlchemy, pandas, and the Injection You Must Never Write

The pipeline runs. Two more people now want the data. The support team wants a small tool that looks up a rider by email. Dev wants his notebook to read the mart directly instead of CSV files. Both need Python talking to PostgreSQL, and the first one is where a careless line of code can hand the whole rider table to a stranger.

A database driver is the Python library that sends SQL to the database and brings rows back. The one rule that matters: send the values separately from the SQL text. Without it, anyone who can type into a form can rewrite your query.

Start with five lines

The driver we use is psycopg 3, the current major version of the standard PostgreSQL driver for Python. A connection is the open line to the database. You send a statement with execute, and fetch rows. Values go in as a separate second argument, and the SQL carries %s holes where they belong. Everything in this section depends on that habit.

Step-by-step: what psycopg_hello.py does, in plain English
  1. psycopg.connect(PG_DSN) opens a connection. The with block closes it at the end, and commits any changes if no error occurred.
  2. The first query asks for the name of city 3. %s is a hole, and (3,) is the one-item tuple that fills it. The comma matters: (3) is just the number 3.
  3. fetchone() returns one row as a tuple. row[0] is its first column.
  4. The second query has two holes, filled in order by ("completed", 500).
  5. The last query has no values, and iterating over the result yields rows one at a time, unpacked into two names.
psycopg_hello.pyneeds PostgreSQL (docker)
# pip install "psycopg[binary]>=3.2,<4"        needs the PostgreSQL container (see setup.sh)
import psycopg

from db import PG_DSN

with psycopg.connect(PG_DSN) as con:      # leaving the block commits and closes the connection
    row = con.execute("SELECT name FROM cities WHERE city_id = %s", (3,)).fetchone()
    print("city 3 is", row[0])

    n = con.execute("SELECT COUNT(*) FROM trips WHERE status = %s AND fare > %s", ("completed", 500)).fetchone()[0]
    print("completed trips over 500 rupees:", n)

    for city_id, name in con.execute("SELECT city_id, name FROM cities ORDER BY name LIMIT 3"):
        print(city_id, name)
terminalactual output · engine: PostgreSQL 18 via psycopg 3.3
city 3 is Delhi
completed trips over 500 rupees: 1289
1 Bengaluru
5 Chennai
3 Delhi

The output shows city 3 is Delhi, 1,289 completed trips cost more than 500 rupees, and the three alphabetically first cities. Nothing surprising, and that is the point: this is the whole everyday API. Offline, DuckDB does the same with duckdb.connect(path).execute(sql, [values]), using ? as the hole.

Anatomy of a safe query — the one line to write from memory
rows = con.execute(1
    "SELECT rider_id FROM riders WHERE email = %s",2
    (email,)3
).fetchall()4
  1. execute. Sends one statement to the database and returns a cursor. People assume it returns rows. It returns an object you then fetch from, or loop over.
  2. The SQL text, with %s. A fixed string that never contains user data. The usual mistake: building it with an f-string or +, which is the injection hole below.
  3. The values tuple. One item per hole, in order. The usual mistake is (email) without the trailing comma, which is a plain string, not a tuple, and fails or splits into characters.
  4. fetchall. Pulls every row into Python at once. Fine for 50 rows. For millions, iterate over the cursor instead so memory stays flat.

SQL injection: shown, then fixed

The support tool takes an email address from a text box. The tempting way to build the query is an f-string. It works perfectly for honest input, and that is exactly why the bug survives testing. Watch what a hostile input does. The script below tries an honest email, an attacker's email, and a stacked statement, against both versions.

Step-by-step: what sql_injection.py does, in plain English
  1. Connect with autocommit=True so each statement takes effect immediately, then create a harmless table scratch_notes for the attacker to destroy.
  2. find_rider_unsafe pastes the email straight into the SQL text with an f-string.
  3. find_rider_safe keeps the SQL fixed and passes the email as a separate parameter.
  4. It tries the honest address rider7@example.com on the unsafe function, then the attack text x' OR '1'='1 on both.
  5. Finally the unsafe function receives x'; DROP TABLE scratch_notes; --. The quote closes the string, the semicolon ends the statement, DROP TABLE is the attacker's statement, and -- comments out the leftover quote. to_regclass then reports whether the table still exists.
sql_injection.pyneeds PostgreSQL (docker)
# pip install "psycopg[binary]>=3.2,<4"        needs the PostgreSQL container (see README)
import psycopg

from db import PG_DSN

with psycopg.connect(PG_DSN, autocommit=True) as con:
    con.execute("DROP TABLE IF EXISTS scratch_notes")
    con.execute("CREATE TABLE scratch_notes AS SELECT 1 AS id")   # a harmless table the attacker will delete

    def find_rider_unsafe(email: str):
        # BAD: the text is pasted into the SQL, so the user can change the SQL itself
        return con.execute(f"SELECT rider_id FROM riders WHERE email = '{email}'").fetchall()

    def find_rider_safe(email: str):
        # GOOD: the SQL text and the value travel separately; %s is a hole, not a string splice
        return con.execute("SELECT rider_id FROM riders WHERE email = %s", (email,)).fetchall()

    honest = "rider7@example.com"
    attack = "x' OR '1'='1"
    print("honest, unsafe :", find_rider_unsafe(honest))
    print("attack, unsafe :", len(find_rider_unsafe(attack)), "riders leaked")
    print("attack, safe   :", find_rider_safe(attack))

    # stacked statements: the second statement is the attacker's
    find_rider_unsafe("x'; DROP TABLE scratch_notes; --")
    left = con.execute("SELECT to_regclass('scratch_notes')").fetchone()[0]
    print("scratch_notes after the unsafe call:", left)
terminalactual output · engine: PostgreSQL 18 via psycopg 3.3
honest, unsafe : [(7,)]
attack, unsafe : 4000 riders leaked
attack, safe   : []
scratch_notes after the unsafe call: None

Read the four lines. The honest email returns rider 7, exactly as intended. The attack returns all 4,000 riders: a full data leak from a one-box form. The safe version, given the very same attack text, returns an empty list, because it looks for a rider whose email is literally the string x' OR '1'='1, and none exists. The last line says None: the unsafe call deleted a table.

Unsafe: the value is pasted into the SQL text f"SELECT rider_id FROM riders WHERE email = '{email}'" the attacker sends: x' OR '1'='1 1 what the database receives (one string): WHERE email = 'x' OR '1'='1' '1'='1' is always true 2 result: 4,000 riders leaked Safe: the SQL and the value travel separately "SELECT rider_id FROM riders WHERE email = %s" same attacker text, sent as the parameter 3 message 1: the statement ... WHERE email = $1 message 2: a value x' OR '1'='1 treated as plain text 4 result: 0 riders found
Fig. 1d.14 — The same attacker text on both versions of the lookup. The attack changes the meaning of the query on the left and is only data on the right.
  1. The attacker's text. x' OR '1'='1 contains a quote mark. In the f-string version the quote ends the email string early, so everything after it is read as SQL.
  2. One string, two meanings. The database receives WHERE email = 'x' OR '1'='1'. '1'='1' is always true, so every row passes: 4,000 riders leaked.
  3. Two separate messages. With %s, psycopg 3 sends the statement (with a placeholder) and the value as separate pieces to the server. The server has already parsed the statement before the value arrives.
  4. Data, never code. The value is compared as plain text. No rider has that email, so the answer is 0 rows. No input can change what the statement does.

Two honest limits. Placeholders work for values only. You cannot use %s for a table or column name, so if a query must vary its table, choose from a fixed list in your own code and never from user text. And parameters stop injection, not every misuse: a query that returns too much is still a bug in your logic.

SQLAlchemy 2.0 Core, and pandas

SQLAlchemy is a toolkit that wraps many drivers behind one interface. Its low-level half, Core, runs SQL text with named parameters (:since) and manages a pool of reusable connections. Its higher-level half, the ORM, maps tables to Python classes. For analytics we use Core only. engine.begin() opens one transaction that commits on success and rolls back on any error.

Step-by-step: what sqlalchemy_core.py does, in plain English
  1. create_engine(...) builds the engine that holds the connection pool. The postgresql+psycopg:// prefix selects the psycopg 3 driver.
  2. text(...) wraps SQL that contains :since, a named parameter.
  3. engine.connect() borrows a connection. conn.execute(QUERY, {"since": ...}) runs the query with the value passed separately, so injection is impossible here too. Each row is read by column name.
  4. engine.begin() opens a transaction: create a temporary table, insert a row, count it, and commit when the block ends without error.
sqlalchemy_core.pyneeds PostgreSQL (docker)
# pip install "sqlalchemy>=2.0,<2.1" "psycopg[binary]>=3.2,<4"
from sqlalchemy import create_engine, text

from db import PG_DSN

# the "+psycopg" part picks the psycopg 3 driver; plain "postgresql://" would look for psycopg2
engine = create_engine(PG_DSN.replace("postgresql://", "postgresql+psycopg://"), pool_size=2)

QUERY = text("""
    SELECT c.name AS city, COUNT(*) AS completed
    FROM trips t JOIN cities c ON c.city_id = t.city_id
    WHERE t.status = 'completed' AND t.requested_at >= :since
    GROUP BY c.name ORDER BY completed DESC LIMIT 3""")

with engine.connect() as conn:                       # connection returns to the pool at the end of the block
    for row in conn.execute(QUERY, {"since": "2026-09-01"}):
        print(row.city, row.completed)               # rows behave like named tuples

with engine.begin() as conn:                         # begin() = one transaction: commit on success, rollback on error
    conn.execute(text("CREATE TEMP TABLE audit (note TEXT)"))
    conn.execute(text("INSERT INTO audit VALUES (:n)"), {"n": "board pack built"})
    print("rows inside the transaction:", conn.execute(text("SELECT COUNT(*) FROM audit")).scalar_one())
terminalactual output · engine: PostgreSQL 18 via SQLAlchemy 2.0
Bengaluru 1995
Mumbai 1705
Delhi 1671
rows inside the transaction: 1

September's top three cities by completed trips are Bengaluru (1,995), Mumbai (1,705) and Delhi (1,671), and the transaction block saw its own inserted row. Now Dev's request. pandas.read_sql runs a query and returns a DataFrame. The script below reads the same status counts two ways: through the SQLAlchemy engine, and through ADBC (Arrow Database Connectivity), a driver family that sends columns as Arrow data instead of one Python object per value.

Step-by-step: what pandas_read_sql.py does, in plain English
  1. Define one query: trips per status.
  2. Route 1: build a SQLAlchemy engine and hand it to pd.read_sql, which returns a DataFrame.
  3. Route 2: open an ADBC connection, execute the query on a cursor, and call fetch_arrow_table() to receive an Arrow table, then to_pandas().
  4. Print the DataFrame, check both routes give equal results, and show the column types.
pandas_read_sql.pyneeds PostgreSQL (docker)
# pip install pandas "sqlalchemy>=2.0,<2.1" "psycopg[binary]>=3.2,<4" "adbc-driver-postgresql>=1.7"
import pandas as pd
from adbc_driver_postgresql import dbapi
from sqlalchemy import create_engine

from db import PG_DSN

SQL = "SELECT status, COUNT(*) AS trips FROM trips GROUP BY status ORDER BY trips DESC"

# route 1: SQLAlchemy engine (the route pandas documents; rows travel through Python objects)
engine = create_engine(PG_DSN.replace("postgresql://", "postgresql+psycopg://"))
df1 = pd.read_sql(SQL, engine)

# route 2: ADBC (columns travel as Arrow data, so no per-row Python objects)
with dbapi.connect(PG_DSN) as conn:
    cur = conn.cursor()
    cur.execute(SQL)
    df3 = cur.fetch_arrow_table().to_pandas()
    cur.close()

print(df1.to_string(index=False))
print("same answer via ADBC:", df1.equals(df3), "| dtypes:", dict(df3.dtypes.astype(str)))
terminalactual output · engine: PostgreSQL 18; pandas 3.0.5, adbc-driver-postgresql 1.13
             status  trips
          completed  46760
 cancelled_by_rider   7202
cancelled_by_driver   3647
          no_driver   2391
same answer via ADBC: True | dtypes: {'status': 'str', 'trips': 'int64'}

Both routes return the same four rows. With four rows the speed difference is invisible, so we did not benchmark it. The reason to know ADBC and connectorx (a Rust-based loader that splits one big query into parallel pieces) is the day you read ten million rows into pandas and the default path takes minutes. connectorx is not installed in the course environment and was not run here. Treat it as a name to try when read_sql is your measured bottleneck.

Driver
The library that talks to the database: psycopg 3 for PostgreSQL, the duckdb package for DuckDB.
Placeholder
%s in psycopg, :name in SQLAlchemy text, ? in DuckDB. Values go separately.
SQL injection
User text pasted into SQL changes the query. Shown: 4,000 riders leaked and a table dropped.
The fix
Parameters. Names of tables or columns cannot be parameters: pick them from a fixed list.
SQLAlchemy Core
Engine, connection pool, text() with named parameters, engine.begin() for a transaction.
pandas.read_sql
Query to DataFrame. Pass a SQLAlchemy engine. For big reads, try ADBC or connectorx.
Version check
As of October 2026 in this course environment: psycopg 3.3.5, SQLAlchemy 2.0.54, pandas 3.0.5.

10 · The stack, and whyWhich Tools, Which Alternatives, and Where the Dialects Differ

The pipeline works and Priya is happy. Next week a colleague will ask: why PostgreSQL, why DuckDB, why not dbt, why not Airflow? Each choice was made for a reason that can run out. This section writes the reasons and the exit conditions in one table, then lists every place the two SQL dialects disagreed during this chapter.

A tool choice is a bet with an expiry date. The table below states what we bet on, what else was possible, what each choice is bad at, and the specific condition that should make you switch.

The stack, and why

The one question that decides it: does this data need to serve a running application, or answer questions about what already happened, and how big is "a lot"?

What this chapter uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
OLTP database (the app's own)PostgreSQL 18 (19 is in release-candidate testing, due November 2026)MySQL, SQLiteRichest SQL of the three (windows, CTEs, JSON, extensions such as pgvector used later in the course) and strict about bad data. Bad at: needs a server and tuning.Use SQLite when the data is a single-user file on one device. Use MySQL when your team already runs it with working replicas and ops runbooks.
Analytics engineDuckDB 1.5, in-processClickHouse, BigQuery, SnowflakeNo server, columnar speed, reads CSV and Parquet directly, same SQL family as production. Bad at: one machine, one writer, no user accounts.The data no longer fits comfortably on one machine's disk (roughly over 1 TB), or more than a handful of people query it at the same time.
Python driverpsycopg 3.3asyncpg, SQLAlchemy ORM, the older psycopg2One library with sync and async APIs, parameters sent separately from SQL, and fast bulk COPY. Bad at: raw speed in async code.Use asyncpg for an async service doing thousands of queries per second. Use the ORM when the app has 20 or more tables and domain classes. psycopg2 is the previous generation; new code should not start on it.
Query layer for analysisSQLAlchemy 2.0 Core + pandas.read_sqlADBC, connectorx, plain driverOne interface across databases, named parameters, connection pool. Bad at: row-by-row conversion makes big reads slow.A single read of about 5 million rows or more takes minutes: try ADBC or connectorx (not run in this course environment).
TransformationPlain SQL scripts run from Pythondbt, SQLMeshNothing to install, every statement visible, perfect for learning. Bad at: no dependency graph, no generated documentation, tests are ones you write.More than about 10 models, or two people editing the same pipeline: move to dbt (Module 16b). Note that dbt Labs and Fivetran completed a merger in June 2026 and that Fivetran also owns SQLMesh, so check each project's licence terms before choosing.
Schedulingcron (any Linux box)Airflow 3.3, Dagster 1.13, Prefect 3.9One line of config, zero servers. Bad at: no retries, no dependencies between jobs, no run history.More than about 5 scheduled jobs with dependencies, or any job that needs automatic retries and backfills.
Schema changesRaw SQL files (schema.sql)Alembic, FlywayThe analytics schema is rebuilt from scratch on each run, so there is nothing to migrate. Bad at: useless for a live production schema.The moment a production table must change without a rebuild (adding a column to a live trips table): use Alembic (SQLAlchemy's migration tool) or Flyway.
Loading raw dataCOPY and read_csvFivetran, AirbyteFast, free and one line per file. Bad at: you maintain every source yourself.More than about 5 external sources (payments API, CRM, ads) whose schemas change under you: buy the connector.

Use boring PostgreSQL for the app, DuckDB plus plain SQL for learning and small analytics, and let a measured pain (size, people, retries) trigger every upgrade.

Version facts in the table were checked in October 2026. PostgreSQL's own site lists 18 as the current major release, with 19 at release candidate 1 on 15 October and general availability planned for 19 November. The scheduler and dbt version numbers are the newest releases on PyPI as of 29 October: Airflow 3.3.2, Dagster 1.13.27, Prefect 3.9.0, dbt-core 1.12.6, SQLMesh 0.236.4 and connectorx 0.4.6. Package versions move fast, so re-check before you pin anything.

Where PostgreSQL and DuckDB disagreed

Nearly all the SQL in this chapter ran unchanged on both engines, and the outputs matched. A few things did not. The script below runs seven small snippets on both engines and prints what each one said. It is the evidence behind the table that follows it.

Step-by-step: what dialect_traps.py does, in plain English
  1. SNIPPETS is a dictionary of seven labelled queries, each probing a feature that differs between engines.
  2. For each engine in turn, connect and run every snippet.
  3. Print the first value of the first row, or the first line of the error message if the engine refused the query.
dialect_traps.pyneeds PostgreSQL (docker) for the first column
"""Run the same snippets on PostgreSQL 18 and DuckDB and show where they disagree.
usage: python dialect_traps.py      (needs the PostgreSQL container for the postgres column)"""
from db import connect, fetch

SNIPPETS = {
    "integer division 7 / 2": "SELECT 7 / 2",
    "ROUND(double precision, 2)": "SELECT ROUND(AVG(CAST(distance_km AS DOUBLE PRECISION)), 2) FROM trips",
    "GROUP BY ALL": "SELECT status, COUNT(*) FROM trips GROUP BY ALL ORDER BY 2 DESC LIMIT 1",
    "QUALIFY": "SELECT trip_id FROM trips QUALIFY ROW_NUMBER() OVER (ORDER BY trip_id) = 1",
    "INTERVAL '30 days' add": "SELECT CAST(TIMESTAMP '2026-01-31 10:00:00' + INTERVAL '30 days' AS DATE)",
    "date_diff in days": "SELECT DATE '2026-03-01' - DATE '2026-02-01'",
    "string_agg": "SELECT string_agg(name, ',' ORDER BY name) FROM cities",
}

for engine in ("postgres", "duckdb"):
    con = connect(engine)
    print(f"\n[engine: {engine}]")
    for label, sql in SNIPPETS.items():
        try:
            out = fetch(con, sql)[1][0][0]
            print(f"  {label:<28} -> {out!r}")
        except Exception as e:
            print(f"  {label:<28} -> ERROR {str(e).splitlines()[0][:70]}")
terminalactual output · engines: PostgreSQL 18 and DuckDB 1.5
[engine: postgres]
  integer division 7 / 2       -> 3
  ROUND(double precision, 2)   -> ERROR function round(double precision, integer) does not exist
  GROUP BY ALL                 -> ERROR syntax error at or near "ORDER"
  QUALIFY                      -> ERROR syntax error at or near "ROW_NUMBER"
  INTERVAL '30 days' add       -> datetime.date(2026, 3, 2)
  date_diff in days            -> 28
  string_agg                   -> 'Bengaluru,Chennai,Delhi,Hyderabad,Mumbai,Pune'

[engine: duckdb]
  integer division 7 / 2       -> 3.5
  ROUND(double precision, 2)   -> 8.01
  GROUP BY ALL                 -> 'completed'
  QUALIFY                      -> 1
  INTERVAL '30 days' add       -> datetime.date(2026, 3, 2)
  date_diff in days            -> 28
  string_agg                   -> 'Bengaluru,Chennai,Delhi,Hyderabad,Mumbai,Pune'
Every dialect difference we hit in this chapter, and what to do about it
FeaturePostgreSQL 18DuckDB 1.5Portable habit
7 / 2 on integers3 (whole-number division)3.5Write 7.0 / 2 or cast to NUMERIC when you want a fraction
ROUND(x, 2) on a floatError: function does not existWorksCast to NUMERIC first, or keep money in NUMERIC columns
GROUP BY ALL, QUALIFYSyntax errorWorksSpell out the columns; filter windows in a CTE
SUM of integersReturns numeric (prints 1,003.00)Returns integer (prints 1003)Cast with CAST(... AS BIGINT) if types must match
Self-referencing foreign key during bulk loadAcceptedConstraint error in 1.5Declare it after loading, or leave it off in the analytics copy
Loading a CSVCOPY t FROM STDIN through the driverread_csv(...) or COPY t FROM 'file'Hide it behind one function, as the pipeline does
Type of a valuepg_typeof(x)typeof(x)Avoid in shared code
Temporary tables and sessionsPer connectionEach cursor() is a separate session; keep one connectionUse one connection object per script

The honest summary: DuckDB is more forgiving (it will round a float and divide to a fraction), and PostgreSQL is stricter. Write for the stricter engine and your SQL will run on both. Things that did not differ in the snippets: adding an interval to a timestamp, subtracting two dates, and string_agg.

Default stack here
PostgreSQL 18 (app), DuckDB 1.5 (offline analytics), psycopg 3 and SQLAlchemy 2.0 (Python), plain SQL scripts (transform), cron (schedule).
Biggest switch triggers
Over about 1 TB or many concurrent readers: a warehouse. Over about 10 models or 2 editors: dbt. Over about 5 dependent jobs: an orchestrator.
Write for the stricter engine
Cast before rounding, use 7.0 / 2 for fractions, avoid GROUP BY ALL and QUALIFY in shared code.
Dates of the claims
All versions: October 2026.

11 · The labEight Board Questions, Answered Twice

It is Thursday. Priya's eight questions are still open, and Dev wants to know whether his pandas habits were the problem. They were not, as the fan-out showed. The cleanest way to settle the argument is to answer each of the eight questions in SQL and in pandas, check that the two agree to the paisa, and chart each answer. That is the lab, and it is also the best way to learn how the two languages map onto each other.

SQL and pandas answer the same questions with different vocabulary. Writing every answer both ways, and testing that they agree, turns each language into a check on the other.

The smallest pair first

Start with one question in both languages: completed trips per city. The SQL says what you want in one block. The pandas version is a chain of four steps read from top to bottom: filter, join, group, sort. The last line proves the two answers are identical.

Step-by-step: what sql_vs_pandas_small.py does, in plain English
  1. Open the DuckDB file read-only, so a typo cannot damage the data.
  2. Run the SQL: join trips to cities, keep completed trips, group by city name, count, and sort. .df() turns the result into a pandas DataFrame.
  3. Load the two tables into DataFrames. Build the same answer as a chain: boolean filter, merge (join), groupby(...).size() (count rows per group), rename the columns to match, and sort.
  4. Print the SQL answer, then print whether DataFrame.equals says the two are the same.
sql_vs_pandas_small.pyruns offline
# pip install duckdb pandas      (the smallest SQL-versus-pandas pair: one question, two answers)
import duckdb

con = duckdb.connect("data/ridenow.duckdb", read_only=True)

# SQL: completed trips per city, biggest first
sql_answer = con.sql("""
    SELECT c.name AS city, COUNT(*) AS completed
    FROM trips t JOIN cities c ON c.city_id = t.city_id
    WHERE t.status = 'completed'
    GROUP BY c.name
    ORDER BY completed DESC
""").df()

# pandas: the same four steps (filter, join, group, sort), read left to right
trips, cities = con.sql("SELECT * FROM trips").df(), con.sql("SELECT * FROM cities").df()
pandas_answer = (trips[trips.status == "completed"]
                 .merge(cities, on="city_id")
                 .groupby("name", as_index=False).size()
                 .rename(columns={"name": "city", "size": "completed"})
                 .sort_values("completed", ascending=False, ignore_index=True))

print(sql_answer.to_string(index=False))
print("same answer in pandas:", sql_answer.equals(pandas_answer))
terminalactual output · engine: DuckDB 1.5; pandas 3.0.5
     city  completed
Bengaluru      12674
   Mumbai      11025
    Delhi      10598
Hyderabad       5863
  Chennai       3553
     Pune       3047
same answer in pandas: True

Bengaluru leads with 12,674 completed trips, then Mumbai (11,025) and Delhi (10,598), and the pandas chain agrees exactly. This pair is the template for the whole lab. The next four tables are a dictionary between the two languages, grouped by the kind of question, because the question type decides which tools you need.

A dictionary, one table per kind of question

Kind 1 — summarise rows (Q1 monthly totals, Q3 cancellation by hour)
StepSQLpandas
Keep some rowsWHERE status = 'completed'trips.query("status == 'completed'")
Group and totalGROUP BY month with COUNT(*), SUM(fare)groupby(month).agg(completed=("trip_id", "size"), gross_fares=("fare", "sum"))
Keep some groupsHAVING COUNT(*) >= 1500g[g.requests >= 1500] after the groupby (pandas has no HAVING)
Count with a conditionCOUNT(*) FILTER (WHERE status LIKE 'cancelled%')make a True/False column with str.startswith("cancelled"), then sum it
Kind 2 — combine tables (Q2 cash per city, Q8 promo ledger)
StepSQLpandas
Inner joinJOIN cities c ON c.city_id = t.city_idmerge(cities, on="city_id")
Keep unmatched left rowsLEFT JOIN paid p ON p.trip_id = t.trip_idmerge(net, on="trip_id", how="left")
Collapse the many side firstA CTE with GROUP BY trip_idgroupby("trip_id", as_index=False).agg(...) before the merge
Guard against fan-outNo switch: write a test that the result has one row per keyvalidate="one_to_one" on the merge
Replace missing with zeroCOALESCE(p.net, 0).fillna(0)
Kind 3 — compare a row with its neighbours (Q4 top drivers, Q5 growth, Q6 moving average)
StepSQLpandas
Number rows inside each groupROW_NUMBER() OVER (PARTITION BY city ORDER BY fares DESC)sort_values(...) then groupby("name").cumcount() + 1
Ranks with tiesRANK() / DENSE_RANK()rank(method="min") / rank(method="dense")
The previous row's valueLAG(fares) OVER (ORDER BY month)fares.shift(1)
Moving average, last 7 rowsAVG(trips) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)trips.rolling(7, min_periods=1).mean()
Running totalSUM(x) OVER (ORDER BY day)x.cumsum()
Kind 4 — first and second events per person (Q7 repeat riders)
StepSQLpandas
Each rider's trips in time orderROW_NUMBER() OVER (PARTITION BY rider_id ORDER BY requested_at)sort_values(["rider_id", "requested_at"]) then groupby("rider_id").cumcount() + 1
Pair the first with the secondJoin the numbered CTE to itself on n = 2Filter n == 1 and n == 2, then merge(..., how="left")
"Within 30 days"second_at <= first_at + INTERVAL '30 days'second_at <= first_at + pd.Timedelta(days=30)
Share per cohort100.0 * COUNT(*) FILTER (...) / COUNT(*).groupby("cohort").mean() on a True/False column
Decision table: SQL or pandas?
Reach forWhenAvoid whenTypical size
SQLThe data already sits in a database; you need joins, totals and windows over many rows; the logic must be reused by a dashboardYou are plotting, fitting a model or doing text work in the same stepMillions of rows and up, shrinking to thousands for Python
pandasThe data fits in memory; you are exploring and iterating; the next step is a chart or a modelThe data is larger than memory, or the answer must stay in sync with a warehouseUp to a few million rows on one laptop
BothMost real work: SQL shrinks and shapes, pandas finishesYou only need one numberAny

Build the lab program in six chunks

Build it in chunks: board_questions.py

We build board_questions.py in six chunks. Chunk 1 connects and loads, chunk 2 builds the machinery that checks SQL against pandas and draws a chart, and chunks 3 to 6 each add two board questions. Each chunk runs on its own, and the entry point stays at the very bottom of the file. Outputs are from DuckDB 1.5; PostgreSQL 18 printed identical results.

  1. Chunk 1 — connect and load the six tables into pandas

    Every question needs the data twice: inside the database for SQL, and in DataFrames for pandas. This chunk makes both available.

    Step-by-step: what chunk 1 does, in plain English
    1. Import matplotlib and select the Agg backend, which draws straight to image files and needs no window.
    2. Choose the engine from the command line, create the out/ folder for charts, and connect.
    3. sql_df runs any SQL and wraps the rows in a DataFrame.
    4. Load every table once into the dictionary T with SELECT *. Timestamps become real datetimes, and money columns become plain floats (PostgreSQL returns exact decimals).
    5. Print how many rows each table holds.
    board_questions.py — chunk 1runs offline
    # pip install duckdb pandas matplotlib      (psycopg[binary] only for --engine postgres)
    # usage: python board_questions.py [duckdb|postgres] [--full]    (--full prints up to 40 rows per answer)
    import sys
    from pathlib import Path
    
    import matplotlib
    matplotlib.use("Agg")                       # draw to files, no window needed
    import matplotlib.pyplot as plt
    import pandas as pd
    
    from db import connect, fetch
    
    # ── chunk 1: connect to the database and load the six tables into pandas ──
    ENGINE = next((a for a in sys.argv[1:] if a in ("duckdb", "postgres")), "duckdb")
    OUT = Path(__file__).parent / "out"
    OUT.mkdir(exist_ok=True)
    con = connect(ENGINE)
    
    
    def sql_df(sql: str) -> pd.DataFrame:
        cols, rows = fetch(con, sql)
        return pd.DataFrame(rows, columns=cols)
    
    
    T = {name: sql_df(f"SELECT * FROM {name}") for name in ["cities", "riders", "drivers", "promotions", "trips", "payments"]}
    T["trips"]["requested_at"] = pd.to_datetime(T["trips"]["requested_at"])
    for col in ["fare", "distance_km", "duration_min"]:
        T["trips"][col] = T["trips"][col].astype(float)
    T["payments"]["amount"] = T["payments"]["amount"].astype(float)
    print(f"[engine: {ENGINE}]  tables loaded:", {k: len(v) for k, v in T.items()})

    matplotlib.use("Agg") — render charts to files without a screen. A dict comprehension builds all six DataFrames in one line.

    Run python board_questions.py; one line is printed:

    terminalactual output
    [engine: duckdb]  tables loaded: {'cities': 6, 'riders': 4000, 'drivers': 300, 'promotions': 5, 'trips': 60000, 'payments': 52380}
  2. Chunk 2 — the question registry, the SQL-equals-pandas check, the chart helper and the runner

    This is the machinery, written before any question so that every question is forced through the same test. A question that disagrees with itself cannot reach the report.

    Step-by-step: what chunk 2 does, in plain English
    1. QUESTIONS is an empty list. The @question("title") decorator adds the function underneath it to that list. A decorator is a function that wraps another function; here it only records it.
    2. same(a, b) lines the two answers up and compares every cell with assert_frame_equal, allowing a difference under one hundredth of a rupee. It raises an error if they differ.
    3. chart(...) draws a bar or line chart of one column and saves a PNG in out/. It removes the top and right frame lines so the chart stays quiet.
    4. run_all() loops over every registered question. Each question returns its SQL answer, its pandas answer and a drawing function. The runner checks they match, draws, and prints the first four rows.
    5. The if __name__ == "__main__": block at the bottom calls run_all(). In the complete file it stays at the very end, below all the questions.
    board_questions.py — chunk 2runs offline
    # ── chunk 2: the question registry, the SQL-equals-pandas check, the chart helper, the runner ──
    QUESTIONS = []
    
    
    def question(title):
        """Register a function that returns (sql_result, pandas_result, chart_function)."""
        def wrap(fn):
            QUESTIONS.append((title, fn))
            return fn
        return wrap
    
    
    def same(a: pd.DataFrame, b: pd.DataFrame) -> bool:
        """Both answers must agree to the cent, whatever the row order."""
        a, b = a.reset_index(drop=True), b.reset_index(drop=True)
        b = b[list(a.columns)]
        pd.testing.assert_frame_equal(a.astype(float, errors="ignore"), b.astype(float, errors="ignore"),
                                      check_dtype=False, atol=0.01)
        return True
    
    
    def chart(fig_name, kind, df, x, y, title, ylabel):
        fig, ax = plt.subplots(figsize=(7, 3.6))
        if kind == "bar":
            ax.bar(df[x].astype(str), df[y], color="#2f6fd0")
        else:
            ax.plot(df[x], df[y], color="#2f6fd0", linewidth=2)
        ax.set_title(title, loc="left", fontsize=11)
        ax.set_ylabel(ylabel)
        ax.spines[["top", "right"]].set_visible(False)
        ax.tick_params(axis="x", labelrotation=45 if kind == "bar" and len(df) > 8 else 0)
        fig.tight_layout()
        fig.savefig(OUT / f"{fig_name}.png", dpi=110)
        plt.close(fig)
    
    
    def run_all():
        for title, fn in QUESTIONS:
            s, p, draw = fn()
            same(s, p)                           # fail loudly if SQL and pandas ever disagree
            draw(s)                              # one PNG per question in out/
            print(f"\n{title}\n  SQL == pandas: True   rows={len(s)}")
            print(s.head(40 if "--full" in sys.argv else 4).to_string(index=False))
    
    
    # ── chunk 2 (tail): the entry point stays at the very bottom, below every question ──
    if __name__ == "__main__":
        run_all()

    A decorator (@question(...)) that registers functions; pd.testing.assert_frame_equal as a built-in "do these two tables match" test.

    Run it: still one line, because no question is registered yet. The program now has a runner and nothing to run.

    terminalactual output
    [engine: duckdb]  tables loaded: {'cities': 6, 'riders': 4000, 'drivers': 300, 'promotions': 5, 'trips': 60000, 'payments': 52380}
  3. Chunk 3 — Q1 monthly trips and fares, Q2 cash by city

    Q1 is the plain summary. Q2 is the join that used to double count, written so that it cannot: payments are collapsed first in SQL, and the pandas merge carries validate="one_to_one".

    Step-by-step: what chunk 3 does, in plain English
    1. Q1 SQL: count completed trips and sum fares per month. Q1 pandas: filter, group by the month of the timestamp, aggregate.
    2. Q2 SQL: the paid CTE nets successful payments minus refunds per trip, then joins trips, cities and paid and sums per city.
    3. Q2 pandas: compute a signed amount per payment row, group to one row per trip, then merge twice with validate="one_to_one" so a repeat of the fan-out would raise an error.
    4. Each question returns (sql_answer, pandas_answer, draw), where draw is a one-line function that calls chart.
    board_questions.py — chunk 3runs offline
    # ── chunk 3: Q1 and Q2 — group-and-aggregate, and a join done safely ──
    @question("Q1  Completed trips and gross fares per month")
    def q1():
        s = sql_df("""SELECT CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month,
                             COUNT(*) AS completed, ROUND(SUM(fare), 2) AS gross_fares
                      FROM trips WHERE status = 'completed' GROUP BY 1 ORDER BY 1""")
        d = T["trips"].query("status == 'completed'")
        p = (d.groupby(d.requested_at.dt.to_period("M").dt.to_timestamp().dt.date)
              .agg(completed=("trip_id", "size"), gross_fares=("fare", "sum")).round(2).reset_index()
              .rename(columns={"requested_at": "month"}))
        return s, p, lambda s: chart("q1_monthly", "bar", s, "month", "gross_fares", "Gross fares per month", "rupees")
    
    
    @question("Q2  Cash collected per city (the join that used to double count)")
    def q2():
        s = sql_df("""WITH paid AS (
                        SELECT trip_id, SUM(CASE WHEN status='succeeded' THEN amount ELSE 0 END)
                                      - SUM(CASE WHEN status='refunded'  THEN amount ELSE 0 END) AS net
                        FROM payments GROUP BY trip_id)
                      SELECT c.name AS city, ROUND(SUM(t.fare), 2) AS gross_fares, ROUND(SUM(COALESCE(p.net, 0)), 2) AS cash_collected
                      FROM trips t JOIN cities c ON c.city_id = t.city_id
                      LEFT JOIN paid p ON p.trip_id = t.trip_id
                      WHERE t.status = 'completed' GROUP BY c.name ORDER BY cash_collected DESC""")
        pay = T["payments"].assign(signed=lambda d: d.amount.where(d.status == "succeeded", 0) - d.amount.where(d.status == "refunded", 0))
        net = pay.groupby("trip_id", as_index=False).agg(net=("signed", "sum"))   # one row per trip BEFORE the merge
        m = (T["trips"].query("status == 'completed'")
             .merge(T["cities"], on="city_id")
             .merge(net, on="trip_id", how="left", validate="one_to_one"))       # raises if the fan-out ever returns
        m["net"] = m["net"].fillna(0)
        p = (m.groupby("name", as_index=False).agg(gross_fares=("fare", "sum"), cash_collected=("net", "sum"))
              .round(2).rename(columns={"name": "city"}).sort_values("cash_collected", ascending=False))
        return s, p, lambda s: chart("q2_city_cash", "bar", s, "city", "cash_collected", "Cash collected by city", "rupees")

    groupby(..., as_index=False).agg(name=("column", "function")) — named aggregation; Series.where(cond, 0) — keep values where the condition holds, otherwise 0.

    Paste chunk 3 above the if __name__ block and run. Two questions print, each ending SQL == pandas: True:

    terminalactual output
    [engine: duckdb]  tables loaded: {'cities': 6, 'riders': 4000, 'drivers': 300, 'promotions': 5, 'trips': 60000, 'payments': 52380}
    
    Q1  Completed trips and gross fares per month
      SQL == pandas: True   rows=9
         month  completed  gross_fares
    2026-01-01       2917    633301.93
    2026-02-01       3144    672720.01
    2026-03-01       4024    850518.18
    2026-04-01       4523    965094.71
    
    Q2  Cash collected per city (the join that used to double count)
      SQL == pandas: True   rows=6
         city  gross_fares  cash_collected
    Bengaluru   2713766.73      2523261.25
       Mumbai   2355479.75      2178763.80
        Delhi   2287930.92      2120948.30
    Hyderabad   1257822.60      1159028.68
  4. Chunk 4 — Q3 cancellation rate by hour, Q4 top three drivers per city

    Q3 needs HAVING, which pandas lacks. Q4 needs a rank inside each city, the first window function.

    Step-by-step: what chunk 4 does, in plain English
    1. Q3 SQL: group requests by the hour of the timestamp, compute the percentage cancelled with FILTER, and keep only hours with at least 1,500 requests (HAVING). That removes the dead hours from midnight to 5 a.m.
    2. Q3 pandas: group, then filter the grouped table with a boolean test, which is how pandas does HAVING.
    3. Q4 SQL: sum fares per city and driver, number the drivers inside each city with ROW_NUMBER() OVER (PARTITION BY city ORDER BY SUM(fare) DESC, driver_id), and keep numbers 1 to 3. The driver_id tie-break makes the result repeatable.
    4. Q4 pandas: sort by city, fares descending and driver, then groupby("name").cumcount() + 1 gives the same row numbers.
    board_questions.py — chunk 4runs offline
    # ── chunk 4: Q3 and Q4 — a rate with HAVING, and ranking inside groups ──
    @question("Q3  Which hours of the day lose the most requests to cancellation?")
    def q3():
        s = sql_df("""SELECT CAST(EXTRACT(hour FROM requested_at) AS INTEGER) AS hour, COUNT(*) AS requests,
                             ROUND(100.0 * COUNT(*) FILTER (WHERE status LIKE 'cancelled%') / COUNT(*), 2) AS cancel_pct
                      FROM trips GROUP BY 1 HAVING COUNT(*) >= 1500 ORDER BY 1""")
        d = T["trips"].assign(hour=T["trips"].requested_at.dt.hour,
                              cancelled=T["trips"].status.str.startswith("cancelled"))
        g = d.groupby("hour").agg(requests=("trip_id", "size"), cancelled=("cancelled", "sum"))
        g = g[g.requests >= 1500]                                # pandas has no HAVING: filter after the groupby
        p = g.assign(cancel_pct=(100.0 * g.cancelled / g.requests).round(2)).drop(columns="cancelled").reset_index()
        return s, p, lambda s: chart("q3_cancel_by_hour", "bar", s, "hour", "cancel_pct", "Cancellation rate by hour", "% of requests")
    
    
    @question("Q4  Top 3 drivers per city by gross fares (ROW_NUMBER)")
    def q4():
        s = sql_df("""WITH ranked AS (
                        SELECT c.name AS city, t.driver_id, ROUND(SUM(t.fare), 2) AS fares,
                               ROW_NUMBER() OVER (PARTITION BY c.name ORDER BY SUM(t.fare) DESC, t.driver_id) AS rk
                        FROM trips t JOIN cities c ON c.city_id = t.city_id
                        WHERE t.status = 'completed' GROUP BY c.name, t.driver_id)
                      SELECT city, rk, driver_id, fares FROM ranked WHERE rk <= 3 ORDER BY city, rk""")
        g = (T["trips"].query("status == 'completed'").merge(T["cities"], on="city_id")
             .groupby(["name", "driver_id"], as_index=False).agg(fares=("fare", "sum")).round({"fares": 2})
             .sort_values(["name", "fares", "driver_id"], ascending=[True, False, True]))
        g["rk"] = g.groupby("name").cumcount() + 1               # the pandas twin of ROW_NUMBER() OVER (PARTITION BY ...)
        p = g[g.rk <= 3].rename(columns={"name": "city"})[["city", "rk", "driver_id", "fares"]]
        def draw(s):
            top = s.query("rk == 1")
            chart("q4_top_driver", "bar", top, "city", "fares", "Best driver in each city (gross fares)", "rupees")
        return s, p, draw

    Series.dt.hour — pull the hour out of a datetime column; cumcount() — the 0, 1, 2 position inside each group, the pandas twin of ROW_NUMBER.

    Add chunk 4 above the entry point and run. Q3 and Q4 appear after Q2; Q3's first rows:

    terminalactual output
    Q3  Which hours of the day lose the most requests to cancellation?
      SQL == pandas: True   rows=17
     hour  requests  cancel_pct
        6      1879       15.38
        7      3894       16.26
        8      4836       22.23
        9      3362       21.86
    
    Q4  Top 3 drivers per city by gross fares (ROW_NUMBER)
      SQL == pandas: True   rows=18
         city  rk  driver_id    fares
    Bengaluru   1         90 38484.46
    Bengaluru   2        297 38213.80
    Bengaluru   3        191 37608.56
      Chennai   1         14 34661.27
  5. Chunk 5 — Q5 month-over-month growth, Q6 the 7-day moving average

    Both are windows that look backward: one row behind for growth, six rows behind for the average.

    Step-by-step: what chunk 5 does, in plain English
    1. Q5 SQL: a CTE totals fares per month, then LAG(fares) OVER (ORDER BY month) supplies last month's total, and the percentage change follows from them.
    2. Q5 pandas: shift(1) moves the column down one row, so each row sees the previous month. The same arithmetic follows.
    3. Q6 SQL: a CTE counts completed trips per day; AVG(trips) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) averages up to seven days.
    4. Q6 pandas: rolling(7, min_periods=1).mean() does the same, and min_periods=1 lets the first six days average fewer rows, as SQL does.
    board_questions.py — chunk 5runs offline
    # ── chunk 5: Q5 and Q6 — LAG for change, a window frame for smoothing ──
    @question("Q5  Month-over-month growth of gross fares (LAG)")
    def q5():
        s = sql_df("""WITH m AS (SELECT CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month, SUM(fare) AS fares
                                 FROM trips WHERE status = 'completed' GROUP BY 1)
                      SELECT month, ROUND(fares, 2) AS fares,
                             ROUND(100.0 * (fares - LAG(fares) OVER (ORDER BY month)) / LAG(fares) OVER (ORDER BY month), 2) AS growth_pct
                      FROM m ORDER BY month""")
        d = T["trips"].query("status == 'completed'")
        m = d.groupby(d.requested_at.dt.to_period("M").dt.to_timestamp().dt.date).fare.sum().rename("fares").reset_index()
        m = m.rename(columns={"requested_at": "month"})
        m["growth_pct"] = ((m.fares - m.fares.shift(1)) / m.fares.shift(1) * 100).round(2)   # shift(1) is LAG(1)
        m["fares"] = m.fares.round(2)
        return s, m, lambda s: chart("q5_growth", "bar", s.dropna(), "month", "growth_pct", "Month-over-month growth", "% change")
    
    
    @question("Q6  Daily completed trips with a 7-day moving average")
    def q6():
        s = sql_df("""WITH daily AS (SELECT CAST(requested_at AS DATE) AS day, COUNT(*) AS trips
                                   FROM trips WHERE status = 'completed' GROUP BY 1)
                      SELECT day, trips,
                             ROUND(AVG(trips) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS avg_7d
                      FROM daily ORDER BY day""")
        d = T["trips"].query("status == 'completed'")
        p = d.groupby(d.requested_at.dt.date).size().rename("trips").reset_index().rename(columns={"requested_at": "day"})
        p["avg_7d"] = p.trips.rolling(7, min_periods=1).mean().round(2)     # rolling(7) is ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
        return s, p, lambda s: chart("q6_moving_avg", "line", s, "day", "avg_7d", "7-day moving average of completed trips", "trips per day")

    Series.shift(1) and Series.rolling(7) — pandas' LAG and window frame. The first month's growth is NaN (not a number), pandas' NULL.

    Add chunk 5 above the entry point and run. Q5 and Q6 print. Q5 starts with an empty growth for January, because nothing precedes it:

    terminalactual output
    Q5  Month-over-month growth of gross fares (LAG)
      SQL == pandas: True   rows=9
         month     fares  growth_pct
    2026-01-01 633301.93         NaN
    2026-02-01 672720.01        6.22
    2026-03-01 850518.18       26.43
    2026-04-01 965094.71       13.47
    
    Q6  Daily completed trips with a 7-day moving average
      SQL == pandas: True   rows=273
           day  trips  avg_7d
    2026-01-01     84   84.00
    2026-01-02     88   86.00
    2026-01-03    119   97.00
    2026-01-04    106   99.25
  6. Chunk 6 — Q7 repeat riders by cohort, Q8 what each promo cost

    Q7 is the hardest: it needs each rider's first and second trip side by side. Q8 is a join and a ledger.

    Step-by-step: what chunk 6 does, in plain English
    1. Q7 SQL: the ordered CTE numbers each rider's completed trips by time. firsts joins trip number 1 to trip number 2 of the same rider (a LEFT JOIN, so riders with no second trip stay) and keeps first trips before 1 September, so every rider has at least 30 days to come back.
    2. The final query groups riders by the month of their first trip and counts how many had a second trip within 30 days, as a percentage.
    3. Q7 pandas: cumcount numbers the trips, two filters and a merge pair first with second, and a boolean column averaged per cohort gives the percentage.
    4. Q8 SQL: join completed trips with a promo code to promotions, multiply each fare by the discount percent, and total by code. Q8 pandas: the same with merge and groupby.
    board_questions.py — chunk 6runs offline
    # ── chunk 6: Q7 and Q8 — a cohort (CTE + window) and a promo ledger ──
    @question("Q7  Share of new riders who take a 2nd trip within 30 days, by first-trip month")
    def q7():
        s = sql_df("""WITH ordered AS (
                        SELECT rider_id, requested_at,
                               ROW_NUMBER() OVER (PARTITION BY rider_id ORDER BY requested_at) AS n
                        FROM trips WHERE status = 'completed'),
                      firsts AS (
                        SELECT f.rider_id, f.requested_at AS first_at, s.requested_at AS second_at
                        FROM ordered f LEFT JOIN ordered s ON s.rider_id = f.rider_id AND s.n = 2
                        WHERE f.n = 1 AND f.requested_at < '2026-09-01')
                      SELECT CAST(DATE_TRUNC('month', first_at) AS DATE) AS cohort, COUNT(*) AS riders,
                             ROUND(100.0 * COUNT(*) FILTER (WHERE second_at <= first_at + INTERVAL '30 days') / COUNT(*), 2) AS repeat_pct
                      FROM firsts GROUP BY 1 ORDER BY 1""")
        d = T["trips"].query("status == 'completed'").sort_values(["rider_id", "requested_at"]).copy()
        d["n"] = d.groupby("rider_id").cumcount() + 1
        f = d[d.n == 1][["rider_id", "requested_at"]].rename(columns={"requested_at": "first_at"})
        f = f.merge(d[d.n == 2][["rider_id", "requested_at"]].rename(columns={"requested_at": "second_at"}), on="rider_id", how="left")
        f = f[f.first_at < "2026-09-01"]
        f["repeat"] = f.second_at <= f.first_at + pd.Timedelta(days=30)
        f["cohort"] = f.first_at.dt.to_period("M").dt.to_timestamp().dt.date
        p = f.groupby("cohort").agg(riders=("rider_id", "size"), repeat=("repeat", "mean")).reset_index()
        p["repeat_pct"] = (p.repeat * 100).round(2)
        p = p.drop(columns="repeat")
        return s, p, lambda s: chart("q7_repeat", "bar", s, "cohort", "repeat_pct", "Riders with a 2nd trip within 30 days", "% of cohort")
    
    
    @question("Q8  What did each promo code cost us?")
    def q8():
        s = sql_df("""SELECT p.code, COUNT(*) AS trips, ROUND(SUM(t.fare * p.discount_pct / 100.0), 2) AS discount_given,
                             ROUND(AVG(t.fare), 2) AS avg_fare
                      FROM trips t JOIN promotions p ON p.promo_id = t.promo_id
                      WHERE t.status = 'completed' GROUP BY p.code ORDER BY discount_given DESC""")
        m = T["trips"].query("status == 'completed'").merge(T["promotions"], on="promo_id")
        m["disc"] = m.fare * m.discount_pct / 100.0
        p = (m.groupby("code", as_index=False).agg(trips=("trip_id", "size"), discount_given=("disc", "sum"), avg_fare=("fare", "mean"))
              .round(2).sort_values("discount_given", ascending=False))
        return s, p, lambda s: chart("q8_promos", "bar", s, "code", "discount_given", "Discount given by promo code", "rupees")

    INTERVAL '30 days' in SQL and pd.Timedelta(days=30) in pandas for date arithmetic; a self-join (the CTE joined to itself).

    Add chunk 6 above the entry point and run. The program now prints all eight answers and writes eight PNG charts to out/. Q7 and Q8 are the last two blocks:

    terminalactual output
    Q7  Share of new riders who take a 2nd trip within 30 days, by first-trip month
      SQL == pandas: True   rows=8
        cohort  riders  repeat_pct
    2026-01-01     541       97.78
    2026-02-01     487       89.53
    2026-03-01     565       81.95
    2026-04-01     507       77.91
    
    Q8  What did each promo code cost us?
      SQL == pandas: True   rows=5
         code  trips  discount_given  avg_fare
    WELCOME20   3263       138362.40    212.02
    WEEKEND15   2997        96248.03    214.10
    BACK2RIDE    862        55650.37    215.20
      RAINY10   1220        26222.03    214.93

The whole program

Lines 1–12 are the header and imports. Chunk 1 is lines 13–31, chunk 2 lines 32–76, chunk 3 lines 77–110, chunk 4 lines 111–143, chunk 5 lines 144–172 and chunk 6 lines 173–212. The last three lines are the entry point, which belongs to chunk 2 and sits at the end. The file is code/01d-sql-data-lifecycle/board_questions.py.

board_questions.pyruns offline (add postgres to use the docker container)
# pip install duckdb pandas matplotlib      (psycopg[binary] only for --engine postgres)
# usage: python board_questions.py [duckdb|postgres] [--full]    (--full prints up to 40 rows per answer)
import sys
from pathlib import Path

import matplotlib
matplotlib.use("Agg")                       # draw to files, no window needed
import matplotlib.pyplot as plt
import pandas as pd

from db import connect, fetch

# ── chunk 1: connect to the database and load the six tables into pandas ──
ENGINE = next((a for a in sys.argv[1:] if a in ("duckdb", "postgres")), "duckdb")
OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)
con = connect(ENGINE)


def sql_df(sql: str) -> pd.DataFrame:
    cols, rows = fetch(con, sql)
    return pd.DataFrame(rows, columns=cols)


T = {name: sql_df(f"SELECT * FROM {name}") for name in ["cities", "riders", "drivers", "promotions", "trips", "payments"]}
T["trips"]["requested_at"] = pd.to_datetime(T["trips"]["requested_at"])
for col in ["fare", "distance_km", "duration_min"]:
    T["trips"][col] = T["trips"][col].astype(float)
T["payments"]["amount"] = T["payments"]["amount"].astype(float)
print(f"[engine: {ENGINE}]  tables loaded:", {k: len(v) for k, v in T.items()})

# ── chunk 2: the question registry, the SQL-equals-pandas check, the chart helper, the runner ──
QUESTIONS = []


def question(title):
    """Register a function that returns (sql_result, pandas_result, chart_function)."""
    def wrap(fn):
        QUESTIONS.append((title, fn))
        return fn
    return wrap


def same(a: pd.DataFrame, b: pd.DataFrame) -> bool:
    """Both answers must agree to the cent, whatever the row order."""
    a, b = a.reset_index(drop=True), b.reset_index(drop=True)
    b = b[list(a.columns)]
    pd.testing.assert_frame_equal(a.astype(float, errors="ignore"), b.astype(float, errors="ignore"),
                                  check_dtype=False, atol=0.01)
    return True


def chart(fig_name, kind, df, x, y, title, ylabel):
    fig, ax = plt.subplots(figsize=(7, 3.6))
    if kind == "bar":
        ax.bar(df[x].astype(str), df[y], color="#2f6fd0")
    else:
        ax.plot(df[x], df[y], color="#2f6fd0", linewidth=2)
    ax.set_title(title, loc="left", fontsize=11)
    ax.set_ylabel(ylabel)
    ax.spines[["top", "right"]].set_visible(False)
    ax.tick_params(axis="x", labelrotation=45 if kind == "bar" and len(df) > 8 else 0)
    fig.tight_layout()
    fig.savefig(OUT / f"{fig_name}.png", dpi=110)
    plt.close(fig)


def run_all():
    for title, fn in QUESTIONS:
        s, p, draw = fn()
        same(s, p)                           # fail loudly if SQL and pandas ever disagree
        draw(s)                              # one PNG per question in out/
        print(f"\n{title}\n  SQL == pandas: True   rows={len(s)}")
        print(s.head(40 if "--full" in sys.argv else 4).to_string(index=False))


# ── chunk 3: Q1 and Q2 — group-and-aggregate, and a join done safely ──
@question("Q1  Completed trips and gross fares per month")
def q1():
    s = sql_df("""SELECT CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month,
                         COUNT(*) AS completed, ROUND(SUM(fare), 2) AS gross_fares
                  FROM trips WHERE status = 'completed' GROUP BY 1 ORDER BY 1""")
    d = T["trips"].query("status == 'completed'")
    p = (d.groupby(d.requested_at.dt.to_period("M").dt.to_timestamp().dt.date)
          .agg(completed=("trip_id", "size"), gross_fares=("fare", "sum")).round(2).reset_index()
          .rename(columns={"requested_at": "month"}))
    return s, p, lambda s: chart("q1_monthly", "bar", s, "month", "gross_fares", "Gross fares per month", "rupees")


@question("Q2  Cash collected per city (the join that used to double count)")
def q2():
    s = sql_df("""WITH paid AS (
                    SELECT trip_id, SUM(CASE WHEN status='succeeded' THEN amount ELSE 0 END)
                                  - SUM(CASE WHEN status='refunded'  THEN amount ELSE 0 END) AS net
                    FROM payments GROUP BY trip_id)
                  SELECT c.name AS city, ROUND(SUM(t.fare), 2) AS gross_fares, ROUND(SUM(COALESCE(p.net, 0)), 2) AS cash_collected
                  FROM trips t JOIN cities c ON c.city_id = t.city_id
                  LEFT JOIN paid p ON p.trip_id = t.trip_id
                  WHERE t.status = 'completed' GROUP BY c.name ORDER BY cash_collected DESC""")
    pay = T["payments"].assign(signed=lambda d: d.amount.where(d.status == "succeeded", 0) - d.amount.where(d.status == "refunded", 0))
    net = pay.groupby("trip_id", as_index=False).agg(net=("signed", "sum"))   # one row per trip BEFORE the merge
    m = (T["trips"].query("status == 'completed'")
         .merge(T["cities"], on="city_id")
         .merge(net, on="trip_id", how="left", validate="one_to_one"))       # raises if the fan-out ever returns
    m["net"] = m["net"].fillna(0)
    p = (m.groupby("name", as_index=False).agg(gross_fares=("fare", "sum"), cash_collected=("net", "sum"))
          .round(2).rename(columns={"name": "city"}).sort_values("cash_collected", ascending=False))
    return s, p, lambda s: chart("q2_city_cash", "bar", s, "city", "cash_collected", "Cash collected by city", "rupees")


# ── chunk 4: Q3 and Q4 — a rate with HAVING, and ranking inside groups ──
@question("Q3  Which hours of the day lose the most requests to cancellation?")
def q3():
    s = sql_df("""SELECT CAST(EXTRACT(hour FROM requested_at) AS INTEGER) AS hour, COUNT(*) AS requests,
                         ROUND(100.0 * COUNT(*) FILTER (WHERE status LIKE 'cancelled%') / COUNT(*), 2) AS cancel_pct
                  FROM trips GROUP BY 1 HAVING COUNT(*) >= 1500 ORDER BY 1""")
    d = T["trips"].assign(hour=T["trips"].requested_at.dt.hour,
                          cancelled=T["trips"].status.str.startswith("cancelled"))
    g = d.groupby("hour").agg(requests=("trip_id", "size"), cancelled=("cancelled", "sum"))
    g = g[g.requests >= 1500]                                # pandas has no HAVING: filter after the groupby
    p = g.assign(cancel_pct=(100.0 * g.cancelled / g.requests).round(2)).drop(columns="cancelled").reset_index()
    return s, p, lambda s: chart("q3_cancel_by_hour", "bar", s, "hour", "cancel_pct", "Cancellation rate by hour", "% of requests")


@question("Q4  Top 3 drivers per city by gross fares (ROW_NUMBER)")
def q4():
    s = sql_df("""WITH ranked AS (
                    SELECT c.name AS city, t.driver_id, ROUND(SUM(t.fare), 2) AS fares,
                           ROW_NUMBER() OVER (PARTITION BY c.name ORDER BY SUM(t.fare) DESC, t.driver_id) AS rk
                    FROM trips t JOIN cities c ON c.city_id = t.city_id
                    WHERE t.status = 'completed' GROUP BY c.name, t.driver_id)
                  SELECT city, rk, driver_id, fares FROM ranked WHERE rk <= 3 ORDER BY city, rk""")
    g = (T["trips"].query("status == 'completed'").merge(T["cities"], on="city_id")
         .groupby(["name", "driver_id"], as_index=False).agg(fares=("fare", "sum")).round({"fares": 2})
         .sort_values(["name", "fares", "driver_id"], ascending=[True, False, True]))
    g["rk"] = g.groupby("name").cumcount() + 1               # the pandas twin of ROW_NUMBER() OVER (PARTITION BY ...)
    p = g[g.rk <= 3].rename(columns={"name": "city"})[["city", "rk", "driver_id", "fares"]]
    def draw(s):
        top = s.query("rk == 1")
        chart("q4_top_driver", "bar", top, "city", "fares", "Best driver in each city (gross fares)", "rupees")
    return s, p, draw


# ── chunk 5: Q5 and Q6 — LAG for change, a window frame for smoothing ──
@question("Q5  Month-over-month growth of gross fares (LAG)")
def q5():
    s = sql_df("""WITH m AS (SELECT CAST(DATE_TRUNC('month', requested_at) AS DATE) AS month, SUM(fare) AS fares
                             FROM trips WHERE status = 'completed' GROUP BY 1)
                  SELECT month, ROUND(fares, 2) AS fares,
                         ROUND(100.0 * (fares - LAG(fares) OVER (ORDER BY month)) / LAG(fares) OVER (ORDER BY month), 2) AS growth_pct
                  FROM m ORDER BY month""")
    d = T["trips"].query("status == 'completed'")
    m = d.groupby(d.requested_at.dt.to_period("M").dt.to_timestamp().dt.date).fare.sum().rename("fares").reset_index()
    m = m.rename(columns={"requested_at": "month"})
    m["growth_pct"] = ((m.fares - m.fares.shift(1)) / m.fares.shift(1) * 100).round(2)   # shift(1) is LAG(1)
    m["fares"] = m.fares.round(2)
    return s, m, lambda s: chart("q5_growth", "bar", s.dropna(), "month", "growth_pct", "Month-over-month growth", "% change")


@question("Q6  Daily completed trips with a 7-day moving average")
def q6():
    s = sql_df("""WITH daily AS (SELECT CAST(requested_at AS DATE) AS day, COUNT(*) AS trips
                               FROM trips WHERE status = 'completed' GROUP BY 1)
                  SELECT day, trips,
                         ROUND(AVG(trips) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS avg_7d
                  FROM daily ORDER BY day""")
    d = T["trips"].query("status == 'completed'")
    p = d.groupby(d.requested_at.dt.date).size().rename("trips").reset_index().rename(columns={"requested_at": "day"})
    p["avg_7d"] = p.trips.rolling(7, min_periods=1).mean().round(2)     # rolling(7) is ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    return s, p, lambda s: chart("q6_moving_avg", "line", s, "day", "avg_7d", "7-day moving average of completed trips", "trips per day")


# ── chunk 6: Q7 and Q8 — a cohort (CTE + window) and a promo ledger ──
@question("Q7  Share of new riders who take a 2nd trip within 30 days, by first-trip month")
def q7():
    s = sql_df("""WITH ordered AS (
                    SELECT rider_id, requested_at,
                           ROW_NUMBER() OVER (PARTITION BY rider_id ORDER BY requested_at) AS n
                    FROM trips WHERE status = 'completed'),
                  firsts AS (
                    SELECT f.rider_id, f.requested_at AS first_at, s.requested_at AS second_at
                    FROM ordered f LEFT JOIN ordered s ON s.rider_id = f.rider_id AND s.n = 2
                    WHERE f.n = 1 AND f.requested_at < '2026-09-01')
                  SELECT CAST(DATE_TRUNC('month', first_at) AS DATE) AS cohort, COUNT(*) AS riders,
                         ROUND(100.0 * COUNT(*) FILTER (WHERE second_at <= first_at + INTERVAL '30 days') / COUNT(*), 2) AS repeat_pct
                  FROM firsts GROUP BY 1 ORDER BY 1""")
    d = T["trips"].query("status == 'completed'").sort_values(["rider_id", "requested_at"]).copy()
    d["n"] = d.groupby("rider_id").cumcount() + 1
    f = d[d.n == 1][["rider_id", "requested_at"]].rename(columns={"requested_at": "first_at"})
    f = f.merge(d[d.n == 2][["rider_id", "requested_at"]].rename(columns={"requested_at": "second_at"}), on="rider_id", how="left")
    f = f[f.first_at < "2026-09-01"]
    f["repeat"] = f.second_at <= f.first_at + pd.Timedelta(days=30)
    f["cohort"] = f.first_at.dt.to_period("M").dt.to_timestamp().dt.date
    p = f.groupby("cohort").agg(riders=("rider_id", "size"), repeat=("repeat", "mean")).reset_index()
    p["repeat_pct"] = (p.repeat * 100).round(2)
    p = p.drop(columns="repeat")
    return s, p, lambda s: chart("q7_repeat", "bar", s, "cohort", "repeat_pct", "Riders with a 2nd trip within 30 days", "% of cohort")


@question("Q8  What did each promo code cost us?")
def q8():
    s = sql_df("""SELECT p.code, COUNT(*) AS trips, ROUND(SUM(t.fare * p.discount_pct / 100.0), 2) AS discount_given,
                         ROUND(AVG(t.fare), 2) AS avg_fare
                  FROM trips t JOIN promotions p ON p.promo_id = t.promo_id
                  WHERE t.status = 'completed' GROUP BY p.code ORDER BY discount_given DESC""")
    m = T["trips"].query("status == 'completed'").merge(T["promotions"], on="promo_id")
    m["disc"] = m.fare * m.discount_pct / 100.0
    p = (m.groupby("code", as_index=False).agg(trips=("trip_id", "size"), discount_given=("disc", "sum"), avg_fare=("fare", "mean"))
          .round(2).sort_values("discount_given", ascending=False))
    return s, p, lambda s: chart("q8_promos", "bar", s, "code", "discount_given", "Discount given by promo code", "rupees")


# ── chunk 2 (tail): the entry point stays at the very bottom, below every question ──
if __name__ == "__main__":
    run_all()

Read the run as eight verified answers. Every question printed SQL == pandas: True. Nothing was merely plausible. And the file ran unchanged against PostgreSQL 18, with identical numbers: the output files from the two engines differ only in the engine name on the first line.

The eight answers, in the board's words

Each answer below has a chart file. The program saved them to code/01d-sql-data-lifecycle/out/ as q1_monthly.png to q8_promos.png. The table gives the finding, in a sentence a director can repeat, with the real numbers.

Priya's eight questions and their answers (all from board_questions.py)
#QuestionAnswerTechniqueChart file
Q1Trips and fares per monthCompleted trips grew from 2,917 in January to 7,403 in September; gross fares from 633,302 to 1,577,089 rupeesGROUP BY, DATE_TRUNCq1_monthly.png
Q2Cash collected per cityBengaluru 2,523,261.25, Mumbai 2,178,763.80, Delhi 2,120,948.30, Hyderabad 1,159,028.68, Chennai 702,528.53, Pune 595,553.18. The six sum to the dashboard's 9,280,083.74Collapse then joinq2_city_cash.png
Q3When do riders cancel?At the rush hours: 22.2% of requests at 8 a.m., 21.9% at 9, 20.4% at 5 p.m., 20.7% at 6, 21.8% at 7. Other hours run 15% to 18%HAVING, FILTERq3_cancel_by_hour.png
Q4Best driversDelhi's driver 205 leads the company with 45,637.80 in gross fares, then Mumbai's driver 288 with 42,722.64ROW_NUMBER per cityq4_top_driver.png
Q5Growth month over monthGrowth is strong but uneven: 6.2% in February, 26.4% in March, 13.5% in April, and a near-flat September (+1.2%)LAGq5_growth.png
Q6Smoothed daily trendThe 7-day average of completed trips climbs from about 85 a day in early January to about 259 at the end of SeptemberFrame of 7 rowsq6_moving_avg.png
Q7Do new riders come back?Of riders whose first trip was in January, 97.8% took a second trip within 30 days; for the August cohort the share is 72.3%. Retention is slipping across newer cohortsCTE, ROW_NUMBER, self-joinq7_repeat.png
Q8What did promos cost?WELCOME20 cost the most: 138,362.40 rupees across 3,263 trips. The five codes together gave away 324,060.27Join and ledgerq8_promos.png

The next eight pictures draw each answer from the real data, one per question, in the order the board will ask them. Each carries the numbers behind its finding.

Jan 2,917 Feb Mar 4,024 Apr May Jun Jul Aug Sep 7,403 1 2 3 completed trips per month, 2026
Fig. 1d.15 — Q1: completed trips per month.
  1. January. 2,917 completed trips: the starting level, in blue.
  2. March. 4,024 trips, up from 3,144 in February. The jump is the biggest single month of growth.
  3. September. 7,403 trips, about two and a half times January. Growth is steady every month.
Bengaluru 2,713,767 2,523,261 Mumbai 2,355,480 2,178,764 Delhi 2,287,931 2,120,948 Hyderabad 1,257,823 1,159,029 Chennai 757,802 702,529 Pune 644,087 595,553 1 2 grey: gross fares green: cash collected
Fig. 1d.16 — Q2: gross fares (grey) and cash collected (green) per city.
  1. Grey bars. What riders were quoted. Bengaluru is the biggest at 2,713,767 rupees.
  2. Green bars. What was actually collected after promos, unpaid trips and refunds. Bengaluru: 2,523,261. The six green values add to 9,280,083.74, the finance dashboard's number.
6 7 8 22.2 9 21.9 10 11 12 13 14 15 16 17 20.4 18 20.7 19 21.8 20 21 22 18.1% overall hour of day (24-hour clock) 1 2 3
Fig. 1d.17 — Q3 drawn from the real answer: the cancellation rate for each of the 17 busy hours. Only the five rush-hour bars are labelled.
  1. Morning rush. At 8 and 9 a.m. riders cancel 22.2% and 21.9% of requests, the two highest bars on the chart. The dashed line is the overall rate of 18.1%.
  2. Evening rush. At 5, 6 and 7 p.m. the rate is 20.4%, 20.7% and 21.8%. A plausible reason is longer waits when demand peaks, though the data cannot prove it.
  3. Everything else. From 10 a.m. to 4 p.m. and in the late evening, cancellations sit between 15.0% and 17.6%, below the dashed line. This is what "normal" looks like, and it is what a rush-hour fix should aim for.
Delhi driver 205: 45,637.80 Mumbai driver 288: 42,722.64 Bengaluru driver 90: 38,484.46 Chennai driver 14: 34,661.27 Pune driver 143: 34,411.20 Hyderabad driver 83: 32,125.77 1
Fig. 1d.18 — Q4: the single best driver in each city by gross fares.
  1. The leader. Delhi's driver 205 earned 45,637.80 rupees in fares, ahead of Mumbai's driver 288 (42,722.64). Bengaluru is the biggest city by trips, yet its best driver (driver 90, 38,484.46) is only third on this list. Bengaluru has 82 drivers against Delhi's 58, so its trips are shared among more people.
Feb 6.2% Mar 26.4% Apr 13.5% May 20.1% Jun 5.5% Jul 12.6% Aug 13.1% Sep 1.2% 1 2 growth in gross fares versus the previous month
Fig. 1d.19 — Q5: gross fares growth against the previous month.
  1. The March jump. Fares grew 26.4% over February. A LAG-based query makes this visible in a single column.
  2. The September stall. Only 1.2% over August. Priya should expect the board to ask about it, and the next questions are about riders: do they come back?
0 100 200 300 1 Jan 30 Sep 1 2 thin grey: the raw daily count blue: 7-day average
Fig. 1d.20 — Q6: the raw daily count of completed trips (thin grey) and its 7-day average (blue).
  1. The noise. Single days swing by 50 trips or more, because weekends are busier. Reading one day tells you little.
  2. The trend. The 7-day average removes the weekly swing and rises from about 85 trips a day to about 258 by 30 September.
Jan n = 541 97.8% Feb n = 487 89.5% Mar n = 565 81.9% Apr n = 507 77.9% May n = 502 75.3% Jun n = 450 76.7% Jul n = 363 77.1% Aug n = 303 72.3% 1 2 3 n = riders in that first-trip cohort
Fig. 1d.21 — Q7: of riders whose first trip was in a month, the share who took a second trip within 30 days.
  1. The January cohort. 541 riders, 97.8% came back.
  2. The August cohort. 303 riders, 72.3% came back. Newer riders return less often than early ones.
  3. The n values. The cohort sizes under each bar show how many riders stand behind each percentage. Smaller cohorts are noisier.
WELCOME20 138,362 (3,263 trips) WEEKEND15 96,248 (2,997 trips) BACK2RIDE 55,650 (862 trips) RAINY10 26,222 (1,220 trips) FESTIVE25 7,577 (147 trips) 1 2
Fig. 1d.22 — Q8: the discount each promo code gave away.
  1. The biggest cost. WELCOME20 gave away 138,362 rupees across 3,263 trips, 43% of all discounts (324,060 in total).
  2. The smallest. FESTIVE25 was live for only 17 days, hence 147 trips and 7,577 rupees. A small group means a noisy average fare.
Boardroom translation

"Two numbers on one table is a trust problem, not an arithmetic one. We traced the 1.9 million rupee gap to a join that counted each payment retry as another trip, proved it on four trips and on the full data, and rebuilt the numbers so they reconcile to the paisa. A seven-test pipeline now blocks the report if the data breaks again. The board gets gross fares of 10.02 million and cash collected of 9.28 million, bridged line by line."

The ROI frame: one analyst-day a month saved on reconciliation, and the avoided cost of a wrong number reaching investors. The elevator version: every figure in the board pack can be traced back to rows, and the pack refuses to build when the rows disagree.

LAB 01d — The eight board questions

Mission: extend board_questions.py into a board pack you would defend in a meeting. Run it on DuckDB first (offline), then on PostgreSQL 18, and prove the two engines give the same answers.

  • All eight questions print SQL == pandas: True on DuckDB, and again on PostgreSQL after python make_db.py --load postgres.
  • Eight chart files exist in out/, each with a title that states the finding (for example "Rush hours lose 1 in 5 requests"), not just the metric.
  • Add a ninth question of your own, such as "which city has the highest refund rate", with both the SQL and pandas versions and the same equality check.
  • Add two new tests to elt_pipeline.py: one that fails when a payment row exists for a trip that is not completed, and one that checks cash_collected never exceeds fare. Show each failing once using --poison style injected data.
  • Run EXPLAIN on your slowest query on PostgreSQL, add one index, and report the before and after time as this chapter did.
  • README documents: the three revenue numbers and the bridge, 3 failure modes you found (name the fan-out and two more), and the dialect differences you hit.

Stretch goal: rewrite the transformation layers as a dbt project (see Module 16b) and compare how much of elt_pipeline.py disappears.

12 · Interview radarHow This Shows Up in Interviews

Interview radar

Data and AI-engineering loops almost always include a live SQL round, and the graders look for the same three things: correct results, awareness of how a join or window can silently change a number, and a plan for proving the number is right.

"Write a query that returns the top three drivers by revenue in each city. What happens if two drivers tie?"

The real test Whether you reach for a window function with a partition rather than a self-join, and whether you know the three ranking functions treat ties differently.

Strong answer I total revenue per city and driver in a CTE, then number the drivers with ROW_NUMBER() OVER (PARTITION BY city ORDER BY revenue DESC, driver_id) and keep numbers one to three in an outer query, because a window function cannot be filtered in the same WHERE that contains it. Ties: ROW_NUMBER breaks them arbitrarily, so I add a second sort key to make the output repeatable. RANK would give two drivers the same place and then skip one, so "top three" could return four rows. In RideNow's data four drivers share a 5.00 rating and RANK goes 1, 1, 1, 1, 5.

Land it Use ROW_NUMBER when you need exactly N rows, RANK when ties should share a place, and always add a tie-breaker so the result is stable.

"The finance dashboard says revenue is 9.3 million and your notebook says 11.2 million. How do you find out which is right?"

The real test Debugging discipline: do you reconcile step by step, and do you know the classic causes of a number that is too big?

Strong answer First I agree on the definition: gross fares, or cash collected? Then I count rows before and after every join. If a join to a payments table turns 46,760 trips into 52,380 rows, the right side repeats keys, a fan-out, and any sum over the left side is inflated.

I confirm on a handful of trips, then fix it by collapsing payments to one row per trip before joining. Finally I build a bridge from one number to the other: gross, minus unpaid, minus discounts, minus refunds. In our case that explained the gap to the paisa.

Land it Row counts before and after a join are the cheapest debugging tool in data work, and a reconciliation bridge is how you earn the finance team's trust.

"What is the difference between WHERE and HAVING? In what order does a database run the clauses of a query?"

Strong answer WHERE filters individual rows before grouping, and HAVING filters groups after the aggregates have been computed. The logical order is FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY, and LIMIT. Because SELECT runs late, a column alias defined there cannot be used in WHERE. A practical consequence: a condition on a plain column belongs in WHERE, because it removes rows early and the database groups less data. Put it in HAVING only when it needs an aggregate, like COUNT(*) > 8000.

Land it WHERE judges rows, HAVING judges groups, and the cheapest filter is the one that runs first.

"A query on a 100-million-row table takes 30 seconds. How do you investigate and speed it up?"

The real test Whether you measure before changing anything, and whether you know an index is not always the answer.

Strong answer I run EXPLAIN (ANALYZE, BUFFERS) and read it: is there a sequential scan that returns very few rows, are the estimated and actual row counts close, and how many pages are touched? If the scan reads everything to keep 50 rows, I add an index on the filtered column.

In our measurement a one-million-row lookup went from 22.4 ms to 0.072 ms. If estimates are far off, I run ANALYZE to refresh statistics. If the query genuinely needs most of the table, an index will not help, and I look at pre-aggregating into a summary table instead.

Land it Measure with EXPLAIN first, add an index only when the plan shows a scan that keeps few rows, and remember every index taxes writes.

"How do you prevent SQL injection? Is escaping quotes enough?"

Strong answer No. Escaping is fragile. The reliable fix is parameterised queries: the SQL text has placeholders and the values travel separately, so input can never be parsed as SQL. In psycopg 3 that is execute("... WHERE email = %s", (email,)). Placeholders only work for values. A table or column name that varies must be chosen from an allow-list in code. As a second layer, the application's database user gets only the rights it needs, so even a successful injection cannot drop tables. I demonstrated the leak: one crafted email returned all 4,000 riders.

Land it Parameters for values, an allow-list for identifiers, least privilege underneath.

"What is the difference between ETL and ELT, and when would you pick each?"

Strong answer In ETL the transform happens before the load, on a separate system, so the warehouse only holds finished tables. In ELT I load the raw data first and transform inside the warehouse with SQL. I prefer ELT when the warehouse is scalable and my team writes SQL, because the raw copy lets me re-run history after a bug fix.

I choose ETL when fields must be masked or dropped before leaving the source for compliance, or when the transform is not SQL, such as parsing documents. Most real systems mix them: mask at the edge, then ELT in layers (raw, staging, mart) with tests between layers.

Land it ELT keeps the raw data so a bug is a re-run; ETL is for what must not land raw.

"Design a pipeline that produces a trusted daily revenue report from our application's PostgreSQL database."

The real test A system-design answer with stages, ownership, and failure handling, not a list of tools.

Strong answer I would not query the production database for analytics. I load a nightly copy into an analytics store, DuckDB or a warehouse depending on size, as raw tables. SQL layers then build staging, which fixes types and collapses one-to-many tables such as payments, and a mart with one row per trip and one per city and day.

After each layer, tests count bad rows: unique keys, no NULL keys, accepted values, one row per trip, and a reconciliation of mart totals to staging totals. A failed test stops the job with a non-zero exit code and blocks the report. A scheduler gives retries, and an alert tells a human.

Land it Copy raw, transform in tested layers, and let a failing test stop the report instead of shipping a plausible wrong number.

"When would you NOT use PostgreSQL for analytics?"

The real test Vendor-agnostic judgment: do you know what row stores are bad at, and can you state a switching condition?

Strong answer PostgreSQL stores rows together, which is ideal for fetching one record and slower for scanning one column across hundreds of millions of rows. I would also avoid running heavy dashboards on the same database that serves the app, since they compete for the same resources. My switching conditions are concrete:

  • Analytical scans over roughly a billion rows or more: use a columnar engine such as DuckDB, ClickHouse or a cloud warehouse.
  • Many concurrent analysts: a managed warehouse that scales compute separately.
  • Small data and one analyst: PostgreSQL is fine, and one fewer system is a feature.

Land it Postgres for serving the app, a columnar engine for scanning the history, and the boundary is a measured pain, not a fashion.

There are no dumb questions

Why does x NOT IN (subquery) sometimes return no rows at all, while NOT EXISTS works?
If the subquery returns even one NULL, NOT IN evaluates to "unknown" for every row, and unknown is not true, so no row passes. NOT EXISTS only asks whether a matching row exists and is not affected by NULLs. Prefer NOT EXISTS for anti joins, which is what the chapter used.
If I LEFT JOIN and then filter the right table in WHERE, is it still a left join?
In effect no. Unmatched rows have NULL in the right-side columns, and a WHERE test on those columns is false for NULL, so those rows disappear and you have an inner join. Put the filter in the ON clause when you want to keep unmatched left rows.
Why not filter a window function directly in WHERE?
WHERE runs before windows are computed. Compute the window in a CTE or subquery and filter in the outer query. DuckDB also offers QUALIFY, which PostgreSQL does not.
Why store money as NUMERIC rather than a float?
Floats cannot represent most decimal fractions exactly, so sums drift by tiny amounts that break reconciliation. NUMERIC(10,2) stores exact decimals. This chapter's schema uses it, and pandas needs a cast to float, so pandas sums are compared with a tolerance of one hundredth.
Does SQL run top to bottom like Python?
No. SQL is declarative: you describe the result and the planner picks the steps. The order you write the clauses is not the order they run. That order is shown in Fig. 1d.3.

13 · RecapWhat You Can Do Now

  • You can read a normalised schema, name its primary and foreign keys, and say which arrow is one-to-many.
  • You can write SELECT, WHERE, GROUP BY and HAVING queries and predict the row count after each step.
  • You can spot a join fan-out by counting rows before and after, explain it on a four-row example, and fix it by collapsing the many side first.
  • You can use a CTE to name each step, and write a recursive CTE with an anchor, a step and a stop.
  • You can use window functions (ROW_NUMBER, RANK, LAG, running totals, a 7-row frame) and explain what PARTITION BY and the frame each do.
  • You can read an EXPLAIN plan, add an index, and measure the before and after.
  • You can build a raw, staging and mart ELT pipeline in SQL with data tests that stop the report, and explain when ETL is the better choice.
  • You can connect Python to PostgreSQL with psycopg 3 and SQLAlchemy 2.0, prevent SQL injection with parameters, and answer every question in SQL and pandas with the two proven equal.
🧠 Flex your memory

From this module: without looking, sketch the four trips and eight payment rows from the fan-out, say what SUM(fare) returns after the join and what it should return, and name the one-line fix.

From an earlier module: Module 01b taught that rates based on small groups are noisy. Look at Q7 and Q8 again. The August cohort has only 303 riders and FESTIVE25 only 147 trips. Which of Priya's eight answers would you caution the board about, and what would you check before trusting a difference between two of those numbers?

Reveal a model answer

Q7's August cohort (303 riders, 72.3% repeat) and Q8's FESTIVE25 (147 trips) rest on small groups, so differences of a few percentage points between them and larger groups could be luck.

Before quoting them, compute how much a rate from 303 riders can wobble by chance, which is the standard-error idea from 01b, and compare the cohorts with that margin. The January cohort has 541 riders, so even a 25-point gap between January and August is far larger than the margin and is likely real. A one-point gap between two codes would not be.