Skip to content

30. SQL for data analysis

Most company data lives in databases, not in CSV files. The sales of a shop, the users of a web app and the events of a mobile game sit in tables inside a database, and the way to ask those tables a question is SQL. An analyst who knows SQL gets answers straight from the source. An analyst who does not waits for an export.

This module teaches SQL from Python. You query the course database data/shop.db with the standard-library module sqlite3, and you query the same data, plus CSV and Parquet files and pandas DataFrames, with DuckDB. Every question in this module is a real analysis question about the course shop: revenue by category, customers who never ordered, month-over-month growth, the top products per region.

  • Connect to SQLite and DuckDB from Python, run a query, fetch the rows and print them in a table that fits 100 characters.
  • Filter, sort and summarize with SELECT, WHERE, ORDER BY, LIMIT, aggregate functions, GROUP BY, HAVING and CASE WHEN.
  • Combine tables with inner, left, right and full joins, and find missing matches with an anti-join (NOT EXISTS, or LEFT JOIN … IS NULL).
  • Structure a long query with CTEs (WITH), and compute rankings, running totals, month-over-month changes and moving averages with window functions.
  • Handle dates in SQLite (text) and DuckDB (a real DATE type), and pass values safely with ? placeholders instead of building SQL with f-strings.
  • Move data between pandas and SQL (pd.read_sql_query, df.to_sql, DuckDB on a DataFrame, .df()), and choose SQL or pandas for a task.

A database is an organized store of data that a program manages for you. A relational database keeps the data in tables. A table has named columns, each with a type, and rows, one per record. It is the same shape as a DataFrame.

The program that stores the data and answers questions is the database engine. You talk to it in SQL (Structured Query Language, said “S-Q-L” or “sequel”). A query is one SQL request, such as “give me the revenue per region”.

SQL is a declarative language: you describe the result you want, and the engine decides how to compute it. In pandas you write the steps (filter, then group, then sum). In SQL you write one statement, and the engine picks the order, the indexes and the algorithm. This is why the same query idea carries from a laptop file to a cluster, with small changes for each engine’s dialect (its variant of SQL).

The course database data/shop.db has four tables. Its schema, the description of the tables, their columns and the links between them, looks like this:

