You are on page 1of 45

IBM DB2 9

Section -5) Working with DB2 Tables,


Views, and Indexes
Vikas Manoria IT Specialist IBM Academic Initiative vmanoria@in.ibm.com

2008 IBM Corporation

IBM DB2 9

Section 5 - Working with DB2 Tables, Views, and Indexes (23.5%)


Ability to demonstrate proper usage of DB2 data types Given a situation, ability to create a table Ability to identify when referential integrity should be used Ability to identify methods of data constraint Ability to identify characteristics of a table, view or index Ability to identify when triggers should be used Knowledge of schemas Knowledge of data type options for storing XML data

IBM DB2 9

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 be used with the DB2 Extenders.
3

IBM DB2 9

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

IBM DB2 9

Variable-length character data type Can store up to 32,672 The data type characters governed by the table space page Variable-length character fixed-length character character The fixed-length double byte Character Large Object data type characters size used Can store to 127 characters Can store up to 32,672 characters 1 to 254 type the table regardless Variable-length double byte character data of Keywords Can store CLOB(800) for 800 bytes Variable-length double byte character data type CHARACTER VARYING,2GB but 1 Can store up to CHAR VARYING, and VARCHARKeywords CHARACTER and is used space page size used Can store to 16,336 characters governed by the tablethe table up to 16,338 characters regardless of Can store up CHARACTER LARGE OBJECT, CHAR LARGE GRAPHIC Keyword CHAR Keyword Keyword LONGused space page size VARCHAR is used space and size OBJECT,pageCLOBused Large Object data type Double Byte Character denote it VARGRAPHIC Keyword used to is used Keyword LONG VARGRAPHIC

Built-in data types - String

Can store up to 2GB data type Binary Large Object Keyword used is DBCLOB Can store up to 2GB Keyword used is BLOB

IBM DB2 9

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 - this representation may vary).

TIMESTAMP :
- Is stored internally as a (packed) string of 10 bytes. - Externally, string has a length of 26 bytes (YYYY-MM-DDHH-MM-SS-NNNNNN ).
6

IBM DB2 9

Built-in data types XML


An value that is stored in a column defined with the Extensible 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 code set. 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
7

IBM DB2 9

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 ensure that 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 table using reference types.
8

IBM DB2 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

Tables
All data is stored in tables in the database. A table consists of one or more columns of various data types. 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 column of each table in the database.
10

IBM DB2 9

CREATE TABLE SQL


CREATE TABLE [TableName]([Column], ...) <IN [TablespaceName]> <INDEX IN [TablespaceName]> <LONG IN [TablespaceName]> [ColumnName][DataType] <NOT NULL> <WITH DEFAULT <[DefaultValue]> | <GENERATED <ALWAYS | BY DEFAULT> AS IDENTITY> <UniqueConstraint> <CheckConstraint> <ReferentialConstraint>
11

IBM DB2 9

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 or UNIQUE or any 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 the column is the null value. It can be checked for its validity and well-formed ness if the CHECK constraint contains the VALIDATED predicate.
12

IBM DB2 9

Creating Tables with Identity Columns


DB2 Database Manager can automatically generate numbers for a column if the column is defined as an identity column. The syntax used to create an identity column is: [ColumnName][DataType] GENERATED <ALWAYS | BY DEFAULT> AS IDENTITY <( <START WITH [1 | StartingValue]> <INCREMENT BY [1 | IncrementValue]> <NO MINVALUE | MINVALUE [MinValue]> <NO MAXVALUE | MAXVALUE [MaxValue]> <NO CYCLE | CYCLE> <NO CACHE | CACHE [CacheSize]> <NO ORDER | ORDER> )>
13

IBM DB2 9

Constraints
Unique constraints, which are used to ensure that values in a column are unique
<CONSTRAINT [ConstraintName]> [UNIQUE | PRIMARY KEY]

Referential integrity constraints, which are used to define relationships between tables.
<CONSTRAINT [ConstraintName]> REFERENCES [PKTableName]<([PKColumnName], ...) <ON UPDATE [RESTRICT | NO ACTION]> <ON DELETE [CASCADE | SET NULL | RESTRICT | NO ACTION]>

Table check constraints, which are used verify that column data does not violate rules defined for the column
<CONSTRAINT [ConstraintName]> CHECK ([CheckConditi]) <ENFORCED | NOT ENFORCED> <ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION>
14

IBM DB2 9

Referential Integrity Constraints UPDATE Rule


<ON UPDATE [RESTRICT | NO ACTION]>
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.
15

IBM DB2 9

Referential Integrity Constraints DELETE Rule


<ON DELETE [CASCADE | SET NULL | RESTRICT | NO ACTION]>

RESTRICT
- Delete for parent key will be rejected if a row in dependent table matches original values of key.

CASCADE
- Implies that deleting a row in parent table automatically deletes any related rows in dependent table.

NO ACTION
- Delete 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.
16

SET NULL
- Ensures that deletion of a row in parent table sets values of foreign key in any dependent row to null (if nullable). - Other parts of row are unchanged.

