Python & BI

DuckDB with SQLAlchemy: duckdb-engine or duckdb-sqlalchemy?

Updated The Thunderduck team9 min read

Three drivers put DuckDB behind SQLAlchemy today, and they are not interchangeable. Two run DuckDB inside your Python process: duckdb-engine, the original, and duckdb-sqlalchemy, a fork that is still being released. The third, thunderduck-sqlalchemy, runs the query on DuckDB somewhere else, against data that is not on your machine.

This post covers all three: which local driver to install, what we measured on SQLAlchemy 2.1 and DuckDB 2.0, pandas and Polars examples that run as written, and where a remote engine takes over.

the short version
# pip install duckdb-sqlalchemy pandas
from sqlalchemy import create_engine
import pandas as pd

engine = create_engine("duckdb:///shop.duckdb")   # or duckdb:///:memory:
df = pd.read_sql("SELECT 42 AS answer", engine)

duckdb-engine, duckdb-sqlalchemy or thunderduck-sqlalchemy?

duckdb-engineduckdb-sqlalchemythunderduck-sqlalchemy
DuckDB runsIn your Python processIn your Python processOn a Thunderduck worker
URL schemeduckdb://duckdb://thunderduck://
Latest release0.17.0, March 20252.0.0.2, November 20261.0.2, November 2026
SQLAlchemyDeclares 1.3.22 and later2.0 and later1.4 and 2.x
Python3.9 and later3.10 and later3.10 and later
WritesYesYesNo, read-only
Versions and requirements as published on PyPI on 26 November 2026.

duckdb-engine (the module is duckdb_engine) is the driver most tutorials name. duckdb-sqlalchemy is a fork of it, started in late 2025, that also targets MotherDuck. Both register the same duckdb:// dialect name, so the connection URL and your code stay the same whichever you install. Install one of them: with both in the environment, create_engine picked duckdb_engine in our run, and nothing tells you which one you got.

What we measured on SQLAlchemy 2.1 and DuckDB 2.0

A fresh pip install today resolves SQLAlchemy 2.1.9 and DuckDB 2.0.1. We ran the same script against both local drivers on that stack, with Python 3.15, pandas 3.1 and Polars 2.2.

duckdb-engine 0.17.0duckdb-sqlalchemy 2.0.0.2
SQL through text(), pandas read_sql, bound parametersWorksWorks
Polars read_databaseWorks with a connection, fails when given the engineWorks with either
inspect(engine).get_columns()Fails on SQLAlchemy 2.1, works on 2.0Works
Table(..., autoload_with=engine)Fails on 2.1 and on 2.0Works
Integer primary key without a SequenceFailsWorks
DataFrame.to_sql, 100,000 rows4.8 s0.45 s

The failures have one cause. duckdb-engine is built on SQLAlchemy's PostgreSQL dialect, and newer SQLAlchemy versions reflect a table with queries against PostgreSQL system catalogs that DuckDB does not have. On 2.1 the error is Referenced table "pg_catalog.pg_collation" not found. On 2.0, reading the columns works and loading a whole Table fails with Type with name REGCLASS does not exist. A plain Integer primary key becomes SERIAL, another PostgreSQL type DuckDB rejects; the fix there is to give the column a Sequence. On SQLAlchemy 1.4, which Superset 6.1 pins, duckdb-engine's reflection worked.

  • For new code on SQLAlchemy 2.x, install duckdb-sqlalchemy. Everything in our script passed, on SQLAlchemy 2.1 with DuckDB 2.0.1 and on 2.0 with DuckDB 1.5.6.
  • Existing duckdb-engine code that only sends SQL strings keeps working. It breaks where SQLAlchemy has to describe an existing table, which is what reflection, Alembic autogenerate and schema browsers do.
  • Use thunderduck-sqlalchemy when the data is not on your machine. That is the second half of this post.

Connect to a local DuckDB

connect.py — one engine, reused below
from sqlalchemy import create_engine, text

engine = create_engine("duckdb:///shop.duckdb")       # a file next to your script
# create_engine("duckdb:////data/shop.duckdb")        # an absolute path: four slashes
# create_engine("duckdb:///:memory:")                 # nothing on disk

# A table to work with: 1 million orders
with engine.begin() as conn:
    conn.execute(text("""
        CREATE OR REPLACE TABLE orders AS
        SELECT range                                         AS order_id,
               (range // 330) % 1000                         AS customer_id,
               ((range * 37) % 20000 / 100.0)::DECIMAL(10,2) AS amount,
               DATE '2026-01-01' + (range % 330)::INT        AS order_date
        FROM range(1_000_000)
    """))

DuckDB settings go in connect_args. read_only lets several processes open the same file at once, and config takes any DuckDB setting:

settings — read-only, with a memory limit
reader = create_engine(
    "duckdb:///shop.duckdb",
    connect_args={
        "read_only": True,
        "config": {"memory_limit": "500MB", "threads": 2},
    },
)

pandas: read_sql, and a faster way than to_sql

pandas — aggregate in DuckDB, get a small frame back
import pandas as pd

