Sub topic 6
DuckDB: an embedded SQL engine for analytics
This chapter assumes you know basic Python and SQL (SELECT, WHERE, GROUP BY, JOIN). It also assumes you have loaded a dataset with pandas before. You should know what a Parquet file is from the earlier chapter on columnar formats.
What DuckDB is
DuckDB is an analytical database that runs inside your Python process. There is no server to install, no port to open, and no cluster to manage. You import it like any other library and send it SQL.
"Embedded" means the engine shares your process and your memory. "Analytical" means it is built for queries that scan many rows and aggregate a few columns, such as sums, averages, and joins over large tables. It is not built for many small concurrent writes, the way a transactional database is.
Under the hood, DuckDB stores and processes data by column. It runs queries in a vectorized way, handling batches of values at a time. It can use all your CPU cores.
Querying files directly
You do not have to load data before you query it. DuckDB can read Parquet and CSV files in place and only reads the columns and row groups the query needs.
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)duckdb.sql returns a lazy relation. The query runs when you ask for a result, here with .df(), which gives a pandas DataFrame.
Querying DataFrames by name
DuckDB can see DataFrames that exist in your Python scope. If a variable holds a pandas or Polars DataFrame, you can use its name as a table.
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. This pattern lets you keep pandas code where it works well and hand the heavy aggregation to DuckDB.
Memory and larger-than-memory data
DuckDB can process some queries on data larger than RAM. When operators such as sorts, joins, and aggregations exceed the memory limit, they can spill intermediate data to a temporary directory on disk. You can set the limit and the spill location:
import duckdb
con = duckdb.connect()
con.sql("SET memory_limit = '4GB'")
con.sql("SET temp_directory = '/tmp/duckdb_spill'")Spilling is slower than staying in memory, and not every operation supports it. Test your own query before you rely on it.
Strengths
- SQL is the interface, so analysts who know SQL start quickly.
- Direct queries over Parquet and CSV avoid a separate load step.
- A single process on one machine means no cluster operations.
- Zero-copy-style exchange with Arrow-backed data keeps conversions cheap.
Limits
- It runs on one machine. If the work needs many machines, you need something like Spark.
- Complex row-by-row Python logic is awkward. You can register Python functions, but this is slower than built-in SQL.
- It is not designed for many concurrent writers. A database file allows one writing process at a time.
- Transformations that read better as chained DataFrame methods may feel unnatural in SQL strings, and errors in those strings appear only at run time.
Common mistakes
- Treating the result of
duckdb.sqlas a finished DataFrame. It is a relation, so call.df(),.pl(), or.fetchall(). - Querying a DataFrame whose variable name is not in scope, which raises a catalog error.
- Skipping
memory_limiton a shared machine, which lets DuckDB use most of the available RAM.
Exercise
You have a 40 GB Parquet file and a laptop with 16 GB of RAM. You need a grouped sum by region. Give one reason DuckDB is a reasonable first try, and one thing you should check before trusting it.
Show answer
DuckDB scans only the needed columns from the Parquet file and can spill large aggregation state to disk, so it may finish without loading everything into memory. Before trusting it, set a memorylimit and a tempdirectory, run the real query, and confirm it completes within acceptable time and disk space.