SlideShare a Scribd company logo
SQL Queries
   Principal form:
      SELECT desired attributes
      FROM tuple variables |
               range over relations
      WHERE condition about t.v.'s;

Running example relation schema:
      Beersname, manf
      Barsname, addr, license
      Drinkersname, addr, phone
      Likesdrinker, beer
      Sellsbar, beer, price
      Frequentsdrinker, bar




                        1
Example
What beers are made by Anheuser-Busch?
      Beersname, manf

      SELECT name
      FROM Beers
      WHERE manf = 'Anheuser-Busch';

    Note single quotes for strings.
                    name
                    Bud
                    Bud Lite
                    Michelob




                         2
Formal Semantics of Single-Relation SQL
Query
1. Start with the relation in the FROM clause.
2. Apply bag , using condition in WHERE
   clause.
3. Apply extended, bag  using terms in
   SELECT clause.

Equivalent Operational Semantics
Imagine a tuple variable ranging over all tuples of
the relation. For each tuple:
     Check if it satis es the WHERE clause.
     Print the values of terms in SELECT, if so.




                          3
Star as List of All Attributes
      Beersname, manf

      SELECT *
      FROM Beers
      WHERE manf = 'Anheuser-Busch';

          name        manf
          Bud         Anheuser-Busch
          Bud Lite    Anheuser-Busch
          Michelob    Anheuser-Busch




                       4
Renaming columns
     Beersname, manf

     SELECT name AS beer
     FROM Beers
     WHERE manf = 'Anheuser-Busch';

                 beer
                 Bud
                 Bud Lite
                 Michelob




                    5
Expressions as Values in Columns
     Sellsbar, beer, price

     SELECT bar, beer,
         price*120 AS priceInYen
     FROM Sells;

         bar     beer      priceInYen
         Joe's   Bud       300
         Sue's   Miller    360
                     
   Note no WHERE clause OK.




                       6
Trick: If you want an answer with a particular
string in each row, use that constant as an
expression.
  Likesdrinker, beer

  SELECT drinker,
      'likes Bud' AS whoLikesBud
  FROM Likes
  WHERE beer = 'Bud';

         drinker whoLikesBud
         Sally likes Bud
         Fred likes Bud
                




                    7
Example
Find the price Joe's Bar charges for Bud.
      Sellsbar, beer, price

      SELECT price
      FROM Sells
      WHERE bar = 'Joe''s Bar' AND
          beer = 'Bud';

    Note: two single-quotes in a character string
    represent one single quote.
    Conditions in WHERE clause can use logical
    operators AND, OR, NOT and parentheses in the
    usual way.
    Remember: SQL is case insensitive. Keywords
    like SELECT or AND can be written upper lower
    case as you like.
    3 Only inside quoted strings does case
         matter.




                         8
Patterns
      stands for any string.
      stands for any one character.
      Attribute LIKE pattern is a condition that
    is true if the string value of the attribute
    matches the pattern.
    3 Also NOT LIKE for negation.

Example
Find drinkers whose phone has exchange 555.
        Drinkersname, addr, phone

        SELECT name
        FROM Drinkers
        WHERE phone LIKE '555-      ';

    Note patterns must be quoted, like strings.




                        9
Nulls
In place of a value in a tuple's component.
     Interpretation is not exactly missing value.
     There could be many reasons why no value is
     present, e.g., value inappropriate.
Comparing Nulls to Values
    3rd truth value UNKNOWN.
    A query only produces tuples if the WHERE-
    condition evaluates to TRUE UNKNOWN is not
    su cent.




                        10
Example
          bar          beer     price
          Joe's bar    Bud      NULL

     SELECT bar
     FROM Sells
     WHERE price 2.00 OR price = 2.00;
         ------------      -------------
          UNKNOWN         UNKNOWN
          ------------------------
                  UNKNOWN

   Joe's Bar is not produced, even though the
   WHERE condition is a tautology.




                      11
