SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Structured Query Language
1   Introduction to SQL
    What is SQL?
    – When a user wants to get some information
      from a database file, he can issue a query.
    – A query is a user–request to retrieve data or
      information with a certain condition.
    – SQL is a query language that allows user to
      specify the conditions. (instead of algorithms)
1   Introduction to SQL
    Concept of SQL

– The user specifies a certain condition.
– The program will go through all the records
  in the database file and select those records
  that satisfy the condition.(searching).
– Statistical information of the data.
– The result of the query will then be stored in
  form of a table.
1   Introduction to SQL
    How to involve SQL in FoxPro
    – Before using SQL, the tables should be
      opened.
    – The SQL command can be entered directly
      in the Command Window
    – To perform exact matching, we should
      SET ANSI ON
2   Basic structure of an SQL
    query
     General         SELECT, ALL / DISTINCT, *,
     Structure       AS, FROM, WHERE

     Comparison      IN, BETWEEN, LIKE "% _"

     Grouping        GROUP BY, HAVING,
                     COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

     Display Order   ORDER BY, ASC / DESC

     Logical         AND, OR, NOT
     Operators

     Output          INTO TABLE / CURSOR
                     TO FILE [ADDITIVE], TO PRINTER, TO SCREEN

     Union           UNION
2   The Situation:
    Student Particulars
     field       type      width   contents
     id          numeric     4     student id number
     name        character  10     name
     dob         date        8     date of birth
     sex         character   1     sex: M / F
     class       character   2     class
     hcode       character   1     house code: R, Y, B, G
     dcode       character   3     district code
     remission   logical     1     fee remission
     mtest       numeric     2     Math test score
I   General Structure


    SELECT ...... FROM ...... WHERE ......
    SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
    FROM tablename WHERE condition
I     General Structure
     SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
     FROM tablename WHERE condition
    – The query will select rows from the source tablename
      and output the result in table form.
    – Expressions expr1, expr2 can be :
       • (1) a column, or
       • (2) an expression of functions and fields.

    – And col1, col2 are their corresponding column names in the
      output table.
I     General Structure
     SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
     FROM tablename WHERE condition
    – DISTINCT will eliminate duplication in the output while
      ALL will keep all duplicated rows.
– condition can be :
   • (1) an inequality, or
   • (2) a string comparison
   • using logical operators AND, OR, NOT.
I       General Structure
       Before using SQL, open the student file:
         USE student
 eg. 1  List all the student records.
            SELECT * FROM student

          id name       dob        sex   class   mtest   hcode   dcode   remission
Result    9801 Peter    06/04/86   M     1A      70      R       SSP     .F.
          9802 Mary     01/10/86   F     1A      92      Y       HHM     .F.
          9803 Johnny   03/16/86   M     1A      91      G       SSP     .T.
          9804 Wendy    07/09/86   F     1B      84      B       YMT     .F.
          9805 Tobe     10/17/86   M     1B      88      R       YMT     .F.
          :    :        :          :     :       :       :       :       :
I
eg. 2
        General Structure
         List the names and house code of 1A students.

          SELECT name, hcode, class FROM student ;
          WHERE class="1A"

           Class                         Class
            1A                          1A

                      class="1A" 
            1A                           1A
            1A                          1A
            1B                          1B
            1B                          1B
             :                            :
I
eg. 2
         General Structure
           List the names and house code of 1A students.


        Result      name     hcode   class
                    Peter    R       1A
                    Mary     Y       1A
                    Johnny   G       1A
                    Luke     G       1A
                    Bobby    B       1A
                    Aaron    R       1A
                    :        :       :
I
eg. 3
         General Structure
         List the residential district of the Red House   members.


              SELECT DISTINCT dcode FROM student ;
              WHERE hcode="R"
                             dcode
        Result
                             HHM
                             KWC
                             MKK
                             SSP
                             TST
                             YMT
I
eg. 4
        General Structure
         List the names and ages (1 d.p.) of 1B girls.




                    1B Girls ?
I
eg. 4
        General Structure
         List the names and ages (1 d.p.) of 1B girls.

            Condition for "1B
                 Girls":
        1) class = "1B"
        2) sex = "F"
        3) Both ( AND operator)
I
eg. 4
        General Structure
         List the names and ages (1 d.p.) of 1B girls.




               What is "age"?
I
eg. 4
        General Structure
         List the names and ages (1 d.p.) of 1B girls.


                  Functions:
    # days : DATE( ) – dob
    # years :(DATE( ) – dob) / 365
    1 d.p.: ROUND(__ , 1)
I
eg. 4
         General Structure
            List the names and ages (1 d.p.) of 1B girls.

        SELECT name, ROUND((DATE( )-dob)/365,1) AS age ;
        FROM student WHERE class="1B" AND sex="F"


        Result        name       age
                      Wendy      12.1
                      Kitty      11.5
                      Janet      12.4
                      Sandy      12.3
                      Mimi       12.2
