Lab 11: SQL Aggregation
- Due: Wednesday 12/02 @ 11:59pm
- Points: 1
- Download: lab11.zip
Attendance
You need to submit the lab problems in addition to attending to get credit for lab. Students in mega lab only need to submit the lab problems. Preceptor interviews are highly recommended but not required for lab submissions.
If you are in regular lab, your TA will come around during lab to check you in. If you didn't attend for a good reason (such as being sick), fill out this form (within 2 weeks of your lab): attendance form.
Preceptor can help if your tests fail, but there are no Preceptor interviews for this lab.
Setup
Download lab11.zip from the link at the top of this page, unzip it, and open
the lab11 folder in VS Code. The folder contains:
lab11.sql: The file you'll edit. Each question asks you to complete oneCREATE TABLEstatement.movies.sql: The movie data used in Questions 1โ3.data.sql: The final exam rooms and cipher tables used in Questions 4โ7.sqlite_shell.py: A program for running SQL interactively, for computers that don't have SQLite installed.tables.pyandtests/: Tests for the questions.
Running SQL
From the VS Code terminal, either run sqlite3 if it is installed:
sqlite3 --init lab11.sql
Or if that doesn't work, run sqlite_shell.py included with the lab:
python3 sqlite_shell.py --init lab11.sql
Type .quit or press Ctrl-C to exit. After you change lab11.sql, exit and run
the command again to see the result. Lab 10 has
more details.
SQL
Consult these drop-downs for a refresher on SQL, aggregation, and the IMDb dataset.
SQL
A SELECT statement describes an output table based on input rows. To write
one:
- Describe the input rows using
FROMandWHEREclauses. - Group those rows and determine which groups should appear as output rows
using
GROUP BYandHAVINGclauses. - Format and order the output rows and columns using
SELECTandORDER BYclauses.
SELECT (Step 3) FROM (Step 1) WHERE (Step 1) GROUP BY (Step 2)
HAVING (Step 2) ORDER BY (Step 3);
Step 1 may involve joining tables with JOIN and ON, as in
Discussion 11. The WHERE, GROUP BY, HAVING, and
ORDER BY clauses are optional.
Aggregation
Here's an example table about flights:
CREATE TABLE flights (departure TEXT, arrival TEXT, price INTEGER);
INSERT INTO flights VALUES
("SFO", "LAX", 97),
("SFO", "AUH", 848),
("LAX", "SLC", 115),
("SFO", "PDX", 192),
("AUH", "SEA", 932),
("SLC", "PDX", 79),
("SFO", "LAS", 40),
("SLC", "LAX", 117),
("SEA", "PDX", 32),
("SLC", "SEA", 42),
("SFO", "SLC", 97),
("LAS", "SLC", 50),
("LAX", "PDX", 89);
An aggregate function such as
COUNT, SUM, MAX, MIN, or AVG combines the values from multiple input
rows into one output row. Without a GROUP BY clause, all of the input rows
are combined. COUNT(*) is the number of rows:
sqlite> SELECT COUNT(*) FROM flights;
13
GROUP BY collects the input rows that have the same value for an expression
into a group, and each group becomes one output row. This statement makes a
group for each departure airport and finds the price of the cheapest flight in
each group:
sqlite> SELECT departure, MIN(price) FROM flights GROUP BY departure;
AUH|932
LAS|50
LAX|89
SEA|32
SFO|40
SLC|42
Just as WHERE filters input rows, HAVING filters groups. A HAVING clause
typically uses an aggregate function. These are the airports with at least two
departures:
sqlite> SELECT departure FROM flights GROUP BY departure HAVING COUNT(*) >= 2;
LAX
SFO
SLC
COUNT(DISTINCT x) counts the different values of x, rather than the rows.
There are 13 flights, but only 6 different departure airports:
sqlite> SELECT COUNT(DISTINCT departure) FROM flights;
6
IMDb Tables
The IMDb 1000 dataset contains the 1000 highest rated popular movies (top 0.2%
of votes) from the
Internet Movie Database.
The titles table (from Lab 10) has a row for each
movie:
tconst(text): A unique identifier for the movie (thetis for title)title(text): The name of the movieyear(integer): The year the movie was maderuntime(integer): How long the movie is, in minutesgenres(text): The movie's genres, separated by commas
The principals table has a row for each actor in each movie:
tconst(text): The movieordering(integer): The actor's billing in the movie; the lead role is 1nconst(text): A unique identifier for the actor (thenis for name)character(text): The name of the character the actor played
The names table has a row for each actor:
nconst(text): A unique identifier for the actorname(text): The actor's namebirth(integer): The year the actor was borndeath(integer): The year the actor died, orNULL
The tables are too large to look at all at once, so it's useful to add LIMIT
to a query to see just a few of their rows:
sqlite> SELECT * FROM principals LIMIT 3;
tt0012349|1|nm0000122|A Tramp
tt0012349|2|nm0701012|The Woman
tt0012349|3|nm0001067|The Child
sqlite> SELECT * FROM names LIMIT 3;
nm0000002|Lauren Bacall|1924|2014
nm0000004|John Belushi|1949|1982
nm0000006|Ingrid Bergman|1915|1982
The tconst and nconst identifiers are useful for joining rows from
different tables. For example, to find the characters in a movie, join titles
and principals on rows with the same tconst.
Required Questions
Q1: Movies with Dogs
Create a dog_movies table that has one row for each movie character whose name
includes the word "dog", with two columns:
title(text): The name of a moviecharacter(text): The name of the dog character
A single movie may appear more than once if it has multiple dog characters. The rows may appear in any order.
dog_movies table:
| title | character |
|---|---|
| As Good as It Gets | Supporting Dog |
| Back to the Future Part III | Buford 'Mad Dog' Tannen |
| Boyz n the Hood | Mad Dog |
| Everything Everywhere All at Once | Debbie the Dog Mom |
| Ghost Dog: The Way of the Samurai | Ghost Dog |
| The Mitchells vs. the Machines | Dog Cop |
| The Mitchells vs. the Machines | Talking Dog |
| The Raid: Redemption | Mad Dog |
| The Revenant | Elk Dog |
| Toy Story | Slinky Dog |
| Toy Story 2 | Slinky Dog |
Hint: Template
CREATE TABLE dog_movies AS
SELECT ____, ____
FROM ____ JOIN ____ ON ____
WHERE ____ LIKE "%dog%";
- Use
FROM,JOIN, andONto combine the information in thetitlesandprincipalstables. - Use
WHEREto select only characters that include "dog". The%sign matches any number of characters, andLIKEis case insensitive, so"%dog%"also matchesSlinky Dog. - Use
SELECTto put the movie title and character in the output.
CREATE TABLE dog_movies AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k dog_moviesQ2: Leads of Leads
Create a leads table that has a row for each actor who has been the lead in
more than 10 movies, with two columns:
name(text): The name of an actorlead_roles(integer): The number of movies in which the actor has been the lead
You can find lead roles by looking in the principals table for rows with
ordering equal to 1. The rows may appear in any order.
leads table:
| name | lead_roles |
|---|---|
| Brad Pitt | 12 |
| Johnny Depp | 12 |
| Leonardo DiCaprio | 13 |
| Robert De Niro | 12 |
| Tom Cruise | 12 |
| Tom Hanks | 18 |
Hint: Template
CREATE TABLE leads AS
SELECT ____, ____ AS lead_roles
FROM ____ JOIN ____ ON ____
WHERE ____
GROUP BY names.nconst
HAVING ____;
- Use
FROM,JOIN, andONto combine the information in theprincipalsandnamestables. - Use
WHEREto select only lead roles. - Use
GROUP BYto create a single group for each person. (Grouping bynconstrather thannamekeeps two different actors with the same name apart.) - Use
HAVINGto output only people who had more than 10 lead roles. - Use
SELECTto put the person's name and the number of their lead roles in the output.
CREATE TABLE leads AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k leadsQ3: Long Movies by Decade
Create a long_movies table that has a row for each decade with the number of
movies from that decade that are over 3 hours (180 minutes) long, with two
columns:
decade(text): The decade, such as1920scount(integer): The number of movies from that decade that are over 3 hours long
The rows may appear in any order. Decades with no movies over 3 hours long don't appear.
long_movies table:
| decade | count |
|---|---|
| 1930s | 1 |
| 1950s | 2 |
| 1960s | 2 |
| 1970s | 3 |
| 1980s | 2 |
| 1990s | 7 |
| 2000s | 4 |
| 2010s | 3 |
| 2020s | 4 |
Hint: Creating the Decade
On integers, / truncates, so 1987 / 10 is 198. When combining arithmetic
with a string using ||, put parentheses around the arithmetic:
sqlite> SELECT (192 * 10) || "s";
1920s
Hint: Template
CREATE TABLE long_movies AS
SELECT ____ AS decade, ____ AS count
FROM ____
WHERE ____
GROUP BY ____;
- Use
FROMandWHEREto choose only the movies with a runtime greater than 180 minutes. - Use
GROUP BYto group together all of the movies from one decade. - Use
SELECTto create a string like1920sfor each decade, and to count the movies in each decade.
CREATE TABLE long_movies AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k long_moviesA Final Exam About Final Exams
Adapted from the Spring 2023 final exam. These tables also appeared in Discussion 11.
The finals table has columns hall (strings) and course (strings), and has
rows for the lecture halls in which a course is holding its final exam.
The sizes table has columns room (strings) and seats (numbers), and has
one row per unique room on campus containing the number of seats in that room.
All lecture halls are rooms. Both tables are created in data.sql:
CREATE TABLE finals (hall TEXT, course TEXT);
INSERT INTO finals VALUES
("RSF", "61A"),
("Wheeler", "61A"),
("Pimentel", "61A"),
("Li Ka Shing", "61A"),
("Stanley", "61A"),
("RSF", "61B"),
("Wheeler", "61B"),
("Morgan", "61B"),
("Wheeler", "61C"),
("Pimentel", "61C"),
("Soda 310", "61C"),
("Soda 306", "10"),
("RSF", "70");
CREATE TABLE sizes (room TEXT, seats INTEGER);
INSERT INTO sizes VALUES
("RSF", 900),
("Wheeler", 700),
("Pimentel", 500),
("Li Ka Shing", 300),
("Stanley", 300),
("Morgan", 100),
("Soda 306", 80),
("Soda 310", 40),
("Soda 320", 30);
Q4: Total Seats
Create a seats table with two columns, course (strings) and total
(numbers), that has a row for each course that uses at least two rooms for
its final. Each row contains the name of the course and the total number of
seats in final rooms for that course. The rows may appear in any order.
Your query should work correctly for any data that might appear in the finals
and sizes tables, but for the example data above the result should be:
seats table:
| course | total |
|---|---|
| 61A | 2700 |
| 61B | 1700 |
| 61C | 1240 |
Hint: Input Rows
Join the finals and sizes tables, using ON so that each joined row has
the same hall (from finals) and room (from sizes).
Hint: Groups
Since the output has one row per course, but the same course appears in
multiple rows of the finals table, group by course.
COUNT(*) evaluates to the number of input rows in a group, which in this case
will be the number of rooms used by a course.
Hint: Output Rows
The expression SUM(seats) evaluates to the sum of the seats values (from
the sizes table) for a group. If there is one group per course, then this
will be the sum of seats in all lecture halls used for that course.
CREATE TABLE seats AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k seatsQ5: Shared Rooms
Create a shared table with two columns, course (strings) and shared
(numbers), that has a row for each course using at least one room that is
also used by another course. Each row contains the name of the course and
the number of its rooms that are also used by another course. The rows may
appear in any order.
Your query should work correctly for any data that might appear in the finals
table, but for the example data above the result should be:
shared table:
| course | shared |
|---|---|
| 61A | 3 |
| 61B | 2 |
| 61C | 2 |
| 70 | 1 |
Which are the two halls for 61B that are shared? Why does RSF count only once for 61A, even though two other courses use it?
Hint: Input Rows
Join finals with itself, using ON and WHERE so that each joined row
describes two different courses that use the same hall. Discussion 11's Room
Sharing question built similar rows, but it used < to keep only one of the
two orderings of each pair, so a course would be left out whenever it comes
second alphabetically. Here, use != so that each course appears in the first
course column of every pair it belongs to.
Hint: Groups
Group by the first course column to make one group (and one output row) per
course. A HAVING clause is not needed if the WHERE clause has already
limited the input rows to those with two different courses using the same hall.
Hint: Output Rows
Count the number of different hall values for a course with
COUNT(DISTINCT ____). DISTINCT is needed so that a hall used by more than
two courses is not counted more than once.
CREATE TABLE shared AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k sharedSubstitution
A substitution cipher replaces each word with another word in a table in order
to encrypt a message. To decode an encrypted message, replace each word x with
its corresponding y in a code table. The original table contains an
encrypted message, one word per row, and n is the position of each word in
the message. Both tables are created in data.sql:
CREATE TABLE original AS
SELECT 1 AS n, "It's" AS word UNION
SELECT 2 , "The" UNION
SELECT 3 , "End";
CREATE TABLE code AS
SELECT "Up" AS x, "Down" AS y UNION
SELECT "Now" , "Home" UNION
SELECT "It's" , "What" UNION
SELECT "See" , "Do" UNION
SELECT "Can" , "See" UNION
SELECT "End" , "Now" UNION
SELECT "What" , "You" UNION
SELECT "The" , "Happens" UNION
SELECT "Love" , "Scheme" UNION
SELECT "Not" , "Mess" UNION
SELECT "Happens", "Go";
Q6: A Secret Message
Create a decoded_once table with one column that decodes the original
message It's The End using the code table. The words appear in order, one
per row.
decoded_once table:
| y |
|---|
| What |
| Happens |
| Now |
Hint
Join the original and code tables so that each joined row has the same
word and x. Then order the rows by n.
CREATE TABLE decoded_once AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k decoded_onceQ7: What Happens Now?
Create a decoded_twice table with one column that decodes the original
message twice: replace each word with its corresponding y in the code table,
then replace that word with its corresponding y in the code table again.
The words appear in order, one per row.
decoded_twice table:
| y |
|---|
| You |
| Go |
| Home |
Hint
Join original with code AS a and code AS b to create six-column rows like
2|The|The|Happens|Happens|Go. The Go at the end is part of the decoded
message.
CREATE TABLE decoded_twice AS
SELECT "REPLACE THIS LINE WITH YOUR SOLUTION";
python3 -m pytest -k decoded_twiceSubmit Assignment
Submit this assignment by running Provenance: Prepare Submission Bundle from the VS Code command palette and uploading the resulting zip to Gradescope. The zip already contains the files you've edited. Lab 00 has detailed instructions.
Your responses to WWPD questions are not submitted, and they do not need to be. Lab credit is based on the code writing questions.