SlideShare une entreprise Scribd logo
1  sur  8
Triggers in SQL
1
Fall 2001 Database Systems 1
Triggers
• Assertions
– Assertions describe rules that should hold for a given
database.
– An assertion is checked anytime a table mentioned in it is
changed.
– If an assertion is violated, then the change that caused
the violation is rejected.
• Triggers
– Triggers explicitly specify when they should be checked
(i.e. insert, delete, update)
– They describe a condition that activates the trigger if it
evaluates to true
– Triggers describe what is to be done upon activation
Fall 2001 Database Systems 2
Designing triggers
• Use triggers to guarantee that when a specific operation is performed,
related actions are performed.
• Do not define triggers that duplicate the functionality already built into
Oracle. For example, do not define triggers to enforce data integrity rules
that can be easily enforced using declarative integrity constraints.
• Limit the size of triggers. If the logic for your trigger requires much more
than 60 lines of PL/SQL code, then it is better to include most of the code in
a stored procedure and call the procedure from the trigger.
• Use triggers only for centralized, global operations that should be fired for
the triggering statement, regardless of which user or database application
issues the statement.
• Do not create recursive triggers. For example, creating an AFTER
UPDATE statement trigger on the Emp_tab table that itself issues an
UPDATE statement on Emp_tab, causes the trigger to fire recursively until it
has run out of memory.
• Use triggers on DATABASE judiciously. They are executed for every user
every time the event occurs on which the trigger is created.
Triggers in SQL
2
Fall 2001 Database Systems 3
Example
CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE sal_diff number;
BEGIN
sal_diff := :new.sal - :old.sal;
dbms_output.put('Old salary: ' || :old.sal);
dbms_output.put(' New salary: ' || :new.sal);
dbms_output.put_line(' Difference ' || sal_diff);
END;
/
Fall 2001 Database Systems 4
Triggers – activation
• A trigger can be activated BEFORE/AFTER/INSTEAD OF an
activating event, usually insert/delete/update to one or more
relations
• The action can refer to both old and new values of tuples that were
inserted/deleted/updated in the event that triggered the action.
CREATE TRIGGER probation_trigger
AFTER UPDATE OF gpa ON student
• A condition may include a WHEN clause
– the trigger action is executed only if the condition holds when the
triggering event occurs
• The WHEN clause takes any boolean condition
WHEN (gpa < 2.0)
Triggers in SQL
3
Fall 2001 Database Systems 5
Trigger - course of action
• The programmer has the option of specifying that the action is performed
either
– once for each modified tuple, or
– once for all the tuples that are changed in one database operation
FOR EACH ROW
UPDATE student
SET probation_date = SYSDATE
WHERE student.sid = OldTuple.sid
• The trigger body can use any valid PL/SQL statement, IF THEN ELSE,
WHILE, etc.
Fall 2001 Database Systems 6
Trigger - exceptions
• If a predefined or user-defined error condition or
exception is raised during the execution of a trigger
body, then all effects of the trigger body, as well as the
triggering statement, are rolled back (unless the error is
trapped by an exception handler).
• Therefore, a trigger body can prevent the execution of
the triggering statement by raising an exception.
• User-defined exceptions are commonly used in triggers
that enforce complex security authorizations or integrity
constraints.
Triggers in SQL
4
Fall 2001 Database Systems 7
Triggers - row level
• Insertions create new tuples
– There is no corresponding “old” value
• Updates change a tuple from an old value to a new value
– You can refer to both values: “old” and “new” of the tuple in the
trigger
• Deletes remove a tuple
– There is no new value for the tuple (it is null)
• Old/New values can only be accessed for each row,
statement level triggers cannot access values of
individual rows that are being changed.
Fall 2001 Database Systems 8
Triggers
• Activation
– BEFORE -- the WHEN condition is tested before the triggering
event
• if the condition is true, the trigger action is executed
• then the event that triggered the update is executed
– INSTEAD OF -- the action is executed if the WHEN condition is
met
• the triggering event is never executed.
– AFTER – the action is executed if the WHEN condition is met
after the triggering event is completed.
• In BEFORE/AFTER trigger, the triggering event is rejected only if an
exception is raised.
Triggers in SQL
5
Fall 2001 Database Systems 9
Mutating tables
• A mutating table is a table that is currently being modified by an UPDATE,
DELETE, or INSERT statement, or it is a table that might need to be
updated by the effects of a declarative DELETE CASCADE referential
integrity constraint.
• A constraining table is a table that a triggering statement might need to read
either directly, for an SQL statement, or indirectly, for a declarative
referential integrity constraint.
• A table is mutating or constraining only to the session that issued the
statement in progress.
• Tables are never considered mutating or constraining for statement triggers
unless the trigger is fired as the result of a DELETE CASCADE.
• Views are not considered mutating or constraining in INSTEAD OF triggers.
Fall 2001 Database Systems 10
Mutating tables
• For all row triggers, or for statement triggers that were fired as the
result of a DELETE CASCADE:
– The SQL statements of a trigger cannot read from (query) or
modify a mutating table of the triggering statement.
– The statements of a trigger cannot change the PRIMARY,
FOREIGN, or UNIQUE KEY columns of a constraining table of
the triggering statement.
• There is an exception to this restriction: For a single row INSERT,
constraining tables are mutating for AFTER row triggers, but not for
BEFORE row triggers. INSERT statements that involve more than
one row, such as INSERT INTO Emp_tab SELECT..., are not
considered single row inserts, even if they only result in one row
being inserted.
• These restrictions prevent a trigger from seeing an inconsistent set
of data.
Triggers in SQL
6
Fall 2001 Database Systems 11
Mutating tables
Fall 2001 Database Systems 12
Example
TOOK(ssn, cid, semester, year,
section, grade)
Students may not enroll in more than one section
of a class in the same semester and year. If this
happens, delete all records for this student in
other sections and insert him/her in the new
section.
Triggers in SQL
7
Fall 2001 Database Systems 13
Example
CREATE OR REPLACE TRIGGER took_trg
AFTER INSERT ON took
REFERENCING NEW AS x
FOR EACH ROW
BEGIN
DELETE FROM took t
WHERE t.cid = :x.cid AND t.semester=:x.semester AND
t.year = :x.year AND t.ssn = :x.ssn AND
t.section <> :x.section ;
END ;
/
Problem: took
is mutating!
Fall 2001 Database Systems 14
Example – correct solution
CREATE VIEW tookv AS SELECT * FROM took ;
CREATE OR REPLACE TRIGGER took_trg
INSTEAD OF INSERT ON tookv
REFERENCING NEW AS x
FOR EACH ROW
BEGIN
DELETE FROM took t
WHERE t.cid = :x.cid AND t.semester=:x.semester AND
t.year = :x.year AND t.ssn = :x.ssn AND
t.section <> :x.section ;
INSERT INTO took(cid, semester, year, section, ssn)
VALUES(:x.cid,:x.semester,:x.year,:x.section,:x.ssn) ;
END ;
/
Triggers in SQL
8
Fall 2001 Database Systems 15
SQL Environment
Schema
Schema
Catalog
Catalog
Cluster = maximum
scope of a DB
operation
Cluster
Environment =
installation of
DBMS
• A schema contains
tables, views, assertions,
domains,indices, etc.
• A catalog contains a
collection of schemas
• A cluster is a collection of
catalogs.
– each user has a cluster
that is the set of all
catalogs accessible to
the user
• An environment is an
installation of a DBMS
Fall 2001 Database Systems 16
System catalogs
• All DBMSs maintain system catalogs as ordinary
relations
– these tables can be queried using SQL in the same
way as any ordinary table
• For ORACLE:
– ALL_ALL_TABLES (OWNER, TABLE_NAME, … )
– ALL_COL_PRIVS(GRANTOR, GRANTEE, TABLE_SCHEMA,
TABLE_NAME, COLUMN_NAME, PRIVILEGE, GRANTABLE)
– also ALL_TAB_PRIVS
– ALL_CONSTRAINTS (OWNER, CONSTRAINT_NAME,
CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION,
DELETE_RULE, STATUS, DEFERRABLE, … )
– ALL_VIEWS, ALL_TABLES, ALL_USERS, ALL_ROLES, etc.

