ZetCode

R SQL databases

last modified November 19, 2026

A relational database stores data in tables and answers questions written in SQL. R talks to databases through DBI, a small interface package that defines functions such as dbConnect, dbGetQuery, and dbWriteTable. The actual connection is provided by a driver package; this article uses RSQLite, which embeds the SQLite engine and needs no server. The examples build an in-memory database, write data frames into it, query and modify the rows, wrap changes in transactions, and translate dplyr verbs into SQL with dbplyr. They use R 4.5.2 with DBI 1.3.0, RSQLite 3.53.3, and dbplyr 2.6.0.

The examples need the DBI, RSQLite, dplyr, and dbplyr packages, which are not part of base R. Install them once with install.packages(c("DBI", "RSQLite", "dplyr", "dbplyr")); the installing packages section of the introduction explains the details.

Connecting to a database

dbConnect opens a connection and returns a driver-specific object. The first argument selects the driver; RSQLite::SQLite() creates one without attaching the package. The special file name ":memory:" keeps the database in RAM, so it disappears when the connection closes, which is convenient for experiments. dbExecute runs a statement that returns no rows, and dbListTables lists the tables in the connected database.

connect.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
cat("class:", class(con)[1], "\n")
cat("RSQLite:", as.character(packageVersion("RSQLite")), "\n")
created <- dbExecute(
  con,
  "CREATE TABLE students (id INTEGER, name TEXT, score REAL)"
)
cat("statements:", created, "\n")
cat("tables:", dbListTables(con), "\n")
dbDisconnect(con)

The connection belongs to the SQLiteConnection class, and the driver reports its version through packageVersion. The CREATE TABLE statement affects no rows, so dbExecute returns zero, and the new table appears in the list. dbDisconnect closes the connection; a script should call it even when the database is only in memory, because it releases the file handles and locks that a real database would hold.

$ Rscript connect.R
class: SQLiteConnection 
RSQLite: 3.53.3 
statements: 0 
tables: students 

Writing a data frame to a table

dbWriteTable creates a table from a data frame, mapping R types to SQL types: integer columns become INTEGER, character columns become TEXT, and double columns become REAL. The table name is the second argument, and dbReadTable reads the whole table back into a data frame. This pair moves a small table in both directions without writing any SQL.

write-table.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
students <- data.frame(
  id = 1:4,
  name = c("Ada", "Bob", "Grace", "Alan"),
  score = c(91, 78, 88, 64)
)
dbWriteTable(con, "students", students)
print(dbReadTable(con, "students"))
count <- dbGetQuery(con, "SELECT COUNT(*) AS n FROM students")
cat("rows:", count$n, "\n")
dbDisconnect(con)

The four rows arrive in the same order and with the same values, and the COUNT(*) query confirms the row count. A data frame is a natural staging area: data read from a CSV file or produced by a model can be written straight into a table. For a large frame, dbWriteTable also accepts append = TRUE to add rows to an existing table instead of replacing it.

$ Rscript write-table.R
  id  name score
1  1   Ada    91
2  2   Bob    78
3  3 Grace    88
4  4  Alan    64
rows: 4 

Querying with SQL

dbGetQuery runs a SELECT statement and returns the result as a data frame, with one column per selected expression and the SQL types converted back to R types. The statement can span several lines inside a single string, which keeps a longer query readable. dbListFields reports the columns of a table without fetching any rows.

