3  Importing Data from SQL

Setup Code (Click to Expand)
# packages needed to run the code in this section
# install.packages(c("DBI", "ODBC", "dplyr"))

One of the first tasks you will need to do with any analysis is loading in the data. While you may have data from a variety of sources, the most common will be in a SQL database.

Here we will cover how to access a SQL database and extract data in R.

3.1 Packages

The R packages you need to interact with SQL are:

  • DBI
  • ODBC

I won’t import either package here because they are only needed for a handful of functions.

3.2 Establish SQL Connection

con <- DBI::dbConnect(
  odbc::odbc(),
  driver = 'SQL Server',
  server = '{db-server}',
  database = '{db-name}',
  trustedconnection = TRUE
)

3.3 Running SQL Query

df <- DBI::dbGetQuery(
  con,
  'SELECT col_1,
          col_2,
          col_3
  FROM    db_name.table_name'
)
head(df)

dplyr::glimpse(df)

3.4 Export to CSV

readr::write_csv(df, here::here('path-to-save-df', 'df.csv'))