Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Triggers. 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block:

Similar presentations


Presentation on theme: "1 Triggers. 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block:"— Presentation transcript:

1 1 Triggers

2 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block: DECLARE (optional) /* Variable declaration */ BEGIN (mandatory) /* Block action*/ EXCEPTION (optional) /* Exception handling */ END; (mandatory) /

3 3 Example from last week DECLARE e_number1 EXCEPTION; cnt NUMBER; BEGIN select count(*) into cnt from number_table; IF cnt = 1 THEN RAISE e_number1; ELSE dbms_output.put_line(cnt); END IF; EXCEPTION WHEN e_number1 THEN dbms_output.put_line('Count = 1'); end;

4 4 PL/SQL reminder-cont. We also showed the structures of procedures and functions, as named PL/SQL blocks which can be called: create or replace procedure num_logged (person IN mylog.who%TYPE, num OUT mylog.logon_num%TYPE) IS BEGIN select logon_num into num from mylog where who = person; END; / create or replace procedure num_logged (person IN mylog.who%TYPE, num OUT mylog.logon_num%TYPE) IS BEGIN select logon_num into num from mylog where who = person; END; /

5 5 Triggers- introduction A trigger is an action which the Database should perform when some DB event has occurred. For example (in pseudocode): TriggerA: For any row that is inserted into table Sailors: if age>30 -> insert this row into oldSailors; else-> insert this row into youngSailors;

6 6 Trigger introduction cont. The code within the trigger, called the trigger body, is made up of PL/SQL blocks The “firing” of a trigger is transparent to the user. There are many optional triggering events, but we will focus on update, delete, and insert. Triggers can be used to check for data integrity, but should be used so only if it is not possible through other means.

7 7 Types of triggers 1.Row level triggers: The code in the trigger is executed once for every row updated. 2.Statement level triggers (Default): The code in the trigger is performed once per statement. For example: if the triggering event was an update which updates 100 rows, a row-level trigger will execute 100 times, and a statement level trigger will execute once.

8 8 Types of triggers-cont. 1.BEFORE triggers: The trigger fires immediately BEFORE the triggering event executes. 2.AFTER triggers: The trigger fires immediately AFTER the triggering event executes. 3.INSTEAD OF triggers: The trigger fires INSTEAD of the triggering event. We can reference the “old” and “new” values. If we want to change rows which will be inserted, we have to use a BEFORE trigger and change the ‘new’ values. Using an AFTER trigger will not allow the change. ‘old’ values are meaningless for INSERT.

9 9 Trigger syntax CREATE [or REPLACE] TRIGGER trig_name {BEFORE | AFTER | INSTEAD OF} {DELETE | INSERT | UPDATE [of column1 [, column2]...] } [or {DELETE | INSERT | UPDATE [of columnA [, columnB]...] }...] on table_name [FOR EACH ROW] [WHEN (condition)] PL/SQL block Further restricts when trigger is fired

10 10 Backing Up Data create table sailors_audit( who varchar2(30), when_changed date, sid number, old_rating number, new_rating number ); create table sailors( sid number, sname VARCHAR2(30), rating number check(rating <= 10), age number );

11 11 Backing Up Data Q: Why AFTER Trigger? A: Because in that case, the firing of the trigger occurs only when the inserted data complies with the table integrity (check..) CREATE or REPLACE TRIGGER backup_trig AFTER UPDATE of Rating on Sailors FOR EACH ROW WHEN (old.rating < new.rating) BEGIN INSERT INTO sailors_audit VALUES (USER, SYSDATE, :old.sid, :old.rating, :new.rating); END; /

12 12 Ensuring Upper Case CREATE or REPLACE TRIGGER sname_trig BEFORE INSERT or UPDATE of sname on Sailors FOR EACH ROW BEGIN :new.sname := UPPER(:new.sname); END; / Why BEFORE Trigger?

13 13 Instead Of Trigger create view sailors_reserves as select sailors.*, reserves.bid, reserves.day from sailors, reserves where sailors.sid = reserves.sid; CREATE or REPLACE TRIGGER view_trig INSTEAD OF INSERT on sailors_reserves FOR EACH ROW BEGIN INSERT INTO sailors values(:new.sname, :new.sid, :new.rating,:new.age); INSERT INTO reserves values(:new.sid, :new.bid, :new.day); END; /

14 14 Statement Trigger CREATE or REPLACE TRIGGER no_work_on_shabbat_trig BEFORE INSERT or DELETE or UPDATE on reserves DECLARE shabbat_exception EXCEPTION; BEGIN if (TO_CHAR (sysdate,'DY')='SAT') then raise shabbat_exception; end if; END; / What happens if exception is thrown? Why BEFORE Trigger?

15 15 Another example create or replace trigger trig2 after update of rating on sailors for each row DECLARE diff number:=abs((:old.rating)-(:new.rating)); BEGIN If ((:old.rating)>(:new.rating)) then dbms_output.put_line('The rating of '||:old.sname||' has dropped by '||diff); elsif ((:old.rating)<(:new.rating)) then dbms_output.put_line('The rating of '||:old.sname||' has been raised by '||diff); else dbms_output.put_line('The rating of '||:old.sname||' has remained the same'); end if; END; /

16 16 Trigger Compilation Errors As with procedures and functions, when creating a Trigger with errors, you will get the message: “Warning: Trigger created with compilation errors.” To view the errors, type: SHOW ERRORS TRIGGER myTrigger To drop a trigger write drop trigger myTrig To disable/enable a trigger write alter trigger myTrig disable/enable

17 17 Additional Types of Triggers Can also define triggers for –logging in and off –create/drop table events –system errors –etc.

