Sie sind auf Seite 1von 12

IBM DB2 9

Section 5 - Working with DB2 Tables,


Views, and Indexes (23.5%)
IBM DB2 9

 Ability to demonstrate proper usage of DB2 data types


 Given a situation, ability to create a table
Section -5) Working with DB2 Tables,
Views, and Indexes  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

© 2008 IBM Corporation


2

IBM DB2 9 IBM DB2 9

Categories of Data Types in DB2 9 Built-in data types - Numeric


 SMALLINT – 2 Bytes
The built-in data types are categorized as follows: (-32,768 to 32,767)
 Numeric  INTEGER/INT – 4 Bytes
 String (-2,147,483,648 to 2,147,483,647)
 Date-time  BIGINT – 8 Bytes
 XML  DECIMAL/DEC/NUM/NUMERIC –
The user-defined data types are categorized as: (p/2)+1 Ex. 67.12345 has precision
of 7, 7 ÷ 2 is 3, + 1 makes 4
 User-defined distinct type
 REAL/FLOAT – 4 Bytes
 User-defined structured type
(1.175E-37 to 3.402E+38)
 User-defined reference type
 DOUBLE – 8 Bytes
In addition to these, special data types designed to be (2.225E-307 to 1.79769E+308)
used with the DB2 Extenders.
3 4

1
IBM DB2 9 IBM DB2 9

Built-in data types - String Built-in data types – Date Time


•Variable-length character data type
•Can store up to 32,672
•Variable-length •The
•The
character fixed-length
characters
fixed-length
data type character
governeddouble
by the table
bytespace page
character
•Character Large
size used Object
•Can data
store 1 type
to 254 characters DATE :
•Can store up to 32,672
•Variable-length •Can characters
store regardless
1 to 127 of the
characters table
•Can
•CHARACTER store
•Variable-length up todouble
double
VARYING, 2GB
byte
CHAR byte
but character
anddata
CLOB(800)
character
VARYING,
•CHARACTER data
andtype
type
for
VARCHAR
CHAR 800Keywords
bytes
Keywords - Is stored internally as a (packed) string of 4 bytes.
space
•Can•Can page
store
store up up
to size
to used
•GRAPHIC
16,338
16,336 Keyword
characters
characters governed
•Keyword CHARACTER LARGE OBJECT, CHAR LARGE is
regardless
by used
the of
tablethe table - Externally, string has a length of 10 bytes (MM-DD-YYYY -
•Keyword
space pageLONG
size VARCHAR is used
used
space page
OBJECT, and size used
CLOB can vary and is dependent on country code).
•Double
•VARGRAPHIC Byte
•Keyword LONG
Character
Keyword used toLarge
VARGRAPHIC denote Object
it
is used
data type
•Can store up to 2GB data type TIME :
•Binary Large Object
- Is stored internally as a (packed) string of 3 bytes.
•Keyword used is DBCLOB
•Can store up to 2GB
- Externally, string has a length of 8 bytes (HH-MM-SS - this
•Keyword used is BLOB representation 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 ).

5 6

IBM DB2 9 IBM DB2 9

Built-in data types – XML User-defined Data Types


 An value that is stored in a column defined with the  User-defined distinct types
Extensible Markup Language (XML) data type must be a - Define a new data type based on a built-in type. This new
well-formed XML document. type has the same features, but you can use it to ensure
that only values of the same type are compared.
 XML documents can only be stored in single-partition - CREATE DISTINCT TYPE CANDOL AS DECIMAL(10,2)
databases that have been defined using the UTF-8 code WITH COMPARISONS
set.  User-defined structured types
 XML values are processed in an internal representation - 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 is not comparable to any string value. that contains data for street number, street name, city, and so forth.
 XMLSERIALIZE (XML value ) = serialized string value  User-defined reference types
 XMLPARSE(string value) = XML value - When using structured types, define references to rows in another table
using reference types.

7 8

2
IBM DB2 9 IBM DB2 9

DB2 Extenders Tables


