Ch.5

QUIZ: Authorization on Views
create view geo_instructor as
(select *
from instructor
where dept_name = ’Geology’);
grant select on geo_instructor to geo_staff
 What if the creator of this view does not have
SELECT permission on instructor?
Database System Concepts - 6th Edition
5.1
©Silberschatz, Korth and Sudarshan
QUIZ: Authorization on Views
create view geo_instructor as
(select *
from instructor
where dept_name = ’Geology’);
grant select on geo_instructor to geo_staff
 What if the creator of this view does not have
SELECT permission on instructor?
A: If a user creates a view on which no authorization can be
granted, the DBMS will deny the view creation request (p.147)
Database System Concepts - 6th Edition
5.2
©Silberschatz, Korth and Sudarshan
QUIZ: Authorization on Views
create view geo_instructor as
(select *
from instructor
where dept_name = ’Geology’);
grant select on geo_instructor to geo_staff
 Suppose that a geo_staff member issues
select * from geo_instructor;
 What if geo_staff does not have permissions on
instructor?
Database System Concepts - 6th Edition
5.3
©Silberschatz, Korth and Sudarshan
QUIZ: Authorization on Views
create view geo_instructor as
(select *
from instructor
where dept_name = ’Geology’);
grant select on geo_instructor to geo_staff
 Suppose that a geo_staff member issues
select * from geo_instructor;
 What if geo_staff does not have permissions on
instructor?
A: The user receives only those privileges that provide no additional
authorization beyond those she already has. (p.147)
Database System Concepts - 6th Edition
5.4
©Silberschatz, Korth and Sudarshan
Chapter 5: Advanced SQL
Database System Concepts, 6th Ed.
©Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on re-use
5.1 Accessing SQL from a Programming
Language
 SKIP for now
 We’ll cover this in the lab, using Python
Database System Concepts - 6th Edition
5.6
©Silberschatz, Korth and Sudarshan
5.2 Modules in SQL:
Functions, Procedures, Methods
 Why needed?
To handle specialized data types such as images and
geometric objects.
Example:
functions to check if polygons overlap, or
to compare images for similarity.
 Some DBMSs (PostgreSQL included) support table-
valued functions, which can return a relation as a result.
Database System Concepts - 6th Edition
5.7
©Silberschatz, Korth and Sudarshan
5.2 Functions in SQL
 Since 1999 (SQL:1999), standard SQL allows
procedural elements: function/procedures, if-then-else
statements, for and while loops, local variables, etc.
 One option: “external” procedures, defined in a
(procedural) language, e.g. C, Java, Python, PL; they
interact with SQL through API calls.
Database System Concepts - 6th Edition
5.8
©Silberschatz, Korth and Sudarshan
5.2 Functions in SQL
 Another option: “native”, a.k.a. “internal”, a.k.a. “stored”
procedures → stored inside the DB; execute them using
the CALL statement
Pros for stored:

External apps. can operate on the DB w/o knowing
about internal details

Unique “point of access” makes code development
and maintenance easier
Cons:

?

?
Database System Concepts - 6th Edition
5.9
©Silberschatz, Korth and Sudarshan
5.2 Functions in SQL
 Object-oriented aspects are covered in Chapter 22
(Object-Based Databases)
 Many DBMSs have proprietary procedural extensions to
SQL that differ from SQL:1999.
Database System Concepts - 6th Edition
5.10
©Silberschatz, Korth and Sudarshan
Example Function
Define a function that, given the name of a department, returns the
number of instructors in that department:
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
SELECT … INTO creates a new table,
unlike SELECT … AS, which only
returns a temporary table (to be used
in the current query).
Database System Concepts - 6th Edition
5.11
©Silberschatz, Korth and Sudarshan
How is the function used?
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
Find the department name and budget of all departments with
more than 5 instructors:
select dept_name, budget
from department
where dept_count (dept_name ) > 5
Database System Concepts - 6th Edition
5.12
©Silberschatz, Korth and Sudarshan
QUIZ Function
Based on the example, define a function that, given the ID of a
student, returns the total nr. of credit hours that student had in
2014.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
Database System Concepts - 6th Edition
5.13
©Silberschatz, Korth and Sudarshan
QUIZ Function
Use the function to find the names of all students who had less
than 4 credit hours in 2014.
select dept_name, budget
from department
where dept_count (dept_name ) > 5
Database System Concepts - 6th Edition
5.14
©Silberschatz, Korth and Sudarshan
Table Functions
 SQL:2003 added functions that return a relation/table.
 Example: Return all info about all instructors in a department
