Pynions

DuckDB in Python: SQL on Parquet, CSV, and DataFrames Without a Server

DuckDB runs SQL on Parquet, CSV, and pandas frames inside Python. Tested DuckDB 2.0.1 code, the 2.0 changes that break 1.x scripts, and when to skip it.

Updated 12 min read
Mallard duck swimming on calm green water

DuckDB is an analytical SQL database that runs inside your Python process, with no server to install. You pip install duckdb, point SQL at a Parquet file, a CSV, or a pandas DataFrame, and get results back as Python objects. The current release is DuckDB 2.0.1, shipped on 20 November 2026.

The Python package pulled 89,895,675 downloads in the last month, as of 30 November 2026. This guide walks through a tested workflow on DuckDB 2.0.1 and Python 3.15.2, then covers the 2.0 changes that break 1.x Python code and the cases where DuckDB is the wrong pick.

Key Takeaways

  • DuckDB is an in-process OLAP database: it runs inside your Python script, reads Parquet, CSV, and JSON files directly, and queries pandas or Polars DataFrames by variable name.
  • Install it with pip install duckdb. DuckDB 2.0 requires Python 3.11 or newer, and free-threaded CPython builds are not supported.
  • DuckDB 2.0 changed the Python client: relations lost fetchone(), a relation runs its query again on every read, and an unfinished execute() result blocks the connection.
  • One process can write to a DuckDB file at a time. For multi-process writes, 2.0 offers the Quack protocol or DuckLake.
  • Database files created by DuckDB 2.0 cannot be opened by DuckDB 1.x unless you create them with storage_compatibility_version set to v1.5.0. Existing 1.x files stay readable.

What Is DuckDB?

DuckDB is a relational database built for analytical queries: aggregations over whole tables, joins between large tables, and scans of columnar files. The DuckDB project describes it as embedded in the host process, with no DBMS server software to install, update, or maintain.

That design borrows from SQLite, which the DuckDB team calls the world's most widely deployed DBMS. DuckDB applies the same embedded, in-process idea to OLAP work. DuckDB has no external dependencies, ships under the MIT License, and its intellectual property is held by the DuckDB Foundation.

DuckDB homepage with the headline Your universal data wrangling tool

Why DuckDB Is Fast

DuckDB uses a columnar-vectorized execution engine. Instead of processing one row at a time, as PostgreSQL, MySQL, and SQLite do, it processes a batch of values (a vector) in one operation. That cuts the CPU cycles spent per value on queries that touch large parts of a dataset.

Storage formats help too. When DuckDB reads a Parquet file, it pushes projections and filters into the scan: it reads only the columns the query needs and can skip parts of the file using zonemaps. Running in-process also removes the client-server hop, which the DuckDB team credits for high-speed data transfer to and from the database.

Why DuckDB Matters in 2027

DuckDB 2.0.0 LTS shipped on 21 October 2026 with close to 20,000 commits since DuckDB 1.5. The DuckDB team calls it its biggest feature release so far: a polished Quack client-server protocol, asynchronous I/O for Parquet and CSV reads, a first-class VARIANT type, triggers, and a new PEG-based SQL parser.

DuckDB 2.0 is a long-term support line with support until at least October 2027. DuckDB 1.4 LTS reached end of community support on 17 November 2026, and the team plans DuckDB 2.1.0 for the first half of 2027.

How DuckDB Works in Python: Install, Query, Persist

Every code block below ran in a clean virtual environment on Python 3.15.2 with duckdb 2.0.1, pandas 3.1.1, polars 2.2.0, and pyarrow 26.0.1. Run the blocks in order from the same folder, since later blocks read the files earlier blocks create.

Install DuckDB 2.0.1

Shell
python -m venv .venv
source .venv/bin/activate
pip install duckdb==2.0.1 pandas==3.1.1 polars==2.2.0 pyarrow==26.0.1
python -c "import duckdb; print(duckdb.__version__)"
Text
2.0.1

On Python 3.10, the same pip install duckdb resolves to a 1.x release, because DuckDB 2.0 needs Python 3.11 or newer.