Provide support for complex, nontraditional data All data is stored in tables in the database. A table
types consists of one or more columns of various data
Packaged separately from the DB2 server code and types. The data is stored in rows or records.
is database dependant May be defined using:
- The CREATE TABLE SQL statement
For example, the DB2 Image Extender includes:
- A GUI tool, the DB2 Control Center
- The DB2IMAGE UDT The catalog view SYSCAT.TABLES contains a row
- UDFs to insert/retrieve from a db2image column for each table defined in the database.
- APIs to search based on characteristics of images SYSCAT.COLUMNS contains a row for each column
of each table in the database.

9 10

IBM DB2 9 IBM DB2 9

CREATE TABLE SQL Creating Tables with XML Columns


 CREATE TABLE [TableName]([Column], ...) CREATE TABLE emp_resume (
<IN [TablespaceName]> empid INTEGER NOT NULL PRIMARY KEY,
resume XML,
<INDEX IN [TablespaceName]> CONSTRAINT xv CHECK (resume IS VALIDATED))
<LONG IN [TablespaceName]>
XML column used has the following restrictions:
 [ColumnName][DataType] <NOT NULL>
 It cannot be part of primary key, foreign key or UNIQUE or
<WITH DEFAULT <[DefaultValue]> | any index except an XML index.
<GENERATED <ALWAYS | BY DEFAULT> AS IDENTITY>  It cannot have a specified default value or a WITH DEFAULT
<UniqueConstraint> clause-if the column is nullable, the default value for the
column is the null value.
<CheckConstraint>
 It can be checked for its validity and well-formed ness if the
<ReferentialConstraint> CHECK constraint contains the VALIDATED predicate.
11 12

3
IBM DB2 9 IBM DB2 9

Creating Tables with Identity Columns Constraints


 DB2 Database Manager can automatically generate numbers  Unique constraints, which are used to ensure that values in
for a column if the column is defined as an identity column. a column are unique
The syntax used to create an identity column is: <CONSTRAINT [ConstraintName]> [UNIQUE | PRIMARY KEY]
 Referential integrity constraints, which are used to define
 [ColumnName][DataType] GENERATED <ALWAYS | BY relationships between tables.
DEFAULT> AS IDENTITY <CONSTRAINT [ConstraintName]> REFERENCES
<( <START WITH [1 | StartingValue]> [PKTableName]<([PKColumnName], ...)
<INCREMENT BY [1 | IncrementValue]> <ON UPDATE [RESTRICT | NO ACTION]> <ON DELETE
<NO MINVALUE | MINVALUE [MinValue]> [CASCADE | SET NULL | RESTRICT | NO ACTION]>
<NO MAXVALUE | MAXVALUE [MaxValue]>  Table check constraints, which are used verify that column
<NO CYCLE | CYCLE> data does not violate rules defined for the column
<NO CACHE | CACHE [CacheSize]> <CONSTRAINT [ConstraintName]> CHECK ([CheckConditi])
<NO ORDER | ORDER> )> <ENFORCED | NOT ENFORCED> <ENABLE QUERY OPTIMIZATION
| DISABLE QUERY OPTIMIZATION>
13 14

IBM DB2 9 IBM DB2 9

Referential Integrity Constraints – UPDATE Rule Referential Integrity Constraints – DELETE Rule
<ON UPDATE [RESTRICT | NO ACTION]> <ON DELETE [CASCADE | SET NULL | RESTRICT | NO ACTION]>
 RESTRICT  RESTRICT  CASCADE
- Update for parent key will be - Delete for parent key will be - Implies that deleting a row in
rejected if a row in dependent rejected if a row in dependent parent table automatically
table matches original values of table matches original values of deletes any related rows in
key. key. dependent table.

 NO ACTION  NO ACTION
 SET NULL
- Update operation for parent key - Delete operation for parent key
- Ensures that deletion of a row in
will be rejected if any row in will be rejected if any row in
parent table sets values of
dependent table does not have a dependent table does not have a
foreign key in any dependent
corresponding parent key when corresponding parent key when
row to null (if nullable).
update statement is completed . update statement is completed .
- Other parts of row are
- This is the default. - This is the default.
unchanged.
15 16

