Pynions

DuckDB or SQLite? Benchmarked in Python on One Million Rows

DuckDB vs SQLite tested in Python 3.15.2 on 1,000,000 rows: one wins aggregates by about 100x, the other wins lookups and inserts. Code and verdict inside.

Updated 8 min read
Rack of network equipment with patch cables glowing green in a dark server room

Pick DuckDB when Python runs analytical queries over large tables, and SQLite when an application reads and writes small records. In our test on 1,000,000 rows, DuckDB 2.0.1 aggregated about 100 times faster than SQLite, while SQLite served key lookups and single-row inserts roughly 70 to 350 times faster.

Both are embedded, single-file databases that need no server, so the choice comes down to the shape of your queries. This guide runs both on the same data in Python, then covers concurrency, typing, and how to use the two together.

Key Takeaways

  • DuckDB wins analytical work: aggregations, joins, and scans over CSV and Parquet files.
  • SQLite wins transactional work: key lookups, many small writes, and app state, with sqlite3 already in the Python standard library.
  • Writes differ: SQLite allows one writer at a time with concurrent readers, while a DuckDB file belongs to one read-write process.
  • You can use both: DuckDB can ATTACH a SQLite file and run analytical SQL on it directly.
  • Both are free and open source, so cost does not decide it.

DuckDB vs SQLite: At a Glance

Feature

DuckDB

SQLite

Best for

Analytics over large tables and files

Application data and local storage

Engine

Columnar-vectorized

Processes each row sequentially

Python install

pip install duckdb

Built into the standard library

Concurrency

One read-write process, or many read-only processes

Many readers plus one writer at a time (WAL mode)

Typing

Strict

Flexible by default, strict with STRICT tables

License

MIT

Public domain

Key strength

Fast scans, joins, and aggregates

Fast key lookups and small writes

Key weakness

Slow row-by-row inserts and lookups

Slow full-table aggregates

What Is SQLite?

SQLite home page showing version 3.54.1 released 2026-10-16

SQLite is a C library that provides a lightweight disk-based database, and Python ships it as the sqlite3 module. The project describes its goal as local data storage for individual applications, and says SQLite "competes with fopen()" rather than with client/server databases. The current release is SQLite 3.54.1, published on 16 October 2026.

SQLite Strengths

  1. Zero setup. The module is part of Python, and the database is one file you can copy or email.
  2. Long-term stability. The developers plan to support SQLite through 2050.
  3. Room to grow. A database file can reach about 17.5 terabytes at the default page size, and about 281 terabytes at the maximum page size.

SQLite Weaknesses

  1. Row-by-row processing. DuckDB's docs say SQLite processes each row sequentially, which the benchmark below makes visible on a full-table aggregate.
  2. One writer at a time. In WAL mode, readers and writers do not block each other, but there can be only one writer.
  3. Loose typing by default. A column declared INTEGER accepts the string 'hello' unless you opt in to STRICT tables.

What Is DuckDB?

DuckDB documentation page for the SQLite extension with the ATTACH example

DuckDB is an embedded analytical database that runs inside your Python process. It uses a columnar-vectorized execution engine built for queries that touch large parts of a dataset.

It also provides ACID transactions through MVCC. The current release is DuckDB 2.0.1, uploaded to PyPI on 20 November 2026. Our DuckDB Python guide covers the API in depth.

DuckDB Strengths

  1. Analytical speed. Aggregates and joins over millions of rows finish in milliseconds in the test below.
  2. File and DataFrame access. DuckDB queries CSV and Parquet files directly with plain SQL, and the Python package can query pandas data without copying it.
  3. Strict typing. Bad values raise an error at write time instead of landing in the table.

DuckDB Weaknesses

  1. Row-by-row writes. The DuckDB docs call lots of individual INSERT statements "very inefficient" for bulk loading.
  2. Single read-write process. Multi-process writes need the Quack client-server protocol or DuckLake.
  3. Built for analytics. DuckDB targets analytical workloads, so point lookups and small transactions are not its strength, as the benchmark shows.

How We Tested

