DuckDB 2.0 vs Polars 2.0 Performance on 100 Million Rows


It’s been a long time since I last wrote about the relative performance between the Polars and DuckDB libraries. Back then, Polars was at version 0.18.4, and DuckDB was at version 0.9.1. 

My conclusion at the end of the article was that, aside from an issue reading Postgres data that Polars had trouble with, they were pretty much equal in performance, give or take a few seconds here or there.

Now, almost 3 years later, with both having recently released version 2 of their libraries, I thought it would be useful to revisit the subject and see whether either has pulled ahead.

In their own tests, the folks at DuckDB found that version 2.0 was 6 times faster than their current 1.56 release when processing the TPC-H SF300 dataset. For their part, Polars found it was faster than DuckDB versions 1.56 and 2.0 in all but one of their benchmarks.

So it will be interesting to see how they perform in my series of real-world data-processing tasks.

A potted history of DuckDB and Polars

DuckDB and Polars are blazingly fast tools for processing data in Python, but they come from different backgrounds.

DuckDB began in 2018, created by Hannes Mühleisen and Mark Raasveldt in the Netherlands. It is an embedded analytical database: you run SQL queries directly inside your application, without setting up a separate database server.

Polars followed in 2020, created by Ritchie Vink. Written in Rust, it takes a DataFrame approach, letting you express transformations through operations on rows and columns. Its design relies heavily on parallel processing and query optimisation.

Both are built for analytical workloads. The main distinction is how you work with them: DuckDB centres on SQL, while Polars centres on DataFrame expressions. To be fair to Polars, it is now also trying to position itself as a SQL tool, with version 2.0 being the first to treat SQL as a first-class citizen in the Polars ecosystem.

Testing methodology

All tests were carried out using Windows. The tests are as follows.

  1. Read data from a local Postgres table 

  2. Write data to a local Postgres table 

  3. Read and process text data on my local PC

  4. Read Parquet data from AWS S3 

  5. Save the text data (from step 3 above) to Parquet data on AWS S3 

Note that I ran all tests on my local PC via a Python Jupyter notebook. My PC spec is as follows:

CPU: Intel Core i9–13900K (13th generation)

Physical cores: 24

Logical processors / threads: 32

RAM: 64 GB installed (63.7 GB usable)

I ran each library test in a Jupyter Notebook. After each run, the notebook was completely closed down before being reopened for the next test run.

Prerequisites

You’ll need a local copy of a Postgres database that lets you create tables and read and write to them. You’ll also need read and write access to an AWS S3 bucket. My Postgres examples prompt for a database password, and my AWS examples assume you have an existing AWS credentials file on your local system.

Library installations

Please note that I have no association or affiliation (commercial or otherwise) with either library being tested.

I used Python 3.13.16, and I installed the following Python libraries via pip.

 pip install boto3 polars==2.0.0 duckdb==2.0.0 sqlalchemy s3fs adbc-driver-postgresql pyarrow jupyter

Checking the library versions

Open a Jupyter notebook and type this into a cell

import polars as plimport duckdb as dbprint(f"Polars  version: {pl.__version__}")print(f"DuckDB  version: {db.__version__}")

You should get something like the following output

Polars  version: 2.0.0DuckDB  version: 2.0.0

If your DuckDB is still showing an older release version, try typing this into a Jupyter cell, run it, then restart the kernel.

%pip install --upgrade --pre duckdb

Test 1 – Reading from a Postgres table

I created a test table called sales_data_100 containing 100 million synthetic sales-related data. I ran the following code in my DBeaver client to create and populate the table. There were no indexes or keys on the table

DO $import$BEGIN  CREATE TABLE public.sales_data_100m (    order_id bigint, order_date date, customer_id bigint,    customer_name text, product_id bigint, product_names text,    categories text, quantity integer, price numeric, total numeric  );  COPY public.sales_data_100m FROM 'D:/sales_data/sales_data_100m.csv'    WITH (FORMAT csv, HEADER MATCH, ENCODING 'UTF8');END$import$;

