SlideShare uma empresa Scribd logo
1 de 31
Lecture 02: Basic SQL




                  1
Outline
• Data in SQL
• Simple Queries in SQL
• Queries with more than one relation

Reading:
• Chapter 3, “Simple Queries” from SQL for Web Nerds,
  by Philip Greenspun http://philip.greenspun.com/sql/



                                           2
SQL Introduction
Standard language for querying and manipulating data

         Structured Query Language

Many standards out there:
• ANSI SQL
• SQL92 (a.k.a. SQL2)
• SQL99 (a.k.a. SQL3)
• Vendors support various subsets of these
• What we discuss is common to all of them


                                                3
SQL
• Data Definition Language (DDL)
  – Create/alter/delete tables and their attributes
  – Following lectures...
• Data Manipulation Language (DML)
  – Query one or more tables – discussed next !
  – Insert/delete/modify tuples in tables
• Transact-SQL
  – Idea: package a sequence of SQL statements  server
  – Won’t discuss in class

                                                4
Data in SQL
1. Atomic types, a.k.a. data types
2. Tables built from atomic types




                                     5
Data Types in SQL
•    Characters:
    –   CHAR(20)            -- fixed length
    –   VARCHAR(40)         -- variable length
•    Numbers:
    –   BIGINT, INT, SMALLINT, TINYINT
    –   REAL, FLOAT      -- differ in precision
    –   MONEY
•    Times and dates:
    –   DATE
    –   DATETIME            -- SQL Server
•    Others... All are simple                    6
Table name                           Attribute names

                   Tables in SQL
Product

          PName       Price     Category       Manufacturer

          Gizmo      $19.99     Gadgets        GizmoWorks

     Powergizmo      $29.99     Gadgets        GizmoWorks

     SingleTouch     $149.99   Photography        Canon

     MultiTouch      $203.99   Household         Hitachi


Tuples or rows                             7
Tables Explained
• A tuple = a record
   – Restriction: all attributes are of atomic type
• A table = a set of tuples
   – Like a list…
   – …but it is unorderd: no first(), no next(), no last().
• No nested tables, only flat tables are allowed !
   – We will see later how to decompose complex structures
     into multiple flat tables


                                                 8
Tables Explained
• The schema of a table is the table name and
  its attributes:
Product(PName, Price, Category, Manfacturer)

• A key is an attribute whose values are unique;
  we underline a key

Product(PName, Price, Category, Manfacturer)
                                     9
SQL Query


Basic form: (plus many many more bells and whistles)


       SELECT attributes
       SELECT attributes
       FROM relations (possibly multiple, joined)
       FROM relations (possibly multiple, joined)
       WHERE conditions (selections)
       WHERE conditions (selections)



                                               10
Simple SQL Query
               Product     PName        Price     Category     Manufacturer
                            Gizmo      $19.99     Gadgets      GizmoWorks
                         Powergizmo    $29.99     Gadgets      GizmoWorks
                         SingleTouch   $149.99   Photography      Canon
                          MultiTouch   $203.99   Household        Hitachi

SELECT
SELECT   **
FROM
FROM     Product
          Product
WHERE
WHERE    category=‘Gadgets’
          category=‘Gadgets’
                           PName       Price     Category      Manufacturer
                           Gizmo       $19.99     Gadgets      GizmoWorks
                         Powergizmo    $29.99     Gadgets      GizmoWorks
 “selection”
                                                     11
Simple SQL Query
               Product     PName            Price             Category      Manufacturer
                           Gizmo            $19.99            Gadgets        GizmoWorks
                         Powergizmo         $29.99            Gadgets        GizmoWorks
                         SingleTouch      $149.99        Photography               Canon
                         MultiTouch       $203.99         Household              Hitachi

SELECT
SELECT   PName, Price, Manufacturer
          PName, Price, Manufacturer
FROM
FROM     Product
          Product
