5) Working With DB2 Tables, Views, And Indexes

download 5) Working With DB2 Tables, Views, And Indexes

of 45

Transcript of 5) Working With DB2 Tables, Views, And Indexes

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    1/45

    IBM DB2 9

    2008 IBM Corporation

    Vikas Manoria

    IT Specialist IBM Academic Initiative

    [email protected]

    Section -5) Working with DB2 Tables,Working with DB2 Tables,

    Views, and IndexesViews, and Indexes

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    2/45

    IBM DB2 9

    2

    Section 5Section 5 -- Working with DB2 Tables,Working with DB2 Tables,

    Views, and Indexes (23.5%)Views, and Indexes (23.5%)Ability to demonstrate proper usage of DB2 data typesAbility to demonstrate proper usage of DB2 data types

    Given a situation, ability to create a tableGiven a situation, ability to create a table

    Ability to identify when referential integrity should be usedAbility to identify when referential integrity should be usedAbility to identify methods of data constraintAbility to identify methods of data constraint

    Ability to identify characteristics of a table, view or indexAbility to identify characteristics of a table, view or index

    Ability to identify when triggers should be usedAbility to identify when triggers should be used

    Knowledge of schemasKnowledge of schemas

    Knowledge of data type options for storing XML dataKnowledge of data type options for storing XML data

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    3/45

    IBM DB2 9

    3

    Categories of Data Types in DB2 9

    The built-in data types are categorized as follows:

    Numeric

    String

    Date-time

    XML

    The user-defined data types are categorized as:

    User-defined distinct type

    User-defined structured type User-defined reference type

    In addition to these, special data types designed to beused with the DB2 Extenders.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    4/45

    IBM DB2 9

    4

    Built-in data types - Numeric

    SMALLINT 2 Bytes

    (-32,768 to 32,767)

    INTEGER/INT 4 Bytes

    (-2,147,483,648 to 2,147,483,647)

    BIGINT 8 Bytes DECIMAL/DEC/NUM/NUMERIC

    (p/2)+1 Ex. 67.12345 has precision

    of 7, 7 2 is 3, + 1 makes 4

    REAL/FLOAT 4 Bytes

    (1.175E-37 to 3.402E+38)

    DOUBLE 8 Bytes

    (2.225E-307 to 1.79769E+308)

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    5/45

    IBM DB2 9

    5

    Built-in data types - String

    The fixed-length characterCan store 1 to 254 characters

    CHARACTER and CHAR Keywords

    Variable-length character data type

    Can store up to 32,672 characters governed by the table space pagesize used

    CHARACTER VARYING, CHAR VARYING, and VARCHAR Keywords

    Variable-length character data type

    Can store up to 32,672 characters regardless of the table

    space page size usedKeyword LONG VARCHAR is used

    Character Large Object data type

    Can store up to 2GB but CLOB(800) for 800 bytes

    Keyword CHARACTER LARGE OBJECT, CHAR LARGE

    OBJECT, and CLOB

    The fixed-length double byte characterCan store 1 to 127 characters

    GRAPHIC Keyword is used

    Variable-length double byte character data type

    Can store up to 16,336 characters governed by the table

    space page size used

    VARGRAPHIC Keyword used to denote it

    Variable-length double byte character data type

    Can store up to 16,338 characters regardless of the table

    space page size used

    Keyword LONG VARGRAPHIC is used

    Double Byte Character Large Object data typeCan store up to 2GB

    Keyword used is DBCLOB

    Binary Large Object data typeCan store up to 2GB

    Keyword used is BLOB

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    6/45

    IBM DB2 9

    6

    Built-in data types Date Time

    DATE :- Is stored internally as a (packed) string of 4 bytes.

    -Externally, string has a length of 10 bytes (MM-DD-YYYY -can vary and is dependent on country code).

    TIME :- Is stored internally as a (packed) string of 3 bytes.

    -Externally, string has a length of 8 bytes (HH-MM-SS - thisrepresentation may vary).

    TIMESTAMP :- Is stored internally as a (packed) string of 10 bytes.

    -Externally, string has a length of 26 bytes (YYYY-MM-DD-HH-MM-SS-NNNNNN ).

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    7/45

    IBM DB2 9

    7

    Built-in data types XML

    An value that is stored in a column defined with theExtensible Markup Language (XML) data type must be a

    well-formed XML document.

    XML documents can only be stored in single-partition

    databases that have been defined using the UTF-8 codeset.

    XML values are processed in an internal representation

    that is not comparable to any string value.

    XMLSERIALIZE (XML value ) = serialized string value

    XMLPARSE(string value) = XML value

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    8/45

    IBM DB2 9

    8

    User-defined Data Types

    User-defined distinct types-Define a new data type based on a built-in type. This new

    type has the same features, but you can use it to ensurethat only values of the same type are compared.

    -

    CREATE DISTINCT TYPE CANDOL AS DECIMAL(10,2)WITH COMPARISONS

    User-defined structured types-Allows you to create a type that consists of several columns of built-in

    types. For example, you can create a structured type named ADDRESS

    that contains data for street number, street name, city, and so forth.User-defined reference types

    -When using structured types, define references to rows in another tableusing reference types.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    9/45

    IBM DB2 9

    9

    DB2 Extenders

    Provide support for complex, nontraditional data

    types

    Packaged separately from the DB2 server code and

    is database dependantFor example, the DB2 Image Extender includes:

    -The DB2IMAGE UDT

    -UDFs to insert/retrieve from a db2image column

    -APIs to search based on characteristics of images

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    10/45

    IBM DB2 9

    10

    Tables

    All data is stored in tables in the database. A tableconsists of one or more columns of various datatypes. The data is stored in rows or records.

    May be defined using:- The CREATE TABLE SQL statement

    - A GUI tool, the DB2 Control Center

    The catalog view SYSCAT.TABLES contains a row

    for each table defined in the database.SYSCAT.COLUMNS contains a row for each columnof each table in the database.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    11/45

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    12/45

    IBM DB2 9

    12

    Creating Tables with XML Columns

    CREATE TABLE emp_resume (empid INTEGER NOT NULL PRIMARY KEY,resume XML,CONSTRAINT xv CHECK (resume IS VALIDATED))

    XML column used has the following restrictions:

    It cannot be part of primary key, foreign key orUNIQUE orany index except an XML index.

    It cannot have a specified default value or a WITH DEFAULT

    clause-if the column is nullable, the default value for thecolumn is the null value.

    It can be checked for its validity and well-formed ness if theCHECK constraint contains the VALIDATED predicate.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    13/45

    IBM DB2 9

    13

    Creating Tables with Identity Columns

    DB2 Database Manager can automatically generate numbersfor a column if the column is defined as an identity column.

    The syntax used to create an identity column is:

    [ColumnName][DataType] GENERATED AS IDENTITY

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    14/45

    IBM DB2 9

    14

    Constraints

    Unique constraints, which are used to ensure that values ina column are unique

    [UNIQUE | PRIMARY KEY]

    Referential integrity constraints, which are used to definerelationships between tables.

    REFERENCES[PKTableName]

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    15/45

    IBM DB2 9

    15

    Referential Integrity Constraints UPDATE Rule

    RESTRICT

    - Update for parent key will be

    rejected if a row in dependent

    table matches original values of

    key.

    NO ACTION

    - Update operation for parent key

    will be rejected if any row in

    dependent table does not have a

    corresponding parent key when

    update statement is completed .

    - This is the default.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    16/45

    IBM DB2 9

    16

    Referential Integrity Constraints DELETE Rule

    RESTRICT

    - Delete for parent key will be

    rejected if a row in dependent

    table matches original values of

    key.

    NO ACTION

    - Delete operation for parent key

    will be rejected if any row in

    dependent table does not have acorresponding parent key when

    update statement is completed .

    - This is the default.

    CASCADE

    - Implies that deleting a row in

    parent table automatically

    deletes any related rows in

    dependent table.

    SET NULL

    - Ensures that deletion of a row in

    parent table sets values offoreign key in any dependent

    row to null (if nullable).

    -Other parts of row are

    unchanged.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    17/45

    IBM DB2 9

    17

    Examples

    CREATE TABLE payroll.employees (empid INTEGERPRIMARY KEY,

    emp_name CHAR(30), mgrno INTEGER,

    CONSTRAINT fkconst FOREIGN KEY (mgrno)

    REFERENCES payroll.employees(empid) )CREATE TABLE payroll.paychecks (

    empid INTEGER, weeknumber CHAR(3),

    pay_amt DECIMAL(6,2),

    CONSTRAINT fkconst FOREIGN KEY (empid)

    REFERENCES employee(empid) ON DELETE

    CASCADE,

    CONSTRAINT chk1 CHECK(pay_amt > 0 AND

    weeknumber BETWEEN 1 AND 52))

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    18/45

    IBM DB2 9

    18

    Examples

    CREATE TABLE stock.activity (activityno SMALLINTNOT NULL

    GENERATED BY DEFAULT AS IDENTITY

    (START WITH 10 INCREMENT BY 10),

    actkwd CHAR(6)WITH DEFAULT Action)CREATE TABLE stock.copy LIKE stock.activity

    CREATE TABLE part_table (

    col1 INT, col2 CHAR(3))

    PARTITION BY (col1 NULLS FIRST)(STARTING 0 ENDING 9 IN tbsp0,

    STARTING 10 ENDING 19 IN tbsp1,

    STARTING 20 ENDING 29 IN tbsp2,

    STARTING 30 ENDING 39 IN tbsp3)

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    19/45

    IBM DB2 9

    19

    Alter Table

    Using it you can add or

    drop:

    A column

    A primary key

    One or more unique

    or referential

    constraints

    One or more check

    constraints

    You can also change:

    The identity attributes of a column

    The length of a string column

    (Only increase)

    The datatype of a column but new

    datatype must be compatible. For

    example, convert an INTEGER

    column to BIGINT is possible, but,

    a DECIMAL(10,2) column cannotbe converted to SMALLINT

    The nullability of a column

    The constraint of a column

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    20/45

    IBM DB2 9

    20

    Informational Constraints

    Informational Constraints are notenforced during insert andupdate processing. However,the DB2 SQL Optimizer will

    evaluate an informationalconstraint when resolve a query.

    Defined by appending thekeywordsNOT ENFORCEDENABLE QUERYOPTIMIZATION to a normalconstraint

    NOT ENFORCED constraints are never checked by the

    system, Not even by SET INTEGRITY

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    21/45

    IBM DB2 9

    21

    Temporarily Suspending Constraint Checking

    Constraint checking for a table can be suspended temporarily

    by executing the SET INTEGRITY statement.

    -SET INTEGRITY FOR employees OFF

    To resume constraint checking for the EMPLOYEES table thatconstraint checking was suspended

    -SET INTEGRITY FOR employees IMMEDIATE CHECKED

    If you want to transfer all offending rows in a separate table

    say BAD_ROWS

    -SET INTEGRITY FOR employees IMMEDIATE CHECKED

    FOR EXCEPTION IN employees USE bad_rows

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    22/45

    IBM DB2 9

    22

    SET CURRENT SCHEMA

    Schemas are objects that are used to logically classify andgroup other objects in the database.

    Two-part naming convention to avoid namespace collisionsfor example, in PAYROLL.STAFF first part is schema name.

    The CURRENT SCHEMA (or CURRENT_SCHEMA) specialregister contains a value that identifies the schema name if noschema/qualifier name is specified, default is authorization IDof the current session user.

    To change the value of the CURRENT SCHEMA,

    SET CURRENT SCHEMA= 'PAYROLL'On reconnect, the CURRENT SCHEMA special register will

    contain your authentication ID, not the value you assigned itearlier.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    23/45

    IBM DB2 9

    23

    Declared Temporary Tables

    It is used to create temporary tables that are used only during

    a session.

    The only object that can be DECLARED is a table.

    These tables are not persistent and can be used only by the

    application that creates them. When the application

    terminates, the rows of the table are deleted, and the

    definition of the table is dropped.

    DECLARE GLOBAL TEMPORARY TABLE

    T1 LIKE TRANSACTIONSON COMMIT PRESERVE ROWS

    NOT LOGGED IN SESSION TEMP;

    (LOB data will be replaced by zeros)

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    24/45

    IBM DB2 9

    24

    A Closer Look At Views

    A view provides a transparent view of the data inunderlying tables. Contains no data itself. Appears

    just like a table to the user. Can also be used torestrict which rows and columns can be viewed or

    updated

    You can create a view on an existing table (or tables)or on another view or any combination. A view definedon another view is called a nested view.

    If a table or another view on which a view is based isdropped, the view remains defined in the database butbecomes inoperative.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    25/45

    IBM DB2 9

    25

    Views with CHECK Options

    Data may be inserted or updated in the underlying tablesthrough a view.

    CREATE VIEW nonfictionbooks AS

    SELECT * FROM books WHERE booktype = 'N

    WITH CHECK OPTION

    WITH CHECK OPTION tells DB2 to check that statementsusing the view satisfy the conditions of the view.

    WITH CASCADED CHECK OPTION must satisfy the

    conditions of the view and all underlying views, even if thoseviews were not defined with the check option.

    WITH LOCAL CHECK OPTION need only satisfy conditionsof views which have the check option specified.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    26/45

    IBM DB2 9

    26

    CREATE VIEW NONFICTIONBOOKS AS

    SELECT * FROM BOOKSWHERE BOOKTYPE = 'N'

    CREATE VIEW NFBOOKS2 AS

    SELECT * FROM NONFICTIONBOOKS

    WHERE BOOKID > 100

    WITH CASCADED CHECK OPTION

    INSERT INTO NFBOOKS2 VALUES(10,..,'N')INSERT INTO NFBOOKS2 VALUES(10,..,'F')

    INSERT INTO NFBOOKS2 VALUES(120,..,'F')

    INSERT INTO NFBOOKS2 VALUES(120,..,N')

    WITH LOCAL CHECK OPTION

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    27/45

    IBM DB2 9

    27

    A Closer Look At Indexes

    An index is an object that contains an ordered set of pointersthat refer to rows in a base table.

    Two reasons why you might create an index:

    -To ensure uniqueness of values in a column or columns.

    -To improve performance of queries against the table whendefined on the appropriate column(s).

    Non-unique indexes allow duplicate key values; unique

    indexes allow only one occurrence of a key value in the list

    including a single null value. Indexes are additional copies of the values so they must be

    updated if the data in the table is updated. For frequent

    updates, this could impact performance.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    28/45

    IBM DB2 9

    28

    Example of creating a non-unique index in ascending order :

    -CREATE INDEX ibookname ON books (bookname)

    You can specify different orders for the columns in the index:

    -CREATE INDEX i2bookname ON books (authoidDESC, bookname ASC)

    Specify a bidirectional index:

    -CREATE INDEX bibookname ON books (bookname)

    ALLOW REVERSE SCANS

    A clustering index increases performance by decreasing no.of I/O, since like data values are stored on the same page.

    -CREATE UNIQUE INDEX indx ON employees(empno) CLUSTER

    An index can be placed in a separate table space from thetable, but only in the CREATE TABLE statement.

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    29/45

    IBM DB2 9

    29

    Another Look at Triggers

    A triggeris used to define a set of actions that are to beexecuted whenever an insert, update, or delete operation isperformed against a table or updatable view.

    Like constraints, triggers are often used to enforce dataintegrity and business rules.

    Unlike constraints, triggers can also be used to update othertables, automatically generate or transform values for insertedor updated rows, and invoke functions to perform tasks suchas issuing errors or alerts.

    Ex. CREATE TRIGGER pay_raise

    BEFORE UPDATE ON employeesFOR EACH ROWSET new.salary = salary * 1.1

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    30/45

    IBM DB2 9

    30

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    31/45

    IBM DB2 9

    31

    1)Which of the following DB2 data types

    does NOT have a fixed length?

    -A. INT-B. CHAR

    -C. XML

    -D. DOUBLE

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    32/45

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    33/45

    IBM DB2 9

    33

    3)Which of the following DB2 data types

    can be used to store 1000 MB of single-

    byte character data?

    A. BLOB

    B. CLOB

    C. DBCLOB

    D. GRAPHIC

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    34/45

    IBM DB2 9

    34

    4)Which of the following DB2 data types

    can NOT be used to create an identity

    column?

    A. SMALLINT

    B. INTEGER

    C.NU

    MERICD. DOUBLE

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    35/45

    IBM DB2 9

    35

    5)Which of the following strings can NOT

    be inserted into an XML column using

    XMLPARSE()?

    A. ""

    B. "John Doe"

    C. ""D. "

    "
  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    36/45

    IBM DB2 9

    36

    6)Which two of the following are optional

    and do not have to be specified when

    creating a table?

    A. Table name

    B. Column name

    C. Default constraint

    D. Column data type

    E. NOT NULL constraint

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    37/45

    IBM DB2 9

    37

    7) Given the following CREATE TABLE statement:

    CREATE TABLE table2 LIKE table1

    Which two of the following will NOT occur when the

    statement is executed?

    A. TABLE2 will have the same column names and column datatypes as TABLE1

    B. TABLE2 will have the same column defaults as TABLE1

    C. TABLE2 will have the same nullability characteristics as

    TABLE1

    D. TABLE2 will have the same indexes as TABLE1.

    E. TABLE2 will have the same referential constraints as TABLE1

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    38/45

    IBM DB2 9

    38

    8) If table TAB1 is created using the following

    statement:CREATE TABLE tab1 (col1 INTEGER NOT NULL,

    col2 CHAR(5), CONSTRAINT cst1 CHECK

    (col1 in (1, 2, 3)))

    Which of the following statements will successfully

    insert a record into table TAB1?

    A. INSERT INTO tab1 VALUES (0, 'abc')

    B. INSERT INTO tab1 VALUES (NULL, 'abc')

    C. INSERT INTO tab1 VALUES (ABS(2), 'abc')

    D. INSERT INTO tab1 VALUES (DEFAULT, 'abc')

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    39/45

    IBM DB2 9

    39

    9)Which of the following is NOT a characteristic of a

    unique index?

    A. Each column in a base table can only participate in one

    unique index, regardless of how the columns are grouped (the

    same column cannot be used in multiple unique indexes)B. In order for an index to be used to support a unique

    constraint, it must have been defined with the UNIQUE attribute

    C. A unique index cannot be created for a populated table if the

    key column specified contains more than one NULL valueD. A unique index can only be created for a non-nullable

    column

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    40/45

    IBM DB2 9

    40

    10)Which of the following is NOT true about schemas?

    A. If a schema name is not specified, either by qualifying a

    database object name or by executing the SET CURRENT

    SCHEMA statement, the authorization ID of the current

    session user is used as the schema name by default

    B. The value assigned to the CURRENT SCHEMA special

    register is persistent across database restarts

    C. A schema enables the creation of multiple objects in a

    database without encountering namespace collisions

    D.When most database objects are created, they are

    either implicitly or explicitly assigned to a schema

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    41/45

    IBM DB2 9

    41

    11) Given the following statements:

    CREATE TABLE table1(col1 INTEGER, col2 CHAR(3));

    CREATE VIEW view1 AS SELECT col1, col2

    FROM table1 WHERE col1 < 100

    WITH LOCAL CHECK OPTION;

    Which INSERT statement will execute successfully?

    A. INSERT INTO view1 VALUES (50, abc)

    B. INSERT INTO view1 VALUES(100, abc)

    C. INSERT INTO view1 VALUES(50, 'abc')

    D. INSERT INTO view1 VALUES(100, 'abc')

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    42/45

    IBM DB2 9

    42

    12)Which of the following actions will NOT

    cause a trigger to be fired?

    A. INSERT

    B. DELETE

    C. ALTER

    D. UPDATE

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    43/45

    IBM DB2 9

    43

    13)Which of the following CREATE TABLE

    statements will NOT be successful?

    A. CREATE TABLE t1 (c1 XML NOT NULL

    UNIQUE, c2 INT)

    B. CREATE TABLE t1 (c1 XML NOT NULL, c2

    CHAR(20))

    C. CREATE TABLE t1 (c1 XML CHECK (c1 IS

    VALIDATED), c2 INT)

    D. CREATE TABLE t1 (c1 XML, c2 XML)

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    44/45

    IBM DB2 9

    44

    14)Which of the following is NOT a characteristic of a

    declared temporary table?A. Declared temporary tables are not persistent and

    can only be used by the application that creates them

    B. It is possible for many applications to create

    declared temporary tables that have the same name

    C. Declared temporary tables are created by

    executing a CREATE TABLE statement with the

    DECLARED GLO

    BAL TEMPO

    RARY clause specifiedD. Once the application that created a global

    temporary table is terminated, any records in the table

    are deleted and the table is automatically destroyed

  • 8/8/2019 5) Working With DB2 Tables, Views, And Indexes

    45/45

    IBM DB2 9

    45

    Japanese

    Hebrew

    ThankYou

    English

    MerciFrench

    Russian

    DankeGerman

    GrazieItalian

    GraciasSpanish

    ObrigadoPortuguese

    Arabic

    Simplified Chinese

    Traditional Chinese

    Tamil

    Thai

    Korean