sql slides(2)

Upload: sai-sri-surampudi

Post on 09-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 SQL Slides(2)

    1/23

    SQL Query Slides

    Sharif University Of TechnologyDatabase Systems

    CE 384

    Prepared By:Babak Bagheri [email protected]

  • 8/8/2019 SQL Slides(2)

    2/23

    R etrieval Queries in SQL

    Basic form of the SQL SELECT statement is called a mapping or aSELECT-FROM-WHERE block

    SELECT < attribute list>FROM < table list>WHERE < condition>

    < attribute list> is a list of attribute names whose values are toberetrieved by the query < table list> is a list of the relation names required to processthequery < condition> is a conditional (Boolean) expression that identifiesthe tuples to be retrieved by the query

  • 8/8/2019 SQL Slides(2)

    3/23

    R elational Database schema

  • 8/8/2019 SQL Slides(2)

    4/23

    Populated D atabase:

  • 8/8/2019 SQL Slides(2)

    5/23

    Simple QueriesQ uery 0: Retrieve the birthdate and address of the employee whosename is 'John B. Smith'.

    Q uery 1: Retrieve the name and address of all employees who work for the 'Research' department.

    Q0: SELECT BDATE, ADDRESSFROM EMPLOYEE

    WHERE FNAME='John' AND MINIT='B AND LNAME='Smith

    Q1: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND

    DNUMBER=DNO

  • 8/8/2019 SQL Slides(2)

    6/23

    Some Queries Cont.

    Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESSFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND

    PLOCATION='Stafford'

    Q uery 3: For each employee, retrieve the employee's name, and the nameof his or her immediate supervisor.

    Q3: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEFROM EMPLOYEE E SWHERE E.SUPERSSN=S.SSN

    Q uery 2: For every project located in 'Stafford', list the project number, thecontrolling department number, and the department manager's last name,address, and birthdate.

  • 8/8/2019 SQL Slides(2)

    7/23

    Some Queries Cont.

    Q4: (SELECT PNAMEFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND

    LNAME='Smith')UNION (SELECT PNAMEFROM PROJECT, WORKS_ON, EMPLOYEEWHERE PNUMBER=PNO AND ESSN=SSN AND

    LNAME='Smith')

    Q uery 4: Make a list of all project numbers for projects that involve anemployee whose last name is 'Smith' as a worker or as a manager of the department that controls the project.

  • 8/8/2019 SQL Slides(2)

    8/23

    Some Queries Cont.

    Q5: SELECT E.FNAME, E.LNAMEFROM EMPLOYEE AS EWHERE E.SSN IN (SELECT ESSN

    FROM DEPENDENTWHERE ESSN=E.SSN AND

    E.FNAME=DEPENDENT_NAME)

    Q uery 5: Retrieve the name of each employee who has a dependent

    with the same first name as the employee.

    Q5A: SELECT E.FNAME, E.LNAMEFROM EMPLOYEE E, DEPENDENT DWHERE E.SSN=D.ESSN AND

    E.FNAME=D.DEPENDENT_NAME

    The comparison operator IN compares a value v with a set (or multi-set)of values V, and evaluates to TRUE if v is one of the elements in V

  • 8/8/2019 SQL Slides(2)

    9/23

    Some Queries Cont. EXISTS

    Q5B: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE EXISTS (SELECT *

    FROM DEPENDENTWHERE SSN=ESSN AND

    FNAME=DEPENDENT_NAME)

    EXISTS is used to check whether the result of a correlated nested queryis empty (contains no tuples) or not

  • 8/8/2019 SQL Slides(2)

    10/23

    Some Queries Cont.explicit ( enumerated) set of v alues

    Q uery 6: Retrieve the social security numbers of all employees who workon project number 1, 2, or 3.

    Q6: SELECT DISTINCT ESSN

    FROM WORKS_ONWHERE PNO IN (1, 2, 3)

    It is also possible to use an explicit (enumerated) set of values in theWHERE-clause rather than a nested query

  • 8/8/2019 SQL Slides(2)

    11/23

    Some Queries Cont.

    Q uery 7: Retrieve the name of each employee who works on all the projectscontrolled by department number 5.

    Q7: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE ( (SELECT PNO

    FROM WORKS_ONWHERE SSN=ESSN)

    CONTAINS(SELECT PNUMBERFROM PROJECTWHERE DNUM=5) )

    The CONTAINS operator compares two sets of valu es , and returns TRUEif one set contains all values in the other set (reminiscent of the divi s ionoperation of algebra).

  • 8/8/2019 SQL Slides(2)

    12/23

    Some Queries Cont. Null Value

    Q uery 8: Retrieve the names of all employees who do not havesupervisors.

    Q8: SELECT FNAME, LNAMEFROM EMPLOYEEWHERE SUPERSSN IS NULL

    S Q L uses IS or IS NOT to compare NULLs because it considers each NULLvalue distinct from other NULL

    Note: If a join condition is specified, tuples with NULL values for the joinattributes are not included in the result

  • 8/8/2019 SQL Slides(2)

    13/23

    Some Queries Cont. JOIN

    Can be written as:

    QTA: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEFROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEESON E.SUPERSSN=S.SSN)

    QT: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEFROM EMPLOYEE E SWHERE E.SUPERSSN=S.SSN

  • 8/8/2019 SQL Slides(2)

    14/23

    Some Queries Cont. JOIN

    Can be written as:

    Q9A: SELECT FNAME, LNAME, ADDRESSFROM (EMPLOYEE JOIN DEPARTMENTON DNUMBER=DNO)WHERE DNAME='Research

    Q9: SELECT FNAME, LNAME, ADDRESSFROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND DNUMBER=DNO

    Or as:Q9B: SELECT FNAME, LNAME, ADDRESS

    FROM (EMPLOYEE NATURAL JOINDEPARTMENT AS DEPT(DNAME, DNO, MSSN, MSDATE)

    WHERE DNAME='Research

  • 8/8/2019 SQL Slides(2)

    15/23

    Joined R elations Featurein SQL2

    Q uery 2: For every project located in 'Stafford', list the project number, thecontrolling department number, and the department manager's last name,address, and birthdate.

    Q2 B: SELECT PNUMBER, DNUM,LNAME, BDATE, ADDRESSFROM (PROJECT JOIN

    DEPARTMENT ONDNUM=DNUMBER) JOIN

    EMPLOYEE ONMGRSSN=SSN) )

    WHERE PLOCATION='Stafford

  • 8/8/2019 SQL Slides(2)

    16/23

    AGGR EGA TE FUNCTIONS

    Q uery 10: Find the maximum salary, the minimum salary, and

    the average salary among all employees.

    Q10: SELECT MAX(SALARY), MIN(SALARY), AVG (SALARY)FROM EMPLOYEE

    Include COUNT , SUM , MAX, MIN, and AVG

    Q uery 11: Find the maximum salary, the minimum salary, and the average

    salary among employees who work for the 'Research' department.Q11: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)

    FROM EMPLOYEE, DEPARTMENTWHERE DNO=DNUMBER AND

    DNAME='Research'

  • 8/8/2019 SQL Slides(2)

    17/23

    Group by

    Q uery 12: For each department, retrieve the department number, thenumber of employees in the department, and their average salary.Q12: SELECT DNO, COUNT (*), AVG (SALARY)

    FROM EMPLOYEEGROUP BY DNO

    S Q L has a GROUP BY -clause for specifying the grouping attributes, whichm ust al s o app e ar in the SELECT-clau se

    Q uery 13: For each project, retrieve the project number, project

    name, and the number of employees who work on that project.Q13: SELECT PNUMBER, PNAME, COUNT (*)

    FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNUMBER, PNAME

  • 8/8/2019 SQL Slides(2)

    18/23

    Group by cont. Having

    Q uery 14: For each project on w h ic h m or e th an t wo e m ploy ees work ,retrieve the project number, project name, and the number of employeeswho work on that project.

    Q14: SELECT PNUMBER, PNAME, COUNT (*)FROM PROJECT, WORKS_ON

    WHERE PNUMBER=PNOGROUP BY PNUMBER, PNAMEHAVING COUNT (*) > 2

    lThe HAVING-clause is used for specifying a selection condition on groups(rather than on individual tuples)

  • 8/8/2019 SQL Slides(2)

    19/23

    Summary of SQL QueriesA query in SQL can consist of up to six clauses, butonly

    the first two, SELECT and F R OM, are mandatory. Theclauses are specified in the following order:

    SELECT < attribute list>FROM < table list>[ WHERE < condition>]

    [G ROU P BY ][ HAVIN G ][ ORDER BY < attribute list>]

  • 8/8/2019 SQL Slides(2)

    20/23

    Summary of SQL Queries

    (cont.)The SELECT-clause lists the attributes or functions tobe retrievedThe F R OM-clause specifies all relations (or aliases)needed in the query but not those needed in nested

    queriesThe WHE R E-clause specifies the conditions forselection and join of tuples from the relationsspecified in the F R OM-clauseGR OUP BY specifies grouping attributesHA VIN G specifies a condition for selection of groups

    OR DER BY specifies an order for displaying the resultof a queryA query is evaluated by first applying the WHE R E-clause, thenGR OUP BY and H A VIN G , and finally the SELECT-clause

  • 8/8/2019 SQL Slides(2)

    21/23

    More complex Select SQL Server

    SELECT [ ALL | DISTINCT ][ TOP n [ PERCENT ] [ WITH TIES ] ]< select_list >< select_list > ::={ *| { t abl e_ na m e | vi e w _na m e | t abl e_ alia s }.*| { colu m n _na m e | ex pr ess ion | IDENTITYCOL |ROWGUIDCOL }[ [ AS ] colu m n _alia s ]| colu m n _alia s = ex pr ess ion} [ ,... n ]

    SELECT se l e c t_ li st [ INTO ne w _t abl e ]FROM t abl e_s ourc e[ WHERE se arc h_ condi t ion ][ GROUP BY group _by _ex pr ess ion ][ HAVING se arc h_ condi t ion ][ ORDER BY ord e r _ex pr ess ion [ ASC |DESC ] ]Select Clause:

    From Clause:[ FROM { < table_source > } [ ,... n ] ]< table_source > ::=t abl e_ na m e [ [ AS ] t abl e_ alia s ] [ WITH ( < table_hint > [ ,... n ]) ]| vi e w _na m e [ [ AS ] t abl e_ alia s ]

    | row set_ func t ion [ [ AS ] t abl e_ alia s ]| OPENXML| d e riv e d _t abl e [ AS ] t abl e_ alia s [ ( colu m n _alia s [ ,... n ] ) ]| < joined_table >< joined_table > ::=< table_source > < join_type > < table_source > ON | < table_source > CROSS JOIN < table_source >| < joined_table >

    < join_type > ::=[ INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } ][ < join_hint > ]JOINArguments< table_source >

  • 8/8/2019 SQL Slides(2)

    22/23

    More complex Select SQL Server

    Cont.Where Clause:

    [ WHERE < search_condition > | ]

    < old_outer_join > ::=colu m n _na m e { * = | = * } colu m n _na m e

    Group by clause:[ GROUP BY [ ALL ] group _by _ex pr ess ion [,... n ][ WITH { CUBE | ROLLUP } ]

    ]

    Having:

    [ HAVING < search_condition > ]

    Order By Clause:

    [ ORDER BY { order_by_expression [ ASC |DESC ] } [ ,... n ] ]

    Compute Clause:[ COMPUTE{ { AVG | COUNT | MAX | MIN | STDEV | STDEVP| VAR | VARP | SUM }( ex pr ess ion ) } [ ,... n ][ BY ex pr ess ion [ ,... n ] ]]

  • 8/8/2019 SQL Slides(2)

    23/23

    ComputeRow aggregate

    function Result

    AVG Average of the values in the numeric expression

    COUNT Number of selected rows

    MAX Highest value in the expression

    MIN Lowest value in the expression

    STDEV Statistical standard deviation for all values in the expression

    STDEVP |Statistical standard deviation for the population for all values in the expression

    SUM Total of the values in the numeric expression

    VAR Statistical variance for all values in the expression

    VARP Statistical variance for the population for all values in the expression