Experiment 7
Experiment 7
Experiment No.7
eneralized Model:
G
Triggers arebasedontheEvent-condition-Action(ECA)Model.AruleintheECAmodel
has three components.
1. The event(s) that triggers the rule.
2. The condition that determines whether theruleactionshouldbeexecuted.Ifnoactionis
specified, the action will be executed once the event occurs.
3. Theactiontobetaken.ItcouldbeasequenceofSQLstatements,aDBtransactionoran
external program that will be executed automatically.
REATE TRIGGER statement is used to implement such action in SQL. Consider the
C
triggers for following cases:-
1. Trigger for insertion:-
This trigger executes whenever condition is satisfied, during the insertion statement. If no
condition is satisfied, then it executed for every insertion statement, for the relation specified.
Example:-
(Somaiya Vidyavihar University)
KJSCE/IT-AI&DS/SYBTECH/SEMIII/DMS/2024-25
I n DB, we have created a trigger for insertion, on the relation Employee. If salaries <
1500 then print ‘Unsuccessful’ else print ‘Successful’.
2. Trigger for Updation:-
This trigger executes for updating ofacolumnname(s)ofaparticularrelation.Acondition
may or may not be specified.
Example:-
In our DB, we have created a trigger for updating, on the relation Employee. If salary is
updated to unacceptable amount, then print unsuccessful and rollback else print successful.
3. Trigger for Deletion:-
This trigger executes during the deletion statement.Ifaparticularconditionissatisfied,the
system may allow or not allow the deletion of certain tuples,
Example:-
If SSN from Employee =101, then print ‘Unsuccessful’ and rollback, else print ‘Successful’.
I nPostgresqlweneedtocreateafunctiontoexecuteallactionstatementsoftriggerandcall
this function in create trigger statement for certain event.
Example.
Inemployeeetablednumisaforeignkey.Sothetriggerwritenherewillincrementtotal_emp
of department table by one and total_sal of department by salary of newly inserted
employee's salary.
begin
UPDATE dept set total_emp=total_emp + 1,
total_sal=total_sal+ new.salary where dept.dno=new.dno;
RETURN new;
ND
E
$emp_update$ LANGUAGE plpgsql;
_ ____________________________________________________________________
Results: (Program printout with output / Document printout as per the format)
ETURN NEW;
R
END;
$$ LANGUAGE plpgsql;
___________________________________________________________________________
Questions:
Ans.
One real-time application of triggers is in inventory management systems, where they
automatically reorder stock when levels fall below a set threshold. This ensures optimal
inventory levels without manual intervention. Additionally, triggers can enforce
business rules and log changes for audit trails. Overall, they enhance efficiency,
accuracy, and timeliness in managing inventory.