84
DB2 INTERVIEW QUESTIONS Q:-What are the New Features that are added in DB2/LUW v9.7? Answer: - ADDED FEATURES (1) SQL Compatibility Feature (Oracle Compatibility) This new version of DB2/LUW not only allows you to use objects in DB2 that look like Oracle objects such as tables with “VARCHAR2” data types and commands like “DECODE” or “NVL” but it can also behave like Oracle. (2) Compression of Indexes, Temp Tables and LOBs : In addition to compressing table data you can also now compress indexes, temporary tables, Large Objects (LOBs) and all XML documents. (3) Convert Existing Databases to Automatic Storage : With v9.7 you can now convert your database and DMS Tablespaces to Automatic Storage. This can be done with either the ALTER TABLESPACE or a redirected restore. (4) Reclaim Unused Space from Automatic Storage Tablespaces : You can now reclaim unused space in automatic storage tablespace. (5) New and Updated Administrative Views: Storage Monitoring: SNAPSTORAGE_PATHS, SNAP_GET_STORAGE_PATHS_V97, SNAPTBSP_PART, SNAP_GET_TBSP_PART_V97 DEPRECATED FEATURES (1) Control Center: This is the first step in replacing Control Center with Data Studio. Q:-What are the New Features that are added in DB2/LUW v10.1? Answer: - (1) Time Travel Query (TTQ) The Time Travel Query (TTQ) allows you to tell DB2 to track changes to tables and then issue queries as if they were being submitted at some time in the past, providing results as they would have appeared at that past time. This 1

Db2 Important questions to read

Embed Size (px)

Citation preview

Page 1: Db2 Important questions to read

DB2 INTERVIEW QUESTIONS

Q:-What are the New Features that are added in DB2/LUW v9.7?

Answer: - ADDED FEATURES

(1) SQL Compatibility Feature (Oracle Compatibility) This new version of DB2/LUW not only allows you to use objects in DB2 that look like Oracle objects such as tables with “VARCHAR2” data types and commands like “DECODE” or “NVL” but it can also behave like Oracle. 

(2) Compression of Indexes, Temp Tables and LOBs : In addition to compressing table data you can also now compress indexes, temporary tables, Large Objects (LOBs) and all XML documents.

(3) Convert Existing Databases to Automatic Storage :   With v9.7 you can now convert your database and DMS Tablespaces to Automatic Storage.  This can be done with either the ALTER TABLESPACE or a redirected restore.

(4) Reclaim Unused Space from Automatic Storage Tablespaces :   You can now reclaim unused space in automatic storage tablespace. 

(5) New and Updated Administrative Views: Storage Monitoring:  SNAPSTORAGE_PATHS, SNAP_GET_STORAGE_PATHS_V97, SNAPTBSP_PART, SNAP_GET_TBSP_PART_V97

DEPRECATED FEATURES

(1) Control Center:   This is the first step in replacing Control Center with Data Studio. 

Q:-What are the New Features that are added in DB2/LUW v10.1?

Answer: -

(1) Time Travel Query (TTQ)

The Time Travel Query (TTQ) allows you to tell DB2 to track changes to tables and then issue queries as if they were being submitted at some time in the past, providing results as they would have appeared at that past time.  This feature is available for all tables upgraded from earlier versions by merely altering the tables that you want to have the TTQ capability.  Of course you can also create tables with this feature with the CREATE TABLE statement. 

(2) Adaptive Compression ( Storage Optimization Feature) DB2 already allows you to compress tables, indexes, backups, in line LOBs and other objects, and in v10.1 the compression capability has been enhanced even more with a new compression feature called adaptive compression.  The current compression is quite efficient both from a storage saving standpoint and a server resource standpoint and in some cases can improve performance of a system.  In DB2 v9.x, there was a single compression dictionary for the entire table.  With the new

1

Page 2: Db2 Important questions to read

adaptive compression a dictionary is also created on individual pages that can benefit from being compressed, allowing additional compression that would not be done using the table level dictionary either because duplication is only seen on a page or new patterns emerge that were not observed at the time the table dictionary was created.  It should be noted that for efficiency’s sake, that page compression is only performed as a page becomes full and if significant space savings can be achieved.  As you have probably read, Moore’s Law continues to be in effect with processor speeds doubling about every 18 months.  However, the speed at which data can be transferred from disk into RAM continues to significantly lag with the gap growing wider all the time.  It is my humble opinion that DB2 compression is a great way to use some of the increased processing power of your server to increase I/O speed by getting more rows with every physical read. 

(3) Multi-Temperature Storage (MTS)

This feature allows you to easily segregate your data onto different classes of storage with your most important data being on your fastest storage and your less important data on cheaper storage. You should note that tablespace need to be automatic storage tablespace to participate in an MTS configuration, but existing tablespaces can be easily converted using the

ALTER TABLESPACE … MANAGED BY AUTOMATIC STORAGE Command.  You can also see which paths are assigned to which storage groups using the ADMIN_GET_STORAGE_PATHS table function.  Finally some of the commands that you will use for storage groups are CREATE STOGROUP and ALTER STOGROUP. 

(4) HADR Improvements

A number of really good improvements have been made to the DB2 High Availability Disaster Recovery feature.

HADR can how have up to 3 standby databases instead of just one as in previous releases.  This allows you to have one warm copy of your database in the same rack for high availability and two others in far-off data centers for disaster recovery.

HADR now allows you to replay the transactions on the standby server on a delay that you set.  For example, your HADR standby server can be kept up to date to 4 hours behind current time.  This allows you time to stop replication if something updates your primary that you don’t really want.  You invoke this using the “hard_replay_delay” DB Configuration parameter.

You can now spool logs on the HADR secondary using the “hard_spool_limit” DB configuration parameter.  This can help in situations where sudden spikes in logging cause performance problems on the secondary server. 

(5) Row and Column Access Control This new security feature allows you to very easily control who accesses what data within a table.  This is also known as fine grained access control.  The Label Based Access Control (LBAC) feature introduced in DB2 v9 is still available and provides security features not available in RCAC.  However, RCAC tends to be easier to use. 

(6) DB2 Performance Enhancements One of the major improvements in the v10.1 release is making DB2 consume fewer CPU resources thereby making the DB2 engine more efficient. 

DISCONTINUED FEATURES

2

Page 3: Db2 Important questions to read

The features below are some of the ones that are no longer available in v10.1

(1) Control Center: - While the v9.7 Control Center may still work for some purposes, it will not support any new functionality introduced in DB2 v10.1.

(2) DB2 JDBC Type 2 driver(3) You will not be able to install DB2 v10.1 on any of these older operating systems:  AIX 5.3, HP-UX

11iv2, Solaris 9, Ubuntu 8.0.4.x

Q:-What is the difference between DMS & SMS Tablespaces?

Answer:-

SMS(System Managed Space) DMS(Database Managed Space)Created using MANAGED BY SYSTEM clause in the CREATE TABLESPACE command.

Created using MANAGED BY DATABASE clause in the CREATE TABLESPACE command.

Containers will be defined as a directory name. Containers will be defined as a file name or a device name. We must specify the initial space for each container.

The file system controls the allocation of storage. Space will be allocated while creating the tablespace.We cannot do any changes in the tablespace containers once created.

We can add, extend, reduce and drop the containers.

Containers will grow until they reach the capacity of the file system.

Containers can be extended beyond the allocated size manually or automatically (if auto resize is enabled) up to the file system size.

There will be no on-going maintenance for SMS tablespace.

We will have some maintenance activities like adding or extending containers, Lowering High Water Mark and Re-balancing.

Generally slower than DMS and Automatically Storage.

Good performance when compared to others.

Q. WHAT IS THE DIFFRENCE BETWEEN LOAD AND IMPORT?

Answer:-

IMPORT LOADSlow when moving large amounts of data. The import utility performs SQL INSERTs

Faster than the import utility when moving large amounts of data, because the load utility writes formatted pages directly into the database.

Creation of tables, hierarchies, and indexes supported with PC/IXF format.

Tables and indexes must exist.

No support for importing into materialized query tables.

Support for loading into materialized query tables.

All rows are logged. Minimal logging is performed.Trigger support. No trigger support.You can import into a host database through DB2 Connect.

You cannot load into a host database.

Supports hierarchical data Does not support hierarchical data.WSF format is supported. WSF format is NOT supported.Supports import into tables and views. Supports loading into tables only.If an import operation is interrupted, and a commit count was specified, the table is usable and will contain the rows that were loaded up to the last

If a load operation is interrupted, and a savecount was specified, the table remains in load pending state and cannot be used until the load operation is

3

Page 4: Db2 Important questions to read

COMMIT. The user can restart the import operation, or accept the table as is.

restarted.

All constraints are validated during an import operation.

The load utility checks for uniqueness and computes generated column values, but all other constraints must be checked using SET INTEGRITY.

If updated statistics are required, the runstats utility must be run after an import operation.

Statistics can be gathered during the load operation if all the data in the table is being replaced.

Import files must exist on the client from which the import utility is invoked.

Depending on the options specified, load files or pipes can reside either on the database partition(s) that contain the database, or on the remotely connected client from which the load utility is invoked.

Question: - How will you tune a query?

Answer: (1) Using Bind Variables: - we should use bind variables, stored procedures, and packages wherever possible to re-use the same parsed SQL statements.

(2) Using the indexes carefully - Having indexes on columns is the most common method of enhancing performance, but having too many of them may degrade the performance as well. So, it's very critical to decide wisely about which all columns of a table we should create indexes on.

(3) Using EXPLAIN PLAN: - This tool can be used to fine tune SQL queries to a great extent. EXPLAIN PLAN explains the complete access path which will be used by the particular SQL statement during execution.

(4) Using WHERE instead of HAVING - usage of WHERE clause may take advantage of the index defined on the column(s) used in the WHERE clause.

(5) Joining tables in the proper order - The order in which tables are joined normally affects the number of rows processed by that JOIN operation and hence proper ordering of tables in a JOIN operation may result in the processing of fewer rows, which will in turn improve the performance. The key to decide the proper order is to have the most restrictive filtering condition in the early phases of a multiple table JOIN. For example, in case we are using a master table and a details table then it's better to connect to the master table first to connecting to the details table first may result in more number of rows getting joined.

(6) Simple is usually faster - yeah... instead of writing a very complex SQL statement, if we break it into multiple simple SQL statements then the chances are quite high that the performance will improve.

Question: - What does the RUNSTATS Utility do?

Answer: - RUNSTATS collects statistics about the data in the table like, cardinality statistics, frequency statistics that will be used by the optimizer to determine a good access path. 

Question: - Does runstats do a sort?

Answer: - No runstats does not perform sort, Reorg performs a sort.

Question:-What DB parameter must be set to allow to take incremental back up?Answer: - First we need to set logarchmeth1 then our db will be ready to take online backup and then for incremental backups to be taken you need to enable TRACKMOD parameter.

4

Page 5: Db2 Important questions to read

Question: What is EXPLAIN in DB2Answer: EXPLAIN is used to detail the access paths chosen by DB2 optimizer for SQL statement. This command is used to monitor the performance of SQL statement used in a program.

Question: - What is rollforward?

Answer: - If a backup operation is performed online, there may be users connected to the database in the middle of a transaction. Thus, an online backup contains the backup image of a database that is potentially in an inconsistent state. After restoring an online backup image, the database is immediately placed in roll forward pending state. You must run the ROLLFORWARD DATABASE command to bring the database back to a normal state.

If you performed an offline backup but your database is configured to use archival logging, then the database is also placed in a roll forward pending state following a restore. In this case, you do not need to use the ROLLFORWARD command because an offline backup implies that the database is already in a consistent state. To avoid this, use the WITHOUT ROLLING FORWARD option in the RESTORE DATABASE command. You need SYSADM, SYSCTRL, or SYSMAINT authority to execute the ROLLFORWARD command.

During the roll forward process, the transactions in the log files are applied. You can apply all the changes in the log files, that is, roll forward to the end of logs, or you can roll forward to a PIT. This means DB2 will traverse the logs and redo or undo all database operations recorded in the logs up to the specified PIT.

To perform a roll forward of the sample database you can use any of the following statements as shown in Figure:-

ROLLFORWARD DATABASE sample TO END OF LOGS AND COMPLETE (1)ROLLFORWARD DATABASE sample TO timestamp AND COMPLETE (2)ROLLFORWARD DATABASE sample TO timestamp USING LOCAL TIME AND COMPLETE (3)ROLLFORWARD DATABASE sample TO END OF BACKUP AND STOP (4)

Example (1) Rolls forward to the end of the logs, which means that all archived and active logs are traversed. At the end, DB2 completes the roll forward operation and brings the database from roll forward pending state to a usable state.

Example (2) Rolls forward to the specified PIT.

Example (3) is similar to example (2), but the timestamp is expressed using local time.

Example (4) Instructs DB2 to determine the minimum PIT that database sample is allowed to roll forward to, and then will roll forward to that PIT and bring the database from roll forward pending state to a usable state.

Question: - Explain db2 Architecture?

5

Page 6: Db2 Important questions to read

Answer: - Each IBM DB2 installation has following basic levels of architecture:

DAS (Database Administration Server)Every system with DB2 installed has one background process known as the DB2 AdministrationServer or “DAS”. The main purpose of DAS is to provide remote administration support. It isrequired if you want to use many of the functions of the GUI client tools.

DAS is a background process to support instance administration

dasusr1 on UNIX (default) DB2DAS service on Windows (default) Only one DAS process per server machine

Required for:

Network database discovery Remote administration Tools Catalog task scheduling

The DB2 Administration Server should always be running. However, you can manually stop and start it from a DB2 command window by using the db2admin command.

DB2 Profile Registry

The DB2 Environment has a set of configurable items stored in what is known as the DB2 ProfileRegistry.

Settings can be applied to various levels

Environment Instance Global (all instances)

DB2 Profile Registry settings are different than the Database Manager and Database configuration parameters. DBM and DB Config parameters are platform independent and are consistent across Windows and UNIX platforms.

To view the current registry settings, use the “db2set” command. There are additional flags you can add to that command to filter the output. For example, the “-all” flag shows all the registry variables that are currently set. The “-lr” flag lists every available registry variable that can be set for the current platform. To set or change one of the registry parameters, use the “db2set” command, followed by the parameter name, the equal sign (=), then the new value. Ensure that you do not leave a space on either side of the equal sign or else your change will not take effect. A commonly set registry variable is DB2COMM. This variable tells DB2 what communication protocols it should be using to listen for connections. To enable DB2 to listen for TCP/IP connections, you would issue the command: “db2set DB2COMM=tcpip”. This is done by default during the DB2 installation process if the installer detects a TCP/IP configuration. To unset a registry variable, set it, but do not specify a value on the right side of the equals sign. With very few exceptions, the instance must be restarted before the Registry setting takes effect.

Instance Concepts

DB2 also has the concept of an instance. An instance is the set of processes, disk and memoryAllocations which provide database services. You can also think of an instance as a container fordatabases. One instance can be used to provide services to one or more databases. A single

6

Page 7: Db2 Important questions to read

machine can have one or more instances. Each instance is independent of other instances, and has it’s own set of configurable parameters.

An instance is also known as a Database Manager (DBM) Manages the system resources assigned to it Can be independently stopped or started Has its own set of processes Has its own configuration file (DBM CFG)

Example:One instance for development, another for QA testing.Both instances are fully independent.

