SlideShare a Scribd company logo
1 of 56
Download to read offline
SQL – deel 1


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

•  vandaag: basisconcepten, voorbeelden, oefeningen
•  volgende week: geavanceerde concepten, extra voorbeeld




                                                        2
geschiedenis

•  SEQUEL (Structured English Query Language)
   –  voor experimentele gegevensbank "System R" (IBM)
•  → SQL (Structured Query Language)
   –  voor DB2, Oracle, INGRES/SQL, ...
   –  eerste commerciële versie: Oracle in 1979




                                                         3
standaardisatie: ANSI - ISO

•  SQL1 : 1986
•  SQL2 of SQL92 : 1992
   –  “levels of conformance”: entry – intemediate - full
•  SQL99 : 1999
   –  aanvullingen met o.a. nieuwe data types, object-georiënteerde
      concepten en triggers
   –  levels of conformance: Core SQL:1999 - Enhanced SQL:1999

 de meeste implementaties van SQL verschillen in meer
 of mindere mate van de standaard
                           	
  


                                                                      4
terminologie


•  relationeel model   •  SQL

   –    schema           –    schema
   –    relatie          –    tabel
   –    tupel            –    rij
   –    attribuut        –    kolom




                                       5
schema

•  bevat
   –  schema-naam
   –  eigenaar en
   –  beschrijving van elementen
      •    tabellen
      •    restricties (constraints)
      •    views
      •    domeinen
      •    autorisaties
      •    …

•  creatie van schema: CREATE SCHEMA

                  CREATE	
  SCHEMA	
  COMPANY	
  
                      	
  AUTHORIZATION	
  Jsmith	
  ;!
                                                          6
cataloog

•    = een verzameling gegevensbankschema's in een “SQL omgeving”
•    de cataloog bevat één speciaal schema: INFORMATION_SCHEMA
•    integriteitsrestricties kunnen opgelegd worden tussen relaties in cataloog
•    schema’s binnen eenzelfde cataloog kunnen elementen delen




                                                                           7
creatie van een tabel

CREATE	
  TABLE	
  	
  [	
  <schema	
  name	
  >.	
  ]	
  <table	
  name>	
  
	
  
	
  	
  	
  	
  	
  (	
  {	
  <column	
  name>	
  <column	
  type>	
  [<aAribute	
  constraint>]	
  }	
  	
  
	
  
	
  	
  	
  	
  	
  	
  {<table	
  constraint>}	
  *)	
  
•  naam
•  voor alle attributen:
      –  naam + SQL-gegevenstype + restricties
•  restricties




                                                                                                            8
numerieke gegevenstypes en domeinen
 •  gehele waarden:
    –  INTEGER - INT
    –  SMALLINT
 •  niet gehele waarden:
    –  FLOAT – REAL
    –  DOUBLE PRECISION
 •  geformateerde getallen:
    –  DECIMAL (i, j) – DEC (i, j) – NUMERIC (i, j) met
        i: precisie (= totaal aantal dec.cijfers)
        j: schaal (= aantal cijfers na dec. punt)




                                                          10
karakter strings
•  string met vaste lengte:
   –  CHAR (n) – CHARACTER (n)
•  string met variabele lengte:
   –  VARCHAR(n) – CHAR VARYING (n) – CHARACTER VARYING (n)
•  notatie van waarden: tussen apostrofs: ‘abc‘




                                                        11
gegevenstypes en domeinen in SQL

•  bit strings:
   –  met vaste lengte: BIT (n)
   –  met variabele lengte: BIT VARYING (n)
   –  notatie van waarden: B’10101’
•  logische waarden
   –  BOOLEAN
   –  mogelijke waarden:      TRUE    FALSE UNKNOWN




                                                      12
datum en tijd

•  DATE
  –  10 posities: YYYY-MM-DD
  –  DATE’2004-02-23’
•  TIME
  –  ten minste 8 posities: HH:MM:SS
  –  TIME’09:12:47’
•  TIMESTAMP
  –  DATE en TIME en 6 posities voor fracties van seconden:
  –  TIMESTAMP’2004-02-23 09:12:47 648302’




                                                              13
in verschillende implementaties

•  namen kunnen verschillen
•  soms nog meer variaties in types

•  voorbeeld:
   –  http://en.wikipedia.org/wiki/
      Comparison_of_relational_database_management_systems




                                                             14
definitie van type van een attribuut

•  ofwel rechtstreeks
•  ofwel via definitie van domein


           CREATE	
  DOMAIN	
  	
  SSN_TYPE	
  AS	
  CHAR(9)	
  ;!




                                                                     15
definiëren van restricties op tabel
•  Soorten:
   –  primaire sleutel:       PRIMARY KEY <attrlist>
   –  alternatieve sleutel:   UNIQUE <attrlist>
   –  verwijssleutel:         FOREIGN KEY <attrlist> REFERENCES
                                             <table><attrlist>
•  Actie bij schending van referentiële integriteit:
   –  bij trigger:            ON DELETE / ON UPDATE
   –  actie:                  SET NULL / CASCADE / SET DEFAULT




                                                           16
restricties op attribuut
•  NOT NULL (automatisch voor primaire sleutels)
•  DEFAULT <value>
•  CHECK (voorwaarde)
    –  kan ook samen met domein declaratie



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




                                                                                      18
specificeren van restricties

•  twee mogelijkheden
   –  onmiddellijk bij tabel of attribuut
   –  met sleutelwoord ‘CONSTRAINT’ en het geven van een naam
      •  geeft de mogelijkheid om de restrictie later gemakkelijk aan te passen, weg
         te laten,….




                                                                                  19
weglaten van tabel / schema

•  Drop behaviour voor schema:
   –  CASCADE:
         •  schema + alle tabellen erin weglaten
   –  RESTRICT:
         •  schema enkel weglaten als het leeg is

•  Drop behaviour voor tabel:
   –  CASCADE:
         •  alle restricties en views die aan de tabel refereren worden mee weggelaten
   –  RESTRICT:
         •  tabel enkel weglaten als er geen restricties of views naar verwijzen



   DROP	
  SCHEMA	
  	
  <name>	
  <drop	
  behaviour>	
  
   DROP	
  TABLE	
  	
  	
  	
  	
  	
  <name>	
  <drop	
  behaviour>	
  
                                                                                    21
wijzigen van tabel

ALTER	
  TABLE	
  <name>	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  {	
  	
  	
  ADD	
  	
  	
  	
  	
  	
  <column	
  name>	
  <column	
  type>	
  
                                 	
  	
  |	
  DROP	
  	
  	
  <column	
  name>	
  <drop	
  behaviour>	
  
                                 	
  	
  |	
  ALTER	
  	
  <column	
  name>	
  <default	
  opVon>	
  
                                 	
  	
  |	
  ADD	
  	
  CONSTRAINT	
  	
  	
  	
  <constraint	
  definiVon>	
  
                                 	
  	
  |	
  DROP	
  	
  CONSTRAINT	
  	
  <constraint	
  name>	
  	
  <drop	
  
behaviour>	
  }	

                                        –  <drop behaviour> =
                                                •  CASCADE | RESTRICT
                                        –  <default option> =
                                                •  DROP DEFAULT | SET DEFAULT <value>




                                                                                                                    22
