SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
Introduction to constraints and
           triggers
More on SQL

   Constraints
     Triggers
Integrity Constraints
   Constraint describes conditions that every legal instance of a
    relation must satisfy.
       Inserts/deletes/updates that violate ICs are disallowed.
       Can be used to :
         •   ensure application semantics (e.g., sid is a key), or
         •   prevent inconsistencies (e.g., sname has to be a string, age must be < 200)


   Types of IC’s:
     Fundamental:      Domain constraints, primary key constraints,
      foreign key constraints
     General constraints : Check Constraints, Table Constraints and
      Assertions.
Check or Table Constraints
      CREATE TABLE Sailors
           ( sid INTEGER,
           sname CHAR(10),
           rating INTEGER,
           age REAL,
           PRIMARY KEY (sid),
           CHECK ( rating >= 1
                  AND rating <= 10    ))


     Can use queries to express constraint.
Explicit Domain Constraints
CREATE DOMAIN values-of-ratings INTEGER
      DEFAULT 1
      CHECK ( VALUE >= 1 AND VALUE <= 10)



     CREATE TABLE Sailors
          ( sid INTEGER,
          sname CHAR(10),
          rating values-of-ratings,
          age REAL,
          PRIMARY KEY (sid))
More Powerful Table Constraints
   Constraint that Interlake boats cannot be reserved:

           CREATE TABLE   Reserves
                 ( sname CHAR(10),
                 bid INTEGER,
                 day DATE,
                 PRIMARY KEY (bid,day),
                 CONSTRAINT noInterlakeRes
                 CHECK (`Interlake’ <>
                              ( SELECT B.bname
                              FROM Boats B
                              WHERE B.bid= bid)))

       If condition evaluates to FALSE, update is rejected.
Table Constraints

   Associated with one table
   Only needs to hold TRUE when table is non-empty.
Table Constraints with Complex CHECK
     Number of boats plus number of sailors is < 100

       CREATE TABLE Sailors
             ( sid INTEGER,
             sname CHAR(10),
             rating INTEGER,
             age REAL,
             PRIMARY KEY (sid),
             CHECK
             ( (SELECT COUNT (S.sid) FROM Sailors S)
             + (SELECT COUNT (B.bid) FROM Boats B)
             < 100 )

    Symmetric constraint, yet associated with Sailors.
    If Sailors is empty, the number of Boats tuples can be anything!
Assertions
                     ( Constraints over Multiple
  Relations)
              CREATE TABLE Sailors        Number of boats
                    ( sid INTEGER,        plus number of
                    sname CHAR(10),       sailors is < 100
 ASSERTION         rating INTEGER,
                    age REAL,
  not               PRIMARY KEY (sid),
  associated        CHECK
                    ( (SELECT COUNT (S.sid) FROM Sailors S)
  with either       + (SELECT COUNT (B.bid) FROM Boats B) < 100 )
  table.
                         CREATE ASSERTION smallClub
                         CHECK
                         ( (SELECT COUNT (S.sid) FROM Sailors S)
                         + (SELECT COUNT (B.bid) FROM Boats B) < 100 )
Triggers
   Trigger: A procedure that starts automatically if
    specified changes occur to the DBMS

   Analog to a "daemon" that monitors a database for
    certain events to occur

   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.
                                                                       1
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 , body of PSM, and even DDL and
      transaction-oriented statements like “commit”.

                                                       1
Example Trigger

Assume our DB has a relation schema :

    Professor (pNum, pName, salary)

We want to write a trigger that :

  Ensures that any new professor inserted
     has salary >= 60000



                                            1
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor

       for what context   ?

BEGIN

       check for violation here ?


END;




                                                      1
Example Trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor

       FOR EACH ROW

BEGIN

         Violation of Minimum Professor Salary?

END;




                                                      1
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;




                                                      1
Example trigger
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
   FOR EACH ROW

DECLARE temp int;    -- dummy variable not needed

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

temp := 10;          -- to illustrate declared variables

END;
.
run;


                                                           1
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


                                                                     1
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;
.
run;

   Conditions can refer to old/new values of tuples modified by
    the statement activating the trigger.



                                                                   1
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;
.
run;

                                                      1
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;
.
run;

   Ensure that salary does not decrease

                                              2
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

                                                 2
Row vs Statement Level Trigger

   Row level: activated once per modified tuple
   Statement level: activate once per SQL statement


   Row level triggers can access new data, statement
    level triggers cannot always do that (depends on
    DBMS).

   Statement level triggers will be more efficient if we
    do not need to make row-specific decisions


                                                            2
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.




                                                   2
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;


                                                     2
When to use BEFORE/AFTER

   Based on efficiency considerations or semantics.

   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 !!



                                                       2
Combining multiple events into one
trigger
CREATE TRIGGER salaryRestrictions
AFTER INSERT OR UPDATE ON Professor
FOR EACH ROW
BEGIN
IF (INSERTING AND :new.salary < 60000) THEN
  RAISE_APPLICATION_ERROR (-20004, 'below min
  salary'); END IF;
IF (UPDATING AND :new.salary < :old.salary)
  THEN RAISE_APPLICATION_ERROR (-20004,
  ‘Salary Decreasing !!'); END IF;
END;


                                                2
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>;




                                                   2
Constraints versus Triggers
   Constraints are useful for database consistency
     Use IC when sufficient
     More opportunity for optimization
     Not restricted into insert/delete/update

   Triggers are flexible and powerful
       Alerters
       Event logging for auditing
       Security enforcement
       Analysis of table accesses (statistics)
       Workflow and business intelligence …

   But can be hard to understand ……
     Several triggers   (Arbitrary order  unpredictable !?)
     Chain triggers      (When to stop ?)
     Recursive triggers (Termination?)

                                                                2
Summary
   SQL allows specification of rich integrity
    constraints and their efficient maintenance

   Triggers respond to changes in the database:
    powerful for enforcing application semantics




                                                   2

Más contenido relacionado

Similar a SQL constraints and triggers intro

Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQLVikash Sharma
 
Oracle trigger
Oracle triggerOracle trigger
Oracle triggernasrul28
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)Ehtisham Ali
 
6 integrity and security
6 integrity and security6 integrity and security
6 integrity and securityDilip G R
 
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
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsmaxpane
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020DmitryLenev
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql databaseKimera Richard
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding GuidelinesChris Adkin
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstatsE Blake
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juniijaprr_editor
 

Similar a SQL constraints and triggers intro (20)

Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Oracle trigger
Oracle triggerOracle trigger
Oracle trigger
 
Less09 Data
Less09 DataLess09 Data
Less09 Data
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
6 integrity and security
6 integrity and security6 integrity and security
6 integrity and security
 
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
 
Triggers (1).pdf
Triggers (1).pdfTriggers (1).pdf
Triggers (1).pdf
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql database
 
SQL
SQLSQL
SQL
 
TSQL Coding Guidelines
TSQL Coding GuidelinesTSQL Coding Guidelines
TSQL Coding Guidelines
 
Transaction
TransactionTransaction
Transaction
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstats
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Les06
Les06Les06
Les06
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni
 

Más de LearningTech

Más de LearningTech (20)

vim
vimvim
vim
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 
Asp.net MVC DI
Asp.net MVC DIAsp.net MVC DI
Asp.net MVC DI
 

SQL constraints and triggers intro

  • 2. More on SQL  Constraints  Triggers
  • 3. Integrity Constraints  Constraint describes conditions that every legal instance of a relation must satisfy.  Inserts/deletes/updates that violate ICs are disallowed.  Can be used to : • ensure application semantics (e.g., sid is a key), or • prevent inconsistencies (e.g., sname has to be a string, age must be < 200)  Types of IC’s:  Fundamental: Domain constraints, primary key constraints, foreign key constraints  General constraints : Check Constraints, Table Constraints and Assertions.
  • 4. Check or Table Constraints CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ))  Can use queries to express constraint.
  • 5. Explicit Domain Constraints CREATE DOMAIN values-of-ratings INTEGER DEFAULT 1 CHECK ( VALUE >= 1 AND VALUE <= 10) CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating values-of-ratings, age REAL, PRIMARY KEY (sid))
  • 6. More Powerful Table Constraints  Constraint that Interlake boats cannot be reserved: CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid= bid)))  If condition evaluates to FALSE, update is rejected.
  • 7. Table Constraints  Associated with one table  Only needs to hold TRUE when table is non-empty.
  • 8. Table Constraints with Complex CHECK Number of boats plus number of sailors is < 100 CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )  Symmetric constraint, yet associated with Sailors.  If Sailors is empty, the number of Boats tuples can be anything!
  • 9. Assertions ( Constraints over Multiple Relations) CREATE TABLE Sailors Number of boats ( sid INTEGER, plus number of sname CHAR(10), sailors is < 100  ASSERTION rating INTEGER, age REAL, not PRIMARY KEY (sid), associated CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) with either + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) table. CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )
  • 10. Triggers  Trigger: A procedure that starts automatically if specified changes occur to the DBMS  Analog to a "daemon" that monitors a database for certain events to occur  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. 1
  • 11. 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 , body of PSM, and even DDL and transaction-oriented statements like “commit”. 1
  • 12. Example Trigger Assume our DB has a relation schema : Professor (pNum, pName, salary) We want to write a trigger that : Ensures that any new professor inserted has salary >= 60000 1
  • 13. Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor for what context ? BEGIN check for violation here ? END; 1
  • 14. Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN Violation of Minimum Professor Salary? END; 1
  • 15. 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; 1
  • 16. Example trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW DECLARE temp int; -- dummy variable not needed BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; temp := 10; -- to illustrate declared variables END; . run; 1
  • 17. 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 1
  • 18. 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; . run;  Conditions can refer to old/new values of tuples modified by the statement activating the trigger. 1
  • 19. 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; . run; 1
  • 20. 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; . run;  Ensure that salary does not decrease 2
  • 21. 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 2
  • 22. Row vs Statement Level Trigger  Row level: activated once per modified tuple  Statement level: activate once per SQL statement  Row level triggers can access new data, statement level triggers cannot always do that (depends on DBMS).  Statement level triggers will be more efficient if we do not need to make row-specific decisions 2
  • 23. 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. 2
  • 24. 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; 2
  • 25. When to use BEFORE/AFTER  Based on efficiency considerations or semantics.  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 !! 2
  • 26. Combining multiple events into one trigger CREATE TRIGGER salaryRestrictions AFTER INSERT OR UPDATE ON Professor FOR EACH ROW BEGIN IF (INSERTING AND :new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004, 'below min salary'); END IF; IF (UPDATING AND :new.salary < :old.salary) THEN RAISE_APPLICATION_ERROR (-20004, ‘Salary Decreasing !!'); END IF; END; 2
  • 27. 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>; 2
  • 28. Constraints versus Triggers  Constraints are useful for database consistency  Use IC when sufficient  More opportunity for optimization  Not restricted into insert/delete/update  Triggers are flexible and powerful  Alerters  Event logging for auditing  Security enforcement  Analysis of table accesses (statistics)  Workflow and business intelligence …  But can be hard to understand ……  Several triggers (Arbitrary order  unpredictable !?)  Chain triggers (When to stop ?)  Recursive triggers (Termination?) 2
  • 29. Summary  SQL allows specification of rich integrity constraints and their efficient maintenance  Triggers respond to changes in the database: powerful for enforcing application semantics 2

Notas del editor

  1. The slides for this text are organized into chapters. This lecture covers Chapter 5. This is one of the most important chapters in any discussion of database systems. Students must acquire a solid grasp of SQL. In particular, learning how to write queries in SQL is important, and comes only with practice. The slides present the concepts through examples. The chapter contains several additional examples with in-depth explanations; assign these as additional readings. The exercises contain numerous further examples, and come with supporting online material. If you need additional time to cover this material, consider abbreviating the earlier discussion of algebra and calculus, and reinforcing the same concepts in the context of SQL. Note that some new SQL:1999 features for the HAVING clause are covered in these slides. (This material is not covered in the 2 nd edition.) Also, material on cursors and other programmatic aspects of SQL has been moved to Chapter 6, following the revisions in the 3 rd edition.
  2. The slides for this text are organized into chapters. This lecture covers Chapter 5. This is one of the most important chapters in any discussion of database systems. Students must acquire a solid grasp of SQL. In particular, learning how to write queries in SQL is important, and comes only with practice. The slides present the concepts through examples. The chapter contains several additional examples with in-depth explanations; assign these as additional readings. The exercises contain numerous further examples, and come with supporting online material. If you need additional time to cover this material, consider abbreviating the earlier discussion of algebra and calculus, and reinforcing the same concepts in the context of SQL. Note that some new SQL:1999 features for the HAVING clause are covered in these slides. (This material is not covered in the 2 nd edition.) Also, material on cursors and other programmatic aspects of SQL has been moved to Chapter 6, following the revisions in the 3 rd edition.
  3. 5
  4. 8
  5. 8
  6. 8
  7. 8
  8. 9
  9. 9