Db2 LUW Administration Basic Commands

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Db2 (DB2 LUW)

Administration
Basic Commands for
Absolute Beginners
Instance
CLP Command Description
db2start Starts the database manager
instance.
db2stop <force> Stops the database manager
instance.
db2ilist List the database Instances
db2level Lists DB2 Software Level
db2licm -l Lists the License status
db2ls List the DB2 Product Installed
db2 get instance Returns the current instance.
export DB2INSTANCE=instance_name Switching the instance
db2 terminate
db2 get dbm cfg Instance level configuration settings
db2 get dbm cfg show detail Instance Level current and delayed
values
db2 update dbm cfg using Updates the instance configuration
<parameter> <value> parameter
db2 list active databases Lists active databases and number
of connections.
db2 list application [show Currently connected applications.
detail]
db2 force application (handle1 Disconnects specific application(s)
[,handle2,..,handlen])
db2 force application all Disconnects all applications from all
the database under the instance.
db2 attach to <node> user Attaches to remote instance
<userid> using <pwd>

Database
db2 create database <dbname> Creates Database
db2 drop database <dbname> Drop a database
db2 activate database <dbname> Explicitly activates the database.
db2 deactivate database Explicitly deactivates the database.
<dbname>
db2 connect to <dbname> Connects to database
[ [user <userid>] using <pwd>]
db2 connect reset Disconnects from current database.
db2 get connection state Identifies which database you are
connected to.
db2 get db cfg for <dbname> Database configuration
db2 get db cfg [show detail] Database configuration current
and delayed
db2 update db cfg for <dbname> Updates database
using <parameter> <value> configuration
db2 list tables Lists tables in the database
[for {user | all | system |
schema <schemaname>}] [show
detail]
db2 describe table <tablename> Displays column information for a
table or view.
db2 list tablespaces [show Displays table space ID, name,
detail] type, contents and state.
db2 list tablespace containers Displays container information
for <tablespace_id> [show
detail]
db2 quiesce tablespaces for Resets the state of a table space to
table <tablename> reset normal.

Backup And Recovery


db2 backup db <dbname> to Take an Offline Full Backup
<location> <COMPRESS>
db2 backup db <dbname> ONLINE Take an Offline Full Backup
to <location> <COMPRESS>
db2 list history backup all List Database history
for db <dbname>
db2 restore db <dbname> TAKEN Restore the database
AT <timestamp> < without
prompting>
db2 list utilities show Show running utilities
detail
Connectivity
db2 catalog [admin] <protocol Catalog a node
TCPIP/ TCPIP4/ TCPIP6> node
<node-name> REMOTE <hostname/
ip-address> SERVER <service-
name/portnumber>
db2 list [admin] node List node directory
directory
db2 catalog database <dbname> Catalog a database
at node <nodename>
db2 list database directory List database directory
[on <path>]
db2 uncatalog node <nodename> Uncatalog node
db2 uncatalog database Uncatalog database
<dbname>

Quiesce Command
db2 quiesce instance Quiesce Instance
<InstanceName> immediate
force connections
db2 quiesce db immediate Quiesce Database

Help
db2 ? SQLCODE Displays the information about the
Error Code
db2 ? COMMAND_NAME Displays the help about the
command
db2licm -h -h option to display help about the
comands
db2 get dbm cfg | findstr Location where db2diag.log file is
DIAGPATH stored which is one-stop file for all
DB2 Errors.

db2pd
db2pd -h db2pd help
db2pd - Status of the Instance
db2pd -alldbs - Status of all the databases
db2pd -db <dbname> -tablespaces Show the tablespaces
Some of the important SYSCAT tables are

1. SYSCAT.TABLES: Contains one row for each table, view, nickname, or


alias that is created. All of catalog tables and views have entries in
SYSCAT.TABLES catalog view.
2. SYSCAT.VIEWS: Contains one or more rows for each view that is created.
SYSCAT.VIEWS view is also particularly useful to determine state of views
in database.
3. SYSCAT.COLUMNS: Contains one row for each column (including
inherited columns, where applicable) that is defined for a table or view.
4. SYSCAT.INDEXES: Contains one row for each index (including inherited
indexes, where applicable) that is defined for a table.
5. SYSCAT.TABLESPACES - Lists all the tablespaces.
6. SYSCAT.DBAUTH - For database-level privileges)
7. SYSCAT.TABAUTH - For privileges on tables and views.