ALTER	
  TABLE	
  	
  COMPANY.EMPLOYEE	
  
     	
  ADD	
  COLUMN	
  Job	
  VARCHAR(12)	
  ;!

ALTER	
  TABLE	
  	
  COMPANY.EMPLOYEE	
  
     	
  DROP	
  COLUMN	
  Address	
  CASCADE	
  ;!

       ALTER	
  TABLE	
  	
  COMPANY.DEPARTMENT	
  
            	
  ALTER	
  COLUMN	
  Mgr_ssn	
  DROP	
  DEFAULT	
  ;!

  ALTER	
  TABLE	
  	
  COMPANY.DEPARTMENT	
  
       	
  ALTER	
  COLUMN	
  Mgr_ssn	
  SET	
  DEFAULT	
  ‘33445555’	
  ;!

      ALTER	
  TABLE	
  	
  COMPANY.EMPLOYEE	
  
           	
  DROP	
  CONSTRAINT	
  EMPSUPERFK	
  CASCADE	
  ;!
                                                                              23
opvragingen (queries) in SQL

•  Basisvorm van een vraag (query):

            SELECT	
  <aAributen	
  lijst>	
  	
  
            	
  	
  	
  	
  	
  FROM	
  	
  	
  	
  	
  <tabellen	
  lijst>	
  
            	
  	
  	
  	
  	
  WHERE	
  	
  <condiVes>	
  ;	

                                                           	
  

•  vgl. met relationele algebra:
   –  SELECT                       projectie
   –  FROM                         carthesisch product
   –  WHERE                        selectie



                                                                                  24
voorbeeld

•  Q_0: geef de geboortedatum en het adres van
   werknemer John B. Smith


   SELECT	
                   	
  Bdate,	
  Address	
  
   FROM	
  	
  	
  	
  	
     	
  EMPLOYEE	
  
   WHERE	
                    	
  Fname='John'	
  AND	
  Minit='B'	
  AND	
  Lname='Smith’	
  ;!

  Bdate                               Address
  ----------                           ------------------------
  1965-01-09                           731 Fondren, Houston, TX!

  In	
  relaVonele	
  algebra:	
  	
  
  πBdate,Address	
  (σ	
  Fname	
  =	
  'John'	
  	
  AND	
  	
  Minit	
  =	
  ‘John’	
  	
  AND	
  	
  Lname	
  =	
  
  ‘Smith’	
  (EMPLOYEE)	
  )	
  
•  Q1B: geef naam en adres van alle werknemers die voor
   het "research" departement werken

    SELECT	
                        	
  E.Fname,	
  E.Lname,	
  E.Address	
  
    FROM	
                          	
  EMPLOYEE	
  	
  E,	
  DEPARTMENT	
  	
  D	
  
    WHERE	
                         	
  D.Dname	
  =	
  'Research'	
  AND	
  D.Dnumber	
  =	
  E.Dno	
  ;!


         •  vergelijk met uitdrukking in tupel relationele calculus


    {	
  t.Fname,	
  t.Lname,	
  t.Address	
  |	
  EMPLOYEE(t)	
  	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
                                             	
                	
   	
   	
  AND	
  (∃d)	
  (DEPARTMENT(d)	
  	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
   	
   	
   	
          	
  AND	
  d.Dname	
  =	
  'Research’	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
   	
   	
   	
          	
  AND	
  d.Number	
  =	
  t.Dno)	
  }	
  

                                                                                                                                                                                 26
 geef	
  namen	
  van	
  projecten	
  die	
  gecontroleerd	
  worden	
  door	
  
    departement	
  5	
  




                                                                	
  select	
  	
  ?	
  
                                                                	
  from	
   	
  ?	
  
                                                                	
  where	
  ?	
  




                                                                                          27
 SELECT	
  pname	
  FROM	
  project	
  WHERE	
  dnum=5;	
  


	
  geef	
  social	
  security	
  numbers	
  van	
  werknemers	
  die	
  werken	
  aan	
  
    projecten	
  die	
  gecontroleerd	
  worden	
  door	
  departement	
  5	
  




                                                                	
  select	
  	
  ?	
  
                                                                	
  from	
   	
  ?	
  
                                                                	
  where	
  ?	
  

                                                                                             28
 SELECT	
  pname,	
  essn	
  FROM	
  project,	
  works_on	
  
	
  WHERE	
  dnum=5	
  and	
  pno=pnumber;	
  

	
  geef	
  voornaam	
  en	
  familienaam	
  van	
  werknemers	
  die	
  werken	
  aan	
  
    projecten	
  die	
  gecontroleerd	
  worden	
  door	
  departement	
  5	
  




                                                               	
  select	
  	
  ?	
  
                                                               	
  from	
   	
  ?	
  
                                                               	
  where	
  ?	
  


                                                                                         29
SELECT	
  pname	
  
FROM	
  project	
  
WHERE	
  dnum=5;	
  

SELECT	
  pname,	
  essn	
  
FROM	
  project,	
  works_on	
  
WHERE	
  dnum=5	
  and	
  pno=pnumber;	
  

SELECT	
  pname,	
  fname,	
  lname	
  	
  
FROM	
  project,	
  works_on,	
  employee	
  	
  
WHERE	
  dnum=5	
  and	
  pno=pnumber	
  and	
  essn=ssn;	
  

                                                                30
voorbeeld
•  geef voor elk project dat als locatie Stafford heeft, het
   projectnummer, nummer van het departement dat het leidt, en de
   familienaam, adres en geboortedatum van de manager van dat
   departement


         SELECT	
                        	
  Pnumber,	
  Dnum,	
  Lname,	
  Address,	
  Bdate	
  
         FROM	
                          	
  PROJECT,	
  DEPARTMENT,	
  EMPLOYEE	
  
         WHERE	
                         	
  Dnum	
  =	
  Dnumber	
  	
  AND	
  	
  Mgr_ssn	
  =	
  Ssn	
  
         	
  	
  	
  	
  	
  	
   	
     	
  AND	
  	
  PlocaVon	
  =	
  'Stafford’	
  ;	
  

    Pnumber Dnum                               Lname                             Address
    Bdate
    ------- ----
    resultaat:                               -------             -----------------------
    ----------
       10      4                             Wallace             291 Berry, Bellaire, TX
    1941-06-20
       30      4                             Wallace             291 Berry, Bellaire, TX
    1941-06-20
dubbelzinnige attribuutnamen

•  Tot nog toe: steeds duidelijk bij welke relatie een
   attribuut behoorde
•  Wat indien dit niet het geval is?
      vb. attributen Name en Dnumber (i.p.v. Dno) in EMPLOYEE en
        DEPARTMENT tabel


