DB2 Database Objects
Tables:
- They are used to save user data in row and column format.
- CREATE
TABLE Command is used to create table, while creating table we can also
specify explicitly to which tablespace it should be saved using IN
clause as shown below.
- CREATE TABLE artists
(
artno SMALLINT NOT NULL,
name VARCHAR(50),
picture BLOB(2M) NOT LOGGED COMPACT
) IN dms01
- Table artists will be saved in tablespace dms01.
- All the Indexes and LOB data can be saved in different tablespace as shown below
- CREATE TABLE artists
(
artno SMALLINT NOT NULL PRIMARY KEY,
name VARCHAR(50),
picture BLOB(2M) NOT LOGGED COMPACT
)
IN dms01
INDEX IN dms02
LONG IN dms03
CREATE INDEX idx_name ON artists (name)
- Table
artists will be saved in tablespace dms01, Index of PK and idx_name
will be saved in tablespace dms02 and BLOB datatype column value will be
saved in dms03.
- Condition is that all the three tablespaces has to be DMS in nature.
- ALTER TABLE command can be used to
- The ALTER TABLE statement modifies existing tables by:
Adding
One or more columns to a table
Adding or dropping
Primary key
One or more unique, referential or check constraint definitions
Drop table restriction
Partitioning key (DPF)
Altering columns
Drop a column
Alter column data type (to compatible data types)
Alter column nullability
Length of a VARCHAR column
Reference type column to add a scope
Generation expression of a generated column
One or more check or referential constraints attributes
Change table attribute
DATA CAPTURE, PCTFREE, LOCK SIZE or APPEND MODE.
Setting table attribute “NOT LOGGED INITIALLY"
Partitioned Table:
- Like
Tablespace, Table is also an logical entity. But rows with each table
are physical entity as they are physically stored inside Page.(smallest
unit of DB2 Database).
- When Rows of tables are distributed
across multiple containers(storage location) then such tables are called
as Partitioned Table.
- Boundaries are defined for each such partition.
- CREATE TABLE sales(sale_date DATE, customer INT, …)
PARTITION BY RANGE(sale_date)
(
STARTING MINVALUES IN TBSP1,
STARTING '3/1/2000' IN TBSP2,
STARTING '6/1/2000' ENDING '9/30/2000' IN TBSP3
);
- In the above Query table sales is partitioned into three parts based upon the column sales_date.
- All rows before 3/1/00 will be saved in tablespace TBSP1
- All rows from 3/1/00 till 6/1/00 will be saved in tablespace TBSP2
- All rows from 6/1/00 till 9/30/00 will be saved in tablespace TBSP3
IDENTITY Column
- If any column of a table is declared as IDENTITY column, then that column will autogenerate UNIQUE numeric values for itself.
- Generally Primary Key column is declared as IDENTITY column.
- IDENTITY Column are like sequence object but sequence objects are not dependent on table where as IDENTITY Column are.
- There are two approaches to declare as column as IDENTITY column
- GENERATED ALWAYS: Numeric value are automatically generated by DB2 and user can not provide it own value for this column.
- GENERATED BY DEFAULT:If user did not provide it own value for this column, only then numeric value are automatically generated by DB2. Uniqueness is not guaranteed
- CREATE TABLE inventory (
partno INTEGER
GENERATED ALWAYS AS IDENTITY
(START WITH 100, INCREMENT BY 1),
description CHAR(20) );
INSERT INTO inventory VALUES (DEFAULT,'door'); ---> inserts 100,door
INSERT INTO inventory (description) VALUES ('hinge'); ---> inserts 101,hinge
INSERT INTO inventory VALUES (102,'window'); ---> ERROR, value always generated
COMMIT;
INSERT INTO inventory (description) VALUES ('lock'); ---> inserts 102,lock
ROLLBACK;
INSERT INTO inventory (description) VALUES ('frame'); ---> inserts 103,frame
COMMIT;
- We can use IDENTITY_VAL_LOCAL() function to retrieve the
generated identity value.
Example 1:
INSERT INTO T1 (ID, ...) VALUES (DEFAULT, ....);
SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1;
Example 2:
INSERT INTO PARENT_TABLE (PK_ID, ... )
VALUES (DEFAULT, ...);
INSERT INTO CHILD1_TABLE ,...,FK_ID,...)
VALUES (...., identity_val_local(),...);
INSERT INTO CHILD2_TABLE ,...,FK_ID,...)
VALUES (...., identity_val_local(),...);
SEQUENCE
- Unlike IDENTITY Column,Sequence is an Database Object for generating unique values.
- CREATE SEQUENCE myseq
START WITH 1
INCREMENT BY 1
NO CYCLE
- NEXTVAL FOR <seqname>:- It displays Next value within the sequence.
PREVVAL FOR <seqname>:- It displays Current value of the sequence.
- Example:- INSERT INTO t1 VALUES (nextval for myseq, ...)
SELECT prevval for myseq FROM sysibm.sysdummy1
INDEXES
- Following are the types of indexes available in DB2
- ascending or descending
- unique or non-unique
- bi-directional (no storage overhead, see notes)
- compound
- cluster
- include columns
- By default all the indexes generated are Ascending Order
- They can be unique or Non unique, it depends on the column on which Index is being generated.
- Bi-directional Indexes allow application to search from both end(top-bottow).
- Compound Indexes consists of multiple column as Primary Key.
- A clustering index determines how rows are
physically ordered (clustered) in a table space. Clustering indexes
provide significant performance advantages in some operations, particularly
those that involve many records.
- When an index contains include columns, it may help performance. If the include column is involved in
a
SELECT that only selects columns from the index, and the index is
used
to access the rows, by having the column INCLUDED in the index, you
can
avoid accessing the table data.
VIEWS
- A view provides a different way of looking at the data in one or more
tables; it is a named specification of a query result
- DB2 uses the CHECK OPTION to specify a constraint to be
enforced on every row being inserted or updated through the
view.
- CREATE VIEW emp_view2 (id, empname, deptno)
AS (SELECT empno, lastname, workdept
FROM employee WHERE dept = 10)
WITH CHECK OPTION;
- Condition "deptno = 10" will be checked for insert and update operations
against this view
- CREATE VIEW emp_view3 AS
( SELECT empno, empname, deptno FROM emp_view2
WHERE empno > 20 ) WITH CASCADED CHECK OPTION;
- Conditions deptno = 10 AND empno > 20 will be checked for insert and
update operations against this view
- CREATE VIEW emp_view4 AS
( SELECT empno, empname, deptno FROM emp_view3
WHERE name = 'Smith' ) WITH LOCAL CHECK OPTION;
- Only condition name='Smith' (defined in emp_view4) is checked for inserts
and updates
Hierarchy of Storage Units
- In DB2 smallest storage units is Page, then comes extent, container and largest of all is tablespace.
- Lets start with Page:-
- Page is considered to be the smallest unit for storage, which is available in 4K,8K,16K and 32K size.
- Basic Page structure consists of
- Page Header(Fixed Length):- It stores location of continuous free space(i.e its offset), free space(Hole Chain) and total amount of free space within the page.
- Page Trailer(Variable Length):- It stores an array of pointers, pointing to the address of the starting point of each row saved within the page. Value of this pointers is called as RBA(Relative Byte Address). As the size of RBA is 2 bytes, page is limited to save only 255 entries(rows).
- Page Content(Variable Length):- It stores row entries of either table or index but not of both.
- When there is more than 4 bytes of free space available in Page, it is called as Large Hole and maintained by Hole chain List. If free space available is less than 4 bytes its not maintained.
- Next is Extents:-
- An Extent is defined as continuous collection of pages.
- All the Pages in an Extent must belong to single Table or Single Index only.
- It's basic IO unit for writing data from bufferpool(in RAM) to database files(on hard disk).
- Page Size and Extent Size are declared during the creation of tablespace and can't be modified later.
- Typically an OLTP environment will have small pages (4k,8k), and a small number of pages per extent: 4,6,16. Decision Support and Data Warehousing applications will have larger pages (16 or 32K), and larger extents (16, 32, 64 or 128). The extent size should be chosen based on the table size and anticipated usage, depending on whether the application is query intensive, transaction intensive or a mixture of both. Smaller tables are handled more efficiently with smaller extents.
- Next is Containers:-
- Containers define the storage path(location) on the OS where data is being saved. It also defines the directory structure in case of partition storage / distributed storage configuration.
- In Automatic Storage the database has a number of storage paths associated with them, and the tablespaces (and hence containers) in the database are assigned and allocated based on those storage paths by DB2.
- In this way, you don’t need to explicitly define the containers. They will grow automatically in their directory paths, and if the directory paths are on different disks, the table data will be spread across these disks. DB2 will create new containers if they are needed.
- Automatic storage gives the best options of DMS (speed and flexibility) and SMS (ease of administration)
- Next is Tablespace:-
- Tablespace can be defined as collection of containers. Containers basically provide location to save data.
- For each tablespace, you have to define the page size, and each tablespace must have access to a bufferpool of the same page size, and a system temporary tablespace of the same page size.
- You have to specify which buffer pool the table space is associated with.
- Extents are stored within containers. Depending on how the containers
are set up (either with Automatic Storage, DMS or SMS) there is a path
associated with each container to part of the physical file system. If
the tablespace (and hence containers) are on a disk array, the extent
size should be set to the disk stripe size
- There are three types of tablespace in DB2; Regular, Large, and Temporary.
- A default database will have 1 bufferpool and 3 tablespace as follows
- SYSCATSPACE Tablespace(REGULAR)
- TEMPSPACE1 Tablespace(TEMPORARY)
- USERSPACE1 Tablespace(LARGE)
- IBMDEFAULTBP