Monday, 30 June 2014

How to know when an "alter table" statement was last executed

How to know when an "alter table" statement was last executed

from syscat.tables using the column ALTER_TIME on DB2 9.5, or using column INVALIDATE_TIME in other DB2 versions

Perform the select below to find out when a table was last modified:

On DB2 9.5:


db2 "select substr(tabname,1,20) as TABLE, alter_time from syscat.tables where tabname='<table_name>'"


Other Versions:


db2 "select substr(tabname,1,20) as TABLE, invalidate_time from syscat.tables where tabname='<table_name>'"

Sunday, 29 June 2014

How to know what tables are in REORG PENDING

How to know what tables are in REORG PENDING

from SYSIBMADM.ADMINTABINFO where REORG_PENDING = 'Y'



perform the command below to find out what tables are in REORG PENDING


db2 " select TABSCHEMA, TABNAME from SYSIBMADM.ADMINTABINFO where REORG_PENDING = 'Y'"

if do you want to generate a script to reorg all tables in reorg peding, execute the statement below:


db2 -x "select 'reorg table', substr(rtrim(TABSCHEMA)||'.'||rtrim(TABNAME),1,20), ';' \
from SYSIBMADM.ADMINTABINFO where REORG_PENDING = 'Y'" 

Saturday, 28 June 2014

How to Calculate the size of one Table or one Schema

How to Calculate the size of one Table or one Schema

calculating the size of one table and one schema

Perform the select below to know the size all tables in a specific schema:

db2 "select substr(a.tabname,1,30), (a.fpages*PAGESIZE/1024) as size_k, a.card from syscat.tables a, \
syscat.tablespaces b where a.TBSPACEID=b.TBSPACEID and a.tabschema='<schema_name>"

DB29.1 or later:
db2 "SELECT tabname,TABSCHEMA, SUM(DATA_OBJECT_P_SIZE)+
SUM(INDEX_OBJECT_P_SIZE)+ SUM(LONG_OBJECT_P_SIZE)+
SUM(LOB_OBJECT_P_SIZE)+ SUM(XML_OBJECT_P_SIZE) FROM
SYSIBMADM.ADMINTABINFO where TABSCHEMA=<tabschema_name> group by tabname,tabschema" 

Perform the select below to know the size one table:

db2 "select substr(a.tabname,1,30), (a.fpages*PAGESIZE/1024) as size_k,
a.card from syscat.tables a, syscat.tablespaces b where
a.TBSPACEID=b.TBSPACEID and a.tabname='<tab_name>'  and tabschema='<schema_name>' "

DB29.1 or later:
 db2 "SELECT TABSCHEMA, TABNAME, SUM(DATA_OBJECT_P_SIZE)+
SUM(INDEX_OBJECT_P_SIZE)+ SUM(LONG_OBJECT_P_SIZE)+
SUM(LOB_OBJECT_P_SIZE)+ SUM(XML_OBJECT_P_SIZE) FROM
SYSIBMADM.ADMINTABINFO where tabschema='<tabschema_name>' and tabname='<table_name>' group by tabschema,tabname" 

Perform the select below to know the size of all schema:

db2 "select sum(a.fpages*PAGESIZE/1024) as size_k_of_schemaName  from syscat.tables a, \ 
syscat.tablespaces b where a.TBSPACEID=b.TBSPACEID and a.tabschema='<schema_name>' group by a.tabschema"

 DB29.1 or later:
 db2 "SELECT TABSCHEMA, SUM(DATA_OBJECT_P_SIZE)+
SUM(INDEX_OBJECT_P_SIZE)+ SUM(LONG_OBJECT_P_SIZE)+
SUM(LOB_OBJECT_P_SIZE)+ SUM(XML_OBJECT_P_SIZE) FROM
SYSIBMADM.ADMINTABINFO GROUP BY TABSCHEMA" 



Do you know the diference between FPAGES AND NPAGES ???

NPAGES - Total number of pages on which the rows of the table exist
FPAGES - Total number of pages


So, FPAGES >= NPAGES, when you run the utilities reorg and runstats, the reorg will try to do FPAGES=NPAGES and the runstats will update the statistics on catalog.

How to know the table, schema and database size

How to know the table, schema and database size

The table size is the sum of pagesize*(number of table pages) plus pagesize*(number of index pages)



Table Size

 db2 "with rs as (select distinct(substr(t.tabname,1,35)) as table, t.card as card, \
t.type as type , t.fpages as fpages, case when ind.nleaf is null then 0 else \
ind.nleaf end as nleaf, ts.pagesize as pagesize,  t.tabname tab2, t.tabschema as schema \
from syscat.tables t inner join syscat.tablespaces ts on t.tbspaceid=ts.tbspaceid \
left join syscat.indexes ind on t.tabname=ind.tabname) select table,\
(sum(nleaf)+fpages)*pagesize as size,card from rs where schema='<schema_name>' and \
type='T' and table='<table_name>' group by card,table,pagesize,fpages"

Tables Size for one specific schema

db2 "with rs as (select distinct(substr(t.tabname,1,35)) as table, t.card as card, t.type as type , \
t.fpages as fpages, case when ind.nleaf is null then 0 else ind.nleaf end as nleaf, \
ts.pagesize as pagesize,  t.tabname tab2, t.tabschema as schema from \
syscat.tables t inner join syscat.tablespaces ts on t.tbspaceid=ts.tbspaceid left \
join syscat.indexes ind on t.tabname=ind.tabname) select table,(sum(nleaf)+fpages)*pagesize as size,\
card from rs where schema='<schema_name>' and type='T' group by card,table,pagesize,fpages"

Schema Size

db2 "select ((select sum(fpages*pagesize) from syscat.tablespaces as a, syscat.tables as b where \
a.TBSPACEID=b.TBSPACEID and tabschema='<schema_name>' group by tabschema)+(select sum(nleaf*pagesize) \
from syscat.tablespaces as a, syscat.indexes as b where a.TBSPACEID=b.TBSPACEID and \
tabschema='<schema_name>' group by tabschema))/1024 as SCHEMA_SIZE_KB from sysibm.sysdummy1"

Database Size

db2 "select sum(TBSP_USED_SIZE_KB) as DATABASE_SIZE from sysibmadm.TBSP_UTILIZATION"

Friday, 27 June 2014

How to install fixpack on DB2 V9.5

How to install fixpack on DB2 V9.5


At first ,you have to download the last fixpack for DB2 v9.5 on:

http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg24021563

Now, you are already to install your fixpack in DB2 V9.5, below you will see all steps necessary to install the fixpack with the installFixPack command:

A - Stop all applications connected on your databases, stop the instance, stop the DAS and stop fault monitors


db2 force applications all
db2stop
cd DB2DIR//das/bin$ ./db2admin stop
db2_kill
ps -ef | grep -i <instance_name>
#If there is any DB2 process
kill <PID of DB2 process>

B - Apply the fixpack with installFixPack command:



./installFixPack -b DB2DIR -f db2lib -f update

Example:
 ./installFixPack -f db2lib -f update -b /opt/ibm/db2/V9.5/

WHERE:


