library(tidyverse)
library(duckdb)
library(arrow)15 DuckDB: a database without the database
15.1 Introduction
To most physicists, “database” means a server: something an administrator installs, that needs accounts and passwords, and that you query in SQL from far away. DuckDB is none of those things. Mark Raasveldt and Hannes Mühleisen began it in 2018 at CWI, the Dutch national research institute for mathematics and computer science, and released the first version in 2019 (Raasveldt and Mühleisen 2019). It is an analytical database that runs inside your R session, like a package: no server, no setup, no accounts. It can query Parquet and CSV files where they lie, sort and join tables much larger than memory by spilling to disk, and keep data in a single compressed database file if you want one.
You will not have to write SQL. The duckdb package (Mühleisen and Raasveldt 2026) connects R to DuckDB, and the dbplyr package (Wickham et al. 2026) translates dplyr pipelines into SQL for you; R for Data Science covers the same machinery in its chapter on databases (Wickham et al. 2023). The verbs stay the same, again.
Prerequisites
DBI, the standard R interface to databases on which duckdb is built, is loaded along with it. This chapter makes its own copy of the dimuon events as a Parquet dataset partitioned by run:
dimuon <- read_csv("data/dimuon.csv.gz", col_types = "iidddidddi")
unlink("scratch/duck", recursive = TRUE)
dimuon |>
group_by(run) |>
write_dataset("scratch/duck/dimuon")15.2 Connecting
dbConnect(duckdb()) starts a DuckDB database in memory, inside your R session. It costs almost nothing, and it disappears when you disconnect:
con <- dbConnect(duckdb())(The first time, DuckDB may print a note about where it keeps optional extensions. It is harmless.)
15.3 Querying files where they lie
DuckDB reads Parquet directly. duckdb’s tbl_function() turns any of DuckDB’s table functions into a dplyr table, and the read_parquet() function accepts a glob pattern that matches many files at once; hive_partitioning = true tells it to recover the run column from the folder names, as arrow did in Chapter 14:
events <- tbl_function(
con,
"read_parquet('scratch/duck/dimuon/**/*.parquet', hive_partitioning = true)"
)
events
#> # A query: ?? x 10
#> # Database: DuckDB 2.0.1 [daver@Windows 10 x64:R 4.6.1/:memory:]
#> event mu1_pt mu1_eta mu1_phi mu1_charge mu2_pt mu2_eta mu2_phi mu2_charge
#> <int> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <int>
#> 1 1 11.3 1.49 1.64 1 5.53 1.96 1.86 1
#> 2 2 24.3 0.286 -0.640 1 4.77 0.223 -0.357 -1
#> 3 3 13.4 -1.45 -3.01 1 12.0 -1.59 2.89 -1
#> 4 4 19.1 0.149 1.72 1 16.6 -0.034 1.93 -1
#> 5 5 11.8 -2.21 2.19 1 7.29 -2.26 1.97 -1
#> 6 6 11.1 1.39 1.08 1 4.57 1.37 0.635 -1
#> 7 7 14.5 -0.637 2.99 1 5.03 -0.813 -3.11 -1
#> 8 8 16.7 0.246 1.60 1 11.4 0.391 1.32 -1
#> 9 9 6.92 0.113 1.25 -1 4.55 -0.432 1.50 1
#> 10 10 16.4 2.35 -2.08 -1 12.7 2.17 -1.95 1
#> # ℹ more rows
#> # ℹ 1 more variable: run <dbl>events is a lazy table, like an arrow query: the ?? in the header means DuckDB has not yet counted the rows, because nothing has run. For a single file, tbl_file(con, "path/to/file.parquet") is a shortcut.
15.4 dplyr becomes SQL
Here is the Z-boson count per run from earlier chapters, written exactly as for a data frame:
z_per_run <- events |>
filter(mu1_charge != mu2_charge) |>
mutate(
mass_gev = sqrt(
2 * mu1_pt * mu2_pt * (cosh(mu1_eta - mu2_eta) - cos(mu1_phi - mu2_phi))
)
) |>
filter(mass_gev > 80, mass_gev < 100) |>
count(run) |>
arrange(run)show_query() shows the SQL that dbplyr wrote:
show_query(z_per_run)
#> <SQL>
#> SELECT run, COUNT(*) AS n
#> FROM (
#> SELECT
#> *,
#> SQRT(((2.0 * mu1_pt) * mu2_pt) * ((EXP(mu1_eta - mu2_eta) + EXP(-(mu1_eta - mu2_eta))) / 2 - COS(mu1_phi - mu2_phi))) AS mass_gev
#> FROM (FROM read_parquet('scratch/duck/dimuon/**/*.parquet', hive_partitioning = true)) AS q01
#> WHERE (mu1_charge != mu2_charge)
#> ) AS q01
#> WHERE (mass_gev > 80.0) AND (mass_gev < 100.0)
#> GROUP BY run
#> ORDER BY runEvery verb has become a clause: filter() a WHERE, mutate() a computed column, count() a GROUP BY, arrange() an ORDER BY. Look at what happened to cosh(): standard SQL has no hyperbolic cosine, so dbplyr wrote it out as (ex + e−x)/2. You can read the SQL to check what will run, or learn SQL from it if you ever need to, but you never have to write it. collect() runs the query and returns a tibble:
collect(z_per_run)
#> # A tibble: 8 × 2
#> run n
#> <dbl> <dbl>
#> 1 2301 581
#> 2 2302 609
#> 3 2303 584
#> 4 2304 630
#> 5 2305 637
#> 6 2306 645
#> 7 2307 608
#> 8 2308 59515.5 What DuckDB adds
DuckDB earns its place in this book by doing the things arrow cannot. The first is window functions: calculations that look at other rows in the same group without collapsing them, like ranks, running sums and lags. Here is the event with the hardest leading muon in each run. In Chapter 14 a ranking like this stopped with an error; here it runs:
events |>
group_by(run) |>
slice_max(mu1_pt, n = 1) |>
ungroup() |>
select(run, event, mu1_pt) |>
arrange(run) |>
collect()
#> # A tibble: 8 × 3
#> run event mu1_pt
#> <dbl> <int> <dbl>
#> 1 2301 13356 81.7
#> 2 2302 1958 77.5
#> 3 2303 11090 82.1
#> 4 2304 3524 76.5
#> 5 2305 11293 82.1
#> 6 2306 1704 84.6
#> 7 2307 14261 77.6
#> 8 2308 14801 81.1A grouped mutate() that uses a summary is another window function. This computes each run’s share of the events without collapsing the table first:
events |>
count(run) |>
mutate(fraction = n / sum(n, na.rm = TRUE)) |>
arrange(run) |>
collect()
#> # A tibble: 8 × 3
#> run n fraction
#> <dbl> <dbl> <dbl>
#> 1 2301 14976 0.125
#> 2 2302 14909 0.125
#> 3 2303 14772 0.124
#> 4 2304 15009 0.126
#> 5 2305 15001 0.126
#> 6 2306 15010 0.126
#> 7 2307 14862 0.124
#> 8 2308 14989 0.125The second is joins on data of any size. Real analyses attach information from other tables: calibrations, run conditions, detector maps. Suppose each run has its own small correction to the momentum scale, measured elsewhere. copy_to() puts the small table into the database, and an ordinary left_join() attaches it:
calibration <- tibble(
run = 2301:2308,
pt_scale = c(1.0012, 0.9991, 1.0004, 1.0021, 0.9987, 1.0000, 1.0009, 0.9995)
)
calibration_db <- copy_to(con, calibration, "calibration", overwrite = TRUE)
events |>
left_join(calibration_db, join_by(run)) |>
mutate(mu1_pt_corrected = mu1_pt * pt_scale) |>
select(run, event, mu1_pt, pt_scale, mu1_pt_corrected) |>
head(5) |>
collect()
#> # A tibble: 5 × 5
#> run event mu1_pt pt_scale mu1_pt_corrected
#> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 2301 1 11.3 1.00 11.3
#> 2 2301 2 24.3 1.00 24.3
#> 3 2301 3 13.4 1.00 13.5
#> 4 2301 4 19.1 1.00 19.1
#> 5 2301 5 11.8 1.00 11.8The third is size. DuckDB sorts, joins and aggregates tables much larger than memory by writing intermediate results to temporary files when it has to, so a query that would crash R simply runs more slowly.
15.6 From arrow to DuckDB and back
arrow and DuckDB both speak Arrow’s columnar format, so they can hand data to each other without copying it. to_duckdb() turns an arrow dataset or query into a DuckDB table, which lets you start in arrow and switch to DuckDB when you need a window function:
open_dataset("scratch/duck/dimuon") |>
filter(mu1_charge != mu2_charge) |>
to_duckdb(con = con) |>
group_by(run) |>
mutate(rank = min_rank(desc(mu1_pt))) |>
filter(rank == 1) |>
select(run, event, mu1_pt) |>
arrange(run) |>
collect()
#> # A tibble: 8 × 3
#> # Groups: run [8]
#> run event mu1_pt
#> <int> <int> <dbl>
#> 1 2301 13356 81.7
#> 2 2302 1958 77.5
#> 3 2303 11090 82.1
#> 4 2304 3524 76.5
#> 5 2305 11293 82.1
#> 6 2306 1704 84.6
#> 7 2307 14261 77.6
#> 8 2308 14801 81.1to_arrow() goes the other way, streaming a DuckDB result into arrow, which can then write it as a Parquet dataset with write_dataset() without ever bringing it into R.
15.7 A database file
An in-memory database vanishes when you disconnect. Give dbConnect() a file name and the database is kept on disk, compressed, ready to reopen. dbWriteTable() copies a data frame into it:
physics <- dbConnect(duckdb(), dbdir = "scratch/duck/physics.duckdb")
dbWriteTable(physics, "dimuon", dimuon)
dbListTables(physics)
#> [1] "dimuon"
dbDisconnect(physics)
file.size("scratch/duck/physics.duckdb") / 1e6
#> [1] 2.10944A later session reconnects to the same file and picks up where the last one left off; read_only = TRUE protects the data from accidental changes:
physics <- dbConnect(duckdb(), dbdir = "scratch/duck/physics.duckdb", read_only = TRUE)
tbl(physics, "dimuon") |>
count() |>
collect()
#> # A tibble: 1 × 1
#> n
#> <dbl>
#> 1 119528
dbDisconnect(physics)A DuckDB file is a fine working copy for an analysis. For archives and for sharing, keep the data in Parquet as well: far more tools read Parquet, and its specification does not depend on any one program.
dbDisconnect(con)15.8 arrow or DuckDB?
Both run dplyr pipelines on data bigger than memory, and both read Parquet. A reasonable rule: start with arrow, whose datasets are the simplest way to read and write collections of Parquet files, and switch to DuckDB, with to_duckdb() if you like, when you need window functions, large joins or sorts, or a persistent database. Neither requires you to learn a new language, and you can move between them in the middle of a pipeline.
15.9 Summary
DuckDB is an analytical database that runs inside R, with no server and no setup. Through duckdb and dbplyr, dplyr pipelines become SQL queries, which show_query() reveals and collect() runs. You queried a partitioned Parquet dataset in place with tbl_function(), used window functions and a join that arrow cannot do, handed data from arrow to DuckDB with to_duckdb(), and kept a table in a compressed database file. For archives, Parquet stays the format of record.
15.10 Exercises
- Use
show_query()on a pipeline that usesif_else()andcase_when()to classify each muon pair as barrel, endcap or mixed. What SQL does each become? - For each run, compute the mean and standard deviation of the invariant mass of pairs between 85 and 97 GeV in DuckDB. Compare with the same calculation done in R after
collect(). - Use
window_order()andcumsum()inside a groupedmutate()to compute, for each run, the running number of Z candidates as the event number increases. Plot it for two runs. - Join the calibration table and recompute the Z-peak position per run using the corrected momenta of both muons. By how much does each run’s peak move?
- Load the star catalog into a DuckDB database file with
dbWriteTable()and compare the file size with the gzipped CSV and with a Parquet file written with zstd.