WHERE
WHERE    Price > 100
         Price > 100
                                    PName             Price         Manufacturer
  “selection” and                SingleTouch         $149.99             Canon
   “projection”                    MultiTouch        $203.99             Hitachi

                                                                 12
A Notation for SQL Queries
                                                   Input Schema



                           Product(PName, Price, Category, Manfacturer)

SELECT
SELECT   Name, Price, Manufacturer
          Name, Price, Manufacturer
FROM
FROM     Product
          Product
WHERE
WHERE    Price > 100
         Price > 100
                                 Answer(PName, Price, Manfacturer)


                           Output Schema          13
Selections
What goes in the WHERE clause:
• x = y, x < y, x <= y, etc
   – For number, they have the usual meanings
   – For CHAR and VARCHAR: lexicographic ordering
      • Expected conversion between CHAR and VARCHAR
   – For dates and times, what you expect...
• Pattern matching on strings: s LIKE p (next)



                                               14
The LIKE operator
•    s LIKE p: pattern matching on strings
•    p may contain two special symbols:
    –    % = any sequence of characters
    –    _ = any single character

Product(Name, Price, Category, Manufacturer)
Find all products whose name mentions ‘gizmo’:

         SELECT
          SELECT    **
         FROM
          FROM      Products
                     Products
         WHERE
          WHERE     PName LIKE ‘%gizmo%’
                     PName LIKE ‘%gizmo%’

                                                 15
Eliminating Duplicates
                            Category
SELECT DISTINCT category
SELECT DISTINCT category    Gadgets
FROM Product
FROM Product               Photography
                           Household



    Compare to:
                             Category
                             Gadgets
SELECT category
SELECT category              Gadgets
FROM Product
FROM Product               Photography
                            Household


                             16
Ordering the Results
  SELECT pname, price, manufacturer
  SELECT pname, price, manufacturer
  FROM Product
  FROM Product
  WHERE category=‘gizmo’ AND price > 50
  WHERE category=‘gizmo’ AND price > 50
  ORDER BY price, pname
  ORDER BY price, pname

Ordering is ascending, unless you specify the DESC keyword.

Ties are broken by the second attribute on the ORDER BY list, etc.



                                                 17
Ordering the Results
     SELECT Category
     SELECT Category
     FROM Product
     FROM Product
     ORDER BY PName
     ORDER BY PName


  PName        Price     Category     Manufacturer



                                                          ?
  Gizmo       $19.99     Gadgets      GizmoWorks
Powergizmo    $29.99     Gadgets      GizmoWorks
SingleTouch   $149.99   Photography      Canon
MultiTouch    $203.99   Household       Hitachi



                                                     18
Ordering the Results
                            Category
SELECT DISTINCT category
SELECT DISTINCT category    Gadgets
FROM Product
FROM Product               Household
ORDER BY category
ORDER BY category          Photography



    Compare to:

SELECT DISTINCT category

                               ?
SELECT DISTINCT category
FROM Product
FROM Product
ORDER BY PName
ORDER BY PName

                             19
Joins in SQL
 • Connect two or more tables:
Product      PName           Price      Category      Manufacturer
             Gizmo          $19.99      Gadgets        GizmoWorks
           Powergizmo       $29.99      Gadgets        GizmoWorks
           SingleTouch      $149.99    Photography         Canon
           MultiTouch       $203.99    Household           Hitachi

             Company        CName        StockPrice          Country

                          GizmoWorks        25                 USA
     What is
 the Connection             Canon           65                Japan
     between
      them ?                Hitachi         15                Japan
                                                      20
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)

Find all products under $200 manufactured in Japan;
return their names and prices.
                                                Join
                                         between Product
  SELECT PName, Price
   SELECT PName, Price                     and Company
  FROM
   FROM Product, Company
              Product, Company
  WHERE Manufacturer=CName AND Country=‘Japan’
   WHERE Manufacturer=CName AND Country=‘Japan’
              AND Price <= 200
              AND Price <= 200

                                            21