An instance is a logical server environment needed to create and work with databases. An instance is also frequently referred to as a database manager, or DBM.Instances are a collection of processes which provide access to database(s). If you have more than one instance created on a machine, each instance acts as an independent server environment which can be stopped and started without affecting other instances. All databases contained in the instance inherit all of the instance’s configuration and share the instance’s resources. You might be asking yourself why you would want to have more than one instance on your server. There are different reasons for doing this. For example, you might want to have one instance set up for your developers, and another instance set up for your testers. That way, if the testers crash their instance while they are doing testing work, it will not affect the developers’ instance. Another reason might be that you don’t want two databases to inherit the same instance configuration settings. A good example of this is the TCP/IP port that applications will be using to connect to the database. This port is defined at the instance level, meaning that two databases contained in the same instance will both be listening for connections on the same port. If you wanted the databases to listen for connections ondifferent ports, you would need to put them in their own instances and set the correct port number for each.

Instance - Stopping and Starting

It is sometimes necessary to stop and restart an instanceExample: - after changing a non-dynamic parameter in the DBM CFGIf you change a non-dynamic instance configuration parameter, you have to stop and restart the instance for the change to take effect. From the command line, this can be done using the “db2stop” and “db2start” commands. Before an instance can be stopped, all applications must disconnect. If you want to stop the instance immediately, forcing off all applications thus terminating their associated processes, you can use the ”db2stop force” command.An instance can also be stopped in the Control Center by right-clicking on the instance object and selecting either Stop or Start.

From the command line, you can enter the “GET DBM CFG” command to view the current parameter values. Adding the “SHOW DETAIL” keywords to the command shows both the current and delayed value of the parameters. The delayed value is the value that will take effect after stopping, then restarting the instance.

To update a parameter, you can use the “UPDATE DBM CFG” command. For example, to update the port number that databases will listen to connections on, to port50009, you would use the command: “update dbm cfg using svcename 50009”.

Databases Concepts

A database is the set of files which contain the actual data. You can create multiple databases inside of an instance. Each database is independent and does not share its configuration, system catalogs or transaction logging mechanism. You cannot query across multiple databases, unless you utilize a DB2 technique known as “Federation”.

7

Page 8: Db2 Important questions to read

A collection of tables and related objects

Each database includes system catalog tables (database meta data) a database configuration file (DB CFG) a recovery log Databases are isolated from each other (object independent)

A database is a collection of tables (including the data) and related objects such as indexes, views, triggers, functions, and stored procedures. Each database also has its own system catalog tables which contain Meta data that describes the content of the database. A database also has its own configuration file and recovery log. Databases are isolated and independent from each other to the extent of database objects and data.

For example, two databases do not share the same system catalog tables or recovery log. However, if the databases exist in the same instance, they share the same instance processes.Database Configuration parameters control things such as the placement of log files, defaults for query optimization, and the amount of memory allocated for the lock list or sorting.

The database configuration file, or DB CFG, is viewed by using the “GET DB CFG FOR” command.For example, to view the database configuration for a database named sample, you would use the command “get db cfg for sample”.

To update a parameter, use the “UPDATE DB CFG FOR” command. For example, to increase theamount of memory used for locking, you would update the value of the LOCKLIST parameter to 2000 4K pages using the command: “UPDATE DB CFG FOR SAMPLE USING LOCKLIST 2000”. Many parameters are dynamic and will take effect immediately. If a parameter is not dynamic, the database must be restarted for the change to take effect. The instance does not need to be stopped, it can remain running, but the database will need all applications to disconnect and all database processes be deactivated. If the database was previously activated with the ACTIVATE DATABASE command, the DEACTIVATE DATABASE command must be issued. Otherwise, a database will no longer be active once the last application is terminated. Once again, to see if a changed parameter was dynamic, use the optional keywords “SHOW DETAIL”when displaying the db cfg parameters and check if the delayed value matches the current value. Certain database manager and database configuration parameters accept a value of “AUTOMATIC”.

Common Processes

db2sysc - database instance process (one per INSTANCE) . The “db2sysc” process is the system controller. This is the central process that manages and coordinates all instance activities.

db2tcpcm - tcpip communication/listener . The “db2tcpcm” process is a “listener” for TCPIP connection requests.

db2pfchr - DB2 asynchronous I/O data prefetchers (NUM_IO_SERVER) – BP prefetchers . The “db2pfchr” is a “pre-fetcher” for retrieving data from disk before it is actually needed. DB2 can detect when data might be needed, prior to the actual instruction to fetch, and will asynchronously spawn 1 or more of these processes to fetch the data.

db2pclnr - DB2 asynchronous I/O data writer (NUM_IOCLEANER) – BP page cleaners. The “db2pclnr” is a “page cleaner”, responsible for writing dirty pages in memory back to disk. This process also acts asynchronously so that DB2 does not have to wait for a page to be written out to disk if it needs room to bring in a new one.

8

Page 9: Db2 Important questions to read

Q:-Describe the DB2 Database Configuration Parameter – SORTHEAP?

Answer: - Defines the maximum number of memory pages used for private sorts or the maximum number of shared memory pages to be used for shared ports. In a private sort, the agent private memory is affected. If it’s a shared sort then the database shared memory is influenced.

Q: - Can memory information be obtained by the GET DB CFG FOR mydb SHOW DETAIL command?

Answer: - Yes. View and Configure information for:

A) Self Tuning Memory (SELF_TUNING_MEM) – Indicates whether the memory tuner is ON or OFF

B) Size of database shared memory (DATABASE_MEMORY) – Details the shared memory amount reserved for the database shared memory region

C) Database Memory Threshold (DB_MEM_THRESH) - Defines how the database manager manages excess unused database shared memory.

Q:-To perform an operation against a different instance – which variable value do you change?

Answer: - The environment variable “set DB2INSTANCE = [target_instance_name]” allows you to perform a task on another Instance. The alternative is to ATTACH to another instance. The DBINSTANCE variable can also be set at the session level.

Q:-Which DB2 configuration is used to set the maximum number of applications that can execute concurrently?

Answer: - MAXCAGENTS. The parameter assists in managing the load on the system during high concurrent application requests. The parameter is useful in managing in a shared environment with limited memory and high levels of connections.

Q:-What command disables roll-forward recovery?

Answer: - The LOGARCMETH1 is the Primary Log Archive method configuration parameter. Assigning the OFF value indicates the log archiving method is not to be used. An example of assigning the OFF value is:

UPDATE DB CFG FOR MYDB USING LOGARCMETH1 OFF;

Q: - To allow the DB2 Discovery utility to see a database, what changes must be made?

9

Page 10: Db2 Important questions to read

Answer:-DAS server must be running and the DISCOVER configuration for DAS must be set to KNOWN or SEARCH.

Question: I’m trying to complete an OFFLINE FULL BACKUP and receive this error message when executing db2 backup DB mydb.

 SQL1035N the database is currently in use.  SQLSTATE=57019

 How can I fix?

Answer: First, check if the database is activated.

db2pd -db mydb -app

or

db2 list active databases

Second, if it’s activated, then deactivate the database

 db2 deactivate database

Third, try OFFLINE FULL BACKUP again

DB2 – Redirect Restore

Question: How do I relocate an existing DB2 database? I have a database on a path such as “/db2inst/db/”   and would like to move the database to “/db2inst/dbnew/”.

 Answer: One option is to backup and restore with a DB2 Redirect Restore

  Second option – use db2relocatedb

I prefer the first option - DB2 Redirect Restore as it forces the DBA to take more precautionary steps. One of things I like about the Redirect Restore is DB2 will generate the script, a few modifications are required, execute the script and Redirect Restore completed!

 Create a Restore Redirect script

Step 1- Ensure all relevant database server files are backed up. Usually I force a backup to tape. If it’s a VM consider a VM snapshot for  extra rollback flexibility.

Step 2 – For the Restore Redirect: Confirm a FULL BACKUP is available and the FULL BACKUP was completed by DB2 backup facility

Step 3 - Confirm you can connect to this database. If crash recovery is required complete first.

Step 4 - Is the database on multiple partitions and no target database exists – then the script must be executed partitions by partition. I prefer to create a target dummy database which runs the script over all the partitions

10

Page 11: Db2 Important questions to read

Step 5 – Using the CLP – here is an example of how to generate the script

1. db2 restore db MYDB from /db2ins/backups taken at 20121126133630 redirect generate script mydb.clp

 Step 6 – Open the redirected restore script in a text editor to make any modifications necessary. You can modify:

Login details – username\password

Restore options - ON, DBPATH ON, INTO, NEWLOGPATH etc

Automatic storage paths

Container layout and paths

Step 7 – Execute the script

1. db2 -tvf mydb.clp

 Step 8 – Confirm directory details

1. db2 list db directory show detail

2. db2 list db directory on /db2wbm/home

Q: - What is Hierarchical database model?A hierarchical database model is a data model in which the data is organized into a tree-like structure. The structure allows representing information using parent/child relationships: each parent can have many children, but each child has only one parent (also known as a 1-to-many relationship).

Q: - What is Materialized Query Table?

A materialized query table (MQT) is a table whose definition is based on the result of a query, and whose data is in the form of pre computed results that are taken from one or more tables on which the materialized query table definition is based.

11

Page 12: Db2 Important questions to read

For Example:-

CREATE TABLE TEMP.SAI_PROD_ACCNT_05032013 AS (SELECT CONSUMER_ID FROM MBC_USER.PAYMENT_DETAILS_T PD WHERE --TO_CHAR(PD.COLLECTION_DATE,'MM/RRRR') = P_MONTHYR AND PD.RECORD_STATUS = 1 AND PD.DB_IP_ADDRESS = 'MIGSERVER' AND TRUNC(PD.CREATE_DATE) IN (TRUNC(SYSDATE) ) AND CONSUMER_ID IN (SELECT ID FROM MBC_USER.CONSUMER_MASTER CM WHERE SUBSTR(CM.SCNO,1,2) IN ('VN','HR','RD','RK','70') AND ID LIKE '104%') AND COLLECTION_DATE > TO_DATE('04/2011','MM/RRRR') AND NOT EXISTS (SELECT 1 FROM MBC_USER.JOURNALBOOK_T WHERE CONS_ID = PD.CONSUMER_ID AND PD.ID = REF_ID AND RECORD_STATUS = 1 AND TRANSACTION_TYPE = 'RECEIPT') UNION ALL SELECT CONS_NUM AS CONSUMER_ID FROM MBC_USER.BILL_DETAILS_T BD WHERE BD.BILLMONTH = 02 AND BD.BILLYEAR = 2013 AND BD.RECORD_STATUS = 6 AND BD.DB_IP_ADDRESS = 'MIGSERVER' AND TRUNC(BD.CREATE_DATE) IN ( TRUNC(SYSDATE)) AND CONS_NUM IN (SELECT ID FROM MBC_USER.CONSUMER_MASTER CM WHERE SUBSTR(CM.SCNO,1,2) IN ('VN','HR','RD','RK','70') AND ID LIKE '104%') AND NOT EXISTS (SELECT 1 FROM MBC_USER.JOURNALBOOK_T WHERE CONS_ID = BD.CONS_NUM AND BD.ID = REF_ID AND RECORD_STATUS = 1 AND TRANSACTION_TYPE = 'BILL')) WITH NO DATA;

Q : - WHAT IS MEANT BY DAS?

ANS. DAS STANDS FOR DATABASE ADMINISTRATION SERVER. The DB2(R) Administration Server (DAS) is a control point used only to assist with tasks on DB2 Universal Database(TM) DB2 UDB servers. 7 You must have a running DAS if you want to use available tools like the Configuration Assistant, the Control Center, or the Development Center. DAS assists the Control Center and Configuration Assistant when working on the following administration tasks:

Enabling remote administration of DB2 UDB servers. Providing the facility for job management, including the ability to schedule the running of both DB2

UDB and operating system command scripts. These command scripts are user-defined. Defining the scheduling of jobs, viewing the results of completed jobs, and performing other

administrative tasks against jobs located either remotely or locally to the DAS using the Task Center. Providing a means for discovering information about the configuration of DB2 UDB instances,

databases, and other DB2 administration servers in conjunction with the DB2 UDB Discovery utility. This information is used by the Configuration Assistant and the Control Center to simplify and automate the configuration of client connections to DB2 UDB databases.

Q: - What are DB2’s directory files?

To keep track of this information, DB2 uses a special set of files known as directory files (or directories). Four types of directories exist:

1. System database directory2. Local database directory3. Node directory4. Database Connection Services (DCS) directory

Q: - What is LOB?

Large object (LOB) data types are used to store large amounts of unstructured data. Large object data types include the following:

12

Page 13: Db2 Important questions to read

Binary large object: The binary large object data type is used to store binary data values (such as documents, graphic images, pictures, audio, and video) that are up to 2 gigabytes in size. The keywords BINARY LARGE OBJECT and BLOB are used to denote the binary large object data type. The amount of storage space set aside to store a binary large object value is determined by the length specification provided when a binary large object data type is defined. For example, 800 bytes of storage space would be set aside for a BLOB(800) definition.

Character large object: The character large object data type is used to store SBCS (single-byte character set) or MBCS (multibyte character set)character string values that are between 32,700 and 2,147,483,647 characters in length. The keywords CHARACTER LARGE OBJECT, CHAR LARGE OBJECT, and CLOB are used to denote the character large object data type. The amount of storage space set aside to store a character large object value is determined by the length specification provided when a character large object data type is defined. For example, 800 bytes of storage space would be set aside for a CLOB(800) definition.

Double-byte character large object: The double-byte character large object data type is used to store DBCS (double-byte character set) character string values that are between 16,350 and 1,073,741,823 characters in length. The keyword DBCLOB is used to denote the double-byte character large object data type. The amount of storage space set aside to store a double-byte character large object value is determined by the length specification provided when a double-byte character large object data type is defined. For example, 800 bytes of storage space would be set aside for a DBCLOB(400) definition.

Q: - Which of the following is NOT a valid method of authentication that can be used by DB2 9?

A. SERVER

B. SERVER_ENCRYPT

C. CLIENT

D. DCS

The correct answer is D.

In DB2 9, the following authentication types are available: SERVER, SERVER_ENCRYPT, CLIENT, KERBEROS, KRB_SERVER_ENCRYPT,DATA_ENCRYPT, DATA_ENCRYPT_CMP, GSSPLUGIN, and GSS_SERVER_ENCRYPT. (Although DCS was a valid method of authentication in DB2 UDB Version 7.x, it is no longer supported.)

Q: - What is check pending and copy pending status in DB2, how do you resolve it?

When a table is loaded with ENFORCE NO option, then the table is left in CHECK PENDING status. It means that the LOAD utility did not perform constraint checking. To remove the check pending state, use the SET INTEGRITY statement like

db2 set integrity for table1 immediate checked

If you load with LOG NO and do not take an inline copy, LOAD places a table space in the COPY-pending status. You can also remove the restriction by using one of these operations:

13

Page 14: Db2 Important questions to read

LOAD REPLACE LOG YES LOAD REPLACE LOG NO with an inline copy REORG LOG YES REORG LOG NO with an inline copy REPAIR SET with NOCOPYPEND

If you use LOG YES and do not make an image copy of the table space, subsequent recovery operations are possible but take longer than if you had made an image copy.

A table space that is in COPY-pending status can be read without restriction; however, it cannot be updated.

Q: - What do the initials DDL and DML stand for and what is their meaning?

DDL is data definition language and DML is data manipulation language. DDL statements are CREATE, ALTER, TRUNCATE. DML statements are SELECT, INSERT, DELETE and UPDATE.