I
eg. 5
         General Structure
         List the names, id of 1A students with no fee   remission.


                 SELECT name, id, class FROM student ;
                 WHERE class="1A" AND NOT remission
                         name        id      class
        Result           Peter       9801    1A
                         Mary        9802    1A
                         Luke        9810    1A
                         Bobby       9811    1A
                         Aaron       9812    1A
                         Ron         9813    1A
                         Gigi        9824    1A
                         :           :       :
II   Comparison
     expr IN ( value1, value2, value3)
     expr BETWEEN value1 AND value2
     expr LIKE "%_"
II
eg. 6
         Comparison
         List the students who were born on Wednesday or Saturdays.


             SELECT name, class, CDOW(dob) AS bdate ;
             FROM student ;
             WHERE DOW(dob) IN (4,7)
                    name      class   bdate
        Result      Peter     1A      Wednesday
                    Wendy     1B      Wednesday
                    Kevin     1C      Saturday
                    Luke      1A      Wednesday
                    Aaron     1A      Saturday
                    :         :       :
II
eg. 7
         Comparison
        List the students who were not born in January, March, June,
   September.

             SELECT name, class, dob FROM student ;
             WHERE MONTH(dob) NOT IN (1,3,6,9)
                        name       class   dob
        Result          Wendy      1B      07/09/86
                        Tobe       1B      10/17/86
                        Eric       1C      05/05/87
                        Patty      1C      08/13/87
                        Kevin      1C      11/21/87
                        Bobby      1A      02/16/86
                        Aaron      1A      08/02/86
                        :          :       :
II
eg. 8
         Comparison
         List the 1A students whose Math test score is   between 80 and 90
   (incl.)

             SELECT name, mtest FROM student ;
             WHERE class="1A" AND ;
             mtest BETWEEN 80 AND 90

        Result          name          mtest
                        Luke          86
                        Aaron         83
                        Gigi          84
II
eg. 9
         Comparison
            List the students whose names start with "T".

             SELECT name, class FROM student ;
             WHERE name LIKE "T%"

        Result    name       class
                  Tobe       1B
                  Teddy      1B
                  Tim        2A
II
eg. 10
          Comparison
         List the Red house members whose names contain   "a" as the 2nd
   letter.


              SELECT name, class, hcode FROM student ;
              WHERE name LIKE "_a%" AND hcode="R"

                   name         class     hcode
         Result
                   Aaron        1A        R
                   Janet        1B        R
                   Paula        2A        R
III Grouping
    SELECT ...... FROM ...... WHERE condition ;
    GROUP BY groupexpr [HAVING requirement]

    Group functions:
     COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

     – groupexpr specifies the related rows to be grouped
       as one entry. Usually it is a column.
     – WHERE condition specifies the condition of
       individual rows before the rows are group.
       HAVING requirement specifies the condition
       involving the whole group.
III Grouping
eg. 11   List the number of students of each class.
Group By Class
     class
      1A

1A    1A
      1A
                            COUNT( )

      1B
      1B
      1B
1B    1B
                            COUNT( )
      1B
      1B
      1C

1C    1C
      1C
                            COUNT( )

     Student
III Grouping
eg. 11     List the number of students of each class.
             SELECT class, COUNT(*) FROM student ;
             GROUP BY class
                          class     cnt
         Result              1A      10
                              1B      9
                             1C       9
                             2A       8
                              2B      8
                             2C       6
III Grouping
eg. 12   List the average Math test score of each class.
Group By Class
     class
      1A

1A    1A
      1A
                            AVG( )
      1B
      1B

1B
      1B
                            AVG( )
      1B
      1B
      1B
      1C

1C    1C                    AVG( )
      1C
     Student
III Grouping
eg. 12     List the average Math test score of each class.

             SELECT class, AVG(mtest) FROM student ;
             GROUP BY class
                       class   avg_mtest
         Result           1A      85.90
                          1B      70.33
                          1C      37.89
                          2A      89.38
                          2B      53.13
                          2C      32.67
III Grouping
eg. 13     List the number of girls of each district.

             SELECT dcode, COUNT(*) FROM student ;
             WHERE sex="F" GROUP BY dcode


         Result        dcode      cnt
                       HHM              6
                       KWC              1
                       MKK              1
                       SSP              5
                       TST              4
                       YMT              8
III Grouping
eg. 14   List the max. and min. test score of Form 1   students of each
   district.

             SELECT MAX(mtest), MIN(mtest), dcode ;
             FROM student ;
             WHERE class LIKE "1_" GROUP BY dcode
                      max_mtest min_mtest dcode
         Result           92        36    HHM
                          91        19    MKK
                          91        31    SSP
                          92        36    TST
                          75        75    TSW
                          88        38    YMT
III Grouping
eg. 15  List the average Math test score of the boys in each class. The list
   should not contain class with less than 3 boys.


             SELECT AVG(mtest), class FROM student ;
             WHERE sex="M" GROUP BY class ;
             HAVING COUNT(*) >= 3
         Result              avg_mtest class
                               86.00    1A
                               77.75     1B
                               35.60    1C
                               86.50    2A
                               56.50     2B
IV Display Order
    SELECT ...... FROM ...... WHERE ......
    GROUP BY ..... ;
    ORDER BY colname ASC / DESC