3-Valued Logic
Think of true = 1; false = 0, and unknown = 1 2.
Then:
    AND = min.
    OR = max.
    NOTx = 1 , x.
Some Key Laws Fail to Hold
Example: Law of the excluded middle, i.e.,
      p OR NOT p = TRUE

    For 3-valued logic: if p = unknown, then left
    side = max1 2,1-1 2 = 1 2 6= 1.
    Like bag algebra, there is no way known to
    make 3-valued logic conform to all the laws we
    expect for sets 2-valued logic, respectively.




                        12
Multirelation Queries
    List of relations in FROM clause.
    Relation-dot-attribute disambiguates
    attributes from several relations.
Example
Find the beers that the frequenters of Joe's Bar
like.
      Likesdrinker, beer
      Frequentsdrinker, bar

      SELECT beer
      FROM Frequents, Likes
      WHERE bar = 'Joe''s Bar' AND
          Frequents.drinker = Likes.drinker;




                        13
Formal Semantics of Multirelation Queries
Same as for single relation, but start with the
product of all the relations mentioned in the FROM
clause.
Operational Semantics
Consider a tuple variable for each relation in the
FROM.

    Imagine these tuple variables each pointing to
    a tuple of their relation, in all combinations
    e.g., nested loops.
    If the current assignment of tuple-variables to
    tuples makes the WHERE true, then output the
    terms of the SELECT.




                        14
drinker bar           drinker beer

                           Sally
     Sally   Joe's                       l
f


                             Likes
     Frequents




                     15
Explicit Tuple Variables
Sometimes we need to refer to two or more copies
of a relation.
     Use tuple variables as aliases of the relations.
Example
Find pairs of beers by the same manufacturer.
       Beersname, manf

       SELECT b1.name, b2.name
       FROM Beers b1, Beers b2
       WHERE b1.manf = b2.manf AND
           b1.name b2.name;

    SQL permits AS between relation and its tuple
    variable; Oracle does not.
    Note that b1.name b2.name is needed to
    avoid producing Bud, Bud and to avoid
    producing a pair in both orders.




                          16
Subqueries
Result of a select-from-where query can be used in
the where-clause of another query.
Simplest Case: Subquery Returns a Single,
Unary Tuple
Find bars that serve Miller at the same price Joe
charges for Bud.
      Sellsbar, beer, price

      SELECT bar
      FROM Sells
      WHERE beer = 'Miller' AND
          price =
              SELECT price
               FROM Sells
               WHERE bar = 'Joe''s Bar' AND
                   beer = 'Bud'
              ;

    Notice the scoping rule: an attribute refers
    to the most closely nested relation with that
    attribute.
    Parentheses around subquery are essential.

                        17
The IN Operator
 Tuple IN relation is true i the tuple is in the
relation.
Example
Find the name and manufacturer of beers that
Fred likes.
      Beersname, manf
      Likesdrinker, beer

      SELECT *
      FROM Beers
      WHERE name IN
          SELECT beer
           FROM Likes
           WHERE drinker = 'Fred'
          ;

    Also:   NOT IN   .




                         18
EXISTS
      relation is true i the relation is
 EXISTS
nonempty.
Example
Find the beers that are the unique beer by their
manufacturer.
      Beersname, manf

      SELECT name
      FROM Beers b1
      WHERE NOT EXISTS
          SELECT *
          FROM Beers
          WHERE manf = b1.manf AND
              name    b1.name
      ;

    Note scoping rule: to refer to outer Beers in
    the inner subquery, we need to give the outer
    a tuple variable, b1 in this example.
    A subquery that refers to values from a
    surrounding query is called a correlated
    subquery.


                        19
Quanti ers
ANY and ALL behave as existential and universal
quanti ers, respectively.
    Beware: in common parlance, any and all
    seem to be synonyms, e.g., I am fatter than
    any of you vs. I am fatter than all of you.
    But in SQL:
Example
Find the beers sold for the highest price.
       Sellsbar, beer, price

       SELECT beer
       FROM Sells
       WHERE price = ALL
           SELECT price
           FROM Sells
       ;