You only need pandas, Polars, and PyArrow for the DataFrame section. In testing, .pl() failed with ModuleNotFoundError: No module named 'pyarrow' until PyArrow was installed, because DuckDB hands results to Polars through Arrow. The installation page also offers the command-line client with pip install duckdb-cli, or uvx duckdb-cli to run it without installing.

Run Your First Query

Python
import duckdb

duckdb.sql("SELECT 42 AS answer").show()
Text
┌────────┐
│ answer │
│ int32  │
├────────┤
│     42 │
└────────┘

duckdb.sql() runs against an in-memory database stored globally inside the module. It returns a relation, an object you can query further, print, or convert to Python data. For a library or any code other people import, the Python API docs recommend creating your own connection with duckdb.connect() instead of the shared module-level database.

Build a 1 Million Row Test Dataset

You need data to query. Save this as make_data.py. It uses DuckDB's own range() table function to write a 1,000,000-row Parquet file of orders and a 1,000-row CSV of customers.

Python
import duckdb

duckdb.execute("""
    COPY (
        SELECT
            i AS order_id,
            i % 1000 AS customer_id,
            DATE '2026-01-01' + (i % 365)::INTEGER AS order_date,
            ['EU', 'US', 'APAC'][1 + i % 3] AS region,
            (5 + (i * 37 % 1000) / 10)::DECIMAL(10, 2) AS amount
        FROM range(1_000_000) AS t(i)
    ) TO 'orders.parquet'
""")

duckdb.execute("""
    COPY (
        SELECT
            i AS customer_id,
            'customer_' || i AS name,
            ['free', 'pro', 'team'][1 + i % 3] AS plan
        FROM range(1000) AS t(i)
    ) TO 'customers.csv'
""")

print(duckdb.sql("SELECT count(*) FROM 'orders.parquet'").fetchall())
Text
[(1000000,)]

COPY ... TO picks the output format from the file extension. The amounts are DECIMAL(10, 2) on purpose, so sums come back exact instead of as floating-point approximations.

Querying Parquet and CSV Files Directly

DuckDB treats a file path in single quotes as a table. No import step, no CREATE TABLE, and no loading the whole file into memory first.

Aggregate a Parquet File

Python
import duckdb

duckdb.sql("""
    SELECT region, count(*) AS orders, sum(amount) AS revenue
    FROM 'orders.parquet'
    GROUP BY region
    ORDER BY revenue DESC
""").show()
Text
┌─────────┬────────┬───────────────┐
│ region  │ orders │    revenue    │
│ varchar │ int64  │ decimal(38,2) │
├─────────┼────────┼───────────────┤
│ EU      │ 333334 │   18317902.10 │
│ APAC    │ 333333 │   18316665.00 │
│ US      │ 333333 │   18315432.90 │
└─────────┴────────┴───────────────┘

This query touches two of the five columns, and the Parquet reader skips the other three. The same syntax takes globs ('orders/*.parquet') and lists of files through read_parquet(), and the Parquet docs list a filename virtual column that tells you which file each row came from.

Let the CSV Sniffer Read the Schema

CSV files carry no types, so DuckDB guesses them. Its CSV sniffer detects the delimiter, quoting, header, and column types from a sample of 20,480 rows by default. sniff_csv() shows what it decided as a ready-to-paste read_csv() call:

Python
import duckdb

print(duckdb.sql("SELECT Prompt FROM sniff_csv('customers.csv')").fetchall()[0][0])
Text
FROM read_csv('customers.csv', auto_detect=false, delim=',', quote='', escape='', new_line='\n', skip=0, comment='', header=true, columns={'customer_id': 'BIGINT', 'name': 'VARCHAR', 'plan': 'VARCHAR'});

Paste that call into production code when you want the schema fixed instead of re-detected on every run. Now join the CSV to the Parquet file in one query:

Python
import duckdb