Q: - How do you eliminate duplicate values in DB2 SELECT?

Use SELECT DISTINCT ... in DB2 query

Q: - What are aggregate functions?

Built-in mathematical functions for use in SELECT clause like Max, Min, Avg, Sum etc

Q: - Can you use MAX on a CHAR column?

YES.

Q:-What is UNION, UNION ALL? –

UNION : eliminates duplicates UNION ALL: retains duplicates Both these are used to combine the results of different SELECT statements.

Q:-What is a cursor? Why should it be used?

Cursor is a programming device that allows the SELECT to find a set of rows but return them one at a time. Cursor should be used because the host language can deal with only one row at a time.

Q:-What are the different Phases of Load..???? (IMP)

The load process consists of four distinct phases:-

(1) Load, during which the data is written to the table.

During the load phase, data is loaded into the table, and index keys and table statistics are collected, if necessary. Save points, or points of consistency, are established at intervals specified through the SAVECOUNT parameter in the LOAD command. Messages are generated, indicating how many input rows

14

Page 15: Db2 Important questions to read

were successfully loaded at the time of the save point. If a failure occurs, you can restart the load operation; the RESTART option automatically restarts the load operation from the last successful consistency point. The TERMINATE option rolls back the failed load operation.

(2) Build, during which indexes are produced.

During the build phase, indexes are produced based on the index keys collected during the load phase. The index keys are sorted during the load phase, and index statistics are collected (if the STATISTICS YES with INDEXES option was specified). The statistics are similar to those collected through the RUNSTATS command. If a failure occurs during the build phase, the RESTART option automatically restarts the load operation at the appropriate point.

(3) Delete, during which the rows that caused a unique key violation or a DATALINK violation are removed from the table. Unique key violations are placed into the exception table, if one was specified, and messages about rejected rows are written to the message file. Following the completion of the load process, review these messages, resolve any problems, and insert corrected rows into the table. Do not attempt to delete or to modify any temporary files created by the load utility. Some temporary files are critical to the delete phase. If a failure occurs during the delete phase, the RESTART option automatically restarts the load operation at the appropriate point.

(4) Index copy, during which the index data is copied from a system temporary table space to the original table space. This will only occur if a system temporary table space was specified for index creation during a load operation with the READ ACCESS option specified.

Q: - What are High water marks?

The table space high-water mark indicates the page number of the highest allocated page in a table space. This is different from the number of used pages, since the actual number of pages in use can be below the high-water mark. For example, the last page in the table space is used, but the rest of the table space is empty, the high-water mark will point to the last page.For example, looking at Figure 1, two tables have been created in one table space. The high-water mark points the last used page. If Table 1 is dropped, there is now some free space within the table space. However, the free space below the high-water mark cannot be reclaimed by DB2 to be used for other table spaces, databases, or even outside of the database. This trapped free space can only be used by the current table space to which the free space belongs.

Q: - What are the compression techniques that are new in db2 9.7?

You can reduce storage needed for your data by using the compression capabilities built into DB2® for Linux, UNIX, and Windows to reduce the size of tables, indexes and even your backup images. Tables and indexes often contain repeated information. This repetition can range from individual or combined column values, to common prefixes for column values, or to repeating patterns in XML data. There are a number of compression capabilities that you can use to reduce the amount of space required to store your tables and indexes, along with features you can employ to determine the savings compression can offer. You can also use backup compression to reduce the size of your backups.

Compression capabilities included with most editions of DB2 V9.7 include:

Value compression Backup compression.

15

Page 16: Db2 Important questions to read

The following additional compression capabilities are available with the a license for the DB2 Storage Optimization Feature:

Row compression, including compression for XML storage objects. Temporary table compression Index compression.

Table compression

It is possible for tables to occupy less space when stored on disk by taking advantage of the table compression capabilities available in the DB2® product. Compression saves disk storage space by using fewer database pages to store data.

Also, since more logical data can be stored per page, fewer pages will need to be read in order to access the same amount of logical data. This means that compression can also result in disk I/O savings, as more data can be brought into memory or written to disk with each I/O request.

Compression can be used with both new and existing tables. It can also be used with temporary tables. To implement data compression in DB2 tables, there are two methods you can employ:

Row compression (available with a license for the DB2 Storage Optimization Feature) Value compression.

Row compression Row compression, sometimes referred to as deep compression, compresses data rows by replacing patterns of values that repeat across rows with shorter symbol strings. Of the various data compression techniques available in DB2 Version 9.7, row compression offers the most dramatic possibilities for storage savings.

Value compression Value compression optimizes space usage for the representation of data, and the storage structures used internally by the database management system to store data. Value compression involves removing duplicate entries for a value, and only storing one copy. The stored copy keeps track of the location of any references to the stored value.

Index compression

Indexes, including indexes on declared or created temporary tables, can be compressed in order to reduce storage costs. This is especially useful for large OLTP and data warehouse environments.

By default, index compression is enabled for compressed tables, and disabled for uncompressed tables. You can override this default behavior by using the COMPRESS YES option of the CREATE INDEX statement. When working with existing indexes, use the ALTER INDEX statement to enable or disable index compression; you must then perform an index reorganization to rebuild the index.

Example 1: Checking whether an index is compressed.

The two statements that follow create a new table T1 that is enabled for row compression, and create an index I1 on T1.

CREATE TABLE T1 (C1 INT, C2 INT, C3 INT) COMPRESS YES CREATE INDEX I1 ON T1(C1)

By default, indexes for T1 are compressed. The compression attribute for index T1, which shows whether compression is enabled, can be checked by using the catalog table or the admin table function:

16

Page 17: Db2 Important questions to read

SELECT COMPRESSION FROM SYSCAT.INDEXES WHERE TABNAME='T1' COMPRESSION ----------- Y 1 record(s) selected.

Q:- How do you reduce the high water marks of a tablespace ?

Example: Reducing the HWM with DB2 9.7

The following example will check an automatic storage table space for free space, reduce the high-water mark and reclaim the free space. The example also shows how to monitor the extent movement operation.

Check Table Space for Free Space

Check the table space to see if there is free space that can be reclaimed using MON_GET_TABLESPACE table function:

db2 "select varchar(tbsp_name, 15) as tbsp_name, tbsp_type, reclaimable_space_enabled, tbsp_free_pages from table (mon_get_tablespace('EXTENTRE MAP',-2)) as t"

Determine the Free Pages below the High-Water Mark

Now check to see how many free pages are above and below the high-water mark using the MON_GET_TABLESPACE table function:

db2 "select varchar(tbsp_name, 15) as tbsp_name, tbsp_free_pages, tbsp_total_pages, tbsp_page_top from table (mon_get_tablespace('EXTENTREMAP',-2)) as t"

Start the Extent Movement and Reclaim Space

The extent movement can be triggered by calling the ALTER TABLESPACE command:

db2 alter tablespace extentremap reduce max

The SQL command completed successfully.

Monitor the Extent Movement

To monitor the asynchronous extent movement, use MON_GET_EXTENT_MOVEMENT_STATUS table function: db2 "select varchar(tbsp_name,15) as tbsp_name, last_extent, num_extents_moved, num_extents_left, total_move_time from table (mon_get_extent_movement_status('EXTENTREMAP',-1)) AS T"

Q:- What are the types of backup available in db2 ?

Backups can be made while the database is active or inactive, depending on the type of recovery logs you use.

17

Page 18: Db2 Important questions to read

Online backup

Performing a backup of your DB2 database while the database instance is running is called an online backup. If you plan to make an online backup, you must use archive logs. To do this, you must enable the Roll-forward recovery option. After you have enabled the database for Roll-forward recovery, you must restart the database. You must also create at least one full offline backup (see the next section) after Roll-forward is enabled but before you perform an online backup. Since the database is running, users can be connected to the database while the backup operation is being performed. Any changes made to the database during the backup operation are recorded in the logs.

Offline backup

Making a backup of a DB2 database while the database instance is shut down is an offline backup. Managing an offline backup is simpler than an online backup and less prone to error because with no users connected to the database, no changes can be made while the backup is taking place. Before you take the database offline, you need to stop your ArcSDE service and any other service that accesses your database. If you use circular logging (your database is non recoverable), an offline backup is your only option. You can use an offline or online backup if you use archive logging. You should make regular full backups of the DB2 database. A full backup should include the DB2 database and, if you have started an ArcSDE service, the giomgr.defs, dbinit.sde, and services.sde files.

Incremental backups

As the size of the database grows, the amount of time it takes to complete a full database backup operation increases. To reduce the number of times you have to perform a full database backup, you can create one full backup image and several incremental backups. An incremental backup only contains pages that have been updated since the previous backup image was made plus all the metadata of the initial database. DB2 uses two types of incremental backup images: cumulative and delta.

A cumulative backup image is a copy of all database data that has changed since the most recent, successful, full backup operation. A cumulative backup image contains a series of incremental backups taken over a period of time; therefore, the previous incremental backup image is contained in it.

A delta backup image is a copy of all database data that has changed since the last successful backup of any kind—full, cumulative, or delta. A delta backup image is also known as a differential or noncumulative backup image.

Q: - How do u change the page size of a table space in db2? (IMP)

Answer: You cannot change the page size of an existing table space.

Q: - Can I have different versions of DB2® installed on one server?

Answer: Yes, you can. But please keep in mind the following limitations, especially on Windows.

On Windows: DB2® Universal Database V8.1 and DB2 Universal Database V8.2 cannot coexist on the same machine. You can install either version before you install DB2 V9.1 or DB2 V9.5 and they can coexist - but have to be installed in different directories. The multi-copy installation feature introduced in DB2 V9 and above, lets you create multiple copies of these versions on the same machine.

On UNIX: The above limitations do not apply. For DB2 V 9/9.5/later (including Windows) or for UNIX/Linux, you can simply install on different locations. For example, you can install DB2 V 9.5 first, and then install DB2 V 9 to a different location, and so on.

18

Page 19: Db2 Important questions to read

Q: - If I have one instance of DB2 on version 8.2, can I use the same instance on DB2 9.5?

Answer: No, you cannot share the instances across various DB2 versions. You can upgrade from DB2 V 8.2 to later releases but cannot share an instance between the releases without an upgrade.

Q: - Where can I find DB2 Fix Packs for Linux, UNIX and Windows?

Answer: You can download Fix Packs and client code for DB2 UDB Version 8 0R Later From IBM Website.

Q: - I recently applied a DB2 Fix Pack on my system. After which I am unable to start the instance. What could be the possible problem?

Answer: Try running "db2iupdt <instance name>"

You can find all the pre-installation and post-installation requirements in the readme.txt file that comes along with the Fix Pack. In case the Fix Pack does not contain any readme.txt, the file can be downloaded from the link listed in answer A3 by entering the Fix Pack number which you are just installed.

Note: For DB2 V 9.5 and later, this step is no longer required.

Q: - How do I verify what DB2 Product I have installed on Windows/UNIX/Linux? And how do I find out the exact DB2 version I am running?

On windows platforms you can view the list of installed products using Add/Remove Programs Control Panel Applet (appwiz.cpl). Product names begin with either DB2 or IBM Data Server.For finding out the exact DB2 version, run 'db2level' from a DB2 Command Window on Windows machines and from a normal UNIX prompt on UNIX. The 'db2level' output will tell you the exact DB2 Fix Pack you are running, the bit level DB2 is running as, whether or not any special builds are being used, and other information DB2 support may require.

Windows Example:C:>db2levelDB21085I Instance "DB2" uses "32" bits and DB2 code release "SQL09013" with level identifier "01040107". Informational tokens are "DB2 v9.1.300.257", "s070719", "WR21392", and Fix Pack "3". Product is installed at "C:PROGRA~1IBMSQLLIB" with DB2 Copy Name "DB2COPY1".

UNIX Example:$ db2levelDB21085I Instance "v8inst1" uses "64" bits and DB2 code release "SQL09050" with level identifier "03010107". Informational tokens are "DB2 v9.5.0.0", "s071001", "AIX6495", and Fix Pack "0". Product is installed at "/view/DB2_v10_aix64_s071001/vbs/INST".

Q:-During instance creation DB2 creates several directories and files with permission that are open to all users. Can I manually change such file permission to not allow access to all users?

Answer: During instance creation time DB2 automatically creates directories and files for its use. Permission of such files and directories should not be changed manually. Any attempt to manually change these could result in unexpected file access errors. Hence its not recommended to change permission on files/directories created by DB2.

19

Page 20: Db2 Important questions to read

Q: - Can you install Data Studio on a machine which already has DB2 installed?

Answer: Data Studio can be installed on a machine which already has DB2 installed. Both products can coexist; you do not need to remove the base DB2 product to install Data Studio.

Q: - Can you have more than one DB2 instance created under the same DB2 installation (DB2 copy)?

Answer: Yes, you can.

Linux, UNIX -- It is possible to have more than one instance on a Linux or UNIX operating system if the DB2® product was installed with root privileges. Each instance can run simultaneously, though they are independent of the other.

Windows -- It is possible to have more than one instance and you can run multiple instances concurrently on windows. Each instance of the database manager maintains its own databases and has its own database manager configuration parameters. You can also have multiple databases created under each instance on all OS platforms.

Q: - Which of the operation is faster load or import, if the amount of records is 1000 then what is the case?

Answer: Basically Load is faster than import. Import as compare to load is slow when moving large amount of data. But if the number of rows is less than we can opt for any one of them Option.

Q:- What is the process model for db2 ?

The DB2 process model

Knowledge of the DB2® process model will help you to understand how the database manager and its associated components interact, and this can help you to troubleshoot problems that might arise. The process model that is used by all DB2 database servers facilitates communication between database servers and clients. The DB2 database server must perform many different tasks, such as processing database application requests or ensuring that log records are written out to disk. Each task is typically performed by a separate engine dispatchable unit (EDU).

The following list includes some of the important EDUs that are used by each database:

db2dlock, for deadlock detection. In a partitioned database environment, an additional thread (db2glock) is used to coordinate the information that is collected by the db2dlock EDU on each partition; db2glock runs only on the catalog partition.

db2fw, the event monitor fast writer; which is used for high volume, parallel writing of event monitor data to tables, files, or pipes

db2hadrp, the high availability disaster recovery (HADR) primary server thread db2hadrs, the HADR standby server thread db2lfr, for log file readers that process individual log files db2loggr, for manipulating log files to handle transaction processing and recovery db2loggw, for writing log records to the log files db2logmgr, for the log manager. Manages log files for a recoverable database.

20

Page 21: Db2 Important questions to read

db2logts, for tracking which table spaces have log records in which log files. This information is recorded in the DB2TSCHG.HIS file in the database directory.

db2lused, for updating object usage db2pfchr, for buffer pool prefetchers db2pclnr, for buffer pool page cleaners db2redom, for the redo master. During recovery, it processes redo log records and assigns log

records to redo workers for processing. db2redow, for the redo workers. During recovery, it processes redo log records at the request of the

redo master. db2shred, for processing individual log records within log pages db2stmm, for the self-tuning memory management feature db2taskd, for the distribution of background database tasks. These tasks are executed by threads

called db2taskp. db2wlmd, for automatic collection of workload management statistics

Q: - What are the utilities you are aware of?Answer: Load utility, db2move, Import, Export, Admin_Copy_Schema

