SlideShare a Scribd company logo
1 of 28
Trigger
V. Saranya AP/CSE,
Sri Vidya College of Engg & Tech,
virudhunagar
Example: 1
Example : 2
Example : 3
Trigger
• A

procedure

that

starts

automatically

specified changes occur to the DBMS

if
Triggers (Active database)
• Three parts:
– Event (activates the trigger)
– Condition (tests whether the triggers should run)
[Optional]
– Action (what happens if the trigger runs)
• Semantics:
– When event occurs, and condition is satisfied, the
action is performed.
Triggers – Event,Condition,Action
• Events could be :
BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName>

e.g.:

BEFORE INSERT ON Professor

• Condition is SQL expression or even an SQL
query (query with non-empty result means
TRUE)
• Action can be many different choices :
– SQL statements , even DDL and transactionoriented statements like “commit”.
Example Trigger
Assume our DB has a relation schema
:

salary)

Professor (pNum, pName,

We want to write a trigger that :
Ensures that any new professor
inserted has salary >= 60000
Example Trigger

Event

CREATE TRIGGER minSalary “BEFORE INSERT” ON
Professor
for what context
BEGIN

?
Condition

check for violation here ?

END;
Example Trigger
CREATE TRIGGER minSalary BEFORE
INSERT ON Professor
FOR EACH ROW
BEGIN

trigger is performed
for each row inserted

Violation of Minimum Professor
Salary?
END;
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON
Professor
FOR EACH ROW
BEGIN
IF (:new.salary < 60000)
THEN RAISE_APPLICATION_ERROR (-20004,
‘Violation of Minimum
Professor Salary’);
END IF;
END;
Example trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
FOR EACH ROW
DECLARE temp int;
needed

-- dummy variable not

BEGIN
IF (:new.salary < 60000)
THEN RAISE_APPLICATION_ERROR (-20004,
‘Violation of Minimum Professor
Salary’);
END IF;
temp := 10;
variables
END;

-- to illustrate declared
Details of Trigger Example
• BEFORE INSERT ON Professor
– This trigger is checked before the tuple is inserted
• FOR EACH ROW
– specifies that trigger is performed for each row
inserted
• :new
– refers to the new tuple inserted
• If (:new.salary < 60000)
– then an application error is raised and hence the
row is not inserted; otherwise the row is inserted.
• Use error code: -20004;
– this is in the valid range
Condition

Example Trigger Using
Condition

CREATE TRIGGER minSalary BEFORE INSERT ON Professor
FOR EACH ROW
WHEN (new.salary < 60000)
BEGIN
RAISE_APPLICATION_ERROR
(-20004,
‘Violation of Minimum Professor Salary’);
END;

• Conditions can refer to
old/new values of tuples
modified by the statement activating the trigger.
Triggers: REFERENCING
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
REFERENCING NEW as newTuple
FOR EACH ROW
WHEN (newTuple.salary < 60000)
BEGIN
RAISE_APPLICATION_ERROR (-20004,
‘Violation of Minimum Professor Salary’);
END;
Example Trigger
CREATE TRIGGER minSalary
BEFORE UPDATE ON Professor
REFERENCING OLD AS oldTuple NEW as newTuple
FOR EACH ROW
WHEN (newTuple.salary < oldTuple.salary)
BEGIN
RAISE_APPLICATION_ERROR (-20004, ‘Salary
Decreasing !!’);
END;

• Ensure that salary does not decrease
Another Trigger Example (SQL:99)
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE AS NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age,
rating)
SELECT sid, name, age, rating
FROM NewSailors N
WHERE N.age <= 18
Defined
by
triggering
transaction & level at which the
trigger is executed

Types of Triggers
This section describes the different types of triggers:
• Row level triggers
– Trigger once for “each row” in a transaction.
• Statement level triggers
– Triggers execute once for “each transaction”.
• Before and after triggers
– Triggers can be executed immediately before and
after INSERT, UPDATE and DELETE.
Row vs Statement Level Trigger
• Example: Consider a relation schema
Account (num, amount)
where we will allow creation of new
accounts
only during normal business hours.
Example: Statement level trigger
CREATE TRIGGER MYTRIG1
BEFORE INSERT ON Account
FOR EACH STATEMENT
--- is default
BEGIN
IF (TO_CHAR(SYSDATE,’dy’) IN (‘sat’,’sun’))
OR
(TO_CHAR(SYSDATE,’hh24:mi’) NOT BETWEEN ’08:00’
AND ’17:00’)
THEN
RAISE_APPLICATION_ERROR(-20500,’Cannot
create new account now !!’);
END IF;
END;
When to use BEFORE/AFTER
• Based on
semantics.

