About Skills Projects Blog Contact View my CV ↗ Español
DuckDB hands-on: analytical SQL on your laptop for large files

DuckDB hands-on: analytical SQL on your laptop for large files

Hands-on DuckDB guide: read Parquet, CSV, and JSON, query with SQL, optimize with pushdown, persist data, and solve real scenarios.

By Omar Flores
Table of Contents

Imagine you need to answer a question about 20 GB of logs stored in S3. Opening a warehouse takes minutes, loading the data costs money, and spinning up a cluster for a single query is like renting a truck to deliver a letter.

DuckDB exists for that moment. It is an analytical database that runs inside your process, with no server, no configuration, and no cluster. You point it at files, write SQL, and get the answer in seconds. It is not a toy: it is the same engine data teams use for ad hoc analysis, pipeline validation, and lakehouse queries.

This guide is hands-on. Each section is an operation you can run today, with code and an explanation of why it works.


What DuckDB is and why it matters

DuckDB is an in-process, columnar, and vectorized database. That means:

  • In-process: it lives inside your Python, R, Java, or CLI application. There is no server listening on a port.
  • Columnar: it stores and processes data by column, like Parquet. Ideal for aggregations and scans.
  • Vectorized: it processes batches of values with SIMD instructions, not row by row.
  • Transactional: it supports ACID, MVCC, and transactions, even as a local file.
  • Extensible: extensions for Parquet, JSON, Iceberg, Delta, HTTP/S3, PostgreSQL, SQLite, Excel, and more.

The mental comparison:

Tool Model When to use
SQLite OLTP, row by row Apps, small data, transactions
PostgreSQL OLTP, server Apps, concurrency, production
DuckDB OLAP, in-process Analytics, large files, ad hoc
ClickHouse OLAP, server Real time, logs, high concurrency
Spark Distributed OLAP Terabytes, batch, cluster

DuckDB does not replace PostgreSQL or ClickHouse. It complements them: it is the engine you use when you want analytical SQL without infrastructure.


Installation and first contact

uv init duckdb-lab
cd duckdb-lab
uv add duckdb

With pip

pip install duckdb

CLI

DuckDB has an interactive CLI:

duckdb
SELECT 'hello' AS message, 42 AS number;

Python

import duckdb

print(duckdb.sql("SELECT 42 AS answer").fetchall())

Output:

[(42,)]

That is it. No connection, no credentials, no server.


Read files: Parquet, CSV, JSON, and S3

Parquet

SELECT *
FROM read_parquet('logs.parquet')
LIMIT 10;

With glob:

SELECT count(*) AS total
FROM read_parquet('logs/*.parquet');

With Hive partitions:

SELECT service, count(*) AS errors
FROM read_parquet('logs/date=2026-12-05/*/*.parquet', hive_partitioning = true)
WHERE level = 'ERROR'
GROUP BY service;

CSV

SELECT *
FROM read_csv('sales.csv', header = true, auto_detect = true)
LIMIT 10;

For large files, DuckDB reads CSV in streaming and applies projection and filters.

JSON

SELECT *
FROM read_json_auto('events.json')
LIMIT 10;

S3 / HTTP

INSTALL httpfs;
LOAD httpfs;

SET s3_region = 'us-east-1';

SELECT count(*)
FROM read_parquet('s3://bucket/logs/*.parquet');

DuckDB downloads only the necessary columns and row groups. You do not need to download the entire dataset.

Query a pandas or Polars DataFrame

import duckdb
import polars as pl

df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
print(duckdb.sql("SELECT * FROM df WHERE a > 1").df())

DuckDB can query in-memory DataFrames without copying them (when the format allows it).


Essential queries

Filters and aggregations

SELECT service, count(*) AS errors, avg(duration_ms) AS avg_ms
FROM read_parquet('logs/*.parquet')
WHERE level = 'ERROR'
  AND timestamp >= '2026-12-01'
GROUP BY service
ORDER BY errors DESC;

Joins

SELECT l.service, l.level, c.owner
FROM read_parquet('logs/*.parquet') l
LEFT JOIN read_csv('services.csv') c USING (service)
WHERE l.level = 'ERROR';

Window functions

SELECT service, timestamp, duration_ms,
       avg(duration_ms) OVER (PARTITION BY service) AS avg_service,
       rank() OVER (PARTITION BY service ORDER BY duration_ms DESC) AS rank
FROM read_parquet('logs/*.parquet');

CTE

WITH errors AS (
    SELECT service, count(*) AS n
    FROM read_parquet('logs/*.parquet')
    WHERE level = 'ERROR'
    GROUP BY service
)
SELECT * FROM errors WHERE n > 100 ORDER BY n DESC;

PIVOT

PIVOT (
    SELECT service, level, count(*) AS n
    FROM read_parquet('logs/*.parquet')
    GROUP BY service, level
) ON level USING sum(n);

Read one file and write another

COPY (
    SELECT * FROM read_parquet('logs/*.parquet') WHERE level = 'ERROR'
) TO 'errors.parquet' (FORMAT PARQUET, COMPRESSION ZSTD);

Persistence: local database

DuckDB can work in memory or persist to a .duckdb file.

duckdb my_db.duckdb
CREATE TABLE sales (
    id INTEGER,
    date DATE,
    amount DECIMAL(10,2),
    region VARCHAR
);

INSERT INTO sales VALUES
    (1, '2026-12-01', 100.50, 'North'),
    (2, '2026-12-02', 220.00, 'South');

SELECT region, sum(amount) FROM sales GROUP BY region;

Transactions

BEGIN;
UPDATE sales SET amount = amount * 1.1 WHERE region = 'North';
COMMIT;