Contenu connexe

En vedette

Sql insert statement
Sql insert statementSql insert statement
Sql insert statementVivek Singh
 
Sql create table statement
Sql create table statementSql create table statement
Sql create table statementVivek Singh
 
SAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_tableSAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_tableYasmin Ashraf
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 
Part 15 triggerr
Part 15  triggerrPart 15  triggerr
Part 15 triggerrDenny Yahya
 
Sql update statement
Sql update statementSql update statement
Sql update statementVivek Singh
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statementsVivek Singh
 
SQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate TableSQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate Table1keydata
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 

En vedette (14)

Sql insert statement
Sql insert statementSql insert statement
Sql insert statement
 
6. triggers
6. triggers6. triggers
6. triggers
 
Sql create table statement
Sql create table statementSql create table statement
Sql create table statement
 
SAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_tableSAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_table
 
Sql wksht-7
Sql wksht-7Sql wksht-7
Sql wksht-7
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Part 15 triggerr
Part 15  triggerrPart 15  triggerr
Part 15 triggerr
 
Sql update statement
Sql update statementSql update statement
Sql update statement
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statements
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
SQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate TableSQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate Table
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 

Similaire à SQL Triggers Explained

11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)Simarjit Mann
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptxKhngNguyn81
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academythewebsacademy
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedureJong Woo Rhee
 