create function instructors_of (dept_name char(20)
returns table ( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructors_of.dept_name)
 Usage
select *
from table (instructors_of (‘Music’))
Can be thought of as
parametrized views!
Database System Concepts - 6th Edition
5.15
©Silberschatz, Korth and Sudarshan
QUIZ: Table Functions
Based on the example, write a function that returns all info about all
instructors in a department, whose salary is over $70,000
create function instructors_of (dept_name char(20)
returns table ( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructors_of.dept_name)
Database System Concepts - 6th Edition
5.16
©Silberschatz, Korth and Sudarshan
SQL Procedures
What is the difference between functions and procedures?
Database System Concepts - 6th Edition
5.17
©Silberschatz, Korth and Sudarshan
SQL Procedures
 The dept_count function could instead be written as procedure:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
 Procedures can be invoked either from another SQL procedure or
from embedded SQL, using the call statement:
declare d_count integer;
call dept_count_proc( ‘Physics’, d_count);
Database System Concepts - 6th Edition
5.18
©Silberschatz, Korth and Sudarshan
QUIZ: Procedures
 Based on the exmaple, write a procedure to find the average
salary and maximum salary of a department:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
 Based on the example, show how to use the procedure:
declare d_count integer;
call dept_count_proc( ‘Physics’, d_count);
Database System Concepts - 6th Edition
5.19
©Silberschatz, Korth and Sudarshan
OVERLOADING
Since SQL:1999, it is allowed to have more than one
function/procedure of the same name, as long as:
 the number of arguments differ, OR
 they have the same nr. of arguments, but the type of at
least one argument is different.
Database System Concepts - 6th Edition
5.20
©Silberschatz, Korth and Sudarshan
Example Function in PostgreSQL
Database System Concepts - 6th Edition
5.21
©Silberschatz, Korth and Sudarshan
Individual work:
Read Sections 5.2.2 and 5.2.3 (pp.176-180) in
our text.
Database System Concepts - 6th Edition
5.22
©Silberschatz, Korth and Sudarshan
5.3 Triggers
 A trigger is a statement that is executed automatically by the
system as a side effect of a modification to the DB.
 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.
 Triggers were introduced into ANSI SQL standard in SQL:1999,
but were supported even earlier using non-standard syntax by
most DBMSs.

Syntax illustrated here may not work exactly on your
database system; check the system manuals
Database System Concepts - 6th Edition
5.23
©Silberschatz, Korth and Sudarshan
Trigger Example
 time_slot_id is not a primary key of timeslot, so we cannot create
FK constraint from section to timeslot.
 Alternative: use triggers on section and timeslot to enforce integrity
constraints
create trigger timeslot_check1 after insert on section
referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot)) /* time_slot_id not present in time_slot */
begin
rollback
end;
Database System Concepts - 6th Edition
5.24
©Silberschatz, Korth and Sudarshan
Trigger Example
(Cont.)
create trigger timeslot_check2 after delete on timeslot
referencing old row as orow
for each row
when (orow.time_slot_id not in (
select time_slot_id
from time_slot)
/* last tuple for time slot id deleted from time slot */
and orow.time_slot_id in (
select time_slot_id
from section)) /* and time_slot_id still referenced from section*/
begin
rollback
end;
Database System Concepts - 6th Edition
5.25
©Silberschatz, Korth and Sudarshan
create trigger timeslot_check1 after
insert on section
referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot))
begin
rollback
end;
Database System Concepts - 6th Edition
5.26
©Silberschatz, Korth and Sudarshan
Triggering Events and Actions in SQL
 Triggering event can be insert, delete or update
 Triggers on update can be restricted to specific attributes
