SlideShare ist ein Scribd-Unternehmen logo
1 von 67
Downloaden Sie, um offline zu lesen
SQL – deel 2



Katrien Verbert
katrien.verbert@cs.kuleuven.be
inhoud

•    views
•    algemene restricties
•    triggers
•    extra voorbeeld
•    quantoren in relationele calculus




                                         2
views in SQL

•  “view" = afgeleide relatie
   –  tupels worden niet expliciet opgeslagen
   –  maar worden berekend uit andere relaties (= de definiërende
      tabellen van de view)




                                                                    3
specificeren van een view
•  sytax
       CREATE VIEW     <viewname> [ < lijst van attribuutnamen> ]
       AS              <query>
  V1

            CREATE VIEW       WORKS_ON1 
            AS   SELECT       Fname, Lname, Pname, Hours 
                  FROM        EMPLOYEE, PROJECT, WORKS_ON 
                  WHERE       Ssn = Essn  AND  Pno = Pnumber ;

     CREATE VIEW          DEPT_INFO(Dept_name,No_of_emps,Total_sal) 
     AS   SELECT          Dname, COUNT(*), SUM(Salary) 
           FROM           DEPARTMENT, EMPLOYEE 
           WHERE          Dnumber = Dno 
           GROUP BY       Dname ;


                                                                       4
gebruik van views

•  queries op view: zoals bij gewone tabellen

              SELECT  Fname, Lname 
              FROM  WORKS_ON1 
              WHERE  Pname = ‘ProductX’ ; 

•  Voordelen van views?
   •  eenvoudiger formulering van queries
   •  beveiligingsmechanisme
       •  gebruiker zicht op deel van gegevensbank geven
   •  vs. nieuwe tabel (cf. DEPT_INFO):
       •  geen redundantie
       •  steeds up-to-date

                                                           5
weglaten van view

•  DROP VIEW (cf. gewone tabel)
   –  voorbeeld:


          DROP VIEW       WORKS_ON1; 




   –  geen verwijdering van tupels




                                        6
implementatie van views

•  twee benaderingen:
   –  query modification:
       •  query op view wordt omgevormd tot query op onderliggende tabellen;
       •  nadeel: kan tot complexe en tijdsintensieve queries leiden
   –  view materialization:
       •  tijdelijke creatie van de afgeleide (view) tabel wanneer ze voor het eerst in
          een query gebruikt wordt;
       •  vereist ‘incremental update’: aanpassing van de afgeleide tabel wanneer
          basistabellen gewijzigd worden;
       •  afgeleide tabel wordt automatisch weggelaten als ze een tijd niet meer
          gebruikt wordt




                                                                                          7
voorbeeld van query modification

  –  de query QV1 op view WORKS_ON1


         SELECT  Fname, Lname 
         FROM  WORKS_ON1 
         WHERE  Pname = ‘ProductX’ ; 

  –  wordt omgevormd tot


     SELECT  Fname, Lname 
     FROM  EMPLOYEE, PROJECT, WORKS_ON 
     WHERE  Ssn = Essn  AND  Pno = Pnumber  
                     AND  Pname = ‘ProductX’ ; 


                                                  8
wijzigen van view

•  view is afgeleid uit andere relaties
•  ⇒ wijziging moet doorgegeven worden aan andere relaties
•  niet steeds mogelijk op eenduidige manier!




                                                         9
wijzigen van view

•  View ← 1 basisrelatie:
   –  aanpassing aan view → aanpassing aan basisrelatie
•  View ← join van meerdere basisrelaties:
   –  welke relaties aanpassen?




                                                          10
voorbeeld

•  Wijzig PNAME van John Smith in WORKS_ON1 van 'ProductX'
   naar 'ProductY’

             UPDATE      WORKS_ON1 
             SET         Pname = 'ProductY' 
             WHERE       Lname = 'Smith' AND Fname = 'John' 
                         AND Pname = 'ProductX’ ; 



•  Hoe de wijziging van productnaam doorgeven aan basisrelaties?
    –  Is het project van naam veranderd?
    –  Of werkt John Smith nu aan een ander project, nl. ProductY
       i.p.v. ProductX ?


                                                                    11
UPDATE            PROJECT 
   SET               Pname = 'ProductY' 
   WHERE             Pname = 'ProductX’ ;

   UPDATE            WORKS_ON 
   SET               Pno =  (SELECT Pnumber FROM PROJECT  
                            WHERE Name = 'ProductY') 
   WHERE             Essn =       (SELECT Ssn FROM EMPLOYEE 
                                  WHERE Lname = 'Smith' AND Fname = 'John') 
                     AND 
                     PNO IN       (SELECT Pnumber FROM PROJECT 
                                  WHERE Pname = 'ProductX') ; 

sommige aanpassingen zijn zinloos:

   UPDATE            DEPT_INFO 
   SET               TOTAL_SAL=100000 
   WHERE             DNAME='Research’ ;
                                                                               12
wijzigen van views: algemeen

•  een view afgeleid uit 1 tabel kan aangepast worden als
   de view een primaire sleutel of kandidaatsleutel van die
   tabel bevat (→ te wijzigen tupel is eenduidig bepaald)
•  een view afgeleid uit meerdere tabellen is meestal niet
   aanpasbaar
   –  indien meerdere aanpassingen mogelijk zijn, moet er een
      procedure zijn om hieruit te kiezen, b.v.:
      •  gebruiker vragen een keuze te maken
   –  DBMS meest waarschijnlijke laten kiezen
•  resultaten van aggregaatfuncties kunnen niet
   aangepast worden


                                                                13
ASSERTIONS
ter herinnering

•  restricties op tabellen
•  restricties op attribuutwaarden




                                     15
restricties op tabellen

•  primaire sleutel:         PRIMARY KEY <attrlist>
•  alternatieve sleutel:     UNIQUE <attrlist>

          worden nagekeken bij toevoegen of wijzigen van tupels


•  verwijssleutel: FOREIGN KEY <attrlist> REFERENCES <table><attrlist>

         wordt nagekeken bij toevoegen of wijzigen van tupels in tabel
         wordt nagekeken bij verwijderen of wijzigen van tupels in verwijzende tabel




                                                                                        16
referentiële integriteit

•    Dno in EMPLOYEE verwijst altijd naar een bestaand
     dnumber in DEPARTMENT



              foreign key                    primary key
18
referentiële integriteit

•    Dno in EMPLOYEE verwijst altijd naar een bestaand
     dnumber in DEPARTMENT



              foreign key                    primary key



                        6                6
                        6
restricties op attribuut
•  NOT NULL (automatisch voor primaire sleutels)
•  DEFAULT <value>
•  CHECK (voorwaarde)


Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21); 



   worden nagekeken bij toevoegen of wijzigen van attribuutwaarden




                                                                 20
algemene restricties specificeren
•  andere restricties dan sleutel-, entiteits- en referentiële
   restricties opgeven: ASSERTION

•  algemene vorm:

            CREATE ASSERTION <name> CHECK <cond> 




                                                                 21
voorbeeld
–  salaris van werknemer <= salaris van manager van dept.
   waarvoor werknemer werkt



        CREATE ASSERTION                     SALARY_CONSTRAINT 
        CHECK   ( NOT EXISTS                  
                                ( SELECT     * 
                                  FROM       EMPLOYEE  E,  EMPLOYEE  M, 
                                             DEPARTMENT  D 
                                  WHERE      E.Salary > M.Salary 
                                             AND   E.Dno = D.Dnumber 
                                             AND   D.Mgr_ssn = M.Ssn) ) ;




                                                                             22
werking
•  bij creatie van een ASSERTION, wordt gecontroleerd of eraan voldaan is
•  elke latere wijziging in de gegevensbank:
   –  slechts toegelaten indien aan de ASSERTION voldaan is
   –  dit kan veel extra werk vereisen!


•  Voorbeeld: er moeten minstens drie werknemers per afdeling zijn.


    CREATE ASSERTION NIET_MINDER_DAN_3 AS 
    CHECK (NOT EXISTS (SELECT e1.DNO 
                FROM (SELECT DISTINCT DNO FROM EMPLOYEE e1 
                           WHERE 3 > (SELECT count(*) 
                                         FROM EMPLOYEE e2 
                                         WHERE e2.DNO = e1.DNO))); 

                                                                      23
CHECK-clausule

•  kan ook bij
   –  attribuut - definitie
   –  CREATE DOMAIN gebruikt worden
•  → domeinrestricties
•  voorbeeld:
   –  departementsnummer kan slechts een gehele waarde tussen 1
      en 20 zijn:




  DNUMBER INT NOT NULL CHECK (DNUMBER > 0 AND 
  DNUMBER < 21); 
  CREATE DOMAIN D_NUM AS INTEGER 
  CHECK         (D_NUM > 0 AND D_NUM < 21) ;                  24
•  CHECK
  –  wordt slechts gecontroleerd bij toevoegen of aanpassen van tupels,
     slaat op attributen of tupels
  –  kan dus efficiënter geïmplementeerd worden
•  ASSERTION
  –  is meer algemeen




                                                                 25
andere mogelijkheden

•  CREATE TRIGGER

•  hierbij wordt de te nemen actie opgegeven wanneer niet
   aan de voorwaarde voldaan is




                                                       26
TRIGGERS
triggers
•  een trigger bestaat uit 3 delen:
   •  een event (bv. update van een attribuut)
   •  een voorwaarde (bv. een query die nagekeken wordt)
   •  een actie (delete, update, insert)


•  syntax

        CREATE TRIGGER <name> 
        { BEFORE | AFTER } <event> ON <table>  
        FOR EACH ROW 
        WHEN (<cond>) 
            <acaon> 


                                                           28
voorbeeld

    CREATE TRIGGER TotalSal1 
    AFTER INSERT ON EMPLOYEE  
    FOR EACH ROW 
    WHEN (NEW.DNO IS NOT NULL) 
       UPDATE DEPARTMENT 
       SET TOTAL_SAL=TOTAL_SAL + NEW.SALARY 
       WHERE DNO=NEW.DNO 




                                               29
elementen van triggers

•  timing van uitvoering van de actie
   –  before
   –  after
   –  instead of


•  actie kan verwijzen naar oude of nieuwe toestand van
   de gegevensbank

•  conditie wordt gespecificeerd in WHEN clausule




                                                          30
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2
SQL deel 2

Weitere ähnliche Inhalte

Mehr von Katrien Verbert

Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Katrien Verbert
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Katrien Verbert
 
Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Katrien Verbert
 
Explaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveExplaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveKatrien Verbert
 
Explaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedExplaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedKatrien Verbert
 
Designing Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedDesigning Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedKatrien Verbert
 
Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Katrien Verbert
 
Explainable AI for non-expert users
Explainable AI for non-expert usersExplainable AI for non-expert users
Explainable AI for non-expert usersKatrien Verbert
 
Towards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsTowards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsKatrien Verbert
 
Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Katrien Verbert
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Katrien Verbert
 
Learning analytics for feedback at scale
Learning analytics for feedback at scaleLearning analytics for feedback at scale
Learning analytics for feedback at scaleKatrien Verbert
 
Interactive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningInteractive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningKatrien Verbert
 
Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Katrien Verbert
 
Interactive Recommender Systems
Interactive Recommender SystemsInteractive Recommender Systems
Interactive Recommender SystemsKatrien Verbert
 
Web Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLWeb Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLKatrien Verbert
 
Information Visualisation: perception and principles
Information Visualisation: perception and principlesInformation Visualisation: perception and principles
Information Visualisation: perception and principlesKatrien Verbert
 
Web Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionWeb Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionKatrien Verbert
 
Information Visualisation: Introduction
Information Visualisation: IntroductionInformation Visualisation: Introduction
Information Visualisation: IntroductionKatrien Verbert
 

Mehr von Katrien Verbert (20)

Explainability methods
Explainability methodsExplainability methods
Explainability methods
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?Human-centered AI: how can we support end-users to interact with AI?
Human-centered AI: how can we support end-users to interact with AI?
 
Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?Human-centered AI: how can we support lay users to understand AI?
Human-centered AI: how can we support lay users to understand AI?
 
Explaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspectiveExplaining job recommendations: a human-centred perspective
Explaining job recommendations: a human-centred perspective
 
Explaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learnedExplaining recommendations: design implications and lessons learned
Explaining recommendations: design implications and lessons learned
 
Designing Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons LearnedDesigning Learning Analytics Dashboards: Lessons Learned
Designing Learning Analytics Dashboards: Lessons Learned
 
Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...Human-centered AI: towards the next generation of interactive and adaptive ex...
Human-centered AI: towards the next generation of interactive and adaptive ex...
 
Explainable AI for non-expert users
Explainable AI for non-expert usersExplainable AI for non-expert users
Explainable AI for non-expert users
 
Towards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methodsTowards the next generation of interactive and adaptive explanation methods
Towards the next generation of interactive and adaptive explanation methods
 
Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...Personalized food recommendations: combining recommendation, visualization an...
Personalized food recommendations: combining recommendation, visualization an...
 
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
Explaining and Exploring Job Recommendations: a User-driven Approach for Inte...
 
Learning analytics for feedback at scale
Learning analytics for feedback at scaleLearning analytics for feedback at scale
Learning analytics for feedback at scale
 
Interactive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learningInteractive recommender systems and dashboards for learning
Interactive recommender systems and dashboards for learning
 
Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”Interactive recommender systems: opening up the “black box”
Interactive recommender systems: opening up the “black box”
 
Interactive Recommender Systems
Interactive Recommender SystemsInteractive Recommender Systems
Interactive Recommender Systems
 
Web Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTMLWeb Information Systems Lecture 2: HTML
Web Information Systems Lecture 2: HTML
 
Information Visualisation: perception and principles
Information Visualisation: perception and principlesInformation Visualisation: perception and principles
Information Visualisation: perception and principles
 
Web Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: IntroductionWeb Information Systems Lecture 1: Introduction
Web Information Systems Lecture 1: Introduction
 
Information Visualisation: Introduction
Information Visualisation: IntroductionInformation Visualisation: Introduction
Information Visualisation: Introduction
 

SQL deel 2

  • 1. SQL – deel 2 Katrien Verbert katrien.verbert@cs.kuleuven.be
  • 2. inhoud •  views •  algemene restricties •  triggers •  extra voorbeeld •  quantoren in relationele calculus 2
  • 3. views in SQL •  “view" = afgeleide relatie –  tupels worden niet expliciet opgeslagen –  maar worden berekend uit andere relaties (= de definiërende tabellen van de view) 3
  • 4. specificeren van een view •  sytax CREATE VIEW <viewname> [ < lijst van attribuutnamen> ] AS <query> V1 CREATE VIEW   WORKS_ON1  AS   SELECT   Fname, Lname, Pname, Hours       FROM   EMPLOYEE, PROJECT, WORKS_ON       WHERE   Ssn = Essn  AND  Pno = Pnumber ; CREATE VIEW      DEPT_INFO(Dept_name,No_of_emps,Total_sal)  AS   SELECT      Dname, COUNT(*), SUM(Salary)       FROM      DEPARTMENT, EMPLOYEE       WHERE      Dnumber = Dno       GROUP BY       Dname ; 4
  • 5. gebruik van views •  queries op view: zoals bij gewone tabellen SELECT  Fname, Lname  FROM  WORKS_ON1  WHERE  Pname = ‘ProductX’ ;  •  Voordelen van views? •  eenvoudiger formulering van queries •  beveiligingsmechanisme •  gebruiker zicht op deel van gegevensbank geven •  vs. nieuwe tabel (cf. DEPT_INFO): •  geen redundantie •  steeds up-to-date 5
  • 6. weglaten van view •  DROP VIEW (cf. gewone tabel) –  voorbeeld: DROP VIEW  WORKS_ON1;  –  geen verwijdering van tupels 6
  • 7. implementatie van views •  twee benaderingen: –  query modification: •  query op view wordt omgevormd tot query op onderliggende tabellen; •  nadeel: kan tot complexe en tijdsintensieve queries leiden –  view materialization: •  tijdelijke creatie van de afgeleide (view) tabel wanneer ze voor het eerst in een query gebruikt wordt; •  vereist ‘incremental update’: aanpassing van de afgeleide tabel wanneer basistabellen gewijzigd worden; •  afgeleide tabel wordt automatisch weggelaten als ze een tijd niet meer gebruikt wordt 7
  • 8. voorbeeld van query modification –  de query QV1 op view WORKS_ON1 SELECT  Fname, Lname  FROM  WORKS_ON1  WHERE  Pname = ‘ProductX’ ;  –  wordt omgevormd tot SELECT  Fname, Lname  FROM  EMPLOYEE, PROJECT, WORKS_ON  WHERE  Ssn = Essn  AND  Pno = Pnumber      AND  Pname = ‘ProductX’ ;  8
  • 9. wijzigen van view •  view is afgeleid uit andere relaties •  ⇒ wijziging moet doorgegeven worden aan andere relaties •  niet steeds mogelijk op eenduidige manier! 9
  • 10. wijzigen van view •  View ← 1 basisrelatie: –  aanpassing aan view → aanpassing aan basisrelatie •  View ← join van meerdere basisrelaties: –  welke relaties aanpassen? 10
  • 11. voorbeeld •  Wijzig PNAME van John Smith in WORKS_ON1 van 'ProductX' naar 'ProductY’ UPDATE   WORKS_ON1  SET     Pname = 'ProductY'  WHERE   Lname = 'Smith' AND Fname = 'John'            AND Pname = 'ProductX’ ;  •  Hoe de wijziging van productnaam doorgeven aan basisrelaties? –  Is het project van naam veranderd? –  Of werkt John Smith nu aan een ander project, nl. ProductY i.p.v. ProductX ? 11
  • 12. UPDATE   PROJECT  SET     Pname = 'ProductY'  WHERE   Pname = 'ProductX’ ; UPDATE   WORKS_ON  SET     Pno =  (SELECT Pnumber FROM PROJECT                   WHERE Name = 'ProductY')  WHERE   Essn =   (SELECT Ssn FROM EMPLOYEE                      WHERE Lname = 'Smith' AND Fname = 'John')            AND            PNO IN   (SELECT Pnumber FROM PROJECT                     WHERE Pname = 'ProductX') ;  sommige aanpassingen zijn zinloos: UPDATE   DEPT_INFO  SET     TOTAL_SAL=100000  WHERE   DNAME='Research’ ; 12
  • 13. wijzigen van views: algemeen •  een view afgeleid uit 1 tabel kan aangepast worden als de view een primaire sleutel of kandidaatsleutel van die tabel bevat (→ te wijzigen tupel is eenduidig bepaald) •  een view afgeleid uit meerdere tabellen is meestal niet aanpasbaar –  indien meerdere aanpassingen mogelijk zijn, moet er een procedure zijn om hieruit te kiezen, b.v.: •  gebruiker vragen een keuze te maken –  DBMS meest waarschijnlijke laten kiezen •  resultaten van aggregaatfuncties kunnen niet aangepast worden 13
  • 15. ter herinnering •  restricties op tabellen •  restricties op attribuutwaarden 15
  • 16. restricties op tabellen •  primaire sleutel: PRIMARY KEY <attrlist> •  alternatieve sleutel: UNIQUE <attrlist>   worden nagekeken bij toevoegen of wijzigen van tupels •  verwijssleutel: FOREIGN KEY <attrlist> REFERENCES <table><attrlist>  wordt nagekeken bij toevoegen of wijzigen van tupels in tabel  wordt nagekeken bij verwijderen of wijzigen van tupels in verwijzende tabel 16
  • 17. referentiële integriteit •  Dno in EMPLOYEE verwijst altijd naar een bestaand dnumber in DEPARTMENT foreign key primary key
  • 18. 18
  • 19. referentiële integriteit •  Dno in EMPLOYEE verwijst altijd naar een bestaand dnumber in DEPARTMENT foreign key primary key 6 6 6
  • 20. restricties op attribuut •  NOT NULL (automatisch voor primaire sleutels) •  DEFAULT <value> •  CHECK (voorwaarde) Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);    worden nagekeken bij toevoegen of wijzigen van attribuutwaarden 20
  • 21. algemene restricties specificeren •  andere restricties dan sleutel-, entiteits- en referentiële restricties opgeven: ASSERTION •  algemene vorm: CREATE ASSERTION <name> CHECK <cond>  21
  • 22. voorbeeld –  salaris van werknemer <= salaris van manager van dept. waarvoor werknemer werkt CREATE ASSERTION   SALARY_CONSTRAINT  CHECK   ( NOT EXISTS                             ( SELECT   *                            FROM   EMPLOYEE  E,  EMPLOYEE  M,                           DEPARTMENT  D                            WHERE   E.Salary > M.Salary                           AND   E.Dno = D.Dnumber                           AND   D.Mgr_ssn = M.Ssn) ) ; 22
  • 23. werking •  bij creatie van een ASSERTION, wordt gecontroleerd of eraan voldaan is •  elke latere wijziging in de gegevensbank: –  slechts toegelaten indien aan de ASSERTION voldaan is –  dit kan veel extra werk vereisen! •  Voorbeeld: er moeten minstens drie werknemers per afdeling zijn. CREATE ASSERTION NIET_MINDER_DAN_3 AS  CHECK (NOT EXISTS (SELECT e1.DNO              FROM (SELECT DISTINCT DNO FROM EMPLOYEE e1                WHERE 3 > (SELECT count(*)                                    FROM EMPLOYEE e2                                    WHERE e2.DNO = e1.DNO)));  23
  • 24. CHECK-clausule •  kan ook bij –  attribuut - definitie –  CREATE DOMAIN gebruikt worden •  → domeinrestricties •  voorbeeld: –  departementsnummer kan slechts een gehele waarde tussen 1 en 20 zijn: DNUMBER INT NOT NULL CHECK (DNUMBER > 0 AND  DNUMBER < 21);  CREATE DOMAIN D_NUM AS INTEGER  CHECK     (D_NUM > 0 AND D_NUM < 21) ;  24
  • 25. •  CHECK –  wordt slechts gecontroleerd bij toevoegen of aanpassen van tupels, slaat op attributen of tupels –  kan dus efficiënter geïmplementeerd worden •  ASSERTION –  is meer algemeen 25
  • 26. andere mogelijkheden •  CREATE TRIGGER •  hierbij wordt de te nemen actie opgegeven wanneer niet aan de voorwaarde voldaan is 26
  • 28. triggers •  een trigger bestaat uit 3 delen: •  een event (bv. update van een attribuut) •  een voorwaarde (bv. een query die nagekeken wordt) •  een actie (delete, update, insert) •  syntax CREATE TRIGGER <name>  { BEFORE | AFTER } <event> ON <table>   FOR EACH ROW  WHEN (<cond>)   <acaon>  28
  • 29. voorbeeld CREATE TRIGGER TotalSal1  AFTER INSERT ON EMPLOYEE   FOR EACH ROW  WHEN (NEW.DNO IS NOT NULL)   UPDATE DEPARTMENT   SET TOTAL_SAL=TOTAL_SAL + NEW.SALARY   WHERE DNO=NEW.DNO  29
  • 30. elementen van triggers •  timing van uitvoering van de actie –  before –  after –  instead of •  actie kan verwijzen naar oude of nieuwe toestand van de gegevensbank •  conditie wordt gespecificeerd in WHEN clausule 30