数据库CH
数据库CH
数据库CH
5
Advanced SQL
In this chapter we address the issue of how to access SQL from a general-purpose
programming language, which is very important for building applications that
use a database to store and retrieve data. We describe how procedural code can
be executed within the database, either by extending the SQL language to support
procedural actions, or by allowing functions defined in procedural languages
to be executed within the database. We describe triggers, which can be used to
specify actions that are to be carried out automatically on certain events such as
insertion, deletion, or update of tuples in a specified relation. We discuss recursive
queries and advanced aggregation features supported by SQL. Finally, we describe
online analytic processing (OLAP) systems, which support interactive analysis of
very large datasets.
Given the fact that the JDBC and ODBC protocols (and variants such as
ADO.NET) are have become the primary means of accessing databases, we have
significantly extended our coverage of these two protocols, including some ex-
amples. However, our coverage is only introductory, and omits many details
that are useful in practise. Online tutorials/manuals or textbooks covering these
protocols should be used as supplements, to help students make full use of the
protocols.
Exercises
5.12 Consider the following relations for a company database:
import java.sql.*;
public class Mystery {
public static void main(String[] args) {
try {
Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:star/X@//edgar.cse.lehigh.edu:1521/XE");
Statement s=con.createStatement();
String q;
String empName = "dog";
boolean more;
ResultSet result;
do {
q = "select mname from mgr where ename = ’" + empName + "’";
result = s.executeQuery(q);
more = result.next();
if (more) {
empName = result.getString("mname");
System.out.println (empName);
}
} while (more);
s.close();
con.close();
} catch(Exception e){e.printStackTrace();} }}
Answer: It prints out the manager of “dog.” that manager’s manager, etc.
until we reach a manager who has no manager (presumably, the CEO, who
most certainly is a cat.) NOTE: if you try to run this, use your OWN Oracle
ID and password, since Star, crafty cat that she is, changes her password.
5.13 Suppose you were asked to define a class MetaDisplay in Java, containing
a method static void printTable(String r); the method takes a relation name
r as input, executes the query “select * from r”, and prints the result out
in nice tabular format, with the attribute names displayed in the header of
the table.
a. What do you need to know about relation r to be able to print the
result in the specified tabular format.
b. What JDBC methods(s) can get you the required information?
c. Write the method printTable(String r) using the JDBC API.
Answer:
Exercises 33
5.14 Repeat Exercise 5.13 using ODBC, defining void printTable(char *r) as a
function instead of a method.
Answer:
a. Same as for JDBC.
34 Chapter 5 Advanced SQL
where the primary keys are underlined. Write a query to find companies
whose employees earn a higher salary, on average, than the average salary
at “First Bank Corporation”.
a. Using SQL functions as appropriate.
b. Without using SQL functions.
Answer:
a.
create function avg salary(cname varchar(15))
returns integer
declare result integer;
select avg(salary) into result
from works
where works.company name = cname
return result;
end
select company name
from works
where avg salary(company name) > avg salary("First Bank Corporation")
b.
select company name
from works
group by company name
having avg(salary) > (select avg(salary)
from works
where company name="First Bank Corporation")
5.16 Rewrite the query in Section 5.2.1 that returns the name and budget of all
departments with more than 12 instructors, using the with clause instead
of using a function call.
Answer:
Exercises 35
5.17 Compare the use of embedded SQL with the use in SQL of functions defined
in a general-purpose programming language. Under what circumstances
would you use each of these features?
Answer: SQL functions are primarily a mechanism for extending the
power of SQL to handle attributes of complex data types (like images), or
to perform complex and non-standard operations. Embedded SQL is use-
ful when imperative actions like displaying results and interacting with
the user are needed. These cannot be done conveniently in an SQL only
environment. Embedded SQL can be used instead of SQL functions by re-
trieving data and then performing the function’s operations on the SQL
result. However a drawback is that a lot of query-evaluation functionality
may end up getting repeated in the host language code.
5.18 Modify the recursive query in Figure 5.15 to define a relation
where the attribute depth indicates how many levels of intermediate pre-
requisites are there between the course and the prerequisite. Direct prereq-
uisites have a depth of 0.
Answer:
select *
from prereq depth
A tuple ( p1 , p2 , 3) in the subpart relation denotes that the part with part-id
p2 is a direct subpart of the part with part-id p1 , and p1 has 3 copies of p2 .
Note that p2 may itself have further subparts. Write a recursive SQL query
that outputs the names of all subparts of the part with part-id “P-100”.
Answer:
select *
from total part
5.20 Consider again the relational schema from Exercise 5.19. Write a JDBC
function using non-recursive SQL to find the total cost of part “P-100”,
including the costs of all its subparts. Be sure to take into account the
fact that a part may have multiple occurrences of a subpart. You may use
recursion in Java if you wish.
Answer: The SQL function ’total cost’ is called from within the JDBC
code.
SQL function:
begin
create temporary table result (name char(10), number integer);
create temporary table newpart (name char(10), number integer);
create temporary table temp (name char(10), number integer);
create temporary table final cost(number integer);
from subpart
where part id = id
repeat
insert into result
select name, number
from newpart;
JDBC function:
System.out.println(rset.getFloat(2));
38 Chapter 5 Advanced SQL
5.21 Suppose there are two relations r and s, such that the foreign key B of r
references the primary key A of s. Describe how the trigger mechanism can
be used to implement the on delete cascade option, when a tuple is deleted
from s.
Answer: We define triggers for each relation whose primary-key is re-
ferred to by the foreign-key of some other relation. The trigger would be
activated whenever a tuple is deleted from the referred-to relation. The
action performed by the trigger would be to visit all the referring rela-
tions, and delete all the tuples in them whose foreign-key attribute value
is the same as the primary-key attribute value of the deleted tuple in the
referred-to relation. These set of triggers will take care of the on delete
cascade operation.
5.22 The execution of a trigger can cause another action to be triggered. Most
database systems place a limit on how deep the nesting can be. Explain
why they might place such a limit.
Answer: It is possible that a trigger body is written in such a way that
a non-terminating recursion may result. An example of such a trigger is a
before insert trigged on a relation that tries to insert another record into the
same relation.
In general, it is extremely difficult to statically identify and prohibit
such triggers from being created. Hence database systems, at runtime, put
a limit on the depth of nested trigger calls.
5.23 Consider the relation, r , shown in Figure 5.27. Give the result of the follow-
ing query:
Answer:
Garfield 359 P 1
Garfield 359 null 1
Garfield null null 1
Painter 705 N 1
Painter 705 null 1
Painter null null 1
Saucon 550 D 1
Saucon 550 null 1
Saucon 651 N 1
Saucon 651 null 1
Saucon null null 2
5.24 For each of the SQL aggregate functions sum, count, min, and max, show
how to compute the aggregate value on a multiset S1 ∪ S2 , given the aggre-
gate values on multisets S1 and S2 .
Exercises 39
select A, B,
(sum(count t ∗ (stddev t*stddev t+ avg t* avg t))/sum(count t)) -
(sum(sum t)/sum(count t))
from aggregation on t
groupby A, B
5.25 In Section 5.5.1, we used the student grades view of Exercise 4.5 to write
a query to find the rank of each student based on grade-point average.
Modify that query to show only the top 10 students (that is, those students
whose rank is 1 through 10).
Answer:
with s grades as
select ID,rank() over (order by (GPA)desc) as s rank
from student grades
select ID,s rank
from s grades
where s rank <= 10
5.28 Consider the bank database of Figure 5.25 and the balance attribute of the
account relation. Write an SQL query to compute a histogram of balance
values, dividing the range 0 to the maximum account balance present, into
three equal ranges.
Answer:
(select 1, count(∗)
from account
where 3∗ balance <= (select max(balance)
from account)
)
union
(select 2, count(∗)
from account
where 3∗ balance > (select max(balance)
from account)
and 1.5∗ balance <= (select max(balance)
from account)
)
union
(select 3, count(∗)
from account
where 1.5∗ balance > (select max(balance)
from account)
)