Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The purpose of this guide is to provide a quick reference to relate DB2 and Oracle
terminology and to provide a comprehensive set of scripts to a DB2/Oracle DBA so
that with some training they are able to fulfil the fole of a development DBA in either
database .
Index
1. Object/code types.......................................................................................................4
2. Column datatypes.......................................................................................................5
3. Database memory model............................................................................................6
3.1 DB2......................................................................................................................6
3.2 Oracle...................................................................................................................6
4. Database basic configuration parameters...............................................................7
5. Database server processes..........................................................................................9
5.1 DB2......................................................................................................................9
5.2 Oracle...................................................................................................................9
6. Database layout........................................................................................................10
7. DB2 lock isolation levels.........................................................................................12
8. Database scripting languages...................................................................................15
9. Database Monitoring................................................................................................16
10. DBA commands.....................................................................................................17
11. Main Differences....................................................................................................29
1. Object/code types
Db2
Dbm cfg
Db cfg
Database manager/Instance
Database
Tablespace
Container
Extent
Page
Bufferpool
Schema
Table
Index
Sequence
View
SQL/PL
Package(collection of static sql access
plans)
(No equivalent)
Control Center
Trigger
db2systm, sqldbcon, db2rhist.asc
Stored procedure
Function
Diagpath (db cfg) default=db2diag.log
(No equivalent)
Oracle
Spfile<sid>.ora
Spfile<sid>.ora
Instance
Database
Tablespace
Datafile
Extent
Blocksize
db_cache_size,
db_$blocksize_cache_size,
db_keep_cache_size
No real equivalent. user=schema in
Oracle
Table
Index
Sequence
View
PL/SQL
(No equivalent)
package (collection of procedures/udfs)
Enterprise Manager
Trigger
control File (control0x.ctl)
stored procedure
Function
<sid>alrt.log
rollback segments/undo tablespace (used
to capture before-update info)
2. Column datatypes
DB2
char
varchar
smallint
integer
bigint
decimal(x,x)
date
time
timestamp
blob
clob
long
Oracle
char
varchar2
number(3,0)
number(6,0)
number(10,0)
number(x,x)
date (to_char(date,DD-MON-YYYY))
date (to_char(date,HH:MM:SS))
date
blob
clob
long
3.2 Oracle
System Global Area (SGA) (consists of shared pool, database buffer cache, redo log
buffer, java pool, streams pool and large pool)
Process Global Area (PGA) (sort area, hash area, bitmap merge area, stack etc)
Note: DB2s instance/database/application shared memory roughly correspond
to Oracles SGA and DB2s application private memory roughly corresponds to
Oracles PGA.
Oracle
db_block_size
db_create_file_dest
db_create_online_log_dest_n
db_domain
db_name, db_unique_name
db_recovery_file_dest
db_recovery_file_dest_size
db_unique_name
instance_name
job_queue_processes
log_archive_dest_n,
log_archive_dest_state_n
nls_language, nls_territory
open_cursors
pga_aggregate_target
processes
remote_listener
remote_login_passwordfile
rollback_segments
sessions
sga_target
7
database_memory=automatic,
db_mem_thresh
max_connections, max_coordagents
No equivalent
No equivalent. Transactions are rolled
back by reading the transaction logs.
Undo data is not stored separately.
maxtotfilop
num_iocleaners
dft_prefetch_sz
max_querydegree
softmax
logretain
logbufsz
catalogcache_sz
pkgcachesz
sortheap
buffpage
util_heap_sz
shared_servers
star_transformation_enabled
undo_management, undo_tablespace
db_files
db_writer_processes
db_file_multiblock_record_count
parallel_max_servers
log_checkpoint_interval,
log_checkpoint_timeout
log_archive_start
log_buffer
dictionary cache (part of
shared_pool_size)
library cache (part of shared_pool_size)
sort_area_size
db_cache_size
large_pool_size
5.2 Oracle
PMON - monitors user processes and cleans them up if they fail
SMON - monitors server processes and cleans them up if they fail
MMON - issues alerts when threshold values have been reached and captures table
and index statistics at intervals
MMAN - manages the automatic allocation of shared memory
MMNL - Captures sesson history and computes metrics
DBWR - writes dirty data in the bufferpool down to disk
ARCn - archives redo log files
LGWR - writes redo log files
CKPT - performs a checkpoint at appropriate time
6. Database layout
The same rules go for DB2 as they do for Oracle. i.e.
1. Put indexes in separate tablespaces on separate disks from the table data.
2. Put logs on fast disks, again separate from the index and disks.
3. Keep static/slow changing data in separate tablespaces from dynamic/quick
changing data
4. Size tables so that all the data goes in 1 extent, where possible.
With DB2, you multiplex the control files or transaction logs from the database but
you can, of course, mirror them at the operating system level.
In Oracle, prior to Oracle 9i, you could only define a block size at the database level
and all tablespaces had to use that block size. Since Oracle 9i, you can assign a
different block size at the tablespace level, and you can assign a single buffer cache
for each block size. To retain tables in memory, Oracle has a keep buffer cache.
You can create multiple bufferpools with DB2, which has the advantage that data
stored in memory from your static data tablespace isnt overwritten by data from your
dynamic data tablespace. Oracle now allows you 1 buffer cache for each different
block size.
DB2 has 2 types of tablespaces:1. System managed storage (SMS) creates a tablespace as a set of directory
containers, in which tables and indexes are created as files. As rows are
inserted into a table, the o/s file is extended a page at a time. SMS has the
advantage is that its easy to administer, but has performance problems when
inserting anything other than small amounts of data
2. Database managed storage (DMS) creates a tablespace as file containers
(similar to Oracle datafiles). As rows are inserted, if they fill an extent, then
another extent is allocated for that table within the tablespace container.
DB2 v9 DMS tablespaces now have the equivalent of Oracles autoextend. Prior to
that, youd have to run daily scripts to check how much free space you had in your
DB2 DMS tablespace and proactively increase the tablespace when it was close to
filling up.
With DB2, storage management is defined at the tablespace rather than table level.
This means that tables should be grouped by storage characteristics and allocated
separate tablespaces. Oracles problem is that allowing tables to have different storage
characteristics within the same tablespace leads to fragmentation problems and in a
10
busy system, Oracle can have problems allocating extents to tables. Oracle also has a
maxextents limit which can cause problems if extent allocation isnt monitored
properly. Since 10g, Oracle now has the ability to allocate storage extents at the
tablespace level. i.e. all tables within the same tablespace will have the same initial,
next and extent percentage increase allocations. This makes it easier for the database
engine to manage.
In terms of logging, in Oracle logfiles and sizes are defined in the create database
statement, whereas DB2 defines these using database parameters logfilsiz, logprimary,
logsecond and newlogpath.
Note: Oracle have defined an Oracle Flexible Architecture (OFA) which defines
exactly how mount points, filesystems. directories and files should be named and
located.
11
transaction. The limitation of this is that the reader is not allowed to use any update
commands. It still doesnt cater for the phantom read problem, however. The only
way to deal with this is to issue a lock table <table> in exclusive mode which will
then prevent other writer applications updating that table, making it identical in
operation to DB2.
The manner in which Oracle rollback segments/undo tablespaces work, is that each
time a writer application updates a row, a pre-updated version of the row is saved in
the rollback segments/undo tablespace together with the time that it was updated.
Problems which Oracle users have with rollback segments/undo tablespace are:1. The higher the write transaction rate there is against a table, the larger the
rollback segment/undo tablespace needs to be. This is because the pre-updated
rows have to be kept in the rollback segment/undo tablespace until the writer
application commits his transaction. If there is insufficient room, extents will
be created within the rollback segment until it fills up. At that point, there is no
more room left, so some pre-updated rows will be overwritten. If the reader
application queries a row which has been updated but the copy of the preupdated row has been overwritten then Oracle will return a snapshot too old
message.
2. The larger the rollback segment, the poorer the performance. Rollback
segments are held on disk and are unindexed. Note: Less of a problem with
undo tablespaces which are recommended post Oracle 9i.
3. If a reader application decides to update some of its read information and
another writer application has already updated that row, Oracle will issue a
record has been updated by another user error message. An Oracle
developers only solution to prevent this happening would be to open a select
for update cursor which allows the reader application to update any of the
rows theyve read but prevents any writer applications from updating the rows.
If we assume that Oracle developers constructing the monthly sales report are
unconcerned with phantom rows, and have a long running transaction which reads
data from a very large accounts table then Oracle is perceived to have an advantage.
There are a number of potential solutions which will reduce lock waiting in DB2,
however:1. In DB2 v8, you can release locks when a cursor is closed rather than when a
transaction is committed. This allows DB2 to operate in a similar fashion to
Oracles default behaviour of statement-level consistency only.
2. In DB2 v8, you can create a materialised query table with a deferred refresh
for many of the tables that you want to generate your monthly accounts
against. To generate your monthly accounts, you could then query the
13
materialised query table directly, whilst the normal users continue to update
the base table. Since materialised query tables allow you to put in where
clauses, you can greatly reduce the number of rows which you need to copy
from the very large table. As youll now be querying a table which writer
applications arent accessing, you can be assured that all 3 potential
corruptions arent possible.
3. In previous versions of DB2, you can simulate oracles rollback segments by
creating an on-update trigger against each table which you will be querying.
The trigger will ensure that the old version of a particular row is copied to a
change table (declared as a global temporary table). The base table should also
have an update timestamp in it. Your program will then open a query cursor
but only locking 1 row at a time. Before it processes each row, it will check to
see whether the row has been updated by checking that the update timestamp
is earlier than when the transaction was started. If its not, the program will
retrieve the old version of the row from the change table and process that
instead. Once the accounts have been generated, the global temporary table
can be dropped. One benefit of methodology 3 over that of Oracles rollback
segment solution, is that the change table can be indexed.
That said, Oracle 10gs undo tablespaces provide a significant advantage for
development/test environments as they allow the new flashback query/table
functionality to be used. Essentially, as undo information is held in an undo tablespace
for a time period controlled by the undo_retention system parameter, its possible to
query the state of a table at any given time during its retention history and also to
revert the table to its state at a particular time. Its not so useful for production
systems with high transaction rates as its unlikely that you could have a large enough
undo tablespace to retain records for a decent period of time.
14
15
9. Database Monitoring
DB2 has event monitoring and snapshot monitoring.
DB2 event monitoring is usually used to capture deadlocks and sql statement
statistics. DB2 event analyser can be used to analyse the sql trace information.
DB2 snapshot monitoring can give point-in-time info about database manager,
database, tablespaces, bufferpools, tables, applications, locks and dynamic sql.
Many of the snapshots hold cumulative information which can be reset by typing
db2 reset monitor all
Up until v8, DB2 snapshot monitoring was only available as commands and produced
a listing style output. From v8 onwards, the statistics are now held in system tables
and can be queried as table functions from SQL, making it very similar to Oracle.
However, Oracle stores much more comprehensive system monitoring information
than DB2. For example, it stores cpu, memory and i/o information as well as a rolling
window of snapshots of sql sessions.
Oracle allows you to trace sql and analyse it using tkprof. You can monitor the
instance, database, tablespaces etc. by examing the v$ system views.
Since Oracle 8i, taking snapshots of information in these tables has been made easier.
The old way of running a bstat (before script) and estat (end script) was replaced by
the statspack in v9i. The statspack is a collection of packages and stored procedures
which allow you to monitor and retrieve snapshot statistics much more easily. Since
10g, the statspack have in turn been replaced by the automatic workload repository
(AWR).
Both Oracle 10g and DB2 9 have substantial autonomic statistics gathering and job
scheduling tools to simplify the life of a DBA.
Toad and Quest are 2 external vendors which specialise in snapshot monitoring of
Oracle, DB2 and SQL*Server.
16
17
6. Creating an instance
DB2: db2icrt $instance
Oracle: The manual method on windows is:a) copy an existing init.ora file and edit.
b) oradim -new -sid <sid> -intpwd <password> -startmode manual [-pfile
<path>/init<sid>.ora] (This creates all the instance-level services)
c) From command line, type set oracle_sid=<sid>
d) sqlplus /nolog
e) connect sys/<password> as sqldba
f) startup nomount
Note: If you get an ORA-03113 error, itll likely be due to memory problems. A
minimum init.ora file is:control_files = (c:\oracle\admin\ora10\control01.ora,
c:\oracle\admin\ora10\control02.ora,
c:\oracle\admin\ora10\control03.ora)
undo_management = auto
db_name
= ora10
db_block_size
= 8192
7. Creating a database
DB2: db2 create db <database name>. This takes under a minute.
Oracle:1. Firstly, you need to configure your oracle net services listener. The easiest way
to do this is by using the netca utility (If youre creating the database for the
first time on Windows and its not on a network, you also have to install a
Microsoft loopback adapter).
2. Then create the database. The easiest way is to use the database configuration
assistant utility - dbca - using an oracle-supplied template.
The manual alternative is comparatively complex. The steps are
a) Run the create database script, an example which is shown below:CREATE DATABASE ORA10
LOGFILE 'c:\oracle\admin\ORA10\logs\redo01.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo02.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo03.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo04.log'
SIZE 10M reuse
CHARACTER SET WE8ISO8859P1
NATIONAL CHARACTER SET UTF8
CONTROLFILE REUSE
DATAFILE 'c:\oracle\admin\ORA10\datafiles\system01.dbf'
SIZE 250M reuse
AUTOEXTEND ON
NEXT 10M MAXSIZE unlimited
EXTENT MANAGEMENT local
SYSAUX DATAFILE 'c:\oracle\admin\ORA10\datafiles\sysaux.dbf'
SIZE 50M reuse
AUTOEXTEND ON
18
NEXT 10M
MAXSIZE unlimited
UNDO TABLESPACE undo
DATAFILE 'c:\oracle\admin\ORA10\datafiles\undo.dbf'
SIZE 10M reuse
DEFAULT TEMPORARY TABLESPACE temp
TEMPFILE 'c:\oracle\admin\ORA10\datafiles\temp01.dbf'
SIZE 20M reuse;
Creating the database takes a similar time as it does to create a DB2 database, but
then you have to run the following 3 scripts to populate the catalog views,
indexes, functions, packages and stored procedures. These scripts take well over
an hour to complete.
b)
c)
d)
e)
@<admin>\catalog
@<admin>\catproc
Log in to sqlplus as system/<password>
@<admin>\pupbld
8. Dropping a database
DB2: db2 drop db <database name>
Oracle: drop database (new in Oracle 10g. Prior to this had to manually delete
files)
9. Turning on archive logging (hot backup)
DB2:
a) Compile the userexit db2uext2 and put in sqllib\bin directory
b) db2 update db cfg for <database> using logretain on
Oracle:
a) Edit the following init<sid>.ora parameters:i)
log_archive_start = true
ii)
log_archive_dest = "/apps/oracle/admin/o817/arch"
iii)
log_archive_format = arch_%t_%s.arc
b) Stop the instance
c) startup mount
d) alter database archivelog
e) alter database open
10. Determining current logfile sequence
DB2: db2 get db cfg for <database> and look at the First active log file
Oracle: archive log list and look at Current log sequence
11. Switching current logfile
DB2: archive log for database <database>
Oracle: alter system switch logfile
12. Backing up a database
DB2: online - db2 update db cfg using logretain on;
19
21
--
22
(CONNECT_DATA =
(SERVICE_NAME = $database)
)
You also need to ensure that you have an entry in listener.ora for the server:# listener.ora Network Configuration File:
C:\Oracle\product\10.2.0\db_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
LISTENER =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = $ip_address)(PORT = $port))
)
Note: Oracle Net Services is undoubtedly one of Oracles weak areas. Configuring
Oracle for remote access is often seen more as an art than a science.
31. How to administer the database
DB2: Use DB2 Control Center (available when you install the Administration
Client).
Oracle: Use Oracle Enterprise Manager (the basic version of this comes with
Oracle 10g but if you want to administer remote servers you need to install the Oracle
Enterpise Manager 10g Grid Control). You really need at least 1Gb of memory to run
Enterprise Manager
To install the basic version, follow these steps:a) emca -repos create (Youll need to know the SID of the instance that you want
to control, the net services listener port and the password for sys) Creating the
repository takes about 15 minutes
b) emca -config -dbcontrol db. This again takes a few minutes to complete. At
the end , it will output a message telling you what the Database control url
is. Type this in to internet Explorer and youll be presented with the login
screen.
c) Once you accept the terms and conditions screen, you get in to Oracle
Enterprise Manager.
To start Oracle Enterprise Manager, after its installed type:a) emctl start dbconsole
It should be noted that Oracle Enterprise Manager is somewhat more extensive in
terms of functionality than the DB2 Control Center is, but DB2 Control Center is
much easier to setup/operate.
32. Creating a user
DB2: Use operating system commands to create a user and then log in to the
database and grant 1 or more of the following privileges to the user:23
grant connect, createtab on database to user $user (will allow the user to connect
and create tables)
grant use of tablespace $tablespace to user $user (will allow the user to create
objects in specified tablespace)
grant insert, update, delete, select on table $table to user $user (will allow the user
to insert, update, delete and select information from the specified table).
grant execute on procedure $procedure to user $user
grant execute on function $function to user $user
Note: DB2 by default grants implicit privileges to select from all tables to the
group public (in which all users are enroled). One of the first things a DB2 DBA
needs to do to make the database secure is to revoke the privileges assigned to group
public.
Oracle: create user $user identified by $password default tablespace
$user_tablespace temporary tablespace $temp_tablespace quota 2M on
$user_tablespace password expire
grant connect, resource to $user
grant all on $table to $user (will allow the user to insert, update, delete and select
information from the specified table)
grant execute on $function/$procedure to $user
33. Creating a group
DB2: Use operating system commands to create a group. DB2 administers groups
at different levels.
At the instance level, there are 4 special groups which are assigned using the update
dbm cfg $name using $value methodology. These groups are:sysadm_group - this is the highest authority. Allows a member of the group to do and
see everything in the database/instance
sysctrl_group - all the rights of a sysadm apart from not being able to alter the
instance level parameters and grant group privileges. Also doesnt allow direct access
to data.
sysmaint_group - all the rights of a sysctrl apart from cant create/drop a database or
tablespace or restore to a new database
sysmon_group - all the rights of a sysmaint apart from cant update database level
parameters, backup/restore a database, perform rollforward recovery or start and stop
an instance.
At the database level, there is a PUBLIC group to which all users belong. There is
also the dbadm privilege which is granted by using grant dbadm on database to user
$user. This privilege allows the user to create an event monitor, load data in to tables,
reorg and runstats the tables and prune log files, quiesce databases. dbadm can also
read all data in the database.
24
Finally, all of the grant privileges which Ive shown above for a user can be granted to
a group apart from those privileges for a stored procedure or function. DB2 allows
you to grant execute on a stored procedure or function to a group, but the users within
that group do not inherit the privilege which makes it redundant.
Oracle: Oracle calls groups - roles. Like DB2 roles get assigned privileges. In Oracle
10g, there are 173 system privileges which can be assigned to a role. You can find
these privileges by typing select name from system_privilege_map. The grouped
privileges / pre-defined roles most often granted to a user are connect (which allows
you to create session, alter session, create synonym, view, database link, table, index,
cluster, sequence) and resource (allows create table, index, cluster, sequence, trigger,
procedure, type). Theres also the dba role which combines the 2 above and allows the
user to grant privileges to other users.
34. Finding a users instance/system level privileges:DB2: Look at the sysadm, sysmaint, sysctrl & sysmon groups in the dbm cfg and
then check to see which users are in those groups at the o/s level.
Oracle:
select
lpad(' ', 2*level) || granted_role "User, his roles and privileges"
from
(
/* THE USERS */
select
null
grantee,
username granted_role
from
dba_users
where
username like upper('%&enter_username%')
/* THE ROLES TO ROLES RELATIONS */
union
select
grantee,
granted_role
from
dba_role_privs
/* THE ROLES TO PRIVILEGE RELATIONS */
union
select
grantee,
privilege
from
25
dba_sys_privs
)
start with grantee is null
connect by grantee = prior granted_role;
26
dba_tab_privs
/* THE ROLES TO ROLES/USERS RELATIONS */
union
select
granted_role p1,
granted_role p2,
grantee,
grantee,
null
from
dba_role_privs
)
start with p1 is null and p2 is null
connect by p1 = prior obj and p2 = prior own;
read a row which has been updated, the reader application will be held in a lock wait
state until the writer application commits. Oracle manifests exactly the same
behaviour as DB2 if the Oracle developer opens a select for update cursor. DB2
reader applications can read the data without locking, if they use the Uncommited
Read isolation level. However, this level means that DB2 can read changed but
uncommitted data, whereas Oracle will read the data before it was changed. Oracles
approach does have a disadvantage in that if the writer application changes data which
the reader application is reading and then commits, the reader application will get a
snapshot too old error message. The other disadvantage of Oracles rollback
segments is it allows the developer to become lazy and commit transactions less often
than is desirable which can lead to performance issues. Various solutions to ensure
that concurrency problems dont occur with DB2 are presented in section 5 above. An
advantage of Oracles undo tablespace solution is that its possible to do flashback
querys to a previous point in time (provided the undo_retention period hasnt been
exceeded).
2. DB2s SQL/PL is compiled whereas Oracles PL/SQL is interpreted.
3. DB2s SQL/PL can only be used in stored procedure, Udf and triggers. It can not
be used as a standalone scripting language. This means, for example, that you cant
output information to the screen or to a file. You can, of course, insert that information
in to a table, however.
4. DB2 stored procedures can be written in C, Cobol and REXX in addition to
SQL/PL and Java. Oracles can only be written in PL/SQL and Java
5. There is no concept of a code package in DB2 SQL/PL. This has the disadvantage
that package variables cant be shared amongst a group of stored procedures. Again,
this can be circumvented by storing the package variables in the calling application.
6. With DB2 a single user can own multiple schemas whereas, in Oracle, a single
user owns a single schema.
7. DB2 v9 has introduced range partitioning but the previous versions didnt have
this. DB2 still doesnt have list partitioning. List partitioning is useful for certain
situations e.g. if you want to partition by countries in Europe or states in America.
DB2 and Oracle have hash partitioning, although in the case of DB2, you cant
partition a table, but have to partition the database, with each partition managed by a
separate DB2 instance. This does have the advantage, however, that more memory
can be used by DB2, as each database instance can address the maximum limit of the
operating system. DB2s partitioned edition (DB2 ESE with data partition facility
DPF) also has the advantage that it can be a shared nothing architecture. i.e. each
database partition can reside on its own disks and use its own cpu and memory.
Oracles Real Application Cluster (RAC) has to share the same data on the same
29
configuration parameters by using the alter system commands and you can make
these changes permanent by adding the scope=both or scope=spfile suffix.
You alter DB2s configuration parameters by running DB2 commands against the
instance-level parameters (db2 update dbm cfg) or database-level parameters (db2
update db cfg for $database.). Some further configuration parameters are held in
whats known as the DB2 registry. You can alter these by using the db2set command.
31