SQL Queries
Chapter 5.1-5.8
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
SQL Query Language
Implements relational algebra / calculus And more
Subqueries, Correlated subqueries Ordering of results Aggregate queries (e.g., SUM, MAX, AVG) Three-valued logic for NULL values
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
Key Topics (Next Two Classes)
Basic SQL queries Aggregate queries Nested queries NULL values and SQL queries Complex constraints and triggers Examples
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
Basic SQL Query
Optional
Attributes from input relations List of relations
SELECT [DISTINCT] attr-list Attr1 op Attr2 FROM relation-list OPS: <, >, =, <=, >=, <> Combine using AND, OR, NOT WHERE qualification
(Conceptual) Evaluation:
1. Take cross-product of relation-list 2. Select rows satisfying qualification
Optimizer chooses efficient plan!!
4
2/6/11
3. Project columns in attr-list (eliminate duplicates only if DISTINCT)
EECS 484: Database Management Systems, Kristen LeFevre
Example of Basic Query
Schema:
Sailors (sid, sname, rating, age) Boats (bid, bname, color) Reserves (sid, bid, day)
Find the names of sailors who have reserved boat #103 SELECT [Link] FROM Sailors S, Reserves R WHERE [Link] = [Link] AND [Link] = 103
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 5
Example of Basic Query
SELECT DISTINCT sname FROM Sailors S, Reserves R WHERE [Link] = [Link] AND [Link] = 103
Equivalent Relational Algebra
!sname ("bid=103(Sailors !" Reserves))
Equivalent Relational Calculus
{T | #S $ Sailors #R $ Reserves ([Link] = [Link] % [Link] = 103 % [Link] = [Link])}
EECS 484: Database Management Systems, Kristen LeFevre 6
2/6/11
Another Example
Schema:
Sailors (sid, sname, rating, age) Boats (bid, bname, color) Reserves (sid, bid, day)
Find the colors of boats reserved by a sailor named rusty SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = rusty
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 7
Note on Range Variables (Aliases)
Needed when same relation appears twice in FROM clause
SELECT [Link], [Link] FROM Sailors S1, Sailors S2 WHERE [Link] > [Link]
Good style to always use range variables anyway
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
ORDER BY clause
In relational algebra and calculus, there is no way to specify ordering of results SQL has an extra ORDER BY clause
Attribute(s) in ORDER BY clause must be in SELECT list.
Find the names and ages of all sailors, in increasing order of age
SELECT [Link], [Link] FROM Sailors S ORDER BY [Link] [ASC]
2/6/11
Find the names and ages of all sailors, in decreasing order of age
SELECT [Link], [Link] FROM Sailors S ORDER BY [Link] DESC
9
EECS 484: Database Management Systems, Kristen LeFevre
ORDER BY clause
SELECT [Link], [Link], [Link] FROM Sailors S ORDER BY [Link] ASC, [Link] DESC What does this query compute?
Find the names, ages, and rankings of all sailors. Sort the result in increasing order of age. If there is a tie, sort those tuples in decreasing order of rating.
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
10
Union
Find names of sailors who have reserved a red or a green boat
SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] AND [Link] = [Link] AND ([Link] = red OR [Link] = green) SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = red UNION SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] and [Link] = [Link] AND [Link] = green
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 11
Intersect
Find sids of sailors who have reserved a red and a green boat
SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = red INTERSECT SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] and [Link] = [Link] AND [Link] = green
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
12
More Set Operators
Also MINUS / EXCEPT (set difference; not standard across systems for some reason) (Painful) SQL oddities
For UNION, default is to eliminate duplicates! To keep duplicates, must specify UNION ALL
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
13
Nested Queries
Query with another query embedded inside
What does this Compute?
SELECT [Link] FROM Sailors S WHERE [Link] IN (SELECT [Link] FROM Reserves R WHERE [Link]=103)
Conceptual evaluation: For each row of Sailors, evaluate the subquery over reserves To find sailors who have not reserved 103, use NOT IN
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
14
Nested Queries with Correlation
Find names of sailors who have reserved exactly one boat.
SELECT [Link] appears once FROM Sailors S WHERE EXISTS (SELECT UNIQUE [Link] FROM Reserves R WHERE [Link]=[Link])
True if value
Illustrates why subquery must be evaluated for each tuple in Sailors.
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
15
More Set Comparison Operators
Weve already seen IN, EXISTS and UNIQUE. Can also use NOT IN, NOT EXISTS and NOT UNIQUE. Also available: op ANY, op ALL, op is <, !, >, ", =, # Find sailors whose rating is greater than that of all sailors called Horatio:
SELECT * FROM Sailors S WHERE [Link] > ALL (SELECT [Link] FROM Sailors S2 WHERE [Link]=Horatio)
What if we replace ALL with ANY?
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 16
Aggregate Operators
SELECT COUNT (*) FROM Sailors S SELECT COUNT (DISTINCT [Link]) FROM Sailors S SELECT AVG ([Link]) FROM Sailors S WHERE [Link]=10
COUNT (*) COUNT ( [DISTINCT] A) SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) Can use Distinct MIN (A) Can use Distinct
single column
SELECT AVG ( DISTINCT [Link]) FROM Sailors S WHERE [Link]=10
SELECT [Link] FROM Sailors S WHERE [Link]= (SELECT MAX([Link]) FROM Sailors S2)
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
17
Aggregate Query - Example
Find name and age of oldest sailor(s)
SELECT [Link], MAX ([Link]) FROM Sailors S SELECT [Link], [Link] FROM Sailors S WHERE [Link] = (SELECT MAX ([Link]) FROM Sailors S2)
How many tuples in the result?
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
18
GROUP BY
Conceptual evaluation
Partition data into groups according to some criterion Evaluate the aggregate for each group Example: For each rating level, find the age of the youngest sailor
SELECT MIN ([Link]), [Link] FROM Sailors S GROUP BY [Link] How many tuples in the result?
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
19
GROUP BY and HAVING
SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification
Target-list contains: Attribute names (subset of grouping-list) Aggregate operations (e.g., min(age))
Conceptual Evaluation: 1. Eliminate tuples that dont satisfy qualification 2. Partition remaining data into groups 3. Eliminate groups according to group-qualification 4. Evaluate aggregate operation(s) for each group
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 20
10
Find the age of the youngest sailor with age >= 18, for each rating with at least 2 such sailors
SELECT [Link], MIN ([Link]) FROM Sailors S WHERE [Link] >= 18 GROUP BY [Link] HAVING COUNT (*) >= 2
sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 71 zorba 10 16.0 64 horatio 7 35.0 29 brutus 1 33.0 58 rusty 10 35.0
rating 1 7 7 8 10 age 33.0 45.0 35.0 55.5 35.0
rating 7 35.0 Answer relation
SQL Examples
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
22
11
Social Network Example (1)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
Find the names and ages of all users belonging to a network named Michigan in decreasing order of Age SELECT [Link], [Link] FROM User U, Network N, Member M WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = Michigan ORDER BY [Link] DESC
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 23
Social Network Example (2)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
Find the names of all unique hometowns, as well as the number of users from each SELECT [Link], COUNT(*) FROM User U GROUP BY [Link]
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
24
12
Social Network Example (3)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
For each network with three or more members, find the network id, the network name, and the average age of users belonging to the network SELECT [Link], [Link], AVG([Link]) FROM User U, Network N, Member M WHERE [Link] = [Link] AND [Link] = [Link] GROUP BY [Link], [Link] HAVING COUNT(*) >= 3
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 25
Social Network Example (4)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
Find the names of users who are older than all members Of the network(s) with name Huron High School SELECT [Link] FROM User U WHERE [Link] > ALL (SELECT [Link] FROM User U2, Network N, Member M WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = Huron High School)
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 26
13
Social Network Example (5)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
Find the names of all users who are friends with the user with uid 456 (omit duplicates) SELECT DISTINCT [Link] FROM User U, Friend F WHERE F.uid1 = 456 AND F.uid2 = [Link]
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
27
Social Network Example (6)
User (uid, username, age, sex, hometown) Network (nid, description, networkname) Member (uid, nid) Friend (uid1, uid2)
Find the uids of all users who are within 1 degree of user 456 SELECT uid2 FROM Friend WHERE uid1 = 456 UNION SELECT F2.uid2 FROM Friend F1, Friend F2 WHERE F1.uid1 = 456 AND F1.uid2 = F2.uid1
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 28
14
WITH Clause
Assign a name to the result of a query
Scope of the name is within the current query, so this is different from creating a view Helpful when writing complex queries WITH Users_by_Network AS ( SELECT nid, count(*) cnt FROM Member GROUP BY nid) SELECT max(cnt) FROM Users_by_Network
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
29
NULL Values in SQL
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
30
15
NULL Values in SQL
NULL represents unknown or inapplicable Query evaluation complications
Q: Is (rating > 10) true when rating is NULL? A: Condition evaluates to unknown (not T or F)
p q T T T F T U F T F F F U U T U F U U p AND q T F U F F F U F U p OR q T T T T F U T U U
What about AND, OR connectives?
Need 3-valued logic
WHERE clause eliminates rows that dont evaluate to true
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre 31
NULL Values Example
What does this query return? SELECT sname FROM sailors WHERE age > 45 OR age <= 45 sailors sid sname 22 dustin 58 rusty 31 lubber rating 7 10 8 age 45 NULL 55
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
32
16
NULL Values in Aggregates
NULL values generally ignored when computing aggregates
Modulo some special cases (see textbook)
SELECT AVG(age) FROM sailors Returns 50! sailors sid sname 22 dustin 58 rusty 31 lubber
rating 7 10 8
age 45 NULL 55
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
33
Advanced Integrity Constraints
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
34
17
Integrity Constraints Revisited
Describes conditions that must be satisfied by every legal instance Types of integrity constraints
Domain constraints Primary key constraints Foreign key constraints General constraints
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
35
Table Constraints
More general than key constraints Can use a query to express constraint
Constraints checked each time table updated CHECK constraint always true for empty relation CREATE TABLE Reserves CREATE TABLE Sailors ( sname CHAR(10), ( sid INTEGER, bid INTEGER, sname CHAR(10), day DATE, rating INTEGER, PRIMARY KEY (bid,day), age REAL, CONSTRAINT noInterlakeRes PRIMARY KEY (sid), CHECK (`Interlake <> CHECK ( rating >= 1 ( SELECT [Link] AND rating <= 10 ) FROM Boats B WHERE [Link]=bid)))
2/6/11 EECS 484: Database Management Systems, Kristen LeFevre
36
18
Constraints Over Multiple Relations
For general constraint over multiple tables, use an assertion
Number of boats plus number of sailors is < 100
CREATE ASSERTION smallClub CHECK ((SELECT COUNT ([Link]) FROM Sailors S) + (SELECT COUNT ([Link]) FROM Boats B) < 100)
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
37
Triggers
Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts:
Event (activates the trigger) Condition (tests whether the trigger should run) Action (what happens if the trigger runs)
Before and After Triggers
Trigger Execution
Row-level Triggers: Once per modified row Statement-level Triggers: Once per SQL statement
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
38
19
Example
Event: Insert new row into Students Condition: New students age >= 18 Event: Update universitys total enrollment
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
39
Oracle Trigger Basic Syntax
CREATE [OR REPLACE] TRIGGER <trigger_name> {BEFORE | AFTER} {INSERT | DELETE | UPDATE} ON <table_name> [REFERENCING [NEW AS <new_row>] [OLD AS <old_row>]] [FOR EACH ROW [WHEN (<condition>)]] <trigger_body>
In Oracle, <trigger_body> is a PL/SQL block
Oracle Triggers Not quite the same As SQL Standard
40
2/6/11
EECS 484: Database Management Systems, Kristen LeFevre
20