E.g., after update of takes on grade
 Values of attributes before and after an update can be
referenced
 referencing old row as : for deletes and updates
 referencing new row as : for inserts and updates
 Triggers can be activated before an event, which can serve as
extra constraints. E.g. convert blank grades to null.
create trigger setnull_trigger before update of takes
referencing new row as nrow
for each row
when (nrow.grade = ‘ ‘)
begin atomic
set nrow.grade = null;
end;

Database System Concepts - 6th Edition
5.27
©Silberschatz, Korth and Sudarshan
Example: trigger to maintain tot_cred
create trigger credits_earned after update of takes on (grade)
referencing new row as nrow
referencing old row as orow
for each row
when nrow.grade <> ’F’ and nrow.grade is not null
and (orow.grade = ’F’ or orow.grade is null)
begin atomic
update student
set tot_cred= tot_cred +
(select credits
Scalar subquery!
from course
where course.course_id = nrow.course_id)
where student.id = nrow.id;
end;
Database System Concepts - 6th Edition
5.28
©Silberschatz, Korth and Sudarshan
Statement-Level Triggers
Instead of executing a separate action for each affected row, a
single action can be executed for all rows affected by a
transaction
 Use
for each statement
instead of
for each row
 Use
referencing old table or referencing new table
to refer to temporary tables (called transition tables)
containing the affected rows
 Can be more efficient when dealing with SQL statements
that updating a large number of rows
Database System Concepts - 6th Edition
5.29
©Silberschatz, Korth and Sudarshan
When not to use triggers
 Triggers were used earlier for tasks such as:

Maintaining summary data (e.g., total salary of each department)

Replicating databases by recording changes to special relations
(called change or delta relations) and having a separate process
that applies the changes over to a replica
There are better ways of doing these now, b/c today’s DBMSs have:

built-in materialized view facilities to maintain summary data

built-in support for replication
 Encapsulation facilities can be used instead of triggers in many cases

Define methods to update fields

Carry out actions as part of the update methods instead of
through a trigger
Database System Concepts - 6th Edition
5.30
©Silberschatz, Korth and Sudarshan
When not to use triggers
 Risk of unintended execution of triggers, for example, when

loading data from a backup copy

replicating updates at a remote site

Trigger execution can be disabled before such actions.
 Other risks with triggers:

Error leading to failure of critical transactions that set off the
trigger

Cascading execution
Database System Concepts - 6th Edition
5.31
©Silberschatz, Korth and Sudarshan
Triggers vs. stored procedures
 Triggers are executed only as side effects of some
event. If we want to run the trigger actions again (e.g.
in order to re-build a backup history table in a data
warehouse), the only way to do it is by re-creating the
triggering events … which could have unwanted
efects on the original tables! In this case, stored
procedures are better.
 On the other hand, triggers are executed
automatically, w/o the need to CALL a procedure; if
there are many paths through which the table can
change (“update paths”), writing a procedure for each
path would lead to much code duplication. In this
case, triggers are better.
Database System Concepts - 6th Edition
5.32
©Silberschatz, Korth and Sudarshan
5.4 Iteration and Recursion in SQL
Database System Concepts - 6th Edition
5.33
©Silberschatz, Korth and Sudarshan
One problem and two solutions
Problem: Calculate the sum of the integers from 1 to N
Database System Concepts - 6th Edition
5.34
©Silberschatz, Korth and Sudarshan
Transitive closure (TC)
Transitivity means: If a R b and b R c, then a R c.
Example:
The “less-than” relation on the set of real numbers is
transitive: If a < b and b < c, then a < c.
Database System Concepts - 6th Edition
5.35
©Silberschatz, Korth and Sudarshan
Example:
The “is prerequisite for” relation on the set of all classes;
Is this relation transitive?
Database System Concepts - 6th Edition
5.36
©Silberschatz, Korth and Sudarshan
In a relational DB, a binary relation is a table with two
columns:
Draw the graph representation of this relation!
Note:
Use this
table
instead of the one given 5.37
in Fig.5.12 of our text! ©Silberschatz, Korth and Sudarshan
Database System
Concepts
- 6 Edition
th
Transitive closure (TC) of a set with
respect to a (transitive) binary relation
Example:
The TC of the set { ITEC450 } is …
Database System Concepts - 6th Edition
5.38
©Silberschatz, Korth and Sudarshan
Transitive closure (TC) of a set with
respect to a (transitive) binary relation
Example:
The TC of the set { ITEC450, ITEC400 } is …
Database System Concepts - 6th Edition
5.39
©Silberschatz, Korth and Sudarshan
Transitive closure (TC) of a set with
respect to a (transitive) binary relation
Database System Concepts - 6th Edition
5.40
©Silberschatz, Korth and Sudarshan
Finding the transitive closure iteratively
Intuition: With the tools we have so far, we can perform only a
fixed number of joins of the table prereq with itself
 This can give only a fixed number of levels of prerequisites
 We can always construct a table with a greater number of
