One Table: orders

PKuniqueFK→ customersFK→ employeesFK→ shippersorder_idsmallintcustomer_idbpcharemployee_idsmallintorder_datedaterequired_datedateshipped_datedateship_viasmallintfreightrealship_cityvarchar(15)ship_regionvarchar(15)ship_countryvarchar(15)…+3 more10501MAPLE32026-03-022026-03-302026-03-05112.40TorontoONCanada10502RIVER72026-03-022026-03-302026-03-09348.75LyonNULLFrance10503SUNNY52026-03-032026-03-312026-03-06223.65AtlantaGAUSA10504ALPIN12026-03-042026-04-012026-03-06195.20GrazNULLAustria10505MAPLE32026-03-042026-04-01NULL27.10TorontoONCanada⋮the real Northwind table has 830 ordersROW = one observationorder 10505: one orderNULL = unknownnot shipped yet — not “zero”COLUMN = one attributefreight: one meaning, one typeGRAIN: one row per orderorder_id unique; customer_id repeats

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).

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.

The Northwind Database

customer_demographicsPKcustomer_type_idcustomer_desccustomer_customer_demoPKFKcustomer_idPKFKcustomer_type_idshippersPKshipper_idcompany_namephonecategoriesPKcategory_idcategory_namedescriptionus_statesPKstate_idstate_namestate_abbrno relationshipscustomersPKcustomer_idcompany_namecontact_namecityregioncountry+ 5 moreordersPKorder_idFKcustomer_idFKemployee_idorder_dateshipped_dateFKship_viafreightship_country+ 6 moreorder_detailsPKFKorder_idPKFKproduct_idunit_pricequantitydiscountproductsPKproduct_idproduct_nameFKsupplier_idFKcategory_idunit_priceunits_in_stockdiscontinued+ 3 moresuppliersPKsupplier_idcompany_namecitycountry+ 8 moreemployeesPKemployee_idlast_namefirst_nametitlehire_dateFKreports_to+ 12 moreemployee_territoriesPKFKemployee_idPKFKterritory_idterritoriesPKterritory_idterritory_descriptionFKregion_idregionPKregion_idregion_descriptionLegendPKprimary keyFKforeign keyone … manyused in the notebookssupporting tables

INNER JOIN, step by step

ordersleft table · one row per orderorder_idcustomer_idfreight10501MAPLE12.4010502RIVER48.7510503SUNNY23.6510504ALPIN95.2010505MAPLE7.10customersright table · one row per customercustomer_idcompany_namecityMAPLEMaple Street DeliTorontoOAKLYOak Lane GrocersPortlandRIVERRiverside BistroLyonSUNNYSunny Side CaféAtlanta✕ no customer ALPINno orders ✕INNER JOIN on customer_idSQLSELECT *FROM orders AS oINNER JOIN customers AS cON o.customer_id = c.customer_id;pandasorders.merge(customers,on="customer_id", how="inner")resultone row per matched order · 4 rows × 5 columnsorder_idcustomer_idfreightcompany_namecity10501MAPLE12.40Maple Street DeliToronto10502RIVER48.75Riverside BistroLyon10503SUNNY23.65Sunny Side CaféAtlanta10505MAPLE7.10Maple Street DeliToronto✓Matched rows survive4 of the 5 orders have a customer, so the result has 4 rows.✕Unmatched rows disappearOrder 10504 (customer ALPIN is unknown) and customer OAKLY (no orders).↻One-to-many repeats the “one” sideMAPLE has two orders, so its name and city appear twice.⇔Shape: width grows, height depends3 + 2 columns (the key once); rows = number of matched pairs.

LEFT JOIN, step by step

ordersleft table · one row per orderorder_idcustomer_idfreight10501MAPLE12.4010502RIVER48.7510503SUNNY23.6510504ALPIN95.2010505MAPLE7.10customersright table · one row per customercustomer_idcompany_namecityMAPLEMaple Street DeliTorontoOAKLYOak Lane GrocersPortlandRIVERRiverside BistroLyonSUNNYSunny Side CaféAtlantano match → NULLsno orders ✕LEFT JOIN on customer_idSQLSELECT *FROM orders AS oLEFT JOIN customers AS cON o.customer_id = c.customer_id;pandasorders.merge(customers,on="customer_id", how="left")resultone row per order · 5 rows × 5 columns (as many rows as orders)order_idcustomer_idfreightcompany_namecity10501MAPLE12.40Maple Street DeliToronto10502RIVER48.75Riverside BistroLyon10503SUNNY23.65Sunny Side CaféAtlanta10504ALPIN95.20NULLNULL10505MAPLE7.10Maple Street DeliToronto✓Every left row survives5 orders in, 5 rows out: the grain of orders is kept.∅No match → NULLOrder 10504 stays; its company_name and city are NULL.✕Right-only rows still disappearCustomer OAKLY has no orders, so it is not in the result.⚠Check the row countUnique key on the right: rows out = rows in. More means duplicates.

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.

GROUP BY + aggregate, step by step

1 · ordersone row per order · 7 rowsorder_idcustomer_idfreight10501MAPLE12.4010502RIVER48.7510503SUNNY23.6510504ALPIN95.2010505MAPLE7.1010506RIVER30.0010507MAPLENULL2 · GROUP BY customer_idrows sorted into buckets · still 7 rowscustomer_id = MAPLE1050112.40105057.1010507NULLcustomer_id = RIVER1050248.751050630.00customer_id = SUNNY1050323.65customer_id = ALPIN1050495.203 · aggregate each groupone row per customer · 4 rowscustomer_idgroup keyn_ordersCOUNT(*)n_freightCOUNT(freight)total_freightSUM(freight)MAPLE3219.50RIVER2278.75SUNNY1123.65ALPIN1195.20MAPLE: 3 orders, but only 2 known freight valuesCOUNT(*) counts rows; COUNT(freight) and SUM(freight) skip NULL.The grain changes: 7 orders → 4 customersIndividual orders are gone; only the key and the summaries remain.Every output column is the key or an aggregateorder_id is not in the result: which of MAPLE's three would it be?

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.

WINDOW functions, step by step

1 · ordersone row per order · 7 rowsorder_idcustomer_idfreight10501MAPLE12.4010502RIVER48.7510503SUNNY23.6510504ALPIN95.2010505MAPLE7.1010506RIVER30.0010507MAPLENULL2 · PARTITION BY customer_ideach row sees its window · ORDER BY order_idwindow: MAPLE#1050112.401105057.10210507NULL3SUM(freight) =19.50window: RIVER#1050248.7511050630.002SUM(freight) =78.75window: SUNNY#1050323.651SUM(freight) =23.65window: ALPIN#1050495.201SUM(freight) =95.203 · resultstill one row per order · 7 rows, 2 new columnsorder_idcustomer_idfreightcustomer_totalSUM() OVERorder_noROW_NUMBER()10501MAPLE12.4019.50110502RIVER48.7578.75110503SUNNY23.6523.65110504ALPIN95.2095.20110505MAPLE7.1019.50210506RIVER30.0078.75210507MAPLENULL19.503Height unchanged, width grows7 rows in, 7 rows out; the window results become new columns.The group value is repeated on every row of the groupAll three MAPLE orders show 19.50, including 10507 whose freight is NULL.Compare GROUP BY: same numbers, but the orders are keptNow you can ask “what share of the customer’s total is this order?”

Windows in code

WINDOW: OVER (…) ↔ transform()

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.

◀ Slides