Performance
db2 get monitor switches Returns the state of the session’s
monitor switches.
db2 update monitor switches Sets the state of the session
using <monitor> <on|off> monitor switch for <monitor>.
db2 reset monitor all Resets performance monitor values.
db2 get snapshot for dbm Returns performance information at
the instance level.
db2 get snapshot for all on Returns all performance
<dbname> information at the database level
for database <dbname>.
db2 get snapshot for dynamic Returns the contents of the dynamic
sql on <dbname> SQL cache.
db2 runstats on table Gathers statistics for table
<tbschema>.<tbname> <tbname>. Table name must be
fully qualified with <dbschema>.
db2 reorgchk on table all Determines if tables need to be
reorganized. Useful for
automatically performing runstats
on all tables.
db2 reorg table <tablename> Reorganizes a table by
reconstructing the rows to eliminate
fragmented data and compacting
information.

Administration
db2 export Extracts database data into a flat
file.
db2 import Imports data into the database
using the IMPORT utility.
db2 load Imports data into the database
using the LOAD utility.
db2 load query table <tbname> Returns the progress of the LOAD
[to local-message-file] utility.
[nosummary | summaryonly]
[showdelta]
db2 backup database <dbname> Performs a database backup.
[to <path>]
db2 restore database <dbname> Performs a database restore.
[from <path>]

Security
UPDATE DBM CFG USING SYSTEM
SYSADM_GROUP group_name SYSADM, SYSCTRL, SYSMAINT,
SYSMON
UPDATE DBM CFG USING
SYSCTRL_GROUP group_name

UPDATE DBM CFG USING


SYSMAINT_GROUP group_name

UPDATE DBM CFG USING


SYSMON_GROUP group_name
GRANT [Privilege, …..] DATABASE
ON DATABASE DBADM, SECADM, LOAD,
TO [Recipient, …..] CONNECT, QUIESCE_CONNECT,
BINDADD, IMPLICIT_SCHEMA,
REVOKE [Privilege, …..] CREATETAB,
ON DATABASE CREATE_NOT_FENCED,
FROM [Forfeiter, …..] <BY CREATE_EXTERNAL_ROUTINE
ALL>
GRANT USE TABLESPACE
OF TABLESPACE USE
[TablespaceName]
TO [Recipient, …..] <WITH
GRANT OPTION>

REVOKE USE
OF TABLESPACE
[TablespaceName]
FROM [Forfeiter, …..] <BY
ALL>
GRANT [Privilege, …..] SCHEMA
ON SCHEMA [SchemaName] CREATEIN, ALTERIN, DROPIN
TO [Recipient, …..] <WITH
GRANT OPTION>

REVOKE [Privilege, …..]


ON SCHEMA [SchemaName]
FROM [Forfeiter, …..] <BY
ALL>
GRANT [ALL <Privileges> | TABLE / NICKNAME
Privilege <(ColumnName, CONTROL, ALTER, SELECT,
…..) >, …..] INSERT, UPDATE, DELETE,
ON TABLE [TableName] INDEX, REFERENCES, ALL
TO [Recipient, …..] <WITH PRIVILEGES (Except CONTROL)
GRANT OPTION>

GRANT [ALL <Privileges> |


Privilege <(ColumnName,
…..) >, …..]
ON [NickName]
TO [Recipient, …..] <WITH
GRANT OPTION>
REVOKE [ALL <Privileges> |
Privilege <(ColumnName,
…..) >, …..]
ON TABLE [TableName]
FROM [Forfeiter, …..] <BY
ALL>

REVOKE [ALL <Privileges> |


Privilege <(ColumnName,
…..) >, …..]
ON [NickName]
FROM [Forfeiter, …..] <BY
ALL>

GRANT [ALL <Privileges> | VIEW


Privilege <(ColumnName, CONTROL, SELECT, INSERT,
…..) >, …..] UPDATE, DELETE, ALL
ON [ViewName] PRIVILEGES (Except CONTROL)
TO [Recipient, …..] <WITH
GRANT OPTION>

REVOKE [ALL <Privileges> |


Privilege <(ColumnName,
…..) >, …..]
ON [ViewName]
FROM [Forfeiter, …..] <BY
ALL>
GRANT CONTROL INDEX
ON INDEX [IndexName] CONTROL
TO [Recipient, …..]