Q:-What does the parameter “diagsize" specify?Answer: diagsize specify how much combined disk space is occupied by both the administration notification and diagnostic log files . The value of the new diagsize database manager configuration parameter decides what form of log files will be adopted. If the value is 0 (default), a single administration notification log file (instance_name.nfy) and diagnostic log file (db2diag.log) will be adopted, with the size of each log file limited only by the available free disk space. This was the growth behavior of these log files in previous releases. However, if the value is not 0, a series of 10 rotating administration notification log files and 10 rotating diagnostic log files will be adopted.

Q:-What are the types of logging that are supported for db2 ?Answer:

DB2 UDB has two types of logging available - circular and archive logging.

Circular logging

Circular logging is the default logging strategy used for a database. In this strategy, once the last primary log file is filled in the log directory, new transactions will be written to the first log file thereby overwriting existing log data. These new transactions will continue to overwrite each old log file in sequence. This method of logging ensures data consistency for all committed transactions so that crash recovery is possible.

Circular logging is typically used in data warehouse environments where the need to recover a database is just a matter of restoring a database image. This strategy should not be a choice in an on-line transaction processing (OLTP) environment since roll-forward recovery is not possible.

Archival logging

In contrast to circular logging, the archival logging process creates a new log file when the last log file is filled so that future transactions will not overwrite existing log files. When the database is initialized, the system allocates a certain number of primary log files of a specified size in the active log directory. This number is controlled by a database configuration parameter When the primary log files are all full, secondary log files are created on an "as-needed" basis until the maximum number of secondary log files has been created. Once this number is reached, if additional log space is needed, an error is issued indicating no more log files are available and all database activity is stopped.

21

Page 22: Db2 Important questions to read

With archival logging, it is possible to take an online database backup during which database activity continues to be logged. In the event of a database crash or failure, the database may be restored using a full backup image followed by a roll-forward operation using the archived logs to bring the database to a point-in-time state or to the most recent consistent state by rolling forward to the end of the logs.

Archived logs are of two types:

Online archived logs: These are the log files that reside in the database log directory ('online') and are no longer needed for normal database activity.

Off-line archived logs: These are the log files that have been moved from the database log directory to an off-line storage location (such as a backup server) and are not needed for normal database activity.

Q: - What is infinite logging?To enable infinite logging, simply set the database configuration parameters user exit and log second to YES and -1, respectively. if we set db cfg parameter LOGSECOND=-1,it sets up the db for Infinite logging. So when you've got an update on a large table without a where clause it could hit the log limits after a few hours and do a rollback (spending that same time again).When you have infinite logging, you are limited by disk-space only (for the logs).

Q:- What is db2 Log Files , Active Log Files & Archive Log Files ? (Imp)

In any RDBMS software every changes made to the database needs to be logged. DB2 is no different to any other RDBMS product. Every transaction (insert, update, delete) performed on the data is logged in the log files. Log files are one of the important components of any RDBMS products. "DB2 log file" are sometimes called as "DB2 Transaction log Files". It records all the changes so that in the event of failure, the DB2 server refers the log records which help in recovering the database to the consistent state.

The information or changes stored in the DB2 log file are called as "Log Record". Each log record is associated with "Log Sequence Number (LSN)" which in simple terms can be referred as a unique identifier for the record in the file. When recovery is needed DB2 server uses the LSN to recover the database to consistent point in time.

DB2 maintains two sets of log file namely PRIMARY and SECONDARY log files.

PRIMARY set of log file are pre-allocated when the database is activated.The number of primary log file is determined by LOGPRIMARY DB CFG parameter

db2 get db cfg | grep -i logprimary

SECONDARY set of log file are allocated dynamically only when a transaction has used all the PRIMARY log files and no new PRIMARY log file can be allocated.The number of secondary log file is determined by LOGSECOND DB CFG parameter

db2 get db cfg | grep -i logsecond

Active and archive logs

Based on the type of transaction data the DB2 log file stores, they are classified as

Active Log files Archive Log files

22

Page 23: Db2 Important questions to read

1) Active Log files

In this transaction log files, all the transaction (COMMITED and UNCOMMITTED) that are currently executing into the DB2 system are logged under this files. This is simply the record of what new data are Inserted, Updated and Deleted.  

It stores both the COMMITED and UNCOMMITED transaction executing into the DB2 systems. It also holds information about the transaction that is committed but its data pages are not

externalized to the disk. While the Transaction is executing and there is a DB2 failure, in such case DB2 will use the active log

file for Crash Recovery which will rollback all the UNCOMMITTED transactions and start the database in consistent state.

Every DB2 database created has the Active Log files Location of the active log file is called as “Active log Path” Following command can be used to find the location of Active log path.

SELECT VARCHAR(NAME,30) AS NAME , VARCHAR(VALUE,70) AS VALUE FROM SYSIBMADM.DBCFG WHERE NAME = 'logpath' WITH UR

db2pd -db sample -dbcfg | grep -i "Path to log files (memory)"

db2 get db cfg for sample | grep -i "Path to log files"

2) Archive Log files  Archive log files are available only when the database is enable for “Archival logging” Archived log file are classified into two parts

a) Online Archive log files

This log file contain all the information about the transaction that are committed for the data pages externalized to diskThey are located in the “Active Log Path” along with the “Active Log file”.When the database is enable for archival logging, the “Online Archive Log file” can be identified using the two step process

    i) Find the “Log head” for the DB2 database. This find the current active log file that is used by the database

SELECT VARCHAR(NAME,30) AS NAME , VARCHAR(VALUE,70) AS VALUE FROM SYSIBMADM.DBCFG WHERE NAME = 'loghead' WITH UR

ii) Check the “Active log Path” for the DB2 database

SELECT VARCHAR(NAME,30) AS NAME , VARCHAR(VALUE,70) AS VALUE FROM SYSIBMADM.DBCFG WHERE NAME = 'logpath' WITH UR

iii) Under the “Active log Path” all files below the “LOG HEAD” are the “Online Archive Log” files

b) Offline Archive log files

-- When the “Online Archive Log” file are moved from “Active Log Path” to the “Archived Log path” they are then termed as “Offline Archive Log files”

23

Page 24: Db2 Important questions to read

-- The location of the “Offline Archive Log” file depends on the value set for “LOGARCHMETH1” parameter.

DB2® records all data changes and other significant events in a log.If you keep these logs, DB2 can re-create those changes for you in the event of a failure or roll the changes back to a previous point in time.DB2 writes each log record to a disk data set called the active log. When the active log is full, DB2 copies the contents of the active log to a disk or magnetic tape data set called the archive log.

You can choose either single logging or dual logging.

A single active log contains up to 93 active log data sets. With dual logging, the active log has twice the capacity for active log data sets, because two identical

copies of the log records are kept.

Q: - What is db2dart utility?

Examines databases for architectural correctness and reports any encountered errors.

Q: - How do you determine the locks that applications are holding using db2pd utility?

If you want to see what lock the application is waiting on we can run the command

db2pd -db dbname -locks wait

Q: - Name the parameter that is used to change the prefetcher’s size?

Q: - What is the need of the prefetchers?

Prefetchers retrieve data from disk and move it into the buffer pool before applications need the data. For example, applications needing to scan through large volumes of data would have to wait for data to be moved from disk into the buffer pool if there were no data prefetchers. Agents of the application send asynchronous read-ahead requests to a common prefetch queue. As prefetchers become available, they implement those requests by using big-block or scatter-read input operations to bring the requested pages from disk to the buffer pool. If you have multiple disks for storage of the database data, the data can be striped across the disks. Striping data lets the prefetchers use multiple disks at the same time to retrieve data.

Q: - If a load is interrupted, then what is the state in which the table space will be placed ? The tablespace Placed in a Load Pending State.

Q: - What happens to a table when repeated attempt for the reorg on the table fails ?

Q: - What are the operations that are supported when the table is in reorg pending state?

When the table is placed in reorg pending state we have to reorg that particular table.Using Command like:

Reorg table <schema name>.<Table Name>

Q:-How do we find the size of the table?

Using Admin tab info or admin get info

24

Page 25: Db2 Important questions to read

ORif we have control center on our work station then right click on the table and click on the estimate size option. This will show us the size of the table and indexes separately in Mb or Kb as u wish.

Q:-What are the ways in which U monitor Reorg and runstats other than db2top? By using db2pd Utility

Q:-What will you do if your Reorg and runstats is taking more time than normal ? Where will U check for that?

????Q:-What if ur Reorg fails in the Index-rebuild state? Where the indexes are marked as bad?

???

Q:-What difference does it make to take the backup online by specifying the include logs and without specifying the clause include logs?

Including log files with a backup image

When performing an online backup operation, you can specify that the log files required to restore and recover a database are included in the backup image. This means that if you need to ship backup images to a disaster recovery site, you do not have to send the log files separately or package them together yourself. Further, you do not have to decide which log files are required to guarantee the consistency of an online backup. This provides some protection against the deletion of log files required for successful recovery.

To make use of this feature specify the INCLUDE LOGS option of the BACKUP DATABASE command. When you specify this option, the backup utility will truncate the currently active log file and copy the necessary set of log extents into the backup image.

To restore the log files from a backup image, use the LOGTARGET option of the RESTORE DATABASE command and specify a fully qualified path that exists on the DB2(R) server. The restore database utility will then write the log files from the image to the target path. If a log file with the same name already exists in the target path, the restore operation will fail and an error will be returned. If the LOGTARGET option is not specified, no log files will be restored from the backup image.

If the LOGTARGET option is specified and the backup image does not include any log files, an error will be returned before an attempt is made to restore any table space data. The restore operation will also fail if an invalid or read-only path is specified. During a database or table space restore where the LOGTARGET option is specified, if one or more log files cannot be extracted, the restore operation fails and an error is returned.

You can also choose to restore only the log files saved in the backup image. To do this, specify the LOGS option with the LOGTARGET option of the RESTORE DATABASE command. If the restore operation encounters any problems when restoring log files in this mode, the restore operation fails and an error is returned.

During an automatic incremental restore operation, only the logs included in the target image of the restore operation will be retrieved from the backup image. Any logs that are included in intermediate images referenced during the incremental restore process will not be extracted from those backup images. During a manual incremental restore, if you specify a log target directory when restoring a backup image that includes log files, the log files in that backup image will be restored.

If you roll a database forward that was restored from an online backup image that includes log files, you might encounter error SQL1268N, which indicates roll-forward recovery has stopped due to an error received when retrieving a log. This error is generated when the target system to which you are attempting to

25

Page 26: Db2 Important questions to read

restore the backup image does not have access to the facility used by the source system to archive its transaction logs.

If you specify the INCLUDE LOGS option of the BACKUP DATABASE command when you back up a database, then subsequently perform a restore operation and a roll-forward operation that use that backup image, DB2 will still search for additional transaction logs when rolling the database forward, even though the backup image includes logs. It is standard rollforward behaviour to continue to search for additional transaction logs until no more logs are found. It is possible to have more than one log file with the same timestamp. Consequently, DB2 does not stop as soon as it finds the first timestamp that matches the point-in-time to which you are rolling forward the database as there might be other log files that also have that timestamp. Instead, DB2 continues to look at the transaction log until it finds a timestamp greater than the point-in-time specified.

When no additional logs can be found, the rollforward operation ends successfully. However, if there is an error while searching for additional transaction log files, error SQL1268N is returned. Error SQL1268N can occur because during the initial restore, certain database configuration parameters were reset or overwritten. Three of these database configuration parameters are the TSM parameters, TSM_NODENAME, TSM_OWNER and TSM_PASSWORD. They are all reset to NULL. To rollforward to the end of logs, you need to reset these database configuration parameters to correspond to the source system prior to the rollforward operation. Alternatively, you can specify the NORETRIEVE option when you issue the ROLLFORWARD DATABASE command. This will prevent the DB2 database system from trying to obtain potentially missing transaction logs elsewhere.

Notes:

1. This feature is available only on single-partition databases.2. This feature is not supported for offline backups.3. When logs are included in an online backup image, the resulting image cannot be restored on

releases of DB2 database prior to Version 8.2.

Q:-What is the result of Roll forward command "Roll forward database dbname and stop”?

Answer: - Stops the rolling forward of log records, and completes the rollforward recovery process by rolling back any incomplete transactions and turning off the rollforward pending state of the database.

Q:-What is the difference between "rollforward to the end of logs and stop" and "rollforward to the end of logs and complete”?

Answer:-Different Options Used In Rollforward Command

END OF LOGS :-Specifies that all committed transactions from all online archive log files listed in the database configuration parameter logpath are to be applied.

COMPLETE / STOP Stops the rolling forward of log records, and completes the rollforward recovery process by rolling back any incomplete transactions and turning off the rollforward pending state of the database. This allows access to the database or table spaces that are being rolled forward. These keywords are equivalent; specify one or the other, but not both. The keyword AND permits specification of multiple operations at once; for example, db2 rollforward db sample to end of logs and complete.

Note: When rolling table spaces forward to a point in time, the table spaces are placed in backup pending state.

26

Page 27: Db2 Important questions to read

Q:-What parameter affects the amount of buffers that are allocated for backup that need to be changed to speed up the backup process?

Answer:- UTIL_HEAP_SZ

Q:-What is the default option for online backups in db2 v9.7?

Q: - What is a Nickname?

A nickname is a 'virtual' table in one database that points to a physical table in another database. The nickname does not contain data itself. It just has information about the physical table. You can use a nickname in an SQL statement anywhere a table name can be used. Under the covers, the federated database server issues whatever SQL is necessary to work with the physical table.

A nickname is a 'virtual' table in one database that points to a physical table in another database. The nickname does not contain data itself. It just has information about the physical table. You can use a nickname in an SQL statement anywhere a table name can be used. Under the covers, the federated database server issues what ever SQL is necessary to work with the physical table.

Q: - What are the Steps For Federation in db2? (Imp)

Answer:-

1. Enable federation in your DB2 instance by issuing the following command from a DB2 command window:

db2 update database manager configuration using federated yes

2. If your DB2 instance was running you must stop it and then start it again.

db2stop

db2start

3. Create the DB2 Sample database if you haven't already. From a DB2 command window, issue:db2sampl

4. Create an empty database (one with no user tables). From a DB2 command window, issue:

db2 create database clouddb

5. First, let's create one table in the federated database. i.e in clouddb

create table greeting (deptno char(3), dept_greeting char(6));

insert into greeting values('E21', 'Howdy');

insert into greeting values('E22', 'Rowdy');

insert into greeting values('E23', 'Anshul');

27

Page 28: Db2 Important questions to read

6. Now, let's create our federated objects

create wrapper drda;

7. Next Step is to Create an server

create server mysample

type db2/udb

version '9.7'

wrapper drda

authid "tolleson"

password "mypassw0rd"

options(

add dbname 'SAMPLE');

8. create user mapping

create user mapping for tolleson

server mysample

options (

remote_authid 'tolleson',

remote_password 'mypassw0rd');

9. Next step is to create a Nicknames

create nickname myemp for mysample.tolleson.employee;

create nickname mydept for mysample.tolleson.department;

Q:-What is online Reorg/offline?

Both online and offline are there, online Reorg allows other transaction to access the tables. REORG with ALLOW NO/READ/WRITE ACCESS.

Q:-If application team is contacting you telling the application is running very slow , what all things you will check out ?

28

Page 29: Db2 Important questions to read

I will check for any transactions that are in lock wait state either using db2top utility or by using db2pd utility.

Q:-What is the difference between Primary Key & Unique index?

Primary: a relational database constraint Primary key consists of one or more columns that uniquely identify a row in the table for a normalized relation, there is one designated primary key Unique index: a physical object that stores only unique values There can be one or more unique indexes on a table.

