SQL: Queries, Programming, Triggers

71
abase Management Systems, R. Ramakrishnan and J. Gehrke SQL: Queries, Programming, Triggers Chapter 5

description

SQL: Queries, Programming, Triggers. Chapter 5. Example Schema. We will use these table definitions in our examples. Sailors ( sid : integer , sname : string , rating : integer , age : real ) Boats ( bid : integer , bname : string , color : string ) - PowerPoint PPT Presentation

Transcript of SQL: Queries, Programming, Triggers

Page 1: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 1

SQL: Queries, Programming, Triggers

Chapter 5

Page 2: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 2

Basic SQL Query

relation-list A list of relation names 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: not eliminated)

SELECT [DISTINCT] target-listFROM relation-listWHERE qualification

Page 3: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 3

SQL vs Domain Relational Calculus

SELECT [DISTINCT] target-listFROM relation-listWHERE qualification

I N T A I N T A Sailors T, , , | , , ,

7

Page 4: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 4

Querying Relations (1)

sid cid grade53831 Carnatic101 C53831 Reggae203 B53650 Topology112 A53666 History105 B

SELECT S.name, E.cidFROM Students S, Enrolled EWHERE S.sid=E.sid AND E.grade=“A”

Enrolled

A student with “sid” has an entry in Enrolled

The Enrolled entry has a grade of “A”

What does the following query compute?

sid name login age gpa

53831 Zhang zhang@ee 19 3.2

53650 Smith smith@cs 21 3.9

53666 Jones jones@cs 20 3.5

Students

Retrieve names of students and the courses they received an “A” grade

Page 5: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 5

Querying Relations (2)sid cid grade

53831 Carnatic101 C53831 Reggae203 B53650 Topology112 A53666 History105 B

SELECT S.name, E.cidFROM Students S, Enrolled EWHERE S.sid=E.sid AND E.grade=“A”

Enrolledsid name login age gpa

53831 Zhang zhang@ee 19 3.2

53650 Smith smith@cs 21 3.9

53666 Jones jones@cs 20 3.5

Students

S.name E.cid

Smith Topology112

Page 6: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 6

Example Schema

We will use these table definitions in our subsequent examples.

Sailors(sid: integer, sname: string, rating: integer, age: real)

Boats(bid: integer, bname: string, color: string)

Reserves(sid: integer, bid: integer, day: date)

Make reservations

Page 7: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 7

Example Instances

sid sname rating age22 dustin 7 45.031 lubber 8 55.558 rusty 10 35.0

sid sname rating age28 yuppy 9 35.031 lubber 8 55.544 guppy 5 35.058 rusty 10 35.0

sid bid day22 101 10/10/9658 103 11/12/96

R1

S1

S2

We will use these instances of the Sailors and Reserves relations in our examples.

If the key for the Reserves relation contained only the attributes sid and bid, how would the semantics differ?

Page 8: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 8

Query Result

Define search space

Semantics of SQL

SELECT [DISTINCT] target-listFROM relation-listWHERE qualification

R1 × R2 × R3 × · · ·

Select rows

qualification

Select columns

target-listrelation-list

Projection

˂, ˃, ≤, ≥, =, ≠

QUERY PROCESSOR

Page 9: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 9

Conceptual Evaluation Strategy

Semantics of an SQL query defined in terms of the following conceptual evaluation strategy:– Compute the cross-product of relation-list.– Discard resulting tuples if they fail qualifications.– Delete attributes that are not in target-list.– If DISTINCT is specified, eliminate duplicate rows.

This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers.

Page 10: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 10

Example of Conceptual EvaluationSELECT S.snameFROM Sailors S, Reserves RWHERE S.sid=R.sid AND R.bid=103

(sid) sname rating age (sid) bid day22 dustin 7 45.0 22 101 10/10/9622 dustin 7 45.0 58 103 11/12/9631 lubber 8 55.5 22 101 10/10/9631 lubber 8 55.5 58 103 11/12/9658 rusty 10 35.0 22 101 10/10/9658 rusty 10 35.0 58 103 11/12/96

S×R

DisqualifiedRemove

Irrelevantcolumns

Answer

Page 11: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 11

Example of Conceptual Evaluation

SELECT S.snameFROM Sailors S, Reserves RWHERE S.sid=R.sid AND R.bid=103