4
IBM DB2 9 IBM DB2 9

Examples Examples
 CREATE TABLE payroll.employees (  CREATE TABLE stock.activity (
empid INTEGER PRIMARY KEY, activityno SMALLINT NOT NULL
emp_name CHAR(30), mgrno INTEGER, GENERATED BY DEFAULT AS IDENTITY
CONSTRAINT fkconst FOREIGN KEY (mgrno) (START WITH 10 INCREMENT BY 10),
REFERENCES payroll.employees(empid) ) actkwd CHAR(6) WITH DEFAULT ‘Action’)
 CREATE TABLE payroll.paychecks (  CREATE TABLE stock.copy LIKE stock.activity
empid INTEGER, weeknumber CHAR(3),  CREATE TABLE part_table (
pay_amt DECIMAL(6,2), col1 INT, col2 CHAR(3))
CONSTRAINT fkconst FOREIGN KEY (empid) PARTITION BY (col1 NULLS FIRST)
REFERENCES employee(empid) ON DELETE (STARTING 0 ENDING 9 IN tbsp0,
CASCADE, STARTING 10 ENDING 19 IN tbsp1,
CONSTRAINT chk1 CHECK (pay_amt > 0 AND STARTING 20 ENDING 29 IN tbsp2,
weeknumber BETWEEN 1 AND 52)) STARTING 30 ENDING 39 IN tbsp3)
17 18

IBM DB2 9 IBM DB2 9

Alter Table Informational Constraints


Using it you can add or You can also change:  Informational Constraints are not
drop:  The identity attributes of a column enforced during insert and
 A column update processing. However,
 The length of a string column the DB2 SQL Optimizer will
 A primary key (Only increase) evaluate an informational
 One or more unique  The datatype of a column but new constraint when resolve a query.
or referential datatype must be compatible. For
 Defined by appending the
constraints example, convert an INTEGER
keywords NOT ENFORCED
 One or more check column to BIGINT is possible, but, ENABLE QUERY
constraints a DECIMAL(10,2) column cannot OPTIMIZATION to a normal
be converted to SMALLINT constraint
 The nullability of a column
 NOT ENFORCED constraints are never checked by the
 The constraint of a column
system, Not even by SET INTEGRITY
19 20

5
IBM DB2 9 IBM DB2 9

Temporarily Suspending Constraint Checking SET CURRENT SCHEMA


 Constraint checking for a table can be suspended temporarily  Schemas are objects that are used to logically classify and
group other objects in the database.
by executing the SET INTEGRITY statement.
 Two-part naming convention to avoid namespace collisions
- SET INTEGRITY FOR employees OFF
for example, in PAYROLL.STAFF first part is schema name.
 To resume constraint checking for the EMPLOYEES table that  The CURRENT SCHEMA (or CURRENT_SCHEMA) special
constraint checking was suspended register contains a value that identifies the schema name if no
schema/qualifier name is specified, default is authorization ID
- SET INTEGRITY FOR employees IMMEDIATE CHECKED of the current session user.
 If you want to transfer all offending rows in a separate table  To change the value of the CURRENT SCHEMA,
say BAD_ROWS SET CURRENT SCHEMA = 'PAYROLL'
- SET INTEGRITY FOR employees IMMEDIATE CHECKED  On reconnect, the CURRENT SCHEMA special register will
FOR EXCEPTION IN employees USE bad_rows contain your authentication ID, not the value you assigned it
earlier.
21 22

IBM DB2 9 IBM DB2 9

Declared Temporary Tables A Closer Look At Views


 It is used to create temporary tables that are used only during A view provides a transparent view of the data in
a session. underlying tables. Contains no data itself. Appears
 The only object that can be DECLARED is a table. just like a table to the user. Can also be used to
 These tables are not persistent and can be used only by the restrict which rows and columns can be viewed or
application that creates them. When the application updated
terminates, the rows of the table are deleted, and the You can create a view on an existing table (or tables)
definition of the table is dropped.
or on another view or any combination. A view defined
 DECLARE GLOBAL TEMPORARY TABLE