levels of prerequisites on which the query will not work!
Solution: write a procedure to iterate as many times as required

See procedure findAllPrereqs in text
Database System Concepts - 6th Edition
5.41
©Silberschatz, Korth and Sudarshan
Sorry, some
underscores are
missing in this
code!
Procedural element:
loop with condition
at the end
Database System Concepts - 6th Edition
5.42
©Silberschatz, Korth and Sudarshan
This is only necessary if
the relation contains cycles!
Give a real-life example of
application with cycles!
Database System Concepts - 6th Edition
5.43
©Silberschatz, Korth and Sudarshan
Finding the transitive closure recursively
Since SQL:1999, standard SQL allows recursive queries:
with recursive c_prereq(course_id, prereq_id) as (
select course_id, prereq_id
from prereq
union
select c_prereq.course_id, prereq.prereq_id,
from c_prereq, prereq
where c_prereq.prereq_id = prereq.course_id
)
select ∗
from c_prereq;
Base query
Recursive
query
c_prereq, is the transitive closure of prereq.
Note:
The explanations
refer to c_prereq
as rec_prereq.
Database System
Concepts - 6 Edition on p.191 of text incorrectly
5.44
©Silberschatz,
Korth and Sudarshan
th
Recursive queries
 Computing transitive closure using iteration, adding successive
tuples to rec_prereq

The next slide shows a prereq relation

Each step of the iterative process constructs an extended
version of rec_prereq from its recursive definition.

The final result is called the fixed point of the recursive view
definition.
 Recursive views are required to be monotonic. That is, if we add
tuples to prereq the view rec_prereq contains all of the tuples it
contained before, plus possibly more.
Database System Concepts - 6th Edition
5.45
©Silberschatz, Korth and Sudarshan
Example of Fixed-Point Computation
with recursive c_prereq(course_id, prereq_id) as (
select course_id, prereq_id
from prereq
where prereq_id = 'CS-347'
union
select c_prereq.course_id, prereq.prereq_id,
from c_prereq, prereq
where c_prereq.prereq_id = prereq.course_id
)
select ∗
from c_prereq;
When c_prereq stagnates
(becomes non-monotonic)
exaluation stops automatically!
Note:
Use this
table
instead of the one given 5.46
in Fig.5.12 of our text! ©Silberschatz, Korth and Sudarshan
Database System
Concepts
- 6 Edition
th
Another Recursion Example
 Given the relation
manager(employee_name, manager_name)
 Find all employee-manager pairs, where the employee reports to the
manager directly or indirectly (that is manager’s manager, manager’s
manager’s manager, etc.)
with recursive empl (employee_name, manager_name ) as (
select employee_name, manager_name
from manager
union
select manager.employee_name, empl.manager_name
from manager, empl
where manager.manager_name = empl.employe_name)
select *
from empl
empl is the transitive closure of the manager relation
Database System Concepts - 6th Edition
5.47
©Silberschatz, Korth and Sudarshan
SKIP
5.6 Advanced aggregation
Homework for Ch.5: 5.5, 5.6, 5.18
Due Thursday, March 26
Database System Concepts - 6th Edition
5.48
©Silberschatz, Korth and Sudarshan