duckdb.sql("""
    SELECT c.plan, count(*) AS orders, round(avg(o.amount), 2) AS avg_order
    FROM 'orders.parquet' AS o
    JOIN 'customers.csv' AS c USING (customer_id)
    GROUP BY c.plan
    ORDER BY c.plan
""").show()
Text
┌─────────┬────────┬───────────┐
│  plan   │ orders │ avg_order │
│ varchar │ int64  │  double   │
├─────────┼────────┼───────────┤
│ free    │ 334000 │     58.54 │
│ pro     │ 333000 │      51.3 │
│ team    │ 333000 │      55.0 │
└─────────┴────────┴───────────┘

Write Results Back to Parquet

COPY ... TO with PARTITION_BY writes one folder per value, in the Hive layout (month=1/, month=2/):

Python
import os

import duckdb

duckdb.execute("""
    COPY (SELECT *, month(order_date) AS month FROM 'orders.parquet')
    TO 'orders_by_month' (FORMAT parquet, PARTITION_BY (month))
""")
print(len(os.listdir("orders_by_month")))

print(duckdb.sql("""
    SELECT count(*)
    FROM read_parquet('orders_by_month/*/*.parquet', hive_partitioning = true)
    WHERE month = 3
""").fetchall())
Text
12
[(84940,)]

DuckDB pushes filters on partition keys down to the folder level, so the month = 3 query skips the files in the other 11 folders. For a single output file from Python, a relation also has write_parquet() and write_csv() methods.

DuckDB With pandas and Polars

DuckDB reads pandas DataFrames, Polars DataFrames, and Arrow tables that are in scope by their variable name. The Python API docs note these frames are read-only to DuckDB: you cannot INSERT into or UPDATE them through SQL.

Query a DataFrame by Variable Name

Python
import duckdb
import pandas as pd

signups = pd.DataFrame({"plan": ["free", "pro", "team"], "signups": [1200, 340, 85]})

rel = duckdb.sql("SELECT plan, signups FROM signups WHERE signups > 100 ORDER BY signups DESC")
print(rel.df())
print(rel.pl())
Text
   plan  signups
0  free     1200
1   pro      340
shape: (2, 2)
┌──────┬─────────┐
│ plan ┆ signups │
│ ---  ┆ ---     │
│ str  ┆ i64     │
╞══════╪═════════╡
│ free ┆ 1200    │
│ pro  ┆ 340     │
└──────┴─────────┘

.df() returns a pandas DataFrame and .pl() a Polars DataFrame; .pl(lazy=True) gives a Polars LazyFrame instead. That makes DuckDB a practical SQL layer over an existing pandas codebase: keep the frames, move the heavy joins and group-bys into SQL. If you are weighing a full switch away from pandas, our Polars vs pandas comparison covers where that speedup comes from.

DuckDB vs pandas vs Polars vs SQLite

Tool

Interface

Built for

Reads Parquet and CSV directly

Concurrent writers

DuckDB 2.0.1

SQL plus a Python relational API

Analytical queries (OLAP)

Yes, as tables in SQL

One read-write process in-process; Quack or DuckLake for more

pandas 3.1.1

DataFrame methods

In-memory data manipulation

Through read_parquet() and read_csv() into memory

Not a database

Polars 2.2.0

DataFrame expressions, lazy API

DataFrame pipelines

Yes, including lazy scans

Not a database

SQLite (Python sqlite3)

SQL

Transactional row lookups and writes (OLTP)

No, import first

One writer at a time

Pick DuckDB when the work is SQL-shaped and the data sits in files. Pick Polars when your team thinks in DataFrame expressions.

Keep pandas for small frames and the libraries that expect it, and use SQLite when an app needs many small transactional reads and writes. Our roundup of pandas alternatives compares more options for large datasets.

What DuckDB 2.0 Changed for Python Code

The Python migration guide lists 15 changes for code written against DuckDB 1.x. Four of them hit everyday scripts.

DuckDB documentation page titled Migrating Python Code to DuckDB 2.0

Relations Run Again on Every Read

A relation from duckdb.sql() or con.sql() holds a query, not a result. Building it runs nothing, and the relational API docs say the query "runs again on every read, so each read sees the current data". Call materialize() when you want to compute once and keep the rows:

