Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on...

86
Kjell Orsborn 22-03-27 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No. ?? A second course on development of database systems Kjell Orsborn Uppsala Database Laboratory Department of Information Science, Uppsala University, Uppsala, Sweden
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    220
  • download

    0

Transcript of Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on...

Page 1: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

1UU - DIS - UDBL

DATABASE SYSTEMS - 10pCourse No. ??

A second course on development of database systems

Kjell OrsbornUppsala Database Laboratory

Department of Information Science, Uppsala University, Uppsala, Sweden

Page 2: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

2UU - DIS - UDBL

Introduction to SQL

Elmasri/Navathe ch 8???

Lecture 3

Kjell Orsborn

Department of Information Science

Uppsala University, Uppsala, Sweden

Page 3: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

3UU - DIS - UDBL

Contents lecture 3 (Elmasri/Navathe ch. 8)

• SQL– Basic Structure

– Set Operations

– Aggregate Functions

– Null Values

– Nested Subqueries

– Derived Relations

– Views

– Modification of the Database

– Joined Relations

– Data Definition Language

– Embedded SQL

Page 4: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

4UU - DIS - UDBL

The SQL database language

• SQL - Structured Query Language

• Was first developed by IBM in the early 70’s at their San Jose Research Lab. It was called Sequel and was implemented as part of their System R project.

• Current version of the ISO/ANSI SQL standard is SQL-92.

• SQL has become the main language in many commercial RDBMS.

Page 5: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

5UU - DIS - UDBL

Parts of the SQL language

• DDL

• Interactive DML– Queries: SELECT

– Updates: INSERT, DELETE, UPDATE

• Embedded DML

• View definition

• Authorizaton

• Integrity

• Transaction control

Page 6: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

6UU - DIS - UDBL

SELECT expressions in SQL• The select expression is the most common way to express

queries in SQL. Using the schema customer(cname,balance) this might look like:– “Find the names of customers that owe you money.”

• select cnamefrom customerwhere balance < 0

• select customers.cnamefrom customerwhere customer.balance < 0

• select cname as kundnamnfrom customer as cwhere c.balance < 0

Page 7: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

7UU - DIS - UDBL

Basic structure• SQL is based on set and relational operations with certain

modifications and enhancements.• A typical SQL query has the form:

select A1,A2,...,An

from r1,r2,...,rm

where P

– Ai’s represent attributes

– ri’s represent relations

– P is a predicate.

• This is equivalent to the relational algebra expression:A1, A2, ..., An

(P (r1 r2 ... rm))

• The result of an SQL query is a relation.

Page 8: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

8UU - DIS - UDBL

Banking example revisited

• Again we use the bank schema in subsequent examples• branch (branch-name,branch-city,assets)• customer (customer-name,customer-street,customer-city)• account (branch-name,account-number,balance)• loan (branch-name,loan-number,amount)• depositor (customer-name,account-number)• borrower (customer-name,loan-number)

Page 9: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

9UU - DIS - UDBL

The select clause• The select clause corresponds to the projection operation of the

relational algebra. It is used to list the attributes desired in the result of a query.

• Find the names of all branches in the loan relation:select branch-namefrom loan

• In “pure” relational algebra syntax, this query would be:branch-name (loan)

• An asterisk (*) in the select clause denotes “all attributes”select *from loan

Page 10: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

10UU - DIS - UDBL

The select clause (cont.)• SQL allows duplicates in relations as well as in query results.

• To force the elimination of duplicates, insert the keyword distinct after select.

• Find the names of all branches in the loan relation, and remove duplicates:

select distinct branch-namefrom loan

• The keyword all specifies that duplicates not be removed.select all branch-namefrom loan

Page 11: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

11UU - DIS - UDBL

The select clause (cont.)

• The select clause can contain arithmetic expressions involving the operators, +, -, *, and /, and operating on constants or attributes of tuples.

• The following query would return a relation which is the same as the loan relation, except that the attribute amount is multiplied by 100:

select branch-name, loan-number, amount * 100

from loan

Page 12: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

12UU - DIS - UDBL

The where clause• The where clause corresponds to the selection predicate of the

relational algebra. It consists of a predicate involving attributes of the relations that appear in the from clause.

• Find all loan numbers for loans made at the Perryridge branch with loan amounts greater than $1200:

select loan-numberfrom loanwhere branch-name = “Perryridge” and amount > 1200