on another view is called a nested view.
T1 LIKE TRANSACTIONS
ON COMMIT PRESERVE ROWS If a table or another view on which a view is based is
NOT LOGGED IN SESSION TEMP; dropped, the view remains defined in the database but
(LOB data will be replaced by zeros) becomes inoperative.
23 24

6
IBM DB2 9 IBM DB2 9

Views with CHECK Options CREATE VIEW NONFICTIONBOOKS AS


SELECT * FROM BOOKS
 Data may be inserted or updated in the underlying tables
through a view. WHERE BOOKTYPE = 'N'
CREATE VIEW nonfictionbooks AS CREATE VIEW NFBOOKS2 AS
SELECT * FROM books WHERE booktype = 'N‘ SELECT * FROM NONFICTIONBOOKS
WITH CHECK OPTION WHERE BOOKID > 100
 WITH CHECK OPTION tells DB2 to check that statements WITH LOCAL CHECK
CASCADED OPTION
CHECK OPTION
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 INSERT INTO NFBOOKS2 VALUES(10,..,'N')
views were not defined with the check option. INSERT INTO NFBOOKS2 VALUES(10,..,'F')
 WITH LOCAL CHECK OPTION need only satisfy conditions INSERT INTO NFBOOKS2 VALUES(120,..,'F')
of views which have the check option specified. INSERT INTO NFBOOKS2 VALUES(120,..,‘N')
25 26

IBM DB2 9 IBM DB2 9

A Closer Look At Indexes  Example of creating a non-unique index in ascending order :


- CREATE INDEX ibookname ON books (bookname)
 An index is an object that contains an ordered set of pointers
 You can specify different orders for the columns in the index:
that refer to rows in a base table.
- CREATE INDEX i2bookname ON books (authoid
 Two reasons why you might create an index: DESC, bookname ASC)
- To ensure uniqueness of values in a column or columns.  Specify a bidirectional index:
- To improve performance of queries against the table when - CREATE INDEX bibookname ON books (bookname)
defined on the appropriate column(s). ALLOW REVERSE SCANS
 Non-unique indexes allow duplicate key values; unique  A clustering index increases performance by decreasing no.
indexes allow only one occurrence of a key value in the list of I/O, since like data values are stored on the same page.
including a single null value. - CREATE UNIQUE INDEX indx ON employees
 Indexes are additional copies of the values so they must be (empno) CLUSTER
updated if the data in the table is updated. For frequent  An index can be placed in a separate table space from the
updates, this could impact performance. table, but only in the CREATE TABLE statement.
27 28

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

IBM DB2 9 IBM DB2 9

1) Which of the following DB2 data types 2) Which of the following is the best statement to use
to create a user-defined data type that can be used
does NOT have a fixed length? to store currency values?
A. CREATE DISTINCT TYPE currency AS
-A. INT NUMERIC(7,2)
B. CREATE DISTINCT TYPE currency AS
-B. CHAR SMALLINT
-C. XML C. CREATE DISTINCT TYPE currency AS
BIGINT
-D. DOUBLE
D. CREATE DISTINCT TYPE currency AS
DOUBLE
31 32

8
IBM DB2 9 IBM DB2 9

3) Which of the following DB2 data types 4) Which of the following DB2 data types
can be used to store 1000 MB of single- can NOT be used to create an identity
byte character data? column?

A. SMALLINT
A. BLOB
B. INTEGER
B. CLOB
C. NUMERIC
C. DBCLOB
D. DOUBLE
D. GRAPHIC
33 34

IBM DB2 9 IBM DB2 9

5) Which of the following strings can NOT 6) Which two of the following are optional
be inserted into an XML column using and do not have to be specified when
XMLPARSE()? creating a table?
A. Table name
A. "<employee />" B. Column name
B. "<name>John Doe</name>" C. Default constraint
C. "<?xml version='1.0' encoding='UTF-8' ?>"
D. Column data type
D. "<p></p>"
E. NOT NULL constraint
35 36