-b
base-install-path:    Specifies the path where the DB2 product will be installed. Mandatory when -n is specified. The length of the path is limited to 128 characters and is a full path name.

    The –b option is not required for a non-root installation of DB2, but it is still mandatory for a root installation. If –b is used in a non-root install, the value of base-install-path must be the user’s HOME/sqllib directory, or else the path is considered invalid. If –b is not provided in a non-root install, the DB2 installer will use the user’s HOME/sqllib as the install path and continue. But, if –b is used and the provided install path has a DB2 copy installed by a root user, the path is considered invalid since the DB2 copy can only be updated by the user who installed it.

-f

    Force option. -f with no argument is not supported. The force arguments below can be combined. For example, -f level -f db2lib.
-f level
    Force a down level or same level fix pack install. If the fix pack image is at a higher level than the installed DB2 product, this option is ignored.
-f db2lib
    Force installFixPack to bypass the checking on DB2 library loading. To ensure that the instances or applications work properly after the installation, the DBM must be stopped for all the related instances (including all nodes for the related DPF instances), and all DB2 libraries related to the installation path must be unloaded.
-f install
    Force installFixPack to bypass all the checking on DB2 library loading, instance and DAS properly stopped or not. To ensure that the instances or applications work properly after the installation, the DBM must be stopped for all the related instances (including all nodes for the related DPF instances), and all DB2 libraries related to the installation path must be unloaded. If this option is specified, instance/DAS will not be updated. User needs to do the instance/DAS update manually after the installation. Also, note that the options update and install are mutually exclusive and cannot be specified in the same installation.
-f update
    Force installFixPack to bypass all the checking on DB2 library loading, instance and DAS properly stopped or not. To ensure that the instances or applications work properly after the installation, the DBM must be stopped for all the related instances (including all nodes for the related DPF instances), and all DB2 libraries related to the installation path must be unloaded. If this option is specified, instance/DAS will be updated. Also, note that the options update and install are mutually exclusive and cannot be specified in the same installation.


References: http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp

Thursday, 26 June 2014

How to install fixpack on DB2

How to install fixpack on DB2

steps to install fixpack on DB2
Follow the steps below to upgrade your DB2 Databases installing the next fixpack:

1 - Download the appropriate fixpack


Use the link below to donwload your fixpack

http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg27007053


2 - Stop all DB2 Process


Do the steps below to all instances
db2 force applications all
db2 terminate
db2stop
db2licd -end      # run at each physical partition

. $HOME/das/dasprofile
db2admin stop


3 - Disable the fault monitor processes:


   Log on as root.
   Locate where the db2fmcu command runs from by issuing the command:

ps -ef

For example, on AIX the db2fmcu command is run from DB2DIR/bin directory, where DB2DIR is the location where the DB2 copy is installed.

Switch to the directory indicated by the ps command.

  • Disable the Fault Monitor Coordinator (FMC) by issuing the command:

db2fmcu -d

     Note:
         1. Since there is only one Fault Monitor Coordinator, this step affects all DB2 copies on the system.
         2. After you apply the fix pack, the Fault Monitor Coordinator is reset so that the system's inittab file is again configured to include the FMC. If you do not want to use the FMC, you must reissue the above command after you have applied the fix pack.
  •    To stop the Fault Monitor Daemon, issue the command:

      db2fm -i iname -D

4 - Clean up all DB2 interprocess


Ensure all DB2 interprocess communications are cleaned for the instance to be updated. As the instance owner, run the following command at each physical partition:

$HOME/sqllib/bin/ipclean

5 - Install the fix pack:


  •    Log on as root.
  •    Change to the directory that contains the fix pack image.
  •    Launch the installation by issuing the installFixPack command. For example,

 ./installFixPack -b DB2DIR
where DB2DIR is the location of the DB2 products that you want to update.


6 - Updating the instance


  1. For each instance, issue the command:
    DB2DIR/instance/db2iupdt iname
    where iname represents the instance name and DB2DIR represents the location where the DB2 copy is installed.
  2. If the DB2 Administration Server (DAS) belongs to the DB2 copy where you installed the fix pack, issue the command:
    DB2DIR/instance/dasupdt
    where DB2DIR is the location where the DB2 copy is installed. If this DB2 copy is now running at a more recent fix pack level than all of the other DB2 copies, consider updating the DAS to belong to this DB2 copy.

7 - Bind the bind file


  • Start the instance

db2start

  • Binding
db2 terminate
db2 CONNECT TO dbname
db2 BIND path\db2schema.bnd BLOCKING ALL GRANT PUBLIC SQLERROR CONTINUE
db2 BIND path\@db2ubind.lst BLOCKING ALL GRANT PUBLIC ACTION ADD
db2 BIND path\@db2cli.lst BLOCKING ALL GRANT PUBLIC ACTION ADD
db2 terminate

8 - Check the db2diag.log



If you don see any errors, you can start to use your database upgraded!!!

Wednesday, 25 June 2014

How to insert, delete, update data without generate logs on DB2

How to insert, delete, update data without generate logs on DB2

using alter table <table_name> activate not logged initially


ON CLP:


db2 +c alter table <table_name> activate not logged initially

db2 +c delete from <table_name> where <column_name>='<value>' 

OR

db2 +c insert into table <table_name> (select * from table_name)

OR

db2 +c update table_name set <column_name>='value' where <column_name>='value'

db2 commit

ON TOAD EDITOR OR ON THE OTHER EDITOR:

db2 alter table <table_name> activate not logged initially

db2 delete from <table_name> where <column_name>='<pattern>' 

OR

db2 insert into table <table_name> (select * from table_name)

OR

db2 update table_name set <column_name>='value' where <column_name>='value'

db2 commit

DMS Tablespace is Full

DMS Tablespace is Full

Tablespace has reached it's limit size. Unable to allocate new pages in table space.

A - Errors

A.1 - Error command line


SQL0289N  Unable to allocate new pages in table space "<tablespace name>"

A.2 - Messages on db2diag.log

2008-03-13-17.24.13.390000-180 I890568H416        LEVEL: Error
PID     : 2760                 TID  : 4408        PROC : db2syscs.exe
INSTANCE: DB2                  NODE : 000         DB   : SAMPLE
APPHDL  : 0-853                APPID: *LOCAL.DB2.080313201909
FUNCTION: DB2 UDB, Common Trace API, sqlbfix, probe:2
RETCODE :ZRC=0x85020021=-2063466463=SQLB_END_OF_CONTAINER
          "DMS Container space full"

B - Possible Causes

B.1 - Containers are full

Cause  One All the containers assigned to this DMS table space are full.
This is the likely cause of the error.

B.2 - Redirect Restore to containers that are too small

Cause Two A redirected restore is being done to containers that are too
small.

B.3 - DMS tablespace enabled for auto resize is in a full FS and it can't grow

Cause Three A DMS table space enabled for auto-resize has not reached its
maximum size but one of the file systems on which the containers
exists is full and the container cannot grow.

C - Investigating


To check if you ran out of space in the containers you should issue the command. Then check the Useable pages, Used pages and Free pages properties to identify if your tablespace is full.
db2 "list tablespace containers show detail"
To check if your ran out of space on your file system you could issue the command on unix, then look for occupation indicators:
df -k

D - Resoluting


D.1 - Containers are full