• SQL uses the logical connectives and, or, (and not). It allows the use of arithmetic expressions as operands to the comparison operators.

Page 13: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

13UU - DIS - UDBL

The where clause (cont.)

• SQL includes a between comparison operator in order to simplify where clauses that specify that a value be less than or equal to some value and greater than or equal to some other value.

• Find the loan number of those loans with loan amounts between $90,000 and $100,000 (that is, ≥ $90,000 and ≤$100,000)

select loan-number from loanwhere amount between 90000 and 100000

Page 14: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

14UU - DIS - UDBL

The from clause• The from clause corresponds to the Cartesian product operation

of the relational algebra. It lists the relations to be scanned when evaluating the whole select expression.

• Find the Cartesian product borrower loan:select * from borrower, loan

• Find the name and loan number of all customers having a loan at the Perryridge branch:

select distinct customer-name, borrower.loan-numberfrom borrower, loanwhere borrower.loan-number = loan.loan-number and

           branch-name = “Perryridge”

Page 15: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

15UU - DIS - UDBL

The rename operation• The SQL mechanism for renaming relations and attributes is

accomplished through the as clause:

old-name as new-name

• Find the name and loan number of all customers having a loan at the Perryridge branch; replace the column name loan-number with the name lid.select distinct customer-name, borrower.loan-number as lidfrom borrower, loanwhere borrower.loan-number = loan.loan-number and

   branch-name = “Perryridge”

Page 16: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

16UU - DIS - UDBL

Tuple Variables• Tuple variables are defined in the from clause via the use of the

as clause.

• Find the customer names and their loan numbers for all customers having a loan at some branch.

select distinct customer-name,T.loan-numberfrom borrower as T, loan as Swhere T.loan-number = S.loan-number

• Find the names of all branches that have greater assets than some branch located in Brooklyn.

select distinct T.branch-namefrom branch as T, branch as Swhere T.assets > S.assets and S.branch-city = “Brooklyn”

Page 17: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

17UU - DIS - UDBL

String operations• SQL includes a string-matching operator for comparisons on

character strings. Patterns are described using two special characters:– percent (%). The % character matches any substring.

– underscore (_). The _ character matches any character.

• Find the names of all customers whose street includes the substring “Main”:

select customer-namefrom customerwhere customer-street like “%Main%”

• Match the name “Main%”:like “Main\%” escape “\”

Page 18: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

18UU - DIS - UDBL

Ordering the display of tuples

• List in alphabetic order the names of all customers having a loan at Perryridge branch:

select distinct customer-namefrom borrower, loanwhere borrower.loan-number = loan.loan-number and

branch-name = “Perryridge”order by customer-name

• We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default.

• SQL must perform a sort to fulfill an order by request. Since sorting a large number of tuples may be costly, it is desirable to sort only when necessary.

Page 19: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

21UU - DIS - UDBL

Set operations• The set operations union, intersect, and except operate on

relations and correspond to the relational algebra operations and.

• Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multiset (sets with duplicates) versions union all, intersect all and except all.

• Suppose a tuple occurs m times in r and n times in s, then, it occurs:– m + n times in r union all s

– min(m, n) times in r intersect all s