Class Problem
Find the beers not sold for the lowest price.



                         20

More Related Content

More from Arjun Shanka

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
Arjun Shanka
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82Arjun Shanka
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
Arjun Shanka
 
javainheritance
javainheritancejavainheritance
javainheritance
Arjun Shanka
 
javarmi
javarmijavarmi
javarmi
Arjun Shanka
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
javapackage
javapackagejavapackage
javapackage
Arjun Shanka
 
javaarray
javaarrayjavaarray
javaarray
Arjun Shanka
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
Arjun Shanka
 
struts
strutsstruts
struts
Arjun Shanka
 
javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
Arjun Shanka
 
javanetworking
javanetworkingjavanetworking
javanetworking
Arjun Shanka
 
servlets
servletsservlets
servlets
Arjun Shanka
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
Arjun Shanka
 
javainterface
javainterfacejavainterface
javainterface
Arjun Shanka
 

More from Arjun Shanka (18)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
servlets
servletsservlets
servlets
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
 
javainterface
javainterfacejavainterface
javainterface
 

Recently uploaded

Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
bosssp10
 
Lundin Gold Corporate Presentation - June 2024
Lundin Gold Corporate Presentation - June 2024Lundin Gold Corporate Presentation - June 2024
Lundin Gold Corporate Presentation - June 2024
Adnet Communications
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
Corey Perlman, Social Media Speaker and Consultant
 
Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024
Kirill Klimov
 
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
SOFTTECHHUB
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
FelixPerez547899
 
2022 Vintage Roman Numerals Men Rings
2022 Vintage Roman  Numerals  Men  Rings2022 Vintage Roman  Numerals  Men  Rings
2022 Vintage Roman Numerals Men Rings
aragme
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
Adam Smith
 
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Holger Mueller
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
Corey Perlman, Social Media Speaker and Consultant
 
Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431
ecamare2
 
Recruiting in the Digital Age: A Social Media Masterclass
Recruiting in the Digital Age: A Social Media MasterclassRecruiting in the Digital Age: A Social Media Masterclass
Recruiting in the Digital Age: A Social Media Masterclass
LuanWise
 
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
AnnySerafinaLove
 
Income Tax exemption for Start up : Section 80 IAC
Income Tax  exemption for Start up : Section 80 IACIncome Tax  exemption for Start up : Section 80 IAC
Income Tax exemption for Start up : Section 80 IAC
CA Dr. Prithvi Ranjan Parhi
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
Top Forex Brokers Review
 
Chapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .pptChapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .ppt
ssuser567e2d
 
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdfikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
agatadrynko
 
-- June 2024 is National Volunteer Month --
-- June 2024 is National Volunteer Month ---- June 2024 is National Volunteer Month --
-- June 2024 is National Volunteer Month --
NZSG
 
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
taqyea
 
Industrial Tech SW: Category Renewal and Creation
Industrial Tech SW:  Category Renewal and CreationIndustrial Tech SW:  Category Renewal and Creation
Industrial Tech SW: Category Renewal and Creation
Christian Dahlen
 

Recently uploaded (20)

Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
 
Lundin Gold Corporate Presentation - June 2024
Lundin Gold Corporate Presentation - June 2024Lundin Gold Corporate Presentation - June 2024
Lundin Gold Corporate Presentation - June 2024
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
 
Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024
 
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
Hamster Kombat' Telegram Game Surpasses 100 Million Players—Token Release Sch...
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
 
2022 Vintage Roman Numerals Men Rings
2022 Vintage Roman  Numerals  Men  Rings2022 Vintage Roman  Numerals  Men  Rings
2022 Vintage Roman Numerals Men Rings
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
 
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
 
Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431Observation Lab PowerPoint Assignment for TEM 431
Observation Lab PowerPoint Assignment for TEM 431
 
Recruiting in the Digital Age: A Social Media Masterclass
Recruiting in the Digital Age: A Social Media MasterclassRecruiting in the Digital Age: A Social Media Masterclass
Recruiting in the Digital Age: A Social Media Masterclass
 
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
Anny Serafina Love - Letter of Recommendation by Kellen Harkins, MS.
 
