Professional Documents
Culture Documents
1
Assertions
2
Assertions
l An expression that should be always true
3
Example 1
4
Example 2
5
Example 3
6
Assertions vs. Triggers
l Assertions do not modify the data, they only check certain conditions
l Triggers are more powerful because the can check conditions and also
modify the data
l Assertions are not linked to specific tables in the database and not linked
to specific events
10
Triggers: Introduction
l The application constraints need to be captured inside the database
11
Triggers
l A procedure that runs automatically when a certain
event occurs in the DBMS
12
Trigger Components
l Three components
l Event: When this event happens, the trigger is activated
l Condition (optional): If the condition is true, the trigger
executes, otherwise skipped
l Action: The actions performed by the trigger
l Semantics
l When the Event occurs and Condition is true, execute the
Action
14
Trigger: Events
l Three event types
l Insert
l Update
l Delete
l Two granularities
l Execute for each row
l Execute for each statement
15
1) Trigger: Event
Trigger name
Create Trigger <name>
Before|After Insert|Update|Delete ON <tablename> That is the event
….
lExample
Create Trigger ABC Create Trigger XYZ
Before Insert On Students After Update On Students
…. ….
16
Granularity of Event
l A single SQL statement may update, delete, or insert many records
at the same time
l E.g., Update student set gpa = gpa x 0.8;
17
Example: Granularity of Event
18
2) Trigger: Condition
lThis component is optional
Create Trigger <name>
Before| After Insert| Update| Delete On <tableName>
For Each Row | For Each Statement
If the employee salary > 150,000 then some actions will be taken
20
Trigger: Referencing Values
l In the action, you may want to reference:
l The new values of inserted or updated records (:new)
l The old values of deleted or updated records (:old)
21
Trigger: Referencing Values (Cont’d)
l Insert Event
l Has only :new defined
l Delete Event
l Has only :old defined
l Update Event
l Has both :new and :old defined
l After triggering
l Should not change :new because the event is already done
22
Example 1
If the employee salary increased by more than 10%, make sure the
‘rank’ field is not empty and its value has changed, otherwise reject the
update
23
Example 2
If the employee salary increased by more than 10%, then increment the rank field
by 1.
24
Example 3: Using Temp Variable
If the newly inserted record in employee has null hireDate field, fill it in with the
current date
25
Example 4: Maintenance of Derived
Attributes
Keep the bonus attribute in Employee table always 3% of the salary attribute
26
Views
• In some cases, it is not desirable for all users to
see the entire logical model (that is, all the
actual relations stored in the database.)
• Consider a person who needs to know a
customer’s loan number but has no need to
see the loan amount. This person should see a
relation described, in SQL, by