IV Display Order
eg. 16   List the boys of class 1A, order by their names.

    SELECT name, id FROM student ;
    WHERE sex="M" AND class="1A" ORDER BY name

          name     id          Result   name     id
          Peter    9801                 Aaron    9812
          Johnny   9803   ORDER BY      Bobby    9811
          Luke     9810                 Johnny   9803
                            dcode
          Bobby    9811                 Luke     9810
          Aaron    9812                 Peter    9801
          Ron      9813                 Ron      9813
IV Display Order
eg. 17     List the 2A students by their residential district.
             SELECT name, id, class, dcode FROM student ;
             WHERE class="2A" ORDER BY dcode
                     name      id     class   dcode
         Result      Jimmy     9712   2A      HHM
                     Tim       9713   2A      HHM
                     Samual    9714   2A      SHT
                     Rosa      9703   2A      SSP
                     Helen     9702   2A      TST
                     Joseph    9715   2A      TSW
                     Paula     9701   2A      YMT
                     Susan     9704   2A      YMT
IV Display Order
eg. 18   List the number of students of each district
   (in desc. order).

               SELECT COUNT(*) AS cnt, dcode FROM student ;
               GROUP BY dcode ORDER BY cnt DESC
                                 cnt        docode
         Result                        11   YMT
                                       10   HHM
                                       10   SSP
                                        9   MKK
                                        5   TST
                                        2   TSW
                                        1   KWC
                                        1   MMK
                                        1   SHT
IV Display Order
eg. 19  List the boys of each house order by the   classes. (2-level
   ordering)


             SELECT name, class, hcode FROM student ;
             WHERE sex="M" ORDER BY hcode, class
IV Display Order
 Result
                  name     hcode   class
                  Bobby    B       1A
          Blue
          House   Teddy    B       1B      Order
                  Joseph   B       2A       by
                  Zion     B       2B      class
 Order
                  Leslie   B       2C
  by              Johnny   G       1A
 hcode            Luke     G       1A
                  Kevin    G       1C
          Green
          House   George   G       1C
                  :        :       :
           :
           :
V   Output

INTO TABLE tablename          the output table is saved as a
                              database file in the disk.

INTO CURSOR temp              the output is stored in the
                              working memory temporarily.

TO FILE filename [ADDITIVE]   output to a text file.
                              (additive = append)

TO PRINTER                    send to printer.


TO SCREEN                     display on screen.
V
eg. 20
          Output
         List the students in desc. order of their names and                save the result
   as a database file name.dbf.

             SELECT * FROM student ;
             ORDER BY name DESC INTO TABLE name.dbf
 Result       id     name      dob        sex   class   mtest   hcode   dcode   remission
              9707   Zion      07/29/85   M     2B      51      B       MKK     .F.
              9709   Yvonne    08/24/85   F     2C      10      R       TST     .F.
              9804   Wendy     07/09/86   F     1B      84      B       YMT     .F.
              9819   Vincent   03/15/85   M     1C      29      Y       MKK     .F.
              9805   Tobe      10/17/86   M     1B      88      R       YMT     .F.
              9713   Tim       06/19/85   M     2A      91      R       HHM     .T.
              9816   Teddy     01/30/86   M     1B      64      B       SSP     .F.
              :      :         :          :     :       :       :       :       :
V
eg. 21
          Output
         Print the Red House members by their classes, sex   and name.


             SELECT class, name, sex FROM student ;
             WHERE hcode="R" ;
             ORDER BY class, sex DESC, name TO PRINTER
                          class   name     sex
         Result           1A      Aaron    M
                          1A      Peter    M
                          1A      Ron      M
                          1B      Tobe     M
                          1B      Janet    F
                          1B      Kitty    F
                          1B      Mimi     F
                          :       :        :
3   Union, Intersection and
    Difference of Tables
            The union of A and B (A∪B)

                A                       B




       A table containing all the rows from A and B.
3   Union, Intersection and
    Difference of Tables
          The intersection of A and B (A∩B)

                   A                      B




    A table containing only rows that appear in both A and B.
3   Union, Intersection and
    Difference of Tables
            The difference of A and B (A–B)

                  A                       B




     A table containing rows that appear in A but not in B.
3   The Situation:
    Bridge Club & Chess Club
     Consider the members of the Bridge Club and
     the Chess Club. The two database files have
     the same structure:

     field   type        width   contents
     id      numeric       4     student id number
     name    character    10     name
     sex     character     1     sex: M / F
     class   character     2     class
3   Union, Intersection and
    Difference of Tables
          Bridge [A]                         Chess [B]
          id     name    sex   class        id     name    sex   class
     1   9812    Aaron   M     1A      1   9802    Mary    F     1A
     2   9801    Peter   M     1A      2   9801    Peter   M     1A
     3   9814    Kenny   M     1B      3   9815    Eddy    M     1B
     4   9806    Kitty   F     1B      4   9814   Kenny    M     1B
     5   9818   Edmond   M     1C      5   9817   George   M     1C
          :        :     :      :           :       :      :      :


           Before using SQL, open the two tables:
                 SELECT A
                 USE bridge
                 SELECT B
                 USE chess
