0% found this document useful (0 votes)
5 views6 pages

DP Unit02 ActiveDatabase

Uploaded by

leebha.pushparaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

DP Unit02 ActiveDatabase

Uploaded by

leebha.pushparaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

168 CHAPTER$5

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:

CREATE ASSERTION smallClub


CHECK (( SELECT COUNT (S.sid) FROM Sailors S )
+ ( SELECT COUNT (B. bid) FROM Boats B)
< 100 )

5.8 TRIGGERS AND ACTIVE DATABASES


A trigger is a procedure that is automatically invoked by the DBMS in re-
sponse to specified changes to the database, and is typically specified by the
DBA. A database that has a set of associated triggers is called an active
database. A trigger description contains three parts:

• Event: A change to the database that activates the trigger.


.. Condition: A query or test that is run when the trigger is activated.
.. Action: A procedure that is executed when the trigger is activated and
its condition is true.

A trigger can be thought of as a 'daemon' that monitors a databa.se, and is exe-


cuted when the database is modified in a way that matches the event specifica-
tion. An insert, delete, or update statement could activate a trigger, regardless
of which user or application invoked the activating statement; users may not
even be aware that a trigger wa.'3 executed as a side effect of their program.

A condition in a trigger can be a true/false statement (e.g., all employee salaries


are less than $100,000) or a query. A query is interpreted as true if the answer
SQL: Que'ries, Constrairds, TriggeTs It>9

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.

An important issue is when the action part of a trigger executes in relation to


the statement that activated the trigger. For example, a statement that inserts
records into the Students table may activate a trigger that is used to maintain
statistics on how many studen~s younger than 18 are inserted at a time by a
typical insert statement. Depending on exactly what the trigger does, we may
want its action to execute before changes are made to the Students table or
afterwards: A trigger that initializes a variable used to count the nurnber of
qualifying insertions should be executed before, and a trigger that executes once
per qualifying inserted record and increments the variable should be executed
after each record is inserted (because we may want to examine the values in
the new record to determine the action).

5.8.1 Examples of Triggers in SQL


The examples shown in Figure 5.20, written using Oracle Server syntax for
defining triggers, illustrate the basic concepts behind triggers. (The SQL:1999
syntax for these triggers is similar; we will see an example using SQL:1999
syntax shortly.) The trigger called iniLcount initializes a counter variable be-
fore every execution of an INSERT statement that adds tuples to the Students
relation. The trigger called incr_count increments the counter for each inserted
tuple that satisfies the condition age < 18.

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

CREATE TRIGGER iniLeount BEFORE INSERT ON Students 1* Event *1


DECLARE
count INTEGER:
BEGIN 1* Action *I
count := 0:
END

CREATE TRIGGER incLcount AFTER INSERT ON Students 1* Event *1


WHEN (new.age < 18) 1* Condition; 'new' is just-inserted tuple *1
FOR EACH ROW
BEGIN 1* Action; a procedure in Oracle's PL/SQL syntax *1
count := count + 1;
END

Figure 5.20 Examples Illustrating Triggers

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

CREATE TRIGGER seLcount AFTER INSERT ON Students j* Event * j


REFERENCING NEW TABLE AS InsertedTuples
FOR EACH STATEMENT
INSERT j* Action * j
INTO StatisticsTable(ModifiedTable, ModificationType, Count)
SELECT 'Students', 'Insert', COUNT *
FROM InsertedTuples I
WHERE 1. age < 18

Figure 5.21 Set-Oriented Trigger

5.9 DESIGNING ACTIVE DATABASES


Triggers offer a powerful mechanism for dealing with changes to a database,
but they must be used with caution. The effect of a collection of triggers can
be very complex, and maintaining an active database can become very difficult.
Often, a judicious use of integrity constraints can replace the use of triggers.

5.9.1 Why Triggers Can Be Hard to Understand


In an active database system, when the DBMS is about to execute a statement
that modifies the databa.se, it checks whether some trigger is activated by the
statement. If so, the DBMS processes the trigger by evaluating its condition
part, and then (if the condition evaluates to true) executing its action part.

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

5.9.2 Constraints versus Triggers


A common use of triggers is to maintain databa..'3e consistency, and in such
cases, we should always consider whether using an integrity constraint (e.g., a
foreign key constraint) achieves the same goals. The meaning of a constraint is
not defined operationally, unlike the effect of a trigger. This property makes a
constraint easier to understand, and also gives the DBMS more opportunities
to optimize execution. A constraint also prevents the data from being made
inconsistent by any kind of statement, whereas a trigger is activated by a specific
kind of statement (INSERT, DELETE, or UPDATE). Again, this restriction makes
a constraint easier to understand.

On the other hand, triggers allow us to maintain database integrity in more


flexible ways, as the following examples illustrate.

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

5.9.3 Other Uses of Triggers


.l\'Iany potential uses of triggers go beyond integrity maintenance. Triggers can
alert users to unusual events (&'3 reflected in updates to the databa..<;e). For
example, we may want to check whether a customer placing an order h&s made
enough purchases in the past month to qualify for an additional discount; if
so, the sales clerk must be informed so that he (or she) can tell the customer
SQL: Q'UeT'Ze,S, CO'l/stmints, Tr'iggers

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.

5.10 REVIEW QUESTIONS


Answers to the review questions can be found in the listed sections.

• 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)

• \Vhat aggregate operators does SQL support? (Section 5.5)


• \i\That is gmvping? Is there a counterpart in relational algebra? Explain
this feature, and discllss the interaction of the HAVING and WHERE clauses.
Mention any restrictions that mllst be satisfied by the fields that appear in
the GROUP BY clause. (Section 5.5.1)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy