Getting started with DuckDB in Python

DuckDB is an in-process analytical database that runs fast SQL over tables, local files and DataFrames without a separate server. Each step below was run in a clean environment, and the output shown is exactly what it printed.

Database profile: DuckDB (license, deployment options, alternatives and benchmarks).

Prerequisites

Steps

  1. Install the DuckDB Python package

    DuckDB runs inside your process, so installing the Python package is all you need; there is no server to configure. Pinning the version keeps results reproducible.

    bash
    pip install duckdb==2.0.1
    python3 -c "import duckdb; print(duckdb.__version__)"
    Expected output
    2.0.1
  2. Connect and create a table

    Passing a file name creates a persistent database file; calling duckdb.connect() with no argument gives you an in-memory database instead.

    python
    import duckdb
    
    con = duckdb.connect("analytics.duckdb")
    con.sql("""
        CREATE TABLE events (
            event_id   INTEGER PRIMARY KEY,
            user_id    INTEGER,
            event_type VARCHAR,
            amount     DECIMAL(10, 2),
            ts         TIMESTAMP
        )
    """)
    con.sql("SHOW TABLES").show()
    Expected output
    ┌─────────┐
    │  name   │
    │ varchar │
    ├─────────┤
    │ events  │
    └─────────┘
  3. Insert rows

    Rows can be inserted with plain SQL or with parameter placeholders from Python. For large volumes, loading from files (shown later) is much faster than row-by-row inserts. In DuckDB 2.0 a relation returned by con.sql() has no fetchone(), so read results with fetchall().

    python
    con.sql("""
        INSERT INTO events VALUES
            (1, 10, 'signup',   NULL,  '2026-11-01 09:00'),
            (2, 10, 'purchase', 19.99, '2026-11-01 09:05'),
            (3, 11, 'signup',   NULL,  '2026-11-02 14:30'),
            (4, 11, 'purchase', 5.00,  '2026-11-03 08:10'),
            (5, 10, 'purchase', 42.50, '2026-11-04 19:45')
    """)
    con.execute("INSERT INTO events VALUES (?, ?, ?, ?, ?)",
                [6, 12, "signup", None, "2026-11-05 11:00"])
    print(con.sql("SELECT count(*) AS n FROM events").fetchall())
    Expected output
    [(6,)]
  4. Run an analytical query

    DuckDB is built for aggregations over many rows. GROUP BY ALL groups by every non-aggregated column, which saves repeating the column list.

    python
    con.sql("""
        SELECT user_id,
               count(*) FILTER (WHERE event_type = 'purchase') AS purchases,
               sum(amount) AS revenue
        FROM events
        GROUP BY ALL
        ORDER BY revenue DESC NULLS LAST
    """).show()
    Expected output
    ┌─────────┬───────────┬───────────────┐
    │ user_id │ purchases │    revenue    │
    │  int32  │   int64   │ decimal(38,2) │
    ├─────────┼───────────┼───────────────┤
    │      10 │         2 │         62.49 │
    │      11 │         1 │          5.00 │
    │      12 │         0 │          NULL │
    └─────────┴───────────┴───────────────┘
  5. Query a CSV file directly

    DuckDB can treat a CSV file like a table and detects the column types automatically. You can query it in place or load it into a table with CREATE TABLE ... AS.

    python
    with open("products.csv", "w") as f:
        f.write("sku,name,category,price\n"
                "A1,Notebook,stationery,3.50\n"
                "A2,Pen,stationery,1.20\n"
                "B1,Headphones,audio,59.00\n"
                "B2,Speaker,audio,89.90\n")
    
    con.sql("SELECT category, avg(price) AS avg_price FROM 'products.csv' GROUP BY category ORDER BY category").show()
    con.sql("CREATE TABLE products AS SELECT * FROM read_csv('products.csv')")
    con.sql("DESCRIBE products").show()
    Expected output
    ┌────────────┬───────────┐
    │  category  │ avg_price │
    │  varchar   │  double   │
    ├────────────┼───────────┤
    │ audio      │     74.45 │
    │ stationery │      2.35 │
    └────────────┴───────────┘
    
    ┌─────────────┬─────────────┬─────────┬─────────┬─────────┬─────────┐
    │ column_name │ column_type │  null   │   key   │ default │  extra  │
    │   varchar   │   varchar   │ varchar │ varchar │ varchar │ varchar │
    ├─────────────┼─────────────┼─────────┼─────────┼─────────┼─────────┤
    │ sku         │ VARCHAR     │ YES     │ NULL    │ NULL    │ NULL    │
    │ name        │ VARCHAR     │ YES     │ NULL    │ NULL    │ NULL    │
    │ category    │ VARCHAR     │ YES     │ NULL    │ NULL    │ NULL    │
    │ price       │ DOUBLE      │ YES     │ NULL    │ NULL    │ NULL    │
    └─────────────┴─────────────┴─────────┴─────────┴─────────┴─────────┘
  6. Export to Parquet and query it

    COPY ... TO writes a compressed, columnar Parquet file. Reading it back only touches the columns a query asks for, which is why Parquet is the usual format for analytics.

    python
    con.sql("COPY events TO 'events.parquet' (FORMAT parquet)")
    con.sql("""
        SELECT event_type, count(*) AS n
        FROM read_parquet('events.parquet')
        GROUP BY event_type
        ORDER BY event_type
    """).show()
    Expected output
    ┌────────────┬───────┐
    │ event_type │   n   │
    │  varchar   │ int64 │
    ├────────────┼───────┤
    │ purchase   │     3 │
    │ signup     │     3 │
    └────────────┴───────┘
  7. Create an index for point lookups

    DuckDB automatically keeps min/max statistics per row group, which speeds up range filters. For selective lookups or uniqueness, you can add an ART index explicitly; primary keys get one automatically.

    python
    con.sql("CREATE INDEX idx_events_user ON events(user_id)")
    con.sql("SELECT index_name, table_name, is_unique FROM duckdb_indexes() ORDER BY index_name").show()
    print(con.sql("SELECT event_id, event_type FROM events WHERE user_id = 11 ORDER BY event_id").fetchall())
    Expected output
    ┌─────────────────┬────────────┬───────────┐
    │   index_name    │ table_name │ is_unique │
    │     varchar     │  varchar   │  boolean  │
    ├─────────────────┼────────────┼───────────┤
    │ idx_events_user │ events     │ false     │
    └─────────────────┴────────────┴───────────┘
    
    [(3, 'signup'), (4, 'purchase')]
  8. Query a pandas DataFrame with SQL

    DuckDB can scan a DataFrame that is in scope just by using its variable name in SQL, and .df() returns any result as a DataFrame. This makes it easy to mix SQL and Python data work.

    python
    import pandas as pd
    
    users = pd.DataFrame({"user_id": [10, 11, 12], "country": ["DE", "TR", "US"]})
    result = con.sql("""
        SELECT u.country, coalesce(sum(e.amount), 0) AS revenue
        FROM users AS u LEFT JOIN events AS e USING (user_id)
        GROUP BY u.country
        ORDER BY u.country
    """).df()
    print(result)
    con.close()
    Expected output
      country  revenue
    0      DE    62.49
    1      TR     5.00
    2      US     0.00

Next steps

FAQ

Is DuckDB a replacement for PostgreSQL?
Not usually. DuckDB targets analytical queries inside one process, while PostgreSQL is a multi-user server tuned for many small transactional reads and writes. Many teams use both, sometimes together through extensions.
Do I need to load a CSV or Parquet file before querying it?
No. You can put a file path or a read_csv / read_parquet call in the FROM clause and DuckDB reads the file directly. Loading into a table makes sense when you will query the same data many times.
Can several processes write to the same DuckDB file?
An embedded DuckDB file can be opened for writing by one process at a time; other processes can open it read-only. For shared multi-writer access you need a server setup such as the client-server mode or a managed service.

More tested tutorials

All tutorials

Sources

Last verified:

  1. duckdb.org/docs/stable/clients/python/overview duckdb.org
  2. duckdb.org/docs/stable/data/csv/overview duckdb.org
  3. duckdb.org/docs/stable/data/parquet/overview duckdb.org
  4. duckdb.org/docs/stable/sql/indexes duckdb.org
  5. duckdb.org/docs/stable/guides/python/sql_on_pandas duckdb.org

Found an error? See how to report a correction.