We ran every sample in a clean virtual environment on 1 December 2026 (Europe/Madrid) on an 8-core Linux box, using Python 3.15.2 with SQLite 3.53.1 from the standard library and DuckDB 2.0.1. The SQLite version depends on how your Python was built, so check sqlite3.sqlite_version on yours.

Text
python -m venv .venv
source .venv/bin/activate
pip install -q duckdb==2.0.1
python -c "import sqlite3, duckdb; print(sqlite3.sqlite_version, duckdb.__version__)"
Text
3.53.1 2.0.1

Your timings will differ with hardware and builds. The ratios between the two engines are what carry over.

Build the Test Data

DuckDB generates 1,000,000 deterministic order rows and writes them to a CSV file. Both databases then load that same file.

Python
import duckdb

duckdb.sql("""
    COPY (
        SELECT
            i AS order_id,
            (hash(i) % 50000)::INTEGER AS customer_id,
            ['US','DE','GB','FR','ES','NL','PL','LT'][1 + (hash(i * 7) % 8)::INTEGER] AS country,
            round(5 + (hash(i * 13) % 49500) / 100.0, 2) AS amount,
            DATE '2026-01-01' + (hash(i * 31) % 330)::INTEGER AS order_date
        FROM range(1, 1000001) t(i)
    ) TO 'orders.csv' (HEADER, DELIMITER ',')
""")
print(duckdb.sql("SELECT count(*) AS rows FROM 'orders.csv'").fetchall()[0][0])
Text
1000000

Load Both Databases

SQLite loads through the standard library with one executemany call inside a single transaction. DuckDB loads with one SQL statement over the CSV file. Both tables have an integer primary key on order_id.

Python
import csv, sqlite3, time, duckdb

# SQLite: stdlib, one transaction, executemany
t = time.perf_counter()
lite = sqlite3.connect("orders.sqlite")
lite.execute("DROP TABLE IF EXISTS orders")
lite.execute("""CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY, customer_id INTEGER, country TEXT,
    amount REAL, order_date TEXT)""")
with open("orders.csv", newline="") as f:
    rows = csv.reader(f)
    next(rows)
    lite.executemany("INSERT INTO orders VALUES (?, ?, ?, ?, ?)", rows)
lite.commit()
print(f"SQLite load:  {time.perf_counter() - t:.2f}s")

# DuckDB: one SQL statement over the CSV
t = time.perf_counter()
duck = duckdb.connect("orders.duckdb")
duck.execute("DROP TABLE IF EXISTS orders")
duck.execute("""CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY, customer_id INTEGER, country VARCHAR,
    amount DOUBLE, order_date DATE)""")
duck.execute("INSERT INTO orders SELECT * FROM read_csv('orders.csv')")
print(f"DuckDB load:  {time.perf_counter() - t:.2f}s")

print(lite.execute("SELECT count(*) FROM orders").fetchone()[0],
      duck.execute("SELECT count(*) FROM orders").fetchone()[0])
Text
SQLite load:  1.12s
DuckDB load:  0.45s
1000000 1000000

Analytical Queries: DuckDB vs SQLite

The benchmark script runs three workloads. The first aggregates all 1,000,000 rows by country, takes the best of five runs, and asserts that both engines return identical results.

Python
import random, sqlite3, time, duckdb

lite = sqlite3.connect("orders.sqlite")
duck = duckdb.connect("orders.duckdb")

def best(fn, runs=5):
    times = []
    for _ in range(runs):
        t = time.perf_counter()
        fn()
        times.append(time.perf_counter() - t)
    return min(times)

# 1. Analytical: scan and aggregate every row
agg = """SELECT country, count(*) AS orders, round(sum(amount), 2) AS revenue,
                round(avg(amount), 2) AS avg_order
         FROM orders GROUP BY country ORDER BY revenue DESC"""
assert lite.execute(agg).fetchall() == duck.execute(agg).fetchall(), "results differ"
a_lite = best(lambda: lite.execute(agg).fetchall())
a_duck = best(lambda: duck.execute(agg).fetchall())
print(f"aggregate 1M rows:      SQLite {a_lite * 1000:7.1f} ms | DuckDB {a_duck * 1000:7.1f} ms | {a_lite / a_duck:5.1f}x")