Python
import duckdb

con = duckdb.connect()
con.execute("CREATE TABLE events (id INTEGER)")
con.execute("INSERT INTO events VALUES (1), (2)")

total = con.sql("SELECT count(*) AS n FROM events")
print(total.fetchall())

con.execute("INSERT INTO events VALUES (3)")
print(total.fetchall())

snapshot = total.materialize()
con.execute("INSERT INTO events VALUES (4)")
print(total.fetchall(), snapshot.fetchall())
Text
[(2,)]
[(3,)]
[(4,)] [(3,)]

The same relation returned 2, then 3, then 4. In a notebook this bites hard: printing a relation runs its query, every time, so an expensive query in a cell you re-display runs again in full.

fetchone() Moved Off Relations

DuckDB 1.x let you call fetchone() and fetchmany() on a relation. In 2.0 those methods are gone from relations, and the error message tells you what to do:

Python
import duckdb

rel = duckdb.sql("SELECT 42 AS answer")
try:
    rel.fetchone()
except AttributeError as err:
    print(err)

print(rel.limit(1).fetchall())
Text
Relations no longer have fetchone(): a relation keeps no result between calls, so every call runs it again. Use rel.limit(1).fetchall() instead
[(42,)]

For a classic cursor loop with fetchone(), create the result with con.execute() instead of con.sql(). To stream an existing relation, the migration guide points to rel.iter_rows() or rel.to_arrow_reader().

An Unfinished execute() Blocks the Connection

execute() results still support fetchone(), with a new catch. In DuckDB 2.0, a partly read result keeps the connection busy, and the next query on it raises ResourceInUseException:

Python
import duckdb

con = duckdb.connect()
first = con.execute("SELECT * FROM range(3)").fetchone()
print(first)

try:
    con.sql("SELECT 1").fetchall()
except duckdb.ResourceInUseException as err:
    print(type(err).__name__)

con.complete()
print(con.sql("SELECT 1 AS ok").fetchall())
Text
(0,)
ResourceInUseException
[(1,)]

Read the result to its end, or call con.complete() or con.abort(), before you run the next query. In 1.x the second query ran, so scripts that peek at one row and move on now fail at the second query.

One Connection per Thread

A DuckDB 2.0 connection runs one call at a time, and a call from a second thread raises ResourceInUseException instead of waiting. Give each thread its own cursor, which the Python API docs describe as a new connection to the same database:

Python
import threading

import duckdb

con = duckdb.connect()
con.execute("CREATE TABLE numbers AS SELECT range AS n FROM range(1000)")


def count_even(cursor, results):
    results.append(cursor.sql("SELECT count(*) FROM numbers WHERE n % 2 = 0").fetchall())


