SlideShare a Scribd company logo
SQL- Introduction to  advanced sql concepts
Introduction to AdvancedIntroduction to Advanced
SQL Concepts - CheckingSQL Concepts - Checking
of Constraintsof Constraints
Check ConstraintsCheck Constraints
• Limits values that may appear in components for
some attributes
• Expressed as either
o Constraint on attribute in definition of its relation’s schema
o Constraint on a tuple as a whole; part of relation schema, but not
associated with individual attributes
Attribute CheckAttribute Check
ConstraintConstraint
Simple Case:
• Assume in table Studio we have declaration:
presC# INT REFERENCES MovieExec(cert#) NOT NULL
• Cannot use set-null policy to fix referential int. violation
General Case:
• Attached to attribute declaration
• Keyword CHECK followed by any condition that could follow
WHERE clause in SQL query
o Checked whenever any tuple gets a new value for this attribute (incl.
on inserts of new tuples)
o Not checked when modification does not change the value of the
attribute to which CHECK belongs
ExampleExample
CREATE TABLE MovieStar (
…
gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)),
…
);
Condition being checked can be anything that could
follow WHERE in SFW query
ExampleExample
• Can the following attribute-based CHECK constraint
simulate a referential integrity constraint?
CREATE TABLE Studio (
Name CHAR(30) PRIMARY KEY,
Address VARCHAR(255),
presC# INT CHECK
(presC# IN (SELECT cert# FROM MovieExec));
• No, updates to MovieExec are invisible to the
above CHECK constraint
Tuple-Based CheckTuple-Based Check
ConstraintConstraint• Add a tuple-based CHECK constraint to MovieStar
schema that prevents the insertion of male stars
whose name begin with “Ms.”
o Checked after insertions and updates to tuples of the
relation on which it is defined
CREATE TABLE MovieStar (
Name CHAR(30) PRIMARY KEY,
Address VARCHAR(255),
Gender CHAR(1),
Birthdate DATE,
CHECK (gender <> ‘M’ OR name NOT LIKE ‘Ms.%’)
//forbid the insertion of tuples that satisfy multiple conditions,
namely “male and name starts with ‘Ms.’ ”
//equivalent to the OR of the negation of the same terms
AssertionsAssertions
• More powerful mechanism of constraining
values in database are part of database
schema
o First-class database citizens like views or relations
• Assertion is a boolean-valued SQL expression
that must be true at all times
o Easy to state for DB implementer, simply state
what must be true
o Harder to implement efficiently since DBMS must
deduce whether or not a given database
modification could affect truth of assertion
ExampleExample
• Express that no one can become president of
a studio unless net worth greater than $10M
MovieExec(name, address, cert#, netWorth)
Studio(name, address, presC#)
CREATE ASSERTION RichPres CHECK
(NOT EXISTS
(SELECT *
FROM Studio, MovieExec
WHERE presC# = cert# AND netWorth < 10000000)
)
);
• Can this be simulated with tuple-based CHECK
constraints?
Using a Tuple-BasedUsing a Tuple-Based
CHECKCHECKCREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES MovieExec(cert#),
CHECK (presc# NOT IN
(SELECT cert#
FROM MovieExec
WHERE netWorth < 10000000)
)
);
ExampleExample
• Assert that the total length of all movies by a given
studio shall not exceed 10,000 minutes
Movie(title,year,length,inColor,studioName,producerC#)
CREATE ASSERTION SumLength CHECK
(10000 >= ALL
(SELECT SUM(length)FROM Movie
GROUP BY StudioName));
 Is the effect the same as that of the following tuple-based CHECK:
CHECK (10000 >= ALL
(SELECT SUM(length) FROM Movie
GROUP BY studioName));
TriggersTriggers
• Aka “event-condition-action” (ECA) rules
• Three important facts about triggers
o Only awakened when certain events, specified by db
programmer, occur
o Executing triggers involves testing a condition first
o If condition satisfied, action of trigger is executed
ExampleExample• Write trigger to prevent any attempt to lower networth of movie exec
MovieExec(name,address,cert#,netWorth)
CREATE TRIGGER NetWorthTrigger
AFTER UPDATE OF netWorth ON MovieExec
REFERENCING
OLD ROW AS OldTuple,
NEW ROW AS NewTuple,
FOR EACH ROW
WHEN (OldTuple.netWorth > NewTuple.netWorth)
UPDATE MovieExec
SET netWorth = OldTuple.netWorth
WHERE cert# = NewTuple.cert#;
Event
Condition
Action
CommentsComments
• The action rule may be executed BEFORE or AFTER the event
o If before, when clause is tested before triggering event
• Besides update, other triggering events are insert and delete
• When clause is optional
• The action may contain any number of SQL statements,
separated by BEGIN … END
• If triggering event is insert, may use a NEW ROW AS clause to
give name to inserted row
o Conversely, may use OLD ROW AS in case of a deletion
More CommentsMore Comments
• If we omit FOR EACH ROW clause, trigger becomes
statement-level trigger (as opposed to row-level trigger)
• Statement-level trigger is executed ONCE no matter how
many rows it actually effects
o Cannot refer to old and new tuples
• However, both types of triggers can access old and new set
of tuples
o OLD TABLE AS … (i.e., deleted tuples or old versions of
updated tuples)
o NEW TABLE AS … (i.e., inserted tuples or new versions of
updated tuples)
ExampleExample
• Prevent average net worth of movie executives to drop below $500K
• Violation on insert, update, delete => need three triggers!
MovieExec(name,address,cert#,netWorth)
CREATE TRIGGER AvgNetWorthTrigger
AFTER UPDATE OF netWorth ON MovieExec
REFERENCING
OLD TABLE AS OldStuff,
NEW TABLE AS NewStuff
FOR EACH STATEMENT
WHEN (500000 > (SELECT AVG(netWorth) FROM MovieExec))
BEGIN
DELETE FROM MovieExec
WHERE (name,address,cert#,netWorth) IN NewStuff;
INSERT INTO MovieExec
(SELECT * FROM OldStuff);
END;
ThankThank You !!!You !!!
For More Information click below link:
Follow Us on:
http://vibranttechnologies.co.in/sql-classes-in-mumbai.html

More Related Content

What's hot (15)

PDF
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
Andrzej Jóźwiak
 
PPTX
TestNG vs Junit
Büşra İçöz
 
PPTX
Introduction to triggers
Syed Awais Mazhar Bukhari
 
PPTX
Unit testing presentation
Arthur Freyman
 
PPTX
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
PPTX
Effective Readable unit testing with junit5
Sajith Vijesekara
 
PPT
Unit testing with Spock Framework
Eugene Dvorkin
 
PPTX
Automation patterns on practice
automated-testing.info
 
PPT
Mxunit
VIkas Patel
 
PPTX
TestNG with selenium
Gousalya Ramachandran
 
PDF
Scala test
Inphina Technologies
 
PDF
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
PPTX
TestNG Session presented in Xebia XKE
Abhishek Yadav
 
PDF
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
istefo
 
PDF
Anatomy of a Gem: Bane
Daniel Wellman
 
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
Andrzej Jóźwiak
 
TestNG vs Junit
Büşra İçöz
 
Introduction to triggers
Syed Awais Mazhar Bukhari
 
Unit testing presentation
Arthur Freyman
 
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
Effective Readable unit testing with junit5
Sajith Vijesekara
 
Unit testing with Spock Framework
Eugene Dvorkin
 
Automation patterns on practice
automated-testing.info
 
Mxunit
VIkas Patel
 
TestNG with selenium
Gousalya Ramachandran
 
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
TestNG Session presented in Xebia XKE
Abhishek Yadav
 
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
istefo
 
Anatomy of a Gem: Bane
Daniel Wellman
 

Viewers also liked (17)

PDF
Oracle Query Tuning Tips - Get it Right the First Time
Dean Richards
 
PPTX
Really using Oracle analytic SQL functions
Kim Berg Hansen
 
PDF
wallplate layout
april webb
 
DOCX
Inicializar windows 8
Alex Souzza
 
PDF
Grafico semanal del ibex 35 para el 11 05 2012
Experiencia Trading
 
PPT
Scribd
Alvaro Analuiza
 
PPTX
Case Study - Windows Azure
msgtscindia
 
PDF
Exposicion competencias
dckyam
 
PDF
Lo malo competencias
dckyam
 
PPTX
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
Microsoft Private Cloud
 
PPT
Business Strategy - Blue Ocean Strategy
Deepak Agrawal
 
PDF
Lg e510 series batería at www baterias-portatil-es (1)
batteryes
 
PPSX
Analytic & Windowing functions in oracle
Logan Palanisamy
 
PPT
Building Applications for SQL Server 2008
Dave Bost
 
PDF
Remote DBA Experts SQL Server 2008 New Features
Remote DBA Experts
 
PPT
Amy Carmichael, Lady Christian missionary in Indian Christian Missionary in ...
deepa karthik
 
PPTX
Tecnologias na escola: hábitos, oportunidades e riscos
UFPE
 
Oracle Query Tuning Tips - Get it Right the First Time
Dean Richards
 
Really using Oracle analytic SQL functions
Kim Berg Hansen
 
wallplate layout
april webb
 
Inicializar windows 8
Alex Souzza
 
Grafico semanal del ibex 35 para el 11 05 2012
Experiencia Trading
 
Case Study - Windows Azure
msgtscindia
 
Exposicion competencias
dckyam
 
Lo malo competencias
dckyam
 
SQL Server 2008 R2 - Developing Rich Reporting Solutions Presentation
Microsoft Private Cloud
 
Business Strategy - Blue Ocean Strategy
Deepak Agrawal
 
Lg e510 series batería at www baterias-portatil-es (1)
batteryes
 
Analytic & Windowing functions in oracle
Logan Palanisamy
 
Building Applications for SQL Server 2008
Dave Bost
 
Remote DBA Experts SQL Server 2008 New Features
Remote DBA Experts
 
Amy Carmichael, Lady Christian missionary in Indian Christian Missionary in ...
deepa karthik
 
Tecnologias na escola: hábitos, oportunidades e riscos
UFPE
 
Ad

Similar to SQL- Introduction to advanced sql concepts (20)

PPT
06.ConstraintTrigger (1).ppt
saikumar580678
 
PDF
Triggers and active database
BalaMuruganSamuthira
 
PDF
[Www.pkbulk.blogspot.com]dbms11
AnusAhmad
 
PPT
Intro to trigger and constraint
LearningTech
 
PPTX
Advanced Topics on Database - Unit-3 AU17
LOGANATHANK24
 
PDF
Database management system important topic.pdf
amariyarana
 
PPT
Data integrity
Rahul Gupta
 
PDF
Oaktable World 2014 Toon Koppelaars: database constraints polite excuse
Kyle Hailey
 
PPT
6 integrity and security
Dilip G R
 
DOC
129471717 unit-v
homeworkping8
 
PPTX
Multimedia Databases Concepts: Managing images, video, audio and beyond
COSMOS58
 
PPT
2e data models
Bibin Devadas
 
PPTX
Triggers.PPTX
ansariparveen06
 
PPT
6. Integrity and Security in DBMS
koolkampus
 
PPTX
Sql server ___________session_19(triggers)
Ehtisham Ali
 
PDF
RDBMS
NIVEETHITHAS
 
PPTX
Unit 4
Abha Damani
 
PPTX
Integrity Constraints explain everything in it
MUHAMMADANSAR76
 
PPTX
Relational Database Management System part II
KavithaA19
 
PDF
1.Implementing_Data_Integrity.pdf
diaa46
 
06.ConstraintTrigger (1).ppt
saikumar580678
 
Triggers and active database
BalaMuruganSamuthira
 
[Www.pkbulk.blogspot.com]dbms11
AnusAhmad
 
Intro to trigger and constraint
LearningTech
 
Advanced Topics on Database - Unit-3 AU17
LOGANATHANK24
 
Database management system important topic.pdf
amariyarana
 
Data integrity
Rahul Gupta
 
Oaktable World 2014 Toon Koppelaars: database constraints polite excuse
Kyle Hailey
 
6 integrity and security
Dilip G R
 
129471717 unit-v
homeworkping8
 
Multimedia Databases Concepts: Managing images, video, audio and beyond
COSMOS58
 
2e data models
Bibin Devadas
 
Triggers.PPTX
ansariparveen06
 
6. Integrity and Security in DBMS
koolkampus
 
Sql server ___________session_19(triggers)
Ehtisham Ali
 
Unit 4
Abha Damani
 
Integrity Constraints explain everything in it
MUHAMMADANSAR76
 
Relational Database Management System part II
KavithaA19
 
1.Implementing_Data_Integrity.pdf
diaa46
 
Ad

More from Vibrant Technologies & Computers (20)

PPT
Buisness analyst business analysis overview ppt 5
Vibrant Technologies & Computers
 
PPT
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
PPT
SQL- Introduction to MySQL
Vibrant Technologies & Computers
 
PPT
SQL- Introduction to SQL database
Vibrant Technologies & Computers
 
PPT
ITIL - introduction to ITIL
Vibrant Technologies & Computers
 
PPT
Salesforce - Introduction to Security & Access
Vibrant Technologies & Computers
 
PPT
Data ware housing- Introduction to olap .
Vibrant Technologies & Computers
 
PPT
Data ware housing - Introduction to data ware housing process.
Vibrant Technologies & Computers
 
PPT
Data ware housing- Introduction to data ware housing
Vibrant Technologies & Computers
 
PPT
Salesforce - classification of cloud computing
Vibrant Technologies & Computers
 
PPT
Salesforce - cloud computing fundamental
Vibrant Technologies & Computers
 
PPT
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
PPT
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
PPT
SQL- Introduction to SQL Set Operations
Vibrant Technologies & Computers
 
PPT
Sas - Introduction to designing the data mart
Vibrant Technologies & Computers
 
PPT
Sas - Introduction to working under change management
Vibrant Technologies & Computers
 
PPT
SAS - overview of SAS
Vibrant Technologies & Computers
 
PPT
Teradata - Architecture of Teradata
Vibrant Technologies & Computers
 
PPT
Teradata - Restoring Data
Vibrant Technologies & Computers
 
PPT
Datastage database design and data modeling ppt 4
Vibrant Technologies & Computers
 
Buisness analyst business analysis overview ppt 5
Vibrant Technologies & Computers
 
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
SQL- Introduction to MySQL
Vibrant Technologies & Computers
 
SQL- Introduction to SQL database
Vibrant Technologies & Computers
 
ITIL - introduction to ITIL
Vibrant Technologies & Computers
 
Salesforce - Introduction to Security & Access
Vibrant Technologies & Computers
 
Data ware housing- Introduction to olap .
Vibrant Technologies & Computers
 
Data ware housing - Introduction to data ware housing process.
Vibrant Technologies & Computers
 
Data ware housing- Introduction to data ware housing
Vibrant Technologies & Computers
 
Salesforce - classification of cloud computing
Vibrant Technologies & Computers
 
Salesforce - cloud computing fundamental
Vibrant Technologies & Computers
 
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
SQL- Introduction to SQL Set Operations
Vibrant Technologies & Computers
 
Sas - Introduction to designing the data mart
Vibrant Technologies & Computers
 
Sas - Introduction to working under change management
Vibrant Technologies & Computers
 
SAS - overview of SAS
Vibrant Technologies & Computers
 
Teradata - Architecture of Teradata
Vibrant Technologies & Computers
 
Teradata - Restoring Data
Vibrant Technologies & Computers
 
Datastage database design and data modeling ppt 4
Vibrant Technologies & Computers
 

Recently uploaded (20)

PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Digital Circuits, important subject in CS
contactparinay1
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 

SQL- Introduction to advanced sql concepts

  • 2. Introduction to AdvancedIntroduction to Advanced SQL Concepts - CheckingSQL Concepts - Checking of Constraintsof Constraints
  • 3. Check ConstraintsCheck Constraints • Limits values that may appear in components for some attributes • Expressed as either o Constraint on attribute in definition of its relation’s schema o Constraint on a tuple as a whole; part of relation schema, but not associated with individual attributes
  • 4. Attribute CheckAttribute Check ConstraintConstraint Simple Case: • Assume in table Studio we have declaration: presC# INT REFERENCES MovieExec(cert#) NOT NULL • Cannot use set-null policy to fix referential int. violation General Case: • Attached to attribute declaration • Keyword CHECK followed by any condition that could follow WHERE clause in SQL query o Checked whenever any tuple gets a new value for this attribute (incl. on inserts of new tuples) o Not checked when modification does not change the value of the attribute to which CHECK belongs
  • 5. ExampleExample CREATE TABLE MovieStar ( … gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)), … ); Condition being checked can be anything that could follow WHERE in SFW query
  • 6. ExampleExample • Can the following attribute-based CHECK constraint simulate a referential integrity constraint? CREATE TABLE Studio ( Name CHAR(30) PRIMARY KEY, Address VARCHAR(255), presC# INT CHECK (presC# IN (SELECT cert# FROM MovieExec)); • No, updates to MovieExec are invisible to the above CHECK constraint
  • 7. Tuple-Based CheckTuple-Based Check ConstraintConstraint• Add a tuple-based CHECK constraint to MovieStar schema that prevents the insertion of male stars whose name begin with “Ms.” o Checked after insertions and updates to tuples of the relation on which it is defined CREATE TABLE MovieStar ( Name CHAR(30) PRIMARY KEY, Address VARCHAR(255), Gender CHAR(1), Birthdate DATE, CHECK (gender <> ‘M’ OR name NOT LIKE ‘Ms.%’) //forbid the insertion of tuples that satisfy multiple conditions, namely “male and name starts with ‘Ms.’ ” //equivalent to the OR of the negation of the same terms
  • 8. AssertionsAssertions • More powerful mechanism of constraining values in database are part of database schema o First-class database citizens like views or relations • Assertion is a boolean-valued SQL expression that must be true at all times o Easy to state for DB implementer, simply state what must be true o Harder to implement efficiently since DBMS must deduce whether or not a given database modification could affect truth of assertion
  • 9. ExampleExample • Express that no one can become president of a studio unless net worth greater than $10M MovieExec(name, address, cert#, netWorth) Studio(name, address, presC#) CREATE ASSERTION RichPres CHECK (NOT EXISTS (SELECT * FROM Studio, MovieExec WHERE presC# = cert# AND netWorth < 10000000) ) ); • Can this be simulated with tuple-based CHECK constraints?
  • 10. Using a Tuple-BasedUsing a Tuple-Based CHECKCHECKCREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# INT REFERENCES MovieExec(cert#), CHECK (presc# NOT IN (SELECT cert# FROM MovieExec WHERE netWorth < 10000000) ) );
  • 11. ExampleExample • Assert that the total length of all movies by a given studio shall not exceed 10,000 minutes Movie(title,year,length,inColor,studioName,producerC#) CREATE ASSERTION SumLength CHECK (10000 >= ALL (SELECT SUM(length)FROM Movie GROUP BY StudioName));  Is the effect the same as that of the following tuple-based CHECK: CHECK (10000 >= ALL (SELECT SUM(length) FROM Movie GROUP BY studioName));
  • 12. TriggersTriggers • Aka “event-condition-action” (ECA) rules • Three important facts about triggers o Only awakened when certain events, specified by db programmer, occur o Executing triggers involves testing a condition first o If condition satisfied, action of trigger is executed
  • 13. ExampleExample• Write trigger to prevent any attempt to lower networth of movie exec MovieExec(name,address,cert#,netWorth) CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD ROW AS OldTuple, NEW ROW AS NewTuple, FOR EACH ROW WHEN (OldTuple.netWorth > NewTuple.netWorth) UPDATE MovieExec SET netWorth = OldTuple.netWorth WHERE cert# = NewTuple.cert#; Event Condition Action
  • 14. CommentsComments • The action rule may be executed BEFORE or AFTER the event o If before, when clause is tested before triggering event • Besides update, other triggering events are insert and delete • When clause is optional • The action may contain any number of SQL statements, separated by BEGIN … END • If triggering event is insert, may use a NEW ROW AS clause to give name to inserted row o Conversely, may use OLD ROW AS in case of a deletion
  • 15. More CommentsMore Comments • If we omit FOR EACH ROW clause, trigger becomes statement-level trigger (as opposed to row-level trigger) • Statement-level trigger is executed ONCE no matter how many rows it actually effects o Cannot refer to old and new tuples • However, both types of triggers can access old and new set of tuples o OLD TABLE AS … (i.e., deleted tuples or old versions of updated tuples) o NEW TABLE AS … (i.e., inserted tuples or new versions of updated tuples)
  • 16. ExampleExample • Prevent average net worth of movie executives to drop below $500K • Violation on insert, update, delete => need three triggers! MovieExec(name,address,cert#,netWorth) CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (500000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (name,address,cert#,netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END;
  • 17. ThankThank You !!!You !!! For More Information click below link: Follow Us on: http://vibranttechnologies.co.in/sql-classes-in-mumbai.html