3         Union, Intersection and
          Difference of Tables
           SELECT ...... FROM ...... WHERE ...... ;
           UNION ;
           SELECT ...... FROM ...... WHERE ......

eg. 22  The two clubs want to hold a joint party. Make a list of all
   students. (Union)

            SELECT * FROM bridge ;
 Result
            UNION ;
            SELECT * FROM chess ;
            ORDER BY class, name INTO TABLE party
3         Union, Intersection and
          Difference of Tables
           SELECT ...... FROM table1 ;
           WHERE col IN ( SELECT col FROM table2 )


eg. 23   Print a list of students who are members of both   clubs.
   (Intersection)


 Result     SELECT * FROM bridge ;
            WHERE id IN ( SELECT id FROM chess ) ;
            TO PRINTER
3         Union, Intersection and
          Difference of Tables
         SELECT ...... FROM table1 ;
         WHERE col NOT IN ( SELECT col FROM table2 )


eg. 24  Make a list of students who are members of the Bridge Club but
   not Chess Club. (Difference)


 Result    SELECT * FROM bridge ;
           WHERE id NOT IN ( SELECT id FROM chess ) ;
           INTO TABLE diff
4   Multiple Tables:
    •   SQL provides a convenient operation to
        retrieve information from multiple tables.

    •   This operation is called join.

    •    The join operation will combine the tables into
         one large table with all possible combinations
         (Math: Cartesian Product), and then it will
    filter      the rows of this combined table to yield
    useful      information.
4   Multiple Tables:

                       field1   field2
                         A         1
field1      field2
                         A         2
 A            1
                         A         3
 B            2
                         B         1
              3
                         B         2
                         B         3
4   The Situation:
    Music Lesson
    Each student should learn a musical instrument.
    Two database files: student.dbf & music.dbf
    The common field: student id

    field   type        width contents
    id      numeric       4   student id number
    type    character    10   type of the music instrument

            SELECT A
            USE student
            SELECT B
            USE music
4   Natural Join
A Natural Join is a join operation that joins two
tables by their common column. This operation
is similar to the setting relation of two tables.


SELECT a.comcol, a.col1, b.col2, expr1, expr2 ;
FROM table1 a, table2 b ;
WHERE a.comcol = b.comcol
4
eg. 25
         Natural Join
         Make a list of students and the instruments they
   learn. (Natural Join)
             id     name class                     id   type

                                   Same id       9801
            9801

                                        Join
                  Student                           Music

                            id      name class   type


                            9801
                                   Product
4
eg. 25
           Natural Join
        Make a list of students and the instruments they     learn.
   (Natural Join)

              SELECT s.class, s.name, s.id, m.type ;
              FROM student s, music m ;
              WHERE s.id=m.id ORDER BY class, name
                          class   name     id     type
         Result           1A      Aaron    9812   Piano
                          1A      Bobby    9811   Flute
                          1A      Gigi     9824   Recorder
                          1A      Jill     9820   Piano
                          1A      Johnny   9803   Violin
                          1A      Luke     9810   Piano
                          1A      Mary     9802   Flute
                          :       :        :      :
4         Natural Join
eg. 26   Find the number of students learning piano in each class.




                          Three Parts :
         (1) Natural Join.
         (2) Condition: m.type="Piano"
         (3) GROUP BY class
4        Natural Join
eg. 26




  Student   Join              Condition        Group By
                             m.type= "Piano"     class
                   Product

   Music
4          Natural Join
eg. 26    Find the number of students learning piano in each class.


              SELECT s.class, COUNT(*) ;
              FROM student s, music m ;
              WHERE s.id=m.id AND m.type="Piano" ;
              GROUP BY class ORDER BY class
                            class    cnt
         Result             1A       4
                            1B       2
                            1C       1
4   Outer Join
An Outer Join is a join operation that includes
rows that have a match, plus rows that do not
have a match in the other table.
4        Outer Join
eg. 27 List the students who have not yet chosen an    instrument. (No
   match)


                id     name class                     id    type


               9801
                                    No match

                     Student                           Music
4          Outer Join
eg. 27 List the students who have not yet chosen an   instrument. (No
   match)

              SELECT class, name, id FROM student ;
              WHERE id NOT IN ( SELECT id FROM music ) ;
              ORDER BY class, name
                         class   name     id
         Result          1A      Mandy    9821
                         1B      Kenny    9814
                         1B      Tobe     9805
                         1C      Edmond   9818
                         1C      George   9817
                         :       :        :
4         Outer Join
eg. 28  Make a checking list of students and the instruments they learn. The list
   should also   contain the students without an instrument.
   (Outer Join)
4        Outer Join
eg. 28


                  Natural Join


                                 Outer Join


                  No Match
4       Outer Join
eg. 28
    SELECT s.class, s.name, s.id, m.type ;
       FROM student s, music m ;
       WHERE s.id=m.id ;

            UNION ;
            SELECT class, name, id, "" ;
            FROM student ;
            WHERE id NOT IN ( SELECT id FROM music ) ;
            ORDER BY 1, 2
