30. SQL for data analysis — Cheat sheet
The essentials of module 30 on one page. Every runnable block on this page is checked against its output. SQL blocks are for reading; run them with con.execute(...) or duckdb.sql(...).
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| open a SQLite file read-only | URI mode | sqlite3.connect("file:data/shop.db?mode=ro", uri=True) |
| make a throwaway database | in-memory | sqlite3.connect(":memory:"), duckdb.connect() |
| run a query, get tuples | execute + fetchall |
con.execute(sql, params).fetchall() |
| get one row | fetchone() (sqlite3) |
(n,) = con.execute("SELECT COUNT(*) FROM orders").fetchone() |
| get the column names | cursor.description |
[c[0] for c in cur.description] |
| pass a value safely | ? placeholder + tuple |
con.execute("... WHERE id = ?", (cid,)) |
| pass named values | :name + dict (sqlite3), $name (DuckDB) |
{"start": "2024-01-01"} |
| insert many rows | executemany |
con.executemany("INSERT INTO t VALUES (?, ?)", rows) |
| save changes as one unit | autocommit=False + with con: (commit or rollback) |
con = sqlite3.connect(path, autocommit=False) |
| query a CSV or Parquet file | DuckDB, path as table | duckdb.sql("SELECT * FROM 'data/sales.csv'") |
| read many files as one table | glob + union_by_name |
read_csv('data/reports/*.csv', union_by_name = true) |
| query a pandas DataFrame | DuckDB replacement scan | duckdb.sql("SELECT ... FROM sales_df") |
| open a SQLite file in DuckDB | ATTACH |
ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY) |
| get a DataFrame from a query | pd.read_sql_query, .df() |
pd.read_sql_query(sql, con, params=(...)) |
| write a DataFrame to a table | df.to_sql |
df.to_sql("sales", mem, index=False) |
| print a DuckDB result narrowly | .show(max_width=100) |
rel.show(max_width=100) |
| keep rows by condition | WHERE |
WHERE region = 'East' AND unit_price >= 100 |
| keep groups by condition | HAVING |
HAVING COUNT(*) > 500 |
| count non-missing values | COUNT(col) |
COUNT(total_charges) |
| replace NULL with a default | COALESCE |
COALESCE(discount, 0) |
| bucket values | CASE WHEN |
CASE WHEN x < 30 THEN 'low' ELSE 'high' END |
| pivot two categories into columns | conditional aggregation | SUM(CASE WHEN channel = 'online' THEN revenue END) |
| rows with no match | anti-join | WHERE NOT EXISTS (SELECT 1 FROM t WHERE t.k = a.k) |
| rows with a match, once | semi-join | WHERE EXISTS (SELECT 1 FROM t WHERE t.k = a.k) |
| name the steps of a query | CTE | WITH step1 AS (...), step2 AS (...) SELECT ... |
| top N per group | ROW_NUMBER() in a CTE, or QUALIFY |
ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC) |
| running total | SUM() OVER (ORDER BY ...) |
SUM(revenue) OVER (ORDER BY month) |
| previous row’s value | LAG |
LAG(revenue) OVER (ORDER BY month) |
| moving average | frame | AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) |
| share of the total | empty window | 100.0 * revenue / SUM(revenue) OVER () |
| month label | strftime |
SQLite strftime('%Y-%m', d), DuckDB strftime(d, '%Y-%m') |
| list the tables (SQLite) | sqlite_schema |
SELECT name FROM sqlite_schema WHERE type = 'table' |
| describe a table | pragma / DESCRIBE |
pragma_table_info('orders'), DuckDB DESCRIBE orders |
Connect, run, fetch, close
Section titled “Connect, run, fetch, close”import sqlite3
import duckdbimport pandas as pd
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True) # read-onlycur = con.execute("SELECT store_id, city FROM stores WHERE region = ?", ("West",))print([c[0] for c in cur.description]) # column namesprint(cur.fetchone()) # next row as a tupleprint(cur.fetchall()) # the remaining rowsrel = duckdb.sql("SELECT COUNT(*) AS n FROM 'data/sales.csv'") # a lazy relationprint(rel.fetchall()) # DuckDB 2.x relations: fetchall(), df(), pl(), show()con.close()['store_id', 'city']('S10', 'Seattle')[('S11', 'San Francisco'), ('S12', 'Denver')][(20228,)]| Object | Made by | Gives |
|---|---|---|
sqlite3.Connection |
sqlite3.connect(path) |
execute, executemany, executescript, commit, close |
sqlite3.Cursor |
con.execute(sql) |
fetchone, fetchmany(n), fetchall, description, iteration |
duckdb.DuckDBPyConnection |
duckdb.connect() (in memory) or duckdb.connect("file.duckdb") |
sql, execute, close |
| DuckDB relation | duckdb.sql(sql) or ddb.sql(sql) |
fetchall, df, pl, show, columns, types; can be queried by its variable name |
Clauses and their logical order
Section titled “Clauses and their logical order”SELECT region, COUNT(*) AS lines -- 5 columns and expressions (windows run here)FROM orders AS o -- 1 source tablesJOIN stores AS s USING (store_id) -- 1 joinsWHERE o.order_date >= '2024-01-01' -- 2 row filterGROUP BY region -- 3 groupsHAVING COUNT(*) > 1000 -- 4 group filterORDER BY lines DESC -- 6 sort (aliases allowed)LIMIT 3; -- 7 cut| Clause | Runs | Can use aggregates | Can use window results | Can use SELECT aliases |
|---|---|---|---|---|
FROM / JOIN |
1 | no | no | no |
WHERE |
2 | no | no | no in standard SQL; yes in SQLite and DuckDB |
GROUP BY |
3 | no | no | yes in SQLite and DuckDB |
HAVING |
4 | yes | no | yes in SQLite and DuckDB |
SELECT |
5 | yes | defines them | — |
QUALIFY (DuckDB) |
after windows | yes | yes | yes |
ORDER BY |
6 | yes | yes | yes |
LIMIT |
7 | — | — | — |
Operators and functions
Section titled “Operators and functions”| Operator or function | Meaning | Note |
|---|---|---|
=, <>, !=, <, <=, >, >= |
compare | text in single quotes |
AND, OR, NOT |
logic | AND binds tighter than OR: add parentheses |
IN ('a', 'b'), NOT IN (...) |
list membership | NOT IN with a NULL in the list returns nothing |
BETWEEN a AND b |
inclusive range | prefer >= a AND < b for dates |
LIKE 'Run%', _ |
pattern | SQLite: case-insensitive (ASCII); DuckDB: case-sensitive, use ILIKE |
IS NULL, IS NOT NULL |
missing test | never = NULL |
COALESCE(a, b) |
first non-NULL | like fillna |
NULLIF(a, b) |
NULL if a = b |
x / NULLIF(y, 0) avoids division by 0 |
CAST(x AS REAL), x::DOUBLE |
convert type | :: is DuckDB (and PostgreSQL) only |
ROUND(x, 2) |
round | round at the end, not before SUM |
a || b |
join text | '2024' || '-Q' || 4 |
lower(s), upper(s), trim(s), length(s) |
text functions | both engines |
5 / 2 |
division | SQLite 2 (integer division), DuckDB 2.5; DuckDB // is integer division |
NULL rules
Section titled “NULL rules”| Expression | Result |
|---|---|
NULL = NULL, NULL <> 1, 1 + NULL |
NULL |
NULL IS NULL |
true |
NULL OR true, NULL AND false |
true, false |
WHERE cond |
keeps rows where cond is true; drops false and NULL |
COUNT(*) |
counts rows, NULL or not |
COUNT(col), SUM, AVG, MIN, MAX |
skip NULLs; SUM of only NULLs is NULL |
GROUP BY col |
all NULLs form one group |
ORDER BY col |
NULLs first in SQLite, last in DuckDB (ascending); add NULLS FIRST / NULLS LAST to fix |
mem = sqlite3.connect(":memory:")null_sql = "SELECT NULL = NULL, NULL IS NULL, 1 + NULL, NULL OR 1"print(mem.execute(null_sql).fetchone())misc_sql = "SELECT COALESCE(NULL, 'n/a'), NULLIF(0, 0), 7 / 2, 7 / 2.0"print(mem.execute(misc_sql).fetchone())mem.close()(None, 1, None, 1)('n/a', None, 3, 3.5)Aggregates and GROUP BY
Section titled “Aggregates and GROUP BY”| Function | Returns | pandas |
|---|---|---|
COUNT(*) |
rows | size() |
COUNT(col) |
non-NULL values | count() |
COUNT(DISTINCT col) |
distinct non-NULL values | nunique() |
SUM, AVG, MIN, MAX |
total, mean, extremes | sum, mean, min, max |
AVG(flag) on 0/1 |
rate | mean() |
SUM(x) FILTER (WHERE cond) |
filtered sum (SQLite and DuckDB) | df.loc[cond, "x"].sum() |
median(x), quantile_cont(x, 0.9) |
median, percentile (DuckDB) | median(), quantile(0.9) |
arg_max(id, value) |
id of the row with the largest value (DuckDB) |
idxmax() |
GROUP BY ALL |
group by every non-aggregated column (DuckDB) | — |
SELECT plan, COUNT(*) AS customers, ROUND(100.0 * AVG(churned), 1) AS churn_pct, -- 100.0, not 100 SUM(CASE WHEN contract = 'two-year' THEN 1 ELSE 0 END) AS two_yearFROM customersWHERE tenure_months >= 12 -- rows firstGROUP BY planHAVING COUNT(*) > 100 -- then groupsORDER BY churn_pct DESC;| Join | Keeps | Unmatched columns | pandas |
|---|---|---|---|
[INNER] JOIN ... ON |
matching pairs | — | merge(how="inner") |
LEFT JOIN |
all left rows | right side NULL | how="left" |
RIGHT JOIN |
all right rows (SQLite 3.39+) | left side NULL | how="right" |
FULL [OUTER] JOIN |
all rows of both (SQLite 3.39+) | NULL on the missing side | how="outer" |
CROSS JOIN |
every pair (n × m rows) | — | how="cross" |
semi-join: WHERE EXISTS (...) |
left rows with a match, once | — | df[df.k.isin(t.k)] |
anti-join: WHERE NOT EXISTS (...) |
left rows without a match | — | df[~df.k.isin(t.k)] |
anti-join: LEFT JOIN ... WHERE t.k IS NULL |
left rows without a match | — | merge(indicator=True) |
self-join: orders o1 JOIN orders o2 ON ... |
pairs inside one table | — | df.merge(df, on=...) |
Rules of thumb:
- A join outputs one row per matching pair. A key that repeats on the right multiplies left rows (fan-out). Join to a primary key or aggregate first.
ON a.k = b.k AND b.flag = 1in a left join filters the right side and keeps all left rows. The same condition inWHEREdrops the unmatched left rows.USING (k)isON a.k = b.kwhen the key has the same name on both sides.- Prefix every column with its table alias once you join:
o.revenue,s.region.
Subqueries and CTEs
Section titled “Subqueries and CTEs”-- scalar subquery: one valueSELECT product FROM products WHERE unit_price > (SELECT AVG(unit_price) FROM products);
-- correlated subquery: runs per outer rowSELECT c.customer_idFROM customers AS cWHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
-- chained CTEs: each step can read the steps before itWITH monthly AS ( SELECT strftime('%Y-%m', order_date) AS month, SUM(revenue) AS revenue FROM orders GROUP BY month),lagged AS ( SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev FROM monthly)SELECT month, ROUND(100 * (revenue - prev) / prev, 1) AS mom_pctFROM laggedWHERE month >= '2024-01'; -- filter after the windowWindow functions
Section titled “Window functions”function(args) OVER ( PARTITION BY group_cols -- separate windows (optional) ORDER BY sort_cols -- order inside the window ROWS BETWEEN start AND end -- frame (optional))| Function | Gives | Ties |
|---|---|---|
ROW_NUMBER() |
1, 2, 3, 4 | broken arbitrarily: add a tie-break column |
RANK() |
1, 2, 2, 4 | same rank, then a gap |
DENSE_RANK() |
1, 2, 2, 3 | same rank, no gap |
NTILE(4) |
quartile number 1–4 | — |
LAG(x), LAG(x, 12), LEAD(x) |
previous, 12 back, next row’s value | NULL at the edges |
FIRST_VALUE(x), LAST_VALUE(x) |
first, last value in the frame | LAST_VALUE needs a full frame |
SUM(x) OVER (ORDER BY t) |
running total | default frame includes ties |
SUM(x) OVER () |
grand total on every row | — |
AVG(x) OVER (PARTITION BY g) |
group mean on every row | like groupby().transform("mean") |
| Frame | Rows the function sees |
|---|---|
none, no ORDER BY |
the whole partition |
none, with ORDER BY |
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: start up to the current row and its ties |
ROWS UNBOUNDED PRECEDING |
start up to the current row, no ties |
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW |
this row and the 6 before (7-row moving window) |
ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING |
the 28 rows before, without this one |
RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW |
the last 7 calendar days (DuckDB, date order) |
db = sqlite3.connect(":memory:")db.execute("CREATE TABLE m (month TEXT, revenue REAL)")db.executemany("INSERT INTO m VALUES (?, ?)", [("01", 10), ("02", 30), ("03", 20)])for row in db.execute(""" SELECT month, revenue, SUM(revenue) OVER (ORDER BY month) AS running, LAG(revenue) OVER (ORDER BY month) AS prev, RANK() OVER (ORDER BY revenue DESC) AS rnk, ROUND(AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), 1) AS ma2 FROM m ORDER BY month"""): print(row)db.close()('01', 10.0, 10.0, None, 3, 10.0)('02', 30.0, 40.0, 10.0, 1, 20.0)('03', 20.0, 60.0, 30.0, 2, 25.0)Filter on a window result in an outer query (CTE or subquery), or with QUALIFY in DuckDB:
SELECT region, product, revenueFROM region_productQUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) <= 3; -- DuckDBDates: SQLite vs DuckDB
Section titled “Dates: SQLite vs DuckDB”| Task | SQLite (dates are TEXT) |
DuckDB (DATE, TIMESTAMP) |
|---|---|---|
| Literal | '2024-05-01' |
DATE '2024-05-01' |
| Today | date('now') |
current_date |
| Parse other formats | not built in: store ISO text | strptime('05/01/2024', '%m/%d/%Y') |
| Year, month (numbers) | CAST(strftime('%Y', d) AS INTEGER) |
year(d), month(d) |
| Month label | strftime('%Y-%m', d) |
strftime(d, '%Y-%m') |
| First of month | date(d, 'start of month') |
date_trunc('month', d) (a TIMESTAMP; cast with ::DATE) |
| Last of month | date(d, 'start of month', '+1 month', '-1 day') |
last_day(d) |
| Add days, months | date(d, '+7 days'), date(d, '+1 month') |
d + INTERVAL 7 DAY, d + INTERVAL 1 MONTH |
| Jan 31 + 1 month | 2024-03-02 (rolls over) |
2024-02-29 (clamps to month end) |
| Days between | julianday(b) - julianday(a) (float) |
date_diff('day', a, b) or b - a |
| Day of week | strftime('%w', d): '0' = Sunday (text) |
dayofweek(d): 0 = Sunday; isodow(d): 1 = Monday |
| Day name | not built in | dayname(d) |
| Year range filter | d >= '2024-01-01' AND d < '2025-01-01' |
same, or year(d) = 2024 |
Placeholders and SQL injection
Section titled “Placeholders and SQL injection”| Driver | Positional | Named | Values |
|---|---|---|---|
sqlite3 |
? |
:name |
tuple / dict |
| DuckDB | ? |
$name |
list / dict (params=) |
pd.read_sql_query with sqlite3 |
? |
:name |
params=(...) / params={...} |
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True)attack = "x' OR '1'='1"unsafe = f"SELECT COUNT(*) FROM customers WHERE customer_id = '{attack}'"print(con.execute(unsafe).fetchone()) # injected: matches every rowsafe = "SELECT COUNT(*) FROM customers WHERE customer_id = ?"print(con.execute(safe, (attack,)).fetchone()) # the value stays a valueprint(duckdb.sql("SELECT $a + $b AS total", params={"a": 2, "b": 3}).fetchall())con.close()(5000,)(0,)[(5,)]- Placeholders take values only. For a table or column name chosen by a user, check it against an allowlist (
if col not in ALLOWED: raise ValueError(...)) before you put it into the SQL text. sqlite3.execute()runs one statement; a second statement raisesProgrammingError. That is a side effect, not a defense.executescript()runs many: never give it user input.- Open course data read-only. Write only into
:memory:or into a copy inoutput/.
pandas ↔ SQL
Section titled “pandas ↔ SQL”| Direction | Code | Note |
|---|---|---|
| SQLite → DataFrame | pd.read_sql_query(sql, con, params=..., parse_dates=["order_date"]) |
sqlite3 connections work directly; other databases need SQLAlchemy |
| DataFrame → SQLite | df.to_sql("t", con, index=False, if_exists="replace") |
returns the number of rows; default if_exists="fail" |
| DataFrame → DuckDB query | duckdb.sql("SELECT ... FROM df") |
finds the variable by name (replacement scan) |
| DuckDB → DataFrame | rel.df() |
dates become datetime64 |
| DuckDB → Polars | rel.pl() |
see module 31 |
| file → DataFrame via SQL | duckdb.sql("SELECT ... FROM 'data/sales.csv'").df() |
filter and aggregate before pandas sees the data |
sales = pd.DataFrame({"region": ["East", "West", "East"], "revenue": [10.0, 5.0, 2.5]})print(duckdb.sql("SELECT region, SUM(revenue) AS revenue FROM sales GROUP BY region " "ORDER BY region").df())mem = sqlite3.connect(":memory:")print(sales.to_sql("sales", mem, index=False))print(pd.read_sql_query("SELECT COUNT(*) AS n FROM sales WHERE revenue > ?", mem, params=(4,)))mem.close() region revenue0 East 12.51 West 5.03 n0 2| SQL | pandas |
|---|---|
SELECT a, b FROM t |
t[["a", "b"]] |
WHERE x > 5 AND y = 'A' |
t.query("x > 5 and y == 'A'") |
ORDER BY x DESC LIMIT 3 |
t.nlargest(3, "x") |
SELECT DISTINCT k |
t["k"].drop_duplicates() |
GROUP BY k + aggregates |
t.groupby("k").agg(...) |
HAVING COUNT(*) > 10 |
t.groupby("k").filter(lambda g: len(g) > 10) (keeps rows), or filter the aggregated frame |
LEFT JOIN u USING (k) |
t.merge(u, on="k", how="left") |
CASE WHEN |
np.where, np.select, pd.cut |
COALESCE(x, 0) |
t["x"].fillna(0) |
ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC) |
t.groupby("g")["v"].rank(method="first", ascending=False) |
SUM(v) OVER (PARTITION BY g ORDER BY t) |
t.groupby("g")["v"].cumsum() (sorted first) |
LAG(v) OVER (PARTITION BY g ORDER BY t) |
t.groupby("g")["v"].shift() |
AVG(v) OVER (ORDER BY t ROWS 6 PRECEDING) |
t["v"].rolling(7, min_periods=1).mean() |
UNION ALL |
pd.concat([a, b]) |
SQLite vs DuckDB
Section titled “SQLite vs DuckDB”| Topic | SQLite | DuckDB |
|---|---|---|
| Install | standard library | pip install duckdb |
| Workload | OLTP: small reads and writes | OLAP: scans and aggregations |
| Storage | rows, one .db file |
columns, .duckdb file or memory |
| Files | none | CSV, Parquet, JSON, globs |
| Types | flexible (type affinity), no DATE, no Boolean |
strict types, DATE, TIMESTAMP, BOOLEAN, lists |
"text" in double quotes |
accepted as a string if no such column (a misfeature) | always an identifier: Binder Error |
| Integer division | 7 / 2 = 3 |
7 / 2 = 3.5, 7 // 2 = 3 |
LIKE |
case-insensitive for ASCII | case-sensitive; ILIKE ignores case |
Ungrouped column in SELECT |
allowed (value from an arbitrary row) | error |
QUALIFY, GROUP BY ALL |
no | yes |
| Relation API | cursors | relations: .fetchall(), .df(), .show(); no fetchone() in 2.x |
Gotchas
Section titled “Gotchas”WHERE col = NULLreturns nothing. UseIS NULL.NOT IN (subquery)returns nothing if the subquery yields one NULL. UseNOT EXISTS.- SQLite integer division:
SUM(flag) * 100 / COUNT(*)gives whole numbers. Write100.0. - A condition on the right table of a
LEFT JOINinWHEREturns it into an inner join. Move it intoON. - Joining to a non-unique key multiplies rows and inflates sums (fan-out). Check uniqueness first.
ROW_NUMBER()with ties is not deterministic. Add a tie-break column toORDER BY.- The default frame with
ORDER BYincludes ties: a running total over raw lines jumps by whole days. Aggregate to one row per key first, or useROWS. WHEREruns before window functions. Filtering in the same query asLAGremoves the rowsLAGneeds. Filter in an outer query or withQUALIFY.- In DuckDB, an alias used inside
OVER (ORDER BY ...)of a grouped query may resolve to the raw column: write the aggregate (SUM(o.revenue)) instead. BETWEEN '2024-01-01' AND '2024-01-31'misses times later on January 31 in timestamp text. Use< '2024-02-01'.- SQLite
strftimewants the format first;strftime(d, '%Y')returns NULL. DuckDB documents the date first. - Month arithmetic differs: SQLite rolls January 31 + 1 month into March; DuckDB clamps to February 29.
with sqlite3.connect(...) as con:commits or rolls back, but does not close. Callcon.close().- In the default (legacy)
sqlite3mode,CREATEandDROPcommit at once, sowith con:cannot roll them back. Connect withautocommit=False(Python 3.12+) when a block changes tables. - f-strings with user input in SQL allow SQL injection. Use placeholders; allowlist identifiers.
print(rel)of a wide DuckDB result can exceed your screen. Userel.show(max_width=100).df.to_sqlwithoutindex=Falsewrites the index as an extra column.