Joins in SQL
Product                                              Company
   PName       Price     Category     Manufacturer       Cname             StockPrice           Country
   Gizmo      $19.99     Gadgets      GizmoWorks       GizmoWorks                25              USA
Powergizmo    $29.99     Gadgets      GizmoWorks         Canon                   65              Japan
SingleTouch   $149.99   Photography      Canon           Hitachi                 15              Japan
MultiTouch    $203.99   Household       Hitachi




  SELECT PName, Price
   SELECT PName, Price
  FROM Product, Company
   FROM Product, Company
  WHERE Manufacturer=CName AND Country=‘Japan’
   WHERE Manufacturer=CName AND Country=‘Japan’
         AND Price <= 200
          AND Price <= 200

                                                                     PName             Price
                                                                   SingleTouch        $149.99


                                                                          22
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)

Find all countries that manufacture some product in the
‘Gadgets’ category.


SELECT
SELECT    Country
           Country
FROM
FROM      Product, Company
          Product, Company
WHERE
WHERE     Manufacturer=CName AND Category=‘Gadgets’
          Manufacturer=CName AND Category=‘Gadgets’



                                             23
Joins in SQL
Product                                              Company
   PName       Price      Category    Manufacturer       Cname      StockPrice   Country
   Gizmo       $19.99     Gadgets     GizmoWorks       GizmoWorks      25         USA
Powergizmo     $29.99     Gadgets     GizmoWorks         Canon         65         Japan
SingleTouch   $149.99   Photography      Canon           Hitachi       15         Japan
MultiTouch    $203.99   Household       Hitachi




      SELECT Country
       SELECT Country
      FROM Product, Company
       FROM Product, Company
      WHERE Manufacturer=CName AND Category=‘Gadgets’
       WHERE Manufacturer=CName AND Category=‘Gadgets’

                                                                       Country
             What is                                                        ??
          the problem ?                                                     ??
            What’s the
            solution ?
                                                                    24
Joins
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)

Find names of people living in Seattle that bought some
product in the ‘Gadgets’ category, and the names of the
stores they bought such product from


  SELECT
  SELECT    DISTINCT persname, store
             DISTINCT persname, store
  FROM
  FROM      Person, Purchase, Product
             Person, Purchase, Product
  WHERE
  WHERE     persname=buyer AND product = pname AND
             persname=buyer AND product = pname AND
            city=‘Seattle’ AND category=‘Gadgets’
             city=‘Seattle’ AND category=‘Gadgets’
                                          25
Disambiguating Attributes
• Sometimes two relations have the same attr:
  Person(pname, address, worksfor)
  Company(cname, address)
                                        Which
SELECT
SELECT   DISTINCT pname, address
          DISTINCT pname, address      address ?
FROM
FROM     Person, Company
         Person, Company
WHERE
WHERE    worksfor = cname
         worksfor = cname


SELECT
SELECT   DISTINCT Person.pname, Company.address
          DISTINCT Person.pname, Company.address
FROM
FROM     Person, Company
          Person, Company
WHERE
WHERE    Person.worksfor = Company.cname 26
         Person.worksfor = Company.cname
Tuple Variables
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find all stores that sold at least one product that the store
‘BestBuy’ also sold:

  SELECT DISTINCT x.store
  SELECT DISTINCT x.store
  FROM Purchase AS x, Purchase AS y
  FROM Purchase AS x, Purchase AS y
  WHERE x.product = y.product AND y.store = ‘BestBuy’
  WHERE x.product = y.product AND y.store = ‘BestBuy’



     Answer (store)
                                                      27
General rule:
               Tuple Variables
tuple variables introduced automatically by the system:

Product ( name, price, category, manufacturer)
               SELECT name
               SELECT name
               FROM Product
               FROM Product
               WHERE price > 100
               WHERE price > 100
Becomes:

                SELECT Product.name
                SELECT Product.name
                FROM Product AS Product
                FROM Product AS Product
                WHERE Product.price > 100
                WHERE Product.price > 100

Doesn’t work when Product occurs more than once:
In that case the user needs to define variables 28
Meaning (Semantics) of SQL
               Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions

1. Nested loops:
 Answer = {}
  Answer = {}
 for x1 in R1 do
  for x1 in R1 do
     for x2 in R2 do
      for x2 in R2 do
        …..
         …..
            for xn in Rn do
             for xn in Rn do
                 if Conditions
                  if Conditions
                      then Answer = Answer ∪ {(a1,…,ak)}
                       then Answer = Answer ∪ {(a1,…,ak)}
 return Answer
  return Answer                                  29
Meaning (Semantics) of SQL
             Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions

 2. Parallel assignment
Answer = {}
 Answer = {}
for all assignments x1 in R1, …, xn in Rn do
 for all assignments x1 in R1, …, xn in Rn do
     if Conditions then Answer = Answer ∪ {(a1,…,ak)}
      if Conditions then Answer = Answer ∪ {(a1,…,ak)}
return Answer
 return Answer


Doesn’t impose any order !
                                             30
First Unintuitive SQLism
SELECT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A


Looking for R ∩ (S ∪ T)

But what happens if T is empty?




                                  31

Mais conteúdo relacionado

Mais procurados

sSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxsSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxNidhi Mehra
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignYoung-Ho Cho
 
Python Environment Setup and Essentials modified.pptx
Python Environment Setup and Essentials modified.pptxPython Environment Setup and Essentials modified.pptx
Python Environment Setup and Essentials modified.pptxAnup Kelkar
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu SharmaMayank Sharma
 
POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE teachersduniya.com
 

Mais procurados (11)

sSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxsSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptx
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
iOS 메모리관리
iOS 메모리관리iOS 메모리관리
iOS 메모리관리
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Python Environment Setup and Essentials modified.pptx
Python Environment Setup and Essentials modified.pptxPython Environment Setup and Essentials modified.pptx
Python Environment Setup and Essentials modified.pptx
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE
 

Destaque

Basic c operators
Basic c operatorsBasic c operators
Basic c operatorsAnuja Lad
 
Final exam review answer(networking)
Final exam review answer(networking)Final exam review answer(networking)
Final exam review answer(networking)welcometofacebook
 
Basic networking hardware pre final 1
Basic networking hardware pre final 1Basic networking hardware pre final 1
Basic networking hardware pre final 1Anuja Lad
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answersvijaybusu
 

Destaque (7)

Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Final exam review answer(networking)
Final exam review answer(networking)Final exam review answer(networking)
Final exam review answer(networking)
 
Basic networking hardware pre final 1
Basic networking hardware pre final 1Basic networking hardware pre final 1
Basic networking hardware pre final 1
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Sql ppt
Sql pptSql ppt
Sql ppt
 

Semelhante a Slides 2-basic sql

Oracle SQL ppt.ppt
Oracle SQL ppt.pptOracle SQL ppt.ppt
Oracle SQL ppt.pptMushDev
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptxJEEVA R
 
Lecture sql
Lecture sqlLecture sql
Lecture sqlSini
 
Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptSajjadAbdullah4
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Serverkrishna43511
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners21awais
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.pptErick Araújo
 
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.pptLaviKushwaha
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentationJKarthickMyilvahanan
 

Semelhante a Slides 2-basic sql (19)

SQL Basic Queries
SQL Basic Queries SQL Basic Queries
SQL Basic Queries
 
sql-basic.ppt
sql-basic.pptsql-basic.ppt
sql-basic.ppt
 
Oracle SQL ppt.ppt
Oracle SQL ppt.pptOracle SQL ppt.ppt
Oracle SQL ppt.ppt
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptx
 
Sql
SqlSql
Sql
 
Lecture sql
Lecture sqlLecture sql
Lecture sql
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.ppt
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Server
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners
 
Data
DataData
Data
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.ppt
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.ppt
 
Xamppinstallation edited
Xamppinstallation editedXamppinstallation edited
Xamppinstallation edited
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
 