(sid) sname rating age (sid) bid day22 dustin 7 45.0 22 101 10/10/9622 dustin 7 45.0 58 103 11/12/9631 lubber 8 55.5 22 101 10/10/9631 lubber 8 55.5 58 103 11/12/9658 rusty 10 35.0 22 101 10/10/9658 rusty 10 35.0 58 103 11/12/96

S×R

Page 12: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 12

A Note on Range Variables

Really needed only if the same relation appears twice in the FROM clause. The previous query can be written in two ways:

SELECT S.snameFROM Sailors S, Reserves RWHERE S.sid=R.sid AND bid=103

SELECT snameFROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103

It is good style,however, to userange variablesalways!

OR

Range variable

Page 13: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 13

Find sailors who’ve reserved at least one boat

Would adding DISTINCT to this query make a difference? Remove duplicate sid

What is the effect of replacing S.sid by S.sname in the SELECT clause? Since two sailors may have the same name, some sailor may have no reservation even his/her name is in the output

SELECT S.sidFROM Sailors S, Reserves RWHERE S.sid = R.sid

Page 14: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 14

Find sailors who’ve reserved at least one boat

SELECT S.sidFROM Sailors S, Reserves RWHERE S.sid = R.sid

Given a sailor sid

sid has a reservation

Sailors(sid, sname, rating, age)

Reserves(sid, bid, day)

sid has a reservation

Page 15: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 15

Name begins and ends with ‘B’ and contains at least three characters

Arithmetic Expressions and Strings

LIKE is used for string matching. ‘_ ’ stands for any one character and ‘%’ stands for 0 or more arbitrary characters.

SELECT S.age, age1 = S.age-5, 2*S.age AS age2FROM Sailors SWHERE S.sname LIKE ‘B_%B’

AS and = are two ways to name fields in result

Page 16: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 16

Find names of sailors who’ve reserved a red or a green boat

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’)

Sailors(sid, sname, rating, age)

Reserves(sid, bid, day)

Boats(bid, bname, color)

sid has a reservation for bid

bid is a boat

color = ‘red’ OR color = ‘green’

Page 17: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 17

Find names of sailors who’ve reserved a red or a green boat

UNION: Compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries).

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNIONSELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

Name of sailors who’ve reserved

red boats

Name of sailors who’ve reserved

green boats

Page 18: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 18

EXCEPT

What do we get if we replace UNION by EXCEPT?Find the sids of all sailors who have reserved red boats but not green boats

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ EXCEPTSELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

Name of sailors who’ve reserved

red boats

Name of sailors who’ve reserved

green boats

Page 19: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 19

Find names of sailors who’ve reserved a red and a green boat

Page 20: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 20

Find names of sailors who’ve reserved a red and a green boat

Sailors(sid, sname, rating, age)

Reserves(sid, bid, day)

Boats(bid, bname, color)

bid is a boat

sid has a reservation for bid

‘red’

Reserves(sid, bid, day)

Boats(bid, bname, color)

That bid is a boat

sid also has a reservation for

another bid

‘green’B2

R2

B1

R1

SELECT S.nameFROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2WHERE S.sid=R1.sid AND R1.bid=B1.bid The sailor reserves 1st boat AND S.sid=R2.sid AND R2.bid=B2.bid The same sailor reserves 2nd boat AND (B1.color=‘red’ AND B2.color=‘green’)

Page 21: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 21

Find names of sailors who’ve reserved a red and a green boat

No boat has two colors → Result is empty !

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ AND B.color=‘green’)

Can’t we say:

Page 22: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 22

Find names of sailors who’ve reserved a red and a green boat

INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples.

Included in the SQL/92 standard, but some systems don’t support it.

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’INTERSECT

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

Name of sailors who’ve reserved

red boats

Name of sailors who’ve reserved

green boats

Page 23: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 23

Nested Queries

A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.)

To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery.

To find sailors who’ve not reserved #103, use NOT IN.

SELECT S.snameFROM Sailors SWHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103)

Find names of sailors who’ve reserved boat #103

All “boat 103”

reservationsSailor S has at least one

of these reservations

Page 24: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 24

Query: Find names of sailors who’ve reserved boat #103

Nested Queries with Correlation (1)

EXISTS tests whether a set is nonempty. SELECT S.sname

FROM Sailors SWHERE EXISTS (SELECT * FROM Reserves R WHERE S.sid=R.sid AND R.bid=103)