IBM DB2 9

Examples
CREATE TABLE payroll.employees ( empid INTEGER PRIMARY 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))
17

IBM DB2 9

Examples
CREATE TABLE stock.activity ( activityno SMALLINT NOT 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)
18

IBM DB2 9

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 cannot be converted to SMALLINT The nullability of a column The constraint of a column

19

IBM DB2 9

Informational Constraints
Informational Constraints are not enforced during insert and update processing. However, the DB2 SQL Optimizer will evaluate an informational constraint when resolve a query. Defined by appending the keywords NOT ENFORCED ENABLE QUERY OPTIMIZATION to a normal constraint NOT ENFORCED constraints are never checked by the system, Not even by SET INTEGRITY
20

IBM DB2 9

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
21

IBM DB2 9

SET CURRENT SCHEMA


Schemas are objects that are used to logically classify and group other objects in the database. Two-part naming convention to avoid namespace collisions for example, in PAYROLL.STAFF first part is schema name. The CURRENT SCHEMA (or CURRENT_SCHEMA) special register contains a value that identifies the schema name if no schema/qualifier name is specified, default is authorization ID of 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 it earlier.
22

IBM DB2 9

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 TRANSACTIONS ON COMMIT PRESERVE ROWS NOT LOGGED IN SESSION TEMP; (LOB data will be replaced by zeros)
23

IBM DB2 9

A Closer Look At Views


A view provides a transparent view of the data in underlying tables. Contains no data itself. Appears just like a table to the user. Can also be used to restrict 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 defined on another view is called a nested view. If a table or another view on which a view is based is dropped, the view remains defined in the database but becomes inoperative.
24

IBM DB2 9

Views with CHECK Options


Data may be inserted or updated in the underlying tables through a view. CREATE VIEW nonfictionbooks AS SELECT * FROM books WHERE booktype = 'N WITH CHECK OPTION WITH CHECK OPTION tells DB2 to check that statements using 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 those views were not defined with the check option. WITH LOCAL CHECK OPTION need only satisfy conditions of views which have the check option specified.
25

IBM DB2 9

CREATE VIEW NONFICTIONBOOKS AS SELECT * FROM BOOKS WHERE BOOKTYPE = 'N' CREATE VIEW NFBOOKS2 AS SELECT * FROM NONFICTIONBOOKS WHERE BOOKID > 100 WITH LOCAL CHECK OPTION CASCADED CHECK OPTION INSERT INSERT INSERT INSERT
26

INTO INTO INTO INTO

NFBOOKS2 NFBOOKS2 NFBOOKS2 NFBOOKS2

VALUES(10,..,'N') VALUES(10,..,'F') VALUES(120,..,'F') VALUES(120,..,N')

IBM DB2 9

A Closer Look At Indexes


An index is an object that contains an ordered set of pointers that 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 when defined 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.
27

IBM DB2 9

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 the table, but only in the CREATE TABLE statement.
28

IBM DB2 9

Another Look at Triggers


A trigger is used to define a set of actions that are to be executed whenever an insert, update, or delete operation is performed against a table or updatable view. Like constraints, triggers are often used to enforce data integrity and business rules. Unlike constraints, triggers can also be used to update other tables, automatically generate or transform values for inserted or updated rows, and invoke functions to perform tasks such as issuing errors or alerts.

Ex.

CREATE TRIGGER pay_raise BEFORE UPDATE ON employees FOR EACH ROW SET new.salary = salary * 1.1

29

IBM DB2 9

30

IBM DB2 9

1) Which of the following DB2 data types does NOT have a fixed length? -A. INT -B. CHAR -C. XML -D. DOUBLE

31

IBM DB2 9

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
32

IBM DB2 9

3) Which of the following DB2 data types can be used to store 1000 MB of singlebyte character data?

A. BLOB B. CLOB C. DBCLOB D. GRAPHIC


33

IBM DB2 9

4) Which of the following DB2 data types can NOT be used to create an identity column? A. SMALLINT B. INTEGER C. NUMERIC D. DOUBLE
34

IBM DB2 9

5) Which of the following strings can NOT be inserted into an XML column using XMLPARSE()?
A. "<employee />" B. "<name>John Doe</name>" C. "<?xml version='1.0' encoding='UTF-8' ?>" D. "<p></p>"
35

IBM DB2 9

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
36

IBM DB2 9

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
37

IBM DB2 9

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

IBM DB2 9

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


39

IBM DB2 9

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
40

IBM DB2 9

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

IBM DB2 9

12) Which of the following actions will NOT cause a trigger to be fired?

A. INSERT B. DELETE C. ALTER D. UPDATE

42

IBM DB2 9

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

IBM DB2 9

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
44

IBM DB2 9

Grazie
Italian Russian

Hebrew

Gracias Spanish

Arabic

Thank You
English Thai

Obrigado
Portuguese

Merci
French

Danke
Traditional Chinese German

Simplified Chinese

Tamil

Japanese

Korean

45

You might also like