– max(0, m r except all s

Page 20: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

22UU - DIS - UDBL

Set operations cont.

• Find all customers who have a loan, an account, or both:(select customer-name from depositor)union(select customer-name from borrower)

• Find all customers who have both a loan and an account:(select customer-name from depositor)intersect(select customer-name from borrower)

• Find all customers who have an account but no loan:(select customer-name from depositor)except(select customer-name from borrower)

Page 21: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

23UU - DIS - UDBL

SQL continued . . . (ch. 8)(Elmasri/Navathe ch. 8)

• SQL continued . . . – Aggregate Functions

– Null Values

– Nested Subqueries

– Derived Relations

– Views

– Modification of the Database

– Joined Relations

– Data Definition Language

– Embedded SQL

Page 22: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

24UU - DIS - UDBL

Aggregate functions

• These functions operate on the multiset of values of a column of a relation, and return a value

avg : average valuemin : minimum valuemax : maximum valuesum : sum of valuescount : number of values

Page 23: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

25UU - DIS - UDBL

Aggregate functions cont.

• Find the average account balance at the Perryridge branch.select avg (balance)from accountwhere branch-name = “Perryridge”

• Find the number of tuples in the customer relation.select count (*)from customer

• Find the number of depositors in the bankselect count (distinct customer-name)from depositor

Page 24: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

26UU - DIS - UDBL

Aggregate functions - group by

• Find the number of depositors for each branch:

select branch-name, count (distinct customer-name)

from depositor, account

where depositor.account-number = account.account-number

group by branch-name

• Note: Attributes in select clause outside of aggregate functions must appear in group by list.

Page 25: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

27UU - DIS - UDBL

Aggregate functions - having

• Find the names of all branches where the average account balance is more than $1,200

select branch-name , avg (balance)from accountgroup by branch-namehaving avg (balance) > 1200

• Note: predicates in the having clause are applied after the formation of groups

Page 26: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

28UU - DIS - UDBL

Null values– It is possible for tuples to have a null value, denoted by null, for some of

their attributes; null signifies an unknown value or that a value does not exist.

– The result of any arithmetic expression involving null is null.

– Comparisons involving null return unknown:

(true or unknown) = true, (false or unknown) = unknown,

(unknown or unknown) = unknown,

(true and unknown) = unknown, (false and unknown) = false,

(unknown and unknown) = unknown– Result of where clause predicate is treated as false if it evaluates to

unknown

– “P is unknown” evaluates to true if predicate P evaluates to unknown.

Page 27: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

29UU - DIS - UDBL

Null values cont.• Find all loan numbers which appear in the loan relation with

null values for amount:select loan-numberfrom loanwhere amount is null

• Total all loan amounts:select sum (amount)from loan

• Above statement ignores null amounts; result is null if there is no non-null amount.

• All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes.

Page 28: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

30UU - DIS - UDBL

Nested subqueries

• SQL provides a mechanism for the nesting of subqueries.

• A subquery is a select-from-where expression that is nested within another query.

• A common use of subqueries is to perform tests for set membership, set comparisons, and set cardinality.

Page 29: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

31UU - DIS - UDBL

Set membership• F in r t r(t = F)

(5 in ) = true

(5 in ) = false

(5 not in ) = true

o45

o46

o46

Page 30: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

32UU - DIS - UDBL

Example query• Find all customers who have both an account and a loan at bank.

select distinct customer-name

from borrower

where customer-name in (select customer-name

from depositor)

• Find all customers who have a loan at the bank but do not have an account at the bank.

select distinct customer-namefrom borrowerwhere customer-name not in (select customer-name

from depositor)

Page 31: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

33UU - DIS - UDBL

Example query

• Find all customers who have both an account and a loan at the Perryridge branch.

select distinct customer-namefrom borrower, loanwhere borrower.loan-number = loan.loan-number and

   branch-name = “Perryridge” and   (branch-name, customer-name) in

(select branch-name, customer-name from depositor, account where depositor.account-number =            account.account-number)

Page 32: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

34UU - DIS - UDBL

Set comparison

• Find all branches that have greater assets than some branch located in Brooklyn:

select distinct T. branch-namefrom branch as T, branch as Swhere T.assets > S.assets and S.branch-city =

“Brooklyn”

Page 33: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

35UU - DIS - UDBL

The some clause• F <comp> some r t (t r[F = <comp> t])

where <comp> can be: <, ≤, >, ≥, <>

(5 < some     ) = true (read: 5 < some tuple in the relation)

(5 < some ) = false

(5 = some ) = true

(5 <> some ) = true (since 0 ≠ 5)

• Also (= some) in, but (<> some) ≠ not in

056

05

05

05

Page 34: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

36UU - DIS - UDBL

Example query

• Find all branches that have greater assets than some branch located in Brooklyn.

select branch-namefrom branchwhere assets > some (select assets from branch

where branch-city = “Brooklyn”)

Page 35: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

37UU - DIS - UDBL

The all clause• F <comp> all r t (t r[F = <comp> t])

(5 < all ) = false

(5 < all ) = true

(5 = all ) = false

(5 <> all   ) = true (since 5 ≠ 4, 6)

• Note that (<> all) not in, but (= all) ≠ in

056

69

45

46

Page 36: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

38UU - DIS - UDBL

Example query

• Find the names of all branches that have greater assets than all branches located in Brooklyn.

select branch-namefrom branchwhere assets > all (select assets from branch

where branch-city = “Brooklyn”)

Page 37: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

39UU - DIS - UDBL

Test for empty relations

• The exists construct returns the value true if the argument subquery is nonempty.

• exists r r ≠ ø• not exists r r = ø

Page 38: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

40UU - DIS - UDBL

Example query• Find all customers who have an account at all branches located in

Brooklyn.

select distinct S.customer-namefrom depositor as Swhere not exists

((select branch-name from branchwhere branch-city = “Brooklyn”)except (select R.branch-name from depositor as T, account as Rwhere T.account-number = R.account-number and

S.customer-name = T.customer-name))

Page 39: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

41UU - DIS - UDBL

Test for absence of duplicate tuples

• The unique construct tests whether a subquery has any duplicate tuples in its result.

• Find all customers who have only one account at the Perryridge branch.select T.customer-namefrom depositor as Twhere unique (select R.customer-name

   from account,depositor as R   where T.customer-name = R.customer-name and     R.account-number = account.account-number and      account.branch-name = “Perryridge”)

Page 40: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

42UU - DIS - UDBL

Another example query

• Find all customers who have at least two accounts at the Perryridge branch.

select distinct T.customer-namefrom depositor Twhere not unique (

select R.customer-namefrom account,depositor as Rwhere T.customer-name = R.customer-name and

R.account-number = account.account-number andaccount.branch-name = “Perryridge”)

Page 41: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

43UU - DIS - UDBL

Derived relations• Find the average account balance of those branches where the

average account balance is greater than $1200.select branch-name, avg-balancefrom (select branch-name, avg (balance)

from account group by branch-name)

as result (branch-name,avg-balance)where avg-balance > 1200

• Note that we do not need to use the having clause, since we compute in the from clause the temporary relation result, and the attributes of result can be used directly in the where clause.

Page 42: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

44UU - DIS - UDBL

Views

• Provide a mechanism to hide certain data from the view of certain users. To create a view we use the command:

create view v as <query expression>

where:– <query expression> is any legal expression

– the view name is represented by v

Page 43: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

45UU - DIS - UDBL

Example queries• A view consisting of branches and their customers

create view all-customer as(select branch-name, customer-name

from depositor, accountwhere depositor.account-number =

account.account-number)union(select branch-name, customer-name

from borrower, loanwhere borrower.loan-number = loan.loan-number)

• Find all customers of the Perryridge branchselect customer-namefrom all-customerwhere branch-name = “Perryridge”

Page 44: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

46UU - DIS - UDBL

Modifying the database – deletion

• Delete all account records at the Perryridge branch.delete from account where branch-name = “Perryridge”

• Delete all accounts at every branch located in Needham.delete from accountwhere branch-name in (select branch-name

from branchwhere branch-city = “Needham”)

delete from depositorwhere account-number in

(select account-numberfrom branch, accountwhere branch-city = “Needham” and

branch.branch-name = account.branch-name)

Page 45: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

47UU - DIS - UDBL

Example query

• Delete the records of all accounts with balances below the average at the bank.delete from accountwhere balance < (select avg (balance) from account)– Problem: as we delete tuples from deposit, the average balance changes

– Solution used in SQL:

1. First, compute avg balance and find all tuples to delete

2. Next, delete all tuples found above (without recomputing avg or retesting the tuples)

Page 46: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

48UU - DIS - UDBL

Modifying the database – insertion

• Add a new tuple to accountinsert into accountvalues (“Perryridge”, A-9732, 1200)

• or equivalentlyinsert into account (branch-name, balance, account-number)values (“Perryridge”, 1200, A-9732)

• Add a new tuple to account with balance set to nullinsert into accountvalues (“Perryridge”, A-777,null)

Page 47: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

49UU - DIS - UDBL

Modifying the database – insertion

• Provide as a gift for all loan customers of the Perryridge branch, a $200 savings account. Let the loan number serve as the account number for the new savings account.insert into accountselect branch-name, loan-number, 200from loanwhere branch-name = “Perryridge”

insert into depositorselect customer-name,loan-numberfrom loan, borrowerwhere branch-name = “Perryridge”and loan.account-number = borrower.account-number

Page 48: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

50UU - DIS - UDBL

Modifying the database – updates

• Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%.

• Write two update statements:update accountset balance = balance * 1.06where balance > 10000

update accountset balance = balance * 1.05where balance ≤ 10000– The order is important.

– Can be done better using the case statement.

Page 49: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

51UU - DIS - UDBL

Update of a view• Create a view of all loan data in the loan relation, hiding the

amount attribute:create view branch-loan asselect branch-name, loan-numberfrom loan

• Add a new tuple to branch-loan:insert into branch-loanvalues (“Perryridge”, “L-307”)

• This insertion must be represented by inserting into the loan relation the tuple:(“Perryridge”, “L-307”, null)

• Updates on more complex views are difficult or impossible to translate, and hence are disallowed.

Page 50: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

52UU - DIS - UDBL

Joined relations• Join operations take two relations and return as a result another

relation.

• These additional operations are typically used as subquery expressions in the from clause.

• Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join.

• Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.

• Join types Join conditions– inner join natural

– left outer join on <predicate>

– right outer join using (A1, A2, ..., An)

– full outer join

Page 51: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

53UU - DIS - UDBL

Joined relations datasets for examples

• Relation loan

• Relation borrower

branch-name

DowntownRedwoodPerryridge

loan-number

L-170L-230L-260

amount

300040001700

customer-name

JonesSmithHayes

loan-number

1-170L-230L-155

Page 52: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

54UU - DIS - UDBL

Joined relations – examples

loan inner join borrower onloan.loan-number = borrower.loan-number

loan left outer join borrower onloan.loan-number = borrower.loan-number

customer-name

JonesSmith

loan-number

1-170L-230

branch-name

DowntownRedwood

loan-number

1-170L-230

amount

30004000

customer-name

JonesSmithnull

loan-number

1-170L-230null

branch-name

DowntownRedwoodPerryridge

loan-number

1-170L-230L-260

amount

300040001700

Page 53: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

55UU - DIS - UDBL

Joined relations – examplesloan natural inner join borrower

loan natural right outer join borrower

branch-name

DowntownRedwood

loan-number

1-170L-230

amount

30004000

customer-name

JonesSmith

customer-name

JonesSmithHayes

branch-name

DowntownRedwood

null

loan-number

L-170L-230L-155

amount

30004000null

Page 54: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

56UU - DIS - UDBL

Joined relations – examplesloan full outer join borrower using (loan-number)

• Find all customers who have either an account or a loan (but not both) at the bank.select customer-namefrom (depositor natural full outer join borrower)where account-number is null or loan-number is null

customer-name

JonesSmithnull

Hayes

branch-name

DowntownRedwoodPerryridge

null

loan-number

L-170L-230L-260L-155

amount

300040001700null

Page 55: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

57UU - DIS - UDBL

Data Definition Language (DDL)

• Allows the specification of not only a set of relations but also information about each relation, including:– The schema for each relation.

– The domain of values associated with each attribute.

– Integrity constraints.

– The set of indexes to be maintained for each relation.

– Security and authorization information for each relation.

– The physical storage structure of each relation on disk.

Page 56: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

58UU - DIS - UDBL

Domain types in SQL• char(n). Fixed length character string, with user-specified

length n.

• varchar(n). Variable length character strings, with user-specified maximum length n.

• int. Integer (a finite subset of the integers that is machine-dependent).

• smallint. Small integer (a machine-dependent subset of the integer domain type).

• numeric(p,d). Fixed point number, with user-specified precision of p digits, with n digits to the right of decimal point.

Page 57: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

59UU - DIS - UDBL

Domain types in SQL cont’d• real, double precision. Floating point and double-precision

floating point numbers, with machine-dependent precision.

• float(n). Floating point number, with user-specified precision of at least n digits.

• date. Dates, containing a (4 digit) year, month and date.

• time. Time of day, in hours, minutes and seconds.– Null values are allowed in all the domain types. Declaring an attribute to

be not null prohibits null values for that attribute.– create domain construct in SQL-92 creates user-defined domain types.

create domain person-name char(20) not null

Page 58: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

60UU - DIS - UDBL

Create table construct• An SQL relation is defined using the create table command:

create table r (A1 D1,A2 D2 ,...,An Dn,integrity-constraint1 i ,...,integrity-constraintk i )

– r is the name of the relation

– each Ai is an attribute name in the schema of relation r

– Di is the data type of values in the domain of attribute Ai

• Example: create table branch

(branch-name char(15) not null,branch-city char(30),assets integer)

Page 59: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

61UU - DIS - UDBL

Integrity constraints create table

• not null• primary key (A1,...,A n)

• check (P), where P is a predicate

• E.g. declare branch-name as the primary key for branch and ensure that the values of assets are non-negative.

create table branch(branch-name char(15) not null,branch-city char(30),assets integer,primary key (branch-name),check (assets >= 0))

• primary key declaration on an attribute automatically ensures not null in SQL-92

Page 60: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

62UU - DIS - UDBL

Drop and alter table constructs

• The drop table command deletes all information about the dropped relation from the database.

• The alter table command is used to add attributes to an existing relation. All tuples in the relation are assigned null as the value for the new attribute. The form of the alter table command is

alter table r add A D

where A is the name of the attribute be added to relation r and and D is the domain of A.

• The alter table command can also be used to drop attributes of a relation

alter table r drop A

where A is the name of an attribute of relation r.

Page 61: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

63UU - DIS - UDBL

Embedded SQL

• The SQL standard defines embeddings of SQL in a variety of programming languages such as such as Pascal, PL/I, Fortran, C, and Cobol.

• A language in which SQL queries are embedded is referred to as a host language, and the SQL structures permitted in the host language comprise embedded SQL.

• The basic form of these languages follows that of the System R embedding of SQL into PL/I.

• EXEC SQL statement is used to identify embedded SQL requests to the preprocessor:EXEC SQL <embedded SQL statement > END EXEC

Page 62: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

64UU - DIS - UDBL

Example query

• From within a host language, find the names and account numbers of customers with more than the variable amount dollars in some account.

• Specify the query in SQL and declare a cursor for it:

EXEC SQLdeclare c cursor forselect customer-name, account-numberfrom depositor, accountwhere depositor.account-number = account.account-numberand account.balance > :amountEND-EXEC

Page 63: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

65UU - DIS - UDBL

Embedded SQL cont’d

• The open statement causes the query to be evaluatedEXEC SQL open c END-EXEC

• The fetch statement causes the values of one tuple in the query result to be placed in host language variables.

EXEC SQL fetch c into :cn :an END-EXEC

• Repeated calls to fetch get successive tuples in the query result; a variable in the SQL communication area indicates when end-of-file is reached.

• The close statement causes the database system to delete the temporary relation that holds the result of the query.

EXEC SQL close c END-EXEC

Page 64: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

66UU - DIS - UDBL

Dynamic SQL

• Allows programs to construct and submit SQL queries at run time.

• Example of the use of dynamic SQL from within a C program.char * sqlprog = “update account set balance = balance * 1.05where account-number = ?”EXEC SQL prepare dynprog from :sqlprog;char account[10] = “A-101”;EXEC SQL execute dynprog using :account;

• The dynamic SQL program contains a ?, which is a place holder for a value that is provided when the SQL program is executed.

Page 65: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

67UU - DIS - UDBL

Other SQL features

– Fourth-generation languages – special language to assist application programmers in creating templates on the screen for a user interface, and in formatting data for report generation; available in most commercial database products

– SQL sessions – provide the abstraction of a client and a server (possibly remote)

• client connects to an SQL server, establishing a session

• executes a series of statements

• disconnects the session

• can commit or rollback the work carried out in the session

– An SQL environment contains several components, including a user identifier, and a schema, which identifies which of severalschemas a session is using.

Page 66: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

68UU - DIS - UDBL

Integrity Constraints(Elmasri/Navathe ch. ?? and ??)

• Integrity Constraints– Domain Constraints

– Referential Integrity Constraints

– Assertions

– Triggers

– Stored procedures

Page 67: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

69UU - DIS - UDBL

Domain constraints

• Integrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency.

• Domain constraints are the most elementary form of integrity constraint.

• They test values inserted in the database, and test queries to ensure that the comparisons make sense.

Page 68: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

70UU - DIS - UDBL

Domain constraints cont’d

• The check clause in SQL-92 permits domains to be restricted:– Use check clause to ensure that an hourly-wage domain allows only

values greater than a specified value. create domain hourly-wage numeric(5,2) constraint value-test check( value >= 4.00)

– The domain hourly-wage is declared to be a decimal number with 5 digits, 2 of which are after the decimal point

– The domain has a constraint that ensures that the hourly-wage is greater than 4.00.

– The clause constraint value-test is optional; useful to indicate which constraint an update violated.

Page 69: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

71UU - DIS - UDBL

Referential integrity• Ensures that a value that appears in one relation for a given set

of attributes also appears for a certain set of attributes in another relation.– Example: if “Perryridge” is a branch name appearing in one of the tuples

in the account relation, then there exists a tuple in the branch relation for branch “Perryridge”.

• Formal definition– Let r1(R1) and r2(R2) be relations with primary keys K1 and K2

respectively.

– The subset of R2 is a foreign key referencing K1 in relation r1 , if for every t2 in r2 there must be a tuple t1 in r1 such that t1[K1] = t2[].

– Referential integrity constraint: (r2) K (r1)

Page 70: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

72UU - DIS - UDBL

Referential integrity in the E-R model

• Consider relationship set R between entity sets E1 and E2.

• The relational schema for R includes the primary keys K1 of E1 and K2 of E2.

• Then K1 and K2 form foreign keys on the relational schemas for E1 and E2 respectively.

• Weak entity sets are also a source of referential integrity constraints. The relation schema for a weak entity set must include the primary key of the entity set on which it depends.

Page 71: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

73UU - DIS - UDBL

Database modification

• The following tests must be made in order to preserve the following referential integrity constraint: (r2) K1(r1)

• Insert. If a tuple t2 is inserted into r2, the system must ensure that there is a tuple t1 in r1 such that t1[K1] = t2[]. That is t2[] K1(r1)

• Delete. If a tuple t1 is deleted from r1, the system must compute the set of tuples in r2 that reference t1:

= t1[K1](r2)If this set is not empty, either the delete command is rejected as an error, or the tuples that reference t1 must themselves be deleted (cascading deletions are possible).

Page 72: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

74UU - DIS - UDBL

Database modification cont’d

• Update. There are two cases:– Case 1: If a tuple t2 is updated in relation r2 and the update modifies

values for the foreign key , then a test similar to the insert case is made. Let t2’ denote the new value of tuple t2. The system must ensure that: t2’[] K1(r1)

– Case 2: If a tuple t1 is updated in r1, and the update modifies values for the primary key (K1), then a test similar to the delete case is made. The system must compute = t1[K1](r2) using the old value of t1 (the value before the update is applied). If this set is not empty, the update may be rejected as an error, or the update may be cascaded to the tuples in the set (cascading update), or the tuples in the set may be deleted (cascading delete).

Page 73: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

75UU - DIS - UDBL

Referential integrity in SQL

• Primary and candidate keys and foreign keys can be specified as part of the SQL create table statement:– The primary key clause of the create table statement includes a

list of the attributes that comprise the primary key.

– The unique key clause of the create table statement includes a list of the attributes that comprise a candidate key.

– The foreign key clause of the create table statement includes both a list of the attributes that comprise the foreign key and the name of the relation referenced by the foreign key.

Page 74: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

76UU - DIS - UDBL

Referential integrity in SQL - example

create table customer(customer-name char(20) not null,customer-street char(30),customer-city char(30),primary key (customer-name))

create table branch(branch-name char(15) not null,branch-city char(30),assets integer,primary key (branch-name))

Page 75: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

77UU - DIS - UDBL

Referential integrity in SQL - example cont’d

create table account(account-number char(10) not null, branch-name char(15),balance integer,primary key (account-number),foreign key (branch-name) references branch)

create table depositor(customer-name char(20) not null,account-number char(10) not null,primary key (customer-name,account-number),foreign key (account-number) references account,foreign key (customer-name) references customer)

Page 76: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

78UU - DIS - UDBL

Cascading actions in SQL

create table account...foreign key (branch-name) references branch

on delete cascadeon update cascade,

...)