Sailor S reserves boat 103

S

Page 25: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 25

NOT EXIST

SELECT S.snameFROM Sailors SWHERE NOT EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid)

Use NOT EXIST to find the names of

sailors who have not reserved a red boat

Page 26: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 26

Query: Find names of sailors who reserve boat 103 at most once.

Nested Queries with Correlation (2)

UNIQUE returns true if no row appears more than once. (Note: returns true if answer is empty)

Can we replace “SELECT R.bid” by “ SELECT * ” ? No, A sailor may reserve boat 103 on different days; and

UNIQUE would return true

SELECT S.snameFROM Sailors SWHERE UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid)“at most

once”

Page 27: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 27

More on Set-Comparison Operators

Also available: op ANY, op ALL , where op: ˃, ˂, =, ≠, ≥, ≤

Example: “Find sailors whose rating is greater than that of some sailor called Horatio”

SELECT *FROM Sailors SWHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’)

The subquery must return a row that makes the comparison true, in order for S.rating > ANY … to return true

Page 28: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 28

Rewriting INTERSECT Queries Using IN

Find sid’s of sailors who’ve reserved both a red and a green boat:

SELECT S.sidFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’)

Similarly, we can rewrite EXCEPT queries using NOT IN.

sid of sailors who’ve reserved

green boats

sid of sailors who’ve reserved

red boats

AND S.sid IN

Page 29: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 29

Division Operations in SQL (1)

Find names of sailors who’ve reserved all boat:

SELECT S.snameFROM Sailors SWHERE NOT EXIST ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid = S.sid ))

All boatsAll boats reserved

by the sailor

Boats not reserved by the sailor

The sailor reserved all boats

Page 30: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 30

Division Operations in SQL (2)

Find names of sailors who’ve reserved all boat:

SELECT S.snameFROM Sailors SWHERE NOT EXIST ((SELECT B.bid FROM Boats B WHERE NOT EXISTS (SELECT R.bid FROM Reserves R WHERE R.bid = B.bid AND R.sid = S.sid))

Sailor S such that … there is no boat B without … a Reserves tuple showing S reserved B.

Sailor S reserved

boat B

such that there is

no boat B without a reservation

Sailor S

showing

Page 31: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 31

Aggregate OperatorsSignificant extension of relational

algebraCOUNT (*) The number of rows in the relation

COUNT ([DISTINCT] A) The number of (unique) values in the A column

SUM ([DISTINCT] A) The sum of all (unique) values in the A column

AVG ([DISTINCT] A) The average of all (unique) values in the A column

MAX (A) The maximum value in the A column

MIN (A) The minimum value in the A column

Page 32: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 32

Aggregate Operators

SELECT AVG (S.age)FROM Sailors SWHERE S.rating=10

SELECT COUNT (*)FROM Sailors S

SELECT AVG (DISTINCT S.age)FROM Sailors SWHERE S.rating=10

SELECT S.snameFROM Sailors SWHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2)

SELECT COUNT (DISTINCT S.rating)FROM Sailors SWHERE S.sname=‘Bob’

Count the number of sailors

Find the average age of sailors with

a rating of 10 Find the average of the distinct ages of sailors with a rating

of 10

Count the number of distinct ratings of

sailors called “Bob”

Find the name of sailors with

the highest rating

Page 33: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 33

Aggregate Operators

SELECT AVG (S.age)FROM Sailors SWHERE S.rating=10

SELECT COUNT (*)FROM Sailors S

SELECT AVG (DISTINCT S.age)FROM Sailors SWHERE S.rating=10

SELECT S.snameFROM Sailors SWHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2)

SELECT COUNT (DISTINCT S.rating)FROM Sailors SWHERE S.sname=‘Bob’

Page 34: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 34

SELECT S.snameFROM Sailors SWHERE ( SELECT MAX (S2.rating) FROM Sailors S2 ) = S.rating

SELECT S.snameFROM Sailors SWHERE S.rating = (SELECT MAX(S2.rating) FROM Sailors S2)

Comparing a number with a

relation is allowed here

Allowed in SQL/92

standard, but is not supported

in some systems

Find name and age of the oldest sailor(s)

Page 35: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 35

SELECT S.sname, MAX (S.age)FROM Sailors S

Find name and age of the oldest sailor(s)

