SQL

CSE 190 M (Web Programming) Spring 2007

University of Washington

Reading: Sebesta Ch. 14 sections 14.1 - 14.2, 14.4, 14.6
References: SQL syntax reference, w3schools tutorial

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

Valid XHTML 1.0 Strict Valid CSS!

Relational databases

Why databases?

Database software

Database design

First database design

design 1


Second database design

design 2


Structured Query Language (SQL)

SELECT name FROM Student WHERE SID = 456;
INSERT INTO Grade VALUES ('123', 'CPS130', 'C+');

The SQL SELECT statement

SELECT column(s) FROM table;
SELECT SID, CID FROM Grade;
SIDCID
142CPS116
142CPS114
123CPS116
857CPS116
857CPS130
456CPS114

Issuing SQL commands directly in MySQL

% mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.

mysql> USE Simpsons;
Database changed

mysql> SELECT * FROM Student;
+-----+----------+------------------+
| SID | name     | email            |
+-----+----------+------------------+
| 123 | Milhouse | milhouse@fox.com |
| 142 | Bart     | bart@fox.com     |
| 456 | Ralph    | ralph@fox.com    |
| 857 | Lisa     | lisa@fox.com     |
+-----+----------+------------------+

The DISTINCT modifier

SELECT DISTINCT column(s) FROM table;
SELECT SID FROM Grade;
SID
142
142
123
857
857
456
SELECT DISTINCT SID FROM Grade;
SID
142
123
857
456

The WHERE clause

SELECT column(s) FROM table WHERE condition(s);
SELECT CID, grade FROM Grade WHERE SID = 142;
CIDgrade
CPS116B-
CPS114B

More about the WHERE clause

WHERE column operator value(s)
SELECT * FROM Grade WHERE grade <> 'A+';
SIDCIDgrade
142CPS116B-
142CPS114B
123CPS116B+
456CPS114C

Multiple WHERE clauses: AND, OR

SELECT * FROM Grade WHERE grade <> 'A+' AND SID <= 142;
SIDCIDgrade
142CPS116B-
142CPS114B
456CPS114C

Approximate matches: LIKE

WHERE column LIKE pattern
SELECT * FROM Grade WHERE grade LIKE 'B%';
SIDCIDgrade
142CPS116B-
142CPS114B
123CPS116B+

Sorting: ORDER BY

ORDER BY column(s)
SELECT * FROM Grade WHERE grade LIKE 'B%' ORDER BY CID;
SIDCIDgrade
142CPS114B
142CPS116B-
123CPS116B+

Connecting to MySQL in PHP: mysql_connect

$db = mysql_connect("host", "username", "password");
mysql_select_db("database name");
# connect to Simpsons database on local computer
$db = mysql_connect("localhost", "stepp", "6uldv8");
mysql_select_db("simpsons");

Error-checking: mysql_error

# connect to Simpsons database on local computer
$db = mysql_connect("localhost", "stepp", "6uldv8");
if (!$db) {
    die("A SQL error occurred: " . mysql_error());
}
if (!mysql_select_db("simpsons")) {
    die("A SQL error occurred: " . mysql_error());
}

Reading result data: mysql_query

$db = mysql_connect("host", "username", "password");
mysql_select_db("database name");
$results = mysql_query("SQL query");
while ($row = mysql_fetch_array($results)) {
    do something with $row;
}

PHP MySQL example

# connect to Simpsons database on local computer
$db = mysql_connect("localhost", "stepp", "6uldv8");
mysql_select_db("Simpsons");
$results = mysql_query("SELECT * FROM Grade WHERE SID = 142;");

# loop through each of Bart's course grade records
while ($row = mysql_fetch_array($results)) {
    print("Course ID: {$row['cid']}\n");
}

Checking rows returned: mysql_num_rows

# connect to Simpsons database on local computer
$db = mysql_connect("localhost", "stepp", "6uldv8");
mysql_select_db("Simpsons");
$results = mysql_query("SELECT * FROM Grade WHERE SID = 142;");

# check whether Bart took any courses
if (mysql_num_rows($results) == 0) {
    print("Student 142 did not take any classes.\n");
    ...
}

Other MySQL PHP functions

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.)