# 2. Transactional: 10,000 primary-key lookups
random.seed(7)
ids = [random.randint(1, 1_000_000) for _ in range(10_000)]
def lookups(con):
    for i in ids:
        con.execute("SELECT * FROM orders WHERE order_id = ?", [i]).fetchall()
p_lite = best(lambda: lookups(lite), runs=3)
p_duck = best(lambda: lookups(duck), runs=3)
print(f"10,000 key lookups:     SQLite {p_lite * 1000:7.1f} ms | DuckDB {p_duck * 1000:7.1f} ms | {p_duck / p_lite:5.1f}x slower in DuckDB")

# 3. Transactional: 10,000 single-row inserts in one transaction
def inserts(con, start):
    con.execute("BEGIN")
    for i in range(start, start + 10_000):
        con.execute("INSERT INTO orders VALUES (?, ?, ?, ?, ?)",
                    [i, i % 50000, "US", 19.99, "2026-12-01"])
    con.execute("COMMIT")
t = time.perf_counter(); inserts(lite, 2_000_001); i_lite = time.perf_counter() - t
t = time.perf_counter(); inserts(duck, 2_000_001); i_duck = time.perf_counter() - t
print(f"10,000 single inserts:  SQLite {i_lite * 1000:7.1f} ms | DuckDB {i_duck * 1000:7.1f} ms | {i_duck / i_lite:5.1f}x slower in DuckDB")
Text
aggregate 1M rows:      SQLite   252.6 ms | DuckDB     2.3 ms | 107.6x
10,000 key lookups:     SQLite    54.0 ms | DuckDB  3823.3 ms |  70.8x slower in DuckDB
10,000 single inserts:  SQLite    13.5 ms | DuckDB  4672.7 ms | 346.5x slower in DuckDB

DuckDB finished the aggregate in about 2 milliseconds against about 250 for SQLite, because its columnar-vectorized engine processes a large batch of values in one operation, which cuts the CPU cycles spent per value. SQLite's own guide lists data analysis as a good fit, and at 250 milliseconds for a million rows it is usable.

Winner: DuckDB. It was about 100 times faster on the scan-and-aggregate workload.

Transactional Work: SQLite vs DuckDB

The second and third workloads in the same script are the ones an application does all day. Ten thousand primary-key lookups took about 54 milliseconds on SQLite and about 3.8 seconds on DuckDB, even though the DuckDB table has a primary key.

The inserts tell the same story. Ten thousand single-row inserts inside one transaction took about 14 milliseconds on SQLite and about 4.7 seconds on DuckDB. The DuckDB documentation recommends against row-by-row inserts in a loop and says to maximize the data loaded per statement.

Winner: SQLite. It was roughly 70 times faster on lookups and 350 times faster on inserts in this run.

Concurrency: One Writer or One Process

SQLite in WAL mode lets readers keep reading while a writer holds an open transaction. DuckDB in its default in-process mode allows one read-write process or many read-only processes. This script shows both behaviors against the files from the benchmark.

Python
import sqlite3, subprocess, sys, duckdb

# SQLite: a second connection can read while the first holds an open write transaction
w = sqlite3.connect("orders.sqlite", timeout=0.2)
w.execute("PRAGMA journal_mode=WAL")
w.execute("BEGIN IMMEDIATE")
w.execute("INSERT INTO orders VALUES (3000001, 1, 'US', 9.99, '2026-12-01')")
r = sqlite3.connect("orders.sqlite")
print("SQLite reader during a write:", r.execute("SELECT count(*) FROM orders").fetchone()[0], "rows")
w.rollback()

# DuckDB: a second process cannot open the same file read-write
holder = duckdb.connect("orders.duckdb")
child = subprocess.run(
    [sys.executable, "-c", "import duckdb; duckdb.connect('orders.duckdb')"],
    capture_output=True, text=True,
)
print("DuckDB second process:", child.stderr.strip().splitlines()[-1].split(" \"")[0])
Text
SQLite reader during a write: 1010000 rows
DuckDB second process: _duckdb.IOException: IO Error: Could not set lock on file