Q:-What is SQLCODE -922?

Authorization failure

Q:-What is SQL-811?

SELECT statement has resulted in retrieval of more than one row

Q:-Is View Update is possible?

Not all of them Some views are updatable eg single table view with all the fields or mandatory fields Examples of non-updatable views are views which are joins, views that contain aggregate functions(such as MIN), and views that have GROUP BY clause

Q:-If I have a view which is a join of two or more tables, can this view be updatable?

NO

Q:-What do you mean by NOT NULL WITH DEFAULT? When will you use it?

This column cannot have nulls and while insertion, if no value is supplied then it wil have zeroes, spaces or date/time depending on whether it is numeric, character or date/time Use it when you do not want to have nulls but at the same time cannot give values all the time you insert this row.

Q:-What do you mean by NOT NULL? When will you use it?

The column cannot have nulls Use it for key fields

Q:-When would you prefer to use VARCHAR?

When a column which contains long text, eg remarks, notes, may have in most cases less than 50% of the maximum length.

Q:-What are the disadvantages of using VARCHAR?

1. Can lead to high space utilization if most of the values are close to MAXIMUM.

29

Page 30: Db2 Important questions to read

2. Positioning of VARCHAR column has to be done carefully as it has performance implications.

3. Relocation of rows to different pages can lead to more I/Os on retrieval.

Q:-When is the authorization check on DB2 objects done. BIND or run time?

At run TIME

Q:-What is Incremental /Delta Back up?

As the size of databases, and particularly warehouses, continues to expand into the terabyte and petabyte range, the time and hardware resources required to back up and recover these databases is also growing substantially. Full database and table space backups are not always the best approach when dealing with large databases, because the storage requirements for multiple copies of such databases are enormous.

Consider the following issues:

When a small percentage of the data in a warehouse changes, it should not be necessary to back up the entire database.

Appending table spaces to existing databases and then taking only table space backups is risky, because there is no guarantee that nothing outside of the backed up table spaces has changed between table space backups.

Two types of incremental backup are supported:

Incremental. An incremental backup image is a copy of all database data that has changed since the most recent, successful, full backup operation. This is also known as a cumulative backup image, because a series of incremental backups taken over time will each have the contents of the previous incremental backup image. The predecessor of an incremental backup image is always the most recent successful full backup of the same object.

Delta. A delta, or incremental delta, backup image is a copy of all database data that has changed since the last successful backup (full, incremental, or delta) of the table space in question. This is also known as a differential, or non-cumulative, backup image. The predecessor of a delta backup image is the most recent successful backup containing a copy of each of the table spaces in the delta backup image.

The key difference between incremental and delta backup images is their behavior when successive backups are taken of an object that is continually changing over time. Each successive incremental image contains the entire contents of the previous incremental image, plus any data that has changed, or is new, since the previous full backup was produced. Delta backup images contain only the pages that have changed since the previous image of any type was produced.

Q:-What is runstats? How it improves performance? Runstats ==> The operation to update the current statistics (like cardinality, high, low values) of tables.DB2 has a cost based optimizer; the access path generated by the optimizer wholly depends upon the correctness of the statistics. So always keep the statistics updated for the user tables.

Q:-What are the tablespace that get created when a DB is initially created?syscatspace

30

Page 31: Db2 Important questions to read

tempspaceuserspace

Q:-What is the use of SYSCAT SPACE?This is a default tablespace created at the time of DB creation. This tablespace is used to store system catalog tables.

Q:-What is Reorg check? To check if there is too much fragmentation issue for a particular table, we use reorgchk. Once you identify the problem, run the Reorg table <table name> to resolve fragmentation issue.

Q:-What is the different Back up types? Full offline db backup, online db backup, tablespace backup

Q:-Other than space utilization what is the difference between DMS and SMS?

Initial allocation of space In SMS allocation of space is done as needed. Because the file system controls the allocation of storage, there is less likelihood that pages will be contiguous, which could have an impact on the performance of some types of queries. While in DMS allocation of space is done when table space created.

Changes to table space containers In SMS No changes once created, other than to add containers for new data partitions as they are added. While in DMS Containers can be extended or added. A rebalance of the table space data will occur if the new space is added below the high water mark for the table space. Containers can be reduced or dropped. A rebalance will occur if there is data in the space being dropped

Performance SMS is Generally slower than DMS and automatic storage, especially for larger tables. While DMS is generally superior to SMS.

Q:-How do you find out deadlock transaction?

By using db2top or db2pd utility.

Q:-What is the use of buffer pools?

The role of buffer pools in caching data

Buffer pools are a key element of DB2® performance, and help you to avoid delays when retrieving data. DB2 can retrieve a page from a buffer pool faster than it can from disk. When data is already in a buffer, an application program avoids the delay of waiting for DB2 to retrieve the data from disk. DB2 lets you use up to 50 buffer pools that contain 4 KB pages and up to 10 buffer pools each that contain 8 KB, 16 KB, and 32 KB pages.

Q:-What is buffer pool hit ratio?

Buffer pool hit ratio is a measure of how often a page access (a get page) is satisfied without requiring an I/O operation.

Q:-Explain the steps of Server Installation?

To start the DB2 Setup wizard:

31

Page 32: Db2 Important questions to read

1. Log on to the system as a user with root authority. 2. Change to the directory where the DB2 database product CD is mounted by entering the following

command:

cd /cdrom

where cdrom represents mount point of the DB2 database product CD.

3. If you downloaded the DB2 database product image, you must decompress and untar the product file. a. Decompress the product file:

gzip -d product.tar.gz

Where product is the name of the database product that you downloaded.

b. Untar the product file:

tar xvf product.tar

c. Change directory:

cd ./product/disk1

4. Enter the ./db2setup command from the directory where the product image resides to start the DB2 Setup wizard.

5. The DB2 Setup Launch pad opens. From this window, you can view installation prerequisites and the release notes, or you can proceed directly to the installation. You may want to review the installation prerequisites and release notes for late-breaking information.

6. Click Install a Product and the Install a Product window will display the products available for installation. Launch the installation by clicking Install New. Proceed through the installation following the DB2 Setup wizard's prompts.

Note:- Once you have initiated the installation, proceed through the DB2 Setup wizard installation panels and make your selections. Installation help is available to guide you through the remaining steps. To invoke the installation help, click Help or press F1. You can click Cancel at any time to end the installation.

Q: - The Application team contacts saying DB response is very low what would you do?

We will Check for is there lock wait transaction is waiting or not by using db2top or db2pd utilities.

Q: -What is EXPLAIN in DB2A: EXPLAIN is used to detail the access paths chosen by DB2 optimizer for SQL statement. This command is used to monitor the performance of SQL statement used in a program.

Q: -What is the size of a data page?Answer: 4K to 8K

Q: - What is Isolation Level in db2? (Imp)

32

Page 33: Db2 Important questions to read

Answer: An isolation level specifies how much one transaction is isolated from other transactions in a multiple-connection environment.

The database manager supports four isolation levels.

Repeatable read (RR) Read stability (RS) Cursor stability (CS) Uncommitted read (UR)

Repeatable read (RR)

The repeatable read isolation level locks all the rows that an application references during a unit of work (UOW). Under RR, an application can retrieve and operate on the rows as many times as necessary until the UOW completes. However, no other application can update, delete, or insert a row that would affect the result set until the UOW completes. Applications running under the RR isolation level cannot see the uncommitted changes of other applications.

Read stability (RS)

The read stability isolation level locks only those rows that an application retrieves during a unit of work.

Cursor stability (CS)

The cursor stability isolation level locks any row being accessed during a transaction while the cursor is positioned on that row. This lock remains in effect until the next row is fetched or the transaction terminates. However, if any data in the row was changed, the lock is held until the change is committed.

Under this isolation level, no other application can update or delete a row while an updatable cursor is positioned on that row. Under CS, access to the uncommitted data of other applications is not possible. However, non-repeatable reads and phantom reads are possible.CS is the default isolation level. It is suitable when you want maximum concurrency and need to see only committed data.

Uncommitted read (UR)

The uncommitted read isolation level allows an application to access the uncommitted changes of other transactions. Moreover, UR does not prevent another application from accessing a row that is being read, unless that application is attempting to alter or drop the table.Under UR, access to uncommitted data, non-repeatable reads, and phantom reads are possible. This isolation level is suitable if you run queries against read-only tables, or if you issue SELECT statements only, and seeing data that has not been committed by other applications is not a problem.

Q:-How will you delete duplicate records from a table?Answer: Delete From Table1Where Id In (Select Id From Tabel1 As Temp Group By Id Having Count (*) >1)

Q:-What is the difference between Where and Having ClauseAnswer: WHERE is for Rows and HAVING is for Groups

Q: what is the maximum number of tables that can be joined ?Answer: fifteen

Q:-Can memory information be obtained by the GET DB CFG FOR mydb SHOW DETAIL command?

33

Page 34: Db2 Important questions to read

Yes. View and Configure information for:

a) Self Tuning Memory (SELF_TUNING_MEM) – Indicates whether the memory tuner is ON or OFF.

b) Size of database shared memory (DATABASE_MEMORY) – Details the shared memory amount reserved for the database shared memory region.

c) Database Memory Threshold (DB_MEM_THRESH) - Defines how the database manager manages excess unused database shared memory.

Q:-What authority should a user have to QUIESCE a DB2 database?

A login account must have either SYSADM or DB2ADM to QUIESCE a database. When the database is in a QUIESCE state – the users with at least one of these criteria can access the database: SYSADM, SYSCTRL, SYSMAINT, DBADMN. The QUIESCE command allows administrative tasks to complete. When the administrative tasks are complete use UNQUIESCE to active the database.

Q:-To perform an operation against a different instance – which variable value do you change?

The environment variable “set DB2INSTANCE = [target_instance_name]” allows you to perform a task on another Instance. The alternative is to ATTACH to another instance.

The DBINSTANCE variable can also be set at the session level.

Q:-Which DB2 configuration is used to set the maximum number of applications that can execute concurrently?

MAXCAGENTS. The parameter assists in managing the load on the system during high concurrent application requests. The parameter is useful in managing in a shared environment with limited memory and high levels of connections.

Q:-To force an application to wait indefinitely to obtain a table lock, which database configuration parameter is used?

LOCKTIMEOUT. Assign a value to LOCKTIMEOUT, to detail the number of seconds an application will wait to obtain a lock. To set LOCKTIMEOUT for an indefinite wait use “-1” . The application will wait until a lock is granted or a deadlock is present. In contrast, assigning “0”, an application will not wait for locks.

Q:-What command disables roll-forward recovery?

The LOGARCMETH1 is the Primary Log Archive method configuration parameter.Assigning the OFF value indicates the log archiving method is not to be used. An example of assigning the OFF value is:

UPDATE DB CFG FOR MYDB USING LOGARCMETH1 OFF;

34

Page 35: Db2 Important questions to read

Q:-To allow the DB2 Discovery utility to see a database , what changes must be made?

DAS server must be running and the DISCOVER configuration for DAS must be set to KNOWN or SEARCH. When the DAS server is created the “discover” setting defaults to “search”.

Q:-Which command starts an instance?

The current DB2 Database Manager Instance background processes can be started by: 1) db2start or 2) START DATABASE MANAGER. To access a database, first starts DB2 at the server level then connect to the database.

Q:-How can you see physical memory (core) utilization by a UNIX DB2 server?

Answer: - By Using db2mtrk

Q:-Tell us something about DB2 memory structure?

Answer: - Root is Instance shared memory, below that is Database shared memory; within each Database there is Application Group shared memory, and then each Agent has private memory.

Q:-How do we control or influence the allocation of these memory sets?

Answer: - By settings in DB and DBM CFG, creation and configuration of buffer pools.

Q:-What command allows me to see all instances set up on a host?

Answer: - db2ilist

Q:-What command lets me see databases defined on an instance that I am attached to?

Answer: - db2 list database directory

Q:-How can I see what the DB2 registry variables are?

Answer: - db2set -all

Q:-What will show me instance configuration?

Answer: - db2 get dbm cfg

Q:-What will show me database configuration?

Answer: - db2 get db cfg for <dbname>

35

Page 36: Db2 Important questions to read

Q: - What is online Reorg/offline?

Answer: Both online and offline are there, online reorg allows other transaction to access the tables. REORG with ALLOW NO/READ/WRITE ACCESS

Q:-If you want to load data without any chance of taking the tablespace to back up pending state, how will you achieve it?Answer: LOAD with NORECOVERY option

Q:-Would you load data to the production tables directly?Answer: No, this cannot be used. Instead use staging tables

Q:-If application team is contacting you telling the application is running very slow , what all things you will check out ?Answer: Check for any transactions that are in lock wait state, list in doubt transactions- Table DB snapshot, Application snapshot, sql snap shot, cpu utilization using top, check is there any stale connection (connections that very old)- check if any background process is running there using list utilities- Check the number of active connections to the DB server- Force the application/transactions which are in lock wait state

Q:-What’s the cmd to find the fix pack of db2udb installed?

Answer: db2level

Q:-What is Redirect Restore? Explain 3 steps to do a redirected restore?

Answer: A redirected restore operation is performed when one of the following situations occur:

You want to restore a backup image to a target machine that is different than the source machine You want to restore your table space containers into a different physical location Your restore operation has failed because one or more containers is inaccessible

Note: A redirected restore cannot be used to move data from one operating system to another.

During a redirected restore operation, directory and file containers are automatically created if they do not already exist. The database manager does not automatically create device containers.

To perform a redirected restore of the DB2TEST database using a script, follow these steps:

1. Use the restore utility to generate a redirected restore script.RESTORE DATABASE DB2TEST FROM C:\DBBACKUP INTO NEWDB REDIRECT GENERATE SCRIPTNEWDB.CLP WITHOUT ROLLING FORWARDThis creates a redirected restore script called NEWDB.CLP.

2. Open the redirected restore script in a text editor to make any modifications that are required. You can modify the restore options, as well as container layout and paths.

36

Page 37: Db2 Important questions to read

3. Run the modified redirected restore script as follows:db2 –tvf NEWDB.CLP

The output of the script will be written into a file called dbname_nodenumber.out. Inour example above, the filename will be db2test_000.out.

Q:-What is the difference between creating buffer pool with immediate option and DEFERRED option?Answer:-

IMMEDIATE

The buffer pool will be created immediately. If there is not enough reserved space in the database shared memory to allocate the new buffer pool, a warning (SQLSTATE 01657) is returned, and the statement is executed DEFERRED.

DEFERRED The buffer pool will be created when the database is deactivated (all applications need to be disconnected from the database). Reserved memory space is not needed; DB2 will allocate the required memory from the system.

Q:-What is Sort heap?Answer: - This parameter defines the maximum number of private memory pages to be used for private sorts, or the maximum number of shared memory pages to be used for shared sorts.

Q:-You just created a DB newly, haven’t set any prams, Can you take an online back up?Answer: - NO

Q:-What are the parms that needs to be set to take an online back of the DB?Answer: Log retain & Logarcmeth1 Parameter needs to be set

Q:-Can you import a file of extension WSF?Answer: Yes

Q:-Can you load a file of extension WSF?Answer: No

Q:-How to check no of active connections to the DB ?Answer: List Active DatabaseQ:-What are the table’s spaces that get created when a DB is initially created?Answer: When a database is created, three table spaces are defined: (1) SYSCATSPACE for the system catalog tables, (2) TEMPSPACE1 for system temporary tables created during database processing, and (3) USERSPACE1 for user-defined tables and indexes. You can also create additional user table spaces at the same time.

