Query Parquet and CSV in-process with DuckDB, use window functions, QUALIFY, ASOF joins and PIVOT, and export Django data to Parquet so analytics never load your production database.
DuckDB is an analytical SQL database that runs inside your Python process, with no server to install. It reads Parquet and CSV files directly, executes queries on all cores with a columnar, vectorised engine, and exchanges results with Polars and pandas through Apache Arrow. This tutorial covers the SQL features that make analytical queries short (window functions, QUALIFY, ASOF joins, PIVOT) and shows how to export data from a Django application to Parquet, so reporting runs on files instead of on your production database.
Tested with Python 3.13, DuckDB 2.0.1, Polars 2.2.0, pandas 3.1.2 and PyArrow 26.0.1. The Django management command was tested with Django 5.2.20 and 6.1.4.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "duckdb>=2.0,<3" "polars>=2.2,<3" "pandas>=3.1,<4" "pyarrow>=26,<27"
The examples use two million synthetic orders for a subscription product and an hourly USD to EUR exchange rate, generated with a fixed seed:
import numpy as np
import polars as pl
rng = np.random.default_rng(7)
n = 2_000_000
seconds = np.sort(rng.integers(0, 365 * 86_400, n))
pl.DataFrame({
"order_id": np.arange(1, n + 1),
"customer_id": rng.integers(1, 50_001, n),
"product": rng.choice(["starter", "pro", "team"], n, p=[0.6, 0.3, 0.1]),
"currency": rng.choice(["EUR", "USD"], n, p=[0.8, 0.2]),
"amount": np.round(rng.gamma(2.0, 25.0, n), 2),
"created_at": (np.datetime64("2026-01-01T00:00:00", "us")
+ (seconds * 1_000_000).astype("timedelta64[us]")),
}).write_parquet("orders.parquet")
hours = np.arange(365 * 24)
pl.DataFrame({
"valid_from": np.datetime64("2026-01-01T00:00:00", "us")
+ (hours * 3_600_000_000).astype("timedelta64[us]"),
"usd_eur": np.round(0.92 + np.cumsum(rng.normal(0, 0.0005, hours.size)), 4),
}).write_csv("fx_rates.csv")
Amounts are stored as floating point here to keep the generator short. Real money belongs in a decimal type; the Django export later in this tutorial does that properly.
PostgreSQL is an OLTP system, built for many small concurrent transactions on individual rows. Analytical (OLAP) queries read a few columns of millions of rows and aggregate them. DuckDB is designed for that pattern:
The trade-off is concurrency; the section on persistence explains the limits.
A file path in single quotes is a table. No import step is needed:
import duckdb
con = duckdb.connect() # in-memory database
con.sql("""
SELECT product, count(*) AS orders, round(sum(amount), 2) AS revenue
FROM 'orders.parquet'
GROUP BY product
ORDER BY revenue DESC
""").show()
┌─────────┬─────────┬─────────────┐
│ product │ orders │ revenue │
│ varchar │ int64 │ double │
├─────────┼─────────┼─────────────┤
│ starter │ 1199352 │ 59924887.59 │
│ pro │ 600548 │ 30076626.78 │
│ team │ 200100 │ 9986185.97 │
└─────────┴─────────┴─────────────┘
For CSV, DuckDB samples the file and detects delimiter, header and column types (here it would infer DOUBLE for the rate). For anything that runs unattended, declare the types so a malformed file fails loudly:
con.sql("""
SELECT *
FROM read_csv('fx_rates.csv', header = true,
columns = {'valid_from': 'TIMESTAMP', 'usd_eur': 'DECIMAL(8,4)'})
LIMIT 3
""").show()
┌─────────────────────┬──────────────┐
│ valid_from │ usd_eur │
│ timestamp │ decimal(8,4) │
├─────────────────────┼──────────────┤
│ 2026-01-01 00:00:00 │ 0.9200 │
│ 2026-01-01 01:00:00 │ 0.9196 │
│ 2026-01-01 02:00:00 │ 0.9204 │
└─────────────────────┴──────────────┘
Parquet carries its own schema and per-row-group statistics, so DuckDB can push projections and filters into the scan. EXPLAIN shows it:
plan = con.sql("""
EXPLAIN
SELECT customer_id, sum(amount)
FROM 'orders.parquet'
WHERE created_at >= TIMESTAMP '2026-12-01' AND product = 'team'
GROUP BY customer_id
""").fetchall()
print(plan[0][1])
...
╭─ Parquet Scan ─────────┴────────────────────────╮
│ Function: PARQUET_SCAN │
│ Projections: customer_id, amount │
│ Filters: │
│ created_at >= '2026-12-01 00:00:00'::TIMESTAMP, │
│ product = 'team' │
│ ~400,000 rows │
╰─────────────────────────────────────────────────╯
Only the two output columns are projected out of the scan, and both filters are evaluated inside the reader, where row-group statistics let it skip whole blocks of the (time-sorted) file. Use EXPLAIN ANALYZE to run the query and see actual row counts and timings per operator.
For data that grows over time, write one directory per partition. COPY ... TO with PARTITION_BY produces the Hive-style layout (year=2026/month=3/...) that DuckDB, Polars, PyArrow and Spark all understand:
con.sql("""
COPY (
SELECT *, year(created_at) AS year, month(created_at) AS month
FROM 'orders.parquet'
)
TO 'orders_by_month' (FORMAT parquet, PARTITION_BY (year, month),
OVERWRITE_OR_IGNORE)
""")
plan = con.sql("""
EXPLAIN
SELECT count(*)
FROM read_parquet('orders_by_month/*/*/*.parquet', hive_partitioning = true)
WHERE month = 3
""").fetchall()
print(plan[0][1])
...
╭─ Read Parquet ───────────╮
│ Function: READ_PARQUET │
│ File Filters: month = 3 │
│ Scanning Files: 1/12 │
│ ~169,158 rows │
╰──────────────────────────╯
The partition filter is resolved from directory names alone: eleven of twelve files are never opened. Partition on columns you filter by, and avoid thousands of tiny files.
A window function computes a value for each row from related rows without collapsing them. A named WINDOW clause avoids repetition:
con.sql("CREATE VIEW orders AS SELECT * FROM 'orders.parquet'")
con.sql("""
SELECT
order_id,
created_at,
amount,
row_number() OVER w AS n,
sum(amount) OVER w AS running_spend,
created_at - lag(created_at) OVER w AS since_previous
FROM orders
WHERE customer_id = 42
WINDOW w AS (PARTITION BY customer_id ORDER BY created_at)
ORDER BY created_at
LIMIT 4
""").show()
┌──────────┬─────────────────────┬────────┬───────┬───────────────┬──────────────────┐
│ order_id │ created_at │ amount │ n │ running_spend │ since_previous │
│ int64 │ timestamp │ double │ int64 │ double │ interval │
├──────────┼─────────────────────┼────────┼───────┼───────────────┼──────────────────┤
│ 10923 │ 2026-01-03 00:38:24 │ 52.16 │ 1 │ 52.16 │ NULL │
│ 141433 │ 2026-01-26 22:00:35 │ 79.54 │ 2 │ 131.7 │ 23 days 21:22:11 │
│ 142106 │ 2026-01-27 01:12:25 │ 122.94 │ 3 │ 254.64 │ 03:11:50 │
│ 161200 │ 2026-01-30 13:21:19 │ 12.67 │ 4 │ 267.31 │ 3 days 12:08:54 │
└──────────┴─────────────────────┴────────┴───────┴───────────────┴──────────────────┘
The view is just a name for the file scan. With an ORDER BY in the window, sum defaults to a running total.
Frames can also be defined by value instead of by row count. A seven-day moving average over daily revenue should use RANGE with an interval, so that a missing day does not silently stretch the window to eight calendar days, which is what ROWS BETWEEN 6 PRECEDING would do:
con.sql("""
WITH daily AS (
SELECT created_at::DATE AS day, sum(amount) AS revenue
FROM orders
GROUP BY ALL
)
SELECT
day,
round(revenue, 2) AS revenue,
round(avg(revenue) OVER (
ORDER BY day
RANGE BETWEEN INTERVAL 6 DAYS PRECEDING AND CURRENT ROW
), 2) AS revenue_7d
FROM daily
ORDER BY day
LIMIT 4
""").show()
┌────────────┬───────────┬────────────┐
│ day │ revenue │ revenue_7d │
│ date │ double │ double │
├────────────┼───────────┼────────────┤
│ 2026-01-01 │ 271759.25 │ 271759.25 │
│ 2026-01-02 │ 261469.29 │ 266614.27 │
│ 2026-01-03 │ 265150.91 │ 266126.48 │
│ 2026-01-04 │ 268136.97 │ 266629.11 │
└────────────┴───────────┴────────────┘
GROUP BY ALL groups by every non-aggregated column in the select list, which removes a common source of copy-paste errors.
Window functions are evaluated after WHERE, so filtering on them normally needs a subquery. QUALIFY is to window functions what HAVING is to aggregates. The latest order per customer becomes one statement:
con.sql("""
SELECT customer_id, order_id, created_at, product
FROM orders
QUALIFY row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) = 1
ORDER BY customer_id
LIMIT 3
""").show()
┌─────────────┬──────────┬─────────────────────┬─────────┐
│ customer_id │ order_id │ created_at │ product │
│ int64 │ int64 │ timestamp │ varchar │
├─────────────┼──────────┼─────────────────────┼─────────┤
│ 1 │ 1986789 │ 2026-12-29 14:06:45 │ starter │
│ 2 │ 1894373 │ 2026-12-12 14:50:16 │ starter │
│ 3 │ 1990514 │ 2026-12-30 06:17:02 │ starter │
└─────────────┴──────────┴─────────────────────┴─────────┘
QUALIFY runs after GROUP BY and HAVING, so it can rank aggregated rows too. The best two days per product:
con.sql("""
SELECT product, created_at::DATE AS day, round(sum(amount), 2) AS revenue
FROM orders
GROUP BY product, day
QUALIFY rank() OVER (PARTITION BY product ORDER BY revenue DESC) <= 2
ORDER BY product, revenue DESC
""").show()
┌─────────┬────────────┬───────────┐
│ product │ day │ revenue │
│ varchar │ date │ double │
├─────────┼────────────┼───────────┤
│ pro │ 2026-08-06 │ 90127.88 │
│ pro │ 2026-02-26 │ 89603.0 │
│ starter │ 2026-02-09 │ 173847.47 │
│ starter │ 2026-05-22 │ 172973.66 │
│ team │ 2026-11-13 │ 31707.02 │
│ team │ 2026-02-22 │ 31113.04 │
└─────────┴────────────┴───────────┘
Two details from testing this on DuckDB 2.0.1: QUALIFY cannot be combined with GROUP BY ALL yet (the binder says so explicitly), so list the grouping columns; and since QUALIFY comes after GROUP BY in the clause order, aggregating the result of a QUALIFY needs a CTE:
con.sql("""
WITH first_orders AS (
SELECT customer_id, product
FROM orders
QUALIFY row_number() OVER (PARTITION BY customer_id ORDER BY created_at) = 1
)
SELECT product AS first_product, count(*) AS customers
FROM first_orders
GROUP BY product
ORDER BY customers DESC
""").show()
┌───────────────┬───────────┐
│ first_product │ customers │
│ varchar │ int64 │
├───────────────┼───────────┤
│ starter │ 30145 │
│ pro │ 14823 │
│ team │ 5032 │
└───────────────┴───────────┘
Converting USD orders to EUR needs the rate that was valid when each order was placed: the last rate at or before created_at. An equality join cannot express that, and a correlated subquery is slow. An ASOF join matches each left row with the nearest right row that satisfies the inequality:
con.sql("CREATE TABLE fx AS SELECT * FROM 'fx_rates.csv'")
con.sql("""
SELECT o.order_id, o.created_at, o.amount AS amount_usd,
fx.valid_from, fx.usd_eur,
round(o.amount * fx.usd_eur, 2) AS amount_eur
FROM orders o
ASOF JOIN fx ON o.created_at >= fx.valid_from
WHERE o.currency = 'USD'
ORDER BY o.created_at
LIMIT 3
""").show()
┌──────────┬─────────────────────┬────────────┬─────────────────────┬─────────┬────────────┐
│ order_id │ created_at │ amount_usd │ valid_from │ usd_eur │ amount_eur │
│ int64 │ timestamp │ double │ timestamp │ double │ double │
├──────────┼─────────────────────┼────────────┼─────────────────────┼─────────┼────────────┤
│ 6 │ 2026-01-01 00:01:43 │ 54.75 │ 2026-01-01 00:00:00 │ 0.92 │ 50.37 │
│ 8 │ 2026-01-01 00:02:25 │ 29.56 │ 2026-01-01 00:00:00 │ 0.92 │ 27.2 │
│ 22 │ 2026-01-01 00:07:14 │ 109.97 │ 2026-01-01 00:00:00 │ 0.92 │ 101.17 │
└──────────┴─────────────────────┴────────────┴─────────────────────┴─────────┴────────────┘
The join condition must contain exactly one inequality; any additional conditions must be equalities, which act like partition keys (for example ON o.currency = fx.currency AND o.created_at >= fx.valid_from for a table with several currencies). An inner ASOF JOIN drops left rows that have no earlier match; use ASOF LEFT JOIN to keep them with nulls, and count rows before and after to be sure nothing disappeared.
Reports often want one column per category. DuckDB's PIVOT statement creates those columns from the data, so you do not have to write a sum(CASE WHEN ...) per value:
con.sql("""
PIVOT orders
ON product IN ('starter', 'pro', 'team')
USING count(*) AS n, round(avg(amount), 2) AS avg
GROUP BY currency
ORDER BY currency
""").show()
┌──────────┬───────────┬─────────────┬────────┬─────────┬────────┬──────────┐
│ currency │ starter_n │ starter_avg │ pro_n │ pro_avg │ team_n │ team_avg │
│ varchar │ int64 │ double │ int64 │ double │ int64 │ double │
├──────────┼───────────┼─────────────┼────────┼─────────┼────────┼──────────┤
│ EUR │ 959914 │ 49.97 │ 480482 │ 50.1 │ 159897 │ 49.89 │
│ USD │ 239438 │ 49.96 │ 120066 │ 50.02 │ 40203 │ 49.96 │
└──────────┴───────────┴─────────────┴────────┴─────────┴────────┴──────────┘
Without the IN (...) list, DuckDB first queries the distinct values and builds columns from them. That is convenient interactively, but list the values in code that others depend on, so the output schema does not change when a new product appears. UNPIVOT does the reverse.
DuckDB can query Polars and pandas DataFrames and PyArrow tables by their Python variable name. This replacement scan reads the data through Arrow without importing it first. Results come back the same way:
customers = pl.DataFrame({"customer_id": [1, 2, 3], "country": ["NL", "DE", "NL"]})
by_country = con.sql("""
SELECT c.country, count(*) AS orders
FROM 'orders.parquet' o JOIN customers c USING (customer_id)
GROUP BY c.country
ORDER BY c.country
""").pl()
print(by_country)
print(con.sql("SELECT * FROM by_country").df()) # and back again, as pandas
shape: (2, 2)
┌─────────┬────────┐
│ country ┆ orders │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪════════╡
│ DE ┆ 40 │
│ NL ┆ 82 │
└─────────┴────────┘
country orders
0 DE 40
1 NL 82
Useful variations:
LazyFrame can be queried the same way (FROM lazy_frame), and .pl(lazy=True) returns a LazyFrame, so you can continue in Polars without materialising the DuckDB result first..to_arrow_table() returns a pyarrow.Table. In DuckDB 2.0, .arrow() returns a RecordBatchReader for streaming instead, which is useful for results larger than memory.con.register("customers", df) over name lookup.con.execute("... WHERE product = ?", [product]).fetchall().Two DuckDB 2.0 behaviours break code written for 1.x. A relation returned by con.sql() keeps no result, so every fetch runs the query again, and relations no longer have fetchone(). A result from con.execute() must be fully fetched before the connection runs anything else ("connection has an unfinished result"); use fetchall(), or con.cursor() for an independent statement.
Reporting queries on the production database compete with user traffic for CPU and I/O, and long-running queries hold back vacuum. Instead, export daily or hourly to Parquet, preferably from a read replica, and run every analytical query on the files. The export touches each row once; the dashboard can then run a hundred queries without the database noticing.
Assume an app shop in a project called myproject:
# shop/models.py
from django.db import models
class Customer(models.Model):
email = models.EmailField(unique=True)
country = models.CharField(max_length=2)
created_at = models.DateTimeField()
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="orders")
product = models.CharField(max_length=20)
currency = models.CharField(max_length=3)
amount = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(db_index=True)
The command below exports one UTC day. It streams rows with iterator() so memory stays flat, writes them in batches with an explicit Arrow schema, and renames the file into place only when it is complete:
# shop/management/commands/export_orders_parquet.py
import datetime as dt
import os
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
from django.core.management.base import BaseCommand
from django.utils import timezone
from shop.models import Order
SCHEMA = pa.schema([
("order_id", pa.int64()),
("customer_id", pa.int64()),
("country", pa.string()),
("product", pa.string()),
("currency", pa.string()),
("amount", pa.decimal128(10, 2)),
("created_at", pa.timestamp("us", tz="UTC")),
])
FIELDS = ["id", "customer_id", "customer__country", "product",
"currency", "amount", "created_at"]
class Command(BaseCommand):
help = "Export one day of orders to a Parquet file for offline analytics."
def add_arguments(self, parser):
parser.add_argument("--day", type=dt.date.fromisoformat,
help="UTC day to export (default: yesterday)")
parser.add_argument("--out", type=Path, default=Path("exports/orders"))
parser.add_argument("--database", default="default",
help="Database alias to read from, e.g. a replica")
parser.add_argument("--batch-size", type=int, default=50_000)
def handle(self, *args, day, out, database, batch_size, **options):
day = day or (timezone.now() - dt.timedelta(days=1)).date()
start = dt.datetime.combine(day, dt.time.min, tzinfo=dt.UTC)
end = start + dt.timedelta(days=1)
rows = (
Order.objects.using(database)
.filter(created_at__gte=start, created_at__lt=end)
.order_by("id")
.values_list(*FIELDS)
.iterator(chunk_size=batch_size)
)
target = out / f"day={day.isoformat()}" / "part-0.parquet"
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_suffix(".parquet.tmp")
written = 0
with pq.ParquetWriter(tmp, SCHEMA, compression="zstd") as writer:
batch = []
for row in rows:
batch.append(row)
if len(batch) == batch_size:
writer.write_table(self._to_table(batch))
written += len(batch)
batch.clear()
if batch or written == 0:
writer.write_table(self._to_table(batch))
written += len(batch)
os.replace(tmp, target) # readers never see a half-written file
self.stdout.write(self.style.SUCCESS(f"{written} orders -> {target}"))
@staticmethod
def _to_table(batch):
columns = list(zip(*batch)) if batch else [[] for _ in FIELDS]
return pa.Table.from_arrays(
[pa.array(col, type=f.type) for col, f in zip(columns, SCHEMA)],
schema=SCHEMA,
)
Design decisions worth keeping:
DecimalField values are stored as decimal128(10, 2), so sums stay exact, and timestamps as UTC-aware. Without a schema, PyArrow infers types per batch, and an all-null batch can change the file's schema.os.replace is atomic on one file system, so readers see the old file or the new one.DATABASES and run with --database replica. On PostgreSQL, iterator() uses a server-side cursor; if you connect through a transaction-pooling connection pooler, set DISABLE_SERVER_SIDE_CURSORS = True for that alias. The driver then receives the whole result set at once, so export smaller time windows (an hour instead of a day) to keep memory bounded.python manage.py export_orders_parquet --day 2026-12-01 --database replica
40104 orders -> exports/orders/day=2026-12-01/part-0.parquet
DuckDB reads the result with the partition key as a column, and the decimal type survives the round trip (figures from a test project with 120,000 seeded orders):
import duckdb
con = duckdb.connect()
con.sql("SET TimeZone = 'UTC'")
con.sql("""
CREATE VIEW orders AS
SELECT * FROM read_parquet('exports/orders/*/*.parquet', hive_partitioning = true)
""")
con.sql("""
SELECT day, country, count(*) AS orders, sum(amount) AS revenue
FROM orders
WHERE day >= DATE '2026-12-01'
GROUP BY ALL
ORDER BY day, country
""").show()
┌────────────┬─────────┬────────┬───────────────┐
│ day │ country │ orders │ revenue │
│ date │ varchar │ int64 │ decimal(38,2) │
├────────────┼─────────┼────────┼───────────────┤
│ 2026-12-01 │ BE │ 12938 │ 1958529.58 │
│ ... │ ... │ ... │ ... │
│ 2026-12-02 │ NL │ 12930 │ 1963215.32 │
└────────────┴─────────┴────────┴───────────────┘
For a straight copy of tables, DuckDB's postgres extension can attach PostgreSQL directly and read tables with the binary COPY protocol. Point it at a replica with a read-only role:
import duckdb
con = duckdb.connect()
con.sql("INSTALL postgres")
con.sql("LOAD postgres")
# The password comes from PGPASSWORD or ~/.pgpass, never from the code.
con.sql("""
ATTACH 'host=replica.example.com dbname=myproject user=analytics'
AS pg (TYPE postgres, READ_ONLY)
""")
con.sql("""
COPY (
SELECT o.id AS order_id, o.customer_id, c.country, o.product,
o.currency, o.amount, o.created_at
FROM pg.public.shop_order o
JOIN pg.public.shop_customer c ON c.id = o.customer_id
WHERE o.created_at >= TIMESTAMPTZ '2026-12-01 00:00:00+00'
AND o.created_at < TIMESTAMPTZ '2026-12-02 00:00:00+00'
)
TO 'exports/orders/day=2026-12-01/part-0.parquet'
(FORMAT parquet, COMPRESSION zstd)
""")
INSTALL downloads the extension once; on servers without outbound internet access, install it at build time. This option couples the export to Django's table names (app_model) rather than to your models. Use the management command when you need model logic or anonymisation, and the extension for bulk copies. The file layout is the same either way.
duckdb.connect() without a path creates an in-memory database that disappears with the connection. Pass a file name to persist tables, for example pre-aggregated results that a Django view can read quickly:
import subprocess
import sys
con = duckdb.connect("analytics.duckdb")
con.sql("""
CREATE OR REPLACE TABLE daily_revenue AS
SELECT created_at::DATE AS day, product, sum(amount) AS revenue
FROM 'orders.parquet'
GROUP BY ALL
""")
other_process = """
import duckdb
try:
duckdb.connect("analytics.duckdb", read_only=True)
except duckdb.IOException as exc:
print(str(exc).splitlines()[0])
"""
subprocess.run([sys.executable, "-c", other_process])
IO Error: Cannot open file "...\analytics.duckdb": The process cannot access the file because it is being used by another process.
That output is from Windows, where the full message also names the process that holds the file; the wording differs per operating system. The rules:
con.cursor(); a single connection object must not be shared across threads.SET threads = 4, SET memory_limit = '2GB', and SET temp_directory = '/var/tmp/duckdb' for spilling.For a Django site with several Gunicorn workers this suggests a simple design: a scheduled job, the only writer, builds a new analytics.duckdb or set of Parquet files under a temporary name and swaps it in with an atomic rename; web workers open it with read_only=True and never write. Parquet avoids the locking question entirely. Data the application writes during requests belongs in PostgreSQL.
duckdb to the current major version; 2.0 changed Python result handling.os.replace them into place, and keep exports idempotent per partition.EXPLAIN that file and row-group pruning happen.QUALIFY for "latest per group" and "top N per group" instead of nested subqueries.ASOF LEFT JOIN for point-in-time lookups and compare row counts before and after.PIVOT ... IN (...) for any query whose output schema other code depends on.threads and memory_limit on shared machines.Found a mistake in this tutorial? Let us know and we will fix it.