COP 5725 Fall 2012 Database Management Systems
COP 5725 Fall 2012 Database Management Systems
University of Florida, CISE Department Prof. Daisy Zhe Wang SQL: Queries, Constraints, Triggers
SQL Constraints & Triggers
DML & Views Why SQL? • SQL is a very-high-level language.
– Say “what to do” rather than “how to do it.”
- – Avoid a lot of data-manipulation details needed in procedural languages like C++ or Java.
- Database management system figures out “best” way to execute query.
- – using relational algebra
Basic SQL Query SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
- relation-list A list of relation names (possibly with a range- variable after each name).
- target-list A list of attributes of relations in relation-list
- qualification Comparisons (Attr op const or Attr1 op Attr2,
where op is one of ) combined using
, , , , , AND, OR and NOT.
- DISTINCT is an optional keyword indicating that the answer
should not contain duplicates. Default is that duplicates are
not eliminated (bag semantics)!
Conceptual Evaluation Strategy
- Semantics of an SQL query defined in terms of the following conceptual evaluation strategy:
relation-list Compute the cross-product of .
- – Discard resulting tuples if they fail qualifications .
- – Delete attributes that are not in target-list .
- – – DISTINCT
If is specified, eliminate duplicate rows.
- This strategy is probably the least efficient way to compute a query! The optimizer will find more efficient strategies to compute
the Example Instances sid sname rating age 22 dustin
7
45.0 31 lubber
8
55.5 58 rusty
10
35.0 Sailors sid bid day 22 101 10/10/96 58 103 11/12/96 Reserves
Example of Conceptual Evaluation
SELECT7
10
35.0 22 101 10/10/96 58 rusty
10
55.5 58 103 11/12/96 58 rusty
8
55.5 22 101 10/10/96 31 lubber
8
45.0 58 103 11/12/96 31 lubber
45.0 22 101 10/10/96 22 dustin
S.sname
7
(sid) sname rating age (sid) bid day 22 dustin
R.bid=103
AND
S.sid=R.sid
WHERE
Sailors S, Reserves R
FROM
35.0 58 103 11/12/96 A Note on Range Variables
- Really needed only if the same relation
FROM appears twice in the clause. The previous query can also be written as:
SELECT
S.sname
FROM
Sailors S, Reserves R
WHERE AND
S.sid=R.sid bid=103
SELECT OR sname
FROM
Sailors, Reserves
WHERE
Sailors.sid=Reserves.sid
AND
bid=103 Find sailors who’ve reserved at least one boat SELECT
S.sid
FROM
Sailors S, Reserves R
WHERE
S.sid=R.sid DISTINCT
- Would adding to this query make a difference?
- What is the effect of replacing S.sid by
SELECT in the clause? Would
S.sname
DISTINCT adding to this variant of the query Expressions and Strings SELECT
AS
S.age, age1=S.age-5, 2*S.age age2
FROM
Sailors S
WHERE LIKE
S.sname ‘B_%B’
- Illustrates use of arithmetic expressions and string pattern match
- AS
and = are two ways to name fields in result.
- LIKE
is used for string matching. ` _ ’ stands for any one character and ` % ’ stands for 0 or
Find sid’s of sailors who’ve reserved a red or a green boat
- UNION
: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries).
- If we replace OR by AND in the first version, what do we get?
- Also available: EXCEPT
(What do we get if we replace UNION by EXCEPT ?)
SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color
=‘red’ OR B.color
=‘green’) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color
=‘red’ UNION SELECT
S.sid FROM
Sailors S, Boats B, Reserves R WHERE
S.sid=R.sid AND
R.bid=B.bid Find sid’s of sailors who’ve reserved a red and a green boat SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2
- INTERSECT
: Can be used to WHERE S.sid=R1.sid AND R1.bid=B1.bid
compute the intersection
AND S.sid=R2.sid AND R2.bid=B2.bid
of any two union-
AND AND
(B1.color=‘red’ B2.color=‘green’) compatible sets of tuples.
SELECT
- Included in the SQL/92 S.sid
FROM Sailors S, Boats B, Reserves R
standard, but some
WHERE AND
S.sid=R.sid R.bid=B.bid systems don’t support it.
AND B.color =‘red’
INTERSECT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color
=‘green’ Nested Queries Find names of sailors who’ve reserved boat #103:
SELECT
S.sname
FROM
Sailors S
WHERE
IN SELECT
S.sid ( R.sid
FROM
Reserves R
WHERE
R.bid=103)
- A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) • To find sailors who’ve not reserved #103, use NOT IN.
- To understand semantics of nested queries, think of a
nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery.
Nested Queries with Correlation
Find names of sailors who’ve reserved boat #103:SELECT
S.sname
FROM
Sailors S
WHERE EXISTS SELECT
( *
FROM
Reserves R
WHERE AND
R.bid=103 S.sid=R.sid)
- EXISTS is another set comparison operator, like >If UNIQUE is used, and * is replaced by R.bid , finds sailors with at most one reservation for boat #103. (UNIQUE checks for duplicate tuples; * denotes all attributes. Why do we have to replace * by R.bid ?)
- Illustrates why, in general, subquery must be re-computed for
More on Set-Comparison Operators
- We’ve already seen IN, EXISTS and UNIQUE. Can also use NOT IN, NOT EXISTS and NOT UNIQUE .
- Also available: <value> op , op op
ANY, ALL <expr> , , , , , op
IN
• Find sailors whose rating is greater than that of some
sailor called Horatio: SELECT * FROM Sailors S WHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2
Rewriting
S.sid
AND
R2.bid=B2.bid
AND
S2.sid=R2.sid
WHERE
Sailors S2, Boats B2, Reserves R2
FROM
S2.sid
SELECT
(
IN
AND
INTERSECT Queries Using
B.color =‘red’
AND
R.bid=B.bid
AND
S.sid=R.sid
WHERE
Sailors S, Boats B, Reserves R
FROM
S.sid
Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT
IN • Similarly, EXCEPT queries re-written using NOT IN.
B2.color=‘green’)
SELECT S.sname
(1) FROM
Sailors S Division in SQL
WHERE NOT EXISTS (( SELECT B.bid
FROM Boats B) EXCEPT Find sailors who’ve reserved all boats.
( SELECT R.bid
- Let’s do it the hard way, FROM Reserves R
WHERE R.sid=S.sid))
without EXCEPT:
(2) SELECT
S.sname
FROM
Sailors S
WHERE NOT EXISTS SELECT
( B.bid
FROM
Boats B
WHERE NOT EXISTS SELECT
( R.bid Sailors S such that ...
FROM
Reserves R
there is no boat B without ... WHERE
R.bid=B.bid
AND
R.sid=S.sid)) Bag Semantics
- Although the SELECT-FROM-WHERE statement uses bag semantics, the default for union, intersection, and difference is set semantics.
- – That is, duplicates are eliminated as the operation is applied.
Motivation: Efficiency
- When doing projection, it is easier to avoid eliminating duplicates.
- – Just work tuple-at-a-time.
- For intersection or difference, it is most efficient to sort the relations first.
- – At that point you may as well eliminate the duplicates anyway.
- Force the result to be a set by SELECT DISTINCT . . .
- Force the result to be a bag (i.e., don’t eliminate duplicates) by ALL, as in . . . UNION ALL . . .
Join Expressions
- SQL provides several versions of (bag) joins.
- These expressions can be stand-alone queries or used in place of relations in a FROM clause.
Products and Natural Joins
- Natural join: R NATURAL JOIN S;
- Product: R CROSS JOIN S;
- Example:
Sailors NATURAL JOIN Reserves;
- Relations can be parenthesized subqueries, as well.
Theta Join
- R JOIN S ON <condition>
- Example:
Sailors S JOIN Reserves R ON S.sid = R.sid;
2. Optional ON <condition> after JOIN.
Outerjoins
- R OUTER JOIN S is the core of an outerjoin expression. It is modified by: 1. Optional NATURAL in front of OUTER.
3. Optional LEFT, RIGHT, or FULL before OUTER.
LEFT = pad dangling tuples of R only. RIGHT = pad dangling tuples of S only. FULL = pad both; this choice is the default.
- Significant extension of relational algebra
SELECT MAX
FROM
Sailors S
SELECT
S.sname
FROM
Sailors S
WHERE
S.rating= (
(S2.rating)
DISTINCT
FROM
Sailors S2)
single column SELECT COUNT
(
DISTINCT
S.rating)
FROM
Sailors S
WHERE
S.age)
(
Aggregate Operators
MIN (A)
COUNT (*)
COUNT ( [
DISTINCT ] A)
SUM ( [
DISTINCT ] A)
AVG ( [
DISTINCT ] A)
MAX (A)
SELECT AVG
SELECT AVG
(S.age)
FROM
Sailors S
WHERE
S.rating=10
SELECT COUNT
(*)
FROM
Sailors S
S.sname =‘Bob’
- The first query is illegal!
S.sname, S.age
Find name and age of the oldest sailor(s)
(We’ll look into the reason a bit later, when we discuss
SELECT
S.sname,
MAX
(S.age)
FROM
Sailors S
SELECT
GROUP BY .)
FROM
- The third query is equivalent to the second query, and is allowed in the SQL/92 standard, but is not supported in some systems.
Sailors S
Sailors S2)
FROM
(S2.age)
SELECT MAX
(
WHERE
S.sname, S.age
FROM
Sailors S
SELECT
Sailors S2)
FROM
(S2.age)
SELECT MAX
WHERE
S.age = ( Motivation for Grouping
- So far, we’ve applied aggregate operators to all
(qualifying) tuples. Sometimes, we want to apply them to each of several groups of tuples.
- Consider: Find the age of the youngest sailor for each rating level.
In general, we don’t know how many rating levels
- – exist, and what the rating values for these levels are! Suppose we know that rating values go from 1 to 10;
- – we can write 10 queries that look like this (!):
SELECT MIN (S.age) For i = 1, 2, ... , 10:
FROM Sailors S
GROUP BY HAVING
Queries With and SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY
grouping-list HAVING group-qualification
- The target-list contains (i) attribute names (ii) terms with aggregate operations (e.g., MIN ( S.age )). The attribute list (i) must be a subset of grouping-list.
- Intuitively, each answer tuple corresponds to a group, and
- these attributes must have a single value per group.
Restriction on SELECT Lists With Aggregation
- If any aggregation is used, then each element of the SELECT list must be either:
1. Aggregated, or 2. An attribute on the GROUP BY list.
Requirements on HAVING Conditions
- These conditions may refer to any relation or tuple-variable in the FROM clause.
- They may refer to attributes of those relations, as long as the attribute makes sense within a group; i.e., it is either:
1. A grouping attribute, or 2. Aggregated.
Conceptual Evaluation
- The cross-product of relation-list is computed, tuples that fail
qualification are discarded, ` unnecessary’ fields are deleted,
and the remaining tuples are partitioned into groups by the value of attributes in grouping-list .
- The group-qualification is then applied to eliminate some groups. Expressions in group-qualification must have a single
value per group ! • One answer tuple is generated per qualifying group.
Find age of the youngest sailor with age >= 18, for each rating with at least 2 such sailors rating minage
35.0 71 zorba 10 16.0 74 horatio
33.0 31 lubber
8
55.5 32 andy
8
25.5 58 rusty 10 35.0 64 horatio
7
9
3
35.0 85 art
3
25.5 95 bob
3
63.5 96 frodo
3
25.5 Answer relation: Sailors instance:
1
45.0 29 brutus
7
sid sname rating age 22 dustin
25.5
7
35.0
8
S.rating,
MIN
(S.age)
AS
minage
FROM
Sailors S
WHERE
S.age >= 18
GROUP BY
S.rating
HAVING COUNT
(*) > 1
25.5 SELECT
rating minage
7
1
33.0
3
25.5
3
63.5
3
25.5
45.0
3
7
35.0
8
55.5
8
25.5
9
35.0
10
25.5 rating age
63.5
3
33.0
25.5
7
35.0
8
25.5 rating age
7
45.0
1
8
3
55.5
8
25.5 10 35.0
7
35.0 10 16.0
9
35.0
3
25.5
35.0 Find age of the youngest sailor with age >= 18, for each rating with at least 2 such sailors rating minage
7
7
3
25.5
3
63.5
3
25.5
7
45.0
35.0
1
8
55.5
8
25.5
9
35.0
10
35.0 HAVING COUNT (*) > 1 AND EVERY (S.age <=60) What is the result of changing EVERY to ANY?
33.0
25.5 rating age
35.0
8
8
25.5 rating age
7
45.0
1
33.0
8
55.5
25.5 10 35.0
3
7
35.0 10 16.0
9
35.0
3
25.5
3
63.5
Find age of the youngest sailor with age >= 18, for each rating with at least 2 such sailors and with every sailor under 60.
For each red boat, find the number of reservations for this boat
SELECT COUNT
B.bid, (*) AS scount
FROM
Boats B, Reserves R
WHERE AND
R.bid=B.bid B.color =‘red’
GROUP BY
B.bid
- What do we get if we remove B.color =‘red’ from the
WHERE clause and add a HAVING clause with this condition?
Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age)
SELECT MIN
S.rating , (S.age) FROM
Sailors S
WHERE
S.age > 18
GROUP BY
S.rating HAVING SELECT COUNT
1 < ( (*)
FROM
Sailors S2
WHERE S.rating =S2.rating) • Shows HAVING clause can also contain a subquery.
- Compare this with the query where we considered only ratings with 2 sailors over 18!
- What if HAVING clause is replaced by:
- –
Find those ratings for which the average age is the minimum over all ratings
AS
(S.age)
AS
avgage
FROM
Sailors S
S.rating)
Temp
S.rating,
WHERE
Temp.avgage = (
SELECT MIN
(Temp.avgage)
Correct solution (in SQL/92):
Aggregate operations cannot be nested! WRONG
AVG
SELECT
SELECT
(
S.rating
FROM
Sailors S
WHERE
S.age = (
SELECT MIN
AVG
(
(S2.age))
FROM
Sailors S2)
SELECT
Temp.rating, Temp.avgage
FROM
GROUP BY
Null Values
- Field values in a tuple are sometimes unknown (e.g., a rating
(e.g., no spouse’s has not been assigned) or inapplicable name).
SQL provides a special value null for such situations.
- – • The presence of
null complicates many issues. E.g.: Special operators needed to check if value is/is not null .
- – Is rating>8 true or false when rating is equal to null ? What
- – about AND, OR and NOT connectives? We need a 3-valued logic (true, false and unknown ).
- – Meaning of constructs must be defined carefully. (e.g., >– WHERE clause eliminates rows that don’t evaluate to true.) New operators (in particular, outer joins ) possible/nee
- –
Three-Valued Logic
- To understand how AND, OR, and NOT work in 3-valued logic, think of TRUE = 1, FALSE = 0, and UNKNOWN = ½.
- AND = MIN; OR = MAX, NOT( ) = 1- .
x x
- Example: TRUE AND (FALSE OR NOT(UNKNOWN))
= MIN(1, MAX(0, (1 - ½ ))) = MIN(1, MAX(0, ½ ) = MIN(1, ½ ) = ½.
Surprising Example
- From the following Sailors relation: sid sname rating age
22 Dustin
7 SELECT sid 58 Lubber 8 FROM Sailors WHERE age < 20 OR age >= 20;
UNKNOWN UNKNOWN
Constraints and Triggers
- A
constraint
is a relationship among data elements that the DBMS is required to enforce.
- – Example: key, foreign key constraints.
: event, condition, action
- Triggers
- – More flexible than simple constraints – Easier to implement than complex constraints.
Kinds of Constraints • Keys .
- Foreign-key , or referential-integrity.
- Value-based constraints.
– Constrain values of a particular attribute.
- Tuple-based constraints.
- – Relationship among components.
• Assertions : any SQL boolean expression.
Foreign Keys (Review) • Consider Relation Sells(bar, beer, price) .
- A constraint that requires a beer in Sells to be a beer in Beers is called a foreign - constraint.
key
- 2 possible violation events/conditions:
- – insert/update to Beer – delete/update on Sells
- 4 possible actions
- – Reject, Cascade, Set NULL, Set Value
Attribute-Based Checks
- Constraints on the value of a particular attribute.
- Add: CHECK( <condition> ) to the declaration for the attribute.
- The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery.
Example
CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) CHECK ( beer IN
(SELECT name FROM Beers)), price REAL CHECK ( price <= 5.00 ) ); Timing of Checks
- Attribute-based checks performed only when a value for that attribute is inserted or updated.
- – Example : CHECK (price <= 5.00) checks
every new price and rejects the modification (for that tuple) if the price is more than $5.
- – Example : CHECK (beer IN (SELECT
name FROM Beers)) not checked if a beer is deleted from Beers (unlike foreign-keys).
Tuple-Based Checks
- CHECK ( <condition> ) may be added as a relation-schema element.
- The condition may refer to any attribute of the relation.
- – But any other attributes or relations require a subquery.
- Checked on insert or update only.
Example: Tuple-Based Check
- Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL,
CHECK (bar = ’Joe’’s Bar’ OR
price <= 5.00) );
Assertions
- These are database-schema elements, like relations or views.
- Defined by:
CREATE ASSERTION <name> CHECK ( <condition> );
- Condition may refer to any relation or attribute in the database schema.
Example: Assertion
- In Sells(bar, beer, price) , no bar may charge an average of more than $5.
CREATE ASSERTION NoRipoffBars CHECK ( NOT EXISTS (
Bars with an average price
SELECT bar FROM Sells
above $5
GROUP BY bar HAVING 5.00 < AVG(price)
));
Example: Assertion
- In Drinkers(name, addr, phone) and
Bars(name, addr, license) , there cannot be
more bars than drinkers.CREATE ASSERTION FewBar CHECK ( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) );
Timing of Assertion Checks
- In principle, we must check every assertion after every modification to any relation of the database.
- A clever system can observe that only certain changes could cause a given assertion to be violated.
- – Example : No change to Beers can affect FewBar. Neither can an insertion to Drinkers.
Triggers: Motivation
- Assertions are powerful, but the DBMS often can’t tell when they need to be checked.
- Attribute- and tuple-based checks are checked at known times, but are not powerful.
- Triggers let the user decide when to check for a powerful condition.
Event-Condition-Action Rules
- Another name for “trigger” is ,
ECA rule or event-condition-action rule.
- Event : typically a type of database
modification, e.g., “insert on Sells.”
- : Any SQL boolean-valued
Condition expression.
- Action : Any SQL statements.
Preliminary Example: A Trigger
- Instead of using a foreign-key constraint and rejecting insertions into
Sells(bar, beer, price) with unknown
beers, a trigger can add that beer to Beers, with a NULL manufacturer.
Example: Trigger Definition The event
CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW
The condition WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers))
INSERT INTO Beers(name) The action
VALUES(NewTuple.beer); Options: CREATE TRIGGER
- CREATE TRIGGER <name>
- Option: CREATE OR REPLACE TRIGGER <name>
- – Useful if there is a trigger with that name and you want to modify the trigger.
Options: The Event • AFTER can be BEFORE.
- – Also, INSTEAD OF, if the relation is a view.
- A great way to execute view modifications: have triggers translate them to appropriate modifications on the base tables.
- INSERT can be DELETE or UPDATE.
- – And UPDATE can be UPDATE . . . ON a particular attribute.
Options: FOR EACH ROW
- Triggers are either “row-level” or
“statement-level.”
- FOR EACH ROW indicates row-level; its absence indicates statement-level.
- : execute once for
Row level triggers each modified tuple.
• Statement-level triggers : execute once
for an SQL statement, regardless of how many tuples are modified.
Options: REFERENCING
- INSERT statements imply a new tuple
(for row-level) or new table (for statement-level).
– The “table” is the set of inserted tuples.
- DELETE implies an old tuple or table.
- UPDATE implies both.
- Refer to these by [NEW OLD][TUPLE TABLE] AS <name>
Options: The Condition
- Any boolean-valued condition is appropriate.
- It is evaluated before or after the triggering event, depending on whether BEFORE or AFTER is used in the event.
- Access the new/old tuple or set of tuples through the names declared in the REFERENCING clause.
Options: The Action
- There can be more than one SQL statement in the action.
- – Surround by BEGIN . . . END if there is more than one.
- But queries make no sense in an action, so we are really limited to modifications.
Another Example
- Using Sells(bar, beer, price) and a unary relation RipoffBars(bar) created for the purpose, maintain a list of bars that raise the price of any beer by more than $1.
The Trigger
- – The event only changes to prices
CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING
Updates let us talk about old Condition:
OLD ROW AS ooo and new tuples a raise in
NEW ROW AS nnn We need to consider price > $1 each price change
FOR EACH ROW WHEN(nnn.price > ooo.price + 1.00) When the price change
INSERT INTO RipoffBars is great enough, add
VALUES(nnn.bar); the bar to RipoffBars Triggers on Views
- Generally, it is impossible to modify a view, because it doesn’t exist.
- But an INSTEAD OF trigger lets us interpret view modifications in a way that makes sense.
- Example: We’ll design a view Synergy that has (drinker, beer, bar) triples such that the bar serves the beer, the drinker frequents the bar and likes the beer.
Example: The View Pick one copy of each attribute
CREATE VIEW Synergy AS SELECT Likes.drinker, Likes.beer, Sells.bar FROM Likes, Sells, Frequents WHERE Likes.drinker = Frequents.drinker
AND Likes.beer = Sells.beer AND Sells.bar = Frequents.bar;
Natural join of Likes, Interpreting a View Insertion
- We cannot insert into Synergy --- it is a view.
- But we can use an INSTEAD OF trigger to turn a (drinker, beer, bar) triple into three insertions of projected pairs, one for each of Likes, Sells, and Frequents.
- – The Sells.price will have to be NULL.
The Trigger
CREATE TRIGGER ViewTrig
INSTEAD OF INSERT ON Synergy REFERENCING NEW ROW AS n FOR EACH ROW BEGIN
INSERT INTO LIKES VALUES(n.drinker, n.beer);
INSERT INTO SELLS(bar, beer) VALUES(n.bar, n.beer);
INSERT INTO FREQUENTS VALUES(n.drinker, n.bar); END;
Trigger Differences in Oracle
- Compared with SQL standard triggers,
Oracle has the following differences: 1. Action is a PL/SQL statement.
2. New/old tuples referenced automatically.
3. Strong constraints on trigger actions designed to make certain you can’t fire
off an infinite sequence of triggers.
Database Modifications
- A
modification
command does not return a result (as a query does), but changes the database in some way.
- Three kinds of modifications:
1. Insert a tuple or tuples.
2. Delete a tuple or tuples.
3. Update the value(s) of an existing tuple or tuples.
Insertion
- To insert a single tuple:
INSERT INTO <relation>
VALUES ( <list of values> );
- Example : add to Likes(drinker, beer) the fact that Sally likes Bud.
INSERT INTO Likes
VALUES(’Sally’, ’Bud’); Specifying Attributes in INSERT
- We may add to the relation name a list of attributes.
- Two reasons to do so:
1. We forget the standard order of attributes for the relation.
2. We don’t have values for all attributes, and we want the system to fill in missing
components with NULL or a default value.
Example: Specifying Attributes
- Another way to add the fact that Sally likes Bud to Likes(drinker, beer) :
INSERT INTO Likes(beer, drinker)
VALUES(’Bud’, ’Sally’);
Inserting Many Tuples
- We may insert the entire result of a query into a relation, using the form:
INSERT INTO <relation> ( <subquery> ); Example: Insert a Subquery
- Using Frequents(drinker, bar) , enter into the new relation PotBuddies(name) all of Sally’s “potential buddies,” i.e., those drinkers who frequent at least one bar that Sally also frequents.
Solution Pairs of Drinker tuples where the first is for Sally, The other the second is for drinker someone else,
INSERT INTO PotBuddies
and the bars are the same.
(SELECT d2.drinker FROM Frequents d1, Frequents d2
WHERE d1.drinker = ’Sally’ AND d2.drinker <> ’Sally’ AND d1.bar = d2.bar );
Deletion
- To delete tuples satisfying a condition from some relation:
DELETE FROM <relation> WHERE <condition>; Example: Deletion
- Delete from Likes(drinker, beer) the fact that Sally likes Bud:
DELETE FROM Likes WHERE drinker = ’Sally’ AND beer = ’Bud’; Example: Delete all Tuples
- Make the relation Likes empty:
DELETE FROM Likes; • Note no WHERE clause needed. DELETE FROM Beers b WHERE EXISTS ( SELECT name FROM Beers WHERE manf = b.manf AND name <> b.name);
Beers with the same manufacturer and a different name from the name of the beer represented by tuple b. Semantics of Deletion --- (1)
Example: Delete Many Tuples
- Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer.
- Suppose Anheuser-Busch makes only Bud and Bud Lite.
- Suppose we come to the tuple b for Bud first.
- The subquery is nonempty, because of the Bud Lite tuple, so we delete Bud.
- Now, when b is the tuple for Bud Lite, do we delete that tuple too?
Semantics of Deletion --- (2)
- Answer : we
do delete Bud Lite as well.
- The reason is that deletion proceeds in two stages:
1. Mark all tuples for which the WHERE condition is satisfied.
2. Delete the marked tuples.
Updates
- To change certain attributes in certain tuples of a relation:
UPDATE <relation> SET <list of attribute assignments> WHERE <condition on tuples>; Example: Update
- Change drinker Fred’s phone number to
555-1212: UPDATE Drinkers SET phone = ’555-1212’ WHERE name = ’Fred’;
Example: Update Several Tuples
- Make $4 the maximum price for beer:
UPDATE Sells SET price = 4.00 WHERE price > 4.00; Views (Review)
- A
view
is a “virtual table” = a relation defined in terms of the contents of other tables and views.
- Declare by: CREATE VIEW <name> AS <query&
- Antonym : a relation whose value is
really stored in the database is called a
base table .
Example: View Definition
- CanDrink(drinker, beer) is a view “containing”
the drinker-beer pairs such that the drinker frequents at least one bar that serves the beer: CREATE VIEW CanDrink AS SELECT drinker, beer
FROM Frequents, Sells WHERE Frequents.bar = Sells.bar; Example: Accessing a View • Query a view as if it were a base table.
- – Also: a limited ability to modify views if it makes sense as a modification of one underlying base table.
- Example query :
SELECT beer FROM CanDrink WHERE drinker = ’Sally’;
What Happens When a View Is
Used?- The DBMS starts by interpreting the query as if the view were a base table.
- – Typical DBMS turns the query into something like relational algebra.
- The definitions of any views used by the query are also replaced by their algebraic equivalents, and “spliced into” the expression tree for the query.
Example: View Expansion
PROJ
beer
SELECT
drinker=‘Sally’
CanDrink PROJ
drinker, beer
JOIN Frequents Sells DMBS Optimization
- It is interesting to observe that the typical DBMS will then “optimize” the query by transforming the algebraic expression to one that can be executed faster.
- Key optimizations: 1. Push selections down the tree.
2. Eliminate unnecessary projections.
Example: Optimization PROJ beer
Notice how JOIN most tuples are eliminated from Frequents
SELECT Sells drinker=’Sally’ before the expensive join.
Frequents Summary
- SQL was an important factor in the early acceptance of the relational model; more natural than earlier, procedural query languages.
- Relationally complete; in fact, significantly more expressive power than relational algebra.
- Even queries that can be expressed in RA can often be expressed more naturally in SQL.
- Many alternative ways to write a query; optimizer should look for most efficient evaluation plan.
In practice, users need to be aware of how queries are
- – optimized and evaluated for best results.
Summary (Contd.)
- NULL for unknown field values brings many complications
- SQL allows specification of rich integrity constraints
- Triggers respond to changes in the database
- More advanced DML
- View definition, execution and optimization
- Useful when more general
CREATE TABLE
FROM
B.bname
SELECT
(`Interlake’ <> (
CHECK
noInterlakeRes
CONSTRAINT
(bid,day),
DATE, PRIMARY KEY
day
INTEGER,
bid
CHAR(10),
Reserves ( sname
rating <= 10 )
Boats B
CHAR(10),
Exercise: General Constraints
ICs than keys are involved.
CREATE TABLE
Sailors ( sid
INTEGER,
sname
rating
AND
INTEGER,
age
REAL, PRIMARY KEY
(sid),
CHECK
( rating >= 1
- Can use queries to express constraint.
- Constraints can be named.
- Awkward and wrong!
- If Sailors is empty, the number of Boats tuples can be anything!
- (
- ASSERTION
- From Sells(bar, beer, price) and
SELECT COUNT
FROM
Number of boats plus number of sailors is < 100
Sailors S)
FROM
(S.sid)
( (
CHECK
smallClub
Boats B) < 100 )
FROM
(B.bid)
Sailors S)
(S.sid)
( (
CHAR(10),
Exercise: Constraints Over Multiple
Relationsis the right solution; not associated with either table.
CREATE TABLE
Sailors ( sid
INTEGER,
sname
rating
INTEGER,
age
REAL, PRIMARY KEY
(sid),
CHECK
SELECT COUNT
CREATE ASSERTION
SELECT COUNT
More Example: Trigger
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18 Group-by Aggregation Exercise
Beers(name, manf) , find the average
price of those beers that are either served in at least three bars or are manufactured by Pete’s.
Solution
SELECT beer, AVG(price) FROM Sells GROUP BY beer HAVING COUNT(bar) >= 3 OR beer IN (SELECT name
FROM Beers WHERE manf = ’Pete’’s’);
Beers manu- factured by Pete’s. Beer groups with at least 3 non-NULL bars and also beer groups where the manufacturer is Pete’s.