(con = DBI::dbConnect(duckdb::duckdb(dbdir = "data/flights.duckdb")))<duckdb_connection 58230 driver=<duckdb_driver dbdir='/Users/rundel/Desktop/Sta523-Fa26/website/static/slides/data/flights.duckdb' read_only=FALSE bigint=numeric>>
Lecture 16
Historical estimates (circa 2012) illustrate the differences in scale. Actual timings depend on the hardware and workload.
| Task | Time (μs) | Roughly |
|---|---|---|
| L1 cache reference | \(5 \times 10^{-4}\) | 0.5 ns |
| L2 cache reference | \(7 \times 10^{-3}\) | 7 ns |
| Main memory reference | \(1 \times 10^{-1}\) | 100 ns |
| Random seek SSD | \(1.5 \times 10^{2}\) | 150 μs |
| Read 1 MB sequentially from memory | \(2.5 \times 10^{2}\) | 250 μs |
| Read 1 MB sequentially from SSD | \(1 \times 10^{3}\) | 1 ms |
| Disk seek | \(1 \times 10^{4}\) | 10 ms |
| Read 1 MB sequentially from disk | \(2 \times 10^{4}\) | 20 ms |
| Round trip packet CA to Netherlands | \(1.5 \times 10^{5}\) | 150 ms |
Using these illustrative rates, imagine we have a 10 GB flat file and want to select the rows that meet some criterion. With no other structure this requires a sequential read of the entire data set.
| File Location | Performance | Time |
|---|---|---|
| in memory | \(10~GB \times (250~\mu s / 1~MB)\) | 2.5 seconds |
| on disk (SSD) | \(10~GB \times (1~ms / 1~MB)\) | 10 seconds |
| on disk (HD) | \(10~GB \times (20~ms / 1~MB)\) | 200 seconds |
These estimates cover reading the file once. Repeated reads add to that cost, so reducing unnecessary reads can make a large difference.
Databases can skip blocks that cannot match a filter, use indexes to locate matching rows, and choose an execution plan suited to the query. Some queries still require scanning all relevant data.
Implementing blocks, indexes, and query planning correctly is hard,
the optimal strategy depends on your queries, and they change,
data is modified (inserts, updates, deletes) so the structures must stay consistent,
multiple users may access the data at the same time,
failures happen and the data must remain correct and recoverable.
A database management system (DBMS) handles all of this for you, and provides a standard interface (e.g. SQL) for saying what you want rather than how to get it.
Today we treat the database as a black box and focus on how R and Python talk to it. We will use DuckDB as the engine and look at it in detail next lecture.
Structured Query Language is a special purpose language for querying and modifying tabular data.
An ANSI standard with dialect divergence (PostgreSQL, MySQL, SQLite, DuckDB, etc.)
Declarative, a query describes the result and the database decides how to compute it
Maps closely, but not exactly, onto the dplyr verbs we have already been using
| dplyr | SQL |
|---|---|
select(x, y) |
SELECT x, y |
mutate(z = x + y) |
SELECT *, x + y AS z |
filter(x > 1) |
WHERE x > 1 |
arrange(desc(x)) |
ORDER BY x DESC |
summarize(n = n(), .by = g) |
SELECT g, COUNT(*) AS n ... GROUP BY g |
summarize(...) |> filter(n > 10) |
HAVING n > 10 |
distinct(x) |
SELECT DISTINCT x |
head(5) |
LIMIT 5 |
left_join(y, by = "k") |
LEFT JOIN y ON x.k = y.k |
mutate(m = mean(x), .by = g) |
AVG(x) OVER (PARTITION BY g) |
Clauses appear in a fixed order (SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT) regardless of the order in which they are evaluated.
The DBI package provides a consistent R interface to relational databases. Each database has a backend package (RSQLite, RPostgres, duckdb, bigrquery, …) that implements the same set of generics for
connecting and disconnecting,
listing tables and fields,
sending queries and fetching results,
executing statements that modify the database,
transactions.
Code written against DBI is largely portable between backends. The SQL you send is not (dialects differences).
A connection object is created with dbConnect() and a driver from the backend package - the connection may be local or remote.
For DuckDB is local, so the driver takes the path of a database file. If this file/database does not exist it will be created. If no path is supplied the database is created in memory and is discarded when the connection closes.
The connection is a handle to the open database, it is what every other DBI function takes as its first argument.
The object itself is tiny, since the data stays in the database. Its class comes from the backend, which is how DBI’s generics dispatch to the right implementation.
A data frame can be written as a new table in the database with dbWriteTable().
dbGetQuery() sends a query and collects a data frame as the result.
It wraps the three step process of sending the query, fetching rows, and clearing the result. The steps can be run separately when a result is too large (or slow) to fetch at once.
Statements that change the database rather than return rows (INSERT, UPDATE, DELETE, CREATE, DROP) are run with dbExecute(), which returns the number of rows affected.
Never paste user supplied values into a query string. Quoting is easy to get wrong and a hostile value can change the meaning of the query (SQL injection). Instead leave ? placeholders and pass the values separately.
Python’s equivalent to DBI is the DB-API specification (PEP 249). Each database has a package (sqlite3, psycopg, duckdb, …) that implements the specification. A connection creates cursors, and a cursor runs a query and fetches rows as tuples.
The dbplyr package lets dplyr work with tables in a database. It is installed with the tidyverse and loaded automatically when needed.
It allows dplyr verbs to operate on a reference to a table in the database. tbl() points at an existing table, copy_to() writes a local data frame to the database and returns a reference to it. The data stays in the database, the R object holds only the connection and the query that produces the table.
The dplyr verbs are all available and the results print like a df tibble.
# A query: ?? x 4
# Database: DuckDB [flights.duckdb]
origin dest tailnum dep_delay
<chr> <chr> <chr> <dbl>
1 EWR CLT N152UW -7
2 EWR IAH N535UA -7
3 JFK MIA N5BSAA -6
4 JFK SJU N531JB -6
5 JFK BQN N827JB -8
6 LGA IAH N15710 -2
# ℹ more rows
A database table is lazy. Each verb builds a description of the query. Printing executes the query but fetches only enough rows for a preview.
Building a pipeline lets the database combine and optimize the operations.
We use collect() to bring the full result into R as a tibble, or pull() to retrieve a single column.
show_query()show_query() can be used to print the query that will be sent.
Join verbs work between tables in the same database and translate to SQL JOIN clauses.
# A query: ?? x 2
# Database: DuckDB [flights.duckdb]
# Ordered by: desc(n)
name n
<chr> <dbl>
1 United Air Lines Inc. 58665
2 JetBlue Airways 54635
3 ExpressJet Airlines Inc. 54173
4 Delta Air Lines Inc. 48110
5 American Airlines Inc. 32729
6 Envoy Air 26397
# ℹ more rows
A grouped mutate() or filter() needs a per group value on every row. SQL does this with window functions, an aggregate followed by an OVER (PARTITION BY ...) clause.
# A query: ?? x 6
# Database: DuckDB [flights.duckdb]
origin dest carrier tailnum arr_delay n
<chr> <chr> <chr> <chr> <dbl> <dbl>
1 EWR IAH UA N14228 11 7198
2 LGA IAH UA N24211 20 7198
3 JFK MIA AA N619AA 33 11728
4 JFK BQN B6 N804JB -18 896
5 LGA ATL DL N668DN -25 17215
6 EWR ORD UA N39463 12 17283
# ℹ more rows
collect(), compute(), collapse()These functions control how a query is executed or composed.
collect() runs the query and returns the result as a tibble in R,
compute() runs the query and stores the result in a temporary table in the database, returning a reference to it. Use it when an expensive intermediate result is reused by several later queries,
collapse() runs nothing but wraps the query so far in a subquery, which is occasionally needed to control how later verbs are translated.
Because the work happens in the database, a database table cannot be combined directly with a local data frame.
The join verbs can copy the local table into the database for you with copy = TRUE, or use copy_to() to do it yourself first.
dbplyr translates many common vector functions from base R, stringr, and lubridate into SQL. Support depends on the database backend.
translate_sql() lets you see the translation of an expression on its own.
<SQL> x IN ('a', 'b') AND y > 10.0
<SQL> CASE WHEN (x > 0.0) THEN 'late' WHEN NOT (x > 0.0) THEN 'on time' END
<SQL> REGEXP_MATCHES(x, '^N1')
<SQL> EXTRACT(year FROM x)
The connection matters since the translation is specific to the engine. dbplyr ships simulate_*() connections for checking a translation without connecting to an actual database.
When dbplyr meets a function it does not know, it passes the call through unchanged, and leaves it to the database to decide whether it makes sense.
Running this query is an error, since DuckDB has no foo(). The flip side is that any function the database does have can be called from dplyr without a translation, like DuckDB’s regexp_extract().
Database tables have no intrinsic row order, so slice(), slice_head(), and slice_tail() are unavailable. head(), slice_min(), slice_max(), and slice_sample() all work, and arrange() before head() gives an ordered result.
Translation can also change behavior - SQL aggregates such as AVG() and SUM() ignore NULL values, so dbplyr warns when translating mean() without na.rm = TRUE. Supplying it acknowledges that behavior and silences the warning.
Using flights_tbl and planes_tbl, answer the following with dplyr. For each, look at the result of show_query() and identify which verbs produced which clauses.
For each origin airport, which destination received the most flights and how many were there?
Which five manufacturers’ planes flew the most flights? Report the number of flights and the mean departure delay for each.
Repeat question 2 without the five row limit, keeping only manufacturers with at least 30,000 flights. Where does this condition appear in the SQL?
pl.sql()polars has a SQL interface that compiles a query into the same lazy plan as the expression API. pl.sql() looks up each table name among the frames in scope and returns a LazyFrame.
Polars parses SQL into expressions for its own execution engine. In this example, SQL and the equivalent method chain produce the same plan apart from an integer cast. This reverses the direction of dbplyr, which turns dplyr into SQL for a database to run.
The polars SQL dialect covers the core of a SELECT query (WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, joins, subqueries, CASE, common table expressions (WITH), window functions) and a few hundred functions for strings, dates, and regular expressions.
Unknown functions are an error because there is no database behind the query to interpret them. Polars SQL also supports operations such as DELETE, which returns the remaining rows without modifying the original frame.
A database combines storage structures and a query planner to execute queries efficiently and avoid unnecessary reads. SQL is the standard language for asking it questions.
DBI is the R interface to any relational database. Use dbGetQuery() for queries, dbExecute() for statements that modify the database, and ? placeholders for values rather than pasting them into the query.
dbplyr lets dplyr verbs run against a database table. Queries are lazy and translated to SQL, show_query() reveals the translation, and collect() brings the result into R.
dbplyr translates many common vector functions from base R, stringr, and lubridate into SQL. Support depends on the database backend. Unknown functions are passed through to the database, which makes any database function usable but means mistakes surface only when the query runs.
polars goes the other direction, compiling SQL into the same lazy plan as its expression API, so SQL and methods can be mixed freely in a single pipeline.
Sta 523 - Fall 2026