Q:-Name at least 2 authorities and privileges which are granted automatically when a database is created?

Answer: The authorities and privileges granted automatically when a database is created are:

a) DBADM, CONNECT, CREATETAB, BINDADD, CREATE_NOT_FENCED, IMPLICIT_SCHEMA, LOAD to the database creator

b) PUBLIC is granted USE privilege on USESPACE1

37

Page 38: Db2 Important questions to read

c) PUBLIC is granted CONNECT, CREATETAB, BINDADD, IMPLICIT_SCHEMA

Q:-Name three Database Privileges.

Answer: The full list of Database Privileges is:

CONNECT

QUIESCE_CONNECT

IMPLICIT_SCHEMA

CREATETAB

BINDADD

CREATE_EXTERNAL_ROUTINE

CREATE_NOT_FENCED_ROUTINE

Q:-Target table t1 is getting deleted. Table t2 has the foreign key. We require that whenever a row from t1 is deleted, the corresponding row from t2 also be deleted. Which option can be used?

Answer: ON DELETE CASCADE: If a row in the parent table is deleted, all the corresponding row in child tables will automatically be deleted.

Q:-A stored procedure has been built and deployed on the db2 udb server machine. What is the minimum software that must be installed to allow an application on the client to execute the stored procedure?

Answer: DB2 Application Development is required on the client machine to run the stored procedure.

Q: What is a db2 bind?

Answer: A db2 bind is a process that builds an access path to db2 tables. A BIND process establishes a relationship between an APPLICATION PROGRAM and its RELATIONAL DATA.

Q: A table called employee has the following columns: name, department, and phone_number. Which can limit read access to the phone_number column?

Answer: Creating a view of the EMPLOYEE table without the phone number.

Q:-Explain difference between sys.Cat and sys.Ibm?

Answer:The database manager creates and maintains two sets of system catalog views that are defined on top of the base system catalog tables.

SYSCAT views are read-only catalog views that are found in the SYSCAT schema. SELECT privilege on these views is granted to PUBLIC by default.

38

Page 39: Db2 Important questions to read

SYSSTAT OR SYSIBM views are updatable catalog views that are found in the SYSSTAT schema. The updatable views contain statistical information that is used by the optimizer. The values in some columns in these views can be changed to test performance.

Q:-Is it possible to alter a table – for example adding a column, when another user is accessing or updating some columns?

Answer:

- Yes It is possible to alter a table- The DB2 tables will not re-structure until any transaction is committed- A new column is defined and identified by the database- The new column will be included only after the transactions of the table are committed- All the altering table statements will be received from other users and are stored - The commit status is updated by the database engine and then the new columns are added

Q:-What are the advantages of using a PACKAGE?

Answer: Packages are the alternative to creating procedures and functionsthey are stand-alone schema objectsthe advantages of packages are 1. Modularity: All the procedures and functions belongs to a particular module of an application can be encapsulated in a package. 2. Easy to design the application : The package body and package specification can be coded and compiled separately without its body. Stored procedures are compiled and executed by qualifying the package names3. Hiding Information : The programming elements declared in the specification of the package is public. The package body elements are declared as private, i.e., they are invisible to the application. Hence they are secured4. Added Functionality: Public variables and cursors are persisted for a session, which enables the sharing of data by all programs of the calling environment5. Better Performance: Packaged sub programs are invoked for the first time by loading the entire package into the memory. Disk I/O operations are not needed for calling related sub programs in the package later.6. Overloading: Multiple programs can be placed in the same package with different number of parameters or types or parameters

Q:-How to execute stored procedures?

Answer: The following is the process to execute the stored procedures:

From the command line type

           db2 connect to Sample;

           db2 -td@ -vf createSQLproc.db2

Type the entire script. After completion of entering the script save the script

Execute the script by invoking the CALL command from Command editor       -CALL Sample;

Q:-Can you use MAX on a CHAR column?

Answer: YES.

39

Page 40: Db2 Important questions to read

Q:-My SQL statement SELECT AVG(SALARY) FROM EMP yields inaccurate results. Why?

Answer: Because SALARY is not declared to have NULLs and the employees for whom the salary is not known are also counted.

Q:-What is a cursor? Why should it be used? –

Answer: Cursor is a programming device that allows the SELECT to find a set of rows but return them one at a time. Cursor should be used because the host language can deal with only one row at a time.

Q:-Can you have more than one cursor open at any one time in a program ? –

Answer: Yes.

Q:-What is auditing?

Answer: Recording SQL statements that access a table. Specified at table creation time or through alter.

Q:-What is RUNSTATS?

Answer: A DB2 utility used to collect statistics about the data values in tables which can be used by the optimizer to decide the access path. It also collects statistics used for space management. These statistics are stored in DB2 catalog tables.

Q:-Are views updateable?

Answer: Not all of them. Some views are updateable e.g. single table view with all the fields or mandatory fields. Examples of non-updateable views are views which are joins, views that contain aggregate functions (such as MIN), and views that have GROUP BY clause.

Q:-What are the various locks available?

Answer: SHARE, EXCLUSIVE, UPDATE

Q:-What is an inner join, and an outer join ?

Answer: Inner Join: combine information from two or more tables by comparing all values that meet the search criteria in the designated column or columns of on e table with all the clause in corresponding columns of the other table or tables. This kind of join which involve a match in both columns are called inner joins.

Outer join is one in which you want both matching and non matching rows to be returned. DB2 has no specific operator for outer joins, it can be simulated by combining a join and a correlated sub query with a UNION.

Q:-What is dynamic SQL?

Answer: Dynamic SQL is a SQL statement created at program execution time.

40

Page 41: Db2 Important questions to read

Q:-What is the difference between CS and RR isolation levels?

Answer: CS: Releases the lock on a page after use RR: Retains all locks acquired till end of transaction

Q:-What is check pending and copy pending status in db2 ?

Answer:

1. Check pending status of a table is set on when you are loading into table with log no and that table has some referential constraint with other table. Copy pending status is set on when you are loading into a table without a NOCOPYPEND option.

2. If the table is loaded with ENFORCE NO option then the table space get into check pending status. That means table space is loaded without enforcing constraints. CHECK utility needs to be run on table space.

If table is loaded with LOG NO option then it gets into copy pending status. The meaning is image copy is needed on table space.

Q: - Explain Process Model of db2?

Answer:

The DB2 process modelKnowledge of the DB2® process model will help us to understand how the database manager and its associated components interact. The process model that is used by all DB2 database servers facilitates communication between database servers and clients. The DB2 database server must perform many different tasks, such as processing database application requests or ensuring that log records are written out to disk. Each task is typically performed by a separate engine dispatchable unit (EDU). For each database being accessed, separate EDUs are started to deal with various database tasks such as prefetching, communication, and logging. Each client application connection has a single coordinator agent that operates on a database. A coordinator agent works on behalf of an application, and communicates to other agents using private memory, interprocess communication (IPC), or remote communication protocols, as needed.

Client programs

Client programs can be remote or local, running on the same machine as the database server. Client programs make first contact with a database through a communication listener.

ListenersCommunication listeners start when the DB2 database server starts. There is a listener for each configured communications protocol, and an interprocess communications (IPC) listener (db2ipccm) for local client programs. Listeners include:

db2ipccm, for local client connections db2tcpcm, for TCP/IP connections db2tcpdm, for TCP/IP discovery tool requests

41

Page 42: Db2 Important questions to read

Agents

All connection requests from local or remote client programs (applications) are allocated a corresponding coordinator agent (db2agent). When the coordinator agent is created, it performs all database requests on behalf of the application.

Database EDUsThe following list includes some of the important EDUs that are used by each database:

db2dlock, for deadlock detection. In a partitioned database environment, an additional thread (db2glock) is used to coordinate the information that is collected by the db2dlock EDU on each partition; db2glock runs only on the catalog partition.

db2hadrp, the high availability disaster recovery (HADR) primary server thread db2hadrs, the HADR standby server thread db2loggr, for manipulating log files to handle transaction processing and recovery db2loggw, for writing log records to the log files db2logmgr, for the log manager. Manages log files for a recoverable database. db2logts, for tracking which table spaces have log records in which log files. This information is recorded in the DB2TSCHG.HIS file in the database directory. db2pfchr, for buffer pool prefetchers db2pclnr, for buffer pool page cleaners

Database server threads and processes

The system controller (db2sysc on UNIX and db2syscs.exe on Windows operating systems) must exist if the database server is to function. The following threads and processes carry out a variety of tasks:

db2wdog, the watchdog on UNIX and Linux operating systems that handles abnormal terminationsdb2sysc, the main system controller EDU; it handles critical DB2 server events.db2licc, manages installed DB2 licenses

Q:-Explain Memory Model for db2?

Answer:

The DB2 UDB memory modelThe DB2 memory structure is illustrated in the Figure 1; it is the same across all platforms.

42

Page 43: Db2 Important questions to read

Figure 1. DB2 memory structure

DB2 breaks and manages memory in four different memory sets. They are:

Instance shared memory Database shared memory Application group shared memory Agent private memory

Each memory set consists of various memory pools (also referred to as heaps).

Instance shared memory

There is one instance shared memory set per DB2 instance. Instance shared memory is allocated when the database manager is started (db2start), and freed when the database manager is stopped (db2stop). It is used for instance level tasks such as monitoring, auditing and inter-node communication. The following database manager configuration (dbm cfg) parameters control the limits to the instance shared memory and its individual memory pools:

Instance memory (instance_memory) Monitor heap (mon_heap_sz): for monitoring use. Audit Buffer (audit_buf_sz): for use of the db2audit facility. Fast Communication buffers (fcm_num_buffers): for inter-node communication between partitions

and agents. Partitioned instances or instances with INTRA_PARALLEL set to ON.

The instance_memory parameter specifies the amount of memory reserved for instance management. The default value is AUTOMATIC. If instance_memory is set to AUTOMATIC, it is possible to determine its value using the following commands:

43

Page 44: Db2 Important questions to read

db2 attach to instance_name (where instance_name is the name of the instance) db2 get dbm cfg show detail

To find out the memory usage of an instance, use the DB2 memory tracker tool, db2mtrk. For example,

db2start db2mtrk -i –v

Database shared memory

There is one database shared memory set per database. Database shared memory is allocated when a database is activated or connected to for the first time. It is freed when database is deactivated (if it was activated) or the last connection disconnects. This memory is used by database level tasks such as backup/restore, locking, and SQL executions.

Figure 2 shows the various memory pools within the database shared memory set. The configuration parameters that control the sizes of these memory pools are shown in parenthesis. Figure 2. The DB2 database shared memory

The full green boxes mean the memory pools are allocated in full when the database is started. Otherwise, only partial amount of memory is allocated. For example, when a database is first started, only about 16 KB of memory is allocated to the utility heap, regardless of the value of util_heap_sz. When a database utility is started, such as backup, restore, export, import and load, then the full amount specified by util_heap_sz is allocated.

The main buffer pools

44

Page 45: Db2 Important questions to read

The database buffer pool(s) area is normally the largest component of the database shared memory. This is where all regular and index data is manipulated by DB2. A database must have at least one buffer pool, and can have a number of buffer pools depending on the workload characteristics, database page sizes used in the database, etc. For example, a table space with an 8KB page size can only use a buffer pool with page size of 8KB. he size of a buffer pool can be "extended" by using the EXTENDED STORAGE option in the CREATE BUFFERPOOL statement.

Application group shared memory

This shared memory set applies only to the following environments. (For other environments, this memory set does not exist.)

Multi-partitioned databases Non-partitioned databases for which intra-parallel processing is enabled Databases for which the connection concentrator is enabled.

Agent private memory

Each DB2 agent process needs to acquire memory to perform work. It will use memory to optimize, build and execute access plans on behalf of the application, to perform sorts, to record cursor information such as location and state, to gather statistics, etc. Agent private memory is allocated for a DB2 agent when the agent is assigned as the result of a connect request or a new SQL request in a parallel environment.

The number of agents is limited by the lower of:

The total of the maxappls database configuration parameter for all active databases, which specifies the maximum number of active applications permitted.

The value of the maxagents database manager configuration parameter, which specifies the maximum number of agents permitted.

The agent private memory set consist of the following memory pools. Their sizes are specified in the database configuration parameters enclosed in parenthesis:

Application Heap (applheapsz) Sort Heap (sortheap) Statement Heap (stmtheap) Statistics Heap (stat_heap_sz) Query Heap (query_heap_sz) Java Interpreter Heap (java_heap_sz) Agent Stack Size (agent_stack_sz) (Windows only)

Q: - Explain the steps for installing the Fix Packs for db2 in Linux.

Installing a fix pack to update existing DB2 database products (Linux and UNIX)

To install a fix pack:

1. For root installations, log on as root. For non-root installations, log on with the user ID that owns the non-root installation.

2. Change to the directory that contains the fix pack image.3. Launch the installation by issuing the installFixPack command. For example,

45

Page 46: Db2 Important questions to read

./installFixPack -b DB2DIR

where DB2DIR is the location of the DB2 database products that you want to update.

Q: - Explain the steps for installing db2 server in Linux / Windows?

Answer: Installing DB2 servers (Linux and UNIX)

Procedure

To start the DB2 Setup wizard:

1. Log on to the system as a user with root authority. 2. Change to the directory where the DB2 database product CD is mounted by entering the following

command: cd /cdrom where cdrom represents mount point of the DB2 database product CD.

3. If you downloaded the DB2 database product image, you must decompress and untar the product file.

a. Decompress the product file:

gzip -d product.tar.gz

where product is the name of the database product that you downloaded.

b. Untar the product file:

tar xvf product.tar

c. Change directory:

cd ./product/disk1

4. Enter the ./db2setup command from the directory where the product image resides to start the DB2 Setup wizard. For multiple CD installations, issue the db2setup command outside the mounted CD location with either a relative or absolute path name to ensure the DB2 database product CD can be unmounted as required.

5. The DB2 Setup Launchpad opens. From this window, you can view installation prerequisites and the release notes, or you can proceed directly to the installation. You may want to review the installation prerequisites and release notes for late-breaking information.

6. Click Install a Product and the Install a Product window will display the products available for installation.

46

Page 47: Db2 Important questions to read

Q: - Explain db2 Architecture.

Answer:-

DB2 architecture and process overview

The following figure shows a general overview of the architecture and processes for DB2 UDB.

On the client side, either local or remote applications, or both, are linked with the DB2 Universal Database(TM) client library. Local clients communicate using shared memory and semaphores; remote clients use a

47

Page 48: Db2 Important questions to read

protocol such as Named Pipes (NPIPE), TCP/IP, NetBIOS, or SNA. On the server side, activity is controlled by engine dispatchable units (EDUs). In all figures in this section, EDUs are shown as circles or groups of circles. EDUs are implemented as threads in a single process on Windows(R)-based platforms and as processes on UNIX(R). DB2 agents are the most common type of EDUs. These agents perform most of the SQL processing on behalf of applications. Prefetchers and page cleaners are other common EDUs. A set of subagents might be assigned to process the client application requests. Multiple subagents can be assigned if the machine where the server resides has multiple processors or is part of a partitioned database. For example, in a symmetric multiprocessing (SMP) environment, multiple SMP subagents can exploit the many processors.

