% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/src_dbi.R
\name{tbl.src_dbi}
\alias{tbl.src_dbi}
\alias{tbl_dbi}
\title{Create a lazy query backed by a database}
\usage{
\method{tbl}{src_dbi}(src, from, vars = NULL, ...)
}
\arguments{
\item{src}{A \code{DBIConnection} object produced by \code{\link[DBI:dbConnect]{DBI::dbConnect()}}.}

\item{from}{Either a table identifier or a literal \code{\link[=sql]{sql()}} string.

Use a string to identify a table in the current schema/catalog or
\code{I()} for a table elsewhere, e.g. \code{I("schema.table")} or
\code{I("catalog.schema.table")}. For backward compatibility, you can also use
\code{\link[=in_schema]{in_schema()}}/\code{\link[=in_catalog]{in_catalog()}} or \code{\link[DBI:Id]{DBI::Id()}}.}

\item{vars}{Optionally, provide a character vector of column names. If
not supplied, will be retrieved from the database by running a simple
query. This argument is mainly useful for better performance when creating
many \code{tbl}s with known variables.}

\item{...}{Passed on to \code{\link[=tbl_sql]{tbl_sql()}}}
}
\description{
Use \code{tbl()} to create a SQL query backed by a database. Manipulating this
object with dplyr verbs then builds up a SQL query that will only be executed
when you explicitly ask for it, either by printing the object, calling
\code{\link[dplyr:collect]{collect()}} to bring the data back to R or calling \code{\link[dplyr:compute]{compute()}} to create a
new table in the database. You can see the query without executing it with
\code{\link[=show_query]{show_query()}}.

Learn more in \code{vignette("dbplyr")}.
}
\examples{
library(dplyr)

# Connect to a temporary in-memory SQLite database and add some data
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con, mtcars)

# To retrieve a single table from a source, use `tbl()`
mtcars_db <- con |> tbl("mtcars")
mtcars_db

# Use `I()` for qualified table names
con |> tbl(I("temp.mtcars")) |> head(1)

# You can also pass raw SQL if you want a more sophisticated query
con |> tbl(sql("SELECT * FROM mtcars WHERE cyl = 8")) |> head(1)

# But in most cases, you'll rely on dbplyr to construct the SQL:
mtcars_db |>
  filter(vs == 1) |>
  summarise(mpg = mean(mpg, na.rm = TRUE), .by = cyl) |>
  show_query()

}