Income Tax exemption for Start up : Section 80 IAC
Income Tax  exemption for Start up : Section 80 IACIncome Tax  exemption for Start up : Section 80 IAC
Income Tax exemption for Start up : Section 80 IAC
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
 
Chapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .pptChapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .ppt
 
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdfikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
 
-- June 2024 is National Volunteer Month --
-- June 2024 is National Volunteer Month ---- June 2024 is National Volunteer Month --
-- June 2024 is National Volunteer Month --
 
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
一比一原版新西兰奥塔哥大学毕业证(otago毕业证)如何办理
 
Industrial Tech SW: Category Renewal and Creation
Industrial Tech SW:  Category Renewal and CreationIndustrial Tech SW:  Category Renewal and Creation
Industrial Tech SW: Category Renewal and Creation
 

slides6

  • 1. SQL Queries Principal form: SELECT desired attributes FROM tuple variables | range over relations WHERE condition about t.v.'s; Running example relation schema: Beersname, manf Barsname, addr, license Drinkersname, addr, phone Likesdrinker, beer Sellsbar, beer, price Frequentsdrinker, bar 1
  • 2. Example What beers are made by Anheuser-Busch? Beersname, manf SELECT name FROM Beers WHERE manf = 'Anheuser-Busch'; Note single quotes for strings. name Bud Bud Lite Michelob 2
  • 3. Formal Semantics of Single-Relation SQL Query 1. Start with the relation in the FROM clause. 2. Apply bag , using condition in WHERE clause. 3. Apply extended, bag using terms in SELECT clause. Equivalent Operational Semantics Imagine a tuple variable ranging over all tuples of the relation. For each tuple: Check if it satis es the WHERE clause. Print the values of terms in SELECT, if so. 3
  • 4. Star as List of All Attributes Beersname, manf SELECT * FROM Beers WHERE manf = 'Anheuser-Busch'; name manf Bud Anheuser-Busch Bud Lite Anheuser-Busch Michelob Anheuser-Busch 4
  • 5. Renaming columns Beersname, manf SELECT name AS beer FROM Beers WHERE manf = 'Anheuser-Busch'; beer Bud Bud Lite Michelob 5
  • 6. Expressions as Values in Columns Sellsbar, beer, price SELECT bar, beer, price*120 AS priceInYen FROM Sells; bar beer priceInYen Joe's Bud 300 Sue's Miller 360 Note no WHERE clause OK. 6
  • 7. Trick: If you want an answer with a particular string in each row, use that constant as an expression. Likesdrinker, beer SELECT drinker, 'likes Bud' AS whoLikesBud FROM Likes WHERE beer = 'Bud'; drinker whoLikesBud Sally likes Bud Fred likes Bud 7
  • 8. Example Find the price Joe's Bar charges for Bud. Sellsbar, beer, price SELECT price FROM Sells WHERE bar = 'Joe''s Bar' AND beer = 'Bud'; Note: two single-quotes in a character string represent one single quote. Conditions in WHERE clause can use logical operators AND, OR, NOT and parentheses in the usual way. Remember: SQL is case insensitive. Keywords like SELECT or AND can be written upper lower case as you like. 3 Only inside quoted strings does case matter. 8
  • 9. Patterns stands for any string. stands for any one character. Attribute LIKE pattern is a condition that is true if the string value of the attribute matches the pattern. 3 Also NOT LIKE for negation. Example Find drinkers whose phone has exchange 555. Drinkersname, addr, phone SELECT name FROM Drinkers WHERE phone LIKE '555- '; Note patterns must be quoted, like strings. 9
  • 10. Nulls In place of a value in a tuple's component. Interpretation is not exactly missing value. There could be many reasons why no value is present, e.g., value inappropriate. Comparing Nulls to Values 3rd truth value UNKNOWN. A query only produces tuples if the WHERE- condition evaluates to TRUE UNKNOWN is not su cent. 10
  • 11. Example bar beer price Joe's bar Bud NULL SELECT bar FROM Sells WHERE price 2.00 OR price = 2.00; ------------ ------------- UNKNOWN UNKNOWN ------------------------ UNKNOWN Joe's Bar is not produced, even though the WHERE condition is a tautology. 11
  • 12. 3-Valued Logic Think of true = 1; false = 0, and unknown = 1 2. Then: AND = min. OR = max. NOTx = 1 , x. Some Key Laws Fail to Hold Example: Law of the excluded middle, i.e., p OR NOT p = TRUE For 3-valued logic: if p = unknown, then left side = max1 2,1-1 2 = 1 2 6= 1. Like bag algebra, there is no way known to make 3-valued logic conform to all the laws we expect for sets 2-valued logic, respectively. 12
  • 13. Multirelation Queries List of relations in FROM clause. Relation-dot-attribute disambiguates attributes from several relations. Example Find the beers that the frequenters of Joe's Bar like. Likesdrinker, beer Frequentsdrinker, bar SELECT beer FROM Frequents, Likes WHERE bar = 'Joe''s Bar' AND Frequents.drinker = Likes.drinker; 13
  • 14. Formal Semantics of Multirelation Queries Same as for single relation, but start with the product of all the relations mentioned in the FROM clause. Operational Semantics Consider a tuple variable for each relation in the FROM. Imagine these tuple variables each pointing to a tuple of their relation, in all combinations e.g., nested loops. If the current assignment of tuple-variables to tuples makes the WHERE true, then output the terms of the SELECT. 14
  • 15. drinker bar drinker beer Sally Sally Joe's l f Likes Frequents 15
  • 16. Explicit Tuple Variables Sometimes we need to refer to two or more copies of a relation. Use tuple variables as aliases of the relations. Example Find pairs of beers by the same manufacturer. Beersname, manf SELECT b1.name, b2.name FROM Beers b1, Beers b2 WHERE b1.manf = b2.manf AND b1.name b2.name; SQL permits AS between relation and its tuple variable; Oracle does not. Note that b1.name b2.name is needed to avoid producing Bud, Bud and to avoid producing a pair in both orders. 16
  • 17. Subqueries Result of a select-from-where query can be used in the where-clause of another query. Simplest Case: Subquery Returns a Single, Unary Tuple Find bars that serve Miller at the same price Joe charges for Bud. Sellsbar, beer, price SELECT bar FROM Sells WHERE beer = 'Miller' AND price = SELECT price FROM Sells WHERE bar = 'Joe''s Bar' AND beer = 'Bud' ; Notice the scoping rule: an attribute refers to the most closely nested relation with that attribute. Parentheses around subquery are essential. 17
  • 18. The IN Operator Tuple IN relation is true i the tuple is in the relation. Example Find the name and manufacturer of beers that Fred likes. Beersname, manf Likesdrinker, beer SELECT * FROM Beers WHERE name IN SELECT beer FROM Likes WHERE drinker = 'Fred' ; Also: NOT IN . 18
  • 19. EXISTS relation is true i the relation is EXISTS nonempty. Example Find the beers that are the unique beer by their manufacturer. Beersname, manf SELECT name FROM Beers b1 WHERE NOT EXISTS SELECT * FROM Beers WHERE manf = b1.manf AND name b1.name ; Note scoping rule: to refer to outer Beers in the inner subquery, we need to give the outer a tuple variable, b1 in this example. A subquery that refers to values from a surrounding query is called a correlated subquery. 19
  • 20. Quanti ers ANY and ALL behave as existential and universal quanti ers, respectively. Beware: in common parlance, any and all seem to be synonyms, e.g., I am fatter than any of you vs. I am fatter than all of you. But in SQL: Example Find the beers sold for the highest price. Sellsbar, beer, price SELECT beer FROM Sells WHERE price = ALL SELECT price FROM Sells ; Class Problem Find the beers not sold for the lowest price. 20