Cause One Add new container(s) to the DMS table space and try the
operation again, after the rebalancer has made the new pages
available for use. Syntax:

ALTER TABLESPACE <TS_NAME>     
ADD (FILE '<path>' <number_of_pages>)

D.2 - Redirect Restore to containers that are too small


Cause Two Perform the redirected restore again to larger containers.

D.3 - DMS tablespace enabled for auto resize is in a full FS and it can't grow


Cause Three Add a new stripe set of containers to the table space.
Existing containers will no longer grow, only those new
containers in the last range of the table space are extended when
an automatic resize occurs. Syntax:
ALTER TABLESPACE <TS_NAME>     
ADD (FILE '<path>' <number_of_pages>)

Tuesday, 24 June 2014

How to check tablespace utilization in DB2 V9

How to check tablespace utilization in DB2 V9

This query can be used to check the space utilization for each table space,
including the current size, percentage free space, and size of free space.
For SMS table spaces, the buffer pool switch must be on to get results returned.

The SYSIBMADM.TBSP_UTILIZATION administrative view returns table space
configuration and utilization information. The view is an SQL interface for
the LIST TABLESPACES CLP command. Its information is based on the SNAPTBSP,
SNAPTBSP_PART administrative views and TABLESPACES catalog view.

db2 "select substr(tbsp_name,1,30) as Tablespace_Name, tbsp_type as Type, \
substr(tbsp_state,1,20) as Status, (tbsp_total_size_kb / 1024 ) as Size_Meg, \
smallint((float(tbsp_free_size_kb)/ float(tbsp_total_size_kb))*100)as Percent_Free_Space, \
int((tbsp_free_size_kb) / 1024 )as Meg_Free_Space from sysibmadm.tbsp_utilization"

The following is an example of the output for this query:

TABLESPACE_NAME                TYPE       STATUS               SIZE_MEG     PERCENT_FREE_SPACE MEG_FREE_SPACE
------------------------------ ---------- -------------------- -------------------- -    -----------------------------   ---------------------
SYSCATSPACE                      DMS             NORMAL                     240                                       0                           0
TEMPSPACE1                       DMS             NORMAL                      100                                     99                         99
USERSPACE1                       DMS             NORMAL                   10240                                    32                     3363
SYSTOOLSPACE                   SMS              NORMAL                          0                                      0                           0
SYSTOOLSTMPSPACE           SMS             NORMAL                           0                                      0                           0


The query below lists tablespaces all DMS and their percentage used:
db2 "select substr(tbsp_name,1,30) as Tablespace_Name, tbsp_type as Type, \
substr(tbsp_state,1,20) as Status, (tbsp_total_size_kb / 1024 ) as Size_Meg, \
decimal((float(tbsp_total_size_kb - tbsp_free_size_kb)/ float(tbsp_total_size_kb))*100,3,1)as Percent_used_Space, \
int((tbsp_free_size_kb) / 1024 )as Meg_Free_Space from sysibmadm.tbsp_utilization where tbsp_type='DMS'"

Output

TABLESPACE_NAME                TYPE       STATUS                        SIZE_MEG             PERCENT_USED_SPACE MEG_FREE_SPACE
------------------------------------------ ---------- -------------------- ----------- -------------------- ---------------------------------- ----------------------------------
SYSCATSPACE                           DMS        NORMAL                                 64                          61.1                                                   24
USERSPACE1                             DMS        NORMAL                                 32                          53.1                                                   15
TBS32K                                         DMS        NORMAL                              69996                      77.8                                            15507
IDX_TBS                                       DMS        NORMAL                              33619                       99.0                                                315
SYSTOOLSPACE                        DMS        NORMAL                                 32                          0.2                                                     31

Monday, 23 June 2014

How to list the tablespaces and their % usage

How to list the tablespaces and their % usage

How to list the tablespaces and their % usage
To check the tablespaces and their percentage usage you can run the following select command, and connect to the database first.
db2 connect to <db_name>


Then run the the select bellow and alter dbname with your database name.  The SNAPSHOT_TBS_CFG function returns configuration information from a table space snapshot, so the snapshot monitoring should be enabled for you can run this select. Tablespace_Type is 1 for SMS and 0 for DMS tablespaces. For SMS tablespaces the percentage usage will be always 100%, so this select makes sense only for DMS tablespaces.

db2 select "TABLESPACE_ID as id, SUBSTR(TABLESPACE_NAME, 1, 20) as name, \
INT(PAGE_SIZE) as PAGE_SIZE, INT(TOTAL_PAGES) as TOTAL_PAGES, \
INT(USED_PAGES) as USED_PAGES, \
INT(DECIMAL(TOTAL_PAGES,10,2)-DECIMAL(USED_PAGES,10,2)) as FREE_PAGES,\
'      ' CONCAT (SUBSTR(CHAR(DECIMAL(USED_PAGES, 10, 2)/ \
DECIMAL(TOTAL_PAGES,10,2)*100),9,5)) CONCAT '%' as PERCENT_USED, \
INT(NUM_CONTAINERS) as N_CONTAINERS \
from table (snapshot_tbs_cfg('<db_name>', 0)) as t \
where TABLESPACE_TYPE=0 order by PERCENT_USED desc"
Output example:
NAME       PAGE_SIZE  TOTAL_PAGES USED_PAGES FREE_PAGES PERCENT_USED N_CONTAINERS
---------- ----------- ---------- ---------- ---------- ------------ ------------
TS_INDEXES        4096     111542      80160      31382       71.86%            3
TS_EVT_REP       16384      19000       7104      11896       37.38%            2
TS_SLOTS         16384      64800      21920      42880       33.82%            3
TS_REC_LOG       16384      12800       2816       9984       22.00%            4
TS_LONG          32768       1280        110       1170       08.59%            3
TS_REST           4096       4500        288       4212       06.40%            3



Specifying a tablespace



db2 select "SUBSTR(TABLESPACE_NAME, 1, 20) as name, \
INT(PAGE_SIZE) as PAGE_SIZE, INT(TOTAL_PAGES) as TOTAL_PAGES, \
INT(USED_PAGES) as USED_PAGES, \
INT(DECIMAL(TOTAL_PAGES,10,2)-DECIMAL(USED_PAGES,10,2)) as FREE_PAGES,\
'      ' CONCAT (SUBSTR(CHAR(DECIMAL(USED_PAGES, 10, 2)/ \
DECIMAL(TOTAL_PAGES,10,2)*100),9,5)) CONCAT '%' as PERCENT_USED, \
INT(NUM_CONTAINERS) as N_CONTAINERS \
from table (snapshot_tbs_cfg('<db_name>', 0)) as t \
where TABLESPACE_TYPE=0 and TABLESPACE_NAME='TS_INDEXES'" 

Where TS_INDEXES is the tablespace name.



Output Example:

NAME       PAGE_SIZE  TOTAL_PAGES USED_PAGES FREE_PAGES PERCENT_USED N_CONTAINERS
---------- ----------- ---------- ---------- ---------- ------------ ------------
TS_INDEXES        4096     111542      80160      31382       71.86%            3

  1 record(s) selected.

Sunday, 22 June 2014

How to improve performance on statements with clause IN

