Working With DB2 Tables, Views, And Indexes

download Working With DB2 Tables, Views, And Indexes

of 12

Transcript of Working With DB2 Tables, Views, And Indexes

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

    1/12

    1

    IBM DB2 9

    2008 IBM Corporation

    Section -5) Working with DB2 Tables,Working with DB2 Tables,Views, and IndexesViews, and Indexes

    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 used

    Ability 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

    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.

    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/6/2019 Working With DB2 Tables, Views, And Indexes

    2/12

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

    3/12

    3

    IBM DB2 9

    9

    DB2 Extenders

    Provide support for complex, nontraditional data

    types

    Packaged separately from the DB2 server code and

    is database dependant

    For 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

    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.

    IBM DB2 9

    11

    CREATE TABLE SQL

    CREATE TABLE [TableName]([Column], ...)

    [ColumnName][DataType]

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

    4/124

    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

    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/6/2019 Working With DB2 Tables, Views, And Indexes

    5/125

    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))

    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)

    IBM DB2 9

    19

    Alter Table

    Using it you can add ordrop:

    A column

    A primary key

    One or more uniqueor referentialconstraints

    One or more checkconstraints

    You can also change:

    The identity attributes of a column

    The length of a string column(Only increase)

    The datatype of a column but newdatatype must be compatible. Forexample, convert an INTEGERcolumn to BIGINT is possible, but,

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

    The nullability of a column

    The constraint of a column

    IBM DB2 9

    20

    Informational Constraints

    Informational Constraints are notenforced during insert andupdate processing. However,the DB2 SQL Optimizer willevaluate an informationalconstraint when resolve a query.

    Defined by appending thekeywordsNOT ENFORCEDENABLE QUERY

    OPTIMIZATION to a normalconstraint

    NOT ENFORCED constraints are never checked by the

    system, Not even by SET INTEGRITY

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

    6/126

    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 that

    constraint 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

    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 willcontain your authentication ID, not the value you assigned itearlier.

    IBM DB2 9

    23

    Declared Temporary Tables

    It is used to create temporary tables that are used only duringa 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 applicationterminates, the rows of the table are deleted, and thedefinition of the table is dropped.

    DECLARE GLOBAL TEMPORARY TABLE

    T1 LIKE TRANSACTIONS

    ON COMMIT PRESERVE ROWS

    NOT LOGGED IN SESSION TEMP;

    (LOB data will be replaced by zeros)

    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

    updatedYou 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/6/2019 Working With DB2 Tables, Views, And Indexes

    7/127

    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.

    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

    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; uniqueindexes allow only one occurrence of a key value in the listincluding a single null value.

    Indexes are additional copies of the values so they must beupdated if the data in the table is updated. For frequentupdates, this could impact performance.

    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 (authoid

    DESC, 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/6/2019 Working With DB2 Tables, Views, And Indexes

    8/128

    IBM DB2 9

    29

    Another Look at Triggers

    A trigger is 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_raiseBEFORE UPDATE ON employees

    FOR EACH ROW

    SET new.salary = salary * 1.1

    IBM DB2 9

    30

    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

    IBM DB2 9

    32

    2) Which of the following is the best statement to use

    to create a user-defined data type that can be used

    to store currency values?

    A. CREATE DISTINCT TYPE currency AS

    NUMERIC(7,2)

    B. CREATE DISTINCT TYPE currency AS

    SMALLINT

    C. CREATE DISTINCT TYPE currency AS

    BIGINT

    D. CREATE DISTINCT TYPE currency AS

    DOUBLE

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

    9/129

    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

    IBM DB2 9

    34

    4) Which of the following DB2 data types

    can NOT be used to create an identitycolumn?

    A. SMALLINT

    B. INTEGER

    C. NUMERICD. DOUBLE

    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. "

    "

    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/6/2019 Working With DB2 Tables, Views, And Indexes

    10/1210

    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 data

    types 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

    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')

    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 value

    D. A unique index can only be created for a non-nullable

    column

    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 defaultB. 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/6/2019 Working With DB2 Tables, Views, And Indexes

    11/1211

    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')

    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

    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)

    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 GLOBAL TEMPORARY clause specified

    D. 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/6/2019 Working With DB2 Tables, Views, And Indexes

    12/1212

    IBM DB2 9

    45

    Japanese

    Hebrew

    Thank

    YouEnglish

    MerciFrench

    Russian

    DankeGerman

    GrazieItalian

    GraciasSpanish

    ObrigadoPortuguese

    Arabic

    Simplified Chinese

    Traditional Chinese

    Tamil

    Thai

    Korean