Today we will focus on the basics of using SQL to retrieve and
manipulate information stored in a database. Many of the operations we
will perform today are analogous to operations we have already learned
using dplyr.
# we will need all of these eventually
library(DBI)
library(odbc)
library(RMySQL)
library(tidyverse)
library(dbplyr)
When working with databases, we normally use Structured Query
Language, or SQL. SQL is a language used to retrieve, manipulate,
and manage information stored in databases (often stored on servers, not
just locally). There are a number of different implementations of SQL,
but they share many of the same standard commands. We will be using
mySQL.
As a data scientist, unless you are maintaining a database, you will rarely use SQL by itself. Instead, you will normally use it as part of a workflow in another language, such as R or Python. For this reason, we will be learning how to utilize SQL through R packages.
Today we will focus exclusively on retrieving information from an existing database rather than making changes to the database itself.
A basic SQL query might look like the following:
SELECT date, id FROM orders WHERE id < 10;
This query retrieves the columns date and
id from the orders table for all observations
where id is less than 10.
There are a few conventions and differences from R worth noting:
SELECT, FROM,
WHERE, etc.) are written in uppercase, while table and
column names are generally written in lowercase.;) is used to indicate the end of a SQL
statement.Unlike many of the functions we have used in R, SQL queries are constructed using a series of clauses rather than a series of function calls. Although we do not need to put each clause on its own line, doing so often makes our queries easier to read. For example, we could rewrite the previous query as:
SELECT date, id
FROM orders
WHERE id < 10;
We will use the dbConnect() function to establish a
connection to an existing database. This requires us to specify
information about the database, including its location and our login
credentials. Take a look at the following requirements.
Student (Read only, Campus only) Credentials, only accessible from the Grinnell Wireless internet:
db_user = 'studentUser'
db_password = 'STAread!'
db_name = 'Test'
db_host = 'aiken.cs.grinnell.edu'
db_port = 3306
mydb = dbConnect(MySQL(), user = db_user, password = db_password,
dbname = db_name, host = db_host, port = db_port)
Note: If for some reason the mydb
connect does not work when running the above code, run the following in
your R console and try again.
Sys.setenv(MARIADB_TLS_DISABLE_PEER_VERIFICATION = 1) # only ever seen this necessary on MAC
The object mydb represents our connection to the
database. We will use this object whenever we want to interact with the
database.
There are a few useful functions in the DBI package:
dbListTables(): List the tables available in a
database.dbListFields(): List the columns available in a
particular table.dbGetQuery(): Retrieve information from a database
using a SQL query.dbExecute(): Execute SQL statements that make changes
to a database. (You do not have access to this for hopefully obvious
reasons!)For today, we will primarily be using dbGetQuery(). The
general format is dbGetQuery(mydb, "SQL query"). Notice
that the entire SQL query is enclosed in double quotation marks because
we are passing it to an R function as a character string.
Within the query itself, we will use single quotation marks for
character values.
We can see what tables exist in our database using:
dbListTables(mydb)
## [1] "course" "course_offering" "customers" "office_hours"
## [5] "orders" "professor_info" "syllabus_info" "week9courses"
## [9] "week9departments" "week9profcourses" "week9professors"
We can also examine what columns exist in a particular table without retrieving all of its data.
dbListFields(mydb, "orders")
## [1] "order" "id" "date"
dbListFields(mydb, "customers")
## [1] "id" "name"
Note that this is not necessarily the best-designed database, since there are many practice tables in here for you all to work with, and not all are related to each other.
Question 1: Identify the four tables in the database
whose names begin with week9. What variables are contained
in each of these tables?
The two most fundamental clauses in a SQL query are
SELECT and FROM.
SELECT specifies which columns we want to
retrieve.FROM specifies which table we want to retrieve them
from.The * symbol is a wildcard that can be used to select
all columns in a table.
dbGetQuery(mydb, "SELECT * FROM customers;")
## id name
## 1 4 Tukey
## 2 8 Wickham
## 3 15 Mason
## 4 16 Jordan
## 5 23 Patil
## 6 42 Cox
dbGetQuery(mydb, "SELECT * FROM orders;")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 3 42 Apr-15
## 4 4 50 Apr-17
## 5 11 4 Apr-18
## 6 12 8 Feb-11
## 7 13 42 Jul-15
## 8 14 50 Jun-17
If we only want certain columns from a table, we can specify their
names instead of using *.
dbGetQuery(mydb, "SELECT date, id
FROM orders;")
## date id
## 1 Jan-01 4
## 2 Feb-01 8
## 3 Apr-15 42
## 4 Apr-17 50
## 5 Apr-18 4
## 6 Feb-11 8
## 7 Jul-15 42
## 8 Jun-17 50
This operation is analogous to using select() in
dplyr. As with select(), we can also specify
the order in which we want the columns to appear.
dbGetQuery(mydb, "SELECT id, date
FROM orders;")
## id date
## 1 4 Jan-01
## 2 8 Feb-01
## 3 42 Apr-15
## 4 50 Apr-17
## 5 4 Apr-18
## 6 8 Feb-11
## 7 42 Jul-15
## 8 50 Jun-17
The LIMIT clause allows us to restrict the number of
rows returned by a query.
dbGetQuery(mydb, "SELECT *
FROM orders
LIMIT 5;")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 3 42 Apr-15
## 4 4 50 Apr-17
## 5 11 4 Apr-18
This is particularly useful when working with large databases. Rather than retrieving an entire table just to examine its contents, we can retrieve a small number of observations.
Question 2: Write queries to return three rows from
each of the four tables whose names begin with week9.
Describe the tables and what you think they represent. What benefits
might there be to using LIMIT when working with large
databases?
Sometimes we may want the columns in our resulting table to have
different names than those used in the original database. We can
accomplish this using the AS keyword.
dbGetQuery(mydb, "SELECT id AS CustomerID, date
FROM orders;")
## CustomerID date
## 1 4 Jan-01
## 2 8 Feb-01
## 3 42 Apr-15
## 4 50 Apr-17
## 5 4 Apr-18
## 6 8 Feb-11
## 7 42 Jul-15
## 8 50 Jun-17
We can rename multiple columns within the same query.
dbGetQuery(mydb, "SELECT id AS CustomerID,
date AS OrderDate
FROM orders;")
## CustomerID OrderDate
## 1 4 Jan-01
## 2 8 Feb-01
## 3 42 Apr-15
## 4 50 Apr-17
## 5 4 Apr-18
## 6 8 Feb-11
## 7 42 Jul-15
## 8 50 Jun-17
These temporary names are referred to as aliases. An alias changes the name of a column in the result of our query, but does not change the name of the column in the original database.
For example, if we run the following query again, we will see that the original column names have not changed.
dbGetQuery(mydb, "SELECT id, date
FROM orders;")
## id date
## 1 4 Jan-01
## 2 8 Feb-01
## 3 42 Apr-15
## 4 50 Apr-17
## 5 4 Apr-18
## 6 8 Feb-11
## 7 42 Jul-15
## 8 50 Jun-17
The DISTINCT keyword allows us to retrieve unique values
from a table. For example, the orders table may contain
multiple orders placed by the same customer. If we only want to know
which customers have placed orders, we can use:
dbGetQuery(mydb, "SELECT DISTINCT id
FROM orders;")
## id
## 1 4
## 2 8
## 3 42
## 4 50
We can also use DISTINCT when selecting multiple
columns. In this case, SQL will return the unique combinations of values
across those columns.
dbGetQuery(mydb, "SELECT DISTINCT id, date
FROM orders;")
## id date
## 1 4 Jan-01
## 2 8 Feb-01
## 3 42 Apr-15
## 4 50 Apr-17
## 5 4 Apr-18
## 6 8 Feb-11
## 7 42 Jul-15
## 8 50 Jun-17
This operation is analogous to using distinct() in
dplyr.
Question 3: Using the week9professors
table, write SQL queries to accomplish the following:
pid) and department IDs (did).ProfessorID and DepartmentID.The WHERE clause allows us to specify conditions that
must be satisfied for a row to be included in the result of a query.
This is analogous to using filter() in
dplyr.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id < 10;")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 11 4 Apr-18
## 4 12 8 Feb-11
We can combine WHERE with the other operations we have
learned so far.
dbGetQuery(mydb, "SELECT DISTINCT id AS CustomerID
FROM orders
WHERE id < 10;")
## CustomerID
## 1 4
## 2 8
Many of the comparison operators used in SQL are similar to those we have used in R.
| Operator | Description |
|---|---|
= |
Equal to |
!= or <> |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
Note that, unlike in R, we use a single = when checking
for equality.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id = 3;")
## [1] order id date
## <0 rows> (or 0-length row.names)
We can specify multiple conditions within a WHERE clause
using AND, OR, and NOT. These
work similarly to the logical operators &,
|, and ! in R.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id >= 3 AND id <= 7;")
## order id date
## 1 1 4 Jan-01
## 2 11 4 Apr-18
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id = 3 OR id = 7;")
## [1] order id date
## <0 rows> (or 0-length row.names)
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE NOT id = 3;")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 3 42 Apr-15
## 4 4 50 Apr-17
## 5 11 4 Apr-18
## 6 12 8 Feb-11
## 7 13 42 Jul-15
## 8 14 50 Jun-17
As in R, we can use parentheses to specify how multiple conditions should be combined.
The IN keyword allows us to check whether a value
matches any value in a specified list. This is analogous to using
%in% in R.
Rather than writing:
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id = 1 OR id = 3 OR id = 5;")
## [1] order id date
## <0 rows> (or 0-length row.names)
We could instead write:
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id IN (1, 3, 5);")
## [1] order id date
## <0 rows> (or 0-length row.names)
We can also use NOT IN to exclude observations with any
of the specified values.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id NOT IN (1, 3, 5);")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 3 42 Apr-15
## 4 4 50 Apr-17
## 5 11 4 Apr-18
## 6 12 8 Feb-11
## 7 13 42 Jul-15
## 8 14 50 Jun-17
The BETWEEN keyword allows us to select observations
whose values fall within a specified range, including both
endpoints.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id BETWEEN 3 AND 7;")
## order id date
## 1 1 4 Jan-01
## 2 11 4 Apr-18
This is equivalent to:
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE id >= 3 AND id <= 7;")
## order id date
## 1 1 4 Jan-01
## 2 11 4 Apr-18
Question 4: Write SQL queries to accomplish the following:
When filtering based on character values, we can use =
to match a specific value.
dbGetQuery(mydb, "SELECT *
FROM week9departments
WHERE depname = 'Chemistry';")
## did depname
## 1 CHM Chemistry
Notice that we use single quotation marks around
'Chemistry' within the SQL query, while the entire query is
enclosed in double quotation marks in R.
However, sometimes we may only know part of the character value we
are interested in. The LIKE keyword allows us to filter
observations based on a pattern.
There are two commonly used wildcards when working with
LIKE:
| Wildcard | Description |
|---|---|
% |
Any number of characters (including zero) |
_ |
Exactly one character |
For example, the following query retrieves departments whose names begin with the letter C.
dbGetQuery(mydb, "SELECT *
FROM week9departments
WHERE depname LIKE 'C%';")
## did depname
## 1 CHM Chemistry
## 2 CSC Computer Science
We can change the location of the wildcard depending on the pattern we want to match.
| Pattern | Matches |
|---|---|
'C%' |
Values beginning with C |
'%s' |
Values ending with s |
'%math%' |
Values containing math |
'C_' |
Two-character values beginning with C |
We can also use NOT LIKE to exclude observations that
match a particular pattern.
In R, we typically represent missing values using NA. In
SQL, missing values are represented using NULL.
To identify observations with missing values, we use
IS NULL.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE date IS NULL;")
## [1] order id date
## <0 rows> (or 0-length row.names)
Similarly, to retrieve observations that do not have missing values,
we use IS NOT NULL.
dbGetQuery(mydb, "SELECT *
FROM orders
WHERE date IS NOT NULL;")
## order id date
## 1 1 4 Jan-01
## 2 2 8 Feb-01
## 3 3 42 Apr-15
## 4 4 50 Apr-17
## 5 11 4 Apr-18
## 6 12 8 Feb-11
## 7 13 42 Jul-15
## 8 14 50 Jun-17
These operations are analogous to using is.na() and
!is.na() in R.
Question 5: Write SQL queries to accomplish the following:
The ORDER BY clause allows us to sort the results of a
query based on one or more columns. This is analogous to using
arrange() in dplyr.
By default, SQL sorts values in ascending order.
dbGetQuery(mydb, "SELECT *
FROM orders
ORDER BY id;")
## order id date
## 1 1 4 Jan-01
## 2 11 4 Apr-18
## 3 2 8 Feb-01
## 4 12 8 Feb-11
## 5 3 42 Apr-15
## 6 13 42 Jul-15
## 7 4 50 Apr-17
## 8 14 50 Jun-17
We can explicitly specify whether we want to sort in ascending
(ASC) or descending (DESC) order.
dbGetQuery(mydb, "SELECT *
FROM orders
ORDER BY id DESC;")
## order id date
## 1 4 50 Apr-17
## 2 14 50 Jun-17
## 3 3 42 Apr-15
## 4 13 42 Jul-15
## 5 2 8 Feb-01
## 6 12 8 Feb-11
## 7 1 4 Jan-01
## 8 11 4 Apr-18
We can also sort by multiple columns, specifying a different direction for each column if desired.
dbGetQuery(mydb, "SELECT *
FROM orders
ORDER BY id ASC, date DESC;")
## order id date
## 1 1 4 Jan-01
## 2 11 4 Apr-18
## 3 12 8 Feb-11
## 4 2 8 Feb-01
## 5 13 42 Jul-15
## 6 3 42 Apr-15
## 7 14 50 Jun-17
## 8 4 50 Apr-17
In this example, we first sort the observations by customer ID in ascending order. Among observations with the same customer ID, we then sort by date in descending order.
Combining LIMIT with ORDER BY allows us to
retrieve observations with the largest or smallest values of a
particular variable.
For example, the following query retrieves the five most recent orders.
dbGetQuery(mydb, "SELECT *
FROM orders
ORDER BY date DESC
LIMIT 5;")
## order id date
## 1 14 50 Jun-17
## 2 13 42 Jul-15
## 3 1 4 Jan-01
## 4 12 8 Feb-11
## 5 2 8 Feb-01
Question 6: Write SQL queries to accomplish the following:
So far, we have introduced a number of different SQL clauses. Unlike
a dplyr pipeline, in which we can specify operations in a
variety of orders, SQL requires that these clauses appear in a
particular order.
The general structure of the queries we have worked with today is:
SELECT column(s)
FROM table
WHERE condition(s)
ORDER BY column(s)
LIMIT number;
We do not need to include every clause in every query. However, when we do use multiple clauses, they must appear in the order shown above.
For example:
dbGetQuery(mydb, "SELECT id AS CustomerID, date AS OrderDate
FROM orders
WHERE id BETWEEN 3 AND 7
ORDER BY date DESC
LIMIT 5;")
## CustomerID OrderDate
## 1 4 Jan-01
## 2 4 Apr-18
This query retrieves up to five of the most recent orders associated with customers whose IDs are between 3 and 7, keeping and renaming only the columns we are interested in.
For reference, the following table summarizes many of the SQL operations we have introduced today and their corresponding R operations.
| SQL | R / dplyr |
|---|---|
SELECT |
select() |
AS |
rename() |
DISTINCT |
distinct() |
WHERE |
filter() |
AND, OR, NOT |
&, \|, ! |
IN |
%in% |
BETWEEN |
between() |
LIKE |
str_detect() |
IS NULL |
is.na() |
ORDER BY |
arrange() |
LIMIT |
head() |
So far, we have simply been printing the results of our SQL queries. We can also save the results of a query as an R dataframe by assigning them to an object.
exampleQuery = dbGetQuery(mydb, "SELECT id AS CustomerID, date
FROM orders
ORDER BY date DESC
LIMIT 5;")
print(exampleQuery)
## CustomerID date
## 1 50 Jun-17
## 2 42 Jul-15
## 3 4 Jan-01
## 4 8 Feb-11
## 5 8 Feb-01
Once we have retrieved information from the database and stored it as a dataframe, we can work with it using any of the R functions we have learned throughout the semester.
dim(exampleQuery)
## [1] 5 2
names(exampleQuery)
## [1] "CustomerID" "date"
str(exampleQuery)
## 'data.frame': 5 obs. of 2 variables:
## $ CustomerID: int 50 42 4 8 8
## $ date : chr "Jun-17" "Jul-15" "Jan-01" "Feb-11" ...
Changes we make to this dataframe in R do not change the information stored in the original database.
Question 7: Write SQL queries to retrieve all four
week9 tables and store them as R dataframes
with the same names as their corresponding tables in the database.
Question 8: Using the week9departments
table, complete the following:
DepartmentID and
DepartmentName, and sort the results alphabetically by
department name.dplyr.When we are finished working with a database, we should disconnect
from it using the dbDisconnect() function.
dbDisconnect(mydb)
## [1] TRUE
More will be added on Wednesday