November 16, 2025
Time-Series Crunching with DuckDB (Without Losing Your Mind)
How to query, resample, and aggregate temporal data efficiently using DuckDB — right from your laptop, scripts, or data lake.

By Quaxel
6 min read
Learn how to use DuckDB for efficient time-series analytics: resampling, window functions, rolling metrics, and lake-style querying — all with simple SQL.
You know that feeling when you "just want to run a quick time-series query"… and 20 minutes later your laptop fan sounds like a jet engine?
Let's be real: time-series data is everywhere now — events, metrics, logs, IoT ticks, financial candles. But most teams either overcomplicate it with heavy infrastructure or underpower it with tools that choke on real-world volume.
DuckDB sits in a very nice middle. It's small, embeddable, and yet surprisingly vicious when it comes to crunching temporal data. In this piece, we'll walk through how to use DuckDB as your go-to time-series engine, without needing a full-blown time-series database.
Why DuckDB Works So Well for Time-Series
Most time-series workloads look like this:
- You have wide tables with a timestamp column.
- You need filters by time, aggregations per bucket, and rolling windows.
- Data often lives in Parquet/CSV in a data lake or object store.
DuckDB's sweet spots line up almost perfectly:
- Columnar execution: Reads only the columns you need (timestamp + value + maybe a few dims).
- Vectorized engine: Crunches large time slices in-memory efficiently.
- Native Parquet support: You can query Parquet directly from disk or S3-like storage.
- Rich SQL: Window functions,
DATE_TRUNC,INTERVAL, and friends feel very natural for time-series.
You don't have to "migrate" your data. You can point DuckDB at your existing files and start querying.
A Simple Mental Model for Time-Series in DuckDB
Let's start with a concrete example.
Imagine an events table like this:
CREATE TABLE events AS
SELECT
TIMESTAMP '2024-01-01'
+ INTERVAL (random()*60*24*7) MINUTE AS ts,
'home' AS page,
random()::DOUBLE AS load_time_ms
FROM range(100000); -- 100k synthetic eventsCREATE TABLE events AS
SELECT
TIMESTAMP '2024-01-01'
+ INTERVAL (random()*60*24*7) MINUTE AS ts,
'home' AS page,
random()::DOUBLE AS load_time_ms
FROM range(100000); -- 100k synthetic eventsWe'll assume:
tsis your event timestamppageis a dimensionload_time_msis the metric
Most time-series analytics can be decomposed into a few patterns:
- Filter by time window
- Truncate or bucket timestamps
- Aggregate per bucket
- Optionally: apply window functions for rolling metrics
DuckDB has first-class support for all of these.
Pattern 1: Time Window Filtering
Filtering by time is your bread and butter.
SELECT *
FROM events
WHERE ts >= TIMESTAMP '2024-01-03'
AND ts < TIMESTAMP '2024-01-04';SELECT *
FROM events
WHERE ts >= TIMESTAMP '2024-01-03'
AND ts < TIMESTAMP '2024-01-04';Want the last 24 hours relative to "now"?
SELECT *
FROM events
WHERE ts >= now() - INTERVAL 1 DAY;SELECT *
FROM events
WHERE ts >= now() - INTERVAL 1 DAY;In practice, this becomes your first optimization lever: always reduce the time range early, so DuckDB touches fewer pages/partitions.
If you're querying Parquet in a data lake, partitioning your files by date (dt=2024-01-03) and filtering on that column lets DuckDB skip entire files.
Pattern 2: Resampling with DATE_TRUNC
Resampling is one of the main reasons people reach for a time-series database: "Give me the average latency per minute/hour/day."
DuckDB's DATE_TRUNC function makes this trivial:
SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
avg(load_time_ms) AS avg_load_ms
FROM events
WHERE ts >= TIMESTAMP '2024-01-01'
AND ts < TIMESTAMP '2024-01-07'
GROUP BY ts_hour
ORDER BY ts_hour;SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
avg(load_time_ms) AS avg_load_ms
FROM events
WHERE ts >= TIMESTAMP '2024-01-01'
AND ts < TIMESTAMP '2024-01-07'
GROUP BY ts_hour
ORDER BY ts_hour;Change 'hour' to 'minute', 'day', 'week', etc., and you've got instant resampling.
Add a dimension:
SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
page,
avg(load_time_ms) AS avg_load_ms
FROM events
GROUP BY ts_hour, page
ORDER BY ts_hour, page;SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
page,
avg(load_time_ms) AS avg_load_ms
FROM events
GROUP BY ts_hour, page
ORDER BY ts_hour, page;That's your basic time-series cube: timestamp bucket + dimension(s) + aggregate.
Pattern 3: Rolling Windows with Window Functions
Static buckets are nice. But product and observability teams love rolling metrics:
- 7-day rolling active users
- 24-hour rolling error rate
- 30-minute moving average latency
DuckDB supports window functions beautifully. For example, a 3-hour rolling average of load time per page:
WITH hourly AS (
SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
page,
avg(load_time_ms) AS avg_load_ms
FROM events
GROUP BY ts_hour, page
)
SELECT
ts_hour,
page,
avg_load_ms,
avg(avg_load_ms) OVER (
PARTITION BY page
ORDER BY ts_hour
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS avg_load_ms_3h_rolling
FROM hourly
ORDER BY ts_hour, page;WITH hourly AS (
SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
page,
avg(load_time_ms) AS avg_load_ms
FROM events
GROUP BY ts_hour, page
)
SELECT
ts_hour,
page,
avg_load_ms,
avg(avg_load_ms) OVER (
PARTITION BY page
ORDER BY ts_hour
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS avg_load_ms_3h_rolling
FROM hourly
ORDER BY ts_hour, page;We first aggregate to hourly granularity (so we don't roll over every individual row), then apply a window over the compressed timeline.
That combination — pre-aggregate, then window — is a very pragmatic pattern for big time-series workloads.
Architecture Sketch: DuckDB + Data Lake for Time-Series
Let's visualize a lightweight architecture you might use in practice.
┌────────────┐
│ Producers │
│ (apps, IoT)│
└─────┬──────┘
│ events/logs
v
┌───────────────┐
│ Object Store │ (S3 / GCS / local)
│ Parquet/CSV │
└──────┬────────┘
│
v
┌──────────┐
│ DuckDB │ ← runs in: notebook, script, CLI
└────┬─────┘
│
v
┌───────────────┐
│ Time-Series │
│ Analytics │
│ (SQL) │
└───────────────┘┌────────────┐
│ Producers │
│ (apps, IoT)│
└─────┬──────┘
│ events/logs
v
┌───────────────┐
│ Object Store │ (S3 / GCS / local)
│ Parquet/CSV │
└──────┬────────┘
│
v
┌──────────┐
│ DuckDB │ ← runs in: notebook, script, CLI
└────┬─────┘
│
v
┌───────────────┐
│ Time-Series │
│ Analytics │
│ (SQL) │
└───────────────┘You're not standing up a separate time-series cluster. You're:
- Dumping your events into Parquet (ideally partitioned by date/hour).
- Pointing DuckDB at that store.
- Running analytics from your laptop or a small container.
For many teams, that's more than enough.
Querying Time-Series Directly from Parquet
Let's say your events live in a directory of daily Parquet files:
data/events/dt=2024-01-01/*.parquet
data/events/dt=2024-01-02/*.parquet
...data/events/dt=2024-01-01/*.parquet
data/events/dt=2024-01-02/*.parquet
...In DuckDB:
CREATE TABLE events AS
SELECT *
FROM 'data/events/dt=*/events_*.parquet';CREATE TABLE events AS
SELECT *
FROM 'data/events/dt=*/events_*.parquet';Or skip the table and query directly:
SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
count(*) AS hits
FROM read_parquet('data/events/dt=*/events_*.parquet')
WHERE dt BETWEEN DATE '2024-01-01' AND DATE '2024-01-07'
GROUP BY ts_hour
ORDER BY ts_hour;SELECT
DATE_TRUNC('hour', ts) AS ts_hour,
count(*) AS hits
FROM read_parquet('data/events/dt=*/events_*.parquet')
WHERE dt BETWEEN DATE '2024-01-01' AND DATE '2024-01-07'
GROUP BY ts_hour
ORDER BY ts_hour;You might be wondering: Do I lose performance by not "loading" data first? In many cases, no. DuckDB is happiest when it can stream from Parquet with predicate + column pruning. For repeated queries, you can always ingest into a local DuckDB file for extra speed.
Case Study: Monitoring API Latency on a Laptop
Imagine you're a backend engineer responsible for an API that serves millions of requests per day. Logs are shipped as gzipped JSON to object storage. A daily batch converts them to Parquet with a schema like:
ts(timestamp)service(string)path(string)latency_ms(double)status(int)
You want to answer questions like:
- "What was the 95th percentile latency per minute for the last 2 hours?"
- "Did a deployment cause a spike between 10:00 and 10:15?"
Here's how you might do it with DuckDB in Python:
import duckdb
from datetime import datetime, timedelta
con = duckdb.connect("observability.duckdb")
end = datetime.utcnow()
start = end - timedelta(hours=2)
query = """
SELECT
DATE_TRUNC('minute', ts) AS ts_minute,
service,
quantile(latency_ms, 0.95) AS p95_latency_ms,
avg(latency_ms) AS avg_latency_ms,
count(*) AS request_count
FROM read_parquet('s3://logs/api/dt=*/logs_*.parquet')
WHERE ts BETWEEN ? AND ?
GROUP BY ts_minute, service
ORDER BY ts_minute, service;
"""
df = con.execute(query, [start, end]).df()
print(df.head())import duckdb
from datetime import datetime, timedelta
con = duckdb.connect("observability.duckdb")
end = datetime.utcnow()
start = end - timedelta(hours=2)
query = """
SELECT
DATE_TRUNC('minute', ts) AS ts_minute,
service,
quantile(latency_ms, 0.95) AS p95_latency_ms,
avg(latency_ms) AS avg_latency_ms,
count(*) AS request_count
FROM read_parquet('s3://logs/api/dt=*/logs_*.parquet')
WHERE ts BETWEEN ? AND ?
GROUP BY ts_minute, service
ORDER BY ts_minute, service;
"""
df = con.execute(query, [start, end]).df()
print(df.head())You're now doing serious time-series observability from a single DuckDB file, querying cloud logs, with code that fits in a tweet.
Handling Gaps: Generating a Time Spine
Time-series data is rarely perfect. Buckets might be empty; devices may go offline; some minutes just have no events.
If you need a complete time axis (for charts or cohort tables), you can generate a "time spine" and left join your aggregates onto it.
-- 1. Generate 1-minute buckets
WITH spine AS (
SELECT
generate_series(
TIMESTAMP '2024-01-01 00:00:00',
TIMESTAMP '2024-01-01 01:00:00',
INTERVAL 1 MINUTE
) AS ts_minute
),
-- 2. Aggregate events to the same grain
agg AS (
SELECT
DATE_TRUNC('minute', ts) AS ts_minute,
count(*) AS hits
FROM events
WHERE ts >= TIMESTAMP '2024-01-01 00:00:00'
AND ts < TIMESTAMP '2024-01-01 01:00:00'
GROUP BY ts_minute
)
-- 3. Join spine and aggregates
SELECT
s.ts_minute,
coalesce(a.hits, 0) AS hits
FROM spine s
LEFT JOIN agg a USING (ts_minute)
ORDER BY s.ts_minute;-- 1. Generate 1-minute buckets
WITH spine AS (
SELECT
generate_series(
TIMESTAMP '2024-01-01 00:00:00',
TIMESTAMP '2024-01-01 01:00:00',
INTERVAL 1 MINUTE
) AS ts_minute
),
-- 2. Aggregate events to the same grain
agg AS (
SELECT
DATE_TRUNC('minute', ts) AS ts_minute,
count(*) AS hits
FROM events
WHERE ts >= TIMESTAMP '2024-01-01 00:00:00'
AND ts < TIMESTAMP '2024-01-01 01:00:00'
GROUP BY ts_minute
)
-- 3. Join spine and aggregates
SELECT
s.ts_minute,
coalesce(a.hits, 0) AS hits
FROM spine s
LEFT JOIN agg a USING (ts_minute)
ORDER BY s.ts_minute;Now every minute is present, with 0 hits where there were no events. Your BI tool (or notebook charts) will thank you.
Dimensional Time-Series: Cohorts and Segmentation
Temporal data gets interesting when you add dimensions:
user_id,plan,countryfor product analyticsdevice_id,firmwarefor IoTservice,region,statusfor infra
DuckDB handles this like any OLAP database would — group by more columns, and use window functions to compute cohort metrics.
Example: Active users per day per plan, plus a 7-day rolling active count:
WITH daily_active AS (
SELECT
DATE_TRUNC('day', ts) AS dt,
plan,
count(DISTINCT user_id) AS dau
FROM events
GROUP BY dt, plan
)
SELECT
dt,
plan,
dau,
sum(dau) OVER (
PARTITION BY plan
ORDER BY dt
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7d_active
FROM daily_active
ORDER BY dt, plan;WITH daily_active AS (
SELECT
DATE_TRUNC('day', ts) AS dt,
plan,
count(DISTINCT user_id) AS dau
FROM events
GROUP BY dt, plan
)
SELECT
dt,
plan,
dau,
sum(dau) OVER (
PARTITION BY plan
ORDER BY dt
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7d_active
FROM daily_active
ORDER BY dt, plan;Is this "a full-blown time-series database"? No. But for analytics, this covers a huge amount of ground with minimal moving parts.
When DuckDB Is a Good Fit (and When It Isn't)
Great fit when:
- You're doing batch or near-real-time analytics, not sub-millisecond serving.
- Data sits in files (Parquet/CSV) and you want to avoid spinning up infra.
- You live in Python/R/SQL notebooks and want tight feedback loops.
- Your datasets fit comfortably on one machine (or you're okay with sampling).
Less ideal when:
- You need highly concurrent, low-latency reads from many clients.
- You're storing years of ultra-high-frequency ticks at massive scale with strict retention policies.
In those cases, a dedicated time-series database (or a columnar data warehouse) might make more sense. DuckDB shines as a developer-first, analytics-first engine, not as a multi-tenant query service.
Wrapping Up (and What to Try Next)
Time-series crunching doesn't have to mean "buy a time-series database" or "ship everything into a warehouse and pray the query finishes."
DuckDB gives you:
- Fast, vectorized time-based aggregations
- Rich window functions and resampling via SQL
- Easy access to Parquet in your data lake
- A frictionless developer experience in notebooks, scripts, and CLIs
If you're working with logs, metrics, or event streams, try this:
- Export a day of data to Parquet.
- Point DuckDB at it.
- Implement:
- one resampling query,
- one rolling window metric,
- one cohort-style report with dimensions.
Then, if you're up for it, share what you discovered:
👉 Drop a comment with how you're using DuckDB for time-series, follow for more DuckDB patterns, and feel free to remix these snippets into your own stack.