Performance tuning
Performance tuningPerformance tuning
Performance tuningami111
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Thuan Nguyen
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15Syed Asrarali
 

Similaire à SQL Triggers Explained (20)

Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
 
11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Unit 4
Unit 4Unit 4
Unit 4
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Trigger
TriggerTrigger
Trigger
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedure
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql DML
Sql DMLSql DML
Sql DML
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
SQL
SQLSQL
SQL
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
 

Plus de AnusAhmad

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexingAnusAhmad
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01AnusAhmad
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13AnusAhmad
 
9. java server faces
9. java server faces9. java server faces
9. java server facesAnusAhmad
 
8. java script
8. java script8. java script
8. java scriptAnusAhmad
 
2. http, html
2. http, html2. http, html
2. http, htmlAnusAhmad
 

Plus de AnusAhmad (20)

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 
8. java script
8. java script8. java script
8. java script
 
7. struts
7. struts7. struts
7. struts
 
5. servlets
5. servlets5. servlets
5. servlets
 
4. jsp
4. jsp4. jsp
4. jsp
 
3. applets
3. applets3. applets
3. applets
 
2. http, html
2. http, html2. http, html
2. http, html
 
1. intro
1. intro1. intro
1. intro
 

Dernier

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Dernier (20)

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

SQL Triggers Explained

  • 1. Triggers in SQL 1 Fall 2001 Database Systems 1 Triggers • Assertions – Assertions describe rules that should hold for a given database. – An assertion is checked anytime a table mentioned in it is changed. – If an assertion is violated, then the change that caused the violation is rejected. • Triggers – Triggers explicitly specify when they should be checked (i.e. insert, delete, update) – They describe a condition that activates the trigger if it evaluates to true – Triggers describe what is to be done upon activation Fall 2001 Database Systems 2 Designing triggers • Use triggers to guarantee that when a specific operation is performed, related actions are performed. • Do not define triggers that duplicate the functionality already built into Oracle. For example, do not define triggers to enforce data integrity rules that can be easily enforced using declarative integrity constraints. • Limit the size of triggers. If the logic for your trigger requires much more than 60 lines of PL/SQL code, then it is better to include most of the code in a stored procedure and call the procedure from the trigger. • Use triggers only for centralized, global operations that should be fired for the triggering statement, regardless of which user or database application issues the statement. • Do not create recursive triggers. For example, creating an AFTER UPDATE statement trigger on the Emp_tab table that itself issues an UPDATE statement on Emp_tab, causes the trigger to fire recursively until it has run out of memory. • Use triggers on DATABASE judiciously. They are executed for every user every time the event occurs on which the trigger is created.
  • 2. Triggers in SQL 2 Fall 2001 Database Systems 3 Example CREATE OR REPLACE TRIGGER Print_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab FOR EACH ROW WHEN (new.Empno > 0) DECLARE sal_diff number; BEGIN sal_diff := :new.sal - :old.sal; dbms_output.put('Old salary: ' || :old.sal); dbms_output.put(' New salary: ' || :new.sal); dbms_output.put_line(' Difference ' || sal_diff); END; / Fall 2001 Database Systems 4 Triggers – activation • A trigger can be activated BEFORE/AFTER/INSTEAD OF an activating event, usually insert/delete/update to one or more relations • The action can refer to both old and new values of tuples that were inserted/deleted/updated in the event that triggered the action. CREATE TRIGGER probation_trigger AFTER UPDATE OF gpa ON student • A condition may include a WHEN clause – the trigger action is executed only if the condition holds when the triggering event occurs • The WHEN clause takes any boolean condition WHEN (gpa < 2.0)
  • 3. Triggers in SQL 3 Fall 2001 Database Systems 5 Trigger - course of action • The programmer has the option of specifying that the action is performed either – once for each modified tuple, or – once for all the tuples that are changed in one database operation FOR EACH ROW UPDATE student SET probation_date = SYSDATE WHERE student.sid = OldTuple.sid • The trigger body can use any valid PL/SQL statement, IF THEN ELSE, WHILE, etc. Fall 2001 Database Systems 6 Trigger - exceptions • If a predefined or user-defined error condition or exception is raised during the execution of a trigger body, then all effects of the trigger body, as well as the triggering statement, are rolled back (unless the error is trapped by an exception handler). • Therefore, a trigger body can prevent the execution of the triggering statement by raising an exception. • User-defined exceptions are commonly used in triggers that enforce complex security authorizations or integrity constraints.
  • 4. Triggers in SQL 4 Fall 2001 Database Systems 7 Triggers - row level • Insertions create new tuples – There is no corresponding “old” value • Updates change a tuple from an old value to a new value – You can refer to both values: “old” and “new” of the tuple in the trigger • Deletes remove a tuple – There is no new value for the tuple (it is null) • Old/New values can only be accessed for each row, statement level triggers cannot access values of individual rows that are being changed. Fall 2001 Database Systems 8 Triggers • Activation – BEFORE -- the WHEN condition is tested before the triggering event • if the condition is true, the trigger action is executed • then the event that triggered the update is executed – INSTEAD OF -- the action is executed if the WHEN condition is met • the triggering event is never executed. – AFTER – the action is executed if the WHEN condition is met after the triggering event is completed. • In BEFORE/AFTER trigger, the triggering event is rejected only if an exception is raised.
  • 5. Triggers in SQL 5 Fall 2001 Database Systems 9 Mutating tables • A mutating table is a table that is currently being modified by an UPDATE, DELETE, or INSERT statement, or it is a table that might need to be updated by the effects of a declarative DELETE CASCADE referential integrity constraint. • A constraining table is a table that a triggering statement might need to read either directly, for an SQL statement, or indirectly, for a declarative referential integrity constraint. • A table is mutating or constraining only to the session that issued the statement in progress. • Tables are never considered mutating or constraining for statement triggers unless the trigger is fired as the result of a DELETE CASCADE. • Views are not considered mutating or constraining in INSTEAD OF triggers. Fall 2001 Database Systems 10 Mutating tables • For all row triggers, or for statement triggers that were fired as the result of a DELETE CASCADE: – The SQL statements of a trigger cannot read from (query) or modify a mutating table of the triggering statement. – The statements of a trigger cannot change the PRIMARY, FOREIGN, or UNIQUE KEY columns of a constraining table of the triggering statement. • There is an exception to this restriction: For a single row INSERT, constraining tables are mutating for AFTER row triggers, but not for BEFORE row triggers. INSERT statements that involve more than one row, such as INSERT INTO Emp_tab SELECT..., are not considered single row inserts, even if they only result in one row being inserted. • These restrictions prevent a trigger from seeing an inconsistent set of data.
  • 6. Triggers in SQL 6 Fall 2001 Database Systems 11 Mutating tables Fall 2001 Database Systems 12 Example TOOK(ssn, cid, semester, year, section, grade) Students may not enroll in more than one section of a class in the same semester and year. If this happens, delete all records for this student in other sections and insert him/her in the new section.
  • 7. Triggers in SQL 7 Fall 2001 Database Systems 13 Example CREATE OR REPLACE TRIGGER took_trg AFTER INSERT ON took REFERENCING NEW AS x FOR EACH ROW BEGIN DELETE FROM took t WHERE t.cid = :x.cid AND t.semester=:x.semester AND t.year = :x.year AND t.ssn = :x.ssn AND t.section <> :x.section ; END ; / Problem: took is mutating! Fall 2001 Database Systems 14 Example – correct solution CREATE VIEW tookv AS SELECT * FROM took ; CREATE OR REPLACE TRIGGER took_trg INSTEAD OF INSERT ON tookv REFERENCING NEW AS x FOR EACH ROW BEGIN DELETE FROM took t WHERE t.cid = :x.cid AND t.semester=:x.semester AND t.year = :x.year AND t.ssn = :x.ssn AND t.section <> :x.section ; INSERT INTO took(cid, semester, year, section, ssn) VALUES(:x.cid,:x.semester,:x.year,:x.section,:x.ssn) ; END ; /
  • 8. Triggers in SQL 8 Fall 2001 Database Systems 15 SQL Environment Schema Schema Catalog Catalog Cluster = maximum scope of a DB operation Cluster Environment = installation of DBMS • A schema contains tables, views, assertions, domains,indices, etc. • A catalog contains a collection of schemas • A cluster is a collection of catalogs. – each user has a cluster that is the set of all catalogs accessible to the user • An environment is an installation of a DBMS Fall 2001 Database Systems 16 System catalogs • All DBMSs maintain system catalogs as ordinary relations – these tables can be queried using SQL in the same way as any ordinary table • For ORACLE: – ALL_ALL_TABLES (OWNER, TABLE_NAME, … ) – ALL_COL_PRIVS(GRANTOR, GRANTEE, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, PRIVILEGE, GRANTABLE) – also ALL_TAB_PRIVS – ALL_CONSTRAINTS (OWNER, CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION, DELETE_RULE, STATUS, DEFERRABLE, … ) – ALL_VIEWS, ALL_TABLES, ALL_USERS, ALL_ROLES, etc.