9
IBM DB2 9 IBM DB2 9

7) Given the following CREATE TABLE statement: 8) If table TAB1 is created using the following
CREATE TABLE table2 LIKE table1 statement:
Which two of the following will NOT occur when the CREATE TABLE tab1 (col1 INTEGER NOT NULL,
statement is executed? col2 CHAR(5), CONSTRAINT cst1 CHECK
(col1 in (1, 2, 3)))
A. TABLE2 will have the same column names and column data
Which of the following statements will successfully
types as TABLE1
insert a record into table TAB1?
B. TABLE2 will have the same column defaults as TABLE1
C. TABLE2 will have the same nullability characteristics as A. INSERT INTO tab1 VALUES (0, 'abc')
TABLE1 B. INSERT INTO tab1 VALUES (NULL, 'abc')
D. TABLE2 will have the same indexes as TABLE1. C. INSERT INTO tab1 VALUES (ABS(2), 'abc')
E. TABLE2 will have the same referential constraints as TABLE1
D. INSERT INTO tab1 VALUES (DEFAULT, 'abc')
37 38

IBM DB2 9 IBM DB2 9

9) Which of the following is NOT a characteristic of a 10) Which of the following is NOT true about schemas?
unique index?
 A. If a schema name is not specified, either by qualifying a
 A. Each column in a base table can only participate in one database object name or by executing the SET CURRENT
unique index, regardless of how the columns are grouped (the SCHEMA statement, the authorization ID of the current
same column cannot be used in multiple unique indexes)
session user is used as the schema name by default
 B. In order for an index to be used to support a unique
 B. The value assigned to the CURRENT SCHEMA special
constraint, it must have been defined with the UNIQUE attribute
register is persistent across database restarts
 C. A unique index cannot be created for a populated table if the
key column specified contains more than one NULL value
 C. A schema enables the creation of multiple objects in a
database without encountering namespace collisions
 D. A unique index can only be created for a non-nullable
column  D. When most database objects are created, they are
either implicitly or explicitly assigned to a schema
39 40

10
IBM DB2 9 IBM DB2 9

11) Given the following statements: 12) Which of the following actions will NOT
CREATE TABLE table1 cause a trigger to be fired?
(col1 INTEGER, col2 CHAR(3));
CREATE VIEW view1 AS SELECT col1, col2
FROM table1 WHERE col1 < 100 A. INSERT
WITH LOCAL CHECK OPTION;
Which INSERT statement will execute successfully?
B. DELETE
A. INSERT INTO view1 VALUES (50, abc) C. ALTER
B. INSERT INTO view1 VALUES(100, abc) D. UPDATE
C. INSERT INTO view1 VALUES(50, 'abc')
D. INSERT INTO view1 VALUES(100, 'abc')
41 42

IBM DB2 9 IBM DB2 9

13) Which of the following CREATE TABLE 14) Which of the following is NOT a characteristic of a
statements will NOT be successful? declared temporary table?
A. Declared temporary tables are not persistent and
A. CREATE TABLE t1 (c1 XML NOT NULL can only be used by the application that creates them
UNIQUE, c2 INT) B. It is possible for many applications to create
declared temporary tables that have the same name
B. CREATE TABLE t1 (c1 XML NOT NULL, c2
CHAR(20)) C. Declared temporary tables are created by
executing a CREATE TABLE statement with the
C. CREATE TABLE t1 (c1 XML CHECK (c1 IS DECLARED GLOBAL TEMPORARY clause specified
VALIDATED), c2 INT) D. Once the application that created a global
D. CREATE TABLE t1 (c1 XML, c2 XML) temporary table is terminated, any records in the table
are deleted and the table is automatically destroyed
43 44

11
IBM DB2 9

Grazie Hebrew
Italian

Gracias
Spanish
Russian

Obrigado

Thank
Portuguese

Arabic

Merci
French

Traditional Chinese
You English
Danke
German

Thai
Simplified Chinese Tamil

Japanese Korean

45

12

Das könnte Ihnen auch gefallen