4) working with db2 data using sql and xquery ppt

Upload: praveen-shah

Post on 30-May-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    1/50

    IBM DB2 9

    Section -4) Working with DB2 DataWorking with DB2 Datausing SQL and XQueryusing SQL and XQuery

    2008 IBM Corporation

    Amit DaharwalIT Specialist IBM Academic Initiative

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    2/50

    IBM DB2 9

    Section 4Section 4 -- Working with DB2 Data usingWorking with DB2 Data usingSQL and XQuery (23.5%)SQL and XQuery (23.5%)

    Given a DML SQL statement, ability to identify resultsGiven a DML SQL statement, ability to identify results

    Ability to use SQL to SELECT data from tablesAbility to use SQL to SELECT data from tables

    Ability to use SQL to SORT or GROUP dataAbility to use SQL to SORT or GROUP data

    2

    , ,, , Knowledge of transactions (i.e., COMMIT, ROLLBACK,Knowledge of transactions (i.e., COMMIT, ROLLBACK,

    and transaction boundaries)and transaction boundaries)

    Ability to call a procedure or invoke a user definedAbility to call a procedure or invoke a user definedfunctionfunction

    Given an XQuery statement, knowledge to identify resultsGiven an XQuery statement, knowledge to identify results

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    3/50

    IBM DB2 9

    What is (Structured Query Language) SQL?Standard language of relational database access is SQL.

    Designed to access tabular data.

    Invented by IBM in the 1970s, the SQL language continues toevolve and is the only way to access relational database data.

    Three major categories.

    3

    DDL (Data Definition Language) - Used to create, modify,or drop database objects

    DML (Data Manipulation Language) - Used to select, insert,

    update, or delete database data (records)DCL (Data Control Language) - Used to provide data objectaccess control

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    4/50

    IBM DB2 9

    Managing Database Objects - DDLTo create, modify, delete objects in a database, SQL Data

    Definition Language (DDL) is used.

    DDL has four basic SQL statements:

    CREATE

    To create objects in a database.

    4

    DECLARETo create Temporary Tables in a database.

    ALTER

    To make permitted alteration in structure of an object.DROP

    To remove any object created with CREATE/ DECLAREstatements from database.

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    5/50

    IBM DB2 9

    Manipulate Data - DMLTo retrieve, insert, update or delete from tables and/or views,

    SQL Data Manipulation Language (DML) is used.

    DML also has four basic SQL statements:

    SELECT

    To retrieve data from table or view.

    5

    INSERTTo add records in tables.

    UPDATE

    To change data.

    DELETE

    To delete records from tables.

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    6/50

    IBM DB2 9

    Using SELECT to Retrieve DataThe SELECT statement is used to retrieve table or

    view data.

    Syntax -

    SELECT [DISTINCT] columns

    6

    WHERE condition

    GROUP BY column

    HAVING conditionORDER BY column

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    7/50

    IBM DB2 9

    Examples -SELECT * FROM staff;

    SELECT * FROM staffFETCH FIRST 10 ROWS ONLY;

    SELECT name, salar

    7

    FROM staff;

    SELECT DISTINCT dept, job

    FROM staff;SELECT name, salary + comm AS pay

    FROM staff;

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    8/50

    IBM DB2 9

    CASE Expressions In SELECTSELECT empno, lastname, job, salary,

    CASE WHEN job IN ('MANAGER, ADMIN)

    THEN salary * 1.10

    WHEN job IN ('DBA, ARCHITECT)

    *

    8

    .

    WHEN job = 'PROGRAMMER'

    THEN salary * 1.05

    ELSE salary * 1.035END as new_salary

    FROM employee

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    9/50

    IBM DB2 9

    With WHERE clauseUse the WHERE clause to select specific rows from a table or

    view.

    Relational operators including:

    =, >, =,

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    10/50

    IBM DB2 9

    Using Functions to Transform DataScalar functions

    Also known as row functions

    Operate on a single value to return another single

    value.

    10

    , , , , ,

    DAY(), LCASE(), LOWER(), UCASE() or UPPER()

    Column functions

    Also known as vector functions.Work on a group of rows to provide a result.

    SUM(), AVG(), MIN(), MAX(), COUNT()

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    11/50

    IBM DB2 9

    Using Set Operators to Combine Multiple QueriesWith DB2, it is possible to combine two or more queries into a

    single query by using a special operator known as a set

    operator. When a set operator is used, the results of eachquery executed are combined in a specific manner to produce

    a single result data set

    11

    are combined and all duplicate rows are eliminated

    INTERSECT - common records that are found in both the result

    data sets will be shown as final result set.

    EXCEPT - all records found in the first result data set that donot have a corresponding record in the second result data set

    will be shown as final result set.

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    12/50

    IBM DB2 9

    SELECT lastname, hiredate FROM employee

    WHEREMONTHNAME(hiredate) = 'December' AND

    salaryNOT BETWEEN 20000.00 AND 90000.00

    SELECT * FROM emp_exp_02 UNIONSELECT * FROM emp_exp_01

    SELECT empno, lastname FROM employee

    12

    as name empnoSELECT COUNT(*) FROM employee WHERE

    workdept IN (SELECT deptno FROM department

    WHERE admrdept = 'A00')

    SELECT workdept, DECIMAL(AVG(salary), 9, 2)

    AS avg_salary FROM employee GROUP BY work

    dept HAVINGAVG(salary) > 60000

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    13/50

    IBM DB2 9

    Using Joins - Concepts Ajoin combines data from two or more tables. A join

    condition is required to refine the result set (eliminates acartesian product). Joining can be INNER or OUTER.

    INNER JOIN - Keeps only the rows from the cross productthat meet the join condition. Result set of inner join consistonl those match rows that are resent in both oin table.

    13

    OUTER JOIN is a concatenation of the inner join and rowsfrom the left table, right table, or both tables that are missing

    from the inner join. There are 3 types of Outer Join.

    1. Left outer join = inner join + rows from the left table2. Right outer join = inner join + rows from the right table

    3. Full outer join = inner join + the rows from both the tables

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    14/50

    IBM DB2 9

    Using Joins ExamplesSELECT lastname, deptname FROM employee e,

    department d WHERE e.workdept = d.deptno

    ORSELECT lastname, deptname FROM employee e INNER

    JOIN department d ON e.workdept = d.deptno

    14

    SELECT lastname, deptname FROM employee e LEFTOUTER JOIN department d ON e.workdept = d.deptno

    SELECT lastname, deptname FROM employee e RIGHT

    OUTER JOIN department d ON e.workdept = d.deptnoSELECT lastname, deptname FROM employee e FULL

    OUTER JOIN department d ON e.workdept = d.deptno

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    15/50

    IBM DB2 9

    15

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    16/50

    IBM DB2 9

    16

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    17/50

    IBM DB2 9

    17

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    18/50

    IBM DB2 9

    18

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    19/50

    IBM DB2 9

    INSERT StatementThe INSERT statement is used to add new rows to a

    table or a view.

    Examples:INSERT INTO staff VALUES

    (1212,'Cerny',NULL,'Sales',3)

    19

    INSERT INTO staff (id, name, dept, job, years)

    VALUES (1212,'Cerny',20,'Sales',3),

    (1213,'Wolfrum',20,NULL,2)

    INSERT INTO department (deptno, deptname)

    SELECT deptno, deptname FROM sales_depts

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    20/50

    IBM DB2 9

    UPDATE StatementThe UPDATE statement is used to change the data in

    a table or a view.

    For example:

    UPDATE staff SET dept = NULL

    20

    ename

    UPDATE staff SET (dept, sal)=(51, 7000)

    WHERE id = 750

    UPDATE employees SET (dept) =(SELECT deptname FROM department

    WHERE deptno = 1)

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    21/50

    IBM DB2 9

    DELETE StatementThe DELETE statement is used to delete entire rows

    of data from a table.

    For example:

    21

    DELETE FROM staff WHERE id IN (1212, 1213)

    DELETE FROM sales WHERE salesperson IS NULL

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    22/50

    IBM DB2 9

    The COMMIT and ROLLBACK statementsA unit of work (UOW), also known as a transaction, is a

    recoverable sequence of operations within an application

    process. Ex. transfer funds transaction.

    The application ends the UOW by issuing either a COMMIT or

    a ROLLBACK statement, whichever is appropriate.

    22

    e s a emen ma es a c anges ma e w n e

    UOW permanent, whereas the ROLLBACK statement reverses

    those changes.

    If the application ends normally without an explicit COMMIT or

    ROLLBACK statement, the UOW is automatically committed. If the application ends abnormally before the end of a UOW,

    that unit of work is automatically rolled back.

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    23/50

    IBM DB2 9

    SavepointsA savepoint lets you selectively roll back a subset of actions

    that make up a UOW without losing the entire transaction.

    do some work;savepoint s1 on rollback retain cursors

    do some more work

    23

    savepoint s2 on rollback retain cursorsdo even more work;

    savepoint s3 on rollback retain cursors

    wrap it up;roll back to savepoint s1;

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    24/50

    IBM DB2 9

    What is XML? XML was designed to structure, store and to send

    data/information.

    At its core XML is text formatted in the form of tags and textthat follow a well-defined set of rules.

    This text may be stored/represented in:

    John Smith Co

    24

    A normal file stored on diskA message being sent over HTTP

    A character string in a programming language

    A CLOB (character large object) in a database

    Any other way textual data can be used

    1234 W. Main St

    ToledoOH95141

    A5412

    985

    1

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    25/50

    IBM DB2 9

    25

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    26/50

    IBM DB2 9

    26

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    27/50

    IBM DB2 9

    27

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    28/50

    IBM DB2 9

    XML specifications

    XMLdocument

    s

    DTDdescribes

    supersedes

    28

    XSD

    XQuery XPath

    XSLT

    searches searches transforms

    uses

    uses

    uses

    uses

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    29/50

    IBM DB2 9

    29

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    30/50

    IBM DB2 9

    30

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    31/50

    IBM DB2 9

    XPath Expressions

    31

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    32/50

    IBM DB2 9

    32

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    33/50

    IBM DB2 9

    33

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    34/50

    IBM DB2 9

    XML Facilities XML data type for columns

    create table s1.t1 (c1 int, c2 xml)

    Language bindings for XML type in programming languages

    cobol, c, java, etc..

    XML indexes

    create ix1 on s1.t1(c2) generate keys using pattern /dept/emp/@empno

    34

    An XML schema/DTD repository

    Support forXQuery as a primary language as well as:

    Support forSQL within XQuery

    Support forXQuery with SQL

    Support for new SQL/XML functions

    Performance, scale, and everything else they expect from a

    DBMS

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    35/50

    IBM DB2 9

    Two ways to query XML data in DB2

    Using XQuery as the primary language

    All queries begin with XQuery.

    Tells the DB2 parser what to expect

    Can execute SQL within a query beginning with XQUERY

    35

    Using SQL as the primary language

    Part 2

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    36/50

    IBM DB2 9

    XQuery: The FLWOR Expression

    FOR: iterates through a sequence, bind variable to items LET: binds a variable to a sequence WHERE: eliminates items of the iteration

    ORDER: reorders items of the iteration RETURN: constructs query results

    36

    ,

    xqueryfor $d in db2-fn:xmlcolumn(dept.deptdoc)/dept

    let $emp := $d//employee/name

    where $d/@bldg > 95

    order by $d/@bldgreturn

    {$d/@bldg, $emp}

    John Doe

    408 555 1212

    344

    Peter Pan

    408 555 9918

    216

    Input:

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    37/50

    IBM DB2 9

    FLWOR Expression

    xquery

    for $d in xmlcolumn(deptdoc)/dept

    where $d/@bldg = 101return

    {$d/employee/name}

    xquery

    for d in xmlcolumn de tdoc /de t

    John Doe

    408 555 1212344

    Peter Pan

    408 555 9918

    216

    create table dept (deptID char(8), deptdoc xml);

    37

    John DoePeter Pan

    John Doe

    Peter Pan

    John DoePeter Pan

    This result is not an XML document!

    xquery

    for $d in xmlcolumn(deptdoc)/dept

    where $d/@bldg = 101

    return $d/employee/name/text()

    where $d/@bldg = 101

    return $d/employee/name

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    38/50

    IBM DB2 9

    Two ways to query XML data in DB2

    Using XQuery as the primary language

    Done

    38

    Looking at query onlyAll queries begin with Select

    XML Retrieval done with XMLQUERY (flags db2 parser to

    switch to XML Processing)

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    39/50

    IBM DB2 9

    XML Functions

    XMLQUERY(). function that enables you to execute an XQueryexpression from within an SQL context. It returns an XMLvalue, which is an XML sequence. This sequence can be

    empty or it can contain one or more items.

    XMLTABLE(). returns a table from the evaluation of XQuery

    39

    sequence, however, XMLTABLE() allows you to execute anXQuery expression and return values as a table instead.

    XMLEXISTS(). If it returns an empty sequence, XMLEXISTS

    returns FALSE; otherwise, TRUE is returned. The XMLEXISTSpredicate can be used in the WHERE clauses of UPDATE,DELETE, and SELECT statements.

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    40/50

    IBM DB2 9

    DML statements for XML Data

    INSERT INTO customers (custinfo) VALUES (

    XMLPARSE(DOCUMENT 'John Doe'

    PRESERVE WHITESPACE))

    DELETE FROM customer WHERE XMLEXISTS ('declare

    default element namespace "http://custrecord.dat";

    40

    $info/customerinfo[name/text()=" John Doe"]'

    PASSING custinfo AS "info")

    UPDATE customer

    SET custinfo = XMLPARSE (DOCUMENT JaneDoe PRESERVE WHITESPACE)

    WHERE empno = 11;

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    41/50

    IBM DB2 9

    XMLTABLE - XML to relationalSELECT X.* fromXMLTABLE (db2-fn:xmlcolumn(PORDERS.PO)//customer

    COLUMNS

    CID INTEGER PATH @id,Name VARCHAR(30) PATH name,ZipType CHAR(2) PATH zip/@type,Zip XML PATH zip

    41

    95023USnull4711

    33129USBobby1325

    ZipZipTypeNameCID

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    42/50

    IBM DB2 9

    42

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    43/50

    IBM DB2 9

    Given the following queries:

    SELECT c1 FROM tab1; SELECT c1 FROM tab2;

    Which of the following set operators can be used to

    produce a result data set that contains only recordsthat are not found in the result data set produced by

    each query after duplicate rows have been

    43

    eliminated?A. UNION

    B. INTERSECT

    C. EXCEPT

    D. MERGE

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    44/50

    IBM DB2 9

    Given the following UPDATE statement:

    UPDATE employees SET workdept = (SELECT deptno FROM

    department WHERE deptno = 'A01') WHERE workdept IS NULL

    Which of the following describes the result if this statement is

    executed?

    A. The statement will fail because an UPDATE statement cannot

    contain a subquery.

    44

    B. The statement will only succeed if the data retrieved by thesubquery does not contain multiple records.

    C. The statement will succeed; if the data retrieved by the subquery

    contains multiple records, only the first record will be used to perform

    the update. D. The statement will only succeed if every record in the

    EMPLOYEES table has a null value in the WORKDEPT column.

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    45/50

    Given the following SALES table definition:

    SALES_DATE DATE

    SALES_PERSON CHAR(20)

    REGION CHAR(20)

    SALES INTEGERWhich of the following SQL statements will remove all rows that

    had a SALES_DATE in the year 1995?

    45

    A. DELETE * FROM sales WHERE YEAR(sales_date) = 1995

    B. DELETE FROM sales WHERE YEAR(sales_date) = 1995

    C. DROP * FROM sales WHERE YEAR(sales_date) = 1995D. DROP FROM sales WHERE YEAR(sales_date) = 1995

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    46/50

    Given the following EMPLOYEEStable definition:

    EMP ID INTEGERNAME CHAR(20)

    DEPT CHAR(10)

    SALARY DECIMAL (10, 2)

    COMMISSION DECIMAL (8, 2)Assuming the DEPT column contains the values 'ADMIN', 'PRODUCTION',

    and 'SALES', which of the following statements will produce a result data set

    46

    ,

    PRODUCTION department employees are grouped together, and all SALESdepartment employees are grouped together?

    A. SELECT name, dept FROM employees ORDER BY dept

    B. SELECT name, dept FROM employees GROUP BY dept

    C. SELECT name, dept FROM employees GROUP BY ROLLUP (dept)

    D. SELECT name, dept FROM employees GROUP BY CUBE (dept)

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    47/50

    Given the following EMPLOYEEStable definition:

    EMP ID INTEGERNAME CHAR(20)

    DEPT CHAR(10)

    SALARY DECIMAL (10, 2)

    COMMISSION DECIMAL (8, 2)Assuming the DEPT column contains the values 'ADMIN', 'PRODUCTION',

    and 'SALES', which of the following statements will produce a result data set

    47

    ,

    PRODUCTION department employees are grouped together, and all SALESdepartment employees are grouped together?

    A. SELECT name, dept FROM employees ORDER BY dept

    B. SELECT name, dept FROM employees GROUP BY dept

    C. SELECT name, dept FROM employees GROUP BY ROLLUP (dept)

    D. SELECT name, dept FROM employees GROUP BY CUBE (dept)

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    48/50

    Which of the following best describes a unit of work?

    A. It is a recoverable sequence of operations whose point ofconsistency is established when a connection to a databasehas been established or when a mechanism known as asavepoint is created.

    B. It is a recoverable sequence of operations whose currentpoint of consistency can be determined by querying the system

    48

    .

    C. It is a recoverable sequence of operations whose point ofconsistency is established when an executable SQL statementis processed after a connection to a database has beenestablished or a previous transaction has been terminated.

    D. It is a recoverable sequence of operations whose point ofconsistency is only established if a mechanism known as asavepoint is created.

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    49/50

    A stored procedure has been created with thefollowing statement:CREATE PROCEDURE proc1 (IN

    var1 VARCHAR(10), OUT rc INTEGER) SPECIFIC

    myproc LANGUAGE SQL What is the correct way

    to invoke this procedure from the command line

    processor (CLP)?

    49

    A. CALL proc1 ('SALES', ?)B. CALL myproc ('SALES', ?)

    C. CALL proc1 (SALES, ?)

    D. RUN proc1 (SALES, ?)

    IBM DB2 9

  • 8/9/2019 4) Working With DB2 Data Using SQL and XQuery PPT

    50/50

    Hebrew

    ThankMerci

    Russian

    GrazieItalian

    GraciasSpanish

    ObrigadoPortuguese

    Arabic

    50

    Japanese

    YouEnglish

    French

    DankeGerman

    Simplified Chinese

    Traditional Chinese

    Tamil

    Thai

    Korean