SQL

CSE 190 M (Web Programming) Spring 2008

University of Washington

References: SQL syntax reference, w3schools tutorial

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp, Jessica Miller, and Amit Levy, and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

Database design

First database design

design 1

Second database design

design 2

IMDb database

Actor
idfnamelnamegender
433259WilliamShatnerM
797926BritneySpearsF
831289SigourneyWeaverF
...
Movie
idnameyear
112290Fight Club1999
209658Meet the Parents2000
210511Memento2000
...
Cast
aidmidRole
433259313398Capt. James T. Kirk
433259407323Sgt. T.J. Hooker
797926342189Herself
...

Practice problem: Movie search

Combining multiple tables: cross product

SELECT column(s) FROM table1, table2, ..., tableN;
SELECT * FROM Student, Grades;

Cross product example

SELECT * FROM Student, Grades;
nameSIDemailSIDCIDgrade
142Bartbart@fox.com142CPS116B-
142Bartbart@fox.com142CPS114B
142Bartbart@fox.com123CPS116B+
142Bartbart@fox.com857CPS116A+
142Bartbart@fox.com857CPS130A+
142Bartbart@fox.com456CPS114C
123Milhousemilhouse@fox.com142CPS116B-
123Milhousemilhouse@fox.com142CPS114B
... (24 rows returned)

Joins

SELECT column(s) FROM table1, table2, ..., tableN WHERE condition(s);
SELECT column(s) FROM table1
JOIN   table2 ON condition(s)
...
JOIN   tableN ON condition(s);
SELECT * FROM Student, Grade WHERE Student.SID = Grade.SID;

Join example

SELECT * FROM Student, Grade WHERE Student.SID = Grade.SID;
nameSIDemailSIDCIDgrade
123Milhousemilhouse@fox.com123CPS116B+
142Bartbart@fox.com142CPS116B-
142Bartbart@fox.com142CPS114B
456Ralphralph@fox.com456CPS114C
857Lisalisa@fox.com857CPS116A+
857Lisalisa@fox.com857CPS130A+

SELECT * FROM Student JOIN Grade ON Student.SID = Grade.SID;

Filtering columns during a join

SELECT name, Grade.* FROM Student, Grade
WHERE  Student.SID = Grade.SID;
nameSIDCIDgrade
Milhouse123CPS116B+
Bart142CPS116B-
Bart142CPS114B
Ralph456CPS114C
Lisa857CPS116A+
Lisa857CPS130A+

Giving names to tables

SELECT name, g.*
FROM   Student s, Grade g
WHERE  s.SID = g.SID;
nameSIDCIDgrade
Milhouse123CPS116B+
Bart142CPS116B-
Bart142CPS114B
Ralph456CPS114C
Lisa857CPS116A+
Lisa857CPS130A+

Self-joins

SELECT *
FROM   Student s1, Student s2
WHERE  s1.SID < s2.SID;
nameSIDCIDgrade
Milhouse123CPS116B+
Bart142CPS116B-
Bart142CPS114B
Ralph456CPS114C
Lisa857CPS116A+
Lisa857CPS130A+

Practice problem: Cast list for a movie

Write a PHP script that, when given a movie, shows the names of all female actors that appeared in it. (To do this, you will need to perform an SQL query with join operations.)