18 18 Optimization Recap and examples

19 19 Optimization introduction For every SQL expression, there are many possible ways of implementation. The different alternatives could result in huge run-time differences. Our aim is to introduce the basic hardware used, and optimization principles Current optimizers are a lot more complicated, but were originated from the same principles.

20 20 Hardware Recap The DB is kept on the Disk. The Disk is divided into BLOCKS (1-4 Kbytes) Any processing of the information occurs in the Main Memory. Therefore, a block which we want to access has to be brought from the Disk to the memory, and perhaps written back. Blocks are read/written from/to the Disk as single units. The time of reading/writing a block to/from the disk is an I/O operation, and takes a lot of time.

21 21 Hardware Recap We assume a constant time for each Disk access, and that only disk access affects define the run time. Every table in the DB is stored as a File (on the Disk), which is a ‘bunch of Blocks’. Every block contains many tuples, each of them has a Record ID (RID), which states its location: (number of block, number of tuple within the block)

22 22 Disk-Memory-CPU Delete from Sailors where sid=90 DISK sailors Reserves Main Memory CPU

23 23 Indexes on files Files can hold the tuples in a few ways, we will deal with a heap (no ordering), or ordered file. An Index of Data Entries is an additional file which helps access the data fast. The index can have the structure of a B+ Tree, or a hash function. A Clustered index means that the Data Entries in the leaves of the tree are in the same order as in the table.

24 24 SID SNAME ratingage 1923Joe832 3321Moe941 1332Boe733 1226Bill623 1445Mark954 (3,1) (3,2) (3,3) (3,4) (4,5) RID Tree INDEX ON SNAME DATA Boe(3,3) Mark(4,5) Bill(3,4) Moe(3,2) Joe (3,1) Example of a tree index on a file ……… Block 3Block 3 4 Getting to the root is 2-3 I/O

25 25 A: B: Boe(3,3),Bill(3,4) C: … M: Moe(3,2),Mark(4,5) … HASH INDEX ON SNAME H( ‘ Mark ’ ) Hash function So why is a hash index good only for equality conditions? Select * from Sailors where sname= ‘ Mark ’ ; To the DATA Is this Index clustered? Finding the right bucket takes 1.2 I/O Buckets

26 26 Natural Join We want to compute We have 4 optional algorithms: 1.Block Nested Loops Join 2.Index Nested Loops Join 3.Sort Merge Join 4.Hash Join SELECT * FROM Reserves R, Sailors S WHERE R.sid = S.sid This is assuming there is not enough space in the memory for the smaller of the 2 relations+2

27 27 Block Nested Loop Join Suppose there are B available blocks in the memory, B R blocks f relation R, and B S blocks of relations S, and |R|<|S|. Until all blocks of R have been read: –Read B-2 blocks of R –Read all blocks of S, and write the result –Run time: B R + B S * ceil(B R /(B-2))

28 28 Index Nested Loop Suppose there is an index on sid of Sailor Until all blocks of R have been read: –Read a block of R –For each tuple in the block, use the index of S to locate the matching tuples in S. We mark the time it takes to read the tuples in S that match a tuple in R as X. Run time: B R + t R X If the index is hash-based and clustered, X=2.2 If the index is tree-based and clustered, X=3-5 If it is not clustered, we evaluate X.

29 29 Sort-Merge Join Sort both relations on the join column Join them according to the join algorithm: sidbiddayagent 2810312/4/96Joe 2810311/3/96Frank 3110110/2/96Joe 3110212/7/96Sam 3110113/7/96Sam 581032/6/96Frank sidsnameratingage 22dustin745 28yuppy935 31lubber855 36lubber636 44guppy535 58rusty1035

30 30 Run time of Sort-Merge Sorting: O(MlogM)+O(NlogN) Merging: O(N)+O(M) if no partition is scanned twice. Total: O(MlogM)+O(NlogN) Typically good if one or both of the relations is already sorted.

31 31 Question 1 Suppose: tuple size= 100 bytes number of tuples (employees)=30,000 Page size=1000 bytes You have an unclustered index on Hobby. How would you calculate this query if 50 employees collect stamps? And if 1,000 employees collect stamps? SELECT E.dno FROM Employees E WHERE E.hobby=‘stamps’

32 32 Question 2 How would you choose to calculate this query? What indexes would you suggest to use? SELECT E.ename, D.mgr FROM Employees E, Departments D WHERE D.dname=‘Toy’ AND E.dno=D.dno

33 33 Question 3 SELECT E.ename, D.mgr FROM Employees E, Departments D WHERE D.dname=‘Toy’ AND E.dno=D.dno AND E.age = 25 How would you choose to calculate this query? What indexes would you suggest to use?

34 34 Question 4 Emp(eid, age, sal, did) Dept(did, projid, budget, status) Proj(projid, code, report) Length of tuples, Number of tuples –Emp: 20 bytes, 20000 tuples –Dept: 40 bytes, 5000 tuples –Proj: 2000 bytes, 1000 tuples Pages contain 4000 bytes; 12 buffer pages

35 35 Question 4 (cont) Consider the queries: –find employees with age = 30 –find projects with code = 20 Assume that there are the same number of qualifying tuples in both. For which query is a clustered index more important?

36 36 Question 4 (cont) Consider the query: find employees with age > 30 Assume that there is an unclustered index on age. Suppose that there are N tuples for which age > 30 For which values of N is it cheaper to do a sequential scan?

37 37 Question 5 Consider the query: select * from R, S where R.a < S.b Can you use a variation on sort-merge join to compute this query? index nested loops join? block nested loops join?


Download ppt "1 Triggers. 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block:"

Similar presentations


Ads by Google