4
class
        Outer Join
        name      id     type
                                    class   name     id     type
1A      Aaron     9812   Piano
1A      Bobby     9811   Flute      1A      Aaron    9812   Piano
1A      Gigi      9824   Recorder   1A      Bobby    9811   Flute
1A      Jill      9820   Piano      1A      Gigi     9824   Recorder
1A      Johnny    9803   Violin     1A      Jill     9820   Piano
1A      Luke      9810   Piano      1A      Johnny   9803   Violin
1A      Mary      9802   Flute      1A      Luke     9810   Piano
:       :         :      :          1A      Mandy    9821
                 Natural Join       1A      Mary     9802   Flute
                                    1A      Peter    9801   Piano
class   name      id
1A      Mandy     9821
                                    1A      Ron      9813   Guitar     empty
                                    1B      Eddy     9815   Piano
1B      Kenny     9814
1B      Tobe      9805              1B      Janet    9822   Guitar
1C      Edmond    9818              1B      Kenny    9814
1C      George    9817              1B      Kitty    9806   Recorder
:       :         :                 :       :        :      :
                   No Match                                  Outer Join

Weitere ähnliche Inhalte

Was ist angesagt? (20)

DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
SQL
SQLSQL
SQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 
Sql commands
Sql commandsSql commands
Sql commands
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 

Andere mochten auch

Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Beat Signer
 
Sql a practical_introduction
Sql a practical_introductionSql a practical_introduction
Sql a practical_introductioninvestnow
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginnersRam Sagar Mourya
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 

Andere mochten auch (6)

Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Sql a practical_introduction
Sql a practical_introductionSql a practical_introduction
Sql a practical_introduction
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 

Mehr von Anuja Lad

Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sqlAnuja Lad
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operatorsAnuja Lad
 
Important topic in board exams
Important topic in board examsImportant topic in board exams
Important topic in board examsAnuja 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
 
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
 

Mehr von Anuja Lad (20)

Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Important topic in board exams
Important topic in board examsImportant topic in board exams
Important topic in board exams
 
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
 
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
 

