db2udb_the_basics day2
TRANSCRIPT
Day2
Tables Views Indexes Packages Procedures Triggers Pages Tablespaces Bufferpools
2
Tables are logical structure maintained by Database manager. In a table each vertical block called as column (Tuple) and each horizontal block called as row (Entity). The collection of data stored in the form of columns and rows is known as a table. In tables, each column has different data type.
3
System Catalog Tables User Tables Temporary Tables
4
Each DB2 database has a set of tables called the system catalog tables. DB2 creates these tables when a database is created.
• DB2 creates the system catalog base tables under the SYSIBM schema like SYSIBM.SYSTABLES,SYSIBM.SYSVIEWS,SYSIBM.SYSPACKAGES.
• These tables are not erasable.• DB2 optimizer uses these to track the changes happening to the
db2 objects.
5
All the tables created by DBAs will come under this category. All the tables will be placed in usersapace1 table space by default
db2 " create table customers (id integer primary key not null, name varchar(50), age integer)”
db2 " insert into customers values (11,‘abc',27)”• db2 "select * from customers”• db2 " select tabname, tabschema, tbspace from syscat.tables“• db2 " select tabname, tabschema, tbspace from syscat.tables"|
grep -i customers• db2 describe table customers
6
Column name schema Data type name Length Scale Nulls------------------------------- --------- ------------------- ---------- ----- ------ID SYSIBM INTEGER 4 0 No NAME SYSIBM VARCHAR 50 0 Yes AGE SYSIBM INTEGER 4 0 Yes
db2 " alter table customers alter column ID set data type bigint"
Column name schema Data type name Length Scale Nulls------------------------------- --------- ------------------- ---------- ----- ------ID SYSIBM BIGINT 8 0 No NAME SYSIBM VARCHAR 50 0 Yes AGE SYSIBM INTEGER 4 0 Yes
7
db2 "alter table customers rename column NAME to NICKNAME”Column name schema Data type name Length Scale Nulls------------------------------- --------- ------------------- ---------- ----- ------ID SYSIBM BIGINT 8 0 No NICKNAME SYSIBM VARCHAR 50 0 Yes AGE SYSIBM INTEGER 4 0 Yes
db2 "drop table customers“
8
For temporary work of different database operations, DB2 uses temporary tables. The temporary tables do not appear in system catalog.
9
View is an alternative way of representing the data stored in the tables. It is not an actual table and it does not have any permanent storage. View provides a way of looking at the data in one or more tables.
• db2 “create view view_sales1(id, itemname, qty, price) as select id, itemname, qty, price from shopper.sales1”
• SYSIBM.SYSVIEWS ,SYSCAT.VIEWS • db2 drop view <view_name> • SYSCAT.TABLES, SYSCAT.VIEWS,SYSCAT.TABLESPACES are the
examples of view subjected to system catalog tables SYSIBM.SYSTABLES,SYSIBM.SYSVIEWS and SYSIBM.SYSTABLESPACES respectively.
10
Indexes are an ordered set of keys each pointing to a row in a table. They improve application performance when looking for specific rows.
Indexes are database objects that are built based on one or more columns of a table. They are used for two main reasons:
• To improve query performance. Indexes can be used to access the data faster using direct access to rows based on the index key values.
• To guarantee uniqueness when they are defined as unique indexes. SYSIBM.SYSINDEXES , SYSCAT.INDEXES db2 describe indexes for table customers show detail
11
To create an index, use the CREATE INDEX statement. This statement requires at a minimum:
• The name of the index• The name of the associated table• The columns that make up the index (also known as index keys)In addition, you can specify the following:• Whether the index is unique (enforce uniqueness for the key values) or
non-unique(allow duplicates)• Which order DB2 should use to build and maintain the key values:
ascending (ASC, the default) or descending (DESC) order• Whether to create INCLUDE columns that are not part of the index key but
are columns often retrieved by your queries
12
db2 “CREATE UNIQUE INDEX company_ix ON company (company_ID ASC, name DESC) INCLUDE (no_employees)”
13
A package is a database object consisting of executable SQL, including the access path the DB2 optimizer will take to perform the SQL operation.
14
15
Procedures are programs whose executable binaries reside at the database server. They serve as subroutines to calling applications, and they normally wrap multiple SQL statements with flow logic. They are used to reduce the traffic so improving the performance.
Besides improving response time for applications running on a different server than the database server, stored procedures also provide a central location to store database application logic. This allows for a single place to maintain your code.
16
17
There are 2 types of procedures in DB2 .1. Fenced Procedure2. Unfenced Procedure A fenced stored procedure runs in a different address space than
the DB2 engine. This guarantees that a failure from the procedure will not corrupt the DB2 engine itself. In Linux and UNIX, a fenced user needs to be created to work with fenced stored procedures.
In terms of performance, unfenced stored procedures run faster than fenced ones; however, there is a risk that unfenced procedures may corrupt DB2 information,
18
A trigger is a database object associated to a table or a view that contains some application logic, which is executed automatically upon an INSERT, UPDATE, or DELETE operation on the table or view.
Triggers can be classified as BEFORE, AFTER, or INSTEAD OF triggers.Example of Before Trigger CREATE TRIGGER default_time NO CASCADE BEFORE INSERT ON schedule
REFERENCING NEW AS n FOR EACH ROW MODE DB2SQL WHEN (n.start_time IS NULL) SET n.start_time = '12:00'
19
CREATE TRIGGER audit_qty AFTER UPDATE OF quantity ON inventory REFERENCING OLD AS o NEW AS n FOR EACH ROW MODE DB2SQL INSERT INTO sold VALUES (n.product_ID, n.daysold, o.quantity - n.quantity)
20
This example demonstrates how a read-only view can still be updated by using INSTEAD OF triggers. In the example, the trigger updates the region column of table table2 when the view view2 (a read-only view) is updated.
CREATE TRIGGER update_view2 INSTEAD OF UPDATE ON view2 REFERENCING OLD AS o NEW AS n FOR EACH ROW MODE DB2SQL BEGIN ATOMIC UPDATE table2 SET region = n.region WHERE region = o.region; END
21
DB2 stores table and index data on a page, which is the smallest unit of storage in a DB2 database.
DB2 creates and manages the pages in the table space automatically, but you can control the page size for your table spaces. If you do not explicitly specify the page size when you create
the table space, DB2 will use the default size of 4K. DB2 supports four different page sizes: 4K,8K, 16K, and 32K.
The maximum number of rows on a page is 255 rows. This is significant, if you have small row sizes.
A table space may contain up to 64 GB of data, if the page size is 4K. Chunk of pages are called as Extent
22
A table space is a storage structure, it contains tables, indexes, large objects, and long data. It can be used to organize data in a database into logical storage group which is related with where data stored on a system.
23
The table spaces are beneficial in database in various ways given as follows:
Recoverability: Tablespaces make backup and restore operations more convenient. Using a single command, you can make backup or restore all the database objects in tablespaces.
Automatic storage Management: Database manager creates and extends containers depending on the needs.
Memory utilization: A single bufferpool can manage multiple tablespaces. You can assign temporary tablespaces to their own bufferpool to increase the performance of activities such as sorts or joins.
24
When you create a new database, the database manager creates some default tablespaces for database. These tablespace is used as a storage for user and temporary data. Each database must contain at least three tablespaces as given here:
Catalog tablespace User tablespace Temporary tablespace
25
26
Logical layer between Hardware and Database
Comprised of one or more containers
A container is a file or a directory
REGULAR
CREATE TABLESPACE name
LARGE
SYSTEM
TEMPORARY
USER
MANAGED BY SYSTEM system-containers
DATABASE database-containers
27
SMS Containers
USING (‘container string’)
DMS Containers
USING (FILE ‘container string’ number of pages)
(DEVICE ‘container string’ number of pages)
28
CREATE TABLESPACE TS1 MANAGED BY SYSTEM
USING (‘/home/inst01/database/ts1’)
CREATE TABLESPACE DMS01D MANAGED BY DATABASE
USING (FILE ‘C:\DMS\DATABASE\DMS01D’ 1000)
29
The database buffer pool area is a piece of real memory that is used by DB2 to temporarily store (cache) the regular data and index pages when they are read from disk to be scanned or modified.
The buffer pool area improves the performance of the database, since the pages can be accessed
much more quickly from memory than from disk.
30
When you create a database, DB2 creates a default buffer pool named IBMDEFAULTBP.
CREATE BUFFERPOOL tempbp SIZE 10000 ALTER TABLESPACE tempspace1 BUFFERPOOL tempbp CREATE BUFFERPOOL bp16k SIZE 100000 PAGESIZE 16K ALTER BUFFERPOOL bp16k SIZE 200000
31
You will not be able to drop any buffer pools that are associated with a table space. Before you can drop the buffer pool you will need to associate the table space with a different buffer pool using the ALTER TABLESPACE statement.
DROP BUFFERPOOL bp16k
32
db2 get snapshot for bufferpools on database-nameBufferpool name = IBMDEFAULTBPDatabase name = MUSICKEGDatabase path = C:\DB2\NODE0000\
SQL00002\Input database alias = MUSICKEGSnapshot timestamp = 05/04/2005
13:11:37.329018Buffer pool data logical reads = 336Buffer pool data physical reads = 129
33
IMPORT EXPORT LOAD db2move
35
36
FileImport
Export
37
IMPORT FROM filename OF IXF
DEL
ASC
LOBS FROM lob-path MODIFIED BY options
MESSAGES
INSERT INTO table-name
INSERT_UPDATE
REPLACE
REPLACE_CREATE
38
EXPORT TO file OF IXF MESSAGES message-file
DEL
WSF
select statement
39
1) Load Loads data, collects index keys
2) Build creates the indexes
3) Delete Delete unique key violations place into exception tables.
4) Index Copy – copy indexes from temp table space
40
LOAD FROM filename OF IXF
ASC
DEL
LOBS FROM lob-path MODIFIED BY options
MESSAGES message-file
INSERT INTO table-name
REPLACE
RESTART
TERMINATE
41
Create nickname sales for
another database SAMPLE table SALES
Create nickname employee for
another database SAMPLE table EMPLOYEE
DECLARE C1 CURSOR FOR SELECT SALES.SALES_PERSON, LASTNAME, FIRSTNME FROM SALES, EMPLOYEE
WHERE SALES_PERSON = EMPLOYEE.LASTNAME
LOAD FROM C1 OF CURSOR INSERT INTO LOCAL_SALES
db2move
Database
42
db2move.lst
table.ixf
DB2MOVE
43
db2move database-name import
export
load
tc table-creators
tn table-name
sn schema-names
ts table space-names
44
CREATE TABLESPACE TS1 MANAGED BY SYSTEM
USING (‘C:\SMS\MUSICKEG\TS1’)
CREATE TABLESPACE DMS01D MANAGED BY DATABASE
USING (FILE ‘C:\DMS\MUSICKEG\DMS01D’ 161)
EXTENTSIZE 8 PREFETECHSIZE 8
CREATE TABLESPACE DMS01I MANAGED BY DATABASE
USING (FILE ‘C:\DMS\MUSICKEG\DMS01I’ 48)
EXTENTSIZE 4 PREFETCHSIZE 4
45
Defining logsRecovery of databaseRecovery of a table spaceOffline versus Online
47
Database
S0000000.log
S0000001.log
S00000002.log
S0000003.log (Secondary Log)
S0000004.log (Secondary Log)
48
Database
S0000000.log
S0000001.log
S00000002.log
S0000003.log
S0000004.log
49
If LOGRETAIN = Recovery you may backup table space or database
If LOGRETAIN = NO you may only backup database
BACKUP DB database-name ONLINE to C:\backup INCLUDE LOGS
50
If LOGRETAIN = NO, you may only recover the database
If LOGRETAIN = RECOVERY, you may recover a table space or a database from a full database backup
51
Offline OnlineRESTORE DB database-name FROM file TAKEN AT
time
ROLLFORWARD DATABASE database-name TO isotime AND STOP END OF LOGS
52
Database_standby
Database1
Laptop computer
53
Database Configuration parameters Database Structure SQL Statements
55
56
57
Database
Buffer Pool
Select * from Staff
58
Sorts are done in sortheap If no space for sort data is moved to
TEMPSPACEn GET SNAPSHOT FOR ALL ON database
59
Dynamic SQL statements
Package Cache
Select * from Staff where ID = 10Select * from Staff where ID = 10
Update Staff Set Salary = Salary + 100 where ID = 10
Select * from EMPLOYEE
60
Locks are held to prevent loss of data Lock Row / Table / Table Space LOCKLIST MAXLOCKS ALTER TABLE table-name LOCKSIZE TABLE
61
62
Determine which statement is causing the majority of problems
Determine what might be causing the problem Testing the solution
63
64
65
66
Buffer pools Numerous Database Configuration
parameters SQL Statement Tuning
67
Security is used at the operating system level
Table access is through the database
69
SYSADM_GROUP SYSCTRL_GROUP SYSMAINT_GROUP SYSMON_GROUP
70
GRANT access to an object/program REVOKE access to an object/program GRANT SELECT ON TABLE ARTISTS TO
USER1
71
The Relational Database can be simple or complex
The database structure is simple, Table spaces, Tables, etc.
Recovery is straight forward Database maintenance can be automated Tuning the database is a life long endeavor
72
July 12, 13 DB2 UDB Administration Proof of Technology
IBM – McClean Tec 8401 Greensboro Drive McClean, VA 22102 Suite 120 First Floor WebSphere Information Integrator July 14, 2005 Contact: Keith E. Gardenhire [email protected]
73
74