Querying
The Timelake reader is Apache DataFusion with a Timelake table provider. You write standard SQL (DataFusion’s dialect); tables are addressed as namespace.table and always read at their latest committed version.
Time buckets
time_bucket(interval, ts [, origin]) groups rows into fixed time windows. It is DataFusion's date_bin under another name: buckets are aligned to the Unix epoch (1970-01-01) unless you pass an origin. DuckDB's time_bucket aligns to Monday 2000-01-03 instead, which gives different buckets for widths of several days, such as weeks: pass that origin to match plain DuckDB.
SELECT device_id, time_bucket(INTERVAL '5 minutes', time) AS bucket, avg(temp), max(temp)
FROM iot.readings
WHERE time >= now() - INTERVAL '1 day'
GROUP BY 1, 2Time-weighted averages, integrals and counters
Sensors report at irregular times, so a plain avg over-weights the moments with many readings, and a plain
max - min misreads a counter that reset. These aggregates follow the signal from reading to reading in time order:
| Aggregate | Result |
|---|---|
time_weighted_mean(time, value [, method]) | The mean, each reading weighted by how long it held |
integral(time, value [, method]) | The area under the signal, in value × seconds (kW readings give kW·s; divide by 3,600 for kWh) |
counter_diff(time, value) | How much a counter grew. A drop is a reset to zero, so the reading after it counts whole |
counter_rate(time, value) | That growth per second |
SELECT device_id, time_bucket(INTERVAL '1 hour', time) AS hour,
time_weighted_mean(time, temp) AS temp, -- forward fill: a value holds until the next
time_weighted_mean(time, temp, 'linear') AS temp_linear, -- a straight line between readings
integral(time, power_kw) / 3600 AS energy_kwh,
counter_diff(time, packets) AS packets
FROM iot.readings GROUP BY 1, 2Each covers the group's first to last reading: nothing is assumed before the first or after the last. Readings at the
same time count once, with the largest value. A group with one reading time gives that value as its mean, 0 as its
integral and growth, and no rate. Group by the series key: a group that mixes series has no single signal, and the
query says so. forward_fill (ffill) is the default method, linear the other.
Each partition of the scan reads a stretch of time and sums each series' runs of readings in order, and the runs are
joined, so the results are exact and cost about what avg does: hourly values of 1,000 tags over 30 days take 2.2 s
on a laptop (avg: 2.0 s), and they beat the same calculation written with lag or lead windows (a month of
energy counters per machine 1.1 s against 1.7 s). Files that could give a series' readings out of order (copies not
yet compacted away, or with dedup off, files that overlap or aren't sorted) are merged in series order first, like
dedup on read, together with the other files of the time they span (setting series-order: auto, segments,
merge). Several of them over the same column in one query compute the runs once (setting shared-signal-state):
all four take 2.1 s in the example above, not 3.5 s. Rollups store the runs and answer wider
buckets from them.
Time in a state
A condition counts as 1 while true and 0 while false, so the same aggregates measure time in a state:
SELECT device_id,
integral(time, pressure > 8.5) AS seconds_above_limit, -- each reading holds until the next
time_weighted_mean(time, state = 'running') AS uptime_share
FROM iot.readings WHERE time >= now() - INTERVAL '1 day' GROUP BY 1On the industrial benchmark, the seconds each of 100 pressure tags spent above its limit over a day took 191 ms this
way and 334 ms as the usual lead() window query, with the same answers.
Gaps in the readings
gap_count(time, threshold) counts the times a series stopped reporting for longer than threshold, an interval
(a sensor or gateway down), and gap_seconds(time, threshold) adds up how long those gaps lasted:
SELECT tag, gap_count(time, INTERVAL '5 minutes') AS gaps, gap_seconds(time, INTERVAL '5 minutes') AS gap_seconds
FROM iot.readings WHERE time >= now() - INTERVAL '1 day' GROUP BY tagA gap is the time from one reading to the next. Like the aggregates above, they cover the group's first to last
reading, so a silence before the first reading or after the last isn't counted, and they read each series in time
order the same way. On the industrial benchmark, the gaps of 100 one-second tags took 77 ms over a day and 1.4 s over
30 days, against 226 ms and 17.8 s as a lead() window query, with the same answers.
Stuck sensors
flatline_count(time, value, threshold) counts the times a series kept exactly the same value for longer than
threshold, and flatline_seconds(time, value, threshold) how long those stretches lasted in all. A stretch lasts from
its first reading to the next reading of another value, or to its own last reading at the end of the group:
SELECT tag, flatline_count(time, value, INTERVAL '10 minutes') AS stuck,
flatline_seconds(time, value, INTERVAL '10 minutes') AS stuck_seconds
FROM iot.readings WHERE time >= now() - INTERVAL '1 day'
GROUP BY tag HAVING flatline_count(time, value, INTERVAL '10 minutes') > 0Like the gap aggregates, they read each series in time order and merge partial results exactly. A day of the
industrial benchmark's 700 analog tags: 0.13 s, against 4.4 s for the same definition written with lag, running sums
and lead.
First, last, and the value at a time
first(time, value) and last(time, value) give a group's value at its earliest and latest time.
value_at(time, value, at) (alias asof, as in pandas) gives the value of the latest row at or before at, or null
when the group has none by then:
SELECT tag, last(time, value) AS now, value_at(time, value, TIMESTAMP '2026-01-30 06:00:00') AS at_shift_start
FROM iot.readings
WHERE time >= TIMESTAMP '2026-01-30 00:00:00'
GROUP BY tagThe time comes first, as in the other signal functions (TimescaleDB's first and last take the value first). They
are names for first_value(value ORDER BY time) and last_value(value ORDER BY time), the latter filtered to
time <= at for value_at, so a rollup that stores first or last answers them too.
ASOF JOIN
ASOF JOIN matches each left row with the right row of the same keys whose time is the nearest at or before its own.
It takes DuckDB's form and Snowflake's:
-- DuckDB: ASOF LEFT JOIN keeps every left row, ASOF JOIN only those with a match
SELECT p.time, p.value AS pressure, s.value AS state
FROM iot.readings p ASOF LEFT JOIN iot.states s ON p.machine = s.machine AND p.time >= s.time
-- Snowflake: every left row is kept
SELECT p.time, p.value AS pressure, s.value AS state
FROM iot.readings p ASOF JOIN iot.states s MATCH_CONDITION (p.time >= s.time) ON p.machine = s.machineUnmatched rows that are kept get nulls. The match condition (DuckDB's one inequality in ON) compares a left time with
a right time by >= or > (the latest right row at or before), or <= or < (the earliest at or after); the rest of
ON is equalities. A WHERE on the right side's columns filters the joined rows: each left row's nearest match is
found first. The right side is held in memory, sorted by time per key, and each left row finds its match by binary search: a day of the
industrial benchmark's one-second readings (8.6 M rows) with their machines' states took 0.23 s, against 78 s as a
range join.
Changes, rolling windows and statistics
Window functions over the window's order, named as in pandas:
| Function | Gives |
|---|---|
diff(x) | the change from the row before |
percent_change(x) (pct_change) | that change as a fraction of the row before (null where it was 0) |
rate(time, x) | that change per second |
rolling_mean(x, n), rolling_std(x, n) | the mean and sample standard deviation of the last n rows, null until they hold n values |
zscore(x) | how many sample standard deviations the row is from the partition's mean |
SELECT time, value, rolling_mean(value, 60) OVER w AS minute_avg, zscore(value) OVER w AS z
FROM iot.readings WHERE tag = 'M00007.pressure' AND time >= now() - INTERVAL '1 hour'
WINDOW w AS (ORDER BY time)rolling_mean(x, 60) is about 4× faster than avg(x) OVER (… ROWS BETWEEN 59 PRECEDING AND CURRENT ROW): it keeps
running sums instead of reading each frame again. The aggregates std (stddev), var, cov (covar_samp),
corr, skewness (skew) and kurtosis (kurt, the excess kurtosis) work as in pandas; the last two merge
exactly across partitions.
quantile(x, q) is the exact quantile, interpolated linearly between the two values around it as pandas does
(quantile(x, 0.5) is the median). approx_quantile(x, q) estimates it from a t-digest in bounded memory, for very
large groups.
histogram(x, low, high, bins) counts the values in each of bins equal-width bins from low to high, as numpy's
histogram with a range: a list of counts, the last bin including high.
Downsampling and bars
For charts, m4(time, value) gives each group's first, smallest, largest and last points (a list of
{time, value}), and lttb(time, value, n) downsamples a whole series to n points that keep its shape
(Largest-Triangle-Three-Buckets). m4 merges from rollups and is the cheaper of the two: 30 days of a 1-second tag,
2.6 M readings, took 0.03 s as 2-hour m4 buckets and 0.11 s as lttb to 500 points.
ohlc(time, price) gives a group's open, high, low and close as a struct, as pandas' ohlc:
SELECT minute, bar['open'] AS open, bar['high'] AS high, bar['low'] AS low, bar['close'] AS close
FROM (SELECT time_bucket(INTERVAL '1 minute', time) AS minute, ohlc(time, price) AS bar
FROM market.trades WHERE symbol = 'ABC' GROUP BY 1)
ORDER BY minuteGap filling
GROUP BY time_bucket(…) gives no row for a bucket without readings. time_buckets(width, start, end [, origin]) is
a table of every bucket in a range, aligned like time_bucket, to join the readings against; start and end can
be expressions such as now() - INTERVAL '1 day'. Window functions then fill the empty buckets:
| Function | Fills a null with |
|---|---|
forward_fill(x) (ffill) | the last value before it |
backward_fill(x) (bfill) | the next value after it |
interpolate(x) | a straight line between the values before and after it, by row |
interpolate(x, t) | the same by time t |
SELECT b.bucket,
h.temp, -- null where the hour had no readings
forward_fill(h.temp) OVER (ORDER BY b.bucket) AS temp_filled,
interpolate(h.temp, b.bucket) OVER (ORDER BY b.bucket) AS temp_line
FROM time_buckets(INTERVAL '1 hour', now() - INTERVAL '1 day', now()) b
LEFT JOIN (SELECT time_bucket(INTERVAL '1 hour', time) AS bucket, avg(temp) AS temp
FROM iot.readings WHERE device_id = 'pump-7' GROUP BY 1) h ON h.bucket = b.bucketRows before the first value (and, for backward_fill and interpolate, after the last) stay null. forward_fill is
DataFusion's last_value(x) IGNORE NULLS over the rows so far, 14 times faster (10 M rows: 0.26 s against 3.6 s).
What the reader accelerates
Time and series filters
Filters are evaluated against each file’s Iceberg column bounds before any data is read, so a time range or a series key value skips whole files. Inside the sorted Parquet files, row-group statistics and page indexes skip the rest. That includes IN lists longer than the 20 values DataFusion prunes with, such as tag IN (<50 machines>): Timelake skips the row groups and pages whose range holds none of the values (setting in-list-pruning). On the IIoT benchmark's compacted readings, a 100-tag list went from 54 to 31 ms on local disk. On object storage the same applies to a join's runtime filter, the list of keys a join to a filtered dimension table (readings JOIN tags … WHERE t.area = …) produces as the query runs.
A query sorted by time, newest first, with a limit (ORDER BY time DESC LIMIT 100) reads the newest time partition
first and older ones only while they can still hold one of the rows asked for (setting newest-first). On 30 days of
the industrial benchmark, the 100 newest readings before a past time took 38 ms instead of 298 ms. The newest buckets
of a GROUP BY time_bucket(…) sorted by the bucket (ORDER BY bucket DESC LIMIT 5) work the same way: the
TSBS DevOps query for the last five minutes' maximum took 115 ms instead of 254 ms.
Windows over each series
A window over each series in time order, such as the time to the next reading,
lead(time) OVER (PARTITION BY device_id ORDER BY time), needs each series' rows together and sorted. When the rows
come from one time partition, the reader merges its sorted files in that order, split by series, and the window reads
them as they come instead of the rows being redistributed and sorted (setting window-series-order). On the
industrial benchmark, gaps in a day of 1-second readings took 215 ms instead of 260 ms. Over several partitions,
sorting is the faster way, and the reader leaves it to DataFusion.
Latest row per series
This query shape is rewritten to read the last-value index instead of scanning the table:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY time DESC) AS rn
FROM iot.readings
) WHERE rn = 1The PARTITION BY columns must be exactly the series key and the ordering must be the time column descending. Other predicates combined with rn = 1 are applied to the latest rows, as the SQL means.
Latest row matching a series filter
SELECT * FROM iot.readings WHERE device_id = 'pump-7' ORDER BY time DESC LIMIT 1Rewritten to the index when the table has a series key, the filters (if any) reference only series key columns, and the limit is 1. Without a filter it returns the newest row of the whole table. A filter on any other column (for example temp > 80) keeps the normal scan, because the latest matching row may not be the latest row.
Both rewrites need a last-value index, which every append maintains (a table whose first rows were written by another tool has none, and these queries scan). Check with EXPLAIN: a rewritten query reads an in-memory source instead of Parquet files:
$ timelake sql "EXPLAIN SELECT * FROM iot.readings WHERE device_id = 'pump-1' ORDER BY time DESC LIMIT 1"
…
| physical_plan | SortExec: TopK(fetch=1), expr=[time@0 DESC], preserve_partitioning=[false] |
| | FilterExec: device_id@1 = pump-1 |
| | DataSourceExec: partitions=1, partition_sizes=[1] |partition_sizes means an in-memory source (the index). A normal scan shows file_groups and Parquet files instead.
Rows sent twice
In tables with dedup on, the reader returns only the latest write of each (series, time), also before compaction has removed the older copies. Only files of one partition whose key ranges overlap are merged for this; the rest are read as they are. Filters on the series key and time apply before the merge, filters on other columns after it, so an older copy never answers a query its newer copy doesn't. In EXPLAIN the merged files show up under DedupExec.
To read the copies as they are (faster on tables that compaction hasn't caught up with), turn it off for a session, or for a table with the property timelake.read-dedup = false:
SET timelake.read_dedup = false;On the command line: timelake sql --set timelake.read_dedup=false "…"; in Python: Lake(..., settings={"read_dedup": "false"}). All settings are on the Settings page.
Bucketed aggregates
A GROUP BY time_bucket(…) query on a table with a rollup of the same bucket width and grouping reads the buckets the rollup has right from it, and the rest (buckets changed since its refresh, partial buckets at the edges of the time range) from the table. The rows are the same either way. SET timelake.rollup_routing = false turns it off.
Object storage
Before planning, the reader loads every table a query references concurrently, each from one head object when it has one (otherwise version hint, metadata, manifests, and last-value index), and it reads each Parquet footer once, unless the head carried it. On remote stores it uses more scan partitions than cores (4× cores, at least 32) because the work is latency-bound. A table version the process loaded or checked is used without a new check for version-check-interval (default 1 second), so queries in that time send no request for it and can miss other processes’ commits. Raise it where dashboards can be a little behind (SET timelake.version_check_interval = '30s', or the table setting), or set 0s to check on every query. The process’s own commits are always visible immediately.
Joins with plain tables
SELECT d.site, avg(r.temp)
FROM iot.readings r JOIN iot.devices d USING (device_id)
WHERE r.time >= TIMESTAMP '2026-01-03 00:00:00'
GROUP BY 1Reading with DuckDB
Timelake tables follow Iceberg’s Hadoop-catalog layout, so DuckDB’s iceberg extension reads a table directory directly. It sees committed data and none of the reader’s rewrites.
INSTALL iceberg; LOAD iceberg;
SELECT * FROM iceberg_scan('s3://my-bucket/lake/iot/readings');
-- the last-value index is plain Parquet; timelake duckdb <table> prints its current location
SELECT * FROM read_parquet('s3://my-bucket/lake/iot/readings/metadata/lvi-….parquet');Duplicates written since the last compaction are visible to DuckDB until compaction removes them. The Timelake reader skips them: it merges the files that may hold the same (series, time) and keeps the latest write. In DuckDB, the insertion time picks the same rows:
SELECT * FROM iceberg_scan('s3://my-bucket/lake/iot/readings')
QUALIFY row_number() OVER (PARTITION BY device_id, time ORDER BY _ingest_ts DESC) = 1;Two copies inserted in the same microsecond tie here; Timelake then takes the later commit.