erDiagram
    stores ||--o{ orders : "store_id"
    products ||--o{ orders : "product_id"
    customers ||--o{ orders : "customer_id"
    stores {
        TEXT store_id PK
        TEXT city
        TEXT region
        INTEGER size_sqm
        TEXT opened
    }
    products {
        TEXT product_id PK
        TEXT product
        TEXT category
        REAL unit_cost
        REAL unit_price
        TEXT launch_date
    }
    customers {
        TEXT customer_id PK
        TEXT plan
        TEXT region
        INTEGER churned
    }
    orders {
        INTEGER line_id PK
        TEXT order_id
        TEXT order_date
        TEXT customer_id FK
        TEXT store_id FK
        TEXT product_id FK
        INTEGER quantity
        REAL revenue
    }

The diagram shows only the key columns of customers and orders. Two words describe the links:

  • A primary key (PK) is a column whose value identifies exactly one row. store_id is the primary key of stores: no two stores share an id.
  • A foreign key (FK) is a column that holds the primary key of another table. orders.store_id says which store sold the line. The engine can follow it to the store row.

orders is a fact table: one row per event (a sales line), with numbers to add up. stores, products and customers are dimension tables: one row per thing, with descriptions to group by. Most analysis queries join a fact table to its dimensions. orders holds the same 20,228 lines as data/sales.csv, but without the region, product and category columns. You get those with a join.

This module uses two engines. Both are embedded databases: the engine is a library that runs inside your Python process. There is no server to install, no user name and no password. A database is a file, or lives only in memory.

SQLite DuckDB
Comes with Python (import sqlite3) the duckdb package
Built for OLTP: many small reads and writes (apps, phones, browsers) OLAP: big scans and aggregations (analysis)
Storage rows, in one .db file columns, in one .duckdb file or in memory
Reads CSV and Parquet directly no yes: FROM 'data/sales.csv'
Queries a pandas DataFrame no (copy it in with to_sql) yes, by its variable name
Date type none: dates are TEXT real DATE and TIMESTAMP types
5 / 2 2 (integer division) 2.5

OLTP (online transaction processing) means many short operations on single rows: “add this order”, “update this address”. OLAP (online analytical processing) means few long queries over many rows: “revenue per month for two years”. Columnar storage keeps each column together on disk and in memory, so a query that sums one column reads only that column. That is why DuckDB is fast for analysis.

Large companies run client-server databases such as PostgreSQL, MySQL, SQL Server, Snowflake or BigQuery. The SQL of this module works there too, with small differences in date functions and types. The Python side changes only in the connect call.

A connection is an open link from Python to one database. sqlite3.connect() opens one. This module opens data/shop.db in read-only mode, so no lesson can change the course data by mistake. The special form file:...?mode=ro with uri=True asks for read-only access.

import sqlite3
import duckdb
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True)
cur = con.execute("SELECT store_id, city, region FROM stores LIMIT 3")
print(type(cur).__name__)
print(cur.fetchall())
Output
Cursor
[('S01', 'Chicago', 'North'), ('S02', 'Minneapolis', 'North'), ('S03', 'Detroit', 'North')]

con.execute() sends the SQL text to the engine and returns a cursor: an object that walks through the result rows. The rows that a query returns are its result set. fetchall() returns all remaining rows as a list of tuples, one tuple per row. A cursor also has fetchone() (the next row, or None at the end) and fetchmany(n) (the next n rows). cur.description holds the column names:

cur = con.execute("SELECT store_id, city, size_sqm FROM stores ORDER BY size_sqm DESC")
print([column[0] for column in cur.description])
print(cur.fetchone())
print(cur.fetchmany(2))
print(len(cur.fetchall()), "rows left")
Output
['store_id', 'city', 'size_sqm']
('S07', 'New York', 3400)
[('S04', 'Houston', 3100), ('S01', 'Chicago', 2850)]
9 rows left

Each fetch moves the cursor forward. After fetchone() and fetchmany(2), 9 of the 12 stores are left. A cursor is an iterator (module 10): for row in cur: reads one row at a time, which saves memory on big results.

A read-only connection refuses to change anything:

con.execute("DELETE FROM orders")
Output
sqlite3.OperationalError: attempt to write a readonly database

A list of tuples is hard to read. This module uses a small helper, show(), that prints a result as an aligned text table. It puts numbers on the right, text on the left and NULL for a missing value, and it stops after 15 rows, so the output stays narrow and short.

def show(
sql: str,
params: tuple = (),
db: sqlite3.Connection | None = None,
max_rows: int = 15,
) -> None:
"""Run a query and print the rows as an aligned text table."""
cur = (db or con).execute(sql, params)
names = [column[0] for column in cur.description]
rows = cur.fetchall()
cells = [["NULL" if v is None else str(v) for v in row] for row in rows[:max_rows]]
widths = [max(map(len, column)) for column in zip(names, *cells)]
first = rows[0] if rows else [None] * len(names)
right = [isinstance(v, int | float) for v in first]
def line(values: list[str]) -> str:
parts = zip(values, widths, right)
return " ".join(v.rjust(w) if r else v.ljust(w) for v, w, r in parts).rstrip()
print(line(names))
for row in cells:
print(line(row))
if len(rows) > max_rows:
print(f"... {len(rows) - max_rows} more rows")
show("SELECT store_id, city, region, size_sqm FROM stores WHERE region = 'North'")
Output
store_id city region size_sqm
S01 Chicago North 2850
S02 Minneapolis North 1950
S03 Detroit North 1420

zip(names, *cells) turns the rows into columns, so max(map(len, column)) finds the widest text in each column. Copy this helper into your own scripts. pandas and DuckDB print aligned tables on their own, as the next sections show.

Four clauses (parts of a query, each starting with a keyword) answer most “show me the rows” questions:

SELECT product_id, product, unit_price -- which columns
FROM products -- which table
WHERE category = 'Electronics' AND unit_price < 300 -- which rows
ORDER BY unit_price DESC -- in which order
LIMIT 3; -- how many

The same query from Python, in a triple-quoted string so that it reads like the block above:

show("""
SELECT product_id, product, unit_price
FROM products
WHERE category = 'Electronics' AND unit_price < 300
ORDER BY unit_price DESC
LIMIT 3
""")
Output
product_id product unit_price
P002 Noise-Cancelling Headphones 249.0
P005 Smartwatch Series 5 199.99
P001 Wireless Earbuds 79.99

SQL keywords are not case-sensitive. This course writes them in capitals so you can tell them from column names. Text values go in single quotes ('Electronics'). -- starts a comment, like # in Python.

SELECT can compute new columns. AS gives a column an alias, a new name for the result. SELECT DISTINCT removes duplicate rows. * means “every column”.

show("""
SELECT product, unit_price, unit_cost,
ROUND(unit_price - unit_cost, 2) AS margin,
ROUND(100 * (unit_price - unit_cost) / unit_price, 1) AS margin_pct
FROM products
ORDER BY margin_pct DESC
LIMIT 4
""")
show("SELECT DISTINCT channel FROM orders ORDER BY channel")
Output
product unit_price unit_cost margin margin_pct
Vitamin C Face Serum 24.99 6.3 18.69 74.8
Mineral Sunscreen SPF 50 15.99 4.1 11.89 74.4
Running Socks 3-Pack 14.99 4.2 10.79 72.0
Hydrating Face Cream 32.0 9.1 22.9 71.6
channel
online
store

The WHERE clause accepts these operators:

Operator Meaning Example
=, <> (or !=) equal, not equal region = 'East'
<, <=, >, >= compare unit_price >= 100
AND, OR, NOT combine conditions (AND binds tighter than OR) a AND (b OR c)
IN (...) equal to one of a list store_id IN ('S01', 'S07')
BETWEEN a AND b inside a range, both ends included order_date BETWEEN '2024-01-01' AND '2024-01-31'
LIKE text pattern: % is any text, _ is one character product LIKE '%Running%'
IS NULL, IS NOT NULL missing, not missing total_charges IS NULL

A query does not run in the order you write it. The engine works through the clauses in a fixed logical order:

flowchart LR
    F["FROM, JOIN"] --> W["WHERE"] --> G["GROUP BY"] --> H["HAVING"]
    H --> S["SELECT<br/>(window functions)"] --> D["DISTINCT"] --> O["ORDER BY"] --> L["LIMIT"]

This order explains several rules. WHERE runs before GROUP BY, so it filters rows, not groups. ORDER BY runs after SELECT, so it can use an alias. Window functions run in the SELECT step, after WHERE, so you cannot filter on them in WHERE. Standard SQL also forbids an alias in WHERE. SQLite and DuckDB accept it as an extension, but portable code repeats the expression or uses a CTE.

SQL marks a missing value with NULL. It is the SQL version of None and NaN. In shop.db, ten new customers have no total_charges yet.

NULL means “unknown”, so a comparison with NULL is also unknown. SQL has three truth values: true, false and unknown. This is three-valued logic. WHERE keeps a row only when the condition is true, so it drops both false and unknown rows.

show("""
SELECT NULL = NULL AS eq, NULL IS NULL AS is_null, 1 + NULL AS plus,
COALESCE(NULL, 0) AS coalesced
""")
show("SELECT COUNT(*) AS n FROM customers WHERE total_charges = NULL")
show("SELECT COUNT(*) AS n FROM customers WHERE total_charges IS NULL")
Output
eq is_null plus coalesced
NULL 1 NULL 0
n
0
n
10

NULL = NULL is not true but NULL, so WHERE total_charges = NULL finds nothing. Always test with IS NULL. Arithmetic with NULL gives NULL. COALESCE(a, b, ...) returns its first argument that is not NULL, which replaces a missing value with a default, like fillna in pandas.

An aggregate function turns many rows into one value. Without GROUP BY, it summarizes the whole table:

Function Returns NULLs
COUNT(*) number of rows counted
COUNT(col) number of non-NULL values skipped
COUNT(DISTINCT col) number of different non-NULL values skipped
SUM(col), AVG(col) total, mean skipped
MIN(col), MAX(col) smallest, largest skipped
show("""
SELECT COUNT(*) AS customers,
COUNT(total_charges) AS with_charges,
COUNT(DISTINCT plan) AS plans,
ROUND(AVG(monthly_charges), 2) AS avg_monthly
FROM customers
""")
Output
customers with_charges plans avg_monthly
5000 4990 3 60.84

COUNT(*) counts 5,000 rows, but COUNT(total_charges) counts 4,990 values, because it skips the 10 NULLs. AVG also skips NULLs: it divides by the number of known values, not by the number of rows.

GROUP BY splits the rows into groups with the same values in the listed columns, and the aggregates run once per group. It is df.groupby(...).agg(...) in pandas. Every column in SELECT must either be in GROUP BY or sit inside an aggregate.

show("""
SELECT plan,
COUNT(*) AS customers,
SUM(churned) AS churned,
ROUND(100.0 * SUM(churned) / COUNT(*), 1) AS churn_pct
FROM customers
GROUP BY plan
ORDER BY churn_pct DESC
""")
Output
plan customers churned churn_pct
premium 990 293 29.6
basic 2028 352 17.4
standard 1982 318 16.0

churned is 0 or 1, so SUM(churned) counts the churned customers and AVG(churned) is the churn rate. The 100.0 matters. SQLite divides two integers with integer division, which drops the decimals: 5 / 2 is 2 in SQLite. One float operand makes the division exact:

show("SELECT 5 / 2 AS int_div, 5 / 2.0 AS real_div, 293 * 100 / 990 AS wrong_pct")
print(duckdb.sql("SELECT 5 / 2 AS div, 5 // 2 AS int_div").fetchall())
Output
int_div real_div wrong_pct
2 2.5 29
[(2.5, 2)]

Engines disagree here, and the SQL standard leaves it open. DuckDB, like BigQuery and Snowflake, makes / a decimal division, and // is its integer division. PostgreSQL and SQL Server truncate 5 / 2 to 2, like SQLite. Write 100.0 in every engine and your percentages are right everywhere.

HAVING filters groups after the aggregation, as WHERE filters rows before it. Use WHERE for conditions on columns and HAVING for conditions on aggregates:

show("""
SELECT payment_method, COUNT(*) AS customers,
ROUND(100.0 * AVG(churned), 1) AS churn_pct
FROM customers
WHERE contract = 'month-to-month'
GROUP BY payment_method
HAVING COUNT(*) > 500
ORDER BY churn_pct DESC
""")
Output
payment_method customers churn_pct
electronic_check 873 37.0
bank_transfer 656 27.3
paypal 502 26.5
credit_card 753 25.0

WHERE keeps only month-to-month customers. GROUP BY makes one group per payment method. HAVING drops the groups with 500 customers or fewer.

A CASE expression picks a value by condition, like if/elif/else or np.select. It runs its WHEN branches in order and returns the first match. ELSE is the default. Without ELSE, no match gives NULL.

CASE
WHEN tenure_months < 6 THEN '0-5 months'
WHEN tenure_months < 24 THEN '6-23 months'
ELSE '24+ months'
END AS tenure_band

Use CASE to make groups, then GROUP BY the new column:

show("""
SELECT CASE
WHEN tenure_months < 6 THEN '0-5 months'
WHEN tenure_months < 24 THEN '6-23 months'
ELSE '24+ months'
END AS tenure_band,
COUNT(*) AS customers,
ROUND(100.0 * AVG(churned), 1) AS churn_pct
FROM customers
GROUP BY tenure_band
ORDER BY MIN(tenure_months)
""")
Output
tenure_band customers churn_pct
0-5 months 956 47.9
6-23 months 2118 16.8
24+ months 1926 7.7

ORDER BY MIN(tenure_months) sorts the bands by their real order, not by the alphabet.

CASE inside an aggregate is conditional aggregation: one pass over the table computes several filtered totals side by side. This is how SQL builds a pivot table. Both engines also accept the shorter FILTER (WHERE ...) clause after an aggregate:

show("""
SELECT strftime('%Y', order_date) AS year,
ROUND(SUM(CASE WHEN channel = 'online' THEN revenue ELSE 0 END), 2)
AS online,
ROUND(SUM(revenue) FILTER (WHERE channel = 'store'), 2) AS store,
ROUND(100.0 * AVG(channel = 'online'), 1) AS online_line_pct
FROM orders
GROUP BY year
""")
Output
year online store online_line_pct
2023 622853.06 1022736.53 36.8
2024 896613.41 1054320.83 46.2

A comparison such as channel = 'online' is 1 or 0 in SQLite, so AVG(channel = 'online') is the share of online lines. The DuckDB version is AVG(CASE WHEN channel = 'online' THEN 1 ELSE 0 END), because DuckDB does not average Booleans.

A join combines rows of two tables. The join condition after ON says which rows belong together, usually “the foreign key equals the primary key”. The columns in it are the join keys.

A join does not work like overlapping circles. The engine looks at pairs of rows: one row from the left table and one from the right. Every pair that meets the condition becomes one output row. So a left row with three matches appears three times, and a row with no match disappears, unless the join type keeps it.

flowchart TD
    P["Every pair: one left row + one right row"] --> C{"ON condition true?"}
    C -- "yes" --> M["Output one combined row per matching pair"]
    C -- "no" --> X["Drop the pair"]
    M --> I["INNER JOIN: only these rows"]
    I --> L["LEFT JOIN adds left rows with no match<br/>(right columns NULL)"]
    I --> R["RIGHT JOIN adds right rows with no match<br/>(left columns NULL)"]
    L --> F["FULL JOIN adds both kinds"]
    R --> F

Two tiny tables make this concrete. Three customers, and four orders. Customer C3 has no order. Order O4 belongs to a customer id C9 that is not in the customer table.

mini = sqlite3.connect(":memory:")
mini.executescript("""
CREATE TABLE cust (customer_id TEXT PRIMARY KEY, name TEXT);
INSERT INTO cust VALUES ('C1', 'Ana'), ('C2', 'Ben'), ('C3', 'Cleo');
CREATE TABLE ord (order_id TEXT PRIMARY KEY, customer_id TEXT, amount REAL);
INSERT INTO ord VALUES ('O1', 'C1', 50), ('O2', 'C1', 30),
('O3', 'C2', 20), ('O4', 'C9', 99);
""")
show("SELECT * FROM cust", db=mini)
show("SELECT * FROM ord", db=mini)
Output
customer_id name
C1 Ana
C2 Ben
C3 Cleo
order_id customer_id amount
O1 C1 50.0
O2 C1 30.0
O3 C2 20.0
O4 C9 99.0

":memory:" creates a database that lives only in memory and disappears when the connection closes. executescript() runs several statements separated by ;. CREATE TABLE defines a table and INSERT INTO ... VALUES adds rows. These two statements change data, so they run on the in-memory database, never on shop.db.

Now the four join types on the same two tables:

show("""
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM cust AS c
INNER JOIN ord AS o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id
""", db=mini)
Output
customer_id name order_id amount
C1 Ana O1 50.0
C1 Ana O2 30.0
C2 Ben O3 20.0

Only matching pairs. Ana appears twice, once per order. Cleo (no order) and O4 (no customer) are gone. JOIN alone means INNER JOIN.

AS c gives the table an alias, so c.customer_id says which table’s column you mean. The alias is required when both tables have a column with the same name. The FULL query sorts with o.order_id IS NULL first: it is 0 for rows with an order and 1 for Cleo, so Cleo comes last.

Join Keeps pandas merge
INNER JOIN matching pairs only how="inner"
LEFT JOIN all left rows; NULLs where no match how="left"
RIGHT JOIN all right rows; NULLs where no match how="right"
FULL JOIN all rows of both sides how="outer"
CROSS JOIN every pair, no condition (3 × 4 = 12 rows here) how="cross"

Two more questions come up all the time. They are not join types in the SQL grammar, but patterns:

  • A semi-join keeps the left rows that have at least one match, once each: “customers who ordered”. Write it with EXISTS.
  • An anti-join keeps the left rows that have no match: “customers who never ordered”. Write it with NOT EXISTS, or with a left join and IS NULL.
show("""
SELECT c.customer_id, c.name FROM cust AS c
WHERE EXISTS (SELECT 1 FROM ord AS o WHERE o.customer_id = c.customer_id)
""", db=mini)
show("""
SELECT c.customer_id, c.name FROM cust AS c
WHERE NOT EXISTS (SELECT 1 FROM ord AS o WHERE o.customer_id = c.customer_id)
""", db=mini)
show("""
SELECT c.customer_id, c.name FROM cust AS c
LEFT JOIN ord AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
""", db=mini)
Output
customer_id name
C1 Ana
C2 Ben
customer_id name
C3 Cleo
customer_id name
C3 Cleo

The query inside EXISTS (...) is a subquery: a query inside another query. It refers to c.customer_id of the outer row, so it is a correlated subquery: it runs once per customer. EXISTS is true when the subquery returns any row. The SELECT 1 shows that only the existence of a row matters, not its columns. The semi-join returns Ana once, although she has two orders: an inner join would return her twice.

A subquery can also stand in FROM, as a temporary table, or in WHERE, as a value or a list:

show("""
SELECT product, unit_price
FROM products
WHERE unit_price > (SELECT AVG(unit_price) FROM products)
ORDER BY unit_price DESC
LIMIT 3
""")
Output
product unit_price
55-inch 4K Smart TV 1299.0
14-inch Ultrabook Laptop 1149.0
Espresso Machine 349.0

The subquery (SELECT AVG(unit_price) FROM products) returns one value, 177.61, and the outer query compares each price with it. Nested subqueries get hard to read quickly. A common table expression (CTE) fixes this. WITH name AS (query) gives a subquery a name before the main query, and the main query uses it like a table. Several CTEs, separated by commas, form a chain where each step can use the steps before it:

WITH customer_totals AS ( -- step 1: one row per customer
SELECT customer_id, SUM(revenue) AS revenue
FROM orders
GROUP BY customer_id
),
spend_bands AS ( -- step 2: uses step 1
SELECT customer_id,
CASE WHEN revenue >= 2000 THEN 'high' ELSE 'normal' END AS band
FROM customer_totals
)
SELECT band, COUNT(*) AS customers -- final step: uses step 2
FROM spend_bands
GROUP BY band;
cte_sql = """
WITH customer_totals AS (
SELECT customer_id, SUM(revenue) AS revenue
FROM orders
GROUP BY customer_id
),
spend_bands AS (
SELECT customer_id,
CASE WHEN revenue >= 2000 THEN 'high' ELSE 'normal' END AS band
FROM customer_totals
)
SELECT band, COUNT(*) AS customers
FROM spend_bands
GROUP BY band
"""
show(cte_sql)
Output
band customers
high 559
normal 2695

A chain of CTEs reads top to bottom, like a pandas method chain. Each CTE is a step you can test on its own: copy it into show() and look at its rows. CTEs exist only while the query runs. They do not create tables.

GROUP BY collapses each group into one row. Often you want to keep every row and add a value computed over a group of rows: a rank within a region, a running total, the value of last month. A window function does that. It computes a value for each row from a set of related rows, its window, and keeps all the rows.

The OVER (...) clause defines the window. It has three optional parts:

function(...) OVER (
PARTITION BY region -- separate windows per region (like groupby)
ORDER BY revenue DESC -- order of rows inside each window
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW -- the frame: which rows count
)

A partition is one group of rows that a window function sees on its own. Without PARTITION BY, the whole result is one partition. In pandas, groupby(...).transform(...), rank, cumsum, shift and rolling do these jobs.

Ranking. ROW_NUMBER(), RANK() and DENSE_RANK() number the rows in window order. They differ only on ties, rows with equal sort values. The two cheapest products cost 14.99 each:

show("""
SELECT product, unit_price,
ROW_NUMBER() OVER (ORDER BY unit_price, product) AS row_number,
RANK() OVER (ORDER BY unit_price) AS rank,
DENSE_RANK() OVER (ORDER BY unit_price) AS dense_rank
FROM products
ORDER BY unit_price, product
LIMIT 5
""")
Output
product unit_price row_number rank dense_rank
Running Socks 3-Pack 14.99 1 1 1
The Mindful Runner 14.99 2 1 1
Mineral Sunscreen SPF 50 15.99 3 3 2
Harbor Lane Mysteries 16.99 4 4 3
Organic Cotton T-Shirt 19.99 5 5 4
Function Ties get Next value after a tie of 2 Use for
ROW_NUMBER() different numbers (arbitrary order) 3 exactly N rows per group, deduplication
RANK() the same number 3 (skips 2) sports-style ranking
DENSE_RANK() the same number 2 (no gap) “the top 3 price levels”

Without a second sort column, ROW_NUMBER() breaks ties in an order the engine chooses, which can change between runs or versions. The query above adds product to its window order, so the two 14.99 products always get 1 and 2 in name order.

Running totals and changes. An aggregate with OVER (ORDER BY ...) becomes cumulative. LAG(col) returns the value of the previous row in the window, and LEAD(col) the next one. LAG(col, 12) looks 12 rows back.

show("""
WITH monthly AS (
SELECT strftime('%Y-%m', order_date) AS month, ROUND(SUM(revenue), 2) AS revenue
FROM orders
WHERE order_date < '2023-05-01'
GROUP BY month
)
SELECT month, revenue,
ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS running_total,
LAG(revenue) OVER (ORDER BY month) AS prev_month
FROM monthly
""")
Output
month revenue running_total prev_month
2023-01 107329.6 107329.6 NULL
2023-02 77405.21 184734.81 107329.6
2023-03 106542.74 291277.55 77405.21
2023-04 99271.34 390548.89 106542.74

The first month has no previous month, so LAG returns NULL. The running total adds each month to the months before it.

Frames. The frame is the part of the partition that the function sees for the current row. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means “this row and the 2 before it”, which gives a 3-row moving average. When ORDER BY is present and no frame is given, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: all rows up to the current one, including every row that ties with it. Example 6 shows how that default surprises you on daily data, and how to fix it.

SQLite has no date type. shop.db stores dates as TEXT in ISO format ('2024-05-01'). ISO text sorts in date order, so <, BETWEEN and MIN work on it. Date functions read and write that text. DuckDB has real DATE and TIMESTAMP types, like pandas datetime64, and it detects them when it reads a CSV file.

Task SQLite (TEXT dates) DuckDB (DATE)
Literal '2024-05-01' DATE '2024-05-01'
Year strftime('%Y', d) (text '2024') year(d) (number 2024)
Month label strftime('%Y-%m', d) strftime(d, '%Y-%m') (also accepts the SQLite order)
First day of month date(d, 'start of month') date_trunc('month', d)
Add 7 days date(d, '+7 days') d + INTERVAL 7 DAY
Days between julianday(b) - julianday(a) date_diff('day', a, b) or b - a
Day of week (0 = Sunday) strftime('%w', d) (text) dayofweek(d)
show("""
SELECT strftime('%Y', '2024-05-05') AS year,
date('2024-05-05', 'start of month') AS month_start,
date('2024-05-05', '+7 days') AS week_later,
julianday('2024-03-01') - julianday('2024-02-01') AS feb_days,
strftime('%w', '2024-05-05') AS dow,
date('2024-01-31', '+1 month') AS jan31_plus_1m
""")
duckdb.sql("""
SELECT year(DATE '2024-05-05') AS year,
date_trunc('month', DATE '2024-05-05') AS month_start,
DATE '2024-05-05' + INTERVAL 7 DAY AS week_later,
DATE '2024-03-01' - DATE '2024-02-01' AS feb_days,
dayofweek(DATE '2024-05-05') AS dow,
DATE '2024-01-31' + INTERVAL 1 MONTH AS jan31_plus_1m
""").show(max_width=100)
Output
year month_start week_later feb_days dow jan31_plus_1m
2024 2024-05-01 2024-05-12 29.0 0 2024-03-02
┌───────┬─────────────────────┬─────────────────────┬──────────┬───────┬─────────────────────┐
│ year │ month_start │ week_later │ feb_days │ dow │ jan31_plus_1m │
│ int64 │ timestamp │ timestamp │ int64 │ int64 │ timestamp │
├───────┼─────────────────────┼─────────────────────┼──────────┼───────┼─────────────────────┤
│ 2024 │ 2024-05-01 00:00:00 │ 2024-05-12 00:00:00 │ 29 │ 0 │ 2024-02-29 00:00:00 │
└───────┴─────────────────────┴─────────────────────┴──────────┴───────┴─────────────────────┘

Both engines agree on most answers, with two differences worth knowing. DuckDB’s date_trunc and INTERVAL arithmetic return a TIMESTAMP. Cast with CAST(x AS DATE) (or x::DATE) when you want a date. And “January 31 plus one month” differs: SQLite rolls over into March (2024-03-02), while DuckDB stops at the last day of February (2024-02-29). Test month arithmetic on month ends.

Programs often build a query from a value that a user typed: a customer id in a web form, a region in a command-line option. Never paste that value into the SQL text with an f-string. SQL injection is an attack where the input contains SQL code, and the engine runs it as part of your query.

Here is an unsafe lookup function. It runs on the read-only connection, so the demo cannot damage anything:

def find_customer_unsafe(customer_id: str) -> list[tuple]:
sql = (
"SELECT customer_id, plan FROM customers "
f"WHERE customer_id = '{customer_id}'"
)
print(sql)
return con.execute(sql).fetchall()
print(len(find_customer_unsafe("C00001")), "row")
print(len(find_customer_unsafe("x' OR '1'='1")), "rows")
Output
SELECT customer_id, plan FROM customers WHERE customer_id = 'C00001'
1 row
SELECT customer_id, plan FROM customers WHERE customer_id = 'x' OR '1'='1'
5000 rows

The input x' OR '1'='1 closes the quoted string and adds OR '1'='1', a condition that is always true. The function now returns all 5,000 customers. On a login form, the same trick skips the password check. With a writable connection, other inputs can change or delete data.

The fix is a parameterized query. Write a ? placeholder (module 10) where a value goes, and pass the values separately as a tuple. The driver sends the SQL and the values to the engine apart. The engine treats a value as data, never as SQL code, whatever characters it contains:

def find_customer(customer_id: str) -> list[tuple]:
sql = "SELECT customer_id, plan FROM customers WHERE customer_id = ?"
return con.execute(sql, (customer_id,)).fetchall()
print(find_customer("C00001"))
print(find_customer("x' OR '1'='1"))
show(
"SELECT COUNT(*) AS lines FROM orders WHERE store_id = ? AND order_date >= ?",
("S12", "2024-01-01"),
)
Output
[('C00001', 'premium')]
[]
lines
575

The attack string is now just an id that does not exist, so the query returns no rows. Note the comma in (customer_id,): a one-element tuple. sqlite3 also accepts named placeholders, :name, with a dict: con.execute("... WHERE region = :region", {"region": "East"}). DuckDB uses ? and $name.

Placeholders work for values only, not for table or column names. When a user picks a column, check it against an allowlist, a fixed set of permitted names:

SORTABLE = {"monthly_charges", "tenure_months", "support_tickets"}
def top_customers(sort_by: str, n: int = 3) -> list[tuple]:
if sort_by not in SORTABLE:
raise ValueError(f"cannot sort by {sort_by!r}")
sql = f"SELECT customer_id, {sort_by} FROM customers ORDER BY {sort_by} DESC"
sql += " LIMIT ?"
return con.execute(sql, (n,)).fetchall()
print(top_customers("support_tickets"))
Output
[('C04542', 9), ('C00592', 8), ('C00480', 7)]

The f-string is safe here, because sort_by can only be one of three names that you wrote yourself. n still goes through a placeholder.

DuckDB queries files directly. Put the file path in quotes where a table name goes. DuckDB detects the file type, the column names and the column types:

rel = duckdb.sql(
"SELECT order_date, region, product, revenue FROM 'data/sales.csv' LIMIT 3"
)
print(type(rel).__name__)
rel.show(max_width=100)
Output
DuckDBPyRelation
┌────────────┬─────────┬────────────────────────┬─────────┐
│ order_date │ region │ product │ revenue │
│ date │ varchar │ varchar │ double │
├────────────┼─────────┼────────────────────────┼─────────┤
│ 2023-01-01 │ West │ Cotton Bed Sheet Set │ 66.49 │
│ 2023-01-01 │ West │ Running Socks 3-Pack │ 14.99 │
│ 2023-01-01 │ South │ Organic Cotton T-Shirt │ 19.99 │
└────────────┴─────────┴────────────────────────┴─────────┘

duckdb.sql() returns a relation: an object that describes a query result. It is lazy: DuckDB computes the rows only when you ask for them. .show(max_width=100) prints the result as a box that fits 100 characters, with the column types under the names. order_date arrived as a real date, not as text.

A relation gives its rows in several forms:

Method Returns
.fetchall() a list of Python tuples, as in sqlite3
.df() a pandas DataFrame
.pl() a Polars DataFrame (module 31)
.show(max_width=100) prints a box table
.columns, .types column names and DuckDB types

The table functions read_csv(...) and read_parquet(...) take options, and a glob pattern (module 07) reads many files as one table:

print(duckdb.sql("""
SELECT COUNT(*) AS lines, MIN(order_date) AS first, MAX(order_date) AS last,
ROUND(SUM(revenue), 2) AS revenue
FROM read_csv('data/reports/2024-*.csv', union_by_name = true)
""").fetchall())
parquet_rel = duckdb.sql("SELECT COUNT(*) AS lines FROM 'data/sales_sample.parquet'")
print(parquet_rel.fetchall())
Output
[(297, datetime.date(2024, 1, 2), datetime.date(2024, 6, 29), 57266.39)]
[(500,)]

The six monthly report files hold 297 lines. The April file has the same columns in a different order. union_by_name = true matches the columns of all files by name and keeps their detected types. Without it, this folder gives order_date as text. The Parquet file stores its types, so DuckDB needs no detection there.

DuckDB can also open the SQLite file. ATTACH adds another database to a DuckDB connection under a name, and its tables become name.table. The sqlite extension, which DuckDB downloads once on first use, does the reading:

ddb = duckdb.connect()
ddb.sql("ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY)")
ddb.sql("""
SELECT s.region, COUNT(*) AS lines, ROUND(SUM(o.revenue), 2) AS revenue
FROM shop.orders AS o
JOIN shop.stores AS s USING (store_id)
GROUP BY s.region
ORDER BY revenue DESC
""").show(max_width=100)
Output
┌─────────┬───────┬───────────┐
│ region │ lines │ revenue │
│ varchar │ int64 │ double │
├─────────┼───────┼───────────┤
│ East │ 5396 │ 993683.72 │
│ South │ 5144 │ 891766.07 │
│ North │ 4966 │ 888229.47 │
│ West │ 4722 │ 822844.57 │
└─────────┴───────┴───────────┘

duckdb.connect() opens a new in-memory DuckDB database; duckdb.sql() uses a default one that the module creates for you. USING (store_id) is a short form of ON o.store_id = s.store_id for a key with the same name on both sides.

pandas reads a query result straight into a DataFrame. pd.read_sql_query(sql, con, params=...) accepts a sqlite3 connection directly. Other databases need a SQLAlchemy engine, a library that connects pandas to almost any database.

df = pd.read_sql_query(
"SELECT order_date, store_id, revenue FROM orders WHERE store_id = ? LIMIT 3",
con,
params=("S07",),
parse_dates=["order_date"],
)
print(df)
print(df.dtypes)
Output
order_date store_id revenue
0 2023-01-01 S07 2183.10
1 2023-01-02 S07 86.00
2 2023-01-02 S07 15.99
order_date datetime64[us]
store_id str
revenue float64
dtype: object

parse_dates converts the TEXT dates to datetime64, because SQLite cannot send a date type.

The other direction, df.to_sql(name, con), writes a DataFrame into a table. It returns the number of rows written. Write into a new in-memory database (or a copy in output/), never into data/shop.db:

sales = pd.read_csv("data/sales.csv")
mem = sqlite3.connect(":memory:")
print(sales.to_sql("sales", mem, index=False))
show("SELECT category, COUNT(*) AS lines FROM sales GROUP BY category LIMIT 2", db=mem)
Output
20228
category lines
Beauty 3109
Books 2567

index=False skips the DataFrame index, which would become an extra column. if_exists="replace" overwrites a table that exists; the default, "fail", raises an error.

DuckDB needs no copy at all. It finds a DataFrame by its variable name, a feature called a replacement scan, and .df() returns the result as a DataFrame:

by_region = duckdb.sql("""
SELECT region, ROUND(SUM(revenue), 2) AS revenue
FROM sales
GROUP BY region
ORDER BY revenue DESC
""").df()
print(by_region)
print(type(by_region).__name__)
Output
region revenue
0 East 993683.72
1 South 891766.07
2 North 888229.47
3 West 822844.57
DataFrame

Here sales is the pandas DataFrame from the previous block. This is a practical mix: load and clean with pandas, aggregate with SQL, plot with pandas again.

Both answer the same questions. The choice depends on where the data lives and who reads the code.

Situation Better choice Why
Data is in a database SQL the engine filters and aggregates before any data moves to Python
Data is bigger than memory SQL (DuckDB) DuckDB streams files and spills to disk
Result goes to a dashboard SQL BI (business intelligence) tools such as Tableau or Power BI read SQL tables and run SQL queries
Many small, custom steps, plots, ML pandas Python functions, plotting and scikit-learn work on DataFrames
Complex reshaping (pivot, melt, MultiIndex) pandas SQL needs many CASE expressions
You need both DuckDB on DataFrames SQL where it is clearer, pandas for the rest

The translation table:

SQL pandas
SELECT a, b df[["a", "b"]]
WHERE x > 5 df[df["x"] > 5] or df.query("x > 5")
ORDER BY x DESC LIMIT 3 df.nlargest(3, "x")
GROUP BY k + SUM(v) df.groupby("k")["v"].sum()
HAVING SUM(v) > 100 filter the grouped result
LEFT JOIN t USING (k) df.merge(t, on="k", how="left")
CASE WHEN np.where, np.select, pd.cut
ROW_NUMBER() OVER (PARTITION BY k ORDER BY v) df.groupby("k")["v"].rank(method="first")
LAG(v) OVER (ORDER BY t) df["v"].shift()
AVG(v) OVER (ORDER BY t ROWS 6 PRECEDING) df["v"].rolling(7, min_periods=1).mean()

Goal: You receive a database you have never seen. Before any analysis, list its tables, count their rows, read the column types and check that every foreign key points to an existing row.

tables = [row[0] for row in con.execute(
"SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
)]
print(tables)
Output
['customers', 'orders', 'products', 'stores']

Every SQLite file has a built-in table, sqlite_schema, that describes its own tables and indexes. Iterating over the cursor reads its rows one by one.

for table in tables:
(n,) = con.execute(f"SELECT COUNT(*) FROM {table}").fetchone()
print(f"{table:<10} {n:>7,} rows")
Output
customers 5,000 rows
orders 20,228 rows
products 30 rows
stores 12 rows

A table name cannot be a ? parameter, so the loop builds the SQL with an f-string. That is safe here, because the names come from the database itself, not from a user. (n,) = ... unpacks the one-element tuple that fetchone() returns.

Step 3 — Read the column types of the fact table

Section titled “Step 3 — Read the column types of the fact table”
show("SELECT name, type, \"notnull\", pk FROM pragma_table_info('orders')")
Output
name type notnull pk
line_id INTEGER 0 1
order_id TEXT 1 0
order_date TEXT 1 0
customer_id TEXT 1 0
store_id TEXT 1 0
channel TEXT 1 0
product_id TEXT 1 0
unit_price REAL 1 0
quantity INTEGER 1 0
discount REAL 1 0
revenue REAL 1 0

pragma_table_info('orders') is a SQLite table function that describes the columns. notnull is in double quotes, because double quotes mark an identifier (a column or table name) in SQL, and NOTNULL is also a keyword. line_id is the primary key, and every other column is required.

show("""
SELECT MIN(order_date) AS first_day, MAX(order_date) AS last_day,
COUNT(DISTINCT order_date) AS days, COUNT(DISTINCT order_id) AS orders
FROM orders
""")
Output
first_day last_day days orders
2023-01-01 2024-12-31 731 14877

The sales run over 731 days (all of 2023 and 2024) and 14,877 orders.

show("""
SELECT
(SELECT COUNT(*) FROM orders AS o WHERE NOT EXISTS
(SELECT 1 FROM stores AS s WHERE s.store_id = o.store_id)) AS bad_store,
(SELECT COUNT(*) FROM orders AS o WHERE NOT EXISTS
(SELECT 1 FROM products AS p WHERE p.product_id = o.product_id))
AS bad_product,
(SELECT COUNT(*) FROM orders AS o WHERE NOT EXISTS
(SELECT 1 FROM customers AS c WHERE c.customer_id = o.customer_id))
AS bad_customer
""")
print(con.execute("SELECT * FROM pragma_foreign_key_check").fetchall())
Output
bad_store bad_product bad_customer
0 0 0
[]

Each anti-join counts the order lines whose store, product or customer does not exist. All three counts are 0, so the joins on these keys in the next examples lose no rows. SQLite also has a built-in check: pragma_foreign_key_check lists every row that breaks a declared foreign key. An empty list means none does. It works on a read-only connection.

Common mistakes:

  • Exploring with SELECT * on a big table and no LIMIT. It moves every row into Python. Add LIMIT 5 while you look.
  • Trusting declared foreign keys. SQLite checks them only after PRAGMA foreign_keys = ON, so old data can break them. Count the orphans with an anti-join.
  • Building SQL from user input with f-strings, because the table-name loop did. That loop is safe only because the names come from the schema.

Example 2 — Revenue by category in SQL and in pandas

Section titled “Example 2 — Revenue by category in SQL and in pandas”

Goal: The finance team asks for revenue, lines and average line value per product category, for the categories above 300,000 USD. Answer in SQL, answer again in pandas, and check that both agree.

Step 1 — Join the order lines to their products

Section titled “Step 1 — Join the order lines to their products”
show("""
SELECT o.line_id, o.product_id, p.product, p.category, o.revenue
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
LIMIT 3
""")
Output
line_id product_id product category revenue
1 P010 Cotton Bed Sheet Set Home 66.49
2 P014 Running Socks 3-Pack Clothing 14.99
3 P015 Organic Cotton T-Shirt Clothing 19.99

orders has no category column. The join brings it in from products. product_id is the primary key of products, so each line matches exactly one product and no fan-out happens.

Step 2 — Group by category and filter the groups

Section titled “Step 2 — Group by category and filter the groups”
category_sql = """
SELECT p.category,
COUNT(*) AS lines,
ROUND(SUM(o.revenue), 2) AS revenue,
ROUND(AVG(o.revenue), 2) AS avg_line
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
GROUP BY p.category
HAVING SUM(o.revenue) > 300000
ORDER BY revenue DESC
"""
show(category_sql)
Output
category lines revenue avg_line
Electronics 3942 1808108.17 458.68
Home 3265 672294.61 205.91
Sports 3331 544108.55 163.35
Clothing 4014 314686.62 78.4

The engine joins, groups, aggregates, drops the groups at or below 300,000 and sorts, all in one statement. Only four short rows travel to Python.

Step 3 — Answer the same question in pandas

Section titled “Step 3 — Answer the same question in pandas”
orders = pd.read_sql_query("SELECT * FROM orders", con)
products = pd.read_sql_query("SELECT * FROM products", con)
by_category = (
orders.merge(products[["product_id", "category"]], on="product_id")
.groupby("category")
.agg(lines=("revenue", "size"), revenue=("revenue", "sum"),
avg_line=("revenue", "mean"))
.query("revenue > 300000")
.sort_values("revenue", ascending=False)
.round(2)
.reset_index()
)
print(by_category.to_string(float_format="{:.2f}".format))
Output
category lines revenue avg_line
0 Electronics 3942 1808108.17 458.68
1 Home 3265 672294.61 205.91
2 Sports 3331 544108.55 163.35
3 Clothing 4014 314686.62 78.40

The pandas version is a method chain with the same steps: merge is the join, groupby and agg the aggregation, query the HAVING filter. pandas first loads all 20,228 lines into memory; SQL sent only the answer. to_string(float_format=...) prints 2 decimals; with display.precision at 3, pandas would show the large totals in scientific notation (1.808e+06).

sql_result = pd.read_sql_query(category_sql, con)
pd.testing.assert_frame_equal(sql_result, by_category)
print("SQL and pandas agree on", len(sql_result), "categories")
Output
SQL and pandas agree on 4 categories

pd.testing.assert_frame_equal raises an AssertionError that lists the differences if the two tables differ in values, column names or dtypes. Here even the dtypes agree. When they do not, for example when SQLite returns an integer column that pandas computed as a float, pass check_dtype=False. Checking one tool against another is a cheap way to catch a wrong join or a wrong filter.

Common mistakes:

  • Putting SUM(o.revenue) > 300000 in WHERE. Aggregates do not exist yet when WHERE runs, so SQLite raises misuse of aggregate. Use HAVING.
  • Selecting a column that is neither grouped nor aggregated, such as p.product here. SQLite returns a value from an arbitrary row of the group without an error. DuckDB and PostgreSQL raise an error, which is better.
  • Rounding before summing. SUM(ROUND(revenue, 2)) and ROUND(SUM(revenue), 2) can differ. Round once, at the end.

Example 3 — Find customers who never ordered

Section titled “Example 3 — Find customers who never ordered”

Goal: Marketing wants the subscription customers with no order in the shop, and whether they churn more often than the customers who buy.

Step 1 — Count them with LEFT JOIN … IS NULL

Section titled “Step 1 — Count them with LEFT JOIN … IS NULL”
show("""
SELECT COUNT(*) AS never_ordered
FROM customers AS c
LEFT JOIN (SELECT DISTINCT customer_id FROM orders) AS buyers
ON buyers.customer_id = c.customer_id
WHERE buyers.customer_id IS NULL
""")
Output
never_ordered
1746

The subquery buyers has one row per customer who ordered. The left join keeps every customer, and the unmatched ones get NULL. WHERE ... IS NULL keeps only those. DISTINCT in the subquery only makes the intermediate join smaller: without it, a buyer with ten lines matches ten times, but IS NULL removes all matched rows anyway, and the count stays 1,746. Fan-out matters when you sum or count the matches, not in an anti-join.

Step 2 — Count them again with NOT EXISTS

Section titled “Step 2 — Count them again with NOT EXISTS”
show("""
SELECT COUNT(*) AS never_ordered
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
""")
Output
never_ordered
1746

Same answer. NOT EXISTS states the question directly (“no order exists for this customer”), and it never fans out, so it is the clearest anti-join. The engine uses the index idx_orders_customer to look up each customer quickly. An index is a sorted lookup structure on a column, like the index of a book.

show("""
SELECT CASE
WHEN EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id)
THEN 'has orders' ELSE 'no orders'
END AS segment,
COUNT(*) AS customers,
ROUND(100.0 * AVG(c.churned), 1) AS churn_pct,
ROUND(AVG(c.tenure_months), 1) AS avg_tenure
FROM customers AS c
GROUP BY segment
""")
Output
segment customers churn_pct avg_tenure
has orders 3254 15.1 26.8
no orders 1746 27.0 16.2

Customers with no order churn far more often (27.0% against 15.1%), and they are newer on average. This is a correlation, not a cause: module 29 explains why. It still makes the 1,746 customers a clear target for a first-purchase offer.

show("""
SELECT COUNT(*) AS not_in_result
FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders
UNION ALL SELECT NULL)
""")
Output
not_in_result
0

UNION ALL stacks the rows of two queries, so the list now has one NULL in it. x NOT IN (a, b, NULL) means x <> a AND x <> b AND x <> NULL. The last part is unknown, so the whole condition is never true and the query returns 0. orders.customer_id has no NULLs, but many real columns do. Use NOT EXISTS, which has no such trap.

Common mistakes:

  • Putting the condition on the right table in WHERE instead of ON. LEFT JOIN orders o ON ... WHERE o.channel = 'online' drops every customer without an order, because their o.channel is NULL. The left join turns into an inner join. Put such conditions in the ON clause.
  • Counting with COUNT(*) after a left join. Unmatched rows count as 1. Use COUNT(o.order_id), which skips the NULLs, to count matches.
  • Using NOT IN with a subquery that can return NULL. Prefer NOT EXISTS.

Example 4 — Month-over-month revenue growth

Section titled “Example 4 — Month-over-month revenue growth”

Goal: The monthly business review shows revenue per month of 2024, the change from the month before and the change from the same month of 2023.

monthly_sql = """
SELECT strftime('%Y-%m', order_date) AS month,
SUM(revenue) AS revenue
FROM orders
GROUP BY month
"""
show(monthly_sql, max_rows=3)
Output
month revenue
2023-01 107329.6
2023-02 77405.21
2023-03 106542.74
... 21 more rows

strftime('%Y-%m', ...) cuts each ISO date to its month. The format codes are the same as in Python’s datetime.strftime. The sum is not rounded yet; the next step rounds only for display.

Step 2 — Add the previous month and the same month last year

Section titled “Step 2 — Add the previous month and the same month last year”
growth_sql = f"""
WITH monthly AS ({monthly_sql}),
compared AS (
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
LAG(revenue, 12) OVER (ORDER BY month) AS prev_year
FROM monthly
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(100 * (revenue - prev_month) / prev_month, 1) AS mom_pct,
ROUND(100 * (revenue - prev_year) / prev_year, 1) AS yoy_pct
FROM compared
WHERE month >= '2024-01'
ORDER BY month
"""
show(growth_sql)
Output
month revenue mom_pct yoy_pct
2024-01 119596.89 -50.4 11.4
2024-02 106320.41 -11.1 37.4
2024-03 145567.22 36.9 36.6
2024-04 114917.5 -21.1 15.8
2024-05 128716.36 12.0 -10.6
2024-06 155854.41 21.1 11.0
2024-07 148989.14 -4.4 13.4
2024-08 151791.33 1.9 -5.0
2024-09 141654.74 -6.7 17.2
2024-10 166147.92 17.3 35.7
2024-11 268466.55 61.6 37.6
2024-12 302911.77 12.8 25.6

The CTE monthly reuses the query of step 1. compared adds the two lagged values. Month-over-month (MoM) compares a month with the one before. Year-over-year (YoY) compares it with the same month a year earlier, which removes the seasonal pattern. January 2024 looks like a crash month-over-month (−50.4%), but it is 11.4% above January 2023: the drop is the normal dip after the holidays. The YoY column tells the real story.

Step 3 — Filter after the window, not before

Section titled “Step 3 — Filter after the window, not before”
show("""
SELECT strftime('%Y-%m', order_date) AS month,
LAG(SUM(revenue), 12) OVER (ORDER BY strftime('%Y-%m', order_date))
AS prev_year
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY month
""", max_rows=2)
Output
month prev_year
2024-01 NULL
2024-02 NULL
... 10 more rows

Here WHERE removed 2023 before the window ran, so LAG(..., 12) finds no earlier months and returns NULL everywhere. Window functions see only the rows that survive WHERE. That is why step 2 computes the lags in a CTE and filters in the outer query.

Step 4 — Run the same report in DuckDB on the CSV file

Section titled “Step 4 — Run the same report in DuckDB on the CSV file”
duck_growth = duckdb.sql("""
WITH monthly AS (
SELECT strftime(order_date, '%Y-%m') AS month, SUM(revenue) AS revenue
FROM 'data/sales.csv'
GROUP BY month
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(100 * (revenue / LAG(revenue) OVER w - 1), 1) AS mom_pct,
ROUND(100 * (revenue / LAG(revenue, 12) OVER w - 1), 1) AS yoy_pct
FROM monthly
WINDOW w AS (ORDER BY month)
QUALIFY month >= '2024-01'
ORDER BY month
""").df()
sqlite_growth = pd.read_sql_query(growth_sql, con)
print(duck_growth.head(3))
pd.testing.assert_frame_equal(duck_growth, sqlite_growth, check_exact=False)
print("Same numbers in both engines")
Output
month revenue mom_pct yoy_pct
0 2024-01 119596.89 -50.4 11.4
1 2024-02 106320.41 -11.1 37.4
2 2024-03 145567.22 36.9 36.6
Same numbers in both engines

Two differences from SQLite. DuckDB documents strftime with the date first and the format second; it also accepts the SQLite order, but SQLite returns NULL for the DuckDB order. And DuckDB has QUALIFY, a clause that filters on window results after they are computed. QUALIFY replaces the extra CTE of step 2. SQLite and PostgreSQL do not have it. The WINDOW w AS (...) clause names a window definition once, so both LAG calls can say OVER w. SQLite supports named windows too.

Common mistakes:

  • Filtering the period in WHERE in the same query as LAG. The window loses the earlier rows (step 3).
  • Using LAG when a month is missing. LAG takes the previous row, not the previous calendar month. In this data every month has sales; in sparse data, build a full calendar first.
  • Dividing by a previous value of 0. Wrap the divisor in NULLIF(prev_month, 0), which turns 0 into NULL, so the result is NULL instead of an error or infinity.

Goal: Each regional manager wants the three products with the highest revenue in their region.

Step 1 — Aggregate revenue per region and product

Section titled “Step 1 — Aggregate revenue per region and product”
region_product_sql = """
SELECT s.region, p.product, ROUND(SUM(o.revenue), 2) AS revenue
FROM orders AS o
JOIN stores AS s ON s.store_id = o.store_id
JOIN products AS p ON p.product_id = o.product_id
GROUP BY s.region, p.product
"""
show(region_product_sql + " ORDER BY s.region, revenue DESC", max_rows=4)
Output
region product revenue
East 55-inch 4K Smart TV 195239.7
East 14-inch Ultrabook Laptop 192687.3
East Noise-Cancelling Headphones 60619.05
East Espresso Machine 50343.25
... 116 more rows

Two joins in a row add the region and the product name. The result has one row per region and product: 4 × 30 = 120 rows.

Step 2 — Number the products inside each region

Section titled “Step 2 — Number the products inside each region”
top3_sql = f"""
WITH region_product AS ({region_product_sql}),
ranked AS (
SELECT region, product, revenue,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS pos
FROM region_product
)
SELECT region, pos, product, revenue
FROM ranked
WHERE pos <= 3
ORDER BY region, pos
"""
show(top3_sql)
Output
region pos product revenue
East 1 55-inch 4K Smart TV 195239.7
East 2 14-inch Ultrabook Laptop 192687.3
East 3 Noise-Cancelling Headphones 60619.05
North 1 55-inch 4K Smart TV 162504.9
North 2 14-inch Ultrabook Laptop 145291.05
North 3 Espresso Machine 55979.6
South 1 14-inch Ultrabook Laptop 165398.55
South 2 55-inch 4K Smart TV 136849.65
South 3 Noise-Cancelling Headphones 68064.15
West 1 14-inch Ultrabook Laptop 161951.55
West 2 55-inch 4K Smart TV 133991.85
West 3 Noise-Cancelling Headphones 47608.8

PARTITION BY region restarts the numbering in each region. The outer WHERE pos <= 3 keeps the top three. The TV and the laptop lead everywhere; the third place differs: headphones in three regions, the espresso machine in the North.

Step 3 — Write it shorter with QUALIFY in DuckDB

Section titled “Step 3 — Write it shorter with QUALIFY in DuckDB”
ddb.sql("""
SELECT s.region, p.product, ROUND(SUM(o.revenue), 2) AS revenue
FROM shop.orders AS o
JOIN shop.stores AS s USING (store_id)
JOIN shop.products AS p USING (product_id)
GROUP BY s.region, p.product
QUALIFY ROW_NUMBER() OVER (PARTITION BY s.region ORDER BY SUM(o.revenue) DESC) <= 3
ORDER BY s.region, revenue DESC
""").show(max_width=100)
Output
┌─────────┬─────────────────────────────┬───────────┐
│ region │ product │ revenue │
│ varchar │ varchar │ double │
├─────────┼─────────────────────────────┼───────────┤
│ East │ 55-inch 4K Smart TV │ 195239.7 │
│ East │ 14-inch Ultrabook Laptop │ 192687.3 │
│ East │ Noise-Cancelling Headphones │ 60619.05 │
│ North │ 55-inch 4K Smart TV │ 162504.9 │
│ North │ 14-inch Ultrabook Laptop │ 145291.05 │
│ North │ Espresso Machine │ 55979.6 │
│ South │ 14-inch Ultrabook Laptop │ 165398.55 │
│ South │ 55-inch 4K Smart TV │ 136849.65 │
│ South │ Noise-Cancelling Headphones │ 68064.15 │
│ West │ 14-inch Ultrabook Laptop │ 161951.55 │
│ West │ 55-inch 4K Smart TV │ 133991.85 │
│ West │ Noise-Cancelling Headphones │ 47608.8 │
└─────────┴─────────────────────────────┴───────────┘
12 rows 3 columns

The same 12 rows. QUALIFY filters on the window function directly, so no CTE is needed. Inside OVER, the window sorts by SUM(o.revenue), not by the alias revenue: DuckDB would read revenue as the raw column o.revenue and raise an error, because that column is not grouped.

Common mistakes:

  • Forgetting PARTITION BY. The numbering then runs over all regions together, and pos <= 3 returns three rows in total.
  • Using RANK() when exactly N rows are required. With a tie for third place, RANK() returns four rows. Choose ROW_NUMBER() for “exactly N” and RANK() for “everyone tied at the cut”.
  • Ranking the raw order lines instead of the aggregated revenue. Aggregate first (step 1), then rank.

Example 6 — Running total and 7-day moving average of daily revenue

Section titled “Example 6 — Running total and 7-day moving average of daily revenue”

Goal: A dashboard shows daily revenue for the 2024 holiday season, the revenue so far in the year and a smoothed 7-day trend line. Compute all three in DuckDB, straight from data/sales.csv.

Step 1 — See the trap of the default frame

Section titled “Step 1 — See the trap of the default frame”
duckdb.sql("""
SELECT order_date, revenue,
ROUND(SUM(revenue) OVER (ORDER BY order_date), 2) AS default_frame,
ROUND(SUM(revenue) OVER (
ORDER BY order_date, order_id, product_id
ROWS UNBOUNDED PRECEDING), 2) AS rows_frame
FROM 'data/sales.csv'
ORDER BY order_date, order_id, product_id
LIMIT 4
""").show(max_width=100)
Output
┌────────────┬─────────┬───────────────┬────────────┐
│ order_date │ revenue │ default_frame │ rows_frame │
│ date │ double │ double │ double │
├────────────┼─────────┼───────────────┼────────────┤
│ 2023-01-01 │ 66.49 │ 4767.04 │ 66.49 │
│ 2023-01-01 │ 14.99 │ 4767.04 │ 81.48 │
│ 2023-01-01 │ 19.99 │ 4767.04 │ 101.47 │
│ 2023-01-01 │ 224.1 │ 4767.04 │ 325.57 │
└────────────┴─────────┴───────────────┴────────────┘

On the raw lines, many rows share a date. The default frame (RANGE ... CURRENT ROW) includes all rows with the same date, so every line of January 1 shows the full day total. The ROWS frame adds one line at a time. Its order within a day comes from the tie-break columns order_id, product_id; without them, it would be arbitrary and could change from run to run. Neither is a clean daily running total. Aggregate to one row per day first.

Step 2 — Aggregate per day, then add the windows

Section titled “Step 2 — Aggregate per day, then add the windows”
daily_sql = """
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue
FROM 'data/sales.csv'
GROUP BY order_date
)
SELECT order_date,
ROUND(revenue, 2) AS revenue,
ROUND(SUM(revenue) OVER (
PARTITION BY year(order_date) ORDER BY order_date), 2) AS ytd,
ROUND(AVG(revenue) OVER (
ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS ma7
FROM daily
"""
daily = duckdb.sql(daily_sql)
duckdb.sql("""
SELECT * FROM daily
WHERE order_date BETWEEN DATE '2024-11-26' AND DATE '2024-12-03'
ORDER BY order_date
""").show(max_width=100)
Output
┌────────────┬──────────┬────────────┬──────────┐
│ order_date │ revenue │ ytd │ ma7 │
│ date │ double │ double │ double │
├────────────┼──────────┼────────────┼──────────┤
│ 2024-11-26 │ 10698.07 │ 1584092.74 │ 7716.19 │
│ 2024-11-27 │ 7916.18 │ 1592008.92 │ 8394.61 │
│ 2024-11-28 │ 4762.69 │ 1596771.61 │ 7710.51 │
│ 2024-11-29 │ 33619.18 │ 1630390.79 │ 11683.43 │
│ 2024-11-30 │ 17631.68 │ 1648022.47 │ 13030.81 │
│ 2024-12-01 │ 14585.64 │ 1662608.11 │ 14070.15 │
│ 2024-12-02 │ 15222.99 │ 1677831.1 │ 14919.49 │
│ 2024-12-03 │ 7475.26 │ 1685306.36 │ 14459.09 │
└────────────┴──────────┴────────────┴──────────┘

PARTITION BY year(order_date) restarts the running total on January 1, which gives year-to-date (YTD) revenue. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW averages the current day and the six before it. Black Friday (2024-11-29, 33,619 USD) lifts the 7-day average for a week, but much less than it lifts the daily value. A relation can be queried by its variable name, like a DataFrame: the second query reads daily.

daily_df = daily.df().sort_values("order_date").reset_index(drop=True)
pandas_ma7 = daily_df["revenue"].rolling(7, min_periods=1).mean().round(2)
print(daily_df.head(3))
print("max difference:", (pandas_ma7 - daily_df["ma7"]).abs().max().round(2))
Output
order_date revenue ytd ma7
0 2023-01-01 4767.04 4767.04 4767.04
1 2023-01-02 1593.88 6360.92 3180.46
2 2023-01-03 1811.84 8172.76 2724.25
max difference: 0.0

rolling(7, min_periods=1) matches the SQL frame, including the first six days, where both average fewer than seven values. With the pandas default for a window of 7, min_periods=7, the first six values would be NaN instead. The largest difference is 0.0 after rounding: both tools compute the same averages.

Common mistakes:

  • Using ROWS BETWEEN 6 PRECEDING on data with missing days. Seven rows are then more than seven days. In DuckDB, RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW counts calendar days. Here every day has sales, so both agree.
  • Reading the first six moving averages as full 7-day averages. Hide them with CASE WHEN COUNT(*) OVER (...) = 7 THEN ... END if the report needs exact windows.
  • Forgetting PARTITION BY for a year-to-date total. Without it, the total keeps growing from 2023 into 2024.

Example 7 — Save a target table in a working copy of the database

Section titled “Example 7 — Save a target table in a working copy of the database”

Goal: Management sets a 2025 revenue target per region: 2024 revenue plus a growth rate. Store the targets as a new table next to the data, join them with the 2024 actuals and read the result into pandas. The course database must stay unchanged.

import hashlib
import shutil
from pathlib import Path
def file_hash(path: str) -> str:
"""Return the SHA-256 fingerprint of a file's bytes."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
original_hash = file_hash("data/shop.db")
Path("output").mkdir(exist_ok=True)
shutil.copy("data/shop.db", "output/shop_work.db")
work = sqlite3.connect("output/shop_work.db", autocommit=False)
print(work.execute("SELECT COUNT(*) FROM orders").fetchone())
Output
(20228,)

The working copy is a normal file that you may change freely. If something goes wrong, delete it and copy again. file_hash() computes a SHA-256 hash, a fingerprint of the file’s bytes: if a single byte changes, the hash changes. Step 4 uses it to prove that data/shop.db is unchanged. autocommit=False (Python 3.12+) is explained in step 2.

Step 2 — Create the table and insert rows with placeholders

Section titled “Step 2 — Create the table and insert rows with placeholders”
growth = {"East": 0.08, "North": 0.10, "South": 0.12, "West": 0.15}
with work:
work.execute("DROP TABLE IF EXISTS targets_2025")
work.execute("CREATE TABLE targets_2025 (region TEXT PRIMARY KEY, growth REAL)")
work.executemany("INSERT INTO targets_2025 VALUES (?, ?)", growth.items())
show("SELECT * FROM targets_2025", db=work)
Output
region growth
East 0.08
North 0.1
South 0.12
West 0.15

executemany runs one INSERT per item, each with its own placeholder values. A transaction is a group of changes that is saved together (a commit) or undone together (a rollback). The connection was opened with autocommit=False, so every statement, DROP and CREATE included, runs inside a transaction. with work: commits at the end of the block, or rolls everything back if a statement fails: the old table survives a failed insert. DROP TABLE IF EXISTS makes the step safe to rerun.

Step 3 — Join the targets with the 2024 actuals

Section titled “Step 3 — Join the targets with the 2024 actuals”
target_sql = """
WITH actual AS (
SELECT s.region, SUM(o.revenue) AS revenue_2024
FROM orders AS o
JOIN stores AS s ON s.store_id = o.store_id
WHERE o.order_date >= :start AND o.order_date < :end
GROUP BY s.region
)
SELECT a.region,
ROUND(a.revenue_2024, 2) AS revenue_2024,
t.growth,
ROUND(a.revenue_2024 * (1 + t.growth), 2) AS target_2025
FROM actual AS a
LEFT JOIN targets_2025 AS t ON t.region = a.region
ORDER BY target_2025 DESC
"""
targets = pd.read_sql_query(
target_sql, work, params={"start": "2024-01-01", "end": "2025-01-01"}
)
print(targets)
print(f"Total 2025 target: {targets['target_2025'].sum():,.2f} USD")
Output
region revenue_2024 growth target_2025
0 East 544765.09 0.08 588346.30
1 South 482265.00 0.12 540136.80
2 North 477729.41 0.10 525502.35
3 West 446174.74 0.15 513100.95
Total 2025 target: 2,167,086.40 USD

The query uses named placeholders (:start, :end) with a dict, and a half-open date interval. The left join keeps a region even if someone forgot its target: its growth would show as NaN, which is easy to spot.

Step 4 — Close the connections and prove the original is unchanged

Section titled “Step 4 — Close the connections and prove the original is unchanged”
work_tables = [row[0] for row in work.execute(
"SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
)]
print("working copy:", work_tables)
for connection in (work, con, mini, mem, ddb):
connection.close()
print("data/shop.db unchanged:", file_hash("data/shop.db") == original_hash)
Output
working copy: ['customers', 'orders', 'products', 'stores', 'targets_2025']
data/shop.db unchanged: True

The new table exists only in output/shop_work.db. The hash of data/shop.db is the same as before step 1, so not one byte of the course database changed. Closing every connection frees the files; on Windows, an open connection keeps a file locked.

Common mistakes:

  • Forgetting the commit. With autocommit=False, every change that you do not commit (with with work: or work.commit()) is rolled back when the connection closes. In the legacy default mode, only the uncommitted inserts and updates disappear; CREATE and DROP were already committed.
  • Building the INSERT with f-strings from the dict. A region name such as O'Brien County breaks the SQL, and hostile input can do worse. Use placeholders.
  • Writing into data/shop.db. Every later lesson and exercise expects the original data. Work on a copy.
Mistake Symptom Fix
WHERE col = NULL No rows, no error WHERE col IS NULL
SUM(churned) * 100 / COUNT(*) in SQLite Whole-number percentages (29 instead of 29.6) Multiply by 100.0, or CAST(... AS REAL)
An aggregate in WHERE misuse of aggregate error Move the condition to HAVING
A window function in WHERE misuse of window function error Compute it in a CTE and filter outside, or use QUALIFY in DuckDB
Joining to a key that is not unique Totals too large (fan-out) Join to a primary key, or aggregate the right table first
Condition on the right table of a left join in WHERE Unmatched rows vanish Put the condition in ON
NOT IN (subquery) with a NULL in it 0 rows Use NOT EXISTS
"Books" in double quotes SQLite treats it as text; DuckDB raises Binder Error Single quotes for text: 'Books'
LIKE 'wireless%' Matches in SQLite (case-insensitive), not in DuckDB Use ILIKE in DuckDB, or lower(col) LIKE ...
strftime(d, '%Y') in SQLite NULL in every row SQLite wants the format first: strftime('%Y', d)
Dates as '2024-1-5' or '05/01/2024' text in SQLite Wrong sorting, date() returns NULL Store ISO YYYY-MM-DD text
f"... WHERE id = '{user_input}'" SQL injection, broken queries on ' ? placeholders and a parameter tuple
con.execute(sql, "S01") ProgrammingError: wrong number of bindings Pass a tuple: ("S01",)
with sqlite3.connect(...) as con: and no close() File stays open (locked on Windows) until the object is garbage-collected Call con.close() or use contextlib.closing
DROP/CREATE in a with con: block, default mode A failed insert rolls back, but the old table is already gone sqlite3.connect(path, autocommit=False), or con.execute("BEGIN") first
Default window frame with ties Running total jumps by whole days Aggregate to one row per key, or use a ROWS frame
print(rel) on a wide DuckDB result Lines longer than the screen rel.show(max_width=100) or .df() with pandas display options
  • Web development: every web framework talks to a database. Django and SQLAlchemy build SQL for you, but slow pages are fixed by reading that SQL, and login forms stay safe because of parameterized queries.
  • Apps and tools: SQLite is the most deployed database in the world. Browsers, phones, Python’s own tools and desktop apps keep their settings and history in SQLite files.
  • Automation and logs: DuckDB answers questions about a folder of CSV, JSON or Parquet log files in one command, without loading them into a server first.
  • Testing: sqlite3.connect(":memory:") gives every test a fresh, empty database in microseconds (module 14).
  • A relational database stores tables with primary and foreign keys. SQL describes the result you want; the engine decides how to compute it.
  • SQLite (in Python’s standard library) is a row store for apps; DuckDB is a columnar engine for analysis that also queries CSV, Parquet and DataFrames directly.
  • connect, execute, fetchall: rows arrive as tuples, column names in cursor.description. Open course data read-only and close every connection.
  • Clauses run in logical order: FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT (with windows), ORDER BY, LIMIT. WHERE filters rows; HAVING filters groups.
  • NULL is unknown: test with IS NULL; aggregates skip NULLs; COUNT(*) does not.
  • A join outputs one row per matching pair. Inner keeps matches; left/right/full also keep unmatched rows with NULLs. EXISTS is a semi-join, NOT EXISTS an anti-join. Watch for fan-out.
  • CTEs (WITH) name the steps of a long query. Window functions (OVER) add ranks, running totals, lags and moving averages without collapsing rows.
  • SQLite stores dates as ISO text with strftime/date; DuckDB has a DATE type with year, date_trunc and INTERVAL.
  • Pass values with ? placeholders; check identifiers against an allowlist. Never format user input into SQL.
  • pd.read_sql_query, df.to_sql and DuckDB’s .df() and replacement scans move data between pandas and SQL.

Q1. In which logical order does the engine process SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY? Why can ORDER BY use a SELECT alias in every engine, but standard SQL forbids it in WHERE?

Answer

FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY (then LIMIT). The alias is created in the SELECT step. ORDER BY runs after it, so the alias exists. WHERE runs before it, so in standard SQL the alias does not exist yet. SQLite and DuckDB allow it as an extension.

Q2. What is the difference between WHERE and HAVING? Give one condition that belongs in each.

Answer

WHERE filters rows before grouping; HAVING filters groups after aggregation. WHERE contract = 'month-to-month' belongs in WHERE. HAVING COUNT(*) > 500 belongs in HAVING, because the count exists only after grouping.

Q3. A table has 5,000 rows, and 10 of them have NULL in total_charges. What do COUNT(*), COUNT(total_charges) and SELECT COUNT(*) ... WHERE total_charges = NULL return?

Answer

5,000, 4,990 and 0. COUNT(col) skips NULLs. = NULL is never true (it is unknown), so the filtered count is 0. Use IS NULL to count 10.

Q4. Table A has 3 customers. Table B has 4 orders: two for customer 1, one for customer 2 and one for an unknown customer. How many rows do the inner, left, right and full joins on the customer id return?

Answer

Inner: 3 (two for customer 1, one for customer 2). Left: 4 (plus customer 3 with NULLs). Right: 4 (the 3 matches plus the order of the unknown customer). Full: 5 (the 3 matches plus both unmatched rows). This is the cust/ord example of the lesson.

Q5. Write two different anti-joins that find products with no order lines. Which one is safer with NULLs, and why is NOT IN risky?

Answer

SELECT p.* FROM products p WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.product_id = p.product_id) and SELECT p.* FROM products p LEFT JOIN orders o ON o.product_id = p.product_id WHERE o.line_id IS NULL. Both handle NULLs correctly. NOT IN (subquery) returns no rows at all if the subquery returns a single NULL, because x <> NULL is unknown.

Q6. Two products tie for second place by revenue. What do ROW_NUMBER(), RANK() and DENSE_RANK() give the four best products?

Answer

ROW_NUMBER(): 1, 2, 3, 4 (the tie is broken arbitrarily). RANK(): 1, 2, 2, 4. DENSE_RANK(): 1, 2, 2, 3.

Q7. Why does LAG(revenue, 12) OVER (ORDER BY month) return NULL for every month when the same query has WHERE month >= '2024-01'? How do you fix it?

Answer

WHERE runs before the window function, so the 2023 months are gone when LAG looks 12 rows back. Compute the lag in a CTE over all months, then filter in the outer query, or use QUALIFY in DuckDB.

Q8. Why is con.execute(f"SELECT * FROM customers WHERE customer_id = '{cid}'") dangerous? Write the safe version.

Answer

The value becomes part of the SQL code. An input such as x' OR '1'='1 changes the query’s meaning (SQL injection), and an input with a quote breaks it. Safe: con.execute("SELECT * FROM customers WHERE customer_id = ?", (cid,)).

Q9. Which engine would you choose to sum revenue per month over a folder of 200 Parquet files, and which to store the settings of a desktop app? Why?

Answer

DuckDB for the Parquet folder: it reads Parquet directly with a glob pattern and is columnar, so it reads only the needed columns. SQLite for the app settings: it is built for many small reads and writes, ships with Python and stores everything in one file.

Q10. What do 5 / 2 give in SQLite and in DuckDB? How do you compute an exact percentage in SQLite?

Answer

2 in SQLite (integer division) and 2.5 in DuckDB. In SQLite, make one operand a float: 100.0 * SUM(churned) / COUNT(*), or CAST(x AS REAL).

Q11. You have a cleaned pandas DataFrame sales. Name two ways to run a SQL GROUP BY on it and get a DataFrame back.

Answer

DuckDB: duckdb.sql("SELECT region, SUM(revenue) FROM sales GROUP BY region").df(), which reads the DataFrame by its name. SQLite: sales.to_sql("sales", mem, index=False) into mem = sqlite3.connect(":memory:"), then pd.read_sql_query("SELECT ...", mem).

Your progress

0 / 4 done

  • Exercises: 26 exercises with hints and full solutions, from single queries to window-function reports.
  • Mini-project: build a store scorecard with CTEs, joins and window functions, and cross-check it in pandas.
  • Cheat sheet: clauses, joins, windows, dates in both engines and the pandas translations on one page.
  • Next module: 31. Polars brings expressions and a lazy query engine to DataFrames, with ideas you now know from SQL.