REVOKE CONTROL
ON INDEX [IndexName]
FROM [Forfeiter, …..] <BY
ALL>
GRANT EXECUTE ON ROUTINE
[RoutineName EXECUTE (Explicit required)
|FUNCTION <SchemaName.> *
|PROCEDURE <SchemaName.> *
|METHOD * FOR [TypeName]
|METHOD * FOR
<SchemaName.> *]
TO [Recipient, …..] <WITH
GRANT OPTION>

REVOKE EXECUTE ON
[Routine Name
|FUNCTION <SchemaName.> *
|PROCEDURE <SchemaName.> *
|METHOD * FOR [TypeName]
|METHOD * FOR
<SchemaName.> *]
FROM [Forfeiter, …..] <BY
ALL>
RESTRICT
GRANT [Privilege, …..] PACKAGE
ON PACKAGE CONTROL, BIND (Explicit
<SchemaName.>[PackageID] required to Bind), EXECUTE
TO [Recipient, …..] <WITH (Implicit)
GRANT OPTION>

REVOKE [Privilege, …..]


ON PACKAGE
<SchemaName.>[PackageID]
FROM [Forfeiter, …..] <BY
ALL>
UPDATE DBM CFG USING AUTHENTICATION
AUTHENTICATION CLIENT, SERVER,
Authentication_Type SERVER_ENCRYPT, KERBEROS,
KRB_SERVER_ENCRYPT,
DATA_ENCRYPT,
DATA_ENCRYPT_CMP, GSSPLUGIN,
GSS_SERVER_ENCRYPT

Help
db2 ? SQLCODE Displays the information about the
Error Code
db2 ? COMMAND_NAME Displays the help about the
command
db2licm -h -h option to display help about the
comands
db2 get dbm cfg | findstr Location where db2diag.log file is
DIAGPATH stored which is one-stop file for all
DB2 Errors.
db2pd -h Problem Determination Tool.
Multiple Options and mastery over
this tool will allow you to solve many
db2 problems
SYSCAT Schema Data Dictionary schema which
contains multiple views which
details
LIST HISTORY-- List History
+-------------------+----->
+-BACKUP------------+
+-ROLLFORWARD-------+
+-DROPPED TABLE-----+
'-ARCHIVE LOG-------'

+-ALL-----------+-->
+-SINCE--
timestamp-------------------+

FOR--+-DATABASE-+--database-
alias------>

More on SYSCAT Schema


SYSCAT schema is inbuilt schema which contains many views which allows you
to quickly find the information about the objects.

Steps
1. Locate the table from syscat schema using below command

db2 LIST TABLES FOR SCHEMA SYSCAT


2. Describe the table to get the column names for that table

db2 describe table SYSCAT.TABLES

3. Form the SQL query to get the data required e.g. from SYSCAT.TABLES

db2 “SELECT TABSCHEMA, TABNAME from SYSCAT.TABLES”

Some of the important SYSCAT tables are

8. SYSCAT.TABLES: Contains one row for each table, view, nickname, or


alias that is created. All of catalog tables and views have entries in
SYSCAT.TABLES catalog view.
9. SYSCAT.VIEWS: Contains one or more rows for each view that is created.
SYSCAT.VIEWS view is also particularly useful to determine state of views
in database.
10. SYSCAT.COLUMNS: Contains one row for each column (including
inherited columns, where applicable) that is defined for a table or view.
11. SYSCAT.INDEXES: Contains one row for each index (including
inherited indexes, where applicable) that is defined for a table.
12. SYSCAT.TABLESPACES - Lists all the tablespaces.
13. SYSCAT.DBAUTH - For database-level privileges)
14. SYSCAT.TABAUTH - For privileges on tables and views.

More on db2pd
db2pd utility is designed to retrieve information, in a non-intrusive manner, from
appropriate DB2 database system memory sets and produce a thorough report
that can be used to monitor or troubleshoot a database system (or any
component of a database system).

db2pd utility has following characteristics:


1. It can invoked from command line or part of a script. Tool can also be used
interactively when a user wants to issue multiple commands. Input can be
provided from a file or an environment variable.
2. Tool views memory structures being used by DB2 to find information on
tablespaces, containers, sessions, locks, current SQL being run by a
session, entries in package cache, logs, log buffers, bufferpools, bufferpool
buffers, and more.
3. Tool does not acquire any latches or locks that would interfere with activity
on system.
4. Tool does not perform any file I/O to or from any database files as this could
interfere with database activity.
5. Tool can report on a combination of requests (tablespaces, users, and
locks) or on all options.
6. Tool can be run for multiple iterations to capture information for situations
where there is a need to see a snapshot of certain outputs during a certain
time-frame.
7. It allows one database, any number of databases, or all databases to be
reported.
8. It has ability to pick specific agents, applications, or other specific options
for reported information such as locks held by an application or locks
mapped to a transaction identifier.