The row count is 1,010,000 because the benchmark inserted 10,000 extra rows. Inside one DuckDB process, multiple threads can write at once using MVCC and optimistic concurrency, and appends never conflict. For several writer processes, DuckDB 2.0 offers the Quack client-server protocol, or DuckLake with a PostgreSQL catalog.

Winner: SQLite for many small writers on one file. DuckDB for one process doing heavy parallel work.

Typing: Flexible vs Strict

SQLite accepts values that do not match the declared column type, and the SQLite docs call flexible typing "a feature of SQLite, not a bug". Since version 3.37.0, STRICT tables enforce types. DuckDB is strictly typed from the start.

Python
import sqlite3
import duckdb

lite = sqlite3.connect(":memory:")
lite.execute("CREATE TABLE loose (n INTEGER)")
lite.execute("INSERT INTO loose VALUES ('hello')")
print("SQLite default table:", lite.execute("SELECT n, typeof(n) FROM loose").fetchall())

lite.execute("CREATE TABLE strict_t (n INTEGER) STRICT")
try:
    lite.execute("INSERT INTO strict_t VALUES ('hello')")
except sqlite3.Error as e:
    print("SQLite STRICT table:", e)

duck = duckdb.connect()
duck.execute("CREATE TABLE t (n INTEGER)")
try:
    duck.execute("INSERT INTO t VALUES ('hello')")
except duckdb.Error as e:
    print("DuckDB:", type(e).__name__, str(e).splitlines()[0])
Text
SQLite default table: [('hello', 'text')]
SQLite STRICT table: cannot store TEXT value in INTEGER column strict_t.n
DuckDB: ConversionException Conversion Error: Could not convert string 'hello' to INT32

Analytical pipelines usually want the strict behavior, because a stray string in a numeric column breaks numeric aggregates downstream. If you stay on SQLite for that reason, create tables with STRICT.

Winner: Tie. DuckDB is strict by default, and SQLite matches it when you add STRICT.

Use Both: Query a SQLite File From DuckDB

You rarely have to migrate. DuckDB's sqlite extension attaches a SQLite file, and the docs say attached SQLite databases support both read and write operations. The extension autoloads on first use, and the script below installs it explicitly.

Python
import time, duckdb

con = duckdb.connect()
con.execute("INSTALL sqlite")
con.execute("LOAD sqlite")
con.execute("ATTACH 'orders.sqlite' AS lite (TYPE sqlite, READ_ONLY)")

q = """SELECT country, count(*) AS orders, round(sum(amount), 2) AS revenue
       FROM lite.orders GROUP BY country ORDER BY revenue DESC LIMIT 3"""
t = time.perf_counter()
for row in con.execute(q).fetchall():
    print(row)
print(f"DuckDB reading the SQLite file: {(time.perf_counter() - t) * 1000:.0f} ms")

con.execute("CREATE TABLE orders AS SELECT * FROM lite.orders")
print(con.execute("SELECT count(*) FROM orders").fetchall()[0][0], "rows copied into DuckDB")
Text
('US', 135133, 31806081.2)
('NL', 125490, 31748821.31)
('LT', 125163, 31609652.61)
DuckDB reading the SQLite file: 35 ms
1010000 rows copied into DuckDB

The aggregate ran on the SQLite file in 35 milliseconds, against about 250 for SQLite itself in the benchmark. The final statement copies the table into native DuckDB storage for repeated analysis.

A common pattern is SQLite for the application's live data and DuckDB for reporting on a read-only copy. For other analysis options, see our comparison of Polars and pandas and the roundup of pandas alternatives.

Pricing and Licensing

Both databases are free. DuckDB uses the MIT License, with the project's intellectual property held by the DuckDB Foundation. SQLite's code and documentation have been dedicated to the public domain by its authors.

Pick DuckDB for Analytics, SQLite for App State

Choose DuckDB if your Python code aggregates, joins, or scans large tables, reads CSV and Parquet files, or feeds data analysis. Start with the DuckDB guide and the Python data analysis overview.

Choose SQLite if your code stores application data, serves key lookups, takes many small writes, or needs several processes writing to one file.

You can run both in one project. Keep the system of record in SQLite, and point DuckDB at it when a question needs a scan.

Frequently Asked Questions

Sources

Related Articles