Buffer pools are areas of database server memory where database pages of user table data, index data, and catalog data are temporarily moved and can be modified. Buffer pools are a key determinant of database performance because data can be accessed much faster from memory than from disk. If more of the data needed by applications is present in a buffer pool, less time is required to access the data than to find it on disk.

The configuration of the buffer pools, as well as prefetchers and page cleaner EDUs, controls how quickly data can be accessed and how readily available it is to applications.

Prefetchers retrieve data from disk and move it into the buffer pool before applications need the data.

Page cleaners move data from the buffer pool back out to disk. Page cleaners are background EDUs that are independent of the application agents. They look for pages from the buffer pool that are no longer needed and write the pages to disk. Page cleaners ensure that there is room in the buffer pool for the pages being retrieved by the prefetchers.

Q: What are the General steps for tuning query workloads in db2?

Answer: 1. Capture the SQL statement that you want to tune.2. Generate a visual representation of the access plan to see the choices that the optimizer

makes in accessing the data.3. Run the Statistics Advisor and follow its recommendations to ensure that the DB2 optimizer

always has the most current and the most needed statistics.4. Run the Index Advisor and follow its recommendations to ensure that the right indexes exist

to help avoid unnecessary table scans.5. Run the Query Advisor and follow its recommendations to find and revise structures in the

statement that are likely to cause the DB2 optimizer to choose a suboptimal access path.

Q: Explain db2advis.

48

Page 49: Db2 Important questions to read

Answer:

db2advis - DB2 Design Advisor Command

The DB2 Design Advisor advises users on the creation of materialized query tables (MQTs) and indexes, the repartitioning of tables, the conversion to multidimensional clustering (MDC) tables, and the deletion of unused objects. 9 The recommendations are based on one or more SQL statements provided by the user. 9 A group of related SQL statements is known as a workload.

Examples: In the following example, the utility connects to database PROTOTYPE, and recommends indexes for table ADDRESSES without any constraints on the solution:

db2advis -d prototype -s "select * from addresses awhere a.zip in ('93213', '98567', '93412')and (company like 'IBM%' or company like '%otus')"

2. In the following example, the utility connects to database PROTOTYPE, and recommends indexes that will not exceed 53MB for queries in table ADVISE_WORKLOAD. The workload name is equal to "production". The maximum allowable time for finding a solution is 20 minutes. db2advis -d prototype -w production -l 53 -t 20

Q: What is REORG? When is it used?

Answer: The REORG operation performs the following functions

Checks referential integrity if applicable for the target table and either deletes rows that violate it or invalidates any affected indexes. (Referential integrity is the relational property that each foreign-key value in a table exists as a primary-key value in the referenced table.)

Performs an internal reorganization of one or more of the indexes for the table (all types) to improve the internal storage of this information and thereby the performance when the index is used to access data.

A REORG operation is necessary in the following cases:

Whenever modifications to a database affect more than about 30 percent of the data

Q: What is RUNSTATS? When is it used?Answer: RUNSTATS updates statistics about the characteristics of a table and/or associated indexes, or statistical views. These characteristics include number of records, number of pages, and average record length. The optimizer uses these statistics when determining access paths to the data.For a table, this utility should be called when the table has had many updates, or after reorganizing the table. For a statistical view, this utility should be called when changes to underlying tables have substantially affected the rows returned by the view.

Examples

1. Collect statistics on the table only, on all columns without distribution statistics:

RUNSTATS ON TABLE db2user.employee

2. Collect statistics on the table only, on columns empid and empname with distribution statistics: 3. RUNSTATS ON TABLE db2user.employee

WITH DISTRIBUTION ON COLUMNS (empid, empname)

Q:-What is Data Server?

49

Page 50: Db2 Important questions to read

Answer: A data server refers to a computer where the DB2 database engine is installed. The DB2 engine is a full-function, robust database management system that includes optimized SQL support based on actual database usage and tools to help manage the data.IBM offers number data server products, including data server clients that can access all the various data servers.

Q:-What is Instance in db2?Answer: An instance is a logical database manager environment where you catalog databases and set configuration parameters. Depending on your needs, you can create more than one instance on the same physical server providing a unique database server environment for each instance.

You can use multiple instances to do the following:

Use one instance for a development environment and another instance for a production environment.

Tune an instance for a particular environment. Restrict access to sensitive information. Control the assignment of SYSADM, SYSCTRL, and SYSMAINT authority for each instance. Optimize the database manager configuration for each instance.

Q: What is tablespace? Explain Type of Tablespace.Answer: A table space is a storage structure containing tables, indexes, large objects, and long data. They are used to organize data in a database into logical storage groupings that relate to where data is stored on a system. Table spaces are stored in database partition groups.

Table spaces consist of one or more containers. A single table space can have several containers. A database must contain at least three table spaces:

A catalog table space / System Tablespace One or more user table spaces One or more temporary table spaces.

Catalog table spacesA catalog table space contains all of the system catalog tables for the database. This table space is called SYSCATSPACE, and it cannot be dropped.

User table spacesA user table space contains user-defined tables. By default, one user table space, USERSPACE1, is created. The page size of a table space determines the maximum row length or number of columns that you can have in a table.

Temporary table spacesA temporary table space contains temporary tables. Temporary table spaces can be system temporary table spaces or user temporary table spaces. System temporary table spaces hold temporary data required by the database manager while performing operations such as sorts or joins. These types of operations require extra space to process the results set. A database must have at least one system temporary table space; by default, one system temporary table space called TEMPSPACE1 is created at database creation.

Q: - What is Schema?

Answer: A schema is a collection of named objects; it provides a way to group those objects logically. A schema is also a name qualifier; it provides a way to use the same natural name for several objects, and to prevent ambiguous references to those objects.

50

Page 51: Db2 Important questions to read

For example, the schema names 'INTERNAL' and 'EXTERNAL' make it easy to distinguish two different SALES tables (INTERNAL.SALES, EXTERNAL.SALES).

Q: - What is Indexes? Explain Type of indexes.

Answer: An index is a set of pointers that are logically ordered by the values of one or more keys. The pointers can refer to rows in a table, blocks in an MDC table, XML data in an XML storage object, and so on.

Indexes are used to:

Improve performance. In most cases, access to data is faster with an index. Although an index cannot be created for a view, an index created for the table on which a view is based can sometimes improve the performance of operations on that view.

Ensure uniqueness. A table with a unique index cannot have rows with identical keys.

Types of indexes

There are different types of indexes that can be created for different purposes. For example, unique indexes enforce the constraint of uniqueness in your index keys; bidirectional indexes allow for scans in both the forward and reverse directions; clustered indexes can help improve the performance of queries that traverse the table in key order.

Unique and non-unique indexes

Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a table have identical key values.

When attempting to create a unique index for a table that already contains data, values in the column or columns that comprise the index are checked for uniqueness; if the table contains rows with duplicate key values, the index creation process fails. Once a unique index has been defined for a table, uniqueness is enforced whenever keys are added or changed within the index.

Bidirectional indexesBy default, bidirectional indexes allow scans in both the forward and reverse directions. The ALLOW REVERSE SCANS clause of the CREATE INDEX statement enables both forward and reverse index scans, that is, in the order defined at index creation time and in the opposite (or reverse) order.

Q: Define Trigger. Explain different type of trigger.

Answer: Triggers

A trigger defines a set of actions that are performed in response to an insert, update, or delete operation on a specified table. When such an SQL operation is executed, the trigger is said to have been activated. Triggers are optional and are defined using the CREATE TRIGGER statement.

Triggers can be used, along with referential constraints and check constraints, to enforce data integrity rules. Triggers can also be used to cause updates to other tables, automatically generate or transform values for inserted or updated rows, or invoke functions to perform tasks such as issuing alerts.

The following types of triggers are supported:

51

Page 52: Db2 Important questions to read

BEFORE triggersRun before an update, or insert. Values that are being updated or inserted can be modified before the database is actually modified.

BEFORE DELETE triggers

Run before a delete. Checks values (a raises an error, if necessary).

AFTER triggersRun after an update, insert, or delete. You can use triggers that run after an update or insert in several ways:

To update data in other tables. This capability is useful for maintaining relationships between data or in keeping audit trail information.

To check against other data in the table or in other tables. This capability is useful to ensure data integrity when referential integrity constraints aren't appropriate, or when table check constraints limit checking to the current table only.

To run non-database operations coded in user-defined functions. This capability is useful when issuing alerts or to update information outside the database.

INSTEAD OF triggers

Describe how to perform insert, update, and delete operations against views that are too complex to support these operations natively. They allow applications to use a view as the sole interface for all SQL operations (insert, delete, update and select).

BEFORE triggers By using triggers that run before an update or insert, values that are being updated or inserted can be modified before the database is actually modified. These can be used to transform input from the application (user view of the data) to an internal database format where desired.

AFTER triggers Triggers that run after an update, insert, or delete can be used in several ways.

INSTEAD OF triggers INSTEAD OF triggers describe how to perform insert, update, and delete operations against complex views. INSTEAD OF triggers allow applications to use a view as the sole interface for all SQL operations (insert, delete, update and select).

Q: - What is View?

Answer: Views:-A view is an efficient way of representing data without the need to maintain it. A view is not an actual table and requires no permanent storage. A "virtual table" is created and used. You can use views to control access to sensitive data, because views allow multiple users to see different presentations of the same data. For example, several users might be accessing a table of data about employees. A manager sees data about his or her employees but not employees in another department. A recruitment officer sees the hire dates of all employees, but not their salaries; a financial officer sees the salaries, but not the hire dates. Each of these users works with a view derived from the table. Each view appears to be a table and has its own name.A view can become inoperative (for example, if the table is dropped); if this occurs, the view is no longer available for SQL operations. A sample CREATE VIEW statement is shown below.

52

Page 53: Db2 Important questions to read

CREATE VIEW EMP_VIEW1 (EMPID, EMPNAME, DEPTNO, JOBTITLE, HIREDATE) AS SELECT ID, NAME, DEPT, JOB, HIREDATE FROM EMPLOYEE WHERE DEPT=10;

Q: What happens if Load is interrupted in between the operation?Answer: When the load operation begins, the target table is placed in the Load in Progress table state. In the event of a failure, the table state will change to Load Pending. To remove the table from this state, you can issue a LOAD TERMINATE to roll back the operation, issue a LOAD REPLACE to reload the entire table, or issue a LOAD RESTART.

Typically, restarting the load operation is the best choice in this situation. It saves time because the load utility restarts the load operation from the last successfully reached point in its progress, rather than from the beginning of the operation. Where exactly the operation restarts from depends upon the parameters specified in the original command. If the SAVECOUNT option was specified, and the previous load operation failed in the load phase, the load operation restarts at the last consistency point it reached. Otherwise, the load operation restarts at the beginning of the last phase successfully reached (the load, build, or delete phase).

If the load operation resulting from the following command fails,

LOAD FROM filename OF file type SAVECOUNT n MESSAGES message file load method INTO target_tablename

you would restart it by replacing the specified load method (load_method) with the RESTART method:

LOAD FROM file_name OF file_type SAVECOUNT n MESSAGES message_file RESTARTINTO target_tablename

Q: - What is the difference between “End of Logs and Complete” & “ End of Backup and stop”?Answer: - End of Logs and Complete Rolls forward to the end of the logs, which means that all archived and active logs are traversed. At the end, DB2 completes the roll forward operation and brings the database from roll forward pending state to a usable state.

“End of Backup and stop” instructs DB2 to determine the minimum PIT that database sample is allowed to roll forward to, and then will roll forward to that PIT and bring the database from roll forward pending state to a usable state.

Q:-How do we get the time when the database has been created?Answer: - I usually go by the time the system catalog tables got created

(db2 list tables for schema SYSIBM)

Note: - sysibm.sysversions gets updated during upgrade / migration

The DB2 Processes

db2ckpwd Checks user IDs and passwords on the DB2 server. Since DB2 relies on operating system-level authentication, this thread verifies the user ID and password when a user or application connects to a database on the server. This authentication will occur when authentication is set to SERVER or when a connection is made from a nonsecure operatingsystem.

53

Page 54: Db2 Important questions to read

Log File States

There are three log file states: active, online archive, and offline archive.

Active Logs

A log is considered active if any of the following applies:

• It contains transactions that have not yet been committed or rolled back.• It contains transactions that have been committed but whose changes have not yet been written to the database disk (externalized).• It contains transactions that have been rolled back but whose changes have been written to the database disk (externalized).

Question: What are the different approach you user for tuning the Query?Answer: -

(1) Create a primary key on each table you create.(2) Create an index

Question: - Which utilities are compatible with running an online backup?

Answer: - The following utilities are compatible with online backup:

EXPORT

ONLINE INSPECT

54

Page 55: Db2 Important questions to read

Question: - Which utilities are not compatible with running an online backup?

Answer:- The following utilities are not compatible with online backup:

REORG TABLE RESTORE

ROLLFORWARD ONLINE BACKUP OFFLINE LOAD

SET WRITE

Question: - I had DB2 V 8.2 on Windows after which I uninstalled it and then installed DB2 V 9. When I try to restore the backup, I get SQL1005N. What could be the reason?

Answer: - An instance can be upgraded from DB2 V 8 to DB2 V 9 directly, instead of uninstalling DB2 8.2 first, then install DB2 V 9 (and then try to get the previous databases back). For the same scenario on windows, you can install DB2 V 9 right on top of DB2 8. Choose the "Migrate" option on the install Launchpad if it is a GUI install.

However, if DB2 V 8 is uninstalled first and DB2 V 9 is installed, try running the following command:

db2 list db directory

If this is empty, run:

db2 list db directory on <drive name/pathname>

This should list all the databases present in the system before you uninstalled DB2.

Catalog the database again and run migrate db command. This should let you connect to the databases and access the data.

Note: Uninstalling or dropping the instance does not drop the database and their directories.

Question: - What are the uses of DB2 Optimizer?

1. It processes SQL statements.

2. It helps to select the access path3.

Question: - Define Data page.

Answer: - Data page can be considered as a unit that is capable of retrieving data from the database. The database from which the data can be retrieved is in the form of 4 kilobytes or 32 kilobytes. The form in which data is retrieved depends on the way the table is defined inside the database. Data page also contains information regarding the catalog or user that is part of the database.

55

Page 56: Db2 Important questions to read

Question: - Mention the different locking levels that are available in DB2.

Answer: - TABLE, PAGE and TABLESPACE

Question: - What are the advantages of using a PACKAGE?

Answer: - The advantages of packages are

1. Modularity: All the procedures and functions belong to a particular module of an application can be encapsulated in a package. 2. Easy to design the application: The package body and package specification can be coded and compiled separately without its body. Stored procedures are compiled and executed by qualifying the package names3. Hiding Information: The programming elements declared in the specification of the package is public. The package body elements are declared as private, i.e., they are invisible to the application. Hence they are secured4. Added Functionality: Public variables and cursors are persisted for a session, which enables the sharing of data by all programs of the calling environment5. Better Performance: Packaged sub programs are invoked for the first time by loading the entire package into the memory. Disk I/O operations are not needed for calling related sub programs in the package later.6. Overloading: Multiple programs can be placed in the same package with different number of parameters or types or parameters

Memory Structure in DB2

There are three main Memory Structure in db2

1. Instance Shared Memory

These are the processes that are initialized when an instance is started. Some of the main processes are:

a) DB2 Daemon Spawer (db2gds) –Global Daemon Process started at each Instance.b) DB2 System Controller (sysc) – Main db2 Process.c) DB2 Watch Dog –Parent process for all other process.d) DB2 Format Log (db2fmtlg) – Pre allocates log files in the Log.