• If a tuple in branch is deleted (updated), there is a tuple in account that will also be deleted (updated), i.e. the delete (update) cascades.

Page 77: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

79UU - DIS - UDBL

Cascading actions in SQL cont’d

• If there is a chain of foreign-key dependencies across multiple relations, with on delete cascade specified for each dependency, a deletion or update at one end of the chain can propagate across the entire chain.

• If a cascading update or delete causes a constraint violation that cannot be handled by a further cascading operation, the system aborts the transaction. As a result, all the changes caused by the transaction and its cascading actions are undone.

Page 78: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

80UU - DIS - UDBL

Assertions

• An assertion is a predicate expressing a condition that we wish the database always to satisfy.

• An assertion in SQL-92 (do not exist in InterBase) takes the form: create assertion <assertion-name> check <predicate>

• When an modification (insert/delete/update)of the db is made, the system tests it for validity. This testing may introduce a significant amount of overhead; hence assertions should be used with great care.

Page 79: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

81UU - DIS - UDBL

Assertion example• The sum of all loan amounts for each branch must be less than

the sum of all account balances at the branch.create assertion sum-constraint check

(not exists (select * from branchwhere (select sum( amount)

from loanwhere loan.branch-name =

branch.branch-name) >= (select sum( amount) from accountwhere loan.branch-name =

branch.branch-name)))