How to improve performance on statements with clause IN

DB2_INLIST_TO_NLJN
If you set the variable below to yes, you can improve your performance on statements with clause IN.

DB2_INLIST_TO_NLJN
  • Operating system: All
  • Default=NO, Values: YES or NO
  • In some situations, the SQL and XQuery compiler can rewrite an IN list predicate to a join. For example, the following query:
        SELECT *
         FROM EMPLOYEE
         WHERE DEPTNO IN ('D11', 'D21', 'E21')
    could be written as:
        SELECT *
         FROM EMPLOYEE, (VALUES 'D11', 'D21', 'E21) AS V(DNO)
         WHERE DEPTNO = V.DNO
    This revision might provide better performance if there is an index on DEPTNO. The list of values would be accessed first and joined to EMPLOYEE with a nested loop join using the index to apply the join predicate.
    Sometimes the optimizer does not have accurate information to determine the best join method for the rewritten version of the query. This can occur if the IN list contains parameter markers or host variables which prevent the optimizer from using catalog statistics to determine the selectivity. This registry variable causes the optimizer to favor nested loop joins to join the list of values, using the table that contributes the IN list as the inner table in the join.

Saturday, 21 June 2014

How to Increase a DMS Tablespace

How to Increase a DMS Tablespace

This topic shows you how to increase a Database-Managed tablespace

Occurrence

When the tablespace size is equal or bigger than the defined safety size (usually about 80-90% used)

Steps to Follow

1 - Detect what tablespace has size issues

Once logged at the instance, to check what tablespace are almost full, type the following command:
db2 list tablespaces show detail
It will shows you a list with all tablespaces and you can identify the specific tablespace with issues.
Example:

db2 list tablespaces show detail

Tablespaces for Current Database

 Tablespace ID                        = 0
 Name                                 = SYSCATSPACE
 Type                                 = Database managed space
 Contents                             = All permanent data. Regular table space.
 State                                = 0x0000
   Detailed explanation:
     Normal
 Total pages                          = 8192
 Useable pages                        = 8188
 Used pages                           = 7736
 Free pages                           = 452
 High water mark (pages)              = 7736
 Page size (bytes)                    = 8192
 Extent size (pages)                  = 4
 Prefetch size (pages)                = 4
 Number of containers                 = 1

 Tablespace ID                        = 1
 Name                                 = TEMPSPACE1
 Type                                 = System managed space
 Contents                             = System Temporary data
 State                                = 0x0000
   Detailed explanation:
     Normal
 Total pages                          = 1
 Useable pages                        = 1
 Used pages                           = 1
 Free pages                           = Not applicable
 High water mark (pages)              = Not applicable
 Page size (bytes)                    = 8192
 Extent size (pages)                  = 32
 Prefetch size (pages)                = 32
 Number of containers                 = 1

 Tablespace ID                        = 2
 Name                                 = USERSPACE1
 Type                                 = Database managed space
 Contents                             = All permanent data. Large table space.
 State                                = 0x0000
   Detailed explanation:
     Normal
 Total pages                          = 4096
 Useable pages                        = 4064
 Used pages                           = 1760
 Free pages                           = 2304
 High water mark (pages)              = 1824
 Page size (bytes)                    = 8192
 Extent size (pages)                  = 32
 Prefetch size (pages)                = 32
 Number of containers                 = 1

 Tablespace ID                        = 3
 Name                                 = IBMDB2SAMPLEREL
 Type                                 = Database managed space
 Contents                             = All permanent data. Large table space.
 State                                = 0x0000
   Detailed explanation:
     Normal
 Total pages                          = 4096
 Useable pages                        = 4064
 Used pages                           = 608
 Free pages                           = 3456
 High water mark (pages)              = 608
 Page size (bytes)                    = 8192
 Extent size (pages)                  = 32
 Prefetch size (pages)                = 32
 Number of containers                 = 1

2 - Check the percentage of use from the tablespace

After detecting the tablespace, you can check the percentage used of it.  Type the following command
db2 list tablespace containers for <tablespace_id>  show detail
Now you can identify the total number of containers, where the tablespace is stored, the total number of pages and the total number of used pages.

Example:
db2 list tablespace containers for 3 show detail

            Tablespace Containers for Tablespace 3

 Container ID                         = 0
 Name                                 = C:\DB2\NODE0000\SAMPLE\T0000003\C0000000.LRG
 Type                                 = File
 Total pages                          = 4096
 Useable pages                        = 4064
 Accessible                           = Yes

3 - Calculating the size of free space needed

Now you are able to calculate the percentage of use from the tablespace. To get this number, do (Used Pages / Useable Pages) * 100 and then with this percentage you can continue calculating how many pages you need to increase to obtain the acceptable amount of free pages.


4 - Verifying the filesystem and the free space

Continuing, now you should check the total amount of free space at the fileystem. Do this typing
df -k <tablespace.path>
And you'll be able to verify if it's enough space to extend the tablespace. Remember you can check the page size in the output of "db2 list tablespaces show detail" command.


5 - Extending the tablespace

Finally, after all checked, you can execute the command to extend the pages of that tablespace. Do this using:
db2 "alter tablespace <tablespace_name> extend (all <page_numbers>)"
This will extend the size of your tablespace. Be careful when using EXTEND ALL clause when the tablespace has more than one container; in cases where the tablespace has more than one container, divide the total number of pages you intent to increase by the number of total containers.
Example:
db2 alter "tablespace IBMDB2SAMPLEREL extend (all 1000)"
Alternatively, if it's not possible to extend the actual containers, a possibility is to add new containers to the tablespace. For that, you should enter the following command:
db2 "alter tablespace <tablespace_name> add (FILE '<new_container_file>' <size>)"
Where size can be in pages (only using the numbers you want), in KBytes (using a K following the number), in MBytes (using a M following the number) or in GBytes (using a G following the number). Also, please note to use single quotes around the name of the file you'll use as a new container.

Friday, 20 June 2014

How to ignore case sensitive search on DB2

How to ignore case sensitive search on DB2

using the upper or lower functions

Example:

db2 "select FIRSTNME from db2inst1.employee "

FIRSTNME   
------------  
Michael    
Sally          
Eva         
Delores    

db2 "select FIRSTNME from db2inst1.employee where upper(FIRSTNME) like 'EVA' "

FIRSTNME   
------------
EVA        

Thursday, 19 June 2014

How to identify unused indexes on DB2

How to identify unused indexes on DB2

usinf db2pd -tcbstats
The db2pd utility is generally used for problem determination and monitoring purposes, but you can also use it to query information about database activity. One piece of information that you can obtain with the db2pd utility is the number of times indexes have been accessed since the database was activated. Listing 7 shows how to use the db2pd utility to get this information for all indexes on all tables in a database.

Listing 7. Query table and index metrics with the db2pd utility
db2pd -db sample -tcbstats all -file db2pd_tab_all.txt

The options on the above call to the db2pd utility have the following meanings:
  • -db Database name
  • -tcbstats all Show all table and index metrics
  • -file Output file
If you want to restrict the output of the db2pd utility to show metrics for only a certain table and its indexes, use the -tcbstats option to specify the tablespace ID and table ID. To do this, you first need to determine the tablespace ID and table ID of the table by executing a SELECT statement on the SYSCAT.TABLES catalog view, as shown in Listing 8.

Listing 8. Query database catalog to determine tablespace ID and table ID of a table
db2 "SELECT TBSPACEID, TABLEID
     FROM SYSCAT.TABLES
     WHERE TABSCHEMA = 'FECHNER' AND TABNAME = 'DEPARTMENT'"

Listing 9 shows a sample result set from a tablespace ID and table ID query such as the one above.

Listing 9. Result set of tablespace ID and table ID query
TBSPACEID TABLEID
--------- -------
        2       5

  1 record(s) selected.

After determining the tablespace ID and table ID of the table you want to query, you can restrict the db2pd output to just that table. You do this by including the tbspaceid and tableid suboptions following the -tcbstats option, as shown in Listing 10.

Listing 10. Restrict db2pd -tcbstats output to a specific table
db2pd -db sample -tcbstats all tbspaceid=2 tableid=5 -file db2pd_tab_dept.txt

Listing 11 shows a sample result set from a db2pd query such as the one above.

Listing 11. Table and index metrics as shown by the db2pd utility to DB2 9.7
Database Partition 0 -- Database SAMPLE -- Active -- Up 0 days 00:20:34

TCB Table Information:
Address    TbspaceID TableID PartID MasterTbs MasterTab TableName          SchemaNm
ObjClass DataSize   LfSize     LobSize    XMLSize   
0x797DF2B8 2         5       n/a    2         5         DEPARTMENT         FECHNER
Perm     1          0          0          0         

TCB Table Stats:
Address    TableName          SchemaNm Scans      UDI        RTSUDI               PgReorgs
NoChgUpdts Reads      FscrUpdates Inserts    Updates    Deletes    OvFlReads  OvFlCrtes
RowsComp   RowsUncomp CCLogReads StoreBytes BytesSaved
0x797DF2B8 DEPARTMENT         FECHNER  0          0          0                    0
0          951        0           0          0          0          0          0
0          0          0          -          -         

TCB Index Information:
Address    InxTbspace ObjectID PartID TbspaceID TableID MasterTbs MasterTab
TableName          SchemaNm IID   IndexObjSize
0x797E0330 2          5        n/a    2         5       2         5
DEPARTMENT         FECHNER  3     8         
0x797E0330 2          5        n/a    2         5       2         5
DEPARTMENT         FECHNER  2     8         
0x797E0330 2          5        n/a    2         5       2         5
DEPARTMENT         FECHNER  1     8         

TCB Index Stats:
Address    TableName          IID   PartID EmpPgDel   RootSplits BndrySplts PseuEmptPg
EmPgMkdUsd Scans      IxOnlyScns KeyUpdates InclUpdats NonBndSpts PgAllocs   Merges
PseuDels   DelClean   IntNodSpl  
0x797E0330 DEPARTMENT         3     n/a    0          0          0          0
0          0          0          0          0          0          1          0
0          0          0          
0x797E0330 DEPARTMENT         2     n/a    0          0          0          0
0          678        0          0          0          0          1          0
0          0          0          
0x797E0330 DEPARTMENT         1     n/a    0          0          0          0
0          245        0          0          0          0          1          0
0          0          0          

The part of the result set that concerns index usage is in the TCB Index Stats section. The sample output above shows that the DEPARTMENT table has three indexes. The indexes are shown by their index IDs (the IID column), not by their names. The Scans column shows how many times the indexes were accessed since the database was activated:
  • The index with ID 1 was accessed 245 times.
  • The index with ID 2 678 times.
  • The index with ID 3 was never accessed.
Because the index with ID 3 has not been accessed, you can conclude that it is not used, or at least that it is seldom used. To get the name of the index with ID 3, query the SYSCAT.INDEXES catalog view using a SELECT statement, as shown in Listing 12.

Listing 12. Query database catalog to determine an index name based on its index ID (IID)
db2 "SELECT INDSCHEMA, INDNAME
     FROM SYSCAT.INDEXES
     WHERE TABSCHEMA = 'FECHNER' AND TABNAME = 'DEPARTMENT' AND IID = 3"

The output of the above SELECT statement is shown in Listing 13.

Listing 13. Result set of index name query
INDSCHEMA                      INDNAME
------------------------------ ------------------------------
FECHNER                        XDEPT3

  1 record(s) selected.

Listing 14. Result set of index details
db2 describe indexes for table FECHNER.DEPARTMENT show detail


In addition to the Scans column, the TCB Index Stats section of the db2pd utility results has a IxOnlyScns column that shows the number of index only scans. An Index only scan is an index access that is not followed by a table access because the index itself contains all the requested data. So if the IxOnlyScns counter is not zero, you have to add the numbers of both the Scans column and the IxOnlyScns column to get the total number of times the index has been accessed.
You have to be careful when interpreting index usage information. The same is true when using the db2pd approach. The fact that a certain index has not been used up until a certain point in time, does not necessarily mean that the index will never be used. So be cautious when deciding whether or not to drop an index that appears not to be used. If you do decide to drop an index, you should first save its CREATE INDEX statement so that you can easily recreate it if necessary.
Listing 15. Table and index metrics as shown by the db2pd utility to DB2 9.1 and 9.5
Database Partition 0 -- Database SAMPLE -- Active -- Up 0 days 00:20:34

Database Partition -1 -- Database MNTTBPP -- Active -- Up 8 days 22:53:29

TCB Table Information:
Address            TbspaceID TableID PartID MasterTbs MasterTab TableName          SchemaNm ObjClass DataSize   LfSize     LobSize    XMLSize   
0x0000000134C8E6F8 2         17      n/a    2         17        TMPVALORITEMCOLETA MNT      Perm     4300       0          0          0         

TCB Table Stats:
Address            TableName          Scans      UDI        PgReorgs   NoChgUpdts Reads      FscrUpdates Inserts    Updates    Deletes    OvFlReads  OvFlCrtes 
0x0000000134C8E6F8 TMPVALORITEMCOLETA 389        7666       0          0          4361401580 0           5086480    0          0          0          0         

TCB Index Information:
Address            InxTbspace ObjectID TbspaceID TableID MasterTbs MasterTab TableName          SchemaNm IID   IndexObjSize
0x0000000134F2F1C0 2          17       2         17      2         17        TMPVALORITEMCOLETA MNT      3     2092      
0x0000000134F2F1C0 2          17       2         17      2         17        TMPVALORITEMCOLETA MNT      2     2092      
0x0000000134F2F1C0 2          17       2         17      2         17        TMPVALORITEMCOLETA MNT      1     2092      

TCB Index Stats:
Address            TableName          IID   EmpPgDel   RootSplits BndrySplts PseuEmptPg Scans      KeyUpdates InclUpdats NonBndSpts PgAllocs   Merges     PseuDels   DelClean   IntNodSpl  
0x0000000134F2F1C0 TMPVALORITEMCOLETA 3     0          0          20         0          501        0          0          68         0          0          0          0          1          
0x0000000134F2F1C0 TMPVALORITEMCOLETA 2     0          1          0          0          1071       0          0          176        136        0          0          0          0          
0x0000000134F2F1C0 TMPVALORITEMCOLETA 1     0          2          268        0          0          0          0          0          207        0          0  

SOURCE: https://www.ibm.com/developerworks/data/library/techarticle/dm-0910db2unusedindex/

Wednesday, 18 June 2014

What is the difference between Type 1 indexes and Type 2 indexes ?

What is the difference between Type 1 indexes and Type 2 indexes ?

Type 1 indexes and Type 2 indexes on DB2

Version 8 introduced Type 2 indexes as a new standard index type, replacing the V7 Type 1 indexes.


Both indexes currently coexist, however, Type 1 indexes will be de-supported in the future. The type 2 index is replacement for the old Type 1 index, which has suffered from:

  • concurrency issues during inserts and next key locks
  •  performance issues due to physically removing a key from a leaf page during update or delete

Some benefits of Type 2 indexes:

  • no more physical action after delete or update action until final commit
  • next-key locking is reduced to a minimum, dramatically improving concurrency
  • online index reorganization supported
  • can be created on columns whose length is greater than 255 bytes

Tuesday, 17 June 2014

How to get the last generated value of an identity column

How to get the last generated value of an identity column

IDENTITY_VAL_LOCAL()

How to use the function IDENTITY_VAL_LOCAL()


Example:

Creating a table
db2 "CREATE TABLE TABLE_X( COD INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, NAME CHAR(30))"

Inserting data
db2 "insert into table_x (name) values ('Rose')"
db2 'insert into table_x (name) values ('Mary')"
db2 "insert into table_x (name) values ('Alyson')"

getting of last generated value of COD
db2 "select IDENTITY_VAL_LOCAL() as last_cod from sysibm.sysdummy1"
OUTPUT

LAST_COD                               
---------------------------------
                               3.

  1 record(s) selected.

The result of the function is not affected by the following:


  •      A single row INSERT statement with a VALUES clause for a table without an identity column
  •      A multiple row INSERT statement with a VALUES clause
  •      An INSERT statement with a fullselect
     A ROLLBACK TO SAVEPOINT statement

Monday, 16 June 2014

How to get snapshot information

How to get snapshot information

A useful table containing all snapshot information about databases and instances.
Monitor level CLP command Information returned
Connections list list applications [show detail] Application identification information for all applications currently connected to a database that is managed by the DB2(R) instance on the partition where snapshot is taken.
Connections list list applications for database dbname[show detail] Application identification information for each application currently connected to the specified database.
Connections list list dcs applications Application identification information for all DCS applications currently connected to a database that is managed by the DB2 instance on the partition where snapshot is taken.
Database manager
get snapshot for dbm
Database manager level information, including instance-level monitor switch settings.
Database manager get dbm monitor switches Instance-level monitor switch settings.
Database get snapshot for database on dbname Database level information and counters for a database. Information is returned only if there is at least one application connected to the database.
Database get snapshot for all databases Database level information and counters for each database active on the partition. Information is returned only if there is at least one application connected to the database.
Database list active databases The number of connections to each active database. Includes databases that were started using the ACTIVATE DATABASE command, but have no connections.
Database get snapshot for dcs database on dbname Database level information and counters for a specific DCS database. Information is returned only if there is at least one application connected to the database.
Database get snapshot for remote database on dbname Database level information and counters for a specific federated system database. Information is returned only if there is at least one application connected to the database.
Database get snapshot for all remote databases Database level information and counters for each active federated system database on the partition. Information is returned only if there is at least one application connected to the database.
Application get snapshot for application applid appl-id Application level information, including cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for application agentid appl-handle Application level information, includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for applications on dbname Application level information for each application that is connected to the database on the partition. This includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for all applications Application level information for each application that is active on the partition. This includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for dcs application applid appl-id Application level information, including cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for all dcs applications Application level information for each DCS application that is active on the partition. This includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for dcs application agentid appl-handle Application level information, including cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application get snapshot for dcs applications on dbname Application level information for each DCS application that is connected to the database on the partition. This includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application
get snapshot for remote applications on dbname
Application level information, includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Application
get snapshot for all remote applications
Application level information for each federated system application that is active on the partition. This includes cumulative counters, status information, and most recent SQL statement executed (if statement switch is set).
Table get snapshot for tables on dbname Table activity information at the database and application level for each application connected to the database. Table activity information at the table level for each table that was accessed by an application connected to the database. Requires the table switch.
Lock get snapshot for locks for application applid appl-id List of locks held by the application. Lock wait information requires the lock switch.
Lock get snapshot for locks for application agentid appl-handle List of locks held by the application. Lock wait information requires the lock switch.
Lock get snapshot for locks on dbname Lock information at the database level, and application level for each application connected to the database. Requires the lock switch.
Table space get snapshot for tablespaces on dbname Information about table space activity for a database. Requires the buffer pool switch. Also included is information on containers, quiescers, and ranges. This information is not under switch control.
Buffer pool get snapshot for all bufferpools Buffer pool activity counters. Requires the buffer pool switch.
Buffer pool get snapshot for bufferpools on dbname Buffer pool activity counters for the specified database. Requires the buffer pool switch.
Dynamic SQL get snapshot for dynamic sql on dbname Point-in-time statement information from the SQL statement cache for the database. The information can also be from a remote data source.

Sunday, 15 June 2014

How to get and change the current schema

How to get and change the current schema

Command to get and change the current schema you are logged in
Sometimes, if you want to know which schema you are using, you can issue the command:
$db2 values current schema

The output is the following:

$ db2 values current schema

1                                                                               
-------------------------------------------
DB2INST2                                                                        

  1 record(s) selected.

To change the current schema issue the following command:

db2 set schema <SchemaName>

Saturday, 14 June 2014

How to get all identity values generated by insert on DB2

How to get all identity values generated by insert on DB2

final table clause

Use the clause final table in your insert statement, see the example below:
create table table_identity (cod1 int not null generated always as identity, cod2 int, cod3 int);

select * from final table (insert into table_identity (cod2,cod3) values (20,20),(30,30));

COD1        COD2        COD3
----------- ----------- -----------
          1          20          20
          2          30          30

  1 record(s) selected.

Friday, 13 June 2014

How to flush bufferpools on DB2

How to flush bufferpools on DB2

db2pdcfg -db sample -flushbp
Starting DB2 9.5 fp2 is possible to flush bufferppols, see the command below:


db2pdcfg -db sample -flushbp



Earlier versions, you need to deactivate and activate the database to flush BPs.

Thursday, 12 June 2014

How to find out foreign key on DB2 tables

How to find out foreign key on DB2 tables

syscat.references - db2look

SYSCAT.REFERENCES

select substr(tabname,1,20) table_name,substr(constname,1,20) 
fk_name,substr(REFTABNAME,1,12) parent_table,substr(refkeyname,1,20) 
pk_orig_table,fk_colnames from syscat.references where tabname = 
'TABLE_NAME'


  DB2LOOK

db2look -d <database_name> -e -t  <table_name>
Look for 'DDL Statements for foreign keys on Table table_name in the output.

How to export and load using compression & named pipes

How to export and load using compression & named pipes

How to export and load using compression & named pipes
---- EXPORT ----

mkfifo /tmp/mypipe

gzip -c < /tmp/mypipe > employee.del.gz &

db2 "export to /tmp/mypipe of del select * from db2inst1.employee"

rm /tmp/mypipe

---- LOAD ----

mkfifo /tmp/mypipe

cat employee.del.gz | gzip -dc > /tmp/mypipe &

db2 "load from /tmp/mypipe of del replace into db2inst1.employee nonrecoverable"

rm /tmp/mypipe

Wednesday, 11 June 2014

How to execute a DB2 script with begin atomic

How to execute a DB2 script with begin atomic

Example1:

begin atomic
declare x char;
set x=(select nome from db2inst1.x0 where nome='a');
insert into db2inst1.x0  (nome) values (x);
end@

Example2:
begin atomic
insert into db2inst1.x0 (nome) values ('cd');
insert into db2inst1.x1  (cod) values (select identity_val_local() from sysibm.sysdummy1);
end@

To execute theses scripts via command line:
db2 -td@ -vf <scriptname>

Tuesday, 10 June 2014

How to enable asynchronous I/O (AIO) support on Linux for DB2 9.1

How to enable asynchronous I/O (AIO) support on Linux for DB2 9.1

setting DB2LINUXAIO variable to true
 
The DB2LINUXAIO enables asynchronous I/O (AIO) support on Linux operating systems. AIO allows DB2 processes to use system resources more effectively. For example, a DB2 process can perform other work while waiting for an I/O request to be completed. The libaio.so.1 shared library is required to use this feature.

Default: FALSE, Values: FALSE or TRUE

db2set DB2LINUXAIO=true

 Note: Setting DB2LINUXAIO to YES is recommended in Version 9.1. However, note that this registry variable is deprecated and will be removed in a future release as AIO will be enabled by default.

Source: Performance variables

Monday, 9 June 2014

How to drop the column propriety 'not null' and column propriety default

How to drop the column propriety 'not null' and column propriety default

set column null and unset or drop column propriety default

Dropping default

 db2 "alter table <schema_name>.<tab_name> alter column <column_name> drop default"


Dropping not null

 db2 "alter table <schema_name>.<tab_name> alter column <column_name> drop not null"

Sunday, 8 June 2014

How to drop all tables and Views from a specific schema

How to drop all tables and Views from a specific schema

dropping all tables and views from a specific SCHEMA, SYSPROC.ADMIN_DROP_SCHEMA




Dropping all tables, views and the own schema:



CALL SYSPROC.ADMIN_DROP_SCHEMA('SCHNAME', NULL, 'ERRORSCHEMA', 'ERRORTABLE')
Replace  'SCHNAME' to schema name, example for DEPT schema :
CALL SYSPROC.ADMIN_DROP_SCHEMA('DEPT', NULL, 'ERRORSCHEMA', 'ERRORTABLE');


Dropping all tables



db2 -x "select 'drop table ' || rtrim(tabschema) || '.' || rtrim(tabname) || ' '  
       || ';'from syscat.tables where type = 'T' and tabschema='<schema_name>'"

Dropping all Views


db2 -x "select 'drop table ' || rtrim(tabschema) || '.' || rtrim(tabname) || ' '  
       || ';'from syscat.tables where type = 'V' and
       tabschema='<schema_name>'"

Dropping all Views and all Tables


db2 -x "select 'drop table ' || rtrim(tabschema) || '.' || 
          rtrim(tabname) || ' '  || ';'from syscat.tables where tabschema='<schema_name>'"

Saturday, 7 June 2014

How to drop a constraint on DB2

How to drop a constraint on DB2

WARNING: take care of constraint created with quotes

Schema Name: group1
Table Name: EMPLOYEE
Constraint Name = KEY1

db2 alter table group1.employee drop constraint group1.key1

If the constraint was created between quotes, so you need to have attention when you will manipulate this constraint, example, when you will drop this constraint:

See the example below:


db2 set schema group1
db2 'alter table group1.employee drop constraint "key1"'

Friday, 6 June 2014

How to do a DB2 instance recycle on AIX

How to do a DB2 instance recycle on AIX

These are the steps you should execute when you need to do a DB2 instance recycle running on AIX
1 - Ask the application people to stop the application before you start with DB2 recycle
2 - Login with the instance owner id to run the commands:

db2 list applications show detail

3 - If there are applications left, double check with the application people if they stopped everything. If you still see applications left, you can do

db2 force applications all
db2 terminate
db2 deactivate db <db_name>
db2stop

4 - If the instance doesn’t come down because some application are still left, use

db2stop force

5 - If db2stop force cant bring the instance down run

db2_kill
ipclean –a

This will cleanup memory.

6 - Check if there are processes left using

ps –ef | grep <instance_name>

7 - Check if there are any ipc resources left for your instance using

ipcs –a | grep <instance_name>

If yes, try to kill them as root (use sudo):

sudo ipcrm –m resource_id (for m resources)
sudo ipcrm –s resource_id (for s resources)
sudo ipcrm –q resource_id (for q resources)

8 - Now that everything is clean, you should be able to start your instance

db2start

Thursday, 5 June 2014

How to determine the owner of a lock

How to determine the owner of a lock

Determine which transaction is holding the lock. Display information about the current locks by running the db2pd command with the -locks attribute.
Look for the row that has a "W", meaning waiting, in the Sts (status) column. The Owner column indicates which transaction is holding the lock. In the following example TranHdl 3 is waiting on a lock held be TranHdl 2 (indicated by 1 below).

db2pd -d <database> -locks showlocks
db2pd -alldbs - locks showlocks
Database Partition 0 -- Database SAMPLE -- Active -- Up 00:00:40
Locks:
TranHdl ...       Sts        Owner ...
2 ...                G           2 ...
3 ...                G           3 ...
2 ...                G           2 ...
3 ...            W        2   1  ...
2 ...                G           2 ...
2 ...                G           2 ...
2 ...                G           2 ...
      2 ...                G           2 ...
Identify the application that is running the transaction that is holding the lock by running db2pd -transactions. In the example below we see that TranHdl 2(indicated by ) is being run by AppHandl 12(indicated by 2 ).
db2pd -d <database> -tansactions transaction= < TranHdl > 
Database Partition 0 -- Database SAMPLE -- Active -- Up 00:05:06
Transactions:
... AppHandl     ... TranHdl      Locks ...
... 12   2       ... 2   1      38 ...
      .... 13               ... 3               5 ...
Identify the Agent ID that is running the application by running db2pd -agents.
db2pd -agents application=< AppHandl> 
Database Partition 0 -- Database SAMPLE -- Active -- Up 00:06:15

Agents:
Current agents: 2
Idle agents: 0
Active agents: 2
Coordinator agents: 2

... AppHandl       ... AgentPid       ... ClientPid        Userid             ClientNm ...
... 13                 ... 749570          ... 434354           jmcmahon       db2bp ...

      ... 12   2        ... 811172      ... 917706       jmcmahon    db2bp ...

How to discover the maximum numbers of connection has been reached

How to discover the maximum numbers of connection has been reached

Steps you should perform to find the maximum numbers of active connections that a database support and if this number has been reached
db2 connect to <db_name>
To find out the maximum numbers of active connections that a database support type:
db2 get db cfg | grep -i MAXAPPLS
the output will be something like that:
 Catalog cache size (4KB)              (CATALOGCACHE_SZ) = (MAXAPPLS*4)
 Max number of active applications            (MAXAPPLS) = 250
If you want to check the instance level configuration for the maximum number of connections:
db2 get dbm cfg | grep -i max
the output will be something like that:

 Max number of existing agents               (MAXAGENTS) = 400
 Max number of coordinating agents     (MAX_COORDAGENTS) = (MAXAGENTS - NUM_INITAGENTS)
 Max no. of concurrent coordinating agents  (MAXCAGENTS) = MAX_COORDAGENTS
 Max number of client connections      (MAX_CONNECTIONS) = MAX_COORDAGENTS
 Number of pooled fenced processes         (FENCED_POOL) = MAX_COORDAGENTS

To discover the high water mark for database connections , type the command below:
db2 get snapshot for dbm | grep -i high
the output will be something like that:
Private Sort heap high water mark              = 38238
High water mark for agents registered          = 129
High water mark for agents waiting for a token = 0
High water mark for coordinating agents        = 126
       High water mark (bytes)                 = 1114112
       High water mark (bytes)                 = 2342912
In this example you can notice the database supports 250 active applications and the High water mark was 129 of  the active connections.

Wednesday, 4 June 2014

How to determine fenced User-ID of a DB2 instance

How to determine fenced User-ID of a DB2 instance

Determine fenced User-ID of a DB2 instance

When you create a DB2 instance in Unix, you have the option of specifying a fenced user-id different than instance owner. The purpose of fenced user id is to protect DB2 from untested or malicious code from the external stored procedures, user defined functions etc. When you try to run these external procedures, they run in a separate address space owned by the fenced user id.
You know about the fenced user id if you created a DB2 instance yourself on your Unix platform. But suppose, you are looking at a DB2 instance created by someone and you are wondering as which is the fenced user id, you can look at the user and group id of the file .fenced in ~/sqllib/adm directory and this will tell you as which is the fenced user id.
$ ls -l ~/sqllib/adm/.fenced
-r--r--r-- 1 vikram vikram 0 Feb 13 19:02 /home/vikram/sqllib/adm/.fenced
In the above example, the instance id is also the fenced user id.
The other way to determine the fenced user id is to run the db2pd program and look for fenced token.
The following command will work both on Windows and Unix.
C:\>db2pd -fmp | grep -i fenced
Trusted Path:    C:\PROGRA~1\IBM\SQLLIB\\function\unfenced
Fenced User:     DB2

$ db2pd -fmp | grep -i fenced
Trusted Path:    /home/vikram/sqllib/function/unfenced
Fenced User:     vikram
The concept of fenced user-id is really for the Unix platforms and for Windows, the fenced user id is same as that of db2 instance owner. The output of db2pd -fmp for Windows shows the name of the instance as fenced user id.

Source: http://www.db2ude.com/?q=node/30

How to delete rows in block on DB2

How to delete rows in block on DB2

use the option fetch first <number_of_rows> rows only to delete in block

Table: employee
Size of Block: 1000

db2 delete from employee where col1 in (select col1 from employee fetch first 1000 rows only )
with the statement  above you can apply in loop to insert in many blocks

How to determine whether you should attempt to reclaim free storage

How to determine whether you should attempt to reclaim free storage

About this task

This task will provide you with information that you can use to determine the extent to which you have unused space below the high water mark for your table space. Based on this, you can make a determination as to whether reclaiming free storage would be beneficial.
Restrictions
Although you can determine various usage attributes about all your table spaces, only table spaces created with DB2® Version 9.7 or later have the reclaimable storage capability. If you want to be able to reclaim storage in table spaces created with earlier versions of the DB2 product, you either must unload then reload the data into a table space created with DB2 Version 9.7, or move the data with an online move.

Procedure

To determine how much free space exists below the high water mark:
  1. Formulate a SELECT statement that incorporates the MON_GET_TABLESPACE table function to report on the state of your table spaces. For example, the following statement will display the total pages, free pages, used pages, for all table spaces, across all database partitions:
    SELECT varchar(tbsp_name, 30) as tbsp_name, 
      reclaimable_space_enabled,
      tbsp_free_pages,
      tbsp_page_top,
      tbsp_usable_pages
    FROM TABLE(MON_GET_TABLESPACE('',-2)) AS t 
    ORDER BY tbsp_free_pages ASC
  2. Run the statement. You will see output that resembles this:
    TBSP_NAME                      RECLAIMABLE_SPACE_ENABLED TBSP_FREE_PAGES      TBSP_PAGE_TOP        TBSP_USABLE_PAGES
    ------------------------------ ------------------------- -------------------- -------------------- --------------------
    TEMPSPACE1                                             0                    0                    0                    1
    SYSTOOLSTMPSPACE                                       0                    0                    0                    1
    TBSP1                                                  1                    0                 1632                 1632
    SMSDEMO                                                0                    0                    0                    1
    SYSCATSPACE                                            1                 2012                10272                12284
    USERSPACE1                                             1                 2496                 1696                 4064
    IBMDB2SAMPLEREL                                        1                 3328                  736                 4064
    TS1                                                    1                 3584                  480                 4064
    TS2                                                    1                 3968                   96                 4064
    TBSP2                                                  1                 3968                   96                 4064
    TBSAUTO                                                1                 3968                   96                 4064
    SYSTOOLSPACE                                           1                 3976                  116                 4092
    
      12 record(s) selected.
  3. Use the following formula to determine the number of free pages below the high water mark:
    freeSpaceBelowHWM = tbsp_free_pages - (tbsp_usable_pages - tbsp_page_top)

Results

Using the information from the report in step 2, the free space below the high water mark for USERSPACE1 would be 2496 - (4064 - 1696) = 128 pages. This represents just slightly over 5% of the total free pages available in the table space.

What to do next

In this case, it might not be worth trying to reclaim this space. However, if you did want to reclaim those 128 pages, you could run an ALTER TABLESPACE USERSPACE1 REDUCE MAX statement. If you were to do so, and then run the MON_GET_TABLESPACE table function again, you would see the following:

TBSP_NAME                      RECLAIMABLE_SPACE_ENABLED TBSP_FREE_PAGES      TBSP_PAGE_TOP        TBSP_USABLE_PAGES
------------------------------ ------------------------- -------------------- -------------------- --------------------
TEMPSPACE1                                             0                    0                    0                    1
USERSPACE1                                             1                    0                 1568                 1568
SYSTOOLSTMPSPACE                                       0                    0                    0                    1
TBSP1                                                  1                    0                 1632                 1632
SMSDEMO                                                0                    0                    0                    1
SYSCATSPACE                                            1                 2012                10272                12284
IBMDB2SAMPLEREL                                        1                 3328                  736                 4064
TS1                                                    1                 3584                  480                 4064
TS2                                                    1                 3968                   96                 4064
TBSP2                                                  1                 3968                   96                 4064
TBSAUTO                                                1                 3968                   96                 4064
SYSTOOLSPACE                                           1                 3976                  116                 4092

  12 record(s) selected.



Source: http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.admin.dbobj.doc/doc/t0055407.html