+ All Categories
Home > Documents > Database Management System - SourceForge

Database Management System - SourceForge

Date post: 29-Jan-2022
Category:
Upload: others
View: 15 times
Download: 0 times
Share this document with a friend
69
Database Management System Engr. Abdul-Rahman Mahmood MS, MCP, QMR(ISO9001:2000) Usman Institute of Technology University Road, Karachi [email protected] [email protected] alphapeeler.sf.net/pubkeys/pkey.htm http://alphapeeler.sourceforge.net pk.linkedin.com/in/armahmood http://alphapeeler.tumblr.com www.twitter.com/alphapeeler [email protected] www.facebook.com/alphapeeler [email protected] abdulmahmood-sss alphasecure mahmood_cubix 48660186 [email protected] [email protected] VC++, VB, ASP
Transcript
Page 1: Database Management System - SourceForge

Database Management SystemEngr. Abdul-Rahman Mahmood

MS, MCP, QMR(ISO9001:2000)Usman Institute of Technology – University Road, Karachi

[email protected] [email protected]

alphapeeler.sf.net/pubkeys/pkey.htm http://alphapeeler.sourceforge.net

pk.linkedin.com/in/armahmood http://alphapeeler.tumblr.com

www.twitter.com/alphapeeler [email protected]

www.facebook.com/alphapeeler [email protected]

abdulmahmood-sss alphasecure mahmood_cubix 48660186

[email protected] [email protected]

VC++, VB, ASP

Page 2: Database Management System - SourceForge
Page 3: Database Management System - SourceForge

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)

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

Page 4: Database Management System - SourceForge

Example Instances

sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.5

58 rusty 10 35.0

sid sname rating age

28 yuppy 9 35.0

31 lubber 8 55.5

44 guppy 5 35.0

58 rusty 10 35.0

sid bid day

22 101 10/10/96

58 103 11/12/96

R1

S1

S2

We will use these instances of the Sailorsand 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 5: Database Management System - SourceForge

Basic SQL Query

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 opAttr2,” 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!

SELECT [DISTINCT] target-listFROM relation-listWHERE qualification

Page 6: Database Management System - SourceForge

Query Processing… Applying a series of horizontal and vertical filters

Start with the

search space

Page 7: Database Management System - SourceForge

Query Processing… Applying a series of horizontal and vertical filters

Apply vertical

filter

Page 8: Database Management System - SourceForge

Query Processing… Applying a series of horizontal and vertical filters

Apply

horizontal

filter

Page 9: Database Management System - SourceForge

Query Processing… Applying a series of horizontal and vertical filters

Apply

another

vertical

filter

Page 10: Database Management System - SourceForge

Query Processing… Applying a series of horizontal and vertical filters

Apply

another

horizontal

filter

Query result

Page 11: Database Management System - SourceForge

Query Result

Define search space

Semantics of SQL

SELECT [DISTINCT] target-listFROM relation-listWHERE qualification

R1 × R2 × R3 × · · ·

Select rows

qualification

Select columns

target-list

relation-list

Projection

˂, ˃, ≤, ≥, =, ≠

QUERY PROCESSOR

Page 12: Database Management System - SourceForge

Conceptual Evaluation Strategy Semantics of an SQL query defined in terms of the following

conceptual evaluation strategy:

Compute the cross-product of relation-list (search space)

Discard resulting tuples if they fail qualifications (horizontal filtering)

Delete attributes that are not in target-list (vertical filtering)

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 13: Database Management System - SourceForge

Example of Conceptual Evaluation

SELECT S.sname

FROM Sailors S, Reserves R

WHERE S.sid=R.sid AND R.bid=103

(sid) sname rating age (sid) bid day

22 dustin 7 45.0 22 101 10/10/96

22 dustin 7 45.0 58 103 11/12/96

31 lubber 8 55.5 22 101 10/10/96

31 lubber 8 55.5 58 103 11/12/96

58 rusty 10 35.0 22 101 10/10/96

58 rusty 10 35.0 58 103 11/12/96

S×R

Page 14: Database Management System - SourceForge

Example of Conceptual Evaluation