You can use db2pd command for monitoring and troubleshooting because it can
return quick and immediate information from DB2 memory sets.

Overview
The tool collects information without acquiring any latches or using any engine
resources. It is therefore possible (and expected) to retrieve information that is
changing while db2pd is collecting information; hence data might not be
completely accurate. If changing memory pointers are encountered, a signal
handler is used to prevent db2pd from ending abnormally. This can result in
messages such as "Changing data structure forced command termination" to
appear in output. Nonetheless, tool can be helpful for troubleshooting. Two
benefits to collecting information without latching include faster retrieval and no
competition for engine resources.

Simplest form of this command is:

db2pd
<-inst>
<-database [DatabaseName] ,... | -alldatabases>
<-everything>
<-full>

db2pd -inst instance -db database options


where DatabaseName is name assigned to one or more databases that
information is to be obtained for.

Example:
Diagnosing a lockwait

db2pd -db databasename -locks -transactions -applications -


dynamic

Example:
Using -wlocks parameter to capture all locks being waited on.

db2pd -wlocks -db pdtest

Example:
Using -apinfo parameter to capture detailed runtime information about lock
owner and lock waiter

db2pd -apinfo 47 -db pdtest

Use
db2 list applications to get appid

Example:
Using callout scripts when considering a locking problem
To use callout scripts, find db2cos output files. Location of files is controlled by
database manager configuration parameter diagpath. Contents of output files
will differ depending on what commands you enter in db2cos script file.

Run db2cos script file containing


db2pd -db sample -locks

Example of output provided is as follows:


In output, W* indicates lock that experienced timeout. In this case, a lockwait has
occurred. A lock timeout can also occur when a lock is being converted to a
higher mode. This is indicated by C* in output. You can map results to a
transaction, an application, an agent, or even an SQL statement with output
provided by other db2pd commands in db2cos file. You can narrow down output
or use other commands to collect information that you need. For example, you
can use db2pd -locks wait parameters to print only locks with a wait status. You
can also use -app and -agent parameters.

Example:
Mapping an application to a dynamic SQL statement
Use -applications -dynamic to report current and last anchor ID and statement
unique ID for dynamic SQL statements. This allows direct mapping from an
application to a dynamic SQL statement.

db2pd -applications -dynamic -db sample

Example:
Monitoring memory usage
Option -memblock can be useful when you are trying to understand memory
usage.

db2pd -memblock

You can also report memory blocks for private memory on UNIX and Linux
operating systems.

db2pd -memb pid=159770

Example:
Monitoring recovery
To verify that recovery is progressing and show several counters. Current Log
and Current LSO values provide log position.

db2pd -recovery

CompletedWork value is number of bytes completed thus far.

Example:
Determining amount of resources a transaction is using
To show number of locks, first log sequence number (LSN), last LSN, first LSO,
last LSO, log space used, and space reserved. This can be useful for
understanding behavior of a transaction.
db2pd -transactions

Example:
Monitoring log usage for a Database
By using Pages Written value, you can determine whether log usage is
increasing:

db2pd -logs

You can identify two types of problems by using this output:


• If most recent log archive fails, Archive Status is set to a value of Failure. If
there is an ongoing archive failure, preventing logs from being archived at
all, Archive Status is set to a value of First Failure.
• If log archiving is proceeding very slowly, Next Log to Archive value is lower
than Current Log Number value. If archiving is very slow, space for active
logs might run out, which in turn might prevent any data changes from
occurring in database.

Note: S0000003.LOG and S0000004.LOG do not contain any log records yet
and therefore StartLSN is 0x0

Example: Displaying top EDUs by processor time consumption and displaying


EDU stack information

If you issue db2pd command with -edus parameter option, output lists all engine
dispatchable units (EDUs). Output for EDUs can be returned at level of
granularity you specify, such as at instance level or at member. On Linux and
UNIX operating systems only, you can also specify interval parameter suboption
so that two snapshots of all EDUs are taken, separated by an interval you
specify. When interval parameter is specified, two additional columns in output
indicate delta of processor user time (USR DELTA column) and delta of
processor system time (SYS DELTA column) across interval.

In following example, deltas for processor user time and processor system time
are given across a five-second interval:

$ db2pd -edus interval=5