monthly = pd.read_sql(
    """
    SELECT date_trunc('month', order_date) AS month,
           count(*)                        AS orders,
           sum(amount)                     AS revenue
    FROM orders
    GROUP BY 1
    ORDER BY 1
    """,
    engine,
)

# Bound parameters, not f-strings
one_customer = pd.read_sql(
    text(
        "SELECT count(*) AS orders, sum(amount) AS revenue "
        "FROM orders WHERE customer_id = :cid AND order_date >= :since"
    ),
    engine,
    params={"cid": 7, "since": "2026-06-01"},
)

The first frame has 11 rows; November holds 78,780 orders and 7,877,382.90 in revenue. The second returns 716 orders and 66,946.00. Two type details: pandas turns the DECIMAL column into float64 and leaves the DATE column as object, so cast in SQL when the exact type matters.

Loading a DataFrame is where the drivers differ most. DataFrame.to_sql sends INSERT statements. For 100,000 rows that took 4.8 seconds on duckdb-engine and 0.45 seconds on duckdb-sqlalchemy, and method="multi" made it slower on both, about 8.5 seconds. DuckDB can read a DataFrame in place instead, which took about 30 milliseconds on either driver:

pandas — load a DataFrame without INSERTs
df = pd.DataFrame({
    "id": range(100_000),
    "name": [f"c{i}" for i in range(100_000)],
    "score": [i * 0.5 for i in range(100_000)],
})

with engine.begin() as conn:
    conn.execute(text("register(:name, :df)"), {"name": "df_view", "df": df})
    conn.execute(text("CREATE OR REPLACE TABLE customers AS SELECT * FROM df_view"))

Polars and Parquet through the same engine

polars — read_database takes a SQLAlchemy connection
import polars as pl

with engine.connect() as conn:
    top = pl.read_database(
        query="""
            SELECT customer_id, sum(amount) AS revenue
            FROM orders
            GROUP BY 1
            ORDER BY 2 DESC
            LIMIT 3
        """,
        connection=conn,
    )

# Files are tables: no load step
with engine.connect() as conn:
    conn.execute(text("COPY orders TO 'orders.parquet' (FORMAT parquet)"))

november = pd.read_sql(
    "SELECT count(*) AS orders FROM 'orders.parquet' "
    "WHERE order_date >= DATE '2026-11-01'",
    engine,
)

Polars keeps the DECIMAL type: the top three customers are 8, 17 and 26, with 140,917.80, 140,665.80 and 140,413.80. Pass read_database a connection, as above. Passing the engine itself fails on duckdb-engine. The Parquet query counts 78,780 November orders straight from the file.

Three things that bite

  • One writing process per file. While one process has shop.duckdb open for writing, a second one gets IO Error: Could not set lock on file ... Conflicting lock is held, even if it only wants to read. Several processes can open the file together when every one of them passes read_only. Inside one process, a read-write engine and a read-only engine on the same file fail too, with Can't open a connection to same database file with a different configuration.
  • An in-memory database dies with the process. With duckdb:///:memory: the tables exist only inside that Python process. Use a file when a second tool has to see the data, or when you want it back tomorrow.
  • A local engine reads what your machine can reach. Buckets, production databases and their credentials all have to be on the laptop, or the data has to be copied there first.

When the data is not on your laptop: thunderduck-sqlalchemy

A data scientist's first hour on a new dataset is rarely spent on the data. It goes on access: an extract request, a CSV that is already a week stale, a bucket path someone pastes in Slack, a local copy that quietly becomes the version of record. The analysis is the easy part. Getting to a governed, current table from a Python process is the part that takes a week.

thunderduck-sqlalchemy removes that hour. It is a SQLAlchemy dialect and PEP 249 driver for Thunderduck, published on PyPI, so every tool in the Python data stack that already speaks SQLAlchemy can read your lakehouse directly — pandas, Polars, PyTorch, Jupyter, Streamlit, Airflow, Dagster, Great Expectations. And because Apache Superset speaks SQLAlchemy too, the same connection string turns Thunderduck into the engine behind a full BI tool.

No extract, no local copy, no second version of the truth. The notebook queries the same catalog the dashboard does.

The code looks almost the same as the local version. What is on the other end of the URL is different: the same DuckDB engine, run on a remote worker sized for each query, against your company's catalogs. Credentials stay on the server, access follows your role, and every query is priced before it runs. You can use both in one notebook: a local driver for a scratch file, thunderduck-sqlalchemy for the shared catalogs.

Connecting, pandas and Polars bulk results, and the behaviour worth knowing for thunderduck-sqlalchemy are in the docs: https://docs.thunderduck.ai/clients/sqlalchemy/

Install thunderduck-sqlalchemy and connect

It installs on Python 3.10+ and works with both SQLAlchemy 1.4 and 2.x — deliberately, because Superset still pins 1.4 while your notebook environment is almost certainly on 2.x. Create an API token in the console under Settings → API Tokens (it starts with tdk_ and is shown once), and that is the whole setup:

install
pip install thunderduck-sqlalchemy
engine.py — one URL, reused everywhere below
import os

from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool

# Keep the token in the environment, never in the notebook.
engine = create_engine(
    f"thunderduck://:{os.environ['TD_TOKEN']}@api.thunderduck.ai/",
    poolclass=NullPool,   # a connection holds no server-side state, so pooling buys nothing
)

There is no driver to compile, no JVM, no ODBC manager, no tunnel to a warehouse VPC. Statements go over HTTPS to Thunderduck's API, run as isolated jobs against your data where it already lives, and page back as rows.

What a data scientist actually gets out of it

  • No extract step. You read the table, not last Tuesday's copy of it. Federated queries mean a single SELECT can join Iceberg or Parquet in your bucket with a live PostgreSQL or MySQL replica — the join a notebook usually fakes with two DataFrames and a merge.
  • Push the heavy lifting down. Filtering, joining and aggregating happen on the engine, next to the data; only the result travels. A GROUP BY that scans 200 GB returns a few thousand rows to your laptop.
  • The governance is the connection, not a policy document. Your token is scoped and revocable, every query lands in query history with its plan, timings and cost, and an over-budget scan is checked before it runs rather than billed after.
  • Reflection is free. Browsing schemas, tables and columns reads Thunderduck's catalog API rather than issuing SQL, so inspect(engine) and DataFrame-shaped discovery cost nothing and start no compute.
  • Cancel means cancel. Stop a runaway query from Superset or your own code and the underlying job is genuinely killed — you stop paying for it at that moment.
  • The same catalog your agents see. An MCP client and your notebook resolve the same tables under the same guardrails, so a model's answer and an analyst's answer come from the same place.

One naming detail worth knowing up front: Thunderduck names tables catalog.schema.table (flat-file catalogs) or catalog.table (Iceberg/Nessie catalogs), while SQLAlchemy only models two levels. So the whole dotted prefix is the schema — Table('lego_sets', md, schema='lego.public') for a three-level name, schema='thunder_duck_demo' for a two-level one.

pip install, one URL, and the notebook is reading the same governed table the dashboard does.

pandas on Thunderduck: the same read_sql

pandas has spoken SQLAlchemy for years, so there is no Thunderduck-specific API to learn. Hand it the engine and a query:

pandas — aggregate on the engine, plot locally
import pandas as pd

REVENUE_BY_SEGMENT = """
SELECT
  c.segment,
  date_trunc('month', o.order_ts) AS month,
  count(*)                        AS orders,
  sum(o.amount)                   AS revenue
FROM lake.raw.orders             AS o    -- Parquet in S3
JOIN pg_replica.public.customers AS c    -- live PostgreSQL replica
  ON c.id = o.customer_id
WHERE o.order_ts >= DATE '2026-01-01'
GROUP BY 1, 2
ORDER BY 1, 2
"""

df = pd.read_sql(REVENUE_BY_SEGMENT, engine)

df.pivot(index="month", columns="segment", values="revenue").plot(
    title="Monthly revenue by segment",
)

That query scans the lake and the replica together and returns a few dozen rows. The equivalent notebook without Thunderduck is an export job, a CSV, a psycopg2 connection and a merge you have to keep in sync with two schemas.

Parameters are supported, and you should use them: the driver renders bound values into SQL with strict escaping and refuses types it does not recognise, which is exactly the safety net string formatting does not give you.

pandas — bound parameters, not f-strings
from sqlalchemy import text

df = pd.read_sql(
    text(
        "SELECT order_id, amount, order_ts "
        "FROM lake.raw.orders "
        "WHERE segment = :segment AND order_ts >= :since "
        "ORDER BY order_ts DESC LIMIT 1000"
    ),
    engine,
    params={"segment": segment_from_user_input, "since": "2026-06-01"},
)

Polars on Thunderduck: the same query, a faster frame

If your stack has moved to Polars, nothing changes on the Thunderduck side — read_database takes a SQLAlchemy connection, so the engine object above is all it needs:

polars — read_database over the same engine
import polars as pl

with engine.connect() as conn:
    df = pl.read_database(query=REVENUE_BY_SEGMENT, connection=conn)

top = (
    df.group_by("segment")
      .agg(pl.col("revenue").sum().alias("revenue"))
      .sort("revenue", descending=True)
)
print(top)

The division of labour is the useful part. Thunderduck does the distributed, expensive half — scanning object storage, joining across systems, aggregating — and Polars does the fast in-memory half on a result set that now fits comfortably in RAM. Neither tool is being asked to do the thing it is bad at.

What to know before you rely on it

  • Expect seconds before the first row. Every statement runs as an isolated job, so this is built for analytics, not for a tight loop that fetches a row at a time.
  • Result sets are row-capped. A page has a ceiling and so does a stored result, so aggregate and filter in SQL. When you do need every row, fetch_dataframe in the same package downloads the full stored result as Parquet instead of paging it.
  • The driver is read-only. No DML, no DDL, no transactions; commit() and rollback() are no-ops. Writes belong in a scheduled job or a dbt model.

Where to go next

The package is on PyPI as thunderduck-sqlalchemy. If you are wiring it into something we have not tried yet, such as Dagster or a feature store, tell us what broke and we will fix it.

Connect your data and ask it something.

Credentials to AI-queryable in about five minutes. No pipelines, no data movement.