Home CS61A: Tables
Post
Cancel

CS61A: Tables

1
2
3
%load_ext sql
%config SqlMagic.style = '_DEPRECATED_DEFAULT'
%sql sqlite:///cs61a.db

Joining Tables

  • Queries may span over multiple tables, so we have to join multiple tables into one.
    • We must modify the FROM clause within a select statement to join multiple tables.
  • Two tables A & B are joined by a comma (or JOIN) to form all combiations of a row from A and a row from B.
1
2
3
4
5
6
7
8
9
10
%%sql
CREATE TABLE dogs AS
    SELECT "ace" AS name, "long" AS fur UNION
    SELECT "bella", "short" UNION
    SELECT "charlie", "long" UNION
    SELECT "daisy", "long" UNION 
    SELECT "ellie", "short" UNION
    SELECT "finn", "curly" UNION
    SELECT "ginger", "short" UNION
    SELECT "hank", "curly";
1
2
3
4
5
6
7
8
 * sqlite:///cs61a.db
Done.





[]
  • Using the parents and the dogs table, we may now manipulate data pertaining to the family structure of dogs, and their fur types at the same time.
  • Ex: Select the names of the parents of curly-furred dogs.
1
2
%%sql
SELECT parent FROM parents, dogs WHERE child = name AND fur = "curly";
1
2
 * sqlite:///cs61a.db
Done.
parent
ellie
daisy
  • When we joined the parents and dogs table, we made a new table where each row of parents is joined with every row of dogs, forming a (length of parents) * (length of dogs) long table.
    • To solve problems that require joining tables together, we must find ways to relate the rows of the two tables together and find the relevant entires that match.
    • Match a row from table A with table B.

Implicit & Explicit Join Syntax

  • Implicit Syntax: Place all conditions for joining the two tables in the WHERE clause.
    • JOIN will just create rows of all possible combinations of table A and table B’s rows
  • Explict Syntax: Use the syntax FROM ____ JOIN ____ ON ____ and pu matching conditions after ON
    • Ex:
1
2
%%sql
SELECT parent FROM parents JOIN dogs ON child = name WHERE fur = "curly";
1
2
 * sqlite:///cs61a.db
Done.
parent
ellie
daisy

Aliases and Dot Expressions

  • We use Dot Expressions to distinguish between two columns that have the same name, and we use Aliases to distinguish between two tables that have the same name.
    • Both of these cases occur when a table is joined with itself.
  • EX: Select all pairs of siblings
1
2
3
4
%%sql
SELECT a.child AS first, b.child AS second -- dot expression is used to select the names of two dogs
    FROM parents AS a, parents AS b     -- Aliasing is used to distinguish between the two tables
    WHERE a.parent = b.parent AND a.child < b.child     -- Check that the two dogs have the same parent and ensure that they are not the same dog + ensure no duplicates
1
2
 * sqlite:///cs61a.db
Done.
firstsecond
bellacharlie
acedaisy
aceginger
daisyginger
  • Ex: Select all grandparent, grandchild pairs
1
2
3
4
%%sql
SELECT a.parent AS gp, b.child AS gc
    FROM parents AS a, parents AS b
    WHERE a.child == b.parent
1
2
 * sqlite:///cs61a.db
Done.
gpgc
ellieace
elliedaisy
ellieginger
finnbella
finncharlie
finnhank

Joining Multiple Tables

  • Multiple tables can be joined to yield all combinations of rows from table.
  • Ex: Select all grandparents with the same fur as their grandchildren
1
2
3
4
5
6
7
8
9
%%sql
CREATE TABLE grandparents AS
    SELECT a.parent AS granddog, b.child AS grandpup
        FROM parents AS a, parents AS b
        WHERE a.child = b.parent;

SELECT a.name, b.name
    FROM grandparents AS gp, dogs AS a, dogs AS b
    WHERE gp.granddog = a.name AND gp.grandpup = b.name AND a.fur = b.fur;
1
2
3
 * sqlite:///cs61a.db
Done.
Done.
namename_1
ellieginger
finnhank
  • To figure out which tables must be joined together, we must understand what information we must gather first.
    • What is the grandpup’s fur? (dogs)
    • What is the granddog’s fur? (dogs)
    • Are two dogs grandpups and grandogs? (grandparents)