2. Database Shared Memory

These are the processes that are initialized when a connection is made to a database. Some of the main processes are:

a) DB2 Log Reader (db2logr) - This Process reads Log file during Rollforward, Restart Recovery & Rollback.

b) DB2 Log Writer (db2logw) – Flushes Log from log buffer to the transaction log files on disk.

c) DB2 Page Cleaner (db2pclr) – This Process cleans the Buffer pool pages.d) DB2 Prefetchers (db2pfchr) – Retrieves pages from disk and places it into the

buffer pool before it is needed.e) DB2 Deadlock Detector (db2dlock) – Deadlock detector process.

56

Page 57: Db2 Important questions to read

3. Application Shared memory

Each Application connecting to the Database would have its share of application level background process associated with it. Some of the main processes are:

a) DB2 Communication Manager (db2ipccm) – Inter Process Communication for each connected locally client.

b) DB2 TCP Manager (db2tcpcm) – TCP Communication manager process for remote client using TCP/IP.

c) DB2 Coordinating Agent (db2agent) – Process that handles all request on behalf of an application.

d) DB2 Sub Agent (db2agenta) – Idle Subagente) Active Sub Agent (db2agentp)

Question: - If I have one instance of DB2 on version 8.2, can I use the same instance on DB2 9.5?

Answer: - No, you cannot share the instances across various DB2 versions. You can upgrade from DB2 V 8.2 to later releases but cannot share an instance between the releases without an upgrade.

Question: - I had DB2 V 8.2 on Windows after which I uninstalled it and then installed DB2 V 9. When I try to restore the backup, I get SQL1005N. What could be the reason?

Answer: - An instance can be upgraded from DB2 V 8 to DB2 V 9 directly, instead of uninstalling DB2 8.2 first, then install DB2 V 9 (and then try to get the previous databases back). For the same scenario on windows, you can install DB2 V 9 right on top of DB2 8. Choose the "Migrate" option on the install launchpad if it is a GUI install.

However, if DB2 V 8 is uninstalled first and DB2 V 9 is installed, try running the following command:

db2 list db directory

if this is empty, run:

db2 list db directory on <drive name/pathname>

this should list all the databases present in the system before you uninstalled DB2.

Catalog the database again and run migrate db command. This should let you connect to the databases and access the data.

Note: Uninstalling or dropping the instance does not drop the database and their directories.

Question: - How do I verify what DB2 Product I have installed on Windows/UNIX/Linux? And how do I find out the exact DB2 version I am running?

Answer: - For finding out the exact DB2 version, run 'db2level' from a DB2 Command Window on Windows machines and from a normal UNIX prompt on UNIX. The 'db2level' output will tell you the exact DB2 Fix Pack you are running, the bit level DB2 is running as, whether or not any special builds are being used, and other information DB2 support may require.

57

Page 58: Db2 Important questions to read

Windows Example:

C :> db2level

UNIX Example:

$ db2level

Question: - During instance creation DB2 creates several directories and files with permission that are open to all users. Can I manually change such file permission to not allow access to all users?

Answer: - During instance creation time DB2 automatically creates directories and files for its use. Permission of such files and directories should not be changed manually. Any attempt to manually change these could result in unexpected file access errors. Hence it’s not recommended to change permission on files/directories created by DB2.

Question: - Can you have more than one DB2 instance created under the same DB2 installation (DB2 copy)?

Answer: - Yes, you can.

Linux, Unix -- It is possible to have more than one instance on a Linux or UNIX operating system if the DB2® product was installed with root privileges. Each instance can run simultaneously, though they are independent of the other.

Windows -- It is possible to have more than one instance and you can run multiple instances concurrently on windows. Each instance of the database manager maintains its own databases and has its own database manager configuration parameters.

You can also have multiple databases created under each instance on all OS platforms.

Question: - Which utilities are compatible with running an online backup?

Answer: - The following utilities are compatible with online backup:

EXPORT ONLINE INSPECT

The following utilities are compatible with online backup only under certain circumstances:

ONLINE CREATE INDEX: In SMS mode, online index create and online backup will not be compatible due to the ALTER TABLE lock. Where online index create acquires it in exclusive mode while online backup acquires it in share.

In DMS mode, online index create and online backup can run concurrently in most cases. There is a possibility if you have a large number of indexes that the online index create will internally acquire an online backup lock that will conflict with any concurrent online backup.

58

Page 59: Db2 Important questions to read

ONLINE INDEX REORGIn SMS mode, online index reorganization and online backup are incompatible in the same way that online index create and online backup are incompatible.

In DMS mode, online index reorganization and online backup can run concurrently in most cases. The only case where they are not compatible is the same case that is described above for online index create and online backup.

IMPORTThe import utility is compatible with online backup except when the IMPORT command is issued with the REPLACE option, in which case, import gets a Z lock on the table and prevents an online backup from running concurrently.

The following utilities are not compatible with online backup:

REORG TABLE RESTORE ROLLFORWARD ONLINE DATABASE BACKUP OFFLINE LOAD SET WRITE

Question: - Can I backup a SMS tablespace and restore it into a DMS tablespace or vice versa?

Answer: - we can backup a SMS tablespace and restore into a SMS tablespace ONLY. We cannot restore it into a DMS tablespace or vice versa. Also you may want to note that you can add a container to a DMS tablespace but not to a SMS tablespace.

Question: - I have a DB2 backup of a database on UNIX platform, can I use this image to restore into a Windows platform, or vice versa?

Answer: - No. You can backup/restore DB2 databases from and to the same Operating System only. Cross-platform backup/restore is not possible and is not supported. This is due to complications with the big-endian and little-endian byte orders on Windows and UNIX Operating Systems. Between little-endian platforms such as Linux and Windows, it is not supported due since the paths in various Config files would be different between the platforms.

Question:-Can you restore a database from a backup image taken on a 32 bit level into a 64 bit level or vice versa?

Answer: - You can restore a database from a backup image taken on a 32 bit level into a 64 bit level, but NOT vice versa.

32 bit backup ==> 64 bit restore ==> YES 64 bit backup ==> 32 bit restore ==> NO

Question: - I have taken a backup of database A and want to restore this backup on some different path. Can I do that in DB2?

59

Page 60: Db2 Important questions to read

Answer: Yes, you can. With DB2 you can "redirect restore" the DB.

Let Us explain that through example given below:-

The source instance for the Windows example is called PROD. The target instance is called MYINST. The existing database on PROD that is going to be restored (created) on MYINST is called MOVIES. The MOVIES database is located on drive D.

The source instance for the UNIX example is called prod. The target instance is called myinst.

1. Create a full database backup image of the MOVIES database. Before issuing the BACKUP DATABASE command on Windows, ensure that the current instance is PROD:

2. set DB2INSTANCE=PROD 3. db2start

db2 backup db movies

The timestamp for this image is 20030909143225. On Windows, the image is located in D:\MOVIES.0\PROD\NODE0000\CATN0000\20030909. DB2 creates this subdirectory tree off the directory from which the BACKUP DATABASE command is issued. In the UNIX example, the image is located in /home/prod.

On Windows, the subdirectory names represent the following:

<database_alias.backup_type>\<instance_name>\<node_number>\ <catalog_node_number>\<date>

Inside this subdirectory tree, there will be a file (143225.0) representing the actual backup image. The file name represents the time at which the backup was taken.

Note: If you were relocating the backup image to another machine, create the above path on the target machine (substituting the appropriate target instance name for PROD) and copy the backup image (in this case 143225.0) to that directory. You can also use compression tools to package the backup image while maintaining the directory tree for transport.

In the UNIX example, the actual backup image is named as follows:

MOVIES.0.prod.NODE0000.CATN0000.20030909143225.001

The components of that name represent the following:

<database_alias>.<backup_type>.<instance_name>.<node_number>. <catalog_node_number>.<timestamp>.<sequence_number>

4. On Windows, start MYINST and then invoke the first step of a redirected restore operation.5. set DB2INSTANCE=MYINST 6. db2start

db2 restore db movies from d taken at 20030909143225 redirect

The FROM parameter must be specified if the RESTORE DATABASE command is invoked from a directory other than the one that contains the backup image.

60

Page 61: Db2 Important questions to read

On the UNIX-based system, issue the following command while logged in as myinst:

db2 restore db movies from /home/prod taken at 20030909143225 redirect

7. Define new table space containers for the three default table spaces that are associated with the restored database (SYSCATSPACE, TEMPSPACE1, and USERSPACE1). On Windows, issue:

8. db2 set tablespace containers for 0 using (path 'd:\tsc_movies\ts0con1') 9. db2 set tablespace containers for 1 using (path 'd:\tsc_movies\ts1con1')

db2 set tablespace containers for 2 using (path 'd:\tsc_movies\ts2con1')

On the UNIX-based system, issue:

db2 "set tablespace containers for 0 using (path 'ts0con1')" db2 "set tablespace containers for 1 using (path 'ts1con1')" db2 "set tablespace containers for 2 using (path 'ts2con1')"

You can use the LIST TABLESPACES SHOW DETAIL command to get information about all of the table spaces in the source database; this will help you ensure that containers have been set for all of the table spaces in the target database.

10. Complete the redirected restore operation:

db2 restore db movies continue

11. Verify that the restored database has been cataloged properly, and that the table space containers that you have defined for it are in fact associated with the restored database:

12. db2 list db directory 13. db2 connect to movies 14. db2 list tablespace containers for 0 15. db2 list tablespace containers for 1 16. db2 list tablespace containers for 2 17. db2 connect reset 18. db2 terminate

db2stop

Question:-Can I include logs while taking a backup? OR I have an online database backup image that was taken with the include logs option. How can I restore and only apply the logs stored in this backup image?

Answer: - While taking backup you can specify the option INCLUDE LOGS. When you specify this option, the backup utility will truncate the currently active log file and copy the necessary set of log extents into the backup image. You will need to create an empty directory and extract the log to this directory during the restore. Then, issue the rollforward command and point DB2 to this directory using the overflow log path option. Here is an example:

Note: - Including log files with a backup image

When performing an online backup operation, you can specify that the log 7 files required to restore and recover a database are included in the backup 7 image. 7 This means that if you need to ship backup images to a disaster recovery site, you do not 7 have to send the log files separately or package them together yourself. 7 Further, you do not have to decide which log

61

Page 62: Db2 Important questions to read

files 7 are required to guarantee the consistency of an online backup. This provides 7 some protection against the deletion of log files required for successful 7 recovery.

To make use of this feature specify the INCLUDE LOGS option of the 7 BACKUP DATABASE command. 7 When you specify this option, the backup utility will truncate the currently 7 active log file and copy the necessary set of log extents into the backup image.

To restore the log files from a backup image, use the LOGTARGET 7 option of the RESTORE DATABASE command and specify a fully qualified path that 7 exists on the DB2(R) server. The restore database utility will then write the log 7 files from the image to the target path. 7 If a log file with the same name already exists in the target path, the restore 7 operation will fail and an error will be returned. If the LOGTARGET 7 option is not specified, no log files will be restored from the backup image.

If the LOGTARGET option is specified and the backup image does not include any log 7 files, an error will be returned before an attempt is made to restore any 7 table space data. 7 The restore operation will also fail if an invalid or read-only path is 7 specified. 7 During a database or table space restore where the LOGTARGET option is specified, if one 7 or more log files cannot be extracted, the restore operation fails and 7 an error is returned.

You can also choose to restore only the log files saved in the backup image. 7 To do this, specify the LOGS option with the LOGTARGET option of the RESTORE DATABASE 7 command. If the restore operation encounters any problems when restoring log files in 7 this mode, the restore operation fails and an error is returned.

During an automatic incremental restore operation, only the logs included in the target 7 image of the restore operation will be retrieved from the backup image. Any logs 7 that are included in intermediate images referenced during the incremental 7 restore process will not be extracted from those backup images. 7 During a manual incremental restore, if you specify a log target 7 directory when restoring 7 a backup image that includes log files, the log files in that backup image will 7 be restored.

DB2 backup db test1 online include logs

Backup successful. The timestamp for this backup image is: 20080318084101

mkdir rest_logs

DB2 restore db test1 logtarget /home/bkogan/rest_logs

SQL2539W Warning! Restoring to an existing database that is the same as the backup image database. The database files will be deleted. Do you want to continue? (y/n) y DB20000I the RESTORE DATABASE command completed successfully.

DB2 "rollforward db test1 to end of logs and stop overflow log path (/home/bkogan/rest_logs) noretreive"

62

Page 63: Db2 Important questions to read

Rollforward Status Input database alias = test1 Number of nodes have returned status = 1 Node number = 0 Rollforward status = not pending Next log file to be read = Log files processed = S0000018.LOG - S0000018.LOG Last committed transaction = 2008-03-18-12.41.14.000000 DB20000I the ROLLFORWARD command completed successfully.

Question: - In DB2 V9x what is the default path for the DB2 backups when automatic backup is enabled?Answer:-

In Windows: C:\DB2\NODE0000\SQL0000x\DB2AUTOBACKUPS on the windows platform and

UNIX/LINUX: /path/to/db/NODE0000/SQL0000x/DB2AUTOBACKUPS

Question: - Which utilities are compatible while running online backups?

Answer: - The following utilities are compatible with online backup:

EXPORT

ONLINE INSPECT

The following utilities are compatible with online backup only under certain circumstances:

ONLINE CREATE INDEX

In SMS mode, online index create and online backup will not be compatible due to the ALTER TABLE lock. Where online index create acquires it in exclusive mode while online backup acquires it in share.

In DMS mode, online index create and online backup can run concurrently in most cases. There is a possibility if you have a large number of indexes that the online index create will internally acquire an online backup lock that will conflict with any concurrent online backup.

ONLINE INDEX REORGIn SMS mode, online index reorganization and online backup are incompatible in the same way that online index create and online backup are incompatible.

In DMS mode, online index reorganization and online backup can run concurrently in most cases. The only case where they are not compatible is the same case that is described above for online index create and online backup.

In addition, online index reorganization quiesces the table before the switch phase and gets a Z lock, which prevents an online backup.

IMPORTThe import utility is compatible with online backup except when the IMPORT command is issued with the REPLACE option, in which case, import gets a Z lock on the table and prevents an online backup from running concurrently.

63

Page 64: Db2 Important questions to read

RUNSTATSRunstats is compatible with online backup except when the system catalog table space is a SMS table space. This is because if the SYSIBM.SYSTABLES resides in a SMS table space, then runstats and online backup will hold incompatible table lock on the table, causing lock waits.

Question: - Default Path of the database??

Answer: - The root directory of this hierarchical tree is assigned the name of the instance the database is associated with. This directory will contain a subdirectory that has been assigned a name corresponding to the partition's node. If the database is a partitioned database, this directory will be named NODExxxx, where xxxx is the unique node number that has been assigned to the partition; if the database is a nonpartitioned database, this directory will be named NODE0000. This node-name directory, in turn, will contain one subdirectory for each database that has been created, along with one subdirectory that contains the containers that are used to hold the database's data.

The name assigned to the subdirectory that holds the containers that are used to house the database's data is the same as that specified for the database; the name assigned to the subdirectory that contains the base files for the database corresponds to the database token that is assigned to the database during the creation process. Thus the subdirectory for the first database created will be named SQL00001, the subdirectory for the second database will be named SQL00002, and so on. Figure 4-2 illustrates how this directory hierarchy typically looks in a nonpartitioned database environment.

64