Sub topic 6
DuckDB: an embedded SQL engine for analytics
This chapter assumes you can write basic SQL (SELECT, WHERE, GROUP BY, JOIN), have loaded data with pandas, and know the eager and lazy execution models and the Parquet format from earlier chapters. By the end, you should know what DuckDB is, how it runs a query, where it is strong, and where it stops being the right tool.
What DuckDB is
DuckDB is an analytical database that runs inside your Python process. It is not a server. You install it with pip install duckdb, import it, and run SQL. There is nothing to start, no port to open, and no login.
Two terms matter here:
- Embedded means the database engine is a library linked into your program, in the way SQLite is. Your code and the engine share one process and one memory space.
- OLAP (online analytical processing) means workloads that scan many rows and compute summaries, such as "total revenue per region". This is the opposite of OLTP, where you read and write single rows, such as "update this customer's address".
DuckDB is built for OLAP on a single machine. It stores and processes data in columns, runs queries in a vectorized way (it handles batches of values at a time instead of one row at a time), and uses all CPU cores by default.
Running a query
The shortest path is duckdb.sql(). It runs SQL and returns a lazy relation object. The query runs when you ask for a result, for example with .df(), .pl(), .fetchall(), or .show().
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)The string 'sales.parquet' in the FROM clause is a file path. DuckDB reads the Parquet file directly, with no load step and no table definition. It also accepts CSV and JSON files, and glob patterns such as 'data/*.parquet' to read many files as one table.
Each DuckDB query goes through the same stages as a lazy engine.
The optimizer applies the techniques from the lazy-evaluation chapter. It pushes filters down to the file scan, reads only the columns the query names, and uses Parquet row-group statistics (minimum and maximum values stored per chunk) to skip chunks that cannot match.
In-memory and persistent databases
duckdb.sql() uses a default in-memory database. Its tables disappear when the process ends. To keep tables, open a database file with duckdb.connect().
import duckdb
con = duckdb.connect("analytics.duckdb")
con.execute(
"CREATE OR REPLACE TABLE sales AS "
"SELECT * FROM 'sales.parquet'"
)
rows = con.execute(
"SELECT region, count(*) AS n FROM sales GROUP BY region ORDER BY n DESC"
).fetchall()
print(rows)
con.close()The .duckdb file is DuckDB's own columnar format. It is compressed and supports transactions. Only one process can open it for writing at a time. Several processes can open it read-only. This is a real limit if you expect many concurrent writers, which is the main reason DuckDB does not replace a server database such as PostgreSQL.
Use a connection (con) instead of the module-level functions when you want a persistent file, separate settings, or several isolated databases in one program.
Querying DataFrames in place
DuckDB can see Python variables. If a pandas DataFrame, a Polars DataFrame, or an Arrow table is in scope, you can use its variable name as a table name. This is called a replacement scan.
import duckdb
import pandas as pd
pdf = pd.DataFrame({"region": ["eu", "us", "eu"], "revenue": [10, 20, 5]})
plf = duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM pdf GROUP BY region"
).pl()
back_to_pandas = plf.to_pandas()
print(back_to_pandas)The .pl() and .to_pandas() conversions need pyarrow installed. DuckDB reads Arrow-based data without copying it first, and pandas data can often be read with little copying too. This makes DuckDB a convenient SQL layer over data you already hold in another library. The interoperability chapter covers the conversions in more detail.
A common mistake is a name collision. If a DataFrame variable has the same name as a table in your connection, the table is used first, and you get data you did not expect. Use distinct names.
Larger-than-memory work
DuckDB does not need the whole dataset in RAM. Because it scans Parquet in chunks and streams them through the operators, a query such as a filtered sum can process a file much bigger than memory. Operators that must hold state, such as large joins, sorts, and group-bys with many distinct keys, can spill intermediate data to disk when they exceed a memory limit.
You control this with two settings:
import duckdb
con = duckdb.connect()
con.execute("SET memory_limit = '4GB'")
con.execute("SET temp_directory = '/tmp/duckdb_spill'")
con.execute("SET threads = 4")
total = con.execute(
"SELECT sum(revenue) FROM 'sales.parquet'"
).fetchone()
print(total)memory_limit caps the memory the engine uses. temp_directory is where spill files go. threads limits CPU use, which matters on a shared machine.
Strengths
- SQL as the interface. Analysts who know SQL can work at once, and complex logic such as window functions,
QUALIFY,PIVOT, and common table expressions is concise. - Zero setup. It is one dependency with no cluster and no service to run, so it works the same on a laptop, in a CI job, and in a container.
- Fast scans and aggregations. Columnar storage, vectorization, and multi-core execution suit group-bys and joins over wide tables.
- Direct file access. It queries Parquet, CSV, and JSON in place, including files on object storage such as S3 when the
httpfsextension is loaded. - Good fit with other tools. It reads and writes pandas, Polars, and Arrow, so it can sit in the middle of a mixed pipeline.
Limits and gotchas
- Single node. DuckDB uses one machine. If the data and the work do not fit on the largest machine you can reasonably get, you need a distributed engine such as Spark.
- Limited write concurrency. One writer process per database file. It is not a multi-user transactional server.
- SQL is the main style. DuckDB has a Python relational API, but most code is SQL strings. Strings get no editor checks, so typos in column names show up at run time. Building SQL from user input with string formatting also invites injection. Use parameters:
import duckdb
min_revenue = 100
result = duckdb.execute(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' WHERE revenue > ? GROUP BY region",
[min_revenue],
).df()
print(result)- Not a streaming system. It processes data at rest. For continuous event streams you need a different tool.
- Python UDFs are slow. A Python function called per row loses the vectorized speed. Prefer built-in SQL functions.
- Row order is not guaranteed without
ORDER BY, as in any SQL engine. Parallel execution can return groups in different orders between runs. - Format versions. Older DuckDB versions had storage-format changes between releases. For long-term storage of shared data, Parquet is the safer interchange format than a
.duckdbfile.
How DuckDB compares to the others
| Aspect | pandas | Polars | DuckDB | Spark |
|---|---|---|---|---|
| Main interface | DataFrame methods | DataFrame expressions | SQL | DataFrame and SQL |
| Execution | Eager | Eager or lazy | Lazy plan, optimized | Lazy plan, distributed |
| Parallelism | Mostly one core | All cores | All cores | Many machines |
| Beyond RAM | No | Partly, via streaming | Yes, with spilling | Yes |
| Setup | `pip install` | `pip install` | `pip install` | Cluster or local session |
Choose DuckDB when your team thinks in SQL, the data fits on one machine (in memory or on local disk), and you want fast analytics without running infrastructure. It is also a good choice when your data already sits in Parquet and you want to query it without a loading step. Consider another tool when you need multi-machine scale, heavy row-by-row Python logic, or many concurrent writers.
Exercise
You have a 40 GB set of Parquet files on a laptop with 16 GB of RAM. You need the total revenue per region for rows where revenue is above zero. Explain why DuckDB can do this, which setting you would set to keep memory use under control, and one mistake that could still cause an out-of-memory failure.
Show answer
DuckDB scans Parquet in chunks, reads only the region and revenue columns, pushes the revenue > 0 filter into the scan, and keeps only a small running aggregate per region, so it never needs all 40 GB in RAM. Set memory_limit (for example SET memory_limit = '10GB') and point temp_directory at a disk with free space so large operators can spill. A mistake that could still fail is running SELECT * and calling .df(), which copies a huge result into pandas memory. Aggregate in SQL first so only a few rows come back.
Exercise
A colleague writes duckdb.sql(f"SELECT * FROM 'sales.parquet' WHERE region = '{user_input}'"). What is the risk, and how do you fix it?
Show answer
Building SQL with string formatting lets a crafted user_input change the query (SQL injection). Pass the value as a parameter instead: duckdb.execute("SELECT * FROM 'sales.parquet' WHERE region = ?", [user_input]).