Kürzlich hochgeladen

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Kürzlich hochgeladen (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

Sql ppt

  • 2. 1 Introduction to SQL What is SQL? – When a user wants to get some information from a database file, he can issue a query. – A query is a user–request to retrieve data or information with a certain condition. – SQL is a query language that allows user to specify the conditions. (instead of algorithms)
  • 3. 1 Introduction to SQL Concept of SQL – The user specifies a certain condition. – The program will go through all the records in the database file and select those records that satisfy the condition.(searching). – Statistical information of the data. – The result of the query will then be stored in form of a table.
  • 4. 1 Introduction to SQL How to involve SQL in FoxPro – Before using SQL, the tables should be opened. – The SQL command can be entered directly in the Command Window – To perform exact matching, we should SET ANSI ON
  • 5. 2 Basic structure of an SQL query General SELECT, ALL / DISTINCT, *, Structure AS, FROM, WHERE Comparison IN, BETWEEN, LIKE "% _" Grouping GROUP BY, HAVING, COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) Display Order ORDER BY, ASC / DESC Logical AND, OR, NOT Operators Output INTO TABLE / CURSOR TO FILE [ADDITIVE], TO PRINTER, TO SCREEN Union UNION
  • 6. 2 The Situation: Student Particulars field type width contents id numeric 4 student id number name character 10 name dob date 8 date of birth sex character 1 sex: M / F class character 2 class hcode character 1 house code: R, Y, B, G dcode character 3 district code remission logical 1 fee remission mtest numeric 2 Math test score
  • 7. I General Structure SELECT ...... FROM ...... WHERE ...... SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ; FROM tablename WHERE condition
  • 8. I General Structure SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ; FROM tablename WHERE condition – The query will select rows from the source tablename and output the result in table form. – Expressions expr1, expr2 can be : • (1) a column, or • (2) an expression of functions and fields. – And col1, col2 are their corresponding column names in the output table.
  • 9. I General Structure SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ; FROM tablename WHERE condition – DISTINCT will eliminate duplication in the output while ALL will keep all duplicated rows. – condition can be : • (1) an inequality, or • (2) a string comparison • using logical operators AND, OR, NOT.
  • 10. I General Structure Before using SQL, open the student file: USE student eg. 1 List all the student records. SELECT * FROM student id name dob sex class mtest hcode dcode remission Result 9801 Peter 06/04/86 M 1A 70 R SSP .F. 9802 Mary 01/10/86 F 1A 92 Y HHM .F. 9803 Johnny 03/16/86 M 1A 91 G SSP .T. 9804 Wendy 07/09/86 F 1B 84 B YMT .F. 9805 Tobe 10/17/86 M 1B 88 R YMT .F. : : : : : : : : :
  • 11. I eg. 2 General Structure List the names and house code of 1A students. SELECT name, hcode, class FROM student ; WHERE class="1A" Class Class 1A  1A class="1A"  1A 1A 1A  1A 1B  1B 1B  1B : :
  • 12. I eg. 2 General Structure List the names and house code of 1A students. Result name hcode class Peter R 1A Mary Y 1A Johnny G 1A Luke G 1A Bobby B 1A Aaron R 1A : : :
  • 13. I eg. 3 General Structure List the residential district of the Red House members. SELECT DISTINCT dcode FROM student ; WHERE hcode="R" dcode Result HHM KWC MKK SSP TST YMT
  • 14. I eg. 4 General Structure List the names and ages (1 d.p.) of 1B girls. 1B Girls ?
  • 15. I eg. 4 General Structure List the names and ages (1 d.p.) of 1B girls. Condition for "1B Girls": 1) class = "1B" 2) sex = "F" 3) Both ( AND operator)
  • 16. I eg. 4 General Structure List the names and ages (1 d.p.) of 1B girls. What is "age"?
  • 17. I eg. 4 General Structure List the names and ages (1 d.p.) of 1B girls. Functions: # days : DATE( ) – dob # years :(DATE( ) – dob) / 365 1 d.p.: ROUND(__ , 1)
  • 18. I eg. 4 General Structure List the names and ages (1 d.p.) of 1B girls. SELECT name, ROUND((DATE( )-dob)/365,1) AS age ; FROM student WHERE class="1B" AND sex="F" Result name age Wendy 12.1 Kitty 11.5 Janet 12.4 Sandy 12.3 Mimi 12.2
  • 19. I eg. 5 General Structure List the names, id of 1A students with no fee remission. SELECT name, id, class FROM student ; WHERE class="1A" AND NOT remission name id class Result Peter 9801 1A Mary 9802 1A Luke 9810 1A Bobby 9811 1A Aaron 9812 1A Ron 9813 1A Gigi 9824 1A : : :
  • 20. II Comparison expr IN ( value1, value2, value3) expr BETWEEN value1 AND value2 expr LIKE "%_"
  • 21. II eg. 6 Comparison List the students who were born on Wednesday or Saturdays. SELECT name, class, CDOW(dob) AS bdate ; FROM student ; WHERE DOW(dob) IN (4,7) name class bdate Result Peter 1A Wednesday Wendy 1B Wednesday Kevin 1C Saturday Luke 1A Wednesday Aaron 1A Saturday : : :
  • 22. II eg. 7 Comparison List the students who were not born in January, March, June, September. SELECT name, class, dob FROM student ; WHERE MONTH(dob) NOT IN (1,3,6,9) name class dob Result Wendy 1B 07/09/86 Tobe 1B 10/17/86 Eric 1C 05/05/87 Patty 1C 08/13/87 Kevin 1C 11/21/87 Bobby 1A 02/16/86 Aaron 1A 08/02/86 : : :
  • 23. II eg. 8 Comparison List the 1A students whose Math test score is between 80 and 90 (incl.) SELECT name, mtest FROM student ; WHERE class="1A" AND ; mtest BETWEEN 80 AND 90 Result name mtest Luke 86 Aaron 83 Gigi 84
  • 24. II eg. 9 Comparison List the students whose names start with "T". SELECT name, class FROM student ; WHERE name LIKE "T%" Result name class Tobe 1B Teddy 1B Tim 2A
  • 25. II eg. 10 Comparison List the Red house members whose names contain "a" as the 2nd letter. SELECT name, class, hcode FROM student ; WHERE name LIKE "_a%" AND hcode="R" name class hcode Result Aaron 1A R Janet 1B R Paula 2A R
  • 26. III Grouping SELECT ...... FROM ...... WHERE condition ; GROUP BY groupexpr [HAVING requirement] Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) – groupexpr specifies the related rows to be grouped as one entry. Usually it is a column. – WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group.
  • 27. III Grouping eg. 11 List the number of students of each class.
  • 28. Group By Class class 1A 1A 1A 1A COUNT( ) 1B 1B 1B 1B 1B COUNT( ) 1B 1B 1C 1C 1C 1C COUNT( ) Student
  • 29. III Grouping eg. 11 List the number of students of each class. SELECT class, COUNT(*) FROM student ; GROUP BY class class cnt Result 1A 10 1B 9 1C 9 2A 8 2B 8 2C 6
  • 30. III Grouping eg. 12 List the average Math test score of each class.
  • 31. Group By Class class 1A 1A 1A 1A AVG( ) 1B 1B 1B 1B AVG( ) 1B 1B 1B 1C 1C 1C AVG( ) 1C Student
  • 32. III Grouping eg. 12 List the average Math test score of each class. SELECT class, AVG(mtest) FROM student ; GROUP BY class class avg_mtest Result 1A 85.90 1B 70.33 1C 37.89 2A 89.38 2B 53.13 2C 32.67
  • 33. III Grouping eg. 13 List the number of girls of each district. SELECT dcode, COUNT(*) FROM student ; WHERE sex="F" GROUP BY dcode Result dcode cnt HHM 6 KWC 1 MKK 1 SSP 5 TST 4 YMT 8
  • 34. III Grouping eg. 14 List the max. and min. test score of Form 1 students of each district. SELECT MAX(mtest), MIN(mtest), dcode ; FROM student ; WHERE class LIKE "1_" GROUP BY dcode max_mtest min_mtest dcode Result 92 36 HHM 91 19 MKK 91 31 SSP 92 36 TST 75 75 TSW 88 38 YMT
  • 35. III Grouping eg. 15 List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys. SELECT AVG(mtest), class FROM student ; WHERE sex="M" GROUP BY class ; HAVING COUNT(*) >= 3 Result avg_mtest class 86.00 1A 77.75 1B 35.60 1C 86.50 2A 56.50 2B
  • 36. IV Display Order SELECT ...... FROM ...... WHERE ...... GROUP BY ..... ; ORDER BY colname ASC / DESC
  • 37. IV Display Order eg. 16 List the boys of class 1A, order by their names. SELECT name, id FROM student ; WHERE sex="M" AND class="1A" ORDER BY name name id Result name id Peter 9801 Aaron 9812 Johnny 9803 ORDER BY Bobby 9811 Luke 9810 Johnny 9803 dcode Bobby 9811 Luke 9810 Aaron 9812 Peter 9801 Ron 9813 Ron 9813
  • 38. IV Display Order eg. 17 List the 2A students by their residential district. SELECT name, id, class, dcode FROM student ; WHERE class="2A" ORDER BY dcode name id class dcode Result Jimmy 9712 2A HHM Tim 9713 2A HHM Samual 9714 2A SHT Rosa 9703 2A SSP Helen 9702 2A TST Joseph 9715 2A TSW Paula 9701 2A YMT Susan 9704 2A YMT
  • 39. IV Display Order eg. 18 List the number of students of each district (in desc. order). SELECT COUNT(*) AS cnt, dcode FROM student ; GROUP BY dcode ORDER BY cnt DESC cnt docode Result 11 YMT 10 HHM 10 SSP 9 MKK 5 TST 2 TSW 1 KWC 1 MMK 1 SHT
  • 40. IV Display Order eg. 19 List the boys of each house order by the classes. (2-level ordering) SELECT name, class, hcode FROM student ; WHERE sex="M" ORDER BY hcode, class
  • 41. IV Display Order Result name hcode class Bobby B 1A Blue House Teddy B 1B Order Joseph B 2A by Zion B 2B class Order Leslie B 2C by Johnny G 1A hcode Luke G 1A Kevin G 1C Green House George G 1C : : : : :
  • 42. V Output INTO TABLE tablename the output table is saved as a database file in the disk. INTO CURSOR temp the output is stored in the working memory temporarily. TO FILE filename [ADDITIVE] output to a text file. (additive = append) TO PRINTER send to printer. TO SCREEN display on screen.
  • 43. V eg. 20 Output List the students in desc. order of their names and save the result as a database file name.dbf. SELECT * FROM student ; ORDER BY name DESC INTO TABLE name.dbf Result id name dob sex class mtest hcode dcode remission 9707 Zion 07/29/85 M 2B 51 B MKK .F. 9709 Yvonne 08/24/85 F 2C 10 R TST .F. 9804 Wendy 07/09/86 F 1B 84 B YMT .F. 9819 Vincent 03/15/85 M 1C 29 Y MKK .F. 9805 Tobe 10/17/86 M 1B 88 R YMT .F. 9713 Tim 06/19/85 M 2A 91 R HHM .T. 9816 Teddy 01/30/86 M 1B 64 B SSP .F. : : : : : : : : :
  • 44. V eg. 21 Output Print the Red House members by their classes, sex and name. SELECT class, name, sex FROM student ; WHERE hcode="R" ; ORDER BY class, sex DESC, name TO PRINTER class name sex Result 1A Aaron M 1A Peter M 1A Ron M 1B Tobe M 1B Janet F 1B Kitty F 1B Mimi F : : :
  • 45. 3 Union, Intersection and Difference of Tables The union of A and B (A∪B) A B A table containing all the rows from A and B.
  • 46. 3 Union, Intersection and Difference of Tables The intersection of A and B (A∩B) A B A table containing only rows that appear in both A and B.
  • 47. 3 Union, Intersection and Difference of Tables The difference of A and B (A–B) A B A table containing rows that appear in A but not in B.
  • 48. 3 The Situation: Bridge Club & Chess Club Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: field type width contents id numeric 4 student id number name character 10 name sex character 1 sex: M / F class character 2 class
  • 49. 3 Union, Intersection and Difference of Tables Bridge [A] Chess [B] id name sex class id name sex class 1 9812 Aaron M 1A 1 9802 Mary F 1A 2 9801 Peter M 1A 2 9801 Peter M 1A 3 9814 Kenny M 1B 3 9815 Eddy M 1B 4 9806 Kitty F 1B 4 9814 Kenny M 1B 5 9818 Edmond M 1C 5 9817 George M 1C : : : : : : : : Before using SQL, open the two tables: SELECT A USE bridge SELECT B USE chess
  • 50. 3 Union, Intersection and Difference of Tables SELECT ...... FROM ...... WHERE ...... ; UNION ; SELECT ...... FROM ...... WHERE ...... eg. 22 The two clubs want to hold a joint party. Make a list of all students. (Union) SELECT * FROM bridge ; Result UNION ; SELECT * FROM chess ; ORDER BY class, name INTO TABLE party
  • 51. 3 Union, Intersection and Difference of Tables SELECT ...... FROM table1 ; WHERE col IN ( SELECT col FROM table2 ) eg. 23 Print a list of students who are members of both clubs. (Intersection) Result SELECT * FROM bridge ; WHERE id IN ( SELECT id FROM chess ) ; TO PRINTER
  • 52. 3 Union, Intersection and Difference of Tables SELECT ...... FROM table1 ; WHERE col NOT IN ( SELECT col FROM table2 ) eg. 24 Make a list of students who are members of the Bridge Club but not Chess Club. (Difference) Result SELECT * FROM bridge ; WHERE id NOT IN ( SELECT id FROM chess ) ; INTO TABLE diff
  • 53. 4 Multiple Tables: • SQL provides a convenient operation to retrieve information from multiple tables. • This operation is called join. • The join operation will combine the tables into one large table with all possible combinations (Math: Cartesian Product), and then it will filter the rows of this combined table to yield useful information.
  • 54. 4 Multiple Tables: field1 field2 A 1 field1 field2 A 2 A 1 A 3 B 2 B 1 3 B 2 B 3
  • 55. 4 The Situation: Music Lesson Each student should learn a musical instrument. Two database files: student.dbf & music.dbf The common field: student id field type width contents id numeric 4 student id number type character 10 type of the music instrument SELECT A USE student SELECT B USE music
  • 56. 4 Natural Join A Natural Join is a join operation that joins two tables by their common column. This operation is similar to the setting relation of two tables. SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol
  • 57. 4 eg. 25 Natural Join Make a list of students and the instruments they learn. (Natural Join) id name class id type Same id 9801 9801 Join Student Music id name class type 9801 Product
  • 58. 4 eg. 25 Natural Join Make a list of students and the instruments they learn. (Natural Join) SELECT s.class, s.name, s.id, m.type ; FROM student s, music m ; WHERE s.id=m.id ORDER BY class, name class name id type Result 1A Aaron 9812 Piano 1A Bobby 9811 Flute 1A Gigi 9824 Recorder 1A Jill 9820 Piano 1A Johnny 9803 Violin 1A Luke 9810 Piano 1A Mary 9802 Flute : : : :
  • 59. 4 Natural Join eg. 26 Find the number of students learning piano in each class. Three Parts : (1) Natural Join. (2) Condition: m.type="Piano" (3) GROUP BY class
  • 60. 4 Natural Join eg. 26 Student Join Condition Group By m.type= "Piano" class Product Music
  • 61. 4 Natural Join eg. 26 Find the number of students learning piano in each class. SELECT s.class, COUNT(*) ; FROM student s, music m ; WHERE s.id=m.id AND m.type="Piano" ; GROUP BY class ORDER BY class class cnt Result 1A 4 1B 2 1C 1
  • 62. 4 Outer Join An Outer Join is a join operation that includes rows that have a match, plus rows that do not have a match in the other table.
  • 63. 4 Outer Join eg. 27 List the students who have not yet chosen an instrument. (No match) id name class id type 9801 No match Student Music
  • 64. 4 Outer Join eg. 27 List the students who have not yet chosen an instrument. (No match) SELECT class, name, id FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY class, name class name id Result 1A Mandy 9821 1B Kenny 9814 1B Tobe 9805 1C Edmond 9818 1C George 9817 : : :
  • 65. 4 Outer Join eg. 28 Make a checking list of students and the instruments they learn. The list should also contain the students without an instrument. (Outer Join)
  • 66. 4 Outer Join eg. 28 Natural Join Outer Join No Match
  • 67. 4 Outer Join eg. 28 SELECT s.class, s.name, s.id, m.type ; FROM student s, music m ; WHERE s.id=m.id ; UNION ; SELECT class, name, id, "" ; FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY 1, 2
  • 68. 4 class Outer Join name id type class name id type 1A Aaron 9812 Piano 1A Bobby 9811 Flute 1A Aaron 9812 Piano 1A Gigi 9824 Recorder 1A Bobby 9811 Flute 1A Jill 9820 Piano 1A Gigi 9824 Recorder 1A Johnny 9803 Violin 1A Jill 9820 Piano 1A Luke 9810 Piano 1A Johnny 9803 Violin 1A Mary 9802 Flute 1A Luke 9810 Piano : : : : 1A Mandy 9821 Natural Join 1A Mary 9802 Flute 1A Peter 9801 Piano class name id 1A Mandy 9821 1A Ron 9813 Guitar empty 1B Eddy 9815 Piano 1B Kenny 9814 1B Tobe 9805 1B Janet 9822 Guitar 1C Edmond 9818 1B Kenny 9814 1C George 9817 1B Kitty 9806 Recorder : : : : : : : No Match Outer Join