SELECT S.sname

FROM Sailors S, Reserves R

WHERE S.sid=R.sid AND R.bid=103

(sid) sname rating age (sid) bid day

22 dustin 7 45.0 22 101 10/10/96

22 dustin 7 45.0 58 103 11/12/96

31 lubber 8 55.5 22 101 10/10/96

31 lubber 8 55.5 58 103 11/12/96

58 rusty 10 35.0 22 101 10/10/96

58 rusty 10 35.0 58 103 11/12/96

S×R

Page 15: Database Management System - SourceForge

A Note on Range VariablesReally 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

OR

Range variable

It is good style,however, to userange variablesalways!

Page 16: Database Management System - SourceForge

Find sailors who’ve reserved at least one boat

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

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

Page 17: Database Management System - SourceForge

Find sailors who’ve reserved at least one boat

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

Casey 123

Casey 456

Page 18: Database Management System - SourceForge

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 19: Database Management System - SourceForge

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)

Foreign key

Foreign key

`

Page 20: Database Management System - SourceForge

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

If we replace OR by AND in the above query, what do we get?

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‟ OR B.color=„green‟)

Page 21: Database Management System - SourceForge

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

SELECT S.nameFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid

AND B.color=„red‟UNION

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 22: Database Management System - SourceForge

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‟EXCEPT

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: Database Management System - SourceForge

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

SELECT S.name

FROM Sailors S, Boats B1, Reserves R1,

Boats B2, Reserves R2

WHERE 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’)

The 1st boat is red

The 2nd boat is green

Sailors(sid, sname, rating, age)

Reserves(sid, bid, day)

Boats(bid, bname, color)

Foreign key

Foreign key

Page 24: Database Management System - SourceForge

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

FROM Sailors S, Boats B, Reserves R

WHERE S.sid=R.sid AND R.bid=B.bid

AND B.color=‘red’INTERSECT

SELECT S.name

FROM Sailors S, Boats B, Reserves R

WHERE 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 25: Database Management System - SourceForge

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 loopsevaluation: For each Sailors tuple, check the qualification by computing the subquery.

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

SELECT S.sname

FROM Sailors S

WHERE S.sid IN (SELECT R.sid

FROM Reserves R

WHERE R.bid=103)

Find names of sailors who’ve reserved boat #103

Sailor S has at least one of these reservations

Page 26: Database Management System - SourceForge

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 RWHERE S.sid=R.sid AND R.bid=103)

Sailor S reserves boat 103

Page 27: Database Management System - SourceForge

NOT EXIST

SELECT S.snameFROM Sailors SWHERE NOT EXISTS (SELECT *

FROM Reserves RWHERE R.bid=103 AND S.sid=R.sid)

Query: Find names of sailors who’ve

never reserved boat #103

Sailor S reserves boat 103

Page 28: Database Management System - SourceForge

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 RWHERE R.bid=103 AND S.sid=R.sid)

Page 29: Database Management System - SourceForge

More on Set-Comparison OperatorsAlso available: op ANY, op ALL , where op: ˃, ˂, =, ≠, ≥, ≤

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 S2WHERE S2.sname=„Horatio‟)

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

Page 30: Database Management System - SourceForge

Rewriting INTERSECT

Queries Using IN

Find sid’s of sailors who’ve reserved both a

red and a green boat:

SELECT S.sid

FROM Sailors S, Boats B, Reserves R

WHERE 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 31: Database Management System - SourceForge

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.bidFROM Reserves RWHERE R.sid = S.sid ))

All boats

All boats reserved by the sailor

Boats not reserved by the sailor

The sailor reserved all boats

Page 32: Database Management System - SourceForge

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 BWHERE NOT EXISTS (SELECT R.bid

FROM Reserves RWHERE 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 Sreserved

boat B

such that there is

no boat Bwithout a

reservation

Sailor S

showing

Page 33: Database Management System - SourceForge

Aggregate OperatorsSignificant extension of relational algebra

COUNT (*) 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 34: Database Management System - SourceForge

Aggregate Operators

SELECT AVG (S.age)

FROM Sailors S

WHERE S.rating=10

SELECT COUNT (*)

FROM Sailors S

SELECT AVG (DISTINCT S.age)

FROM Sailors S

WHERE S.rating=10

SELECT S.sname

FROM Sailors S

WHERE S.rating= (SELECT MAX(S2.rating)

FROM Sailors S2)

SELECT COUNT (DISTINCT S.rating)

FROM Sailors S

WHERE 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 names of sailors with the highest rating

Page 35: Database Management System - SourceForge

Aggregate Operators

SELECT AVG (S.age)

FROM Sailors S

WHERE S.rating=10

SELECT COUNT (*)

FROM Sailors S

SELECT AVG (DISTINCT S.age)

FROM Sailors S

WHERE S.rating=10

SELECT S.sname

FROM Sailors S

WHERE S.rating= (SELECT MAX(S2.rating)

FROM Sailors S2)

SELECT COUNT (DISTINCT S.rating)

FROM Sailors S

WHERE S.sname=‘Bob’

Page 36: Database Management System - SourceForge

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 37: Database Management System - SourceForge

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

Page 38: Database Management System - SourceForge

GROUP BY and HAVING (1) 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

Relation

Group 1Aggregator32

Group 2

Group 3

Aggregator

Aggregator

32

32

Page 39: Database Management System - SourceForge

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 40: Database Management System - SourceForge

Queries With GROUP BY and HAVING

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

SELECTFROM

WHERE

Grouping

Grouping

Grouping

Qualifier selecting groups

Aggregator32

43 Aggregator

GROUP BYHAVING

MIN(Attribute)

Output a table

Page 41: Database Management System - SourceForge

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 42: Database Management System - SourceForge

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 (e.g., all sailors with the same rating)

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

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

Example

Page 43: Database Management System - SourceForge

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 44: Database Management System - SourceForge

rating age

1 33.0

7 45.0

7 35.0

8 55.5

10 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 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

Input relation

Disqualify

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

4 rating groups

rating

7 35.0

age Answer

Only one group

satisfies HAVING

Page 45: Database Management System - SourceForge

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 suchsailors

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 46: Database Management System - SourceForge

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 47: Database Management System - SourceForge

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

Grouping over a join of two relations

SELECT B.bid, COUNT (*) AS scount

FROM Boats B, Reserves R

WHERE R.bid=B.bid

GROUP BY B.bid

HAVING B.color=‘red’

B.color is not in the

grouping-list

Note: HAVING clause is to select groups !

Page 48: Database Management System - SourceForge

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

Sai

lors

Age>18

GroupS.rating

Rating

Size>1

Min.age22

26WHERE

S.age > 18

GROUP BYS.rating

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

14

32

SELECT S.rating, MIN(S.age)

Page 49: Database Management System - SourceForge

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

FROM Sailors S2WHERE 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 sailorswith this rating

14

32

Page 50: Database Management System - SourceForge

Find the age of the youngest sailor older than 18, for each rating level 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.

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. /* see next page

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

FROM Sailors S2WHERE S.rating = S2.rating)

Replacing this by“HAVING COUNT(*) > 1”

Page 51: Database Management System - SourceForge

Find the age of the youngest sailor older than 18, for each rating level 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 S2WHERE S.rating = S2.rating)

Counting including 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 include only adult sailors

At least 2 such sailors, i.e., older than 18

“age” is notmentioned in this subquery

Page 52: Database Management System - SourceForge

Find those ratings for which the average

age is the minimum over all ratings

SELECT S.rating

FROM Sailors S

WHERE S.age = (SELECT MIN (AVG (S2.age))

FROM Sailors S2)

Aggregate operations cannot

be nested

Page 53: Database Management System - SourceForge

Find those ratings for which the average

age is the minimum over all ratings

SELECT Temp.rating, Temp.avgage

FROM (SELECT S.rating, AVG (S.age) AS avgage

FROM Sailors S

GROUP BY S.rating) AS Temp

WHERE Temp.avgage = (SELECT MIN (Temp.avgage)

FROM Temp)

Correct solution (in SQL/92):

Minimum over all ratings

Find average age for each rating group.

This table hastwo columns

Average age for some rating group

Output this rating group and its average age

Page 54: Database Management System - SourceForge

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 55: Database Management System - SourceForge

Null Values

The 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 56: Database Management System - SourceForge

Outer Joins

sid bid day

22 101 10/10/96

58 103 11/12/96

R1

sid 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/96

31 lubber 8 55.55 null null

58 rusty 10 35.0 103 11/12/96

No match in

R1

No “sid = 31”

Page 57: Database Management System - SourceForge

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, agemust 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.

We have not discussed this

Page 58: Database Management System - SourceForge

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 constraintWhen a row is inserted or an

existing row is modified, the

command is rejected if this

condition is false

Page 59: Database Management System - SourceForge

Can use queries to express constraintConstraints can be named

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 noInterlakeRes

CHECK (`Interlake’ <>