Here’s a sample of ten records from the dataset.

+----------+------------+-------------+----------------+------------+| order_id | order_date | customer_id | customer_name  | product_id |+----------+------------+-------------+----------------+------------+|        0 | 2021-11-25 |         238 | Customer_25600 |        211 ||        1 | 2017-06-10 |         534 | Customer_14188 |        209 ||        2 | 2010-02-15 |         924 | Customer_14013 |        207 ||        3 | 2011-01-26 |         633 | Customer_6120  |        211 ||        4 | 2014-01-11 |         561 | Customer_1352  |        205 ||        5 | 2021-04-19 |         533 | Customer_5342  |        208 ||        6 | 2012-03-14 |         684 | Customer_21604 |        207 ||        7 | 2017-07-01 |         744 | Customer_30291 |        201 ||        8 | 2013-02-13 |         678 | Customer_32618 |        204 ||        9 | 2023-01-04 |         340 | Customer_16898 |        207 |+----------+------------+-------------+----------------+------------+

Polars doesn’t manage database connections and data transfer on its own. Instead, external libraries (known as engines) handle this. At present, Polars can use two engines to read from databases: one called ConnectorX and the other called ADBC. We used the latter.

Read Also:  A new era of discovery

For the Postgres test, we’ll just read every record in the table and time how long it takes.

Polars code

from datetime import datetimefrom time import perf_counterfrom getpass import getpassfrom urllib.parse import quoteimport polars as plpassword = getpass("PostgreSQL password: ")connection_uri = (    f"postgresql://postgres:{quote(password, safe='')}"    "@localhost:5432/postgres")query = "SELECT * FROM public.sales_data_100m"print(f"Polars version: {pl.__version__}")print("Polars Timing — Read PostgreSQL Table")print("====================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()pdf = pl.read_database_uri(    query=query,    uri=connection_uri,    engine="adbc",)elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {pdf.height:,}")print(f"Elapsed time: {elapsed:.3f} seconds")

DuckDB code

from datetime import datetimefrom time import perf_counterfrom getpass import getpassfrom urllib.parse import quoteimport duckdb as dbimport polars as plpassword = getpass("PostgreSQL password: ")connection_uri = (    f"postgresql://postgres:{quote(password, safe='')}"    "@localhost:5432/postgres")# Prepare DuckDB outside the timed section.con = db.connect(database=":memory:")con.execute("INSTALL postgres")con.execute("LOAD postgres")print(f"DuckDB version: {db.__version__}")print("DuckDB Timing — Read PostgreSQL Table")print("====================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()# Attach your PostgreSQL database without allowing writes.uri_sql = connection_uri.replace("'", "''")con.execute(    f"ATTACH '{uri_sql}' AS pg (TYPE postgres, READ_ONLY)")# Execute the query and fully materialise the result.pdf = con.sql("""    SELECT *    FROM pg.public.sales_data_100m""").pl()elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {pdf.height:,}")print(f"Elapsed time: {elapsed:.3f} seconds")con.close()

And here are the results, which are pretty impressive if you’re a DuckDB fan.

Results

PostgreSQL password:  ········Polars version: 2.0.0Polars Timing — Read PostgreSQL Table====================================Start time: 17:34:53End time: 17:37:41Records read: 100,000,000Elapsed time: 167.525 secondsPostgreSQL password:  ········DuckDB version: 2.0.0DuckDB Timing — Read PostgreSQL Table====================================Start time: 17:35:26End time: 17:35:37Records read: 100,000,000Elapsed time: 11.380 seconds

DuckDB was over 14x faster. 

Test 2 – Writing to a Postgres table

In the second test, we’ll write 10 million synthetic sales data records to a Postgres table.

Polars code