Page 80: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

82UU - DIS - UDBL

Another assertion example

• Every loan has at least one borrower who maintains an account with a minimum balance of $1000.00.

create assertion balance-constraint check(not exists (select * from loanwhere not exists

(select *from borrower, depositor, accountwhere loan.loan-number = borrower.loan-number and borrower.customer-name = depositor.customer-name and  depositor.account-number = account.account-number and  account.balance >= 1000)))

Page 81: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

83UU - DIS - UDBL

Triggers

• A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database.

• To design a trigger mechanism, we must:– Specify the conditions under which the trigger is to be executed.

– Specify the actions to be taken when the trigger executes.

• The SQL-92 standard does not include triggers, but many implementations support triggers. SQL-3 has specified triggers. Here, triggers are presented as defined by InterBase.

Page 82: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

84UU - DIS - UDBL

Trigger example• Suppose that instead of allowing negative account balances, the

bank deals with overdrafts by– setting the account balance to zero

– creating a loan in the amount of the overdraft

– giving this loan a loan number identical to the account number of the overdrawn account

• New values after an update are represented by the keyword new and old values by the keyword old.

• The condition for executing the trigger is a check to see if the balance after an update to the account relation (represented by new.balance) results in a negative balance.

Page 83: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

85UU - DIS - UDBL