( SELECT B.bname

FROM Boats B

WHERE B.bid=bid)))

“Interlake” boats cannot be reserved

Page 60: Database Management System - SourceForge

Constraints Over Multiple Relations

CREATE ASSERTION smallClub

CHECK( (SELECT COUNT (S.sid) FROM Sailors S)

+ (SELECT COUNT (B.bid) FROM Boats B) < 100 )

ASSERTION is not

associated with either

table

Number of boats plus

number of sailors is <

100

Page 61: Database Management System - SourceForge

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

Three parts

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

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

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

Condition

Action

Event

Page 62: Database Management System - SourceForge

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

BEFOREThe action is executed before theevent that triggered the action is executed

AFTERThe 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 63: Database Management System - SourceForge

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 tuplesOLD 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

Page 64: Database Management System - SourceForge

CountTable

age count

17 113

18 0...

.

.

.

99 2

Trigger Examples (SQL:1999)CREATE TRIGGER InitCounter

BEFORE INSERT ON SAILORSFOR EACH STATEMENTINSERT INTO CountTable

SET count = 0WHERE age = 18

CREATE TRIGGER IncrCountAFTER INSERT ON SAILORSREFERENCING NEW AS newrowWHEN newrow.age = 18 FOR EACH ROW

UPDATE CountTableSET count = count + 1WHERE age = 18