If the SELECT clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause (aggregate value for each group – discussed later.)

Only aggregate operations allowed

Illegal

Page 36: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 36

SIMPLE GROUP BY So far, we’ve applied aggregate operators to all

(qualifying) tuples.

RelationQualifierAggregator32

SELECT AVG (S.age)FROM Sailors SWHERE S.rating=10

Find the average age of sailors with

a rating of 10

Qualifier

Aggregator

Page 37: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 37

GROUP BY and HAVING So far, we’ve applied aggregate operators to all

(qualifying) tuples.

Sometimes, we want to apply them to each of several groups of tuples.

RelationQualifierAggregator32

RelationGroup 1Aggregator12Group 2

Group 3

Aggregator

Aggregator

911

Only one group

Page 38: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 38

GROUP BY and HAVING (2)

Consider: Find the age of the youngest sailor for each rating level. /* Min(age) for multiple groups

– If we know that rating values go from 1 to 10, we can write 10 queries that look like this:

– In general, we don’t know how many rating levels exist, and what the rating values for these levels are !

SELECT MIN (S.age)FROM Sailors SWHERE S.rating = i

For i = 1, 2, ... , 10:

Page 39: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 39

Queries With GROUP BY and HAVING

SELECT [DISTINCT] target-listFROM relation-listWHERE qualificationGROUP BY grouping-listHAVING group-qualification

SELECTFROM

WHERE

Group 1

Group 2

Group 3

Qualifier selecting groups

Aggregator129 Aggregator

GROUP BYHAVING

MIN(Attribute)

Output a table

Page 40: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 40

Queries With GROUP BY and HAVING

The target-list contains: (i) attribute names, (ii) terms with aggregate operations (e.g., MIN (S.age)).

Each answer tuple belongs to a group. The attribute list must be a subset of grouping-list. A group is a set of tuples that have the same value for all

attributes in grouping-list.

SELECT [DISTINCT] target-listFROM relation-listWHERE qualificationGROUP BY grouping-listHAVING group-qualification

Page 41: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 41

Conceptual Evaluation

1. The cross-product of relation-list is computed

2. Tuples that fail qualification are discarded

3. `Unnecessary’ fields are deleted

4. The remaining tuples are partitioned into groups by the value of attributes in grouping-list.

5. The group-qualification is then applied to eliminate some groups

6. One answer tuple is generated per qualifying group

SELECT [DISTINCT] target-listFROM relation-listWHERE qualificationGROUP BY grouping-listHAVING group-qualification

Page 42: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 42

rating age1 33.07 45.07 35.08 55.510 35.0

Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.ratingHAVING COUNT (*) > 1

sid sname rating age22 dustin 7 45.031 lubber 8 55.571 zorba 10 16.064 horatio 7 35.029 brutus 1 33.058 rusty 10 35.0

Input relation

Disqualify

Only S.rating and S.age are mentioned in SELECT

4 rating groups

rating7 35.0

age Answer

Only one group

satisfies HAVING

Sailors

Page 43: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 43

Find the age of the youngest sailor with age ≥ 18

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.ratingHAVING COUNT (*) > 1

Find the age of the youngest sailor with age ≥ 18, for each rating

Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.rating

SELECT MIN (S.age)FROM Sailors SWHERE S.age >= 18

“GROUP BY and HAVING” Examples

Page 44: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 44

For each red boat, find the number of reservations for this boat

SELECT B.bid, COUNT (*) AS scountFROM Boats B, Reserves RWHERE R.bid=B.bid AND B.color=‘red’GROUP BY B.bid

1) Find all reservations for red boats

2) Group the reservations for red boats according to bid

3) Count the number of reservations for each red-boat group

Page 45: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 45

Illegal Having Clause

SELECT B.bid, COUNT (*) AS scountFROM Boats B, Reserves RWHERE R.bid=B.bidGROUP BY B.bidHAVING B.color=‘red’

Having clause is to select groups; but B.Color is not in grouping-list

HAVING B.color=‘red’

SELECTFROM

WHERE

Group 1

Group 2

Group 3

Qualifier selecting groups

Aggregator?? Aggregator

GROUP BY“bid”HAVING

“red” ?Output a table

Page 46: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 46

Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors

Step 1: Select the desired tuples (using WHERE)

Step 2: Form the groups (using GROUP BY)

Step 3: Select the desired groups (using HAVING)

Step 4: Compute the aggregation for each group (using COUNT, MAX, AVG, etc.)

Needs aggregate function

Page 47: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 47

Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors

Sailo

rs

Age>18

Group S.rating

Rating

Size>1

Min.age22

26WHERE

S.age > 18

GROUP BYS.rating

HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

1 3

2

4

14

32

MIN(S.age)

Page 48: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 48

Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors

WHERES.age > 18

GROUP BYS.rating

HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

14

32

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

MIN(S.age)

1

2

3

4

Page 49: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 49

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors

1) Find all sailors older than 18

2) Group qualified sailors according to rating

3.2) Discard groups with less than two sailors

4) Find youngest age for each qualified group

3.1) Count the number of sailors in a group

Number of sailors with this rating

Page 50: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 50

Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

What if HAVING clause is replaced by

“HAVING COUNT(*) > 1” ?

Find the age of the youngest sailor older than 18, for each rating level that has at least two such sailors (MORE IN NEXT PAGE)

Page 51: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 51

Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

Counting includes sailors younger than

18

At least 2 sailors

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING COUNT (*) › 1

Counting only adult

sailorsAt least 2 such

sailors, i.e., older than 18

“age” is not mentioned in this subquery

Find the age of the youngest sailor older than 18 for each rating level that has at least

two such sailors

Page 52: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 52

Find the age of the youngest sailor older than 18, for each rating that has at least 2 sailors

Shows HAVING clause can also contain a subquery. We can use S.rating inside the nested subquery

because it has a single value for the current group of sailors.

SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)

Page 53: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 53

Find those ratings for which the average age is the minimum over all ratings

SELECT S.ratingFROM Sailors SWHERE S.age = (SELECT MIN (AVG (S2.age)) FROM Sailors S2)

Aggregate operations cannot

be nested

Page 54: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 54

Find those ratings for which the average age is the minimum over all ratings

SELECT Temp.rating, Temp.avgageFROM (SELECT S.rating, AVG (S.age) AS avgage FROM Sailors S GROUP BY S.rating) AS TempWHERE Temp.avgage = (SELECT MIN (Temp.avgage) FROM Temp)

Correct solution (in SQL/92):

Minimum over all ratings

Find average age for each rating group

Average age for some rating group

Temp rating avgage

Page 55: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 55

Null Values

Field values in a tuple are sometimes

– unknown (e.g., a rating has not been assigned), or

– inapplicable (e.g., no spouse’s name).

SQL provides a special value null for such situations.

Page 56: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 56

Null ValuesThe presence of null complicates many issues: Special operators needed, e.g., IS NULL to test if a value is null.

Is rating>8 true or false when rating is equal to null? null

What about AND, OR and NOT ? Need a 3-valued logic (true, false, and unknown), e.g., (unknown OR false) = unknown.

Meaning of constructs must be defined carefully, e.g., WHERE clause eliminates rows that don’t evaluate to true.Null + 5 = null; but SUM (null, 5) = 5. (nulls can cause some unexpected behavior)

New operators (in particular, outer joins) possible/needed.

Page 57: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 57

Outer Joins

sid bid day22 101 10/10/9658 103 11/12/96

R1sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0

S1

S1 R1 sid sname rating age bid day

22 dustin 7 45.0 101 10/10/9631 lubber 8 55.55 null null58 rusty 10 35.0 103 11/12/96

No match in R1

Page 58: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 58

Integrity Constraints (Review)

An IC describes conditions that every legal instance of a relation must satisfy.– Inserts/deletes/updates that violate IC’s are disallowed.– Can be used to ensure application semantics (e.g., sid is a key),

or prevent inconsistencies (e.g., sname has to be a string, age must be < 200)

Types of IC’s: Domain constraints, primary key constraints, foreign key constraints, general constraints.– Domain constraints: Field values must be of right type. Always

enforced.

Page 59: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 59

General Constraints

Useful when more general ICs than keys are involved.

CREATE TABLE Sailors( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 )

A general constraint 1 ≤ rating ≤ 10

Page 60: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 60

Constraints can be named Can use queries to express constraint

A named general

constraint

Find the name of the boat

General Constraints

CREATE TABLE Reserves ( sname CHAR(10),

bid INTEGER,day DATE,PRIMARY KEY (bid,day),CONSTRAINT noInterlakeResCHECK (`Interlake’ <>

( SELECT B.bnameFROM Boats BWHERE B.bid=bid)))

For each boat

Convenient to have a named constraint, e.g., delete it later:

ALTER TABLE RESERVESDROP CHECK noInterlakeRes

Page 61: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 61

Constraints Over Multiple Relations

CREATE ASSERTION smallClubCHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )

CREATE TABLE Sailors ( sid INTEGER,

sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )

Number of boats plus number of sailors is < 100This is not

checked in Boats. If it is not

modified, the number of Boats

tuples can be anything

Awkward and wrong!ASSERTION is the right solution; not

associated with either table

Page 62: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 62

Triggers

Trigger is a procedure that starts automatically if specified changes occur to the DBMS

Three parts

Event A change to the database that activates the trigger (e.g., BEFORE insert, AFTER update)

Condition A query or test that is run when the trigger is activated (e.g., WHEN total salaries > $1M)

Action A procedure that is executed when the trigger is activated and its condition is true

Condition

Action

Event

Page 63: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 63

Specify Action

The action can be executed before, after, or instead of the triggering event

BEFORE The action is executed before the event that triggered the action

AFTER The action is executed after the triggering event

INSTEADOF

The action is executed and the triggering event is never executed

(1) Event

(2) Action

trig

ger

Page 64: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 64

Two kinds of triggers

An SQL INSERT/DELETE/UPDATE statement may affect multiple rows of a table

Page 65: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 65

Two kinds of triggers

Statement-level trigger: executed once for all the tuples that are changed in one SQL statement.

REFERENCING NEW TABLE AS newtuples, /* Set of new tuples OLD TABLE AS oldtuples /* Set of old tuples

Row-level trigger: executed once for each modified tuple. REFERENCING OLD AS oldtuple,

NEW AS newtuple

newtuples, oldtuple, newtuple can be used in the CONDITION and ACTION clauses

An SQL INSERT/DELETE/UPDATE statement may affect multiple rows of a table

Page 66: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 66

CountTable

age count17 11318 0...

...99 2

Trigger Examples (SQL:1999)CREATE TRIGGER InitCounter

BEFORE INSERT ON SAILORS FOR EACH STATEMENT

INSERT INTO CountTableSET count = 0WHERE age = 18

CREATE TRIGGER IncrCountAFTER INSERT ON SAILORS

FOR EACH ROW UPDATE CountTableSET count = count + 1WHERE age = 18

Statement-level trigger:execute trigger only once to initialize counter

Row-level trigger: evaluate each new sailor to decide whether to increment the counter

CountTable

age count17 11318 229...

...99 2

Page 67: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 67

Statement-Level Trigger Example (SQL:1999)

CREATE TRIGGER youngSailorUpdateAFTER INSERT ON SAILORS /* Event

REFERENCING NEW TABLE AS NewSailorsFOR EACH STATEMENT /* Statement-level trigger (default)

INSERT /* Action INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18

• Give a table name to the set of newly inserted tuples

• OLD TABLE declaration is not needed for INSERT operation

Maintain information on young sailors in a separate YoungSailors table

SailorsNewSailors

≤ 18 YoungSailors

TRIGGER

New tuples

Insert

Page 68: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 68

Row-Level Trigger Example (SQL:1999)

CREAT TRIGGER RatingTriggerAFTER UPDATE OF rating ON SailorsREFERENCING

OLD AS OldTuple, /* value before updateNEW AS NewTuple /* value after update

WHEN (OldTupple.rating ˃ NewTupple.rating)FOR EACH ROW

UPDATE SailorsSET rating = OldTuple.ratingWHERE SID = NewTuple.SID

/* Condition

/* Event

/* Row-level trigger/* Action: Restore /* any attempt to/* lower rating

Sailors(SID, sname, rating, age)

Page 69: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 69

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 relational algebra 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.

Page 70: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 70

Summary (Contd.)

NULL for unknown-field values brings many complications

SQL allows specification of rich integrity constraints Triggers respond to changes in the database

Page 71: SQL:  Queries, Programming, Triggers

Database Management Systems, R. Ramakrishnan and J. Gehrke 71

Midterm Closed-book exam Chapters 1, 2, 3, 4, 5 Date: February 25, 2016

How to prepare ?– For each chapter, spend three hours to review

the slides– Practice the Algebra, Calculus, and SQL

examples in the textbook– Practice the homeworks