query.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
students <- data.frame(
  id = 1:5,
  name = c("Ada", "Bob", "Grace", "Alan", "Mia"),
  score = c(91, 78, 88, 64, 95),
  city = c("Bratislava", "Kosice", "Bratislava", "Zilina", "Kosice")
)
dbWriteTable(con, "students", students)
top <- dbGetQuery(con, "
  SELECT name, score
  FROM students
  WHERE score >= 80
  ORDER BY score DESC
")
print(top)
cat("columns:", dbListFields(con, "students"), "\n")
dbDisconnect(con)

The WHERE clause keeps the three students with a score of at least eighty, and ORDER BY score DESC puts the highest score first. The identifier and city columns are not selected, so they do not appear in the result. dbListFields returns all four columns of the stored table, which is a quick way to check a schema before writing a query.

$ Rscript query.R
   name score
1   Mia    95
2   Ada    91
3 Grace    88
columns: id name score city 

Parameterised queries

Building SQL by pasting values into a string is fragile: a quote in a name breaks the statement, and user input can change the meaning of the query. DBI supports placeholders written as ?, and the params argument supplies the values separately. The driver quotes and escapes each value, so the statement structure stays fixed no matter what the data contains. The same mechanism works for INSERT and other statements that do not return rows.

parameters.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
students <- data.frame(
  id = 1:4,
  name = c("Ada", "Bob", "Grace", "Alan"),
  score = c(91, 78, 88, 64)
)
dbWriteTable(con, "students", students)
threshold <- 80
above <- dbGetQuery(con,
  "SELECT name, score FROM students WHERE score > ? ORDER BY name",
  params = list(threshold))
print(above)
new <- data.frame(id = 5, name = "Mia", score = 95)
dbExecute(con,
  "INSERT INTO students (id, name, score) VALUES (?, ?, ?)",
  params = unname(as.list(new)))
cat("rows now:", dbGetQuery(con, "SELECT COUNT(*) AS n FROM students")$n, "\n")
dbDisconnect(con)

The threshold arrives as the first placeholder value, and the two students above eighty are returned in name order. The new row is inserted with three placeholders; as.list(new) turns the one-row data frame into a list of three scalars, and unname removes the column names so that only the values are passed. The final count is five. SQLite numbers its placeholders with ?; other drivers use $1 or :name, which DBI also accepts.

$ Rscript parameters.R
   name score
1   Ada    91
2 Grace    88
[1] 1
rows now: 5 

Updating and deleting rows

dbExecute also runs UPDATE and DELETE, and it returns the number of rows that the statement changed. That count is the quickest check that a WHERE clause matched what the author expected. Both statements are dangerous without a condition: an UPDATE without WHERE rewrites every row, and a DELETE without one empties the table.

change-rows.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
students <- data.frame(
  id = 1:5,
  name = c("Ada", "Bob", "Grace", "Alan", "Eva"),
  score = c(91, 78, 88, 64, 55)
)
dbWriteTable(con, "students", students)
changed <- dbExecute(con,
  "UPDATE students SET score = ? WHERE name = ?",
  params = list(85, "Alan"))
cat("updated:", changed, "\n")
removed <- dbExecute(con,
  "DELETE FROM students WHERE score < ?",
  params = list(70))
cat("removed:", removed, "\n")
print(dbGetQuery(con, "SELECT name, score FROM students ORDER BY id"))
dbDisconnect(con)

The update changes exactly one row, Alan's score, and the delete removes the single student below seventy, Eva. The remaining four rows keep their original order from the ORDER BY id, and Alan now sits at eighty-five. If a statement modifies the wrong number of rows, a transaction from the next section can undo it before the change is committed.

$ Rscript change-rows.R
updated: 1 
removed: 1 
   name score
1   Ada    91
2   Bob    78
3 Grace    88
4  Alan    85

Transactions

A transaction groups several statements into one unit. dbBegin starts it, dbCommit makes the changes permanent, and dbRollback discards everything since the beginning. A database that supports transactions guarantees that a committed group is either fully applied or not applied at all, even if the process fails in the middle. In SQLite, changes are private to the connection until the commit.

transactions.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
invisible(dbExecute(con, "CREATE TABLE log (id INTEGER, note TEXT)"))
insert_note <- function(id, note) {
  invisible(dbExecute(con, "INSERT INTO log (id, note) VALUES (?, ?)",
                      params = list(id, note)))
}
dbBegin(con)
insert_note(1, "first")
insert_note(2, "second")
dbRollback(con)
cat("after rollback:", dbGetQuery(con, "SELECT COUNT(*) AS n FROM log")$n, "\n")
dbBegin(con)
insert_note(1, "first")
dbCommit(con)
cat("after commit:", dbGetQuery(con, "SELECT COUNT(*) AS n FROM log")$n, "\n")
dbDisconnect(con)

The first transaction inserts two notes and rolls them back, so the table is empty when the count is printed. The second transaction inserts one note and commits it, so the final count is one. The helper wraps dbExecute in invisible to keep the row counts out of the console. A real application would roll back when a statement fails instead of committing the partial work.

$ Rscript transactions.R
after rollback: 0 
after commit: 1 

Queries with dbplyr

dbplyr translates dplyr verbs into SQL. tbl creates a lazy reference to a table: the verbs build a query plan, show_query prints the SQL that the plan would run, and collect executes it and returns a tibble. Nothing is sent to the database until collect, so a long pipeline can be inspected and corrected before it runs.

dbplyr.R
library(DBI)
suppressPackageStartupMessages(library(dplyr))
suppressPackageStartupMessages(library(dbplyr))
con <- dbConnect(RSQLite::SQLite(), ":memory:")
students <- data.frame(
  id = 1:4,
  name = c("Ada", "Bob", "Grace", "Alan"),
  score = c(91, 78, 88, 64)
)
dbWriteTable(con, "students", students)
table_ref <- tbl(con, "students")
result <- table_ref |>
  filter(score >= 80) |>
  select(name, score) |>
  arrange(desc(score))
show_query(result)
print(collect(result))
dbDisconnect(con)

The translated query selects two columns, filters on the score, and sorts the result. dbplyr quotes identifiers with backticks and writes the numeric constant as 80.0; both are details of the SQLite dialect that the package handles automatically. collect returns the same two rows that the hand-written query produced, now as a tibble. The advantage grows with the pipeline: joins, grouped summaries, and window functions translate in the same way.

$ Rscript dbplyr.R
<SQL>
SELECT `name`, `score`
FROM `students`
WHERE (`score` >= 80.0)
ORDER BY `score` DESC
# A tibble: 2 × 2
  name  score
  <chr> <dbl>
1 Ada      91
2 Grace    88

A complete example

The final script stores a small sales table and asks the database for revenue per region. The query multiplies quantity by price inside SUM, groups the rows by region, and orders the groups by the computed total. The result is written back as a new table, which is how a report can be cached for another process or another session.

report.R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
sales <- data.frame(
  product = c("pen", "pen", "book", "book", "bag", "bag"),
  region = c("west", "east", "west", "east", "west", "east"),
  qty = c(10, 4, 3, 6, 2, 1),
  price = c(2.5, 2.5, 12, 12, 30, 30)
)
dbWriteTable(con, "sales", sales)
report <- dbGetQuery(con, "
  SELECT region,
         SUM(qty) AS units,
         SUM(qty * price) AS revenue
  FROM sales
  GROUP BY region
  ORDER BY revenue DESC
")
print(report)
cat("total:", sum(report$revenue), "\n")
dbWriteTable(con, "region_report", report, overwrite = TRUE)
cat("tables:", dbListTables(con), "\n")
dbDisconnect(con)

The west region sold fifteen units for 121, and the east region sold eleven units for 112, for a total of 233. The result already has the final column names, so dbWriteTable stores it without further preparation, and dbListTables shows both the source table and the report. The same pattern works for a much larger table: let the database do the aggregation and bring back only the summary.

$ Rscript report.R
  region units revenue
1   west    15     121
2   east    11     112
total: 233 
tables: region_report sales 

Next steps

The data I/O article covers CSV and RDS files, which are the right choice for a single user and a small table, and the JSON article covers the format that most web APIs return. The dplyr article explains the verbs that dbplyr translates, and the packages article shows how to install and report the versions of DBI and a driver. For a database that runs as a server, the same code works after replacing the driver and the connection arguments.

Source

DBI: R database interface

RSQLite on CRAN

dbplyr: a dplyr backend for databases

DBI specification

In this article we connected to an in-memory SQLite database, wrote a data frame into a table, and read it back. We ran hand-written queries, passed values through placeholders, updated and deleted rows, and grouped statements in transactions. dbplyr translated a dplyr pipeline into SQL and collected the result, and the final script aggregated a sales table and stored the report. The series continues with R web scraping.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.