results = []
threads = [threading.Thread(target=count_even, args=(con.cursor(), results)) for _ in range(4)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
print(results)
Text
[[(500,)], [(500,)], [(500,)], [(500,)]]

duckdb.sql() and the other module-level functions share one default connection, so the same rule applies to them inside threads.

New Database Files Are Unreadable by DuckDB 1.x

Persist data by passing a file name to duckdb.connect(). Open the file with read_only=True when a process only reads:

Python
import duckdb

with duckdb.connect("shop.duckdb") as con:
    con.execute("CREATE TABLE orders AS SELECT * FROM 'orders.parquet'")
    print(con.sql("SELECT count(*) FROM orders").fetchall())

with duckdb.connect("shop.duckdb", read_only=True) as con:
    print(con.sql("SELECT max(order_date) FROM orders").fetchall())
Text
[(1000000,)]
[(datetime.date(2026, 12, 31),)]

A database file that DuckDB 2.0 creates in its default format cannot be opened by DuckDB 1.x. Opening shop.duckdb with duckdb 1.5.6 failed with this error:

Text
IO Error: Trying to read a database file with version number 69, but we can only read versions between 64 and 68.

If a 1.5 process still shares the file, write it in the older format:

Python
import duckdb

with duckdb.connect("shared.duckdb", config={"storage_compatibility_version": "v1.5.0"}) as con:
    con.execute("CREATE TABLE t AS SELECT 1 AS x")
    print(con.sql("SELECT * FROM t").fetchall())
Text
[(1,)]

duckdb 1.5.6 opened shared.duckdb and returned the same row. Existing files are safer than some upgrade posts claim: the 2.0.0 announcement says DuckDB 2.0 can read and write your existing database files and they remain readable by older versions. A file created by duckdb 1.5.6, then written to by 2.0.1, still opened in 1.5.6 with the new rows and table.

Change

DuckDB 1.x

DuckDB 2.0

Python version

3.10 or newer on 1.5.6, 3.9 or newer on 1.4.4

3.11 or newer; free-threaded builds not supported

rel.fetchone(), rel.fetchmany()

Worked on relations

Removed; use con.execute() or rel.limit(1).fetchall()

Reading a relation twice

Kept the first result

Runs the query again; use materialize()

Partly read execute() result

Other queries still ran

Next query raises ResourceInUseException

con.execute(q).pl() and .fetch_arrow_table()

Worked

Removed from execute() results; use con.sql(q).pl()

Arrow batch size

1,000,000 rows

131,072 rows

New database files

Readable by 1.x

Unreadable by 1.x unless written with v1.5.0 compatibility

When DuckDB Is the Wrong Tool

DuckDB's concurrency docs set the main limit. In in-process mode, one process can read and write a database file, or several processes can open it read-only. Inside that one writer process, multiple threads can write, and appends never conflict.

That rules out the classic web-app pattern of several workers writing to one file. On r/dataengineering, u/pra__bhu summed up the practitioner view in a 2026 thread: "anything with multiple users writing data simultaneously is a no-go. reads scale fine though". DuckDB 2.0 adds two ways around it: the Quack protocol turns a DuckDB process into a server other processes connect to, and DuckLake 1.1 coordinates DuckDB instances through a PostgreSQL catalog.

Use Something Else When

  • Your app does many small transactional reads and writes per second from several processes. SQLite's own usage guide points apps that need high write concurrency to a client/server database.
  • Your data needs a cluster. DuckDB runs on one machine, though it does process larger-than-memory workloads by spilling to disk.
  • You run free-threaded CPython. DuckDB 2.0 does not support those builds.

DuckDB Fits When

The same r/dataengineering thread shows where teams land. Its top answer, from u/ambidextrousalpaca, describes replacing new PySpark pipelines with DuckDB driven from Python: "We observed that the actual data loads we were processing were never big enough to necessitate a Spark cluster." Their team's test on their own data ran "about 10 times faster and used half the resources", a single-team result, not a benchmark.

Other answers in that thread use DuckDB to take small queries off Snowflake and to ship a prebuilt .duckdb file inside web app containers for read-only analytics. That read-heavy, file-centric shape is DuckDB's sweet spot.

Common DuckDB Mistakes to Avoid

Calling fetchone() on a Relation

Code written for DuckDB 1.x calls duckdb.sql(q).fetchone() and fails on 2.0 with AttributeError. Use duckdb.execute(q).fetchone() for cursor-style reads, or rel.limit(1).fetchall().

Re-displaying an Expensive Relation

Every print(rel), rel.show(), and fetch runs the full query again in DuckDB 2.0. Assign rel.materialize() or a DataFrame from rel.df() once and reuse it.

Peeking at One Row and Moving On

con.execute(q).fetchone() leaves the rest of the result open, and the next query on that connection raises ResourceInUseException. Fetch everything, or call con.complete() first.

Sharing One Connection Across Threads

A DuckDB 2.0 connection refuses a second concurrent call instead of queueing it. Pass con.cursor() to each thread.

Creating Shared Files on 2.0 While Readers Run 1.x

A .duckdb file that DuckDB 2.0 creates in its default format cannot be opened by any 1.x reader. Upgrade all processes together, or create new files with storage_compatibility_version set to v1.5.0 until the last 1.x process is gone.

Frequently Asked Questions

Sources

Related Articles