Mais de Anuja Lad

Important topic in board exams
Important topic in board examsImportant topic in board exams
Important topic in board examsAnuja Lad
 
Data communication
Data communicationData communication
Data communicationAnuja Lad
 
Data communication intro
Data communication introData communication intro
Data communication introAnuja Lad
 
Questions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingQuestions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingAnuja Lad
 
T y b com question paper of mumbai university
T y b com question paper of mumbai universityT y b com question paper of mumbai university
T y b com question paper of mumbai universityAnuja Lad
 
Questions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingQuestions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingAnuja Lad
 
T y b com question paper of mumbai university
T y b com question paper of mumbai universityT y b com question paper of mumbai university
T y b com question paper of mumbai universityAnuja Lad
 
Basic networking hardware pre final 1
Basic networking hardware pre final 1Basic networking hardware pre final 1
Basic networking hardware pre final 1Anuja Lad
 
Data communication
Data communicationData communication
Data communicationAnuja Lad
 
Data communication intro
Data communication introData communication intro
Data communication introAnuja Lad
 
Intro net 91407
Intro net 91407Intro net 91407
Intro net 91407Anuja Lad
 
Itmg360 chapter one_v05
Itmg360 chapter one_v05Itmg360 chapter one_v05
Itmg360 chapter one_v05Anuja Lad
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510Anuja Lad
 
Lab 4 excel basics
Lab 4 excel basicsLab 4 excel basics
Lab 4 excel basicsAnuja Lad
 
Introductionto excel2007
Introductionto excel2007Introductionto excel2007
Introductionto excel2007Anuja Lad
 
5 intro to networking
5 intro to networking5 intro to networking
5 intro to networkingAnuja Lad
 
1 introduction-to-computer-networking
1 introduction-to-computer-networking1 introduction-to-computer-networking
1 introduction-to-computer-networkingAnuja Lad
 

Mais de Anuja Lad (20)

Important topic in board exams
Important topic in board examsImportant topic in board exams
Important topic in board exams
 
Data communication
Data communicationData communication
Data communication
 
Data communication intro
Data communication introData communication intro
Data communication intro
 
Questions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingQuestions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networking
 
T y b com question paper of mumbai university
T y b com question paper of mumbai universityT y b com question paper of mumbai university
T y b com question paper of mumbai university
 
Questions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networkingQuestions from chapter 1 data communication and networking
Questions from chapter 1 data communication and networking
 
T y b com question paper of mumbai university
T y b com question paper of mumbai universityT y b com question paper of mumbai university
T y b com question paper of mumbai university
 
Basic networking hardware pre final 1
Basic networking hardware pre final 1Basic networking hardware pre final 1
Basic networking hardware pre final 1
 
Data communication
Data communicationData communication
Data communication
 
Data communication intro
Data communication introData communication intro
Data communication intro
 
Intro net 91407
Intro net 91407Intro net 91407
Intro net 91407
 
Itmg360 chapter one_v05
Itmg360 chapter one_v05Itmg360 chapter one_v05
Itmg360 chapter one_v05
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
Lab 4 excel basics
Lab 4 excel basicsLab 4 excel basics
Lab 4 excel basics
 
Mysql2
Mysql2Mysql2
Mysql2
 
Introductionto excel2007
Introductionto excel2007Introductionto excel2007
Introductionto excel2007
 
C tutorial
C tutorialC tutorial
C tutorial
 
C
CC
C
 
5 intro to networking
5 intro to networking5 intro to networking
5 intro to networking
 