Trigger example cont’dcreate trigger overdraft for account before update as

begin   if (new.balance < 0) then

      begin         insert into loan values

   (branch-name, old.account-number, new.balance);         insert into borrower

   (select customer-name, account-number   from depositor   where old.account-number = depositor.account-number);update account S set S.balance = 0   where S.account-number = old.account-number;

      end

end

Page 84: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

86UU - DIS - UDBL

Stored procedures

• A stored procedure makes it possible to store procedural code for applications in the database (here s.p. according to InterBase is presented).

• A stored procedure can perfor complex operations and act as an interface to an application.

• Procedures are executed in the database and can more easily and efficiently retrieve data since they can include SQL queries directly.

• Stored procedures can perform certain error handling using exceptions (comp. exeptions i programming languages)

Page 85: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

87UU - DIS - UDBL

Stored procedure example• The following procedure, SUB_TOT_BUDGET, takes a department number as its

input parameter, and returns the total, average, minimum, and maximum budgets of departments with the specified HEAD_DEPT. It computes total, average, smallest, and largest department budget.

CREATE PROCEDURE SUB_TOT_BUDGET (head_dept CHAR(25))   RETURNS (tot_budget DECIMAL(12, 2), avg_budget DECIMAL(12, 2),

           min_budget DECIMAL(12, 2), max_budget DECIMAL(12, 2)) AS BEGIN

SELECT SUM(BUDGET), AVG(BUDGET), MIN(BUDGET), MAX(BUDGET)FROM DEPARTMENT WHERE HEAD_DEPT = :head_deptINTO :tot_budget, :avg_budget, :min_budget, :max_budget;

   END;END

• The procedure is executed by:EXECUTE PROCEDURE SUB_TOT_BUDGET(“Sales and Marketing”);

Page 86: Kjell Orsborn 2015-06-20 1 UU - DIS - UDBL DATABASE SYSTEMS - 10p Course No.? A second course on development of database systems Kjell Orsborn Uppsala.

Kjell Orsborn 23-04-18

88UU - DIS - UDBL

Stored proc. vs. triggers

• Triggers are used when one should monitor updates of tables where one do not who, or how, the table will be updated. Should be used with carefulness!!!

• Stored procedures are used to update tables where one knows that the table update will allways be done through the procedure instead of through a direct update.

• Stored procedures are precompiled and can be used as efficient views (views are normally not optimized before they are refererenced), but are usually used for updates.