Statement-level trigger (default):

Execute trigger only once to initialize counter

Row-level trigger:

Evaluate each new sailor to decide whether to increment the counter

CountTable

age count

17 113

18 229...

.

.

.

99 2

Page 65: Database Management System - SourceForge

Statement-Level Trigger Example (SQL:1999)

CREATE TRIGGER youngSailorUpdate

AFTER INSERT ON SAILORS /* Event

REFERENCING NEW TABLE AS NewSailors

FOR 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

Maintain information on young sailors in a separate YoungSailorstable

SailorsNewSailors

≤ 18 YoungSailors

TRIGGER

New tuples

Page 66: Database Management System - SourceForge

Row-Level Trigger Example (SQL:1999)

CREAT TRIGGER RatingTrigger

AFTER UPDATE OF rating ON Sailors

REFERENCING

OLD AS OldTuple, /* value before update

NEW AS NewTuple /* value after update

WHEN (OldTupple.rating ˃ NewTupple.rating)

FOR EACH ROW

UPDATE Sailors

SET rating = OldTuple.rating

WHERE SID = NewTuple.SID

/* Row-level trigger

/* Condition

/* Event

/* Action: Restore

/* any attempt to

/* lower rating

Sailors(SID, sname, rating, age)

Page 67: Database Management System - SourceForge

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.

Page 68: Database Management System - SourceForge

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 69: Database Management System - SourceForge

Homework #5

Practice the 50+ SQL examples in Chapter 5

Do the following exercises:

Exercise 5.4.2 (Fulltime is 40 hours, Hint: Use SELECT in HAVING clause)

Exercise 5.4.3 (Hint: Use “ALL” and nested SELECT)

Exercise 5.8.2.e (Hint: Use an assertion with “NOT IN”)

Exercise 5.10.3 (Hint: Add CHECK statement to the Workstable.)

Due: 31/10/2013


Recommended