Today is about concepts, not syntax. Every analysis you will write in SQL or pandas is built from a handful of operations that change the shape of a table. If you can picture the shape before and after, the code becomes the easy part.
A row is one observation, a column is one attribute, and a null is a value we don’t know, which is not the same as zero. The grain says what one row represents: one order, one order line, one customer. Ask “what is one row?” before every analysis.
One Table: orders PK unique FK → customers FK → employees FK → shippers order_id smallint customer_id bpchar employee_id smallint order_date date required_date date shipped_date date ship_via smallint freight real ship_city varchar(15) ship_region varchar(15) ship_country varchar(15) … +3 more 10501 MAPLE 3 2026-03-02 2026-03-30 2026-03-05 1 12.40 Toronto ON Canada 10502 RIVER 7 2026-03-02 2026-03-30 2026-03-09 3 48.75 Lyon NULL France 10503 SUNNY 5 2026-03-03 2026-03-31 2026-03-06 2 23.65 Atlanta GA USA 10504 ALPIN 1 2026-03-04 2026-04-01 2026-03-06 1 95.20 Graz NULL Austria 10505 MAPLE 3 2026-03-04 2026-04-01 NULL 2 7.10 Toronto ON Canada ⋮ the real Northwind table has 830 orders ROW = one observation order 10505: one order NULL = unknown not shipped yet — not “zero” COLUMN = one attribute freight: one meaning, one type GRAIN: one row per order order_id unique; customer_id repeats A concrete table before we start transforming anything: the orders table from the Northwind database, with made-up values. One row is one order (the grain), so order_id, the primary key, never repeats. customer_id, employee_id and ship_via are foreign keys: they point to rows in other tables, and they can repeat, since MAPLE has two orders here. Each column holds one attribute with one type; the second header line shows the SQL type. NULL means unknown: order 10505 hasn’t shipped yet, and a French or Austrian address simply has no region. Neither is zero or an empty string.
Here is the whole session on one assembly line: filter and sort, join, group by, aggregate, window. We’ll take the stations one at a time and watch what each does to the height (rows) and width (columns) of the table.
A filter removes rows and keeps every column, so the grain stays the same and you just have fewer observations. SQL: WHERE. pandas: df.loc[mask]. Watch out for nulls: a row whose value is unknown does not pass a test like amount > 50.
Filter in code
FILTER: WHERE ↔ df.loc[mask]
SQL pandas One condition: orders with freight above $50
SELECT *
FROM orders
WHERE freight > 50 ; -- 10504 orders. loc[orders["freight" ] > 50 ]
# 10504 Several conditions, and only some columns
SELECT order_id, customer_id, freight
FROM orders
WHERE ship_country = 'Canada'
AND order_date >= '2026-03-03' ; -- 10505 orders. loc[
(orders["ship_country" ] == "Canada" )
& (orders["order_date" ] >= "2026-03-03" ),
["order_id" , "customer_id" , "freight" ],
] # 10505 Missing values: orders not shipped yet
SELECT order_id, order_date
FROM orders
WHERE shipped_date IS NULL ; -- 10505 orders. loc[orders["shipped_date" ]. isna(),
["order_id" , "order_date" ]]
# 10505 Rows get fewer, columns stay the same (unless you pick them). = NULL never matches: use IS NULL / .isna(). In pandas, put each condition in ( ) and combine with & (and) or | (or).
Same three questions, two notations, run against the orders table from the start of the deck. The results (the comments) are the rows from that slide. SQL names the table in FROM and the condition in WHERE. pandas builds a True/False mask and passes it to .loc, with an optional list of columns as the second argument. Point out the two classic traps: shipped_date = NULL returns nothing because nothing equals an unknown value, and in pandas the parentheses around each comparison are required because & binds tighter than ==.
Sorting changes nothing but the order. Every row survives. It’s how we find the largest, smallest, or most recent. A SQL result has no guaranteed order without ORDER BY, so sort explicitly whenever order matters, and add a tie-breaker.
Sort in code
SORT: ORDER BY ↔ sort_values()
SQL pandas Most expensive shipping first
SELECT order_id, freight
FROM orders
ORDER BY freight DESC ; -- 10504, 10502, ... orders. sort_values("freight" , ascending= False )
# 10504, 10502, ... Several sort keys, with a tie-breaker
SELECT *
FROM orders
ORDER BY ship_country,
order_date DESC ,
order_id;orders. sort_values(
["ship_country" , "order_date" , "order_id" ],
ascending= [True , False , True ],
) Top 3, with missing values at the end
SELECT order_id, shipped_date
FROM orders
ORDER BY shipped_date DESC NULLS LAST
LIMIT 3 ;(orders
. sort_values("shipped_date" , ascending= False ,
na_position= "last" )
. head(3 )[["order_id" , "shipped_date" ]]) Every row survives; only the order changes. Without ORDER BY, SQL promises no order. Add a unique column (order_id) as the last key so ties come out the same every time.
Sorting never changes which rows you have, only their sequence. DESC / ascending=False reverses a key, and each key can have its own direction. The tie-breaker matters: two orders on the same date could come out in either order, and a unique last key such as order_id makes the result reproducible, also between SQL and pandas. Nulls differ between tools: PostgreSQL puts NULLs last when sorting ascending but first when sorting descending, while pandas puts them last either way unless na_position says otherwise. Writing NULLS LAST / na_position=“last” explicitly removes the guesswork. LIMIT and head() only make sense after a sort: “top 3” of an unsorted table is just three arbitrary rows.
Why do businesses split data across tables? Normalization: store each fact with the entity it describes. A customer’s address lives once in Customers, not on every order. That prevents inconsistent copies, but to answer most questions we have to bring the tables back together. The key is the bridge.
The Northwind Database customer_demographics PK customer_type_id customer_desc customer_customer_demo PK FK customer_id PK FK customer_type_id shippers PK shipper_id company_name phone categories PK category_id category_name description us_states PK state_id state_name state_abbr no relationships customers PK customer_id company_name contact_name city region country + 5 more orders PK order_id FK customer_id FK employee_id order_date shipped_date FK ship_via freight ship_country + 6 more order_details PK FK order_id PK FK product_id unit_price quantity discount products PK product_id product_name FK supplier_id FK category_id unit_price units_in_stock discontinued + 3 more suppliers PK supplier_id company_name city country + 8 more employees PK employee_id last_name first_name title hire_date FK reports_to + 12 more employee_territories PK FK employee_id PK FK territory_id territories PK territory_id territory_description FK region_id region PK region_id region_description Legend PK primary key FK foreign key one … many used in the notebooks supporting tables Here is the database we query in the notebooks. Read the lines as one-to-many: one customer places many orders, one order has many order lines, one product appears on many order lines. order_details sits in the middle and resolves the many-to-many relationship between orders and products; its primary key is the pair (order_id, product_id). Two things to point out: unit_price appears in both order_details (the price actually charged) and products (today’s list price), and employees.reports_to points back into employees, which is a self-join. The gray tables are supporting data we won’t use.
A join adds columns: the order row picks up the customer’s name. The number of rows depends on the matches. One-to-one keeps it, one-to-many multiplies it, and duplicate keys can silently inflate totals. Always name the key (ON / on=) and check the row count afterwards.
INNER JOIN, step by step orders left table · one row per order order_id customer_id freight 10501 MAPLE 12.40 10502 RIVER 48.75 10503 SUNNY 23.65 10504 ALPIN 95.20 10505 MAPLE 7.10 customers right table · one row per customer customer_id company_name city MAPLE Maple Street Deli Toronto OAKLY Oak Lane Grocers Portland RIVER Riverside Bistro Lyon SUNNY Sunny Side Café Atlanta ✕ no customer ALPIN no orders ✕ INNER JOIN on customer_id SQL SELECT * FROM orders AS o INNER JOIN customers AS c ON o.customer_id = c.customer_id; pandas orders.merge(customers, on="customer_id", how="inner") result one row per matched order · 4 rows × 5 columns order_id customer_id freight company_name city 10501 MAPLE 12.40 Maple Street Deli Toronto 10502 RIVER 48.75 Riverside Bistro Lyon 10503 SUNNY 23.65 Sunny Side Café Atlanta 10505 MAPLE 7.10 Maple Street Deli Toronto ✓ Matched rows survive 4 of the 5 orders have a customer, so the result has 4 rows. ✕ Unmatched rows disappear Order 10504 (customer ALPIN is unknown) and customer OAKLY (no orders). ↻ One-to-many repeats the “one” side MAPLE has two orders, so its name and city appear twice. ⇔ Shape: width grows, height depends 3 + 2 columns (the key once); rows = number of matched pairs. Walk through it line by line. Each order looks up its customer_id in customers; the colored lines are the matches. Order 10504 points to ALPIN, which doesn’t exist in customers, so an inner join drops it. OAKLY never ordered anything, so it’s dropped too. MAPLE has two orders, so both find the same customer row, and MAPLE’s name and city are copied into two result rows. That’s normal for one-to-many, but it’s why summing a customer-level number after this join would double-count. Ask the class: how many rows would we get if customers accidentally had MAPLE twice? (Answer: 6, since each MAPLE order matches both copies.) In pandas, validate=“many_to_one” would catch that.
LEFT JOIN, step by step orders left table · one row per order order_id customer_id freight 10501 MAPLE 12.40 10502 RIVER 48.75 10503 SUNNY 23.65 10504 ALPIN 95.20 10505 MAPLE 7.10 customers right table · one row per customer customer_id company_name city MAPLE Maple Street Deli Toronto OAKLY Oak Lane Grocers Portland RIVER Riverside Bistro Lyon SUNNY Sunny Side Café Atlanta no match → NULLs no orders ✕ LEFT JOIN on customer_id SQL SELECT * FROM orders AS o LEFT JOIN customers AS c ON o.customer_id = c.customer_id; pandas orders.merge(customers, on="customer_id", how="left") result one row per order · 5 rows × 5 columns (as many rows as orders) order_id customer_id freight company_name city 10501 MAPLE 12.40 Maple Street Deli Toronto 10502 RIVER 48.75 Riverside Bistro Lyon 10503 SUNNY 23.65 Sunny Side Café Atlanta 10504 ALPIN 95.20 NULL NULL 10505 MAPLE 7.10 Maple Street Deli Toronto ✓ Every left row survives 5 orders in, 5 rows out: the grain of orders is kept. ∅ No match → NULL Order 10504 stays; its company_name and city are NULL. ✕ Right-only rows still disappear Customer OAKLY has no orders, so it is not in the result. ⚠ Check the row count Unique key on the right: rows out = rows in. More means duplicates. Same two tables, one word changed: LEFT instead of INNER. Now every order survives. Order 10504 still has no matching customer, but instead of disappearing it’s kept, and the customer columns are filled with NULL: we don’t know who ALPIN is. OAKLY is still missing, because a left join only protects rows of the left table. This is the join to use when the left table defines the grain you want, for example every order in a report whether or not the customer record is complete. The row-count check: if customer_id is unique in customers, a left join returns exactly as many rows as orders. More rows means the right key has duplicates. Finding the unmatched rows (WHERE c.customer_id IS NULL, or indicator=True in pandas) is also a quick data-quality check.
Inner: only matched pairs. Left: every left row, with nulls where there is no match. Right: the mirror image. Full outer: everything. The choice is a business decision. Do you want to see orders from unknown customers, or customers who never ordered? In Northwind, a left join finds the two customers with no orders.
Join in code
JOIN: JOIN … ON ↔ merge(on=, how=)
SQL pandas Inner join: orders with their customer's name
SELECT o.order_id, o.freight, c .company_name
FROM orders AS o
INNER JOIN customers AS c
ON o.customer_id = c .customer_id; -- 4 rows orders. merge(
customers[["customer_id" , "company_name" ]],
on= "customer_id" , how= "inner" ,
)[["order_id" , "freight" , "company_name" ]] # 4 rows Left join: find orders whose customer is missing
SELECT o.order_id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c
ON o.customer_id = c .customer_id
WHERE c .customer_id IS NULL ; -- 10504 j = orders. merge(customers, on= "customer_id" ,
how= "left" , indicator= True )
j. loc[j["_merge" ] == "left_only" ,
["order_id" , "customer_id" ]] # 10504 Right and full outer join
-- every customer survives: 5 rows
... RIGHT JOIN customers AS c ON ...
-- everything survives: 6 rows
... FULL OUTER JOIN customers AS c ON ...# every customer survives: 5 rows
orders. merge(customers, on= "customer_id" , how= "right" )
# everything survives: 6 rows
orders. merge(customers, on= "customer_id" , how= "outer" ) Always name the key (ON / on=); for different names use left_on= / right_on=. Check the row count after every join. validate="many_to_one" makes pandas stop if a customer appears twice.
The same joins from the diagrams, now as code; the row counts in the comments match the pictures. SQL uses table aliases (o, c) so every column says where it comes from. pandas merge needs the key in on= and the join type in how=; the default is inner. The second example is a pattern worth memorizing: a left join followed by “right side is NULL” finds rows without a match. In pandas, indicator=True adds a _merge column saying both, left_only, or right_only. Right join is just a left join with the tables swapped; most people write left joins. Full outer (how=“outer”) keeps everything, which is useful for reconciling two lists. Warn against leaving out the key: pandas then joins on every column name the tables share, and SQL NATURAL JOIN does the same. In Northwind, orders and products both have unit_price, and a join on both silently drops rows.
Grouping on its own doesn’t remove anything. It sorts the rows into buckets that share a key, here the customer ID. It’s the preparation step, and the next slide shows what we do with each bucket.
Aggregation collapses each group to one row: a count, sum, or average. The grain changes from one row per order to one row per customer, and the individual orders are gone. COUNT(*) counts rows, COUNT(column) counts known values. WHERE filters before grouping, HAVING after.
GROUP BY + aggregate, step by step 1 · orders one row per order · 7 rows order_id customer_id freight 10501 MAPLE 12.40 10502 RIVER 48.75 10503 SUNNY 23.65 10504 ALPIN 95.20 10505 MAPLE 7.10 10506 RIVER 30.00 10507 MAPLE NULL 2 · GROUP BY customer_id rows sorted into buckets · still 7 rows customer_id = MAPLE 10501 12.40 10505 7.10 10507 NULL customer_id = RIVER 10502 48.75 10506 30.00 customer_id = SUNNY 10503 23.65 customer_id = ALPIN 10504 95.20 3 · aggregate each group one row per customer · 4 rows customer_id group key n_orders COUNT(*) n_freight COUNT(freight) total_freight SUM(freight) MAPLE 3 2 19.50 RIVER 2 2 78.75 SUNNY 1 1 23.65 ALPIN 1 1 95.20 MAPLE: 3 orders, but only 2 known freight values COUNT(*) counts rows; COUNT(freight) and SUM(freight) skip NULL. The grain changes: 7 orders → 4 customers Individual orders are gone; only the key and the summaries remain. Every output column is the key or an aggregate order_id is not in the result: which of MAPLE's three would it be? Two new orders arrived since the orders slide: a second one for RIVER and a third for MAPLE whose freight isn’t known yet. Step 2 is GROUP BY on its own: nothing is removed, the seven rows are just sorted into one bucket per customer. Step 3 is the aggregation: each bucket becomes exactly one row, and every column is either the group key or a summary of the bucket. Point at MAPLE: COUNT(*) says 3 because there are three rows, COUNT(freight) says 2 because one freight is NULL, and SUM(freight) adds only the two known values. The NULL is skipped, not treated as zero. Ask: why can’t order_id be in the result? MAPLE has three of them, and a group row can only hold one value per column.
Group and aggregate in code
GROUP BY ↔ groupby().agg()
SQL pandas Several summaries per customer, largest total first
SELECT customer_id,
COUNT (* ) AS n_orders,
COUNT (freight) AS n_freight,
SUM (freight) AS total_freight
FROM orders
GROUP BY customer_id
ORDER BY total_freight DESC ;(orders
. groupby("customer_id" , as_index= False )
. agg(n_orders= ("order_id" , "size" ),
n_freight= ("freight" , "count" ),
total_freight= ("freight" , "sum" ))
. sort_values("total_freight" , ascending= False )) Filter groups after aggregating: HAVING
SELECT customer_id, COUNT (* ) AS n_orders
FROM orders
GROUP BY customer_id
HAVING COUNT (* ) >= 2 ; -- MAPLE, RIVER n = (orders. groupby("customer_id" , as_index= False )
. agg(n_orders= ("order_id" , "size" )))
n. loc[n["n_orders" ] >= 2 ] # MAPLE, RIVER Filter rows before grouping: WHERE
SELECT customer_id, SUM (freight) AS total
FROM orders
WHERE order_date >= '2026-03-03'
GROUP BY customer_id;(orders. loc[orders["order_date" ] >= "2026-03-03" ]
. groupby("customer_id" , as_index= False )
. agg(total= ("freight" , "sum" ))) COUNT(*) / "size" count rows; COUNT(col) / "count" skip NULL. WHERE filters rows before grouping, HAVING filters groups after .
The first example is the diagram as code: it produces exactly the table from the previous slide, sorted by total. In pandas, agg takes one argument per output column: new_name=(input column, function). “size” counts rows like COUNT(*), “count” counts non-missing values like COUNT(freight). as_index=False keeps customer_id as a normal column, so the result looks like the SQL table. The second and third examples are the classic WHERE-versus-HAVING question. HAVING can use an aggregate because it runs after grouping; WHERE can’t, because the groups don’t exist yet. pandas has no HAVING keyword: aggregate first, then filter the aggregated table with a normal mask. One difference to mention: for a group whose values are all NULL, SQL SUM returns NULL but pandas sum returns 0 unless you use sum(min_count=1). Also, neither tool promises a particular group order unless you sort: pandas happens to sort the keys, SQL gives no guarantee.
Aggregating gives the totals but loses the details. Filtering and sorting keep the details but give no totals. What if the question needs both, like “each order next to that customer’s average”? Ask the class how they would do it with what we have so far (answer: aggregate, then join back).
A window function computes over related rows but keeps every row and adds the result as a new column. SQL: AVG(amount) OVER (PARTITION BY customer_id). pandas: groupby(…).transform(“mean”). Ranks, running totals, and previous-row values (LAG / shift) work the same way.
WINDOW functions, step by step 1 · orders one row per order · 7 rows order_id customer_id freight 10501 MAPLE 12.40 10502 RIVER 48.75 10503 SUNNY 23.65 10504 ALPIN 95.20 10505 MAPLE 7.10 10506 RIVER 30.00 10507 MAPLE NULL 2 · PARTITION BY customer_id each row sees its window · ORDER BY order_id window: MAPLE # 10501 12.40 1 10505 7.10 2 10507 NULL 3 SUM(freight) = 19.50 window: RIVER # 10502 48.75 1 10506 30.00 2 SUM(freight) = 78.75 window: SUNNY # 10503 23.65 1 SUM(freight) = 23.65 window: ALPIN # 10504 95.20 1 SUM(freight) = 95.20 3 · result still one row per order · 7 rows, 2 new columns order_id customer_id freight customer_total SUM() OVER order_no ROW_NUMBER() 10501 MAPLE 12.40 19.50 1 10502 RIVER 48.75 78.75 1 10503 SUNNY 23.65 23.65 1 10504 ALPIN 95.20 95.20 1 10505 MAPLE 7.10 19.50 2 10506 RIVER 30.00 78.75 2 10507 MAPLE NULL 19.50 3 Height unchanged, width grows 7 rows in, 7 rows out; the window results become new columns. The group value is repeated on every row of the group All three MAPLE orders show 19.50, including 10507 whose freight is NULL. Compare GROUP BY: same numbers, but the orders are kept Now you can ask “what share of the customer’s total is this order?” Same seven orders and the same buckets as the GROUP BY slide, but look at the lines on the right: seven go out, one per order, instead of four. PARTITION BY says which rows belong together, like GROUP BY, but nothing is collapsed. Each row looks at its own window, and the result is written back onto that row. SUM(freight) OVER the MAPLE window is 19.50, and all three MAPLE rows get it, even 10507, whose own freight is unknown. ROW_NUMBER needs an order inside the window, here order_id, and numbers the rows 1, 2, 3 within each customer. This answers the dilemma from two slides ago: each individual order next to its customer’s total. From there, freight / customer_total is each order’s share.
Windows in code
SQL pandas The customer's total next to every order
SELECT order_id, customer_id, freight,
SUM (freight) OVER (PARTITION BY customer_id)
AS customer_total
FROM orders; -- still 7 rows orders["customer_total" ] = (orders
. groupby("customer_id" )["freight" ]
. transform("sum" )) # still 7 rows Number the orders within each customer
SELECT order_id, customer_id,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_id) AS order_no
FROM orders;orders = orders. sort_values(["customer_id" , "order_id" ])
orders["order_no" ] = (orders
. groupby("customer_id" ). cumcount() + 1 ) The previous order's freight, per customer (sorted as above)
SELECT order_id, customer_id, freight,
LAG(freight) OVER (PARTITION BY customer_id
ORDER BY order_id) AS prev_freight
FROM orders;orders["prev_freight" ] = (orders
. groupby("customer_id" )["freight" ]
. shift(1 )) # first row: NaN PARTITION BY = which rows belong together; ORDER BY inside OVER = their sequence. The row count never changes. In pandas: transform for group values; sort first, then cumcount, shift, cumsum.
Compare with the GROUP BY code slide: the SQL is almost the same aggregate, SUM(freight), but OVER (PARTITION BY …) replaces GROUP BY, and the result keeps all rows. In pandas the difference is one word: .agg() returns one row per group, .transform() returns one value per original row, lined up with the original index, so it can be assigned as a new column. The second and third examples need an order inside each window. SQL puts it in OVER (… ORDER BY …). pandas has no such clause, so we sort the table first; cumcount and shift then follow the current row order within each group. Forgetting to sort is the most common bug here. LAG returns NULL for the first row of each window, and shift returns NaN: there is no previous order. Mention that the final output order in SQL is still undefined unless the outer query has ORDER BY; the ORDER BY inside OVER only controls the calculation.
Side by side: GROUP BY destroys the grain, windowing preserves it. “Total sales per customer” means GROUP BY. “Every sale next to its customer’s total” means a window. Before writing code, decide whether the answer should have one row per group or one row per original record.
A full business question: total spending by active customers, highest first. Join customers and orders, filter to active, group and aggregate, sort. SQL is declarative: you state the result and the database plans the steps. In pandas you chain the same steps yourself. Same pipeline, different notation.
The four moves: carve (filter and sort), connect (join), compress (aggregate), contextualize (window). For any operation, ask what one row is before and after, and how the height and width change. Next up are the notebooks, where we run each move in both SQL and pandas on Northwind.