Skip to content

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

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
import sqlite3
import duckdb
import pandas as pd
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True) # read-only
cur = con.execute("SELECT store_id, city FROM stores WHERE region = ?", ("West",))
print([c[0] for c in cur.description]) # column names
print(cur.fetchone()) # next row as a tuple
print(cur.fetchall()) # the remaining rows
rel = duckdb.sql("SELECT COUNT(*) AS n FROM 'data/sales.csv'") # a lazy relation
print(rel.fetchall()) # DuckDB 2.x relations: fetchall(), df(), pl(), show()
con.close()
Output
['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
SELECT region, COUNT(*) AS lines -- 5 columns and expressions (windows run here)
FROM orders AS o -- 1 source tables
JOIN stores AS s USING (store_id) -- 1 joins
WHERE o.order_date >= '2024-01-01' -- 2 row filter
GROUP BY region -- 3 groups
HAVING COUNT(*) > 1000 -- 4 group filter
ORDER 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 — — —
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
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()
Output
(None, 1, None, 1)
('n/a', None, 3, 3.5)
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_year
FROM customers
WHERE tenure_months >= 12 -- rows first
GROUP BY plan
HAVING COUNT(*) > 100 -- then groups
ORDER 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 = 1 in a left join filters the right side and keeps all left rows. The same condition in WHERE drops the unmatched left rows.
  • USING (k) is ON a.k = b.k when the key has the same name on both sides.
  • Prefix every column with its table alias once you join: o.revenue, s.region.
-- scalar subquery: one value
SELECT product FROM products WHERE unit_price > (SELECT AVG(unit_price) FROM products);
-- correlated subquery: runs per outer row
SELECT c.customer_id
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
-- chained CTEs: each step can read the steps before it
WITH 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_pct
FROM lagged
WHERE month >= '2024-01'; -- filter after the window
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()
Output
('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, revenue
FROM region_product
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) <= 3; -- 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
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 row
safe = "SELECT COUNT(*) FROM customers WHERE customer_id = ?"
print(con.execute(safe, (attack,)).fetchone()) # the value stays a value
print(duckdb.sql("SELECT $a + $b AS total", params={"a": 2, "b": 3}).fetchall())
con.close()
Output
(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 raises ProgrammingError. 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 in output/.
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()
Output
region revenue
0 East 12.5
1 West 5.0
3
n
0 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])
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
  • WHERE col = NULL returns nothing. Use IS NULL.
  • NOT IN (subquery) returns nothing if the subquery yields one NULL. Use NOT EXISTS.
  • SQLite integer division: SUM(flag) * 100 / COUNT(*) gives whole numbers. Write 100.0.
  • A condition on the right table of a LEFT JOIN in WHERE turns it into an inner join. Move it into ON.
  • 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 to ORDER BY.
  • The default frame with ORDER BY includes ties: a running total over raw lines jumps by whole days. Aggregate to one row per key first, or use ROWS.
  • WHERE runs before window functions. Filtering in the same query as LAG removes the rows LAG needs. Filter in an outer query or with QUALIFY.
  • 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 strftime wants 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. Call con.close().
  • In the default (legacy) sqlite3 mode, CREATE and DROP commit at once, so with con: cannot roll them back. Connect with autocommit=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. Use rel.show(max_width=100).
  • df.to_sql without index=False writes the index as an extra column.