From Python

import duckdb

con = duckdb.connect("my_db.duckdb")
con.execute("CREATE TABLE IF NOT EXISTS sales (id INTEGER, amount DOUBLE)")
con.execute("INSERT INTO sales VALUES (1, 100.0), (2, 200.0)")
print(con.execute("SELECT sum(amount) FROM sales").fetchone())
con.close()

When to persist and when not to

  • Persist: data you want to reuse, small/medium tables, intermediate results, tests.
  • Do not persist: ad hoc analysis over Parquet, where the file is already the source of truth.

In 2026, DuckDB 2.0 added the Quack protocol, which enables client-server communication and multiple processes writing to the same database. Even so, it is not a PostgreSQL replacement for concurrent OLTP.


Performance: how to make it fly

1. Read only what is needed

SELECT service, count(*)
FROM read_parquet('logs/*.parquet')
WHERE level = 'ERROR'
GROUP BY service;

DuckDB applies projection pushdown (reads only service and level) and predicate pushdown (filters at scan time). If the file is sorted by level, it can skip row groups.

2. Tune threads and memory

SET threads = 8;
SET memory_limit = '8GB';
SET preserve_insertion_order = false;
SET enable_progress_bar = true;

preserve_insertion_order = false allows aggregations without maintaining order, reducing memory.

3. Use EXPLAIN ANALYZE

EXPLAIN ANALYZE
SELECT service, count(*)
FROM read_parquet('logs/*.parquet')
WHERE level = 'ERROR'
GROUP BY service;

The output shows time per operator and rows processed. If PARQUET_SCAN reads more than expected, check the filter and file order.

4. Sort and partition files

logs/
  date=2026-12-05/
    service=api/part-000.parquet
    service=worker/part-000.parquet

A query for one day and one service reads a fraction of the dataset.

5. Avoid CSV for hot data

Convert to Parquet once:

COPY (SELECT * FROM read_csv('logs.csv')) TO 'logs.parquet' (FORMAT PARQUET, COMPRESSION ZSTD);

6. Load extensions only when needed

INSTALL httpfs;
LOAD httpfs;

Each extension adds functionality, but also surface area and dependencies.


Real-world scenarios

Ad hoc log analysis

SELECT
    date_trunc('hour', timestamp) AS hour,
    service,
    count(*) FILTER (WHERE level = 'ERROR') AS errors,
    count(*) AS total
FROM read_parquet('logs/*.parquet')
WHERE timestamp >= now() - INTERVAL 7 DAY
GROUP BY 1, 2
ORDER BY 1, 3 DESC;

Validate a pipeline before publishing

DuckDB is ideal for data tests: read the output Parquet, compare with the input, check counts and nulls.

SELECT
    count(*) AS rows,
    count(*) FILTER (WHERE id IS NULL) AS null_ids,
    count(DISTINCT id) AS unique_ids
FROM read_parquet('output/*.parquet');

Join files from different sources

SELECT s.*, p.category
FROM read_parquet('sales/*.parquet') s
LEFT JOIN read_csv('products.csv') p USING (product_id);

Lakehouse with Iceberg or Delta

DuckDB has Iceberg and Delta extensions. You can query lakehouse tables without Spark:

INSTALL iceberg;
LOAD iceberg;

SELECT count(*) FROM iceberg_scan('s3://lake/sales');

Export results for Excel

COPY (SELECT region, sum(amount) FROM sales GROUP BY region)
TO 'summary.csv' (HEADER, DELIMITER ',');

DuckDB 2.0: what is new and what matters

Version 2.0 LTS (“Cinnamon Teal”, October 2026) brought relevant changes:

  • Quack protocol: client-server communication to share a database between processes.
  • Asynchronous I/O for Parquet, CSV, and native storage: key for S3.
  • VARIANT type for JSON and semi-structured data.
  • New SQL parser and v2.0 storage format.
  • Lakehouse partitioning optimizations.
  • Triggers and SQL variables.

If you come from 1.x, check file format compatibility: once 2.0 writes, 1.x cannot open it.


Limitations and when NOT to use DuckDB

  • Concurrent OLTP: if you need many simultaneous user writes, use PostgreSQL.
  • Multi-client server: DuckDB is not a managed service; for that use ClickHouse, Snowflake, or BigQuery.
  • Data that does not fit on disk: DuckDB can spill to disk, but it is not a distributed system.
  • Very high concurrency: one process, one file; for many concurrent sessions, another engine.
  • Warehouse replacement: DuckDB is an excellent local/edge layer, not the central warehouse of a large company.

Checklist and cheatsheet

Install and start

uv add duckdb
duckdb

Read

SELECT * FROM read_parquet('data/*.parquet') LIMIT 10;
SELECT * FROM read_csv('data.csv') LIMIT 10;
SELECT * FROM read_json_auto('data.json') LIMIT 10;

Optimize

SET threads = 8;
SET memory_limit = '8GB';
SET preserve_insertion_order = false;
EXPLAIN ANALYZE SELECT ...;

Export

COPY (SELECT ...) TO 'out.parquet' (FORMAT PARQUET, COMPRESSION ZSTD);

Checklist

  • Am I reading Parquet instead of CSV?
  • Do I select only the necessary columns?
  • Do I filter early?
  • Are files sorted by the filter column?
  • Do I partition by date/service?
  • Did I tune threads and memory_limit?
  • Did I check EXPLAIN ANALYZE?
  • Do I use a persistent database only when needed?

DuckDB does not give you a warehouse. It gives you the freedom not to need one for the next question. And when the question stops requiring infrastructure, analysis becomes what it should be: curiosity with SQL.