To provide information only about EDUs that are top consumers of processor
time and to reduce amount of output returned, you can further include top
parameter option. In following example, only top five EDUs are returned, across
an interval of 5 seconds. Stack information is also returned, and can be found
stored separately in directory path specified by DUMPDIR, which defaults to
diagpath.

$ db2pd -edus interval=5 top=5 stacks

Example: Displaying agent event metrics


The db2pd command supports returning event metrics for agents. If you need to
determine whether an agent changed state during a specific period of time, use
event option together with -agents parameter.

AGENT_STATE_LAST_UPDATE_TIME(Tick Value) column that is returned


shows last time that event being processed by agent was changed. Together
with a previously obtained value for AGENT_STATE_LAST_UPDATE_TIME(Tick
Value), you can determine whether an agent has moved on to a new task or
whether it continues to process same task over an extended period of time.

db2pd -agents event

Example:
Monitoring progress of index reorganization
In DB2 9.8FP3 and later fix packs, progress report of an index reorganization has
following characteristics:
• db2pd -reorgs index command reports index reorg progress for partitioned
indexes (FP1 introduced support for only non-partitioned indexes).
• db2pd -reorgs index command supports monitoring of index reorg at
partition level (that is, during reorganization of a single partition).

• Reorg progress for non-partitioned and partitioned indexes is reported in


separate outputs. One output shows reorg progress for non-partitioned
indexes, and following outputs show reorg progress for partitioned indexes
on each table partition; index reorg statistics of only one partition is reported
in each output.
• Non-partitioned indexes are processed first, followed by partitioned indexes
in serial fashion.
• db2pd -reorgs index command displays following additional information
fields in output for partitioned indexes:
– MaxPartition - Total number of partitions for table being processed.
For partition-level reorg, MaxPartition will always have a value of 1
since only a single partition is being reorganized.
– PartitionID - Data partition identifier for partition being processed.

Following example shows an output obtained using db2pd -reorgs index


command which reports index reorg progress for a range-partitioned table with 2
partitions.

db2pd -reorgs index

Results
Following is an example of output obtained using db2pd command with the-
reorgs index parameter, which reports index reorganization progress for a
range-partitioned table with two partitions.

Note: First output reports Index Reorg Stats of non-partitioned indexes.


Following outputs report Index Reorg Stats of partitioned indexes on each
partition; index reorganization statistics of only one partition is reported in each
output.

Note: First output reports Index Reorg Stats of non-partitioned indexes.


Following outputs report Index Reorg Stats of partitioned indexes on each
partition.

Example:
Monitoring progress of RUNSTATS operations
You can use LIST UTILITIES command or db2pd command to monitor progress
of RUNSTATS operations on a database.

Procedure
Issue LIST UTILITIES command and specify SHOW DETAIL parameter:

list utilities show detail

or issue db2pd command and specify -runstats parameter:


db2pd -runstats

Example:
Monitoring a rollforward operation
You can use db2pd or LIST UTILITIES command to monitor progress of
rollforward operations on a database.

Procedure
Issue LIST UTILITIES command and specify SHOW DETAIL parameter

LIST UTILITIES SHOW DETAIL

Issue db2pd command and specify -recovery parameter:

db2pd -recovery

Results
For rollforward recovery, there are two phases of progress monitoring:
FORWARD and BACKWARD. During FORWARD phase, log files are read and
log records are applied to database. For rollforward recovery, when this phase
begins UNKNOWN is specified for total work estimate. Amount of work
processed in bytes is updated as process continues.

During BACKWARD phase, any uncommitted changes applied during


FORWARD phase are rolled back. An estimate for amount of log data to be
processed, in bytes, is provided. Amount of work processed, in bytes, is updated
as process continues.

More on LIST HISTORY


Lists entries in history file. History file contains a record of recovery and
administrative events.

Following events can be used in LIST HISTORY command: BACKUP,


ROLLFORWARD, DROPPED TABLE, LOAD, CREATE TABLESPACE, ALTER
TABLESPACE, RENAME TABLESPACE, REORG, ARCHIVE LOG.

Example: List all backup operations performed on SAMPLE database.


list history backup all for sample

Example: List all rollforward operations performed on SAMPLE database since


2004-01-01-00:00:00.

list history rollforward since 20040101000000 for sample

Example: List all create tablespace operations on tablesspace TS1 in SAMPLE


database.

list history create tablespace containing ts1 for sample

Example: List all load operations on table sylviaq.sales in SAMPLE database.

list history load containing sylviaq.sales for sample

You might also like