SQL (Structured Query Language) asks a database for rows. This page covers the SQL you need for analysis, the two engines of the course and their Python APIs: SQLite (in the standard library, one file per database) and DuckDB (an analytics engine that also queries CSV, Parquet and DataFrames). Examples use the course database data/shop.db (tables stores, products, customers, orders) and data/sales.csv. SQL blocks are for reading; the Python blocks run them.
I want to…
Use…
Example
open a SQLite file read-only
URI mode
sqlite3.connect("file:data/shop.db?mode=ro", uri=True)
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 / one value
fetchone()
(n,) = con.execute("SELECT COUNT(*) FROM orders").fetchone()
rows as dicts
con.row_factory = sqlite3.Row
row["city"], dict(row)
column names
cur.description
[c[0] for c in cur.description]
pass a value safely
? placeholder + tuple
con.execute("SELECT * FROM stores WHERE region = ?", ("West",))
pass named values
:name (sqlite3), $name (DuckDB)
params={"start": "2024-01-01"}
insert many rows
executemany
con.executemany("INSERT INTO t VALUES (?, ?)", rows)
commit or roll back as one unit
with con:
with con: con.executemany(...)
query a CSV or Parquet file
DuckDB, path as a 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 or Polars frame
DuckDB, frame variable as a table
duckdb.sql("SELECT ... FROM sales_df")
open a SQLite file in DuckDB
ATTACH
ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY)
result as a pandas / Polars frame
.df() / .pl()
duckdb.sql(sql).pl()
SQLite → pandas
pd.read_sql_query
pd.read_sql_query(sql, con, params=(...,))
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 rows / non-null values / distinct
COUNT(*), COUNT(col), COUNT(DISTINCT col)
COUNT(DISTINCT order_id)
aggregate some rows only
FILTER (WHERE ...)
SUM(revenue) FILTER (WHERE channel = 'online')
replace NULL
COALESCE
COALESCE(discount, 0)
avoid division by zero
NULLIF
revenue / NULLIF(quantity, 0)
bucket values
CASE WHEN
CASE WHEN x < 30 THEN 'low' ELSE 'high' END
rows without a match
anti-join
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
name the steps of a query
CTE
WITH monthly AS (...), ranked AS (...) SELECT ...
top N per group
ROW_NUMBER() + QUALIFY (DuckDB)
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) <= 3
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
a ROWS frame
AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
share of the total
an empty window
revenue / SUM(revenue) OVER ()
month label
strftime
SQLite strftime('%Y-%m', d), DuckDB strftime(d, '%Y-%m')
long → wide
conditional aggregation, DuckDB PIVOT
PIVOT sales ON channel USING SUM(quantity)
list the tables
sqlite_schema, DuckDB SHOW TABLES
SELECT name FROM sqlite_schema WHERE type = 'table'
describe a table
pragma_table_info, DuckDB DESCRIBE
DESCRIBE SELECT * FROM 'data/stores.csv'
save a result to Parquet
DuckDB COPY ... TO
COPY (SELECT ...) TO 'out.parquet' (FORMAT parquet)
pd.set_option( "display.width" , 100 )
pd.set_option( "display.max_columns" , 12 )
pd.set_option( "display.precision" , 3 )
pl.Config.set_tbl_width_chars( 100 )
pl.Config.set_fmt_float( "full" )
con = sqlite3.connect( "file:data/shop.db?mode=ro" , uri = True ) # SQLite, read-only
ddb = duckdb.connect() # DuckDB, in memory
ddb.sql( "ATTACH 'data/shop.db' AS shop (TYPE sqlite, READ_ONLY)" ) # the same file
ddb.sql( "CREATE VIEW sales AS SELECT * FROM 'data/sales.csv'" ) # a CSV as a table
tables = "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
print ([name for (name,) in con.execute(tables)])
print (ddb.sql( "SELECT COUNT(*) FROM shop.orders" ).fetchall())
print (ddb.sql( "SELECT order_date FROM sales" ).types) # DuckDB detects real dates
['customers', 'orders', 'products', 'stores']
You write SELECT first, but the database runs it fifth. The logical order explains most errors: WHERE cannot see aggregates, and window results do not exist until SELECT runs.
SELECT region, COUNT ( * ) AS lines -- written 1, runs 5
FROM orders AS o -- written 2, runs 1
JOIN stores AS s USING (store_id) -- written 3, runs 1
WHERE o . order_date >= '2024-01-01' -- written 4, runs 2
GROUP BY region -- written 5, runs 3
HAVING COUNT ( * ) > 1000 -- written 6, runs 4
ORDER BY lines DESC -- written 7, runs 7
LIMIT 3 ; -- written 8, runs 8
flowchart LR
F["FROM / JOIN"] --> W["WHERE"] --> G["GROUP BY"] --> H["HAVING"]
H --> S["SELECT + windows"] --> Q["QUALIFY"] --> O["ORDER BY"] --> L["LIMIT"]
Logical step
Clause
Does
Sees aggregates
Sees window results
Sees SELECT aliases
1
FROM, JOIN
build the rows from tables
no
no
no
2
WHERE
drop rows
no
no
no (yes in SQLite and DuckDB)
3
GROUP BY
form groups
no
no
yes in SQLite and DuckDB
4
HAVING
drop groups
yes
no
yes in SQLite and DuckDB
5
SELECT
compute columns, then window functions
yes
defines them
—
5
DISTINCT
drop duplicate output rows
—
—
—
6
QUALIFY (DuckDB)
drop rows by a window result
yes
yes
yes
7
ORDER BY
sort
yes
yes
yes
8
LIMIT n OFFSET m
cut
—
—
—
con.execute( "SELECT region, COUNT(*) FROM stores WHERE COUNT(*) > 2 GROUP BY region" )
sqlite3.OperationalError: misuse of aggregate: COUNT()
fixed = """SELECT region, ROUND(AVG(size_sqm)) AS avg_sqm FROM stores
GROUP BY region HAVING avg_sqm > 2000 ORDER BY region"""
print (con.execute(fixed).fetchall()) # HAVING sees aggregates (and, here, aliases)
[('East', 2403.0), ('North', 2073.0), ('South', 2360.0)]
Operator or function
Meaning
Note
=, <> / !=, <, <=, >, >=
compare
text in single quotes: 'East'
AND, OR, NOT
logic
AND binds tighter than OR: add parentheses
IN ('a', 'b'), NOT IN (...)
membership
NOT IN with a NULL in the list returns no rows
BETWEEN a AND b
inclusive range
for dates prefer >= a AND < b
LIKE 'Run%', _
% any text, _ one character
SQLite: ignores ASCII case; DuckDB: case-sensitive, ILIKE ignores case
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)
CAST(x AS REAL), x::DOUBLE, TRY_CAST(x AS INTEGER)
convert type
:: and TRY_CAST are DuckDB
a || b
join text
NULL || 'x' is NULL; DuckDB concat() skips NULLs
lower, upper, trim, length, substr(s, start, n), replace
text functions
both engines; positions start at 1
ROUND(x, 2)
round half away from zero
Python’s round rounds half to even
7 / 2
division
SQLite 3 (integers), DuckDB 3.5; DuckDB 7 // 2 is 3
SELECT DISTINCT a, b
unique rows
applies to the whole output row
ORDER BY x DESC NULLS LAST
sort
SQLite: NULL is the smallest value (first in ASC, last in DESC); DuckDB: last in both
Expression
Result
Why
NULL = NULL, NULL <> 1, 1 + NULL
NULL
unknown in, unknown out
NULL IS NULL
true
the only safe test
NULL OR TRUE, NULL AND FALSE
true, false
three-valued logic
WHERE cond
keeps true rows only
false and NULL rows are dropped
COUNT(*) vs COUNT(col)
all rows vs non-NULL values
SUM, AVG, MIN, MAX
skip NULLs
SUM of only NULLs is NULL
GROUP BY col
all NULLs form one group
Join
Keeps
Missing side
pandas
Polars
[INNER] JOIN ... ON a.k = b.k
matching pairs
—
merge(how="inner")
join(how="inner")
LEFT JOIN
every left row
right columns NULL
how="left"
how="left"
RIGHT JOIN
every right row
left columns NULL
how="right"
how="right"
FULL [OUTER] JOIN
every row of both
NULL on the missing side
how="outer"
how="full"
CROSS JOIN
every pair (n × m)
—
how="cross"
how="cross"
WHERE EXISTS (subquery)
left rows with a match, once
—
df[df.k.isin(o.k)]
how="semi"
WHERE NOT EXISTS (subquery)
left rows without a match
—
df[~df.k.isin(o.k)]
how="anti"
LEFT JOIN ... WHERE b.k IS NULL
left rows without a match
—
merge(indicator=True)
how="anti"
self-join t AS a JOIN t AS b
pairs inside one table
—
df.merge(df, ...)
df.join(df, ...)
USING (k)
ON a.k = b.k, one k column
—
on="k"
on="k"
RIGHT and FULL joins need SQLite 3.39 or later; check sqlite3.sqlite_version (the course environment has 3.50). A join returns one row per matching pair : a key that repeats on the right side multiplies the left rows.
SELECT COUNT(*) FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.customer_id IS NULL
SELECT COUNT(*) FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
SELECT COUNT(*) FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders UNION ALL SELECT NULL)
fan_out = "SELECT COUNT(*) FROM stores JOIN stores AS s2 USING (region)"
for sql in [never, not_exists, not_in_null, fan_out]:
print (con.execute(sql).fetchone())
The two anti-joins agree. One NULL in the NOT IN list makes every comparison unknown, so no row passes. The self-join on a non-unique key turns 12 stores into 36 rows.
Function
Returns
Engines
COUNT(*), COUNT(col), COUNT(DISTINCT col)
rows, non-NULL values, distinct values
both
SUM, AVG, MIN, MAX
total, mean, extremes
both
AVG(flag) on a 0/1 column
a rate
both
agg(x) FILTER (WHERE cond)
aggregate only some rows
both
SUM(CASE WHEN cond THEN x END)
the same, portable to every database
both
group_concat(x, ','), string_agg(x, ',')
join text
both (string_agg in SQLite 3.44+)
median(x), quantile_cont(x, 0.9), mode(x)
median, percentile, most common
DuckDB
arg_max(id, value), arg_min(id, value)
id of the row with the largest / smallest value
DuckDB
GROUP BY ALL
group by every non-aggregated column
DuckDB
ORDER BY ALL
sort by every output column, left to right
DuckDB
ANY_VALUE(col)
any value of the group
DuckDB (SQLite allows a bare column)
ROUND(100.0 * AVG(churned), 1) AS churn_pct,
COUNT(*) FILTER (WHERE contract = 'month-to-month') AS monthly,
SUM(CASE WHEN has_autopay = 1 THEN 1 ELSE 0 END) AS autopay
WHERE tenure_months >= 12
print (pd.read_sql_query(churn, con))
plan customers churn_pct monthly autopay
0 premium 653 18.4 250 335
2 standard 1262 8.2 482 691
arg_max(product, revenue) AS biggest_line,
median(revenue) AS median_rev,
ROUND(quantile_cont(revenue, 0.9), 2) AS p90_rev,
string_agg(DISTINCT channel, '/' ORDER BY channel) AS channels
ddb.sql( "PIVOT sales ON channel USING SUM(quantity) GROUP BY region ORDER BY 1" ).show()
┌─────────┬──────────────────────────┬────────────┬─────────┬──────────────┐
│ region │ biggest_line │ median_rev │ p90_rev │ channels │
│ varchar │ varchar │ double │ double │ varchar │
├─────────┼──────────────────────────┼────────────┼─────────┼──────────────┤
│ East │ 14-inch Ultrabook Laptop │ 79.99 │ 349.0 │ online/store │
│ North │ 55-inch 4K Smart TV │ 79.99 │ 340.2 │ online/store │
│ South │ 14-inch Ultrabook Laptop │ 79.99 │ 336.87 │ online/store │
│ West │ 14-inch Ultrabook Laptop │ 79.99 │ 348.66 │ online/store │
└─────────┴──────────────────────────┴────────────┴─────────┴──────────────┘
┌─────────┬────────┬────────┐
│ region │ online │ store │
│ varchar │ int128 │ int128 │
├─────────┼────────┼────────┤
└─────────┴────────┴────────┘
Form
Syntax
Use
searched
CASE WHEN c1 THEN a WHEN c2 THEN b ELSE d END
ranges and any condition; the first true branch wins
simple
CASE col WHEN 'x' THEN a WHEN 'y' THEN b END
map fixed values
no ELSE
CASE WHEN c THEN a END
NULL when nothing matches; SUM and COUNT skip it
inside an aggregate
SUM(CASE WHEN channel = 'online' THEN revenue ELSE 0 END)
pivot categories into columns
in ORDER BY
ORDER BY CASE plan WHEN 'premium' THEN 1 ELSE 2 END
a custom sort order
SQLite shortcut
iif(cond, a, b)
one condition
SELECT CASE WHEN unit_price < 30 THEN 'budget'
WHEN unit_price < 150 THEN 'mid'
ELSE 'premium' END AS band,
ROUND(AVG(unit_price - unit_cost), 2) AS avg_margin
ORDER BY CASE band WHEN 'budget' THEN 1 WHEN 'mid' THEN 2 ELSE 3 END
print (con.execute(bands).fetchall())
[('budget', 9, 14.3), ('mid', 12, 49.84), ('premium', 9, 199.66)]
A CTE (common table expression) names a query step with WITH name AS (...). Each step can read the steps before it, so a long query reads top to bottom.
Form
Example
Returns
scalar subquery
WHERE unit_price > (SELECT AVG(unit_price) FROM products)
one value
IN subquery
WHERE store_id IN (SELECT store_id FROM stores WHERE region = 'West')
a list
correlated subquery
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
runs per outer row
derived table
FROM (SELECT ...) AS t
a table
CTE
WITH t AS (SELECT ...) SELECT ... FROM t
a named table
chained CTEs
WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b
steps
recursive CTE
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5)
a generated series
SELECT date_trunc('month', order_date)::DATE AS month, SUM(revenue) AS revenue
SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev
SELECT month, ROUND(revenue, 2) AS revenue,
ROUND(100 * (revenue / prev - 1), 1) AS mom_pct
WHERE month >= DATE '2024-10-01' -- filter after the window, not before
┌────────────┬───────────┬─────────┐
│ month │ revenue │ mom_pct │
│ date │ double │ double │
├────────────┼───────────┼─────────┤
│ 2024-10-01 │ 166147.92 │ 17.3 │
│ 2024-11-01 │ 268466.55 │ 61.6 │
│ 2024-12-01 │ 302911.77 │ 12.8 │
└────────────┴───────────┴─────────┘
A window function computes a value from a set of rows related to the current row, without merging the rows. The row count does not change.
PARTITION BY group_cols -- separate windows (optional)
ORDER BY sort_cols -- order inside each window
ROWS BETWEEN start AND end -- the frame (optional)
Function
Gives
Note
ROW_NUMBER()
1, 2, 3, 4
ties broken arbitrarily: add a tie-break column
RANK()
1, 2, 2, 4
ties share a rank, then a gap
DENSE_RANK()
1, 2, 2, 3
ties share a rank, no gap
NTILE(4)
bucket 1–4
quartiles
PERCENT_RANK(), CUME_DIST()
relative position 0–1
LAG(x), LAG(x, 12), LEAD(x)
the previous, 12th previous, next value
NULL at the edges; LAG(x, 1, 0) sets a default
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
pandas transform("mean"), Polars .over("g")
Frame
Rows the function sees
no ORDER BY
the whole partition
ORDER BY, no frame
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: up to the current row and its ties
ROWS UNBOUNDED PRECEDING
up to the current row, no ties
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
a 7-row moving window
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
a centered 3-row window
RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW
the last 7 calendar days (DuckDB)
SELECT region, product, ROUND(SUM(revenue), 2) AS revenue
SELECT region, product, revenue,
ROUND(100 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS pct
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, product) <= 2
ORDER BY region, revenue DESC
ddb.sql(top2).show( max_width = 100 )
┌─────────┬──────────────────────────┬───────────┬────────┐
│ region │ product │ revenue │ pct │
│ varchar │ varchar │ double │ double │
├─────────┼──────────────────────────┼───────────┼────────┤
│ East │ 55-inch 4K Smart TV │ 195239.7 │ 19.6 │
│ East │ 14-inch Ultrabook Laptop │ 192687.3 │ 19.4 │
│ North │ 55-inch 4K Smart TV │ 162504.9 │ 18.3 │
│ North │ 14-inch Ultrabook Laptop │ 145291.05 │ 16.4 │
│ South │ 14-inch Ultrabook Laptop │ 165398.55 │ 18.5 │
│ South │ 55-inch 4K Smart TV │ 136849.65 │ 15.3 │
│ West │ 14-inch Ultrabook Laptop │ 161951.55 │ 19.7 │
│ West │ 55-inch 4K Smart TV │ 133991.85 │ 16.3 │
└─────────┴──────────────────────────┴───────────┴────────┘
mem = sqlite3.connect( ":memory:" )
mem.execute( "CREATE TABLE m (month TEXT, revenue REAL)" )
mem.executemany( "INSERT INTO m VALUES (?, ?)" , [( "01" , 10 ), ( "02" , 30 ), ( "03" , 20 )])
SUM(revenue) OVER (ORDER BY month) AS running,
LAG(revenue) OVER (ORDER BY month) AS prev,
RANK() OVER (ORDER BY revenue DESC) AS rnk,
AVG(revenue) OVER (ORDER BY month ROWS 1 PRECEDING) AS ma2 -- this + previous
for row in mem.execute(win):
('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)
SQLite has no QUALIFY: filter on a window result in an outer query (SELECT * FROM (... ) WHERE rn <= 2) or a CTE.
SQLite has no date type: store dates as ISO text ('2024-05-01'), which sorts and compares correctly. DuckDB has real DATE, TIMESTAMP and INTERVAL types.
Task
SQLite (text dates)
DuckDB (DATE, TIMESTAMP)
literal
'2024-05-01'
DATE '2024-05-01', '2024-05-01'::DATE
today
date('now')
current_date
parse other formats
not built in: store ISO text
strptime('05/01/2024', '%m/%d/%Y') (a TIMESTAMP)
year, month as numbers
CAST(strftime('%Y', d) AS INTEGER)
year(d), month(d), quarter(d)
month label
strftime('%Y-%m', d) (format first)
strftime(d, '%Y-%m') (date first)
first of month
date(d, 'start of month')
date_trunc('month', d) (a TIMESTAMP; add ::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 + 7 (a DATE), d + INTERVAL 1 MONTH (a TIMESTAMP)
Jan 31 + 1 month
2024-03-02 (rolls over)
2024-02-29 (clamps to the month end)
days between
julianday(b) - julianday(a) (a float)
date_diff('day', a, b) or b - a
day of week
strftime('%w', d): '0' = Sunday, as text
dayofweek(d): 0 = Sunday; isodow(d): 1 = Monday
day / month name
not built in
dayname(d), monthname(d)
one year
d >= '2024-01-01' AND d < '2025-01-01'
the same, or year(d) = 2024
a calendar of days
recursive CTE
generate_series(DATE '2024-01-01', DATE '2024-01-31', INTERVAL 1 DAY)
lite = """SELECT strftime('%Y-%m', '2024-01-31'), -- month label
date('2024-01-31', '+1 month'), -- add a month
strftime('%w', '2024-05-05'), -- day of week (a Sunday)
julianday('2024-03-01') - julianday('2024-01-01'), -- days between
date('2024-05-17', 'start of month')"""
duck = """SELECT strftime(DATE '2024-01-31', '%Y-%m'),
DATE '2024-01-31' + INTERVAL 1 MONTH,
dayofweek(DATE '2024-05-05'),
date_diff('day', DATE '2024-01-01', DATE '2024-03-01'),
date_trunc('month', DATE '2024-05-17')"""
print (con.execute(lite).fetchone())
print (ddb.sql(duck).fetchall()[ 0 ])
print (con.execute( "SELECT strftime('2024-05-05', '%Y')" ).fetchone()) # wrong order
('2024-01', '2024-03-02', '0', 60.0, '2024-05-01')
('2024-01', datetime.datetime(2024, 2, 29, 0, 0), 0, 60, datetime.datetime(2024, 5, 1, 0, 0))
Call
Does
sqlite3.connect("shop.db")
open or create a file
sqlite3.connect("file:shop.db?mode=ro", uri=True)
open read-only; fails if the file is missing
sqlite3.connect(":memory:")
a database in memory
sqlite3.connect(p, autocommit=False)
Python 3.12+: every change is in a transaction, CREATE and DROP too
con.execute(sql, params)
run one statement; returns a cursor
con.executemany(sql, rows)
run one statement per row
con.executescript(sql)
run several statements (never with user input)
cur.fetchone(), cur.fetchmany(n), cur.fetchall(), for row in cur:
read rows as tuples
cur.description
column names: [c[0] for c in cur.description]
con.row_factory = sqlite3.Row
rows that also work like dicts: row["city"]
with con:
commit on success, roll back on an exception; does not close
con.commit(), con.rollback(), con.close()
transactions and cleanup
con.backup(other), con.iterdump()
copy a database; dump it as SQL
contextlib.closing(sqlite3.connect(p))
a with block that closes
from contextlib import closing
with closing(sqlite3.connect( ":memory:" , autocommit = False )) as mem:
mem.row_factory = sqlite3.Row
with mem: # one transaction: commit at the end, roll back on an error
mem.execute( "CREATE TABLE targets (store_id TEXT PRIMARY KEY, target REAL)" )
rows = [( "S01" , 90_000.0 ), ( "S02" , 70_000.0 )]
mem.executemany( "INSERT INTO targets VALUES (?, ?)" , rows)
cur = mem.execute( "SELECT store_id, target FROM targets ORDER BY target DESC" )
print ([c[ 0 ] for c in cur.description])
print (row[ "store_id" ], row[ "target" ], dict (row))
print (cur.fetchall()[ 0 ][ 0 ]) # rows still index by position
S01 90000.0 {'store_id': 'S01', 'target': 90000.0}
Call
Does
duckdb.sql(sql)
run on the default in-memory connection; returns a relation
duckdb.connect(), duckdb.connect("file.duckdb", read_only=True)
a connection in memory / to a file
ddb.sql(sql, params=...)
a relation : a lazy query; runs when you fetch
rel.fetchall(), rel.df(), rel.pl(), rel.fetchnumpy()
results as tuples, pandas, Polars, NumPy
rel.show(max_width=100), rel.columns, rel.types, rel.shape
inspect
rel.limit(5).fetchall()
the first rows (relations have no fetchone or fetchmany in DuckDB 2)
rel.filter("x > 0").aggregate("COUNT(*)"), .order("x"), .project("a, b")
the relational API: build a query with methods
ddb.sql("SELECT * FROM rel")
a relation variable can be queried by name
ddb.execute(sql, params)
a DB-API style call; then fetchone, fetchall, df() on the connection
ddb.complete(), ddb.abort()
finish or drop an unfinished execute result (DuckDB 2)
ddb.register("name", df)
expose a DataFrame under a table name
rel.write_parquet(p), rel.write_csv(p), COPY (...) TO p (FORMAT parquet)
save a result
ddb.sql("ATTACH 'x.db' AS x (TYPE sqlite, READ_ONLY)")
read a SQLite file (the extension downloads once)
read_csv(p, union_by_name = true, filename = true)
many files; add the file name as a column
rel = ddb.sql( "SELECT store_id, city, size_sqm FROM 'data/stores.csv'" )
print (rel.shape, rel.columns, [ str (t) for t in rel.types])
big = rel.filter( "size_sqm > 2500" ).order( "size_sqm DESC" ) # still lazy
print (big.limit( 2 ).fetchall())
print (ddb.sql( "SELECT COUNT(*) AS n FROM big" ).fetchall()) # query a relation by name
print ( type (big.df()). __name__ , big.pl().schema)
big.write_parquet( "big_stores.parquet" )
print (ddb.sql( "SELECT COUNT(*) FROM 'big_stores.parquet'" ).fetchall())
(12, 3) ['store_id', 'city', 'size_sqm'] ['VARCHAR', 'VARCHAR', 'BIGINT']
[('S07', 'New York', 3400), ('S04', 'Houston', 3100)]
DataFrame Schema({'store_id': String, 'city': String, 'size_sqm': Int64})
In DuckDB 2 a connection keeps the result of execute() until you fetch every row. A half-read result blocks sql() on that connection:
print (ddb.execute( "SELECT * FROM range(3)" ).fetchone()) # one row of three read
ddb.sql( "SELECT 1" ).fetchall()
_duckdb.ResourceInUseException: Resource In Use Error: connection has an unfinished result from execute(); call complete() or abort(), or fetch until a fetch returns no rows, before other work on this connection, or use a separate connection from cursor()
ddb.abort() # drop the unfinished result (or fetchall(), or ddb.complete())
print (ddb.sql( "SELECT 1" ).fetchall())
Never build SQL with f-strings or + from values you did not write. A placeholder sends the value separately from the SQL text, so it can never change the query.
Driver
Positional
Named
Values
sqlite3
?
:name
a tuple ((x,) for one) / a dict
DuckDB
? or $1
$name
a list / a dict, params= in sql()
pd.read_sql_query + sqlite3
?
:name
params=(...) / params={...}
pl.read_database
the driver’s style
execute_options={"parameters": ...}
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
named = "SELECT COUNT(*) FROM orders WHERE order_date >= :start AND store_id = :store"
print (con.execute(named, { "start" : "2024-01-01" , "store" : "S01" }).fetchone())
west = ddb.sql( "SELECT COUNT(*) FROM sales WHERE region = $r" , params = { "r" : "West" })
print (west.fetchall()) # DuckDB: $name and a dict
ALLOWED = { "region" , "channel" , "category" } # identifiers cannot be parameters
def revenue_by (column: str ) -> list[ tuple ]:
if column not in ALLOWED :
raise ValueError ( f "unknown column: { column !r } " )
sql = f "SELECT { column } , ROUND(SUM(revenue)) FROM sales GROUP BY 1 ORDER BY 1"
return ddb.sql(sql).fetchall()
print (revenue_by( "channel" ))
[('online', 1519466.0), ('store', 2077057.0)]
SQL
pandas
Polars
SELECT a, b FROM t
t[["a", "b"]]
t.select("a", "b")
SELECT *, a * 2 AS c
t.assign(c=t["a"] * 2)
t.with_columns(c=pl.col("a") * 2)
WHERE x > 5 AND y = 'A'
t.query("x > 5 and y == 'A'")
t.filter(pl.col("x") > 5, pl.col("y") == "A")
WHERE k IN ('a', 'b')
t[t["k"].isin(["a", "b"])]
t.filter(pl.col("k").is_in(["a", "b"]))
WHERE x IS NULL
t[t["x"].isna()]
t.filter(pl.col("x").is_null())
ORDER BY x DESC LIMIT 3
t.nlargest(3, "x")
t.top_k(3, by="x")
SELECT DISTINCT k
t["k"].drop_duplicates()
t.select("k").unique()
COUNT(*) ... GROUP BY k
t.groupby("k").size()
t.group_by("k").len()
SUM(x) ... GROUP BY k
t.groupby("k")["x"].sum()
t.group_by("k").agg(pl.col("x").sum())
HAVING COUNT(*) > 10
filter the aggregated frame
.filter(pl.col("len") > 10) after len()
COUNT(DISTINCT k)
t["k"].nunique()
pl.col("k").n_unique()
LEFT JOIN u USING (k)
t.merge(u, on="k", how="left")
t.join(u, on="k", how="left")
WHERE NOT EXISTS (...)
t[~t["k"].isin(u["k"])]
t.join(u, on="k", how="anti")
CASE WHEN ... END
np.where, np.select
pl.when().then().otherwise()
COALESCE(x, 0)
t["x"].fillna(0)
pl.col("x").fill_null(0)
SUM(x) OVER (PARTITION BY g)
t.groupby("g")["x"].transform("sum")
pl.col("x").sum().over("g")
ROW_NUMBER() OVER (PARTITION BY g ORDER BY v DESC)
t.groupby("g")["v"].rank(method="first", ascending=False)
pl.col("v").rank("ordinal", descending=True).over("g")
SUM(v) OVER (PARTITION BY g ORDER BY d)
t.sort_values("d").groupby("g")["v"].cumsum()
pl.col("v").cum_sum().over("g", order_by="d")
LAG(v) OVER (PARTITION BY g ORDER BY d)
t.sort_values("d").groupby("g")["v"].shift()
pl.col("v").shift().over("g", order_by="d")
AVG(v) OVER (ORDER BY d ROWS 6 PRECEDING)
t["v"].rolling(7, min_periods=1).mean()
pl.col("v").rolling_mean(7, min_samples=1)
UNION ALL / UNION
pd.concat([a, b]) / + .drop_duplicates()
pl.concat([a, b]) / + .unique()
Direction
Code
SQLite → pandas
pd.read_sql_query(sql, con, params=(...), parse_dates=["order_date"])
SQLite → Polars
pl.read_database(sql, connection=con)
pandas → SQLite
df.to_sql("t", con, index=False, if_exists="replace") (returns the row count)
pandas or Polars → DuckDB
duckdb.sql("SELECT ... FROM df"): the variable name is the table name
DuckDB → pandas / Polars
rel.df() / rel.pl()
Polars → SQL on itself
df.sql("SELECT ... FROM self")
orders = pd.read_sql_query(
"SELECT order_id, order_date, revenue FROM orders WHERE store_id = ? LIMIT 3" ,
parse_dates = [ "order_date" ],
print (orders.dtypes.astype( str ).to_dict())
stores_pl = pl.read_database( "SELECT store_id, region FROM stores" , connection = con)
counts = duckdb.sql( "SELECT region, COUNT(*) FROM stores_pl GROUP BY ALL ORDER BY 1" )
print (counts.pl().rows()) # a Polars frame queried by its variable name
mem = sqlite3.connect( ":memory:" )
print (orders.to_sql( "orders" , mem, index = False )) # rows written
print (mem.execute( "SELECT typeof(order_date) FROM orders" ).fetchone()) # dates: text
{'order_id': 'str', 'order_date': 'datetime64[us]', 'revenue': 'float64'}
[('East', 3), ('North', 3), ('South', 3), ('West', 3)]
Topic
SQLite
DuckDB
install
standard library (import sqlite3)
pip install duckdb
workload
OLTP: many small reads and writes, apps
OLAP: scans and aggregations, analysis
storage
rows, one .db file
columns, a .duckdb file or memory
files
none
CSV, Parquet, JSON, globs, DataFrames
types
flexible (type affinity), no DATE, no Boolean
strict: DATE, TIMESTAMP, BOOLEAN, lists, structs
"text" in double quotes
a string if no such column exists
always a column name: Binder Error
7 / 2
3
3.5 (7 // 2 is 3)
LIKE
ignores ASCII case
case-sensitive; ILIKE ignores case
column not in GROUP BY
allowed, value from any row
Binder Error; use ANY_VALUE(col)
extras
iif, julianday
QUALIFY, GROUP BY ALL, PIVOT, EXCLUDE, arg_max, median
NULLs in ORDER BY
first (ASC) / last (DESC)
last
Trap
Symptom
Fix
WHERE col = NULL
no rows
IS NULL
NOT IN (subquery) with a NULL inside
no rows
NOT EXISTS
SQLite integer division
SUM(flag) * 100 / COUNT(*) gives whole numbers
write 100.0, or CAST(... AS REAL)
a filter on the right table of a LEFT JOIN in WHERE
unmatched left rows vanish (an inner join)
move the condition into ON
a join to a non-unique key
rows multiply; sums inflate (fan-out)
join to a primary key, or aggregate first
an aggregate in WHERE
misuse of aggregate (SQLite), Binder Error (DuckDB)
HAVING
a window result in WHERE
error, or rows that LAG needs are gone
filter in an outer query, or QUALIFY in DuckDB
ROW_NUMBER() with tied sort values
a different row wins on each run
add a tie-break column to ORDER BY
running total over raw lines
jumps by whole days: the default frame includes ties
aggregate to one row per key, or use ROWS
BETWEEN '2024-01-01' AND '2024-01-31' on timestamp text
rows later on January 31 are missing
>= '2024-01-01' AND < '2024-02-01'
SQLite strftime(d, '%Y')
NULL
the format comes first in SQLite: strftime('%Y', d)
month arithmetic
SQLite Jan 31 + 1 month = March 2; DuckDB = February 29
test month ends; use start of month before adding
DuckDB date_trunc or + INTERVAL on a date
a TIMESTAMP, printed with 00:00:00
cast back: date_trunc('month', d)::DATE
f-strings with user input
SQL injection
placeholders; allowlist table and column names
execute("... WHERE id = ?", cid)
ProgrammingError
a tuple: (cid,)
execute("SELECT 1; SELECT 2")
ProgrammingError: You can only execute one statement at a time
one statement per call
with sqlite3.connect(p) as con:
the file stays open
it only commits; call con.close() or use closing()
sqlite3.connect("data/shop.db") to read
a typo in the path creates an empty database
"file:...?mode=ro", uri=True
DuckDB rel.fetchone(), rel.fetchmany()
AttributeError in DuckDB 2
rel.limit(1).fetchall(), .pl().item(), .df()
a half-read ddb.execute() result
ResourceInUseException on the next ddb.sql()
fetch all rows, ddb.complete() / ddb.abort(), or ddb.cursor()
ddb.execute(...).pl()
AttributeError: connections have no pl()
ddb.sql(...).pl()
DuckDB SUM of an integer column
type HUGEINT (int128): pandas gets float64, Polars Decimal(38, 0)
SUM(quantity)::BIGINT
print(rel) of a wide DuckDB result
lines wider than the screen
rel.show(max_width=100)
df.to_sql without index=False
an extra index column
index=False
dates written by to_sql to SQLite
text such as 2023-01-01 00:00:00
parse_dates= when you read them back