efficiency

considerations

or

• Suppose we perform statement-level after
insert, then all the rows are inserted first,
then if the condition fails,
and all the
inserted rows must be “rolled back”
•

Not very efficient !!
Combining multiple events into one
trigger
CREATE TRIGGER salaryRestrictions
AFTER INSERT OR UPDATE ON Professor
FOR EACH ROW
BEGIN
1 IF (INSERTING AND :new.salary < 60000) THEN
RAISE_APPLICATION_ERROR (-20004, 'below min
salary'); END IF;
2 IF (UPDATING AND :new.salary < :old.salary)
THEN RAISE_APPLICATION_ERROR (-20004,
‘Salary Decreasing !!'); END IF;
END;
Summary : Trigger Syntax
CREATE TRIGGER <triggerName>
BEFORE|AFTER
INSERT|DELETE|UPDATE
[OF <columnList>] ON <tableName>|<viewName>
[REFERENCING [OLD AS <oldName>] [NEW AS
<newName>]]
[FOR EACH ROW] (default is “FOR EACH STATEMENT”)
[WHEN (<condition>)]
<PSM body>;
Some Points about Triggers
• Check the system tables :
– user_triggers
– user_trigger_cols
– user_errors
• ORA-04091: mutating relation problem
– In a row level trigger, you cannot have the
body refer to the table specified in the event
• Also INSTEAD OF triggers can be specified on
views
To Show Compilation Errors
SELECT line, position, text
FROM user_errors
WHERE name = 'MY_TRIGGER'
AND TYPE = 'TRIGGER‘
• In SQL*Plus, you can also use the following
shortcut:
“SQL> SHOW ERRORS TRIGGER
MY_TRIGGER”
Mutating Trigger

“Trigger that triggers itself”
Constraints versus Triggers
•

Constraints are useful for database consistency

•

Triggers are flexible and powerful

•

But can be hard to understand ……

– More opportunity for optimization
– Not restricted into insert/delete/update

–
–
–
–
–

Alerts
Event logging for auditing
Security enforcement
Analysis of table accesses (statistics)
Workflow and business intelligence …

– Several triggers
(Arbitrary order  unpredictable !?)
– Chain triggers
(When to stop ?)
– Recursive triggers (Termination?)
Purpose of Triggers






To
To
To
To
To

generate data automatically
enforce complex integrity constraints
customize complex security authorization
maintain replicate tables
audit data modifications.

More Related Content

What's hot

06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinctBishal Ghimire
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONArun Sial
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Beat Signer
 
MYSQL Aggregate Functions
MYSQL Aggregate FunctionsMYSQL Aggregate Functions
MYSQL Aggregate FunctionsLeroy Blair
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptgourav kottawar
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Serverprogrammings guru
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functionsMudasir Syed
 
Types of keys in dbms
Types of keys in dbmsTypes of keys in dbms
Types of keys in dbmsdarshhingu
 

What's hot (20)

06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinct
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Trigger
TriggerTrigger
Trigger
 
MYSQL Aggregate Functions
MYSQL Aggregate FunctionsMYSQL Aggregate Functions
MYSQL Aggregate Functions
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functions
 
Oracle Database Sequence
Oracle Database SequenceOracle Database Sequence
Oracle Database Sequence
 
Sql commands
Sql commandsSql commands
Sql commands
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Types of keys in dbms
Types of keys in dbmsTypes of keys in dbms
Types of keys in dbms
 

Viewers also liked

Bases de données réparties par la pratique
Bases de données réparties par la pratiqueBases de données réparties par la pratique
Bases de données réparties par la pratiqueAbdelouahed Abdou
 
Introduction aux Triggers avec MySQL
Introduction aux Triggers avec MySQLIntroduction aux Triggers avec MySQL
Introduction aux Triggers avec MySQLRouff Joseph
 
[JSS2015] - Document db et nosql
[JSS2015] - Document db et nosql[JSS2015] - Document db et nosql
[JSS2015] - Document db et nosqlGUSS
 
Les bases fondamentales du langage transact sql
Les bases fondamentales du langage transact sqlLes bases fondamentales du langage transact sql
Les bases fondamentales du langage transact sqlZineb Meryem
 
Indexing and hashing
Indexing and hashingIndexing and hashing
Indexing and hashingJeet Poria
 
Architecture of-dbms-and-data-independence
Architecture of-dbms-and-data-independenceArchitecture of-dbms-and-data-independence
Architecture of-dbms-and-data-independenceAnuj Modi
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbmsshekhar1991
 
Relational Algebra-Database Systems
Relational Algebra-Database SystemsRelational Algebra-Database Systems
Relational Algebra-Database Systemsjakodongo
 
Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)Jargalsaikhan Alyeksandr
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMSkoolkampus
 
Webinar Smile et Talend : Faites communiquer vos applications en temps réel
Webinar Smile et Talend  : Faites communiquer vos applications en temps réelWebinar Smile et Talend  : Faites communiquer vos applications en temps réel
Webinar Smile et Talend : Faites communiquer vos applications en temps réelSmile I.T is open
 
ERP Implementation Life Cycle
ERP Implementation Life CycleERP Implementation Life Cycle
ERP Implementation Life CycleApurv Gourav
 
Business process reengineering
Business process reengineeringBusiness process reengineering
Business process reengineeringNeelkamal Sharma
 

Viewers also liked (20)

Bases de données réparties par la pratique
Bases de données réparties par la pratiqueBases de données réparties par la pratique
Bases de données réparties par la pratique
 
Introduction aux Triggers avec MySQL
Introduction aux Triggers avec MySQLIntroduction aux Triggers avec MySQL
Introduction aux Triggers avec MySQL
 
Triggers ppt
Triggers pptTriggers ppt
Triggers ppt
 
[JSS2015] - Document db et nosql
[JSS2015] - Document db et nosql[JSS2015] - Document db et nosql
[JSS2015] - Document db et nosql
 
Les bases fondamentales du langage transact sql
Les bases fondamentales du langage transact sqlLes bases fondamentales du langage transact sql
Les bases fondamentales du langage transact sql
 
TRIGGERS
TRIGGERSTRIGGERS
TRIGGERS
 
Indexing and hashing
Indexing and hashingIndexing and hashing
Indexing and hashing
 
Architecture of-dbms-and-data-independence
Architecture of-dbms-and-data-independenceArchitecture of-dbms-and-data-independence
Architecture of-dbms-and-data-independence
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
Relational Algebra-Database Systems
Relational Algebra-Database SystemsRelational Algebra-Database Systems
Relational Algebra-Database Systems
 
Database management system basic, database, database management, learn databa...
Database management system basic, database, database management, learn databa...Database management system basic, database, database management, learn databa...
Database management system basic, database, database management, learn databa...
 
Dbms architecture
Dbms architectureDbms architecture
Dbms architecture
 
PLM Introduction
PLM IntroductionPLM Introduction
PLM Introduction
 
Database language
Database languageDatabase language
Database language
 
Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS
 
Webinar Smile et Talend : Faites communiquer vos applications en temps réel
Webinar Smile et Talend  : Faites communiquer vos applications en temps réelWebinar Smile et Talend  : Faites communiquer vos applications en temps réel
Webinar Smile et Talend : Faites communiquer vos applications en temps réel
 
ERP Implementation Life Cycle
ERP Implementation Life CycleERP Implementation Life Cycle
ERP Implementation Life Cycle
 
DBMS - Normalization
DBMS - NormalizationDBMS - Normalization
DBMS - Normalization
 
Business process reengineering
Business process reengineeringBusiness process reengineering
Business process reengineering
 

Similar to Trigger

Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraintLearningTech
 
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
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQLVikash Sharma
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptxKhngNguyn81
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Thuan Nguyen
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Achmad Solichin
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11AnusAhmad
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql databaseKimera Richard
 
SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5jeetendra mandal
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueriesecomputernotes
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 

Similar to Trigger (20)

Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraint
 
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
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
lecture13.ppt
lecture13.pptlecture13.ppt
lecture13.ppt
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Les06
Les06Les06
Les06
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
 
Les06
Les06Les06
Les06
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql database
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5SQL interview questions jeetendra mandal - part 5
SQL interview questions jeetendra mandal - part 5
 
Sql transacation
Sql transacationSql transacation
Sql transacation
 
Triggers and active database
Triggers and active databaseTriggers and active database
Triggers and active database
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 

More from Slideshare

Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010Slideshare
 
Report generation
Report generationReport generation
Report generationSlideshare
 
Security in Relational model
Security in Relational modelSecurity in Relational model
Security in Relational modelSlideshare
 
Entity Relationship Model
Entity Relationship ModelEntity Relationship Model
Entity Relationship ModelSlideshare
 
Major issues in data mining
Major issues in data miningMajor issues in data mining
Major issues in data miningSlideshare
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingSlideshare
 
What is in you
What is in youWhat is in you
What is in youSlideshare
 
Propositional logic & inference
Propositional logic & inferencePropositional logic & inference
Propositional logic & inferenceSlideshare
 
Logical reasoning 21.1.13
Logical reasoning 21.1.13Logical reasoning 21.1.13
Logical reasoning 21.1.13Slideshare
 
Statistical learning
Statistical learningStatistical learning
Statistical learningSlideshare
 
Resolution(decision)
Resolution(decision)Resolution(decision)
Resolution(decision)Slideshare
 
Reinforcement learning 7313
Reinforcement learning 7313Reinforcement learning 7313
Reinforcement learning 7313Slideshare
 
Neural networks
Neural networksNeural networks
Neural networksSlideshare
 
Instance based learning
Instance based learningInstance based learning
Instance based learningSlideshare
 
Statistical learning
Statistical learningStatistical learning
Statistical learningSlideshare
 
Neural networks
Neural networksNeural networks
Neural networksSlideshare
 
Logical reasoning
Logical reasoning Logical reasoning
Logical reasoning Slideshare
 
Instance based learning
Instance based learningInstance based learning
Instance based learningSlideshare
 

More from Slideshare (20)

Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010Crystal report generation in visual studio 2010
Crystal report generation in visual studio 2010
 
Report generation
Report generationReport generation
Report generation
 
Security in Relational model
Security in Relational modelSecurity in Relational model
Security in Relational model
 
Entity Relationship Model
Entity Relationship ModelEntity Relationship Model
Entity Relationship Model
 
OLAP
OLAPOLAP
OLAP
 
Major issues in data mining
Major issues in data miningMajor issues in data mining
Major issues in data mining
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
What is in you
What is in youWhat is in you
What is in you
 
Propositional logic & inference
Propositional logic & inferencePropositional logic & inference
Propositional logic & inference
 
Logical reasoning 21.1.13
Logical reasoning 21.1.13Logical reasoning 21.1.13
Logical reasoning 21.1.13
 
Logic agent
Logic agentLogic agent
Logic agent
 
Statistical learning
Statistical learningStatistical learning
Statistical learning
 
Resolution(decision)
Resolution(decision)Resolution(decision)
Resolution(decision)
 
Reinforcement learning 7313
Reinforcement learning 7313Reinforcement learning 7313
Reinforcement learning 7313
 
Neural networks
Neural networksNeural networks
Neural networks
 
Instance based learning
Instance based learningInstance based learning
Instance based learning
 
Statistical learning
Statistical learningStatistical learning
Statistical learning
 
Neural networks
Neural networksNeural networks
Neural networks
 
Logical reasoning
Logical reasoning Logical reasoning
Logical reasoning
 
Instance based learning
Instance based learningInstance based learning
Instance based learning
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Recently uploaded (20)

LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

Trigger

  • 1. Trigger V. Saranya AP/CSE, Sri Vidya College of Engg & Tech, virudhunagar
  • 6. Triggers (Active database) • Three parts: – Event (activates the trigger) – Condition (tests whether the triggers should run) [Optional] – Action (what happens if the trigger runs) • Semantics: – When event occurs, and condition is satisfied, the action is performed.
  • 7. Triggers – Event,Condition,Action • Events could be : BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName> e.g.: BEFORE INSERT ON Professor • Condition is SQL expression or even an SQL query (query with non-empty result means TRUE) • Action can be many different choices : – SQL statements , even DDL and transactionoriented statements like “commit”.
  • 8. Example Trigger Assume our DB has a relation schema : salary) Professor (pNum, pName, We want to write a trigger that : Ensures that any new professor inserted has salary >= 60000
  • 9. Example Trigger Event CREATE TRIGGER minSalary “BEFORE INSERT” ON Professor for what context BEGIN ? Condition check for violation here ? END;
  • 10. Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN trigger is performed for each row inserted Violation of Minimum Professor Salary? END;
  • 11. Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; END;
  • 12. Example trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW DECLARE temp int; needed -- dummy variable not BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; temp := 10; variables END; -- to illustrate declared
  • 13. Details of Trigger Example • BEFORE INSERT ON Professor – This trigger is checked before the tuple is inserted • FOR EACH ROW – specifies that trigger is performed for each row inserted • :new – refers to the new tuple inserted • If (:new.salary < 60000) – then an application error is raised and hence the row is not inserted; otherwise the row is inserted. • Use error code: -20004; – this is in the valid range
  • 14. Condition Example Trigger Using Condition CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW WHEN (new.salary < 60000) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END; • Conditions can refer to old/new values of tuples modified by the statement activating the trigger.
  • 15. Triggers: REFERENCING CREATE TRIGGER minSalary BEFORE INSERT ON Professor REFERENCING NEW as newTuple FOR EACH ROW WHEN (newTuple.salary < 60000) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END;
  • 16. Example Trigger CREATE TRIGGER minSalary BEFORE UPDATE ON Professor REFERENCING OLD AS oldTuple NEW as newTuple FOR EACH ROW WHEN (newTuple.salary < oldTuple.salary) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Salary Decreasing !!’); END; • Ensure that salary does not decrease
  • 17. Another Trigger Example (SQL:99) CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18
  • 18. Defined by triggering transaction & level at which the trigger is executed Types of Triggers This section describes the different types of triggers: • Row level triggers – Trigger once for “each row” in a transaction. • Statement level triggers – Triggers execute once for “each transaction”. • Before and after triggers – Triggers can be executed immediately before and after INSERT, UPDATE and DELETE.
  • 19. Row vs Statement Level Trigger • Example: Consider a relation schema Account (num, amount) where we will allow creation of new accounts only during normal business hours.
  • 20. Example: Statement level trigger CREATE TRIGGER MYTRIG1 BEFORE INSERT ON Account FOR EACH STATEMENT --- is default BEGIN IF (TO_CHAR(SYSDATE,’dy’) IN (‘sat’,’sun’)) OR (TO_CHAR(SYSDATE,’hh24:mi’) NOT BETWEEN ’08:00’ AND ’17:00’) THEN RAISE_APPLICATION_ERROR(-20500,’Cannot create new account now !!’); END IF; END;
  • 21. When to use BEFORE/AFTER • Based on semantics. efficiency considerations or • Suppose we perform statement-level after insert, then all the rows are inserted first, then if the condition fails, and all the inserted rows must be “rolled back” • Not very efficient !!
  • 22. Combining multiple events into one trigger CREATE TRIGGER salaryRestrictions AFTER INSERT OR UPDATE ON Professor FOR EACH ROW BEGIN 1 IF (INSERTING AND :new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004, 'below min salary'); END IF; 2 IF (UPDATING AND :new.salary < :old.salary) THEN RAISE_APPLICATION_ERROR (-20004, ‘Salary Decreasing !!'); END IF; END;
  • 23. Summary : Trigger Syntax CREATE TRIGGER <triggerName> BEFORE|AFTER INSERT|DELETE|UPDATE [OF <columnList>] ON <tableName>|<viewName> [REFERENCING [OLD AS <oldName>] [NEW AS <newName>]] [FOR EACH ROW] (default is “FOR EACH STATEMENT”) [WHEN (<condition>)] <PSM body>;
  • 24. Some Points about Triggers • Check the system tables : – user_triggers – user_trigger_cols – user_errors • ORA-04091: mutating relation problem – In a row level trigger, you cannot have the body refer to the table specified in the event • Also INSTEAD OF triggers can be specified on views
  • 25. To Show Compilation Errors SELECT line, position, text FROM user_errors WHERE name = 'MY_TRIGGER' AND TYPE = 'TRIGGER‘ • In SQL*Plus, you can also use the following shortcut: “SQL> SHOW ERRORS TRIGGER MY_TRIGGER”
  • 26. Mutating Trigger “Trigger that triggers itself”
  • 27. Constraints versus Triggers • Constraints are useful for database consistency • Triggers are flexible and powerful • But can be hard to understand …… – More opportunity for optimization – Not restricted into insert/delete/update – – – – – Alerts Event logging for auditing Security enforcement Analysis of table accesses (statistics) Workflow and business intelligence … – Several triggers (Arbitrary order  unpredictable !?) – Chain triggers (When to stop ?) – Recursive triggers (Termination?)
  • 28. Purpose of Triggers      To To To To To generate data automatically enforce complex integrity constraints customize complex security authorization maintain replicate tables audit data modifications.