---
title: "DATA-412/612: Databases and dbplyr — Practice Questions"
subtitle: "Guided exercises with answers after each question"
author: "Course practice worksheet"
format:
  html:
    toc: true
    toc-depth: 2
    code-fold: false
    number-sections: true
execute:
  eval: false
  warning: false
  message: false
---

## Learning objectives

By the end of this worksheet, you should be able to connect to a SQLite database, inspect its tables, use `dplyr` verbs on database-backed tables, understand lazy queries, use `collect()` appropriately, join tables by identifiers, and produce a time-series visualization.

### Preparation

Download and unzip the European soccer database from Canvas (or the [course data page](https://dcgerard.github.io/stat_412_612/data.html)). Place `soccer.sqlite` under `data/soccer/` relative to your `.qmd` file, or update the path below. Install the packages once if necessary.

```{r}
# Install once in the R console, if needed:
# install.packages(c("DBI", "RSQLite", "dplyr", "dbplyr", "tidyr", "readr", "ggplot2"))

library(DBI)
library(RSQLite)
library(dplyr)   # tbl(), select(), filter(), etc.
library(dbplyr) # translation of dplyr commands to SQL
library(tidyr)  # pivot_longer()
library(readr)  # parse_date()
library(ggplot2)

db_path <- "data/soccer/soccer.sqlite"
stopifnot(file.exists(db_path))  # Avoid silently creating an empty SQLite file.
con <- dbConnect(SQLite(), dbname = db_path)
```

**Key idea:** R/RStudio → `dplyr` → `dbplyr` (SQL translation) → DBI / RSQLite (connection) → SQLite (query engine) → `soccer.sqlite` (data file). A database-backed `tbl()` is a lazy table reference, *not* an ordinary in-memory data frame.

## Part A. Connect to and inspect the database

### Question 1 — Understand the components

In one or two sentences each, distinguish **SQLite**, **`soccer.sqlite`**, **RSQLite**, **DBI**, **dbplyr**, and **dplyr**. Which component actually executes SQL queries?

**Answer:** SQLite is the database engine; `soccer.sqlite` is the file containing the tables; `RSQLite` implements the SQLite driver in R; `DBI` supplies the database interface; `dbplyr` translates `dplyr` operations into SQL; and `dplyr` provides data manipulation functions. **SQLite executes the SQL.**

### Question 2 — Explore available tables

Using the connection `con`:

1. List the names of all tables in the soccer database.
2. Check whether the tables `Team`, `Match`, and `Country` exist.
3. How many tables does the database report? (Include SQLite's internal tables, if present.)

Use `dbListTables()` and R operations on its result. Do **not** import whole tables.

**Answer:**

```{r}
tables <- dbListTables(con)
tables
all(c("Team", "Match", "Country") %in% tables)
length(tables)
```

The lecture database typically includes the seven soccer tables and the internal `sqlite_sequence` table. The exact count comes from `dbListTables(con)`.

### Question 3 — Make lazy references

Create the following objects using `tbl()`:

- `Team_db` referring to `Team`
- `Country_db` referring to `Country`
- `League_db` referring to `League`
- `Match_db` referring to `Match`

Then display the first six rows of `Country_db`. Explain why `Match_db` is **not** a regular data frame.

**Answer:**

```{r}
Team_db    <- tbl(con, "Team")
Country_db <- tbl(con, "Country")
League_db  <- tbl(con, "League")
Match_db   <- tbl(con, "Match")
head(Country_db)
```

`tbl(con, ...)` creates a lazy reference to a database table. It does not download the entire table into R.

### Question 4 — Investigate columns

Without calling `collect()` on the complete table:

1. Display the column names of `Match_db`.
2. Select columns from `id` through `away_team_goal` (inclusive).
3. Display the first ten rows of that selection.

Do not access undocumented internal fields such as `$ops$vars`; use a supported function for column names.

**Answer:**

```{r}
colnames(Match_db)
match_cols <- Match_db %>% select(id:away_team_goal)
head(match_cols, 10)
```

## Part B. Query the database with dplyr

### Question 5 — Filter without downloading

Using **only the database-backed** `Match_db`, select `season`, `date`, `home_team_goal`, and `away_team_goal` for matches from the `2010/2011` season in which the home team scored **strictly more** than the away team. Save this as `home_wins_db`.

1. Display the query object.
2. Use `show_query()` to inspect the SQL generated by `dbplyr`.
3. Is the full result already in R's memory? Briefly explain.

**Answer:**

```{r}
home_wins_db <- Match_db %>%
  filter(season == "2010/2011", home_team_goal > away_team_goal) %>%
  select(season, date, home_team_goal, away_team_goal)
home_wins_db
show_query(home_wins_db)
```

`home_wins_db` represents a database query, not an in-memory copy of its full result. Displaying it fetches only a preview; `show_query()` displays the generated SQL.

### Question 6 — Summarize inside SQLite

Using `Match_db`, calculate for each `season`:

- `n_matches`: number of matches;
- `avg_home_goals`: mean home-team goals;
- `avg_away_goals`: mean away-team goals.

Sort by `season` and display the result. Keep the work in the database until you actually need the result in R.

**Answer:**

```{r}
Match_db %>%
  group_by(season) %>%
  summarise(
    n_matches = n(),
    avg_home_goals = mean(home_team_goal, na.rm = TRUE),
    avg_away_goals = mean(away_team_goal, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  arrange(season)
```

### Question 7 — Understand collect()

Starting from `home_wins_db` in Question 5:

1. Retrieve the results into R as `home_wins`.
2. Verify that `home_wins` is a data frame.
3. Report the number of rows in `home_wins`.
4. Explain the practical difference between `home_wins_db` and `home_wins`.

**Answer:**

```{r}
home_wins <- home_wins_db %>% collect()
is.data.frame(home_wins)
nrow(home_wins)
```

`home_wins_db` is a database-backed query. `home_wins` is a local tibble created when `collect()` runs the query and returns its results.

## Part C. Connect the tables

### Question 8 — Find England's Premier League ID

Using `League_db` and `Country_db`, find the `id` and `name` of the **England Premier League**, together with its country name.

Hint: The league table includes `country_id`, which corresponds to `id` in the country table. Join on these columns and be careful about duplicate `name` fields.

**Answer:**

```{r}
england_league_db <- League_db %>%
  inner_join(
    Country_db %>%
      select(country_id = id, country_name = name),
    by = "country_id"
  ) %>%
  filter(country_name == "England", name == "England Premier League") %>%
  select(league_id = id, league_name = name, country_name)

england_league_db %>% collect()
```

### Question 9 — Match IDs to team names

For matches in the `2010/2011` season, create a table with the following five columns:

- `date`
- `home_team` (full name)
- `away_team` (full name)
- `home_team_goal`
- `away_team_goal`

Join `Match_db` with `Team_db` **twice**, once for each team identifier. Display the first ten records. Can these joins be completed before `collect()`?

**Answer:**

```{r}
home_teams_db <- Team_db %>%
  select(home_team_api_id = team_api_id, home_team = team_long_name)
away_teams_db <- Team_db %>%
  select(away_team_api_id = team_api_id, away_team = team_long_name)

named_matches_db <- Match_db %>%
  filter(season == "2010/2011") %>%
  inner_join(home_teams_db, by = "home_team_api_id") %>%
  inner_join(away_teams_db, by = "away_team_api_id") %>%
  select(date, home_team, away_team, home_team_goal, away_team_goal)

named_matches_db %>% head(10)
```

Yes. The two joins can be executed by SQLite before transferring data to R.

### Question 10 — Country for each team

Starting with `Match_db`, identify all distinct pairs of `country_id` and team ID appearing as a home or away team. Join these IDs to `Team_db` and `Country_db` and return one row per unique combination of team name and country name, sorted alphabetically by team name.

**Hint:** In this question, first select only `country_id`, `home_team_api_id`, and `away_team_api_id` from `Match_db`, then use `collect()` and `pivot_longer()`. (We are deliberately practicing an in-memory reshape.)

**Answer:**

```{r}
Match_db %>%
  select(country_id, home_team_api_id, away_team_api_id) %>%
  collect() %>%
  pivot_longer(
    cols = c(home_team_api_id, away_team_api_id),
    names_to = "home_away",
    values_to = "team_api_id"
  ) %>%
  distinct(country_id, team_api_id) %>%
  left_join(Team_db %>% collect(), by = "team_api_id") %>%
  left_join(Country_db %>% collect(), by = c("country_id" = "id")) %>%
  transmute(team_long_name, country_name = name) %>%
  distinct() %>%
  arrange(team_long_name) %>%
  head()
```

## Part D. Premier League time-series exercise

### Question 11 — Daily goal difference, 2010/2011

Using the England Premier League matches in the `2010/2011` season:

1. Identify the Premier League's `league_id` from the database; do not hard-code it.
2. Keep `date`, `home_team_goal`, and `away_team_goal` for its matches.
3. Create `goal_diff = home_team_goal - away_team_goal`.
4. Convert the date-time string to a calendar `Date` (using `parse_date()` after extracting the date portion).
5. For **each calendar day**, calculate `mean_goal_diff`, the mean of `goal_diff` across matches on that day. Exclude missing goal differences if any occur.
6. Plot `mean_goal_diff` against `date` using points and a line, with an informative title and axis labels.

**Interpretation:** A positive daily value indicates that home teams scored more goals on average than away teams on that date. This is a **mean goal difference**, not a proportion.

**Answer:**

```{r}
premier_league_id <- england_league_db %>%
  select(league_id) %>%
  collect() %>%
  pull(league_id)

stopifnot(length(premier_league_id) == 1)

premier_matches <- Match_db %>%
  filter(league_id == !!premier_league_id, season == "2010/2011") %>%
  select(date, home_team_goal, away_team_goal) %>%
  collect()

daily_goal_diff <- premier_matches %>%
  mutate(
    date = readr::parse_date(substr(date, 1, 10), format = "%Y-%m-%d"),
    goal_diff = home_team_goal - away_team_goal
  ) %>%
  group_by(date) %>%
  summarise(mean_goal_diff = mean(goal_diff, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

ggplot(daily_goal_diff, aes(x = date, y = mean_goal_diff)) +
  geom_line() +
  geom_point() +
  labs(
    title = "Premier League: Daily Mean Home–Away Goal Difference (2010/2011)",
    x = "Match date",
    y = "Mean home goals minus away goals"
  ) +
  theme_minimal()
```

Positive mean goal difference means that home teams scored more goals on average on that date; negative means away teams scored more. It is not a proportion.

### Question 12 — Reason about performance

Suppose the `Match` table grows to tens of millions of rows.

1. Why might `Match_db %>% collect() %>% filter(season == "2010/2011")` be inefficient?
2. Rewrite it so that filtering occurs before downloading.
3. Which operations from Question 11 would you push to the database to reduce transferred data?

**Answer:**

```{r}
small_result <- Match_db %>%
  filter(season == "2010/2011") %>%
  select(date, home_team_goal, away_team_goal) %>%
  collect()
```

Collecting before filtering transfers unnecessary records. Apply `filter()` and `select()` in the database before `collect()`. When possible, also perform joins and summaries remotely.

### Clean up

```{r}
dbDisconnect(con)
```

### References

- [dbplyr introduction](https://dbplyr.tidyverse.org/articles/dbplyr.html)
- [DBI documentation](https://dbi.r-dbi.org/)
- [Course soccer dataset](https://dcgerard.github.io/stat_412_612/data.html)