Numerical Expressions

  • Expressions can contain function calls and arithmetic operators
  • Through expressions, we may:
    • Combine values: +, -, *, /, %, and, or
    • Transform values: abs, round, not
    • Compare values: <, <=, >, >=, <>, !=, =
      • both <> and != means not equal.
  • Ex: Cities Table
1
2
3
4
5
6
7
8
%%sql
CREATE TABLE cities AS
    SELECT 38 AS latitude, 122 AS longitude, "Berkeley" AS name UNION
    SELECT 42, 71, "Cambridge" UNION
    SELECT 45, 93, "Minneapolis" UNION
    SELECT 33, 117, "San Diego" UNION
    SELECT 26, 80, "Miami" UNION
    SELECT 90, 0, "North Pole";
1
2
3
4
5
6
7
8
 * sqlite:///cs61a.db
Done.





[]
  • Ex: Create a new table cold that contains all cities with a latitude at or above 43
1
2
3
4
5
6
%%sql

CREATE TABLE cold AS
    SELECT name FROM cities WHERE latitude >= 43;

SELECT name FROM cold;
1
2
3
 * sqlite:///cs61a.db
Done.
Done.
name
Minneapolis
North Pole
  • Ex: Create a new table distances that contains the north-south difference of cities
1
2
3
4
5
6
7
8
%%sql
CREATE TABLE distances AS
    SELECT a.name AS city_1, b.name AS city_2, 60*(a.latitude-b.latitude) AS distance
    FROM cities AS a, cities AS b
    WHERE a.name > b.name
    ORDER BY distance DESC;

SELECT * FROM distances;
1
2
3
 * sqlite:///cs61a.db
Done.
Done.
city_1city_2distance
North PoleMiami3840
North PoleBerkeley3120
North PoleCambridge2880
North PoleMinneapolis2700
MinneapolisMiami1140
San DiegoMiami420
MinneapolisBerkeley420
CambridgeBerkeley240
MinneapolisCambridge180
San DiegoBerkeley-300
San DiegoCambridge-540
MiamiBerkeley-720
San DiegoMinneapolis-720
MiamiCambridge-960
San DiegoNorth Pole-3420

String Expressions

  • String values may be combined to form longer strings
    • This is done through the concatenation symbol ||
1
%sql SELECT "hello, " || "world";
1
2
 * sqlite:///cs61a.db
Done.
"hello, " || "world"
hello, world
  • String manipulation is also built into SQL
    • SUBSTR(column, start, length): For each value in the column, start from at the start index (one-based), and capture the next length letters, including the start letter.
    • INSTR(column, string): Returns the index at which a string first appears in another value.
1
%sql DROP TABLE phrase;
1
2
3
4
5
6
7
8
 * sqlite:///cs61a.db
Done.





[]
1
%sql DROP TABLE phrase
1
2
3
4
5
6
7
8
 * sqlite:///cs61a.db
Done.





[]
1
2
3
4
5
6
%%sql
CREATE TABLE phrase AS SELECT "hello, world" AS s;
    SELECT "Bye, world" UNION
    SELECT "Hello, CS61A world";

SELECT SUBSTR(s, 4, 2) || SUBSTR(s, INSTR(s, " ")+1, 1) AS modified FROM phrase;
1
2
3
4
 * sqlite:///cs61a.db
Done.
Done.
Done.
modified
low
  • Strings may also be used to represent structured values.
    • This is not a good idea
  • Ex: A linked list representation
1
2
3
%%sql
CREATE TABLE lists AS SELECT "one" AS car, "two,three,four" AS cdr;
SELECT SUBSTR(cdr, 1, instr(cdr, ",")-1) AS cadr FROM lists;
1
2
3
 * sqlite:///cs61a.db
Done.
Done.
cadr
two
  • Ex: Nouns table
1
2
3
4
5
6
7
8
%%sql 

CREATE TABLE nouns AS
    SELECT "dog" AS phrase UNION
    SELECT "cat" UNION
    SELECT "bird";

SELECT subject.phrase || " chased " || object.phrase AS sentence FROM nouns AS subject, nouns AS object WHERE object.phrase != subject.phrase;
1
2
3
 * sqlite:///cs61a.db
Done.
Done.
sentence
bird chased cat
bird chased dog
cat chased bird
cat chased dog
dog chased bird
dog chased cat
This post is licensed under CC BY 4.0 by the author.

CS61A: Lecture 32

CS61A: Aggregation