Lecture 17
DuckDB is an open source, in-process, analytical relational database. It was created at CWI in the Netherlands and first released in 2019.
In-process means there is no server. The engine is a library that runs inside R, Python, or the CLI, and a database is a single file.
Analytical means online analytical processing (OLAP) vs online transaction processing (OLTP).
Data is stored by column.
Queries are multithreaded and use all available CPU cores by default.
CSV, JSON, and Parquet files can be queried directly without an explicit import step.
Last time we used DuckDB as the engine behind DBI and dbplyr in R and the DB-API in Python.
Today the focus is the SQL itself, using DuckDB’s command line interface (CLI). Everything we use today works in the same way when run through dbGetQuery() or duckdb.sql().
The CLI is a single executable with no dependencies. It is separate from the R and Python packages, which bundle the engine but not the shell.
The CLI is already installed on the department servers.
DuckDB v2.0.0 has just been released and is the version used in these slides, but everything here also works with older versions.
Just like with DBI, running duckdb with a file path opens (or creates) that database. With no path the database is initialized in memory and discarded on exit.
DuckDB v2.0.0 (Cyanoptera) d54cbbe3df
Enter ".help" for usage hints.
employees D
Commands beginning with . are instructions to the shell rather than SQL. They do not need a semicolon.
┌─────────┬─────────┬────────────┐
│ name │ salary │ dept │
│ varchar │ double │ varchar │
├─────────┼─────────┼────────────┤
│ Alice │ 52000.0 │ Accounting │
│ Bob │ 40000.0 │ Accounting │
│ Carol │ 30000.0 │ Sales │
│ Dave │ 33000.0 │ Accounting │
│ Eve │ 44000.0 │ Sales │
│ Frank │ 37000.0 │ Sales │
└─────────┴─────────┴────────────┘
SQL keywords are case insensitive. By convention they are written in upper case and identifiers in lower case. Whitespace and line breaks are ignored, and a query is ended by a semicolon.
The default output format is called duckbox, alternative formats can be selected by .mode.
DuckDB can treat a CSV (or Parquet or JSON) file as a table, so a file can be queried without importing it.
A table can be created from any query with CREATE TABLE ... AS, including a query on a file.
A view stores the query rather than its result. It can be used like a table but is re-evaluated each time, so the file is read on every query.
Dropping something that does not exist is an error, but IF EXISTS makes it a no-op. Along with CREATE OR REPLACE this lets a script be re-run safely.
DuckDB extends standard SQL with a collection of shortcuts that remove boilerplate. They are not portable to other databases, but they make interactive work much more pleasant.
Some commonly used examples,
FROM first syntax and an optional SELECT
GROUP BY ALL and ORDER BY ALL
SELECT * EXCLUDE (...) and SELECT * REPLACE (...)
DESCRIBE and SUMMARIZE
SEMI JOIN, ANTI JOIN, and QUALIFY
Starting with FROM lets you name the table before the columns, which matches the order you think in (and the order dplyr pipes run in). SELECT * is implied when it is omitted.
┌─────────┬─────────┬────────────┐
│ name │ salary │ dept │
│ varchar │ double │ varchar │
├─────────┼─────────┼────────────┤
│ Alice │ 52000.0 │ Accounting │
│ Bob │ 40000.0 │ Accounting │
│ Carol │ 30000.0 │ Sales │
│ Dave │ 33000.0 │ Accounting │
│ Eve │ 44000.0 │ Sales │
│ Frank │ 37000.0 │ Sales │
└─────────┴─────────┴────────────┘
GROUP BY ALL groups by every non-aggregated column in the SELECT, so the grouping columns do not need to be listed twice. ORDER BY ALL sorts by every selected column, left to right.
SELECT * can be modified to drop columns or replace them with an expression, rather than listing every column that should be kept.
┌─────────┬────────┬────────────┐
│ name │ salary │ dept │
│ varchar │ double │ varchar │
├─────────┼────────┼────────────┤
│ Alice │ 52.0 │ Accounting │
│ Bob │ 40.0 │ Accounting │
│ Carol │ 30.0 │ Sales │
└─────────┴────────┴────────────┘
DESCRIBE reports the columns and types of a table or query. SUMMARIZE computes summary statistics for every column.
┌─────────────┬─────────────┬────────────┬─────────┬───┬─────────┬───────┬─────────────────┐
│ column_name │ column_type │ min │ max │ … │ q75 │ count │ null_percentage │
│ varchar │ varchar │ varchar │ varchar │ … │ varchar │ int64 │ decimal(9,2) │
├─────────────┼─────────────┼────────────┼─────────┼───┼─────────┼───────┼─────────────────┤
│ name │ VARCHAR │ Alice │ Frank │ … │ NULL │ 6 │ 0.00 │
│ salary │ DOUBLE │ 30000.0 │ 52000.0 │ … │ 44000.0 │ 6 │ 0.00 │
│ dept │ VARCHAR │ Accounting │ Sales │ … │ NULL │ 6 │ 0.00 │
└─────────────┴─────────────┴────────────┴─────────┴───┴─────────┴───────┴─────────────────┘
3 rows use .last to show entire result 12 columns (7 shown)
DuckDB also adds join types. SEMI JOIN keeps the rows of the left table that have a match, and ANTI JOIN keeps those that do not. Neither adds columns from the right table.
┌─────────┬─────────┬────────────┐
│ name │ salary │ dept │
│ varchar │ double │ varchar │
├─────────┼─────────┼────────────┤
│ Bob │ 40000.0 │ Accounting │
│ Carol │ 30000.0 │ Sales │
│ Eve │ 44000.0 │ Sales │
│ Frank │ 37000.0 │ Sales │
└─────────┴─────────┴────────────┘
The flights.duckdb database contains nycflights13::flights and nycflights13::planes as tables. It was built from Parquet files with the file-as-table trick,
┌───────┬───────┬───────┬───┬────────┬────────┬──────────────────────────┐
│ year │ month │ day │ … │ hour │ minute │ time_hour │
│ int32 │ int32 │ int32 │ … │ double │ double │ timestamp with time zone │
├───────┼───────┼───────┼───┼────────┼────────┼──────────────────────────┤
│ 2013 │ 1 │ 1 │ … │ 5.0 │ 15.0 │ 2013-01-01 05:00:00-05 │
│ 2013 │ 1 │ 1 │ … │ 5.0 │ 29.0 │ 2013-01-01 05:00:00-05 │
│ 2013 │ 1 │ 1 │ … │ 5.0 │ 40.0 │ 2013-01-01 05:00:00-05 │
│ · │ · │ · │ … │ · │ · │ · │
│ · │ · │ · │ … │ · │ · │ · │
│ · │ · │ · │ … │ · │ · │ · │
│ 2013 │ 9 │ 30 │ … │ 12.0 │ 10.0 │ 2013-09-30 12:00:00-04 │
│ 2013 │ 9 │ 30 │ … │ 11.0 │ 59.0 │ 2013-09-30 11:00:00-04 │
│ 2013 │ 9 │ 30 │ … │ 8.0 │ 40.0 │ 2013-09-30 08:00:00-04 │
└───────┴───────┴───────┴───┴────────┴────────┴──────────────────────────┘
336776 rows (6 shown) 19 columns (6 shown)
Run Time (s): real 0.008 user 0.013426 sys 0.006671
┌─────────┬───────┬─────────────────────────┬───┬───────┬───────┬───────────┐
│ tailnum │ year │ type │ … │ seats │ speed │ engine │
│ varchar │ int32 │ varchar │ … │ int32 │ int32 │ varchar │
├─────────┼───────┼─────────────────────────┼───┼───────┼───────┼───────────┤
│ N10156 │ 2004 │ Fixed wing multi engine │ … │ 55 │ NULL │ Turbo-fan │
│ N102UW │ 1998 │ Fixed wing multi engine │ … │ 182 │ NULL │ Turbo-fan │
│ N103US │ 1999 │ Fixed wing multi engine │ … │ 182 │ NULL │ Turbo-fan │
│ · │ · │ · │ … │ · │ · │ · │
│ · │ · │ · │ … │ · │ · │ · │
│ · │ · │ · │ … │ · │ · │ · │
│ N998AT │ 2002 │ Fixed wing multi engine │ … │ 100 │ NULL │ Turbo-fan │
│ N998DL │ 1992 │ Fixed wing multi engine │ … │ 142 │ NULL │ Turbo-jet │
│ N999DN │ 1992 │ Fixed wing multi engine │ … │ 142 │ NULL │ Turbo-jet │
└─────────┴───────┴─────────────────────────┴───┴───────┴───────┴───────────┘
3322 rows (6 shown) 9 columns (6 shown)
Run Time (s): real 0.001 user 0.000659 sys 0.000167
What is the total number of seats available on all of the planes that flew out of New York in 2013?
Write your query against flights.duckdb and check it with .timer on.
Does the following seem correct?
Does this answer make sense? Why or why not?
flights and planes share two column names, tailnum and year, but year means different things in each table. Naming the join column avoids matching on both.
For each carrier, how does its average departure delay compare to the average over all flights?
┌─────────┬─────────────┐
│ carrier │ carrier_avg │
│ varchar │ double │
├─────────┼─────────────┤
│ US │ 3.78 │
│ HA │ 4.9 │
│ AS │ 5.8 │
│ · │ · │
│ · │ · │
│ · │ · │
│ YV │ 19.0 │
│ EV │ 19.96 │
│ F9 │ 20.22 │
└─────────┴─────────────┘
16 rows 2 columns
(6 shown)
Run Time (s): real 0.001 user 0.003019 sys 0.001440
A query that returns a single value can be used anywhere a value is expected. Here the overall average is computed once and divides every carrier’s average.
┌─────────┬─────────────┬────────┐
│ carrier │ carrier_avg │ ratio │
│ varchar │ double │ double │
├─────────┼─────────────┼────────┤
│ US │ 3.78 │ 0.3 │
│ HA │ 4.9 │ 0.39 │
│ AS │ 5.8 │ 0.46 │
│ · │ · │ · │
│ · │ · │ · │
│ · │ · │ · │
│ YV │ 19.0 │ 1.5 │
│ EV │ 19.96 │ 1.58 │
│ F9 │ 20.22 │ 1.6 │
└─────────┴─────────────┴────────┘
16 rows (6 shown) 3 columns
Run Time (s): real 0.002 user 0.006068 sys 0.002056
WITH names a subquery up front so the query reads top to bottom. CROSS JOIN adds the one row of overall to every flight.
┌─────────┬────────┐
│ carrier │ ratio │
│ varchar │ double │
├─────────┼────────┤
│ US │ 0.3 │
│ HA │ 0.39 │
│ AS │ 0.46 │
│ · │ · │
│ · │ · │
│ · │ · │
│ YV │ 1.5 │
│ EV │ 1.58 │
│ F9 │ 1.6 │
└─────────┴────────┘
16 rows
(6 shown)
Run Time (s): real 0.003 user 0.006365 sys 0.000743
dplyr user system elapsed
0.652 0.034 0.694
# A tibble: 16 × 3
carrier carrier_avg ratio
<chr> <dbl> <dbl>
1 US 3.78 0.3
2 HA 4.9 0.39
3 AS 5.8 0.46
4 AA 8.59 0.68
5 DL 9.26 0.73
6 MQ 10.6 0.83
# ℹ 10 more rows
For each origin airport, what are the three most common destinations?
┌─────────┬─────────┬───────┐
│ origin │ dest │ n │
│ varchar │ varchar │ int64 │
├─────────┼─────────┼───────┤
│ EWR │ ORD │ 6100 │
│ EWR │ BOS │ 5327 │
│ EWR │ SFO │ 5127 │
│ · │ · │ · │
│ · │ · │ · │
│ · │ · │ · │
│ LGA │ SBN │ 6 │
│ LGA │ MYR │ 3 │
│ LGA │ LEX │ 1 │
└─────────┴─────────┴───────┘
224 rows 3 columns
(6 shown)
A window function computes a value for each row from the other rows in its partition without collapsing them, like a grouped mutate().
Filtering on that value in WHERE does not work as WHERE is evaluated before window functions.
Binder Error: WHERE clause cannot contain window functions!
LINE 5: rank() OVER (PARTITION BY origin ORDER BY n DESC) AS rank
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The standard fix is to wrap the query in a subquery and filter that. DuckDB adds QUALIFY, which filters on window results directly, as HAVING does for aggregates.
┌─────────┬─────────┬───────┬───────┐
│ origin │ dest │ n │ rank │
│ varchar │ varchar │ int64 │ int64 │
├─────────┼─────────┼───────┼───────┤
│ EWR │ ORD │ 6100 │ 1 │
│ EWR │ BOS │ 5327 │ 2 │
│ EWR │ SFO │ 5127 │ 3 │
│ JFK │ LAX │ 11262 │ 1 │
│ JFK │ SFO │ 8204 │ 2 │
│ JFK │ BOS │ 5898 │ 3 │
│ LGA │ ATL │ 10263 │ 1 │
│ LGA │ ORD │ 8857 │ 2 │
│ LGA │ CLT │ 6168 │ 3 │
└─────────┴─────────┴───────┴───────┘
Using flights.duckdb,
For each month, which carrier had the worst mean arrival delay? Use a window function and QUALIFY.
What fraction of each carrier’s flights departed more than 30 minutes late, and how does that compare to the fraction over all flights? Use a CTE.
The file-as-table trick extends to many files. A glob pattern reads them as one table, which is how large data sets are usually distributed, e.g. one Parquet file per month.
Files can also be remote. DuckDB fetches only the parts of a Parquet file that a query needs, here the footer of a 1.6 MB file holding the row count.
nycflights13 is one year and three airports from the Bureau of Transportation Statistics on-time data. The whole thing, every domestic flight since 1987, is 38 Parquet files, one per year, available in /data/rdu/ on the department servers.
Every one of the 217 million rows contributes to the following query.
┌────────┬──────────┬───────────┬──────────┐
│ decade │ flights │ dep_delay │ pct_late │
│ int64 │ int64 │ double │ double │
├────────┼──────────┼───────────┼──────────┤
│ 1980 │ 11555122 │ 7.5 │ 14.9 │
│ 1990 │ 52694390 │ 7.6 │ 14.6 │
│ 2000 │ 62857045 │ 8.7 │ 17.9 │
│ 2010 │ 62561043 │ 9.4 │ 18.3 │
│ 2020 │ 27722094 │ 10.2 │ 18.3 │
└────────┴──────────┴───────────┴──────────┘
Run Time (s): real 0.303 user 3.429797 sys 0.211091
The busiest destination from RDU each year:
┌───────┬─────────┬───────┐
│ Year │ Dest │ n │
│ int64 │ varchar │ int64 │
├───────┼─────────┼───────┤
│ 2024 │ ATL │ 2296 │
│ 2023 │ JFK │ 4730 │
│ 2022 │ JFK │ 4573 │
│ 2021 │ ATL │ 4008 │
│ 2020 │ ATL │ 3552 │
│ 2019 │ ATL │ 5290 │
└───────┴─────────┴───────┘
Run Time (s): real 0.150 user 1.707782 sys 0.136680
DuckDB is an in-process analytical database. The same engine runs inside R, Python, and the CLI, and a database is a single file or lives in memory.
The CLI is the quickest way to explore data with SQL. Dot commands (.tables, .schema, .mode, .timer) control the shell, and everything else is SQL ending in a semicolon.
Scalar subqueries and CTEs break a complex query into steps, window functions compute within-group values without collapsing rows, and QUALIFY filters on them.
CSV, JSON, and Parquet files can be queried as tables. CREATE TABLE ... AS copies a file into the database, while CREATE VIEW keeps reading it from disk.
DuckDB’s friendly SQL (FROM first, GROUP BY ALL, EXCLUDE, SUMMARIZE) removes a lot of boilerplate at the cost of portability.
A glob of Parquet files is a table too. A laptop can aggregate hundreds of millions of rows in seconds because only the columns a query touches are read.
Sta 523 - Fall 2026