from datetime import datetimefrom time import perf_counterfrom getpass import getpassfrom urllib.parse import quoteimport polars as plpassword = getpass("PostgreSQL password: ")connection_uri = (    f"postgresql://postgres:{quote(password, safe='')}"    "@localhost:5432/postgres")# Load the source data separately from the database-write timing.csv_start = perf_counter()pdf = pl.read_csv(    r"D:sales_datasales_data_10m.csv",    n_rows=10_000_000,    try_parse_dates=True,    schema_overrides={        "price": pl.Float64,        "total": pl.Float64,    },)print(f"CSV records loaded: {pdf.height:,}")print(f"CSV read time: {perf_counter() - csv_start:.3f} seconds")print(f"nPolars version: {pl.__version__}")print("Polars Timing — Write PostgreSQL Table")print("=====================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()pdf.write_database(    table_name="public.polars_test",    connection=connection_uri,    engine="adbc",    if_table_exists="fail",)elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Elapsed time: {elapsed:.3f} seconds")print(f"Write rate: {pdf.height / elapsed:,.0f} rows/second")# Verify the committed row count, outside the write timing.verification = pl.read_database_uri(    query="SELECT COUNT(*) AS row_count FROM public.polars_test",    uri=connection_uri,    engine="adbc",)print(f"Records verified in PostgreSQL: {verification.item():,}")

DuckDB code

from datetime import datetimefrom time import perf_counterfrom getpass import getpassfrom urllib.parse import quoteimport duckdb as dbpassword = getpass("PostgreSQL password: ")connection_uri = (    f"postgresql://postgres:{quote(password, safe='')}"    "@localhost:5432/postgres")con = db.connect(database=":memory:")con.execute("INSTALL postgres")con.execute("LOAD postgres")# Fully load the CSV before starting the database-write timer.csv_start = perf_counter()con.execute("""    CREATE TABLE source_data AS    SELECT *    FROM read_csv(        'D:/sales_data/sales_data_10m.csv',        header = true,        types = {            'order_id': 'BIGINT',            'order_date': 'DATE',            'customer_id': 'BIGINT',            'customer_name': 'VARCHAR',            'product_id': 'BIGINT',            'product_names': 'VARCHAR',            'categories': 'VARCHAR',            'quantity': 'BIGINT',            'price': 'DOUBLE',            'total': 'DOUBLE'        }    )    LIMIT 10000000""")csv_elapsed = perf_counter() - csv_startrow_count = con.execute(    "SELECT COUNT(*) FROM source_data").fetchone()[0]print(f"CSV records loaded: {row_count:,}")print(f"CSV load time: {csv_elapsed:.3f} seconds")print(f"nDuckDB version: {db.__version__}")print("DuckDB Timing — Write PostgreSQL Table")print("=====================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()uri_sql = connection_uri.replace("'", "''")con.execute(f"ATTACH '{uri_sql}' AS pg (TYPE postgres)")# Creates the PostgreSQL table and writes all source rows.# Fails if the destination table already exists.con.execute("""    CREATE TABLE pg.public.duckdb_test AS    SELECT * FROM source_data""")elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Elapsed time: {elapsed:.3f} seconds")print(f"Write rate: {row_count / elapsed:,.0f} rows/second")# Verify the committed row count outside the write timing.verified_count = con.execute("""    SELECT *    FROM postgres_query(        'pg',        'SELECT COUNT(*) FROM public.duckdb_test'    )""").fetchone()[0]print(f"Records verified in PostgreSQL: {verified_count:,}")con.close()

Results

PostgreSQL password:  ········CSV records loaded: 10,000,000CSV read time: 4.366 secondsPolars version: 2.0.0Polars Timing — Write PostgreSQL Table=====================================Start time: 17:54:11End time: 17:54:41Elapsed time: 29.406 secondsWrite rate: 340,066 rows/secondRecords verified in PostgreSQL: 10,000,000CSV records loaded: 10,000,000CSV load time: 4.084 secondsDuckDB version: 2.0.0DuckDB Timing — Write PostgreSQL Table=====================================Start time: 17:58:48End time: 17:59:23Elapsed time: 35.162 secondsWrite rate: 284,400 rows/secondRecords verified in PostgreSQL: 10,000,000

