DP Unit02 ActiveDatabase
DP Unit02 ActiveDatabase
rating INTEGER,
age REAL,
PRIMARY KEY (sid),
CHECK ( rating >= 1 AND rating <= 10)
CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S )
+ ( SELECT COUNT (B. bid) FROM Boats B )
< 100 ))
This solution suffers from two drawbacks. It is associated with Sailors, al-
though it involves Boats in a completely symmetric way. More important,
if the Sailors table is empty, this constraint is defined (as per the semantics
of table constraints) to always hold, even if we have more than 100 rows in
Boats! vVe could extend this constraint specification to check that Sailors is
nonempty, but this approach becomes cumbersome. The best solution is to
create an assertion, as follows:
set is nonempty and false if the query ha.') no answers. If the condition part
evaluates to true, the action a.,sociated with the trigger is executed.
A trigger action can examine the answers to th(~ query in the condition part
of the trigger, refer to old and new values of tuples modified by the statement
activating the trigger, execute Hew queries, and make changes to the database.
In fact, an action can even execute a series of data-definition commands (e.g.,
create new tables, change authorizations) and transaction-oriented commands
(e.g., commit) or call host-language procedures.
One of the example triggers in Figure 5.20 executes before the aetivating state-
ment, and the other example executes after it. A trigger can also be scheduled
to execute instead of the activating statement; or in deferred fashion, at the
end of the transaction containing the activating statement; or in asynchronous
fashion, as part of a separate transaction.
The example in Figure 5.20 illustrates another point about trigger execution:
A user must be able to specify whether a trigger is to be executed once per
modified record or once per activating statement. If the action depends on in-
dividual changed records, for example, we have to examine the age field of the
inserted Students record to decide whether to increment the count, the trigger-
170 CHAPTER 5
ing event should be defined to occur for each modified record; the FOR EACH
ROW clause is used to do this. Such a trigger is called a row-level trigger. On
the other hand, the iniLcount trigger is executed just once per INSERT state-
ment, regardless of the number of records inserted, because we have omitted
the FOR EACH ROW phrase. Such a trigger is called a statement-level trigger.
In Figure 5.20, the keyword new refers to the newly inserted tuple. If an existing
tuple were modified, the keywords old and new could be used to refer to the
values before and after the modification. SQL:1999 also allows the action part
of a trigger to refer to the set of changed records, rather than just one changed
record at a time. For example, it would be useful to be able to refer to the set
of inserted Students records in a trigger that executes once after the INSERT
statement; we could count the number of inserted records with age < 18 through
an SQL query over this set. Such a trigger is shown in Figure 5.21 and is an
aJternative to the triggers shown in Figure 5.20.
The definition in Figure 5.21 uses the syntax of SQL: 1999, in order to illustrate
the similarities and differences with respect to the syntax used in a typical
current DBMS. The keyword clause NEW TABLE enables us to give a table name
(InsertedTuples) to the set of newly inserted tuples. The FOR EACH STATEMENT
clause specifies a statement-level trigger and can be omitted because it is the
default. This definition does not have a WHEN clause; if such a clause is included,
it follows the FOR EACH STATEMENT clause, just before the action specification.
The trigger is evaluated once for each SQL statement that inserts tuples into
Students, and inserts a single tuple into a table that contains statistics on mod-
S(JL: (JneTie,s, Constraints, Triggers 171
ifications to database tables. The first two fields of the tuple contain constants
(identifying the modified table, Students, and the kind of modifying statement,
an INSERT), and the third field is the number of inserted Students tuples with
age < 18. (The trigger in Figure 5.20 only computes the count; an additional
trigger is required to insert the appropriate tuple into the statistics table.)
If a statement activates more than one trigger, the DBMS typically processes
all of them, in senne arbitrary order. An important point is that the execution
of the action part of a trigger could in turn activate another trigger. In par-
ticular, the execution of the action part of a trigger could a,gain activate the
sarne trigger; such triggers "u'e called recursive triggers. The potential for
such chain activations and the unpredictable order in which a DBMS processes
activated triggers can make it difficult to understand the effect of a collection
of triggers.
172 CHAPTER'5
• Suppose that we have a table called Orders with fields iternid, quantity,
custornerid, and unitprice. When a customer places an order, the first
three field values are filled in by the user (in this example, a sales clerk).
The fourth field's value can be obtained from a table called Items, but it
is important to include it in the Orders table to have a complete record of
the order, in case the price of the item is subsequently changed. We can
define a trigger to look up this value and include it in the fourth field of
a newly inserted record. In addition to reducing the number of fields that
the clerk h&'3 to type in, this trigger eliminates the possibility of an entry
error leading to an inconsistent price in the Orders table.
• Continuing with this example, we may want to perform some additional
actions when an order is received. For example, if the purchase is being
charged to a credit line issued by the company, we may want to check
whether the total cost of the purch&'3e is within the current credit limit.
We can use a trigger to do the check; indeed, we can even use a CHECK
constraint. Using a trigger, however, allows us to implement more sophis-
ticated policies for dealing with purchases that exceed a credit limit. For
instance, we may allow purchases that exceed the limit by no more than
10% if the customer has dealt with the company for at least a year, and
add the customer to a table of candidates for credit limit increases.
and possibly generate additional sales! \Ve can rela;y this information by using
a trigger that checks recent purcha.ses and prints a message if the customer
qualifies for the discount.
Triggers can generate a log of events to support auditing and security checks.
For example, each time a customer places an order, we can create a record with
the customer's ID and current credit limit and insert this record in a customer
history table. Subsequent analysis of this table might suggest candidates for
an increased credit limit (e.g., customers who have never failed to pay a bill on
time and who have come within 10% of their credit limit at least three times
in the last month).
As the examples in Section 5.8 illustrate, we can use triggers to gather statistics
on table accesses and modifications. Some database systems even use triggers
internally as the basis for managing replicas of relations (Section 22.11.1). Our
list of potential uses of triggers is not exhaustive; for example, triggers have
also been considered for workflow management and enforcing business rules.
• What are the parts of a basic SQL query? Are the input and result tables
of an SQL query sets or multisets? How can you obtain a set of tuples as
the result of a query? (Section 5.2)
• What are range variables in SQL? How can you give names to output
columns in a query that are defined by arithmetic or string expressions?
What support does SQL offer for string pattern matching? (Section 5.2)
• What operations does SQL provide over (multi)sets of tuples, and how
would you use these in writing queries? (Section 5.3)
• vVhat are nested queries? What is correlation in nested queries? How
would you use the operators IN, EXISTS, UNIQUE, ANY, and ALL in writing
nested queries? Why are they useful? Illustrate your answer by showing
how to write the division operator in SQL. (Section 5.4)