1 introduction-to-computer-networking
1 introduction-to-computer-networking1 introduction-to-computer-networking
1 introduction-to-computer-networking
 

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Slides 2-basic sql

  • 2. Outline • Data in SQL • Simple Queries in SQL • Queries with more than one relation Reading: • Chapter 3, “Simple Queries” from SQL for Web Nerds, by Philip Greenspun http://philip.greenspun.com/sql/ 2
  • 3. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: • ANSI SQL • SQL92 (a.k.a. SQL2) • SQL99 (a.k.a. SQL3) • Vendors support various subsets of these • What we discuss is common to all of them 3
  • 4. SQL • Data Definition Language (DDL) – Create/alter/delete tables and their attributes – Following lectures... • Data Manipulation Language (DML) – Query one or more tables – discussed next ! – Insert/delete/modify tuples in tables • Transact-SQL – Idea: package a sequence of SQL statements  server – Won’t discuss in class 4
  • 5. Data in SQL 1. Atomic types, a.k.a. data types 2. Tables built from atomic types 5
  • 6. Data Types in SQL • Characters: – CHAR(20) -- fixed length – VARCHAR(40) -- variable length • Numbers: – BIGINT, INT, SMALLINT, TINYINT – REAL, FLOAT -- differ in precision – MONEY • Times and dates: – DATE – DATETIME -- SQL Server • Others... All are simple 6
  • 7. Table name Attribute names Tables in SQL Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Tuples or rows 7
  • 8. Tables Explained • A tuple = a record – Restriction: all attributes are of atomic type • A table = a set of tuples – Like a list… – …but it is unorderd: no first(), no next(), no last(). • No nested tables, only flat tables are allowed ! – We will see later how to decompose complex structures into multiple flat tables 8
  • 9. Tables Explained • The schema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer) • A key is an attribute whose values are unique; we underline a key Product(PName, Price, Category, Manfacturer) 9
  • 10. SQL Query Basic form: (plus many many more bells and whistles) SELECT attributes SELECT attributes FROM relations (possibly multiple, joined) FROM relations (possibly multiple, joined) WHERE conditions (selections) WHERE conditions (selections) 10
  • 11. Simple SQL Query Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT SELECT ** FROM FROM Product Product WHERE WHERE category=‘Gadgets’ category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks “selection” 11
  • 12. Simple SQL Query Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT SELECT PName, Price, Manufacturer PName, Price, Manufacturer FROM FROM Product Product WHERE WHERE Price > 100 Price > 100 PName Price Manufacturer “selection” and SingleTouch $149.99 Canon “projection” MultiTouch $203.99 Hitachi 12
  • 13. A Notation for SQL Queries Input Schema Product(PName, Price, Category, Manfacturer) SELECT SELECT Name, Price, Manufacturer Name, Price, Manufacturer FROM FROM Product Product WHERE WHERE Price > 100 Price > 100 Answer(PName, Price, Manfacturer) Output Schema 13
  • 14. Selections What goes in the WHERE clause: • x = y, x < y, x <= y, etc – For number, they have the usual meanings – For CHAR and VARCHAR: lexicographic ordering • Expected conversion between CHAR and VARCHAR – For dates and times, what you expect... • Pattern matching on strings: s LIKE p (next) 14
  • 15. The LIKE operator • s LIKE p: pattern matching on strings • p may contain two special symbols: – % = any sequence of characters – _ = any single character Product(Name, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT SELECT ** FROM FROM Products Products WHERE WHERE PName LIKE ‘%gizmo%’ PName LIKE ‘%gizmo%’ 15
  • 16. Eliminating Duplicates Category SELECT DISTINCT category SELECT DISTINCT category Gadgets FROM Product FROM Product Photography Household Compare to: Category Gadgets SELECT category SELECT category Gadgets FROM Product FROM Product Photography Household 16
  • 17. Ordering the Results SELECT pname, price, manufacturer SELECT pname, price, manufacturer FROM Product FROM Product WHERE category=‘gizmo’ AND price > 50 WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname ORDER BY price, pname Ordering is ascending, unless you specify the DESC keyword. Ties are broken by the second attribute on the ORDER BY list, etc. 17
  • 18. Ordering the Results SELECT Category SELECT Category FROM Product FROM Product ORDER BY PName ORDER BY PName PName Price Category Manufacturer ? Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi 18
  • 19. Ordering the Results Category SELECT DISTINCT category SELECT DISTINCT category Gadgets FROM Product FROM Product Household ORDER BY category ORDER BY category Photography Compare to: SELECT DISTINCT category ? SELECT DISTINCT category FROM Product FROM Product ORDER BY PName ORDER BY PName 19
  • 20. Joins in SQL • Connect two or more tables: Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Company CName StockPrice Country GizmoWorks 25 USA What is the Connection Canon 65 Japan between them ? Hitachi 15 Japan 20
  • 21. Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. Join between Product SELECT PName, Price SELECT PName, Price and Company FROM FROM Product, Company Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 AND Price <= 200 21
  • 22. Joins in SQL Product Company PName Price Category Manufacturer Cname StockPrice Country Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan SingleTouch $149.99 Photography Canon Hitachi 15 Japan MultiTouch $203.99 Household Hitachi SELECT PName, Price SELECT PName, Price FROM Product, Company FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 AND Price <= 200 PName Price SingleTouch $149.99 22
  • 23. Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT SELECT Country Country FROM FROM Product, Company Product, Company WHERE WHERE Manufacturer=CName AND Category=‘Gadgets’ Manufacturer=CName AND Category=‘Gadgets’ 23
  • 24. Joins in SQL Product Company PName Price Category Manufacturer Cname StockPrice Country Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan SingleTouch $149.99 Photography Canon Hitachi 15 Japan MultiTouch $203.99 Household Hitachi SELECT Country SELECT Country FROM Product, Company FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’ WHERE Manufacturer=CName AND Category=‘Gadgets’ Country What is ?? the problem ? ?? What’s the solution ? 24
  • 25. Joins Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT SELECT DISTINCT persname, store DISTINCT persname, store FROM FROM Person, Purchase, Product Person, Purchase, Product WHERE WHERE persname=buyer AND product = pname AND persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’ city=‘Seattle’ AND category=‘Gadgets’ 25
  • 26. Disambiguating Attributes • Sometimes two relations have the same attr: Person(pname, address, worksfor) Company(cname, address) Which SELECT SELECT DISTINCT pname, address DISTINCT pname, address address ? FROM FROM Person, Company Person, Company WHERE WHERE worksfor = cname worksfor = cname SELECT SELECT DISTINCT Person.pname, Company.address DISTINCT Person.pname, Company.address FROM FROM Person, Company Person, Company WHERE WHERE Person.worksfor = Company.cname 26 Person.worksfor = Company.cname
  • 27. Tuple Variables Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find all stores that sold at least one product that the store ‘BestBuy’ also sold: SELECT DISTINCT x.store SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ WHERE x.product = y.product AND y.store = ‘BestBuy’ Answer (store) 27
  • 28. General rule: Tuple Variables tuple variables introduced automatically by the system: Product ( name, price, category, manufacturer) SELECT name SELECT name FROM Product FROM Product WHERE price > 100 WHERE price > 100 Becomes: SELECT Product.name SELECT Product.name FROM Product AS Product FROM Product AS Product WHERE Product.price > 100 WHERE Product.price > 100 Doesn’t work when Product occurs more than once: In that case the user needs to define variables 28
  • 29. Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 1. Nested loops: Answer = {} Answer = {} for x1 in R1 do for x1 in R1 do for x2 in R2 do for x2 in R2 do ….. ….. for xn in Rn do for xn in Rn do if Conditions if Conditions then Answer = Answer ∪ {(a1,…,ak)} then Answer = Answer ∪ {(a1,…,ak)} return Answer return Answer 29
  • 30. Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 2. Parallel assignment Answer = {} Answer = {} for all assignments x1 in R1, …, xn in Rn do for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer ∪ {(a1,…,ak)} if Conditions then Answer = Answer ∪ {(a1,…,ak)} return Answer return Answer Doesn’t impose any order ! 30
  • 31. First Unintuitive SQLism SELECT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A Looking for R ∩ (S ∪ T) But what happens if T is empty? 31