Test 3 – Reading and manipulating a local CSV file

For this test, I want to read the 100 million-record file I used in Test1 and sum the product_id column.

Read Also:  Loss Function Explained For Noobs (How Models Know They Are Wrong)

Polars code

from datetime import datetimefrom time import perf_counterimport polars as plcsv_path = r"D:sales_datasales_data_10m.csv"print(f"Polars version: {pl.__version__}")print("Polars Timing — Read CSV and Sum product_id")print("==========================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()# Read all columns and rows into memory.pdf = pl.read_csv(    csv_path,    try_parse_dates=True,    schema_overrides={        "product_id": pl.Int64,        "price": pl.Float64,        "total": pl.Float64,    },)read_end = perf_counter()# Sum product_id across all rows.product_id_sum = pdf["product_id"].sum()sum_end = perf_counter()print(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {pdf.height:,}")print(f"Sum of product_id: {product_id_sum:,}")print(f"CSV read time: {read_end - start:.3f} seconds")print(f"Sum time: {sum_end - read_end:.6f} seconds")print(f"Total elapsed time: {sum_end - start:.3f} seconds")

DuckDB code

from datetime import datetimefrom time import perf_counterimport duckdb as dbcon = db.connect(database=":memory:")print(f"DuckDB version: {db.__version__}")print("DuckDB Timing — Read CSV and Sum product_id")print("==========================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()# Fully load all columns and rows into an in-memory DuckDB table.con.execute("""    CREATE TABLE sales_data AS    SELECT *    FROM read_csv(        'D:/sales_data/sales_data_10m.csv',        header = true,        types = {            'order_id': 'BIGINT',            'order_date': 'DATE',            'customer_id': 'BIGINT',            'customer_name': 'VARCHAR',            'product_id': 'BIGINT',            'product_names': 'VARCHAR',            'categories': 'VARCHAR',            'quantity': 'BIGINT',            'price': 'DOUBLE',            'total': 'DOUBLE'        }    )""")read_end = perf_counter()product_id_sum = con.execute("""    SELECT SUM(product_id)    FROM sales_data""").fetchone()[0]sum_end = perf_counter()# Count outside the timed section.row_count = con.execute(    "SELECT COUNT(*) FROM sales_data").fetchone()[0]print(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {row_count:,}")print(f"Sum of product_id: {product_id_sum:,}")print(f"CSV read time: {read_end - start:.3f} seconds")print(f"Sum time: {sum_end - read_end:.6f} seconds")print(f"Total elapsed time: {sum_end - start:.3f} seconds")# Keep con open if you want to run further queries on sales_data.# con.close()

As expected, DuckDB went the SQL route while Polars took the dataframe path. Which was fastest?

Results

Polars version: 2.0.0Polars Timing — Read CSV and Sum product_id==========================================Start time: 11:06:21End time: 11:06:31Records read: 100,000,000Sum of product_id: 20,549,995,844CSV read time: 10.589 secondsSum time: 0.094468 secondsTotal elapsed time: 10.684 secondsDuckDB version: 2.0.0DuckDB Timing — Read CSV and Sum product_id==========================================Start time: 11:07:46End time: 11:07:54Records read: 100,000,000Sum of product_id: 20,549,995,844CSV read time: 7.943 secondsSum time: 0.042463 secondsTotal elapsed time: 7.985 seconds

Hmm…, DuckDB just edges it that time.

Test 4 — Reading Parquet data from AWS S3

My test data is 322 Parquet files on S3 totalling about 3.8GB. In the code, please substitute your own details for AWS region, bucket name, etc.

Polars code

from datetime import datetimefrom time import perf_counterimport polars as plsource = "s3://my_bucket/*.parquet"region = "my_region"print(f"Polars version: {pl.__version__}")print("Polars Timing — Read Parquet Data from S3")print("========================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()final_df = (    pl.scan_parquet(        source,        storage_options={"aws_region": region},        credential_provider=pl.CredentialProviderAWS(            profile_name="default"        ),        parallel="auto",    )    .collect())elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {final_df.height:,}")print(f"Elapsed time: {elapsed:.3f} seconds")

DuckDB code

from datetime import datetimefrom time import perf_counterimport duckdb as dbimport polars as plsource = "s3://my-bucket/*.parquet"region = "my_region"# Prepare DuckDB outside the timed section.con = db.connect(database=":memory:")con.execute("INSTALL httpfs")con.execute("LOAD httpfs")con.execute("INSTALL aws")con.execute("LOAD aws")print(f"DuckDB version: {db.__version__}")print("DuckDB Timing — Read Parquet Data from S3")print("========================================")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()region_sql = region.replace("'", "''")# Load credentials from the existing AWS profile.con.execute(f"""    CREATE OR REPLACE SECRET s3_credentials (        TYPE s3,        PROVIDER credential_chain,        CHAIN 'config',        PROFILE 'default',        REGION '{region_sql}'    )""")# Read all matching files and fully materialise the result.final_df = con.read_parquet(source).pl()elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Records read: {final_df.height:,}")print(f"Elapsed time: {elapsed:.3f} seconds")con.close()

The results are pretty even-stevens.

Read Also:  Three ways Google scientists use AI to better understand nature — Google DeepMind

Result

Polars version: 2.0.0Polars Timing — Read Parquet Data from S3========================================Start time: 11:24:50End time: 11:27:55Records read: 335,021,098Elapsed time: 184.753 secondsDuckDB version: 2.0.0DuckDB Timing — Read Parquet Data from S3========================================Start time: 11:31:16End time: 11:34:19Records read: 335,021,098Elapsed time: 182.860 seconds

Test 5— Writing Parquet data to AWS S3

For my final test, I’ll write the 100 million sales data test file from Test 1 to AWS S3 in Parquet format.

Polars code

from datetime import datetimefrom time import perf_counterimport polars as plsource = r"D:sales_datasales_data_100m.csv"destination = (    "s3://my-bucket/polars/sales_data_100m.parquet")region = "eu-west-1"credentials = pl.CredentialProviderAWS(profile_name="default")storage_options = {"aws_region": region}print(f"Polars version: {pl.__version__}")print("Polars Timing — CSV to Parquet on S3")print("===================================")print(f"Destination: {destination}")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()sales = pl.scan_csv(    source,    schema_overrides={        "order_id": pl.Int64,        "order_date": pl.Date,        "customer_id": pl.Int64,        "customer_name": pl.String,        "product_id": pl.Int64,        "product_names": pl.String,        "categories": pl.String,        "quantity": pl.Int64,        "price": pl.Float64,        "total": pl.Float64,    },)sales.sink_parquet(    destination,    compression="zstd",    compression_level=3,    row_group_size=100_000,    storage_options=storage_options,    credential_provider=credentials,    engine="streaming",)elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Total elapsed time: {elapsed:.3f} seconds")print(f"Total elapsed time: {elapsed / 60:.2f} minutes")# Verify the output row count outside the timed section.# Parquet metadata allows counting without loading every column.records_written = (    pl.scan_parquet(        destination,        storage_options=storage_options,        credential_provider=credentials,    )    .select(pl.len())    .collect()    .item())print(f"Records verified on S3: {records_written:,}")

DuckDB code

from datetime import datetimefrom time import perf_counterimport duckdb as dbsource = "D:/sales_data/sales_data_100m.csv"destination = (    "s3://my-bucket/duckdb/sales_data_100m.parquet")region = "eu-west-1"# Prepare DuckDB outside the timed section.con = db.connect(database=":memory:")con.execute("INSTALL httpfs")con.execute("LOAD httpfs")con.execute("INSTALL aws")con.execute("LOAD aws")print(f"DuckDB version: {db.__version__}")print("DuckDB Timing — CSV to Parquet on S3")print("===================================")print(f"Destination: {destination}")print(f"Start time: {datetime.now():%H:%M:%S}")start = perf_counter()region_sql = region.replace("'", "''")source_sql = source.replace("'", "''")destination_sql = destination.replace("'", "''")con.execute(f"""    CREATE OR REPLACE SECRET s3_credentials (        TYPE s3,        PROVIDER credential_chain,        CHAIN 'config',        PROFILE 'default',        REGION '{region_sql}'    )""")# Read, compress and upload without first creating a full local table.con.execute(f"""    COPY (        SELECT *        FROM read_csv(            '{source_sql}',            header = true,            types = {{                'order_id': 'BIGINT',                'order_date': 'DATE',                'customer_id': 'BIGINT',                'customer_name': 'VARCHAR',                'product_id': 'BIGINT',                'product_names': 'VARCHAR',                'categories': 'VARCHAR',                'quantity': 'BIGINT',                'price': 'DOUBLE',                'total': 'DOUBLE'            }}        )    )    TO '{destination_sql}'    (        FORMAT PARQUET,        COMPRESSION ZSTD,        COMPRESSION_LEVEL 3,        ROW_GROUP_SIZE 100000    )""")elapsed = perf_counter() - startprint(f"End time: {datetime.now():%H:%M:%S}")print(f"Total elapsed time: {elapsed:.3f} seconds")print(f"Total elapsed time: {elapsed / 60:.2f} minutes")# Verify the output row count outside the timed section.records_written = con.execute(f"""    SELECT COUNT(*)    FROM read_parquet('{destination_sql}')""").fetchone()[0]print(f"Records verified on S3: {records_written:,}")con.close()

The results show that, once again, there is little difference in performance between the two libraries. Both output Parquet files were also of a similar size, with the DuckDB version coming in at 1.3 GB and the Polars version at 1.4 GB

Results

Polars version: 2.0.0Polars Timing — CSV to Parquet on S3===================================Destination: s3://taupirho-sales-data/polars/sales_data_100m.parquetStart time: 11:43:47End time: 11:45:44Total elapsed time: 116.484 secondsTotal elapsed time: 1.94 minutesRecords verified on S3: 100,000,000DuckDB version: 2.0.0DuckDB Timing — CSV to Parquet on S3===================================Destination: s3://taupirho-sales-data/duckdb/sales_data_100m.parquetStart time: 11:48:52End time: 11:50:46Total elapsed time: 113.570 secondsTotal elapsed time: 1.89 minutesRecords verified on S3: 100,000,000

Summary

Once again, except for the first test reading from a Postgres table, where DuckDB had a clear performance lead, my conclusion is similar to the one I came to almost 3 years ago.

Both are fast, equally capable data-processing libraries. If you’re comfortable with SQL, I’d use DuckDB. Operations on database tables are often easier to code and understand than the equivalent Polars (or Pandas) dataframe operations. However, Polars is pushing SQL into more of its operations, and we’ll have to see how that develops in upcoming releases.

If you’re already familiar with a DataFrame-based library like Pandas and want a significant performance boost, Polars is worth considering. 

One distinct advantage Polars currently has over DuckDB is that it can run on a cluster of distributed servers via its Polars Cloud product. This lets Polars process terabyte-scale datasets. 

The closest equivalent for DuckDB is a product called MotherDuck, which is built around DuckDB but is a separate entity and not involved in Amazon Web Services’ recent takeover of DuckDB. I would be amazed if, given this acquisition and DuckDB’s recent announcement of their new quack networking protocol, AWS don’t deliver a similar cloud-based service for DuckDB very soon.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top