1 of 18

CS50 for MBAs

SQL

2 of 18

Learning Objectives

  • Learn how to answer questions via SQL.
    • Learn how to SELECT data from a relational database.
    • Learn how to JOIN tables on keys.
    • Learn how to nest queries.

3 of 18

DB Browser for SQLite

4 of 18

movies.db

5 of 18

Tables

  1. movies
  2. people
  3. stars
  4. directors
  5. ratings

6 of 18

What are the titles of all of the movies in which Kevin Bacon (b. 1958) starred?

  1. Select Kevin Bacon's ID.
  2. Select the IDs of all movies associated with that ID.
  3. Select the titles of all movies associated with those IDs.

7 of 18

What are the titles of all of the movies in which Kevin Bacon (b. 1958) starred?

  • Select Kevin Bacon's ID.
  • Select the IDs of all movies associated with that ID.
  • Select the titles of all movies associated with those IDs.

8 of 18

What are the titles of all of the movies in which Kevin Bacon (b. 1958) starred?

  • Select Kevin Bacon's ID.
  • Select the IDs of all movies associated with that ID.
  • Select the titles of all movies associated with those IDs.

9 of 18

What are the titles of all of the movies in which Kevin Bacon (b. 1958) starred?

  • Select Kevin Bacon's ID.
  • Select the IDs of all movies associated with that ID.
  • Select the titles of all movies associated with those IDs.

10 of 18

Nested SELECTs

SELECT title FROM movies WHERE id IN�(SELECT movie_id FROM stars WHERE person_id =�(SELECT id FROM people WHERE name = "Kevin Bacon" and birth = 1958));

11 of 18

Implicit JOINs

SELECT title FROM movies, stars, people WHERE�people.name = "Kevin Bacon" and people.birth = 1958 AND�stars.person_id = people.id AND�stars.movie_id = movies.id;

12 of 18

Explicit JOINs

SELECT title FROM movies �JOIN stars ON movies.id = stars.movie_id�JOIN people on stars.person_id = people.id WHERE�people.name = "Kevin Bacon" and people.birth = 1958 AND�stars.person_id = people.id AND�stars.movie_id = movies.id;

13 of 18

IMDb Questions and Answers

14 of 18

Movies

15 of 18

References

  • https://www.w3schools.com/sql/
  • ...

16 of 18

submit what you've done so far

17 of 18

practice problems

18 of 18

CS50 for MBAs

SQL