•  Oplossing: attribuutnaam = <tabel>.<attribuut>



  SELECT	
                        	
  Fname,	
  EMPLOYEE.Name,	
  Address	
  
  FROM	
                          	
  EMPLOYEE,	
  DEPARTMENT	
  
  WHERE	
                         	
  DEPARTMENT.Name	
  =	
  'Research'	
  
  	
  	
  	
  	
  	
  	
   	
     	
  AND	
  DEPARTMENT.Dnumber	
  =	
  EMPLOYEE.Dnumber	
  ;!
aliasen

•  voorbeeld:
   –  geef voor elke werknemer de voor- en familienaam en de
      familienaam van zijn/haar supervisor
   –  2 verwijzingen naar EMPLOYEE: een voor werknemer zelf, een
      voor supervisor


•  hoe van elkaar onderscheiden?
•  "aliases": de verwijzingen krijgen aparte namen


       SELECT	
     	
  E.Fname,	
  	
  E.Lname,	
  S.Fname,	
  S.Lname	
  
       FROM	
       	
  EMPLOYEE	
  	
  AS	
  E,	
  	
  	
  EMPLOYEE	
  AS	
  S	
  
       WHERE	
      	
  E.Super_ssn	
  =	
  S.Ssn	
  ;!

                                                                                      33
aliasen
–  Q 8: for each employee, retrieve the employee’s first and last
   name and the last name of his or her immediate supervisor

       SELECT	
        	
  E.Fname,	
  	
  E.Lname,	
  S.Fname,	
  S.Lname	
  
       FROM	
          	
  EMPLOYEE	
  	
  AS	
  E,	
  	
  	
  EMPLOYEE	
  AS	
  S	
  
       WHERE	
         	
  E.Super_ssn	
  =	
  S.Ssn	
  ;!


    SELECT	
        	
  E.Fname,	
  	
  E.Lname,	
  S.Fname,	
  S.Lname	
  
    FROM	
          	
  EMPLOYEE	
  	
  E	
  	
  S	
  
    WHERE	
         	
  E.Super_ssn	
  =	
  S.Ssn	
  ;	
  


–  Definitie: - onmiddellijk na de naam van de relatie
              - na sleutelwoord AS

                                                                                         34
weglaten van WHERE en van attributenlijst

•  WHERE kan weggelaten worden: geen selectie

     SELECT	
      	
  Ssn	
  
     FROM	
        	
  EMPLOYEE	
  ;!


    SELECT	
      	
  Ssn,	
  Dname	
  
    FROM	
        	
  EMPLOYEE,	
  DEPARTMENT	
  ;!   carthesisch product




                                                                     35
weglaten van WHERE en van attributenlijst

•  Alle attributen selecteren (met *) : geen projectie


      SELECT	
                  	
  *	
  
      FROM	
                    	
  EMPLOYEE	
  
      WHERE	
  	
  	
  	
  	
  Dno	
  =	
  5	
  ;!


       SELECT	
              	
  *	
  
       FROM	
                	
  EMPLOYEE,	
  DEPARTMENT	
  
       WHERE	
               	
  Dname	
  =	
  'Research'	
  AND	
  Dno	
  =	
  Dnumber	
  ;!


      SELECT	
             	
  *	
  
      FROM	
               	
  EMPLOYEE,	
  DEPARTMENT	
  ;!


                                                                                                36
Verschil tussen tabellen en relaties

•  een relatie uit het relationeel model is een verzameling
   tupels en bevat dus geen dubbels
•  SQL elimineert niet automatisch dubbels




                                                              37
SELECT               	
  Salary	
                 •  Vermijden van dubbels:
FROM	
               	
  EMPLOYEE	
  ;!
                                                     SELECT DISTINCT
equivalent met
 SELECT	
  	
  	
  ALL	
  Salary	
                   SELECT	
  	
  	
  DISTINCT	
  Salary	
  
 FROM	
  	
  	
  	
  	
  	
  	
  EMPLOYEE	
  ;!      FROM	
  	
  	
  	
  	
  	
  	
  EMPLOYEE	
  ;!


                     Salary                                    Salary
                     ------                                    ------
                     30000                                     30000
                     40000                                     40000
                     25000                                     25000
                     43000                                     43000
                     38000                                     38000
                     25000                                     55000!
                     25000
                     55000!                                                                           38
Verzameling-bewerkingen in SQL
 –  UNION, INTERSECT, EXCEPT (= verschil)
 –  relaties moeten vergelijkbaar zijn
       •  zelfde attribuuttypes in zelfde volgorde
 –  dubbels worden automatisch verwijderd

 –  vb: Q 4:
       •  geef alle projecten waarbij Smith betrokken is als manager van het
          controlerend departement of waaraan hij meewerkt

(SELECT	
       	
  DISTINCT	
  Pnumber	
  
	
  FROM	
      	
  PROJECT,	
  DEPARTMENT,	
  EMPLOYEE	
  
	
  WHERE	
     	
  Dnum	
  =	
  Dnumber	
  AND	
  Mgr_ssn	
  =	
  Ssn	
  AND	
  Lname	
  =	
  'Smith')	
  	
  
	
  
UNION	
  
	
  
(SELECT	
       	
  DISTINCT	
  Pnumber	
  
	
  FROM	
      	
  PROJECT,	
  WORKS_ON,	
  EMPLOYEE	
  
	
  WHERE	
     	
  Pno	
  =	
  Pnumber	
  AND	
  Essn	
  =	
  Ssn	
  AND	
  Lname	
  =	
  'Smith')	
  ;!
operaties die slaan op multisets

•  sleutelwoord ALL na de operator:
     –  UNION ALL
     –  EXCEPT ALL
     –  INTERSECT ALL

 R	
   A	
      S	
   A	
      T	
   A	
        V	
   A	
      W	
   A	
  
       a1	
           a1	
           a1	
             a2	
           a1	
  
       a2	
           a2	
           a1	
             a3	
           a2	
  
       a2	
           a4	
           a2	
  
       a3	
           a5	
           a2	
  
                                     a2	
     T ← R UNION ALL S
                                     a3	
  
                                     a4	
     V ← R EXCEPT ALL S
                                     a5	
  
                                              W ← R INTERSECT ALL S
string- en rekenkundige operatoren
•  Test string op patroon: LIKE
    –  _ : één willekeurig teken
    –  % : willekeurige rij tekens


Q12: Geef de naam van alle werknemers die in Houston, Texas wonen
   SELECT	
      	
  Fname,Lname	
  
   FROM	
        	
  EMPLOYEE	
  
   WHERE	
       	
  Address	
  LIKE	
  	
  '%Houston,TX%’	
  ;	
  

Q12A: Geef de naam van alle werknemers die in de jaren 1950
geboren zijn
    SELECT	
      	
  Fname,Lname	
  
    FROM	
        	
  EMPLOYEE	
  
    WHERE	
       	
  Bdate	
  LIKE	
  	
  '_	
  _5_	
  _	
  _	
  _	
  _	
  _	
  _’	
  ;!
rekenkundige operatoren: +, -, *, /

•  kunnen gebruikt worden op numerieke waarden

•  Q13: Geef het salaris van elke werknemer die werkt
   aan project ‘ProductX’, verhoogd met 10 %




     SELECT	
                        	
  Fname,	
  Lname,	
  	
  1.1	
  *	
  Salary	
  AS	
  Increased_sal	
  
     FROM	
                          	
  EMPLOYEE,	
  	
  WORKS_ON,	
  	
  PROJECT	
  
     WHERE	
                         	
  Ssn	
  =	
  Essn	
  	
  AND	
  	
  Pno	
  =	
  Pnumber	
  	
  
     	
  	
  	
  	
  	
  	
   	
     	
  AND	
  	
  Pname	
  =	
  'ProductX’	
  ;!



                                                                                                                 42
andere operatoren
•  strings
   –  concatenatie              ||
•  datum, tijd, tijdsstempel:
   –  verhogen of verlagen met een interval
   –  verschil tussen data, tijden: → een interval
•  BETWEEN:
   –  Q14: Geef alle werknemers van departement 5 met een
      salaris tussen 30 000 en 40 000 EUR

   SELECT	
     	
  *	
  
   FROM	
       	
  EMPLOYEE	
  
   WHERE	
      	
  (Salary	
  BETWEEN	
  30	
  000	
  AND	
  40	
  000)	
  AND	
  	
  Dno	
  =	
  5	
  ;!

   de salaris-voorwaarde is equivalent met
   ((Salary >= 30 000) AND (Salary <= 40 000))                                                               43
ordenen van query resultaten
•  ORDER BY <attributen> [ ASC | DESC ]

    –  Q 15: Geef een lijst van de namen van de werknemers en de namen van de
       projecten waarop zij werken, per departement, en in elk departement
       alfabetisch geordend volgens familienaam, voornaam



  SELECT	
          	
     	
  Dname,	
  	
  Fname,	
  	
  Lname,	
  	
  Pname	
  
  FROM	
            	
     	
  DEPARTMENT,	
  EMPLOYEE,	
  WORKS_ON,	
  PROJECT	
  
  WHERE	
           	
     	
  Dnumber	
  =	
  Dno	
  	
  AND	
  	
  Ssn	
  =	
  Essn	
  	
  
       	
           	
     	
  AND	
  	
  Pno	
  =	
  Pnumber	
  	
  
  ORDER	
  BY	
     	
     	
  Dname,	
  Lname,	
  Fname	
  ;	
  

•  default ordening is stijgend (ASC)
•  dalende orde (DESC) moet steeds expliciet vermeld worden:

  ORDER BY                     Dname DESC, Lname ASC, Fname ASC
•  nagaan of een waarde null is:
   –  IS NULL
   –  IS NOT NULL




•  Q 18 : retrieve the names of all employees who have no
   supervisors


             SELECT	
     	
  Fname,	
  Lname	
  
             FROM	
       	
  EMPLOYEE	
  
             WHERE	
      	
  Super_ssn	
  IS	
  NULL	
  ;!


                                                              45
aggregaatfuncties

•  Ingebouwde functies:
   –  COUNT, SUM, MAX, MIN, AVG


•  voorbeeld: zoek som, maximum, minimum en
   gemiddelde van alle salarissen




  SELECT	
     	
  SUM(Salary),	
  MAX(Salary),	
  MIN(Salary),	
  AVG(Salary)	
  
  FROM	
       	
  EMPLOYEE;	
  




                                                                                     46
aggregaatfuncties
 –  Q 20
      •  zoek som, maximum, minimum, gemiddelde, van de salarissen van alle
         werknemers uit het 'Research' departement




 SELECT	
     	
  SUM(Salary),	
  MAX(Salary),	
  MIN(Salary),	
  AVG(Salary)	
  
 FROM	
       	
  (EMPLOYEE	
  JOIN	
  DEPARTMENT	
  ON	
  Dno	
  =	
  Dnumber)	
  
 WHERE	
      	
  DNAME	
  =	
  'Research’	
  ;	
  




                                                                                      47
aggregaatfuncties
•  bepaal totaal aantal werknemers

       SELECT	
          	
  COUNT(*)	
  
       FROM	
            	
  EMPLOYEE	
  ;	
  

•  bepaal aantal werknemers in departement 'Research’

        SELECT	
         	
  COUNT(*)	
  
        FROM	
           	
  EMPLOYEE,	
  DEPARTMENT	
  
        WHERE	
          	
  Dno	
  =	
  Dnumber	
  	
  AND	
  	
  Dname	
  =	
  'Research’	
  ;!
•  tel het aantal verschillende waarden voor salaris

        SELECT	
  	
     	
  COUNT	
  (DISTINCT	
  Salary)	
  
        FROM	
           	
  EMPLOYEE	
  ;	
  
                                                                                                    48
aggregaatfuncties

  –  gebruik binnen WHERE (voor geneste queries):
  –  voorbeeld: geef alle werknemers die minstens 2 personen ten
     laste hebben


          SELECT	
                            	
  Lname,	
  Fname	
  
          FROM	
                              	
  EMPLOYEE	
  
          WHERE	
                             	
  (	
  SELECT	
   	
  COUNT(*)	
  
          	
  	
  	
  	
  	
  	
  	
   	
     	
  	
  	
  FROM	
    	
  DEPENDENT	
  
          	
  	
  	
  	
  	
  	
  	
   	
     	
  	
  	
  WHERE	
   	
  Ssn	
  =	
  Essn	
  )	
  >=	
  2	
  ;!




                                                                                                                 49
groepering
•  Groeperen van tupels : GROUP BY
   –  aggregaatfuncties worden voor elke groep afzonderlijk toegepast


•  voorbeeld: geef voor elk departement het nummer, het aantal
  werknemers en het gemiddelde salaris


               SELECT	
             	
  	
  	
  	
  DNO,	
  COUNT(*),	
  AVG(Salary)	
  
               FROM	
               	
  	
  	
  	
  EMPLOYEE	
  
               GROUP	
  BY	
  	
  	
  DNO	
  ;	
  




                                                                                           50
aanpassingen maken in SQL

•  Toevoegen:   INSERT
•  Weglaten:    DELETE
•  Wijzigen:    UPDATE




                            51
toevoegen

•  INSERT commando
•  verschillende vormen
   –  zonder expliciete vermelding van attributen:
       •  volgorde respecteren
   –  met expliciete vermelding van attributen:
       •  nulls en defaults kunnen weggelaten worden




        INSERT	
  INTO	
                             	
  EMPLOYEE	
  
        VALUES	
   	
                                	
  ('Richard',	
  'K',	
  'Marini',	
  '653298653',	
  
        	
  	
  	
  	
  	
  	
  	
  	
   	
   	
     	
  ‘1962-­‐12-­‐30',	
  '98	
  Oak	
  Forest,	
  Katy',	
  TX',	
  
        	
  	
  	
  	
  	
  	
  	
  	
   	
   	
     	
  'M',	
  37000,	
  '987654321',	
  4)	
  ;	
  

                INSERT	
  INTO	
                         	
  EMPLOYEE	
  (Fname,	
  Lname,	
  Ssn)	
  
                VALUES	
  	
   	
                        	
  ('Richard',	
  'Marini',	
  '653298653')	
  ;	
  
                                                                                                                            52
Meerdere tupels tegelijk toevoegen

•  vaak meteen na creatie van tabel, laden van resultaat
   van een query
CREATE	
  TABLE	
   	
                                                   	
  DEPTS_INFO	
  	
  
                 	
  (	
  Dept_name	
                                    	
          	
  VARCHAR(15),	
  
	
               	
  	
  	
  No_of_emps	
                                	
          	
  INTEGER,	
  
	
  	
  	
       	
  	
  	
  Total_sal 	
  	
                            	
          	
  INTEGER	
  );	
  
	
  
INSERT	
  INTO	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  DEPTS_INFO	
  (Dept_name,No_of_emps,Total_sal)	
  
                 	
  SELECT	
                         	
                 	
  Dname,	
  COUNT(*),	
  SUM(Salary)	
  
	
  	
  	
       	
  FROM	
                           	
                 	
  (	
  DEPARTMENT	
  JOIN	
  EMPLOYEE	
  ON	
  
                 	
              	
  	
               	
                 	
  Dnumber	
  =	
  Dno	
  )	
  
	
  	
  	
  	
   	
  GROUP	
  BY	
   	
  Dname	
  ;!
   In dit voorbeeld niet zo'n goed idee
              redundantie + mogelijk verlies van integriteit
              beter : view definiëren (zie later)                                                                            53
weglaten van tupels
•  DELETE FROM <tabel> WHERE <conditie>
  –  alle tupels die aan conditie voldoen worden weggelaten
  –  geen WHERE deel: alle tupels weg
              •  ! tabel verdwijnt niet, wordt enkel leeg
              •  tabel kan weggelaten worden met DROP TABLE


   DELETE	
  FROM	
                                                	
  EMPLOYEE	
  
   WHERE	
      	
                                                 	
  Lname	
  =‘Brown'	
  ;!
  DELETE	
  FROM	
                                                 	
  EMPLOYEE	
  
  WHERE	
      	
                                                  	
  Ssn	
  =‘123456789'	
  ;!

   DELETE	
  FROM	
                                                 	
  EMPLOYEE	
  
   WHERE	
                                                  	
      	
  Dno	
  IN	
  	
  	
  (SELECT	
  	
  	
  Dnumber	
  	
  
   	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
   	
      	
          	
  	
  	
  	
  	
  	
  FROM	
   	
  	
  	
  	
  	
  DEPARTMENT	
  	
  
   	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
   	
      	
          	
  	
  	
  	
  	
  	
  WHERE	
  	
  	
  	
  Dname	
  =	
  'Research')	
  ;!

   DELETE	
  FROM	
                                                 	
  EMPLOYEE	
  ;!                                                                         54
wijzigen van tupels

•  UPDATE <tabel> SET { < attr > = < expr > , … }
       WHERE <conditie>
                                     •  selecteer te wijzigen tupels met WHERE-conditie
                                     •  ken voor die tupels nieuwe waarden aan attributen toe: in SET deel




                UPDATE	
   	
  PROJECT	
  
                SET	
   	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  PlocaVon	
  =	
  'Bellaire',	
  Dnum	
  =	
  5	
  
                WHERE	
                                          	
  Pnumber	
  =	
  10	
  ;	
  


  UPDATE	
                                                   	
  EMPLOYEE	
  
  SET	
   	
                                                 	
  Salary	
  =	
  Salary	
  *	
  1.1	
  
  WHERE	
                                                    	
  Dno	
  IN	
        	
  (SELECT	
        	
  Dnumber	
  
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
     	
          	
         	
  FROM	
           	
  DEPARTMENT	
  
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
     	
          	
         	
  WHERE	
          	
  Dname	
  =	
  'Research')	
  ;!   55
VRAGEN?


          56

More Related Content

Viewers also liked

The Most Pinteresting Brands by Unmetric
The Most Pinteresting Brands by UnmetricThe Most Pinteresting Brands by Unmetric
The Most Pinteresting Brands by UnmetricUnmetric
 

Viewers also liked (8)

The Most Pinteresting Brands by Unmetric
The Most Pinteresting Brands by UnmetricThe Most Pinteresting Brands by Unmetric
The Most Pinteresting Brands by Unmetric
 
Comercio electronico
Comercio electronico      Comercio electronico
Comercio electronico
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronico
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronico
 
Comercio electronico
Comercio electronicoComercio electronico
Comercio electronico
 
Medios De Pago
Medios De PagoMedios De Pago
Medios De Pago
 
Comercio electrónico
Comercio electrónicoComercio electrónico
Comercio electrónico
 
Apostila tge e tgd
Apostila tge e tgdApostila tge e tgd
Apostila tge e tgd
 

More from 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
 

More from 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 1

  • 1. SQL – deel 1 Katrien Verbert katrien.verbert@cs.kuleuven.be
  • 2. SQL •  vandaag: basisconcepten, voorbeelden, oefeningen •  volgende week: geavanceerde concepten, extra voorbeeld 2
  • 3. geschiedenis •  SEQUEL (Structured English Query Language) –  voor experimentele gegevensbank "System R" (IBM) •  → SQL (Structured Query Language) –  voor DB2, Oracle, INGRES/SQL, ... –  eerste commerciële versie: Oracle in 1979 3
  • 4. standaardisatie: ANSI - ISO •  SQL1 : 1986 •  SQL2 of SQL92 : 1992 –  “levels of conformance”: entry – intemediate - full •  SQL99 : 1999 –  aanvullingen met o.a. nieuwe data types, object-georiënteerde concepten en triggers –  levels of conformance: Core SQL:1999 - Enhanced SQL:1999 de meeste implementaties van SQL verschillen in meer of mindere mate van de standaard   4
  • 5. terminologie •  relationeel model •  SQL –  schema –  schema –  relatie –  tabel –  tupel –  rij –  attribuut –  kolom 5
  • 6. schema •  bevat –  schema-naam –  eigenaar en –  beschrijving van elementen •  tabellen •  restricties (constraints) •  views •  domeinen •  autorisaties •  … •  creatie van schema: CREATE SCHEMA CREATE  SCHEMA  COMPANY    AUTHORIZATION  Jsmith  ;! 6
  • 7. cataloog •  = een verzameling gegevensbankschema's in een “SQL omgeving” •  de cataloog bevat één speciaal schema: INFORMATION_SCHEMA •  integriteitsrestricties kunnen opgelegd worden tussen relaties in cataloog •  schema’s binnen eenzelfde cataloog kunnen elementen delen 7
  • 8. creatie van een tabel CREATE  TABLE    [  <schema  name  >.  ]  <table  name>              (  {  <column  name>  <column  type>  [<aAribute  constraint>]  }                  {<table  constraint>}  *)   •  naam •  voor alle attributen: –  naam + SQL-gegevenstype + restricties •  restricties 8
  • 9.
  • 10. numerieke gegevenstypes en domeinen •  gehele waarden: –  INTEGER - INT –  SMALLINT •  niet gehele waarden: –  FLOAT – REAL –  DOUBLE PRECISION •  geformateerde getallen: –  DECIMAL (i, j) – DEC (i, j) – NUMERIC (i, j) met i: precisie (= totaal aantal dec.cijfers) j: schaal (= aantal cijfers na dec. punt) 10
  • 11. karakter strings •  string met vaste lengte: –  CHAR (n) – CHARACTER (n) •  string met variabele lengte: –  VARCHAR(n) – CHAR VARYING (n) – CHARACTER VARYING (n) •  notatie van waarden: tussen apostrofs: ‘abc‘ 11
  • 12. gegevenstypes en domeinen in SQL •  bit strings: –  met vaste lengte: BIT (n) –  met variabele lengte: BIT VARYING (n) –  notatie van waarden: B’10101’ •  logische waarden –  BOOLEAN –  mogelijke waarden: TRUE FALSE UNKNOWN 12
  • 13. datum en tijd •  DATE –  10 posities: YYYY-MM-DD –  DATE’2004-02-23’ •  TIME –  ten minste 8 posities: HH:MM:SS –  TIME’09:12:47’ •  TIMESTAMP –  DATE en TIME en 6 posities voor fracties van seconden: –  TIMESTAMP’2004-02-23 09:12:47 648302’ 13
  • 14. in verschillende implementaties •  namen kunnen verschillen •  soms nog meer variaties in types •  voorbeeld: –  http://en.wikipedia.org/wiki/ Comparison_of_relational_database_management_systems 14
  • 15. definitie van type van een attribuut •  ofwel rechtstreeks •  ofwel via definitie van domein CREATE  DOMAIN    SSN_TYPE  AS  CHAR(9)  ;! 15
  • 16. definiëren van restricties op tabel •  Soorten: –  primaire sleutel: PRIMARY KEY <attrlist> –  alternatieve sleutel: UNIQUE <attrlist> –  verwijssleutel: FOREIGN KEY <attrlist> REFERENCES <table><attrlist> •  Actie bij schending van referentiële integriteit: –  bij trigger: ON DELETE / ON UPDATE –  actie: SET NULL / CASCADE / SET DEFAULT 16
  • 17.
  • 18. restricties op attribuut •  NOT NULL (automatisch voor primaire sleutels) •  DEFAULT <value> •  CHECK (voorwaarde) –  kan ook samen met domein declaratie Dnumber  INT  NOT  NULL  CHECK  (Dnumber  >  0  AND  Dnumber  <   21);   18
  • 19. specificeren van restricties •  twee mogelijkheden –  onmiddellijk bij tabel of attribuut –  met sleutelwoord ‘CONSTRAINT’ en het geven van een naam •  geeft de mogelijkheid om de restrictie later gemakkelijk aan te passen, weg te laten,…. 19
  • 20.
  • 21. weglaten van tabel / schema •  Drop behaviour voor schema: –  CASCADE: •  schema + alle tabellen erin weglaten –  RESTRICT: •  schema enkel weglaten als het leeg is •  Drop behaviour voor tabel: –  CASCADE: •  alle restricties en views die aan de tabel refereren worden mee weggelaten –  RESTRICT: •  tabel enkel weglaten als er geen restricties of views naar verwijzen DROP  SCHEMA    <name>  <drop  behaviour>   DROP  TABLE            <name>  <drop  behaviour>   21
  • 22. wijzigen van tabel ALTER  TABLE  <name>                    {      ADD            <column  name>  <column  type>      |  DROP      <column  name>  <drop  behaviour>      |  ALTER    <column  name>  <default  opVon>      |  ADD    CONSTRAINT        <constraint  definiVon>      |  DROP    CONSTRAINT    <constraint  name>    <drop   behaviour>  } –  <drop behaviour> = •  CASCADE | RESTRICT –  <default option> = •  DROP DEFAULT | SET DEFAULT <value> 22
  • 23. ALTER  TABLE    COMPANY.EMPLOYEE    ADD  COLUMN  Job  VARCHAR(12)  ;! ALTER  TABLE    COMPANY.EMPLOYEE    DROP  COLUMN  Address  CASCADE  ;! ALTER  TABLE    COMPANY.DEPARTMENT    ALTER  COLUMN  Mgr_ssn  DROP  DEFAULT  ;! ALTER  TABLE    COMPANY.DEPARTMENT    ALTER  COLUMN  Mgr_ssn  SET  DEFAULT  ‘33445555’  ;! ALTER  TABLE    COMPANY.EMPLOYEE    DROP  CONSTRAINT  EMPSUPERFK  CASCADE  ;! 23
  • 24. opvragingen (queries) in SQL •  Basisvorm van een vraag (query): SELECT  <aAributen  lijst>              FROM          <tabellen  lijst>            WHERE    <condiVes>  ;   •  vgl. met relationele algebra: –  SELECT projectie –  FROM carthesisch product –  WHERE selectie 24
  • 25. voorbeeld •  Q_0: geef de geboortedatum en het adres van werknemer John B. Smith SELECT    Bdate,  Address   FROM            EMPLOYEE   WHERE    Fname='John'  AND  Minit='B'  AND  Lname='Smith’  ;! Bdate Address ---------- ------------------------ 1965-01-09 731 Fondren, Houston, TX! In  relaVonele  algebra:     πBdate,Address  (σ  Fname  =  'John'    AND    Minit  =  ‘John’    AND    Lname  =   ‘Smith’  (EMPLOYEE)  )  
  • 26. •  Q1B: geef naam en adres van alle werknemers die voor het "research" departement werken SELECT    E.Fname,  E.Lname,  E.Address   FROM    EMPLOYEE    E,  DEPARTMENT    D   WHERE    D.Dname  =  'Research'  AND  D.Dnumber  =  E.Dno  ;! •  vergelijk met uitdrukking in tupel relationele calculus {  t.Fname,  t.Lname,  t.Address  |  EMPLOYEE(t)                                  AND  (∃d)  (DEPARTMENT(d)                                                                AND  d.Dname  =  'Research’                                                              AND  d.Number  =  t.Dno)  }   26
  • 27.  geef  namen  van  projecten  die  gecontroleerd  worden  door   departement  5    select    ?    from    ?    where  ?   27
  • 28.  SELECT  pname  FROM  project  WHERE  dnum=5;    geef  social  security  numbers  van  werknemers  die  werken  aan   projecten  die  gecontroleerd  worden  door  departement  5    select    ?    from    ?    where  ?   28
  • 29.  SELECT  pname,  essn  FROM  project,  works_on    WHERE  dnum=5  and  pno=pnumber;    geef  voornaam  en  familienaam  van  werknemers  die  werken  aan   projecten  die  gecontroleerd  worden  door  departement  5    select    ?    from    ?    where  ?   29
  • 30. SELECT  pname   FROM  project   WHERE  dnum=5;   SELECT  pname,  essn   FROM  project,  works_on   WHERE  dnum=5  and  pno=pnumber;   SELECT  pname,  fname,  lname     FROM  project,  works_on,  employee     WHERE  dnum=5  and  pno=pnumber  and  essn=ssn;   30
  • 31. voorbeeld •  geef voor elk project dat als locatie Stafford heeft, het projectnummer, nummer van het departement dat het leidt, en de familienaam, adres en geboortedatum van de manager van dat departement SELECT    Pnumber,  Dnum,  Lname,  Address,  Bdate   FROM    PROJECT,  DEPARTMENT,  EMPLOYEE   WHERE    Dnum  =  Dnumber    AND    Mgr_ssn  =  Ssn                  AND    PlocaVon  =  'Stafford’  ;   Pnumber Dnum Lname Address Bdate ------- ---- resultaat: ------- ----------------------- ---------- 10 4 Wallace 291 Berry, Bellaire, TX 1941-06-20 30 4 Wallace 291 Berry, Bellaire, TX 1941-06-20
  • 32. dubbelzinnige attribuutnamen •  Tot nog toe: steeds duidelijk bij welke relatie een attribuut behoorde •  Wat indien dit niet het geval is? vb. attributen Name en Dnumber (i.p.v. Dno) in EMPLOYEE en DEPARTMENT tabel •  Oplossing: attribuutnaam = <tabel>.<attribuut> SELECT    Fname,  EMPLOYEE.Name,  Address   FROM    EMPLOYEE,  DEPARTMENT   WHERE    DEPARTMENT.Name  =  'Research'                  AND  DEPARTMENT.Dnumber  =  EMPLOYEE.Dnumber  ;!
  • 33. aliasen •  voorbeeld: –  geef voor elke werknemer de voor- en familienaam en de familienaam van zijn/haar supervisor –  2 verwijzingen naar EMPLOYEE: een voor werknemer zelf, een voor supervisor •  hoe van elkaar onderscheiden? •  "aliases": de verwijzingen krijgen aparte namen SELECT    E.Fname,    E.Lname,  S.Fname,  S.Lname   FROM    EMPLOYEE    AS  E,      EMPLOYEE  AS  S   WHERE    E.Super_ssn  =  S.Ssn  ;! 33
  • 34. aliasen –  Q 8: for each employee, retrieve the employee’s first and last name and the last name of his or her immediate supervisor SELECT    E.Fname,    E.Lname,  S.Fname,  S.Lname   FROM    EMPLOYEE    AS  E,      EMPLOYEE  AS  S   WHERE    E.Super_ssn  =  S.Ssn  ;! SELECT    E.Fname,    E.Lname,  S.Fname,  S.Lname   FROM    EMPLOYEE    E    S   WHERE    E.Super_ssn  =  S.Ssn  ;   –  Definitie: - onmiddellijk na de naam van de relatie - na sleutelwoord AS 34
  • 35. weglaten van WHERE en van attributenlijst •  WHERE kan weggelaten worden: geen selectie SELECT    Ssn   FROM    EMPLOYEE  ;! SELECT    Ssn,  Dname   FROM    EMPLOYEE,  DEPARTMENT  ;! carthesisch product 35
  • 36. weglaten van WHERE en van attributenlijst •  Alle attributen selecteren (met *) : geen projectie SELECT    *   FROM    EMPLOYEE   WHERE          Dno  =  5  ;! SELECT    *   FROM    EMPLOYEE,  DEPARTMENT   WHERE    Dname  =  'Research'  AND  Dno  =  Dnumber  ;! SELECT    *   FROM    EMPLOYEE,  DEPARTMENT  ;! 36
  • 37. Verschil tussen tabellen en relaties •  een relatie uit het relationeel model is een verzameling tupels en bevat dus geen dubbels •  SQL elimineert niet automatisch dubbels 37
  • 38. SELECT  Salary   •  Vermijden van dubbels: FROM    EMPLOYEE  ;! SELECT DISTINCT equivalent met SELECT      ALL  Salary   SELECT      DISTINCT  Salary   FROM              EMPLOYEE  ;! FROM              EMPLOYEE  ;! Salary Salary ------ ------ 30000 30000 40000 40000 25000 25000 43000 43000 38000 38000 25000 55000! 25000 55000! 38
  • 39. Verzameling-bewerkingen in SQL –  UNION, INTERSECT, EXCEPT (= verschil) –  relaties moeten vergelijkbaar zijn •  zelfde attribuuttypes in zelfde volgorde –  dubbels worden automatisch verwijderd –  vb: Q 4: •  geef alle projecten waarbij Smith betrokken is als manager van het controlerend departement of waaraan hij meewerkt (SELECT    DISTINCT  Pnumber    FROM    PROJECT,  DEPARTMENT,  EMPLOYEE    WHERE    Dnum  =  Dnumber  AND  Mgr_ssn  =  Ssn  AND  Lname  =  'Smith')       UNION     (SELECT    DISTINCT  Pnumber    FROM    PROJECT,  WORKS_ON,  EMPLOYEE    WHERE    Pno  =  Pnumber  AND  Essn  =  Ssn  AND  Lname  =  'Smith')  ;!
  • 40. operaties die slaan op multisets •  sleutelwoord ALL na de operator: –  UNION ALL –  EXCEPT ALL –  INTERSECT ALL R   A   S   A   T   A   V   A   W   A   a1   a1   a1   a2   a1   a2   a2   a1   a3   a2   a2   a4   a2   a3   a5   a2   a2   T ← R UNION ALL S a3   a4   V ← R EXCEPT ALL S a5   W ← R INTERSECT ALL S
  • 41. string- en rekenkundige operatoren •  Test string op patroon: LIKE –  _ : één willekeurig teken –  % : willekeurige rij tekens Q12: Geef de naam van alle werknemers die in Houston, Texas wonen SELECT    Fname,Lname   FROM    EMPLOYEE   WHERE    Address  LIKE    '%Houston,TX%’  ;   Q12A: Geef de naam van alle werknemers die in de jaren 1950 geboren zijn SELECT    Fname,Lname   FROM    EMPLOYEE   WHERE    Bdate  LIKE    '_  _5_  _  _  _  _  _  _’  ;!
  • 42. rekenkundige operatoren: +, -, *, / •  kunnen gebruikt worden op numerieke waarden •  Q13: Geef het salaris van elke werknemer die werkt aan project ‘ProductX’, verhoogd met 10 % SELECT    Fname,  Lname,    1.1  *  Salary  AS  Increased_sal   FROM    EMPLOYEE,    WORKS_ON,    PROJECT   WHERE    Ssn  =  Essn    AND    Pno  =  Pnumber                    AND    Pname  =  'ProductX’  ;! 42
  • 43. andere operatoren •  strings –  concatenatie || •  datum, tijd, tijdsstempel: –  verhogen of verlagen met een interval –  verschil tussen data, tijden: → een interval •  BETWEEN: –  Q14: Geef alle werknemers van departement 5 met een salaris tussen 30 000 en 40 000 EUR SELECT    *   FROM    EMPLOYEE   WHERE    (Salary  BETWEEN  30  000  AND  40  000)  AND    Dno  =  5  ;! de salaris-voorwaarde is equivalent met ((Salary >= 30 000) AND (Salary <= 40 000)) 43
  • 44. ordenen van query resultaten •  ORDER BY <attributen> [ ASC | DESC ] –  Q 15: Geef een lijst van de namen van de werknemers en de namen van de projecten waarop zij werken, per departement, en in elk departement alfabetisch geordend volgens familienaam, voornaam SELECT      Dname,    Fname,    Lname,    Pname   FROM      DEPARTMENT,  EMPLOYEE,  WORKS_ON,  PROJECT   WHERE      Dnumber  =  Dno    AND    Ssn  =  Essn          AND    Pno  =  Pnumber     ORDER  BY      Dname,  Lname,  Fname  ;   •  default ordening is stijgend (ASC) •  dalende orde (DESC) moet steeds expliciet vermeld worden: ORDER BY Dname DESC, Lname ASC, Fname ASC
  • 45. •  nagaan of een waarde null is: –  IS NULL –  IS NOT NULL •  Q 18 : retrieve the names of all employees who have no supervisors SELECT    Fname,  Lname   FROM    EMPLOYEE   WHERE    Super_ssn  IS  NULL  ;! 45
  • 46. aggregaatfuncties •  Ingebouwde functies: –  COUNT, SUM, MAX, MIN, AVG •  voorbeeld: zoek som, maximum, minimum en gemiddelde van alle salarissen SELECT    SUM(Salary),  MAX(Salary),  MIN(Salary),  AVG(Salary)   FROM    EMPLOYEE;   46
  • 47. aggregaatfuncties –  Q 20 •  zoek som, maximum, minimum, gemiddelde, van de salarissen van alle werknemers uit het 'Research' departement SELECT    SUM(Salary),  MAX(Salary),  MIN(Salary),  AVG(Salary)   FROM    (EMPLOYEE  JOIN  DEPARTMENT  ON  Dno  =  Dnumber)   WHERE    DNAME  =  'Research’  ;   47
  • 48. aggregaatfuncties •  bepaal totaal aantal werknemers SELECT    COUNT(*)   FROM    EMPLOYEE  ;   •  bepaal aantal werknemers in departement 'Research’ SELECT    COUNT(*)   FROM    EMPLOYEE,  DEPARTMENT   WHERE    Dno  =  Dnumber    AND    Dname  =  'Research’  ;! •  tel het aantal verschillende waarden voor salaris SELECT      COUNT  (DISTINCT  Salary)   FROM    EMPLOYEE  ;   48
  • 49. aggregaatfuncties –  gebruik binnen WHERE (voor geneste queries): –  voorbeeld: geef alle werknemers die minstens 2 personen ten laste hebben SELECT    Lname,  Fname   FROM    EMPLOYEE   WHERE    (  SELECT    COUNT(*)                        FROM    DEPENDENT                        WHERE    Ssn  =  Essn  )  >=  2  ;! 49
  • 50. groepering •  Groeperen van tupels : GROUP BY –  aggregaatfuncties worden voor elke groep afzonderlijk toegepast •  voorbeeld: geef voor elk departement het nummer, het aantal werknemers en het gemiddelde salaris SELECT          DNO,  COUNT(*),  AVG(Salary)   FROM          EMPLOYEE   GROUP  BY      DNO  ;   50
  • 51. aanpassingen maken in SQL •  Toevoegen: INSERT •  Weglaten: DELETE •  Wijzigen: UPDATE 51
  • 52. toevoegen •  INSERT commando •  verschillende vormen –  zonder expliciete vermelding van attributen: •  volgorde respecteren –  met expliciete vermelding van attributen: •  nulls en defaults kunnen weggelaten worden INSERT  INTO    EMPLOYEE   VALUES      ('Richard',  'K',  'Marini',  '653298653',                        ‘1962-­‐12-­‐30',  '98  Oak  Forest,  Katy',  TX',                        'M',  37000,  '987654321',  4)  ;   INSERT  INTO    EMPLOYEE  (Fname,  Lname,  Ssn)   VALUES        ('Richard',  'Marini',  '653298653')  ;   52
  • 53. Meerdere tupels tegelijk toevoegen •  vaak meteen na creatie van tabel, laden van resultaat van een query CREATE  TABLE      DEPTS_INFO      (  Dept_name      VARCHAR(15),          No_of_emps      INTEGER,              Total_sal        INTEGER  );     INSERT  INTO                            DEPTS_INFO  (Dept_name,No_of_emps,Total_sal)    SELECT      Dname,  COUNT(*),  SUM(Salary)          FROM      (  DEPARTMENT  JOIN  EMPLOYEE  ON            Dnumber  =  Dno  )            GROUP  BY    Dname  ;! In dit voorbeeld niet zo'n goed idee redundantie + mogelijk verlies van integriteit beter : view definiëren (zie later) 53
  • 54. weglaten van tupels •  DELETE FROM <tabel> WHERE <conditie> –  alle tupels die aan conditie voldoen worden weggelaten –  geen WHERE deel: alle tupels weg •  ! tabel verdwijnt niet, wordt enkel leeg •  tabel kan weggelaten worden met DROP TABLE DELETE  FROM    EMPLOYEE   WHERE      Lname  =‘Brown'  ;! DELETE  FROM    EMPLOYEE   WHERE      Ssn  =‘123456789'  ;! DELETE  FROM    EMPLOYEE   WHERE      Dno  IN      (SELECT      Dnumber                                                FROM            DEPARTMENT                                                WHERE        Dname  =  'Research')  ;! DELETE  FROM    EMPLOYEE  ;! 54
  • 55. wijzigen van tupels •  UPDATE <tabel> SET { < attr > = < expr > , … } WHERE <conditie> •  selecteer te wijzigen tupels met WHERE-conditie •  ken voor die tupels nieuwe waarden aan attributen toe: in SET deel UPDATE    PROJECT   SET                      PlocaVon  =  'Bellaire',  Dnum  =  5   WHERE    Pnumber  =  10  ;   UPDATE    EMPLOYEE   SET      Salary  =  Salary  *  1.1   WHERE    Dno  IN    (SELECT    Dnumber                                    FROM    DEPARTMENT                                    WHERE    Dname  =  'Research')  ;! 55
  • 56. VRAGEN? 56