SYSTABLES SYSIBM Information about all tables in the database
SYSINDEXES SYSIBM Information about the indexes on all tables SYSVIEWS SYSIBM Information on all views in the database select name, creator from sysibm.systables where creator = 'FUZZY' • Data Definition Language ( DDL ) Create, Alter and Drop • Data Manipulation Language ( DML ) Select, Insert, Update and Delete • Data Control Language ( DCL ) Grant and Revoke All the tables are created in table spaces. Table spaces reside on ESDS or LDS Creation of temporary tables: 1) CREATE GLOBAL TEMPORARY TABLE TEMPPROD (SERIAL CHAR(8) NOT NULL, DESCRIPTION VARCHAR(60) NOT NULL, MFGCOST DECIMAL(8,2), MFGDEPT CHAR(3), MARKUP SMALLINT, SALESDEPT CHAR(3), CURDATE DATE NOT NULL); 2) CREATE GLOBAL TEMPORARY TABLE TEMPPROD LIKE PROD; 3) DROP TABLE TEMPPROD; *********** IMP ********* the temporary table is created only when when some SQL operation is done on it like( select,update) 4) one more way to create a temporary table is to use the command declare global temporary table name, for this a temporary DB and temporary TS have to be created as follows: CREATE DATABASE DTTDB AS TEMP; CREATE TABLESPACE DTTTS IN DTTDB SEGSIZE 4; The second kind of temporary table exists only until the session exists Handling NULL values: UPDATE IBMGRP.MEMBERDETAILS SET LASTNAME = 'NULL' WHERE LASTNAME IS NULL; VIEWS • It is a logical derivation of a table from other table/tables. A View does not exist in its own right. • They provide a certain amount if logical independence • They allow the same data to be seen by different users in different ways • In DB2 a view that is to accept a update must be derived from a single base table Aliases • Mean ‘another name’ for the table. • Aliases are used basically for accessing remote tables (in distributed data processing), which add a location prefix to their names. • Using aliases creates a shorter name. Synonym • Also means another name for the table, but is private to the user who created it. Syntax: CREATE VIEW <Viewname> (<columns>) AS Subquery (Subquery SELECT FROM other Table(s)) CREATE ALIAS <Aliasname> FOR <Tablename> CREATE SYNONYM <Synonymname> FOR <Tablename> CREATE VIEW IBMGRP.VIEW1 AS SELECT FIRSTNAME, LASTNAME FROM IBMGRP.MEMBERDETAILS; UPDATE IBMGRP.VIEW1 SET LASTNAME = '1NULL' WHERE LASTNAME = 'NULL'; ******* When a VIEW is updated the table is also updated ******* Embedded SQL • It is like the file I/O • Normally the embedded SQL statements contain the host variables coded with the INTO clause of the SELECT statement. • They are delimited with EXEC SQL ...... END EXEC. • E.g. EXEC SQL SELECT Empno, Empname INTO :Hempno, :Hempname FROM EMPLOYEE WHERE empno = 1001 END EXEC. CURSOR: • Used when a large number of rows are to be Selected • Can be likened to a pointer • Can be used for modifying data using ‘FOR UPDATE OF’ clause The four (4) Cursor control statements are • Declare : name assigned for a particular SQL statement • Open : readies the cursor for row retrieval; sometimes builds the result table. However it does not assign values to the host variables • Fetch : returns data from the results table one row at a time and assigns the value to specified host variables • Close : releases all resources used by the cursor DECLARE : EXEC SQL DECLARE EMPCUR CURSOR FOR SELECT Empno, Empname,Dept, Job FROM EMP WHERE Dept = 'D11' FOR UPDATE OF Job ENDEXEC. OPEN: EXEC SQL OPEN EMPCUR ENDEXEC. FETCH: EXEC SQL FETCH EMPCUR INTO :Empno, :Empname, :Dept, :Job ENDEXEC. CLOSE E.g. For the Close statement EXEC SQL CLOSE EMPCUR END EXEC. When you update a row or delete a row from table using cursor, Data integrity is maintained because the current row is locked for usage. UPDATE E.g. For the Update statement using cursors EXEC SQL UPDATE EMP Set Job = :Newjob WHERE current of EMPCUR END EXEC. DELETE E.g. For the Delete statement using cursors EXEC SQL DELETE FROM EMP WHERE current of EMPCUR END EXEC. Program preparation: PRECOMPILE ---> separates all the DB2 code and writes it in a DBRM and Modified source code and DBRM are tagged with • Searches all the SQL statements and DB2 related INCLUDE members and comments out every SQL statement in the program • The SQL statements are replaced by a CALL to the DB2 runtime interface module, along with parameters. • All SQL statements are extracted and put in a Database Request Module (DBRM) • Places a timestamp in the modified source and the DBRM so that these are tied. If there is a mismatch in this a runtime error of ‘818‘, timestamp mismatch occurs • All DB2 related INCLUDE statements must be placed between EXEC SQL & END EXEC keywords for the precompiler to recognize them COMPILE and LINK: > Only COBOL code is compiled • Modified precompiler COBOL output is compiled • Compiled source is link edited to an executable load module • Appropriate DB2 host language interface module should also be included in the link edit step(i.e DSNELI) Coding SQL in COBOL: Declaring TABLE/VIEWS is COBOL program is not mandatory but it helps documentation. Also if the SQL statements do not match with the table declarations, the DBRM when binded will though warning messages One way to declare a table or view is to code a DECLARE statement in the WORKINGSTORAGE SECTION or LINKAGE SECTION within the DATA DIVISION of your COBOL program. Specify the name of the table and list each column and its data type. When you declare a table or view, you specify DECLARE tablename TABLE regardless of whether the tablename refers to a table or a view. For example, the DECLARE TABLE statement for the DSN8810.DEPT table looks like the following DECLARE statement in COBOL: EXEC SQL DECLARE DSN8810.DEPT TABLE (DEPTNO CHAR(3) NOT NULL, DEPTNAME VARCHAR(36) NOT NULL, MGRNO CHAR(6) , ADMRDEPT CHAR(3) NOT NULL, LOCATION CHAR(16) ) ENDEXEC. Usage of HOST VARIABLEs: EXEC SQL SELECT LASTNAME, WORKDEPT INTO :CBLNAME, :CBLDEPT FROM DSN8810.EMP FETCH FIRST 1 ROW ONLY ENDEXEC. Using both table column and host variable in the same SQL statement: MOVE 4476 TO RAISE. MOVE ’000220’ TO PERSON. EXEC SQL SELECT EMPNO, LASTNAME, SALARY, :RAISE, SALARY + :RAISE INTO :EMPNUM, :PERSONNAME, :EMPSAL, :EMPRAISE, :EMPTTL FROM DSN8810.EMP WHERE EMPNO = :PERSON ENDEXEC. The following results have column headings that represent the names of the host variables: EMPNUM PERSONNAME EMPSAL EMPRAISE EMPTTL ======= =========== ======= ========= ======= 000220 LUTZ 29840 4476 34316 Updating multiple rows: MOVE ’D11’ TO DEPTID. EXEC SQL UPDATE DSN8810.EMP SET SALARY = 1.10 * SALARY WHERE WORKDEPT = :DEPTID END-EXEC. Inserting Data : EXEC SQL INSERT INTO DSN8810.ACT VALUES (:HV-ACTNO, :HV-ACTKWD, :HV-ACTDESC) END-EXEC. Update a row with null value: EXEC SQL UPDATE DSN8810.EMP SET PHONENO = :NEWPHONE:PHONEIND WHERE EMPNO = :EMPID END-EXEC. Null indicator should be: -1 if data is null 0 if data is notnull +ve if data is truncated when passed to the host variable Move the whole row into a group that has the host variables as elementary items If you want to avoid listing host variables, you can substitute the name of a structure, say :PEMP, that contains :EMPNO, :FIRSTNME, :MIDINIT, :LASTNAME, and :WORKDEPT. The example then reads: EXEC SQL SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT INTO :PEMP FROM DSN8810.VEMP WHERE EMPNO = :EMPID END-EXEC. *************** Usage of cursors ********************* --> Each and every cursor is associated with a table, multiple tables require multiple cursors to access them --> If SQLCODE = 100 means that end-of-table is reached --> Do not mention the host variables with the SELECT clause when you have to return multiple rows. So for this reason the FETCH statement is important when CURSOR's are used. Only after FETCH statement is executed with host variables only then the rows are retrieved into the table. Create Cursor: EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, SALARY FROM DSN8810.EMP X WHERE EXISTS (SELECT * FROM DSN8810.PROJ Y WHERE X.EMPNO=Y.RESPEMP AND Y.PROJNO=:GOODPROJ) FOR UPDATE OF SALARY; Fetch rows: EXEC SQL FETCH C1 INTO :HV-EMPNO, :HV-FIRSTNME, :HV-MIDINIT, :HV-LASTNAME, :HV-SALARY :IND-SALARY END-EXEC. Positioned Update: If FOR UPDATE is mentioned in the CURSOR DECLARE statement then positioned update can be done as follows; EXEC SQL UPDATE DSN8810.EMP SET SALARY = 50000 WHERE CURRENT OF C1 END-EXEC. Positioned DELETE: EXEC SQL DELETE FROM DSN8810.EMP WHERE CURRENT OF C1 END-EXEC. Cursor CLOSE: EXEC SQL CLOSE C1 END-EXEC. ********* ---> A cursor created with rowset positioning can fetch multiple rows at a time: EXEC SQL DECLARE C1 CURSOR WITH ROWSET POSITIONING FOR SELECT EMPNO, LASTNAME, SALARY FROM DSN8810.EMP END-EXEC. EXEC SQL FETCH NEXT ROWSET FROM C1 FOR 20 ROWS INTO :HVA-EMPNO, :HVA-LASTNAME, :HVA-SALARY :INDA-SALARY END-EXEC. With rowset positioning a particular row can be updated/deleted, let say EXEC SQL UPDATE DSN8810.EMP SET SALARY = 50000 FOR CURSOR C1 FOR ROW 5 OF ROWSET END-EXEC. Preparing embedded SQL statements in COBOL: 1) Mandatory to declare SQL communication area: A COBOL program that contains SQL statements must include one or both of the following host variables: a) An SQLCODE variable declared as PIC S9(9) BINARY, PIC S9(9) COMP-4, PIC S9(9) COMP-5, or PICTURE S9(9) COMP b) An SQLSTATE variable declared as PICTURE X(5) The above declarations can go in WORKING STORAGE SECTION OR DATA DIVISION Alternatively, you can include an SQLCA, which contains the SQLCODE and SQLSTATE variables. EXEC SQL INCLUDE SQLCA END-EXEC. CASE statements: Example 1 (simple-when-clause): Assume that in the EMPLOYEE table the first character of a department number represents the division in the organization. Use a CASE expression to list the full name of the division to which each employee belongs. SELECT EMPNO, LASTNAME, CASE SUBSTR(WORKDEPT,1,1) WHEN 'A' THEN 'Administration' WHEN 'B' THEN 'Human Resources' WHEN 'C' THEN 'Design' WHEN 'D' THEN 'Operations' END FROM EMPLOYEE; Example 2 (searched-when-clause): You can also use a CASE expression to avoid "division by zero" errors. From the EMPLOYEE table, find all employees who earn more than 25 percent of their income from commission, but who are not fully paid on commission: SELECT EMPNO, WORKDEPT, SALARY+COMM FROM EMPLOYEE WHERE (CASE WHEN SALARY=0 THEN 0 ELSE COMM/(SALARY+COMM) END) > 0.25; Example 3 (searched-when-clause): You can use a CASE expression to avoid "division by zero" errors in another way. The following queries show an accumulation or summing operation. In the first query, DB2® performs the division before performing the CASE statement and an error occurs along with the results. SELECT REF_ID,PAYMT_PAST_DUE_CT, CASE WHEN PAYMT_PAST_DUE_CT=0 THEN 0 WHEN PAYMT_PAST_DUE_CT>0 THEN SUM(BAL_AMT/PAYMT_PAST_DUE_CT) END FROM PAY_TABLE GROUP BY REF_ID,PAYMT_PAST_DUE_CT; However, if the CASE expression is included in the SUM aggregate function, the CASE expression would prevent the errors. In the following query, the CASE expression screens out the unwanted division because the CASE operation is performed before the division. SELECT REF_ID,PAYMT_PAST_DUE_CT, SUM(CASE WHEN PAYMT_PAST_DUE_CT=0 THEN 0 WHEN PAYMT_PAST_DUE_CT>0 THEN BAL_AMT/PAYMT_PAST_DUE_CT END) FROM PAY_TABLE GROUP BY REF_ID,PAYMT_PAST_DUE_CT; Example 4: This example shows how to group the results of a query by a CASE expression without having to re-type the expression. Using the sample employee table, find the maximum, minimum, and average salary. Instead of finding these values for each department, assume that you want to combine some departments into the same group. SELECT CASE_DEPT,MAX(SALARY),MIN(SALARY),AVG(SALARY) FROM (SELECT SALARY,CASE WHEN WORKDEPT = 'A00' OR WORKDEPT = 'E21' THEN 'A00_E21' WHEN WORKDEPT = 'D11' OR WORKDEPT = 'E11' THEN 'D11_E11' ELSE WORKDEPT END AS CASE_DEPT FROM DSN8910.EMP) X GROUP BY CASE_DEPT; DB2 PLAN/PACKAGE: each package corresponds to a single DBRM All packages can be grouped together to form a PLAN. Advantage of grouping all PACKAGES instead of using them as directly DBRM's is that, IF a collection of DBRM's is made as a plan then any change in one DBRM results in rebinding of the whole PLAN REBIND PACKAGE: REBIND PACKAGE (LEDGER.*) REBIND PACKAGE (LEDGER.*.(*)) REBIND PLAN: Example: Rebinds PLANA and changes the package list: REBIND PLAN(PLANA) PKLIST(GROUP1.*) MEMBER(ABC) Example: Rebinds the plan and drops the entire package list: REBIND PLAN(PLANA) NOPKLIST CONCURRENCY/LOCKS: LOCKS: khbkh Definition: Concurrency is the ability of more than one application process to access the same data at essentially the same time. Example: An application for order entry is used by many transactions simultaneously. Each transaction makes inserts in tables of invoices and invoice items, reads a table of data about customers, and reads and updates data about items on hand. Two operations on the same data, by two simultaneous transactions, might be separated only by microseconds. To the users, the operations appear concurrent. Conceptual background: Concurrency must be controlled to prevent lost updates and such possibly undesirable effects as unrepeatable reads and access to uncommitted data. Lost updates. Without concurrency control, two processes, A and B, might both read the same row from the database, and both calculate new values for one of its columns, based on what they read. If A updates the row with its new value, and then B updates the same row, A’s update is lost. Access to uncommitted data. Also without concurrency control, process A might update a value in the database, and process B might read that value before it was committed. Then, if A’s value is not later committed, but backed out, B’s calculations are based on uncommitted (and presumably incorrect) data. Unrepeatable reads. Some processes require the following sequence of events: A reads a row from the database and then goes on to process other SQL requests. Later, A reads the first row again and must find the same values it read the first time. Without control, process B could have changed the row between the two read operations. Different isolation levels Cursor stability: once the commit or rollback happens any other application can access Repeatable read: If RR is placed exclusive locks are put on the table, no other transaction can access that particular row until tarnsaction that held the record with RR is completed CS--> More performance RR--> more integrity Read stability: same a RR but the difference is no one can modify the the row or page but transactions can insert data. If there is no requirement that same number of rows have to fetched when the transaction is repeated on the table, RS can be used . Otherwise RR has to be used Uncommited READ: only relates to FETCH and SELECT Helps you read uncomitted changes in the table. Best for static tables, data retrieval is very fast http://db2portal.blogspot.com/2009/06/know-your-isolation-levels.html BIND options: Acquire/Release: RELEASE(COMMIT), RELEASE(DEALLOCATE) deallocate is useful db2 applications where the sql statements make a lot of updates are made to the table, that is when there are many instances of commit. Because if COMMIT happens the lock is not released If release(commit), is used lock is released every time after an update is made to the table ACQUIRE(ALLOCATE): means the lock is acquired when the plan is allocated. That means when the application starts all the tables, table spaces, partions are locked ACQUIRE(USE) : means the lock is acquired when the SPECIFIC partition/table space/table are accessed *********IMP****** ACQUIRE(ALLOCATE) and RELEASE(COMMIT) options are not allowed *******IMP***********if RELEASE(COMMIT) is used , but cursor is declared with HOLD option the LOCK is still maintained post the commit position CURRENTDATA(YES/NO): To guarantee data stability when a read only cursor is accessing data with CS isolation level READ ONLY is specified when cursor is delcared Interview Questions: Q7) After a table is defined, can columns be removed? NO Q65) How would you find out the total number of rows in a table? - GS A65) Use SELECT COUNT(*) ... TWO PHASE COMMIT: phase one: all the particpants are asked about their job, responses are collected in this phase only PHASE 2 if everybody says ok then commit, else rollback Q6) What information is used as input to the bind process? A6) The database request module produced during the pre-compile. The SYSIBM.SYSSTMT table of the DB2 catalog Q11) What is a buffer pool? A11) A buffer pool is main storage that is reserved to satisfy the buffering requirements for one or more tablespaces or indexes, and is made up of either 4K or 32K pages. Q12) How many buffer pools are there in DB2? A12) There are four buffer pools: BP0, BP1, BP2, and BP32. DB2 DBA: CREATE TABLESPACE TB IN DATABASENAME using storagegroup stgname priqty secqty erase no --> do not erase tables when table space is dropped locksize any bufferpool bp0 close no <== close the table spave when not accessed freepage 5 (Percentage of space that has to be left before any other table space starts) pctfree 10 (percentage of each page that has to be left free) SEGSIZE 32 (--segmented table space) more than one table (4 to 64) in multiples of four NUMPARTS2 (1 to 254) (part1...) (PART2...) When a table having referential integrity is altered, the table space is put in check pending status. So ideally a parent table must be update before a child table is updated Q21) What are data types? A21) They are attributes of columns, literals, and host variables. The data types are SMALLINT, INTEGER, FLOAT, DECIMAL, CHAR, VARCHAR, DATE and TIME. DELETING A PLAN Q24) What will the FREE command do to a plan? A24) It will drop(delete) that existing plan. DBRM: SYSIBM.SYSSTMT PLAN: SYSIBM.SYSPLANS Q36) What is the format (internal layout) of “TIMESTAMP”? A36) This is a seven part value that consists of a date (yymmdd) and time(hhmmss and microseconds). Lets say SQL query is accessing 500 rows but requires only 10 rows from that for the use RR-500 RS-10 CS-1 UR-none(read only) Types of Locks: Intent none:(Read only) Lock Owner can only read the data, cannot modify Applied on the table space/table Shared/Exclusive/Update Q44) What information is held in SYSIBM.SYSCOPY? A44) The SYSIBM.SYSCOPY table contains information about image copies made of the tablespaces. Q45) What information is contained in a SYSCOPY entry? A45) Included is the name of the database, the table space name, and the image copy type(full or incremental etc.,) as well as the date and time each copy was made. Q46) What information can you find in SYSIBM.SYSLINKS table? A46) The SYSIBM.SYSLINKS table contains information about the links between tables created by referential constraints. Q47) Where would you find information about the type of database authority held by the user? A47) SYSIBM.SYSDBAUTH. SYSIBM.SYSINDEXES SYSIBM.SYSVIEWS Q148) What is Skeleton cursor table (SKCT)? A148) The Executable form of a Plan. This is stored in sysibm.sct02 table CURSOR DELCARED WITH HOLD OPTION is not closed after a commit; explicit close is required to close the cursor Q54) What is the physical storage length of each of the following DB2 data types: DATE, TIME, TIMESTAMP? A54) DATE: 4bytes TIME: 3bytes TIMESTAMP: 10bytes Q55) What is the COBOL picture clause of the following DB2 data types: DATE, TIME, TIMESTAMP? A55) DATE: PIC X(10) TIME : PIC X(08) TIMESTAMP: PIC X(26) Utility to run a plan Use IKJEFT01 utility program to run the above DSN command in a JCL. Q65) How can you quickly find out the number of rows updated after an update statement? A65) Check the value stored in SQLERRD(3). Q108) What is CHECK PENDING ? A108) 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. Q109) What is QUIESCE? A109) A QUIESCE flushes all DB2 buffers on to the disk. This gives a correct snapshot of the database and should be used before and after any IMAGECOPY to maintain consistency. Q113) What is sqlcode -922 ? A113) Authorization failure Q114) What is sqlcode -811? A114) SELECT statement has resulted in retrieval of more than one row. Q145) What is the error code -803 ? A145) unique index violation Q167) What is the meaning of -805 SQL return code? A167) Program name not in plan. Bind the plan and include the DBRM for the program named as part of the plan Q115) What does the sqlcode of -818 pertain to? - GS A115) This is generated when the consistency tokens in the DBRM and the load module are different. Q122) What is filter factor? A122) One divided by the number of distinct values of a column. Q123) What is index cardinality? - GS A123) The number of distinct values a column or columns contain Q150) Can we declare DB2 HOST variable in COBOL COPY book? A150) NO. If we declare DB2 host variable in COBOL COPY book, at the time of Pre-compilation we get the host variable not defined, because pre-compiler will not expand COBOL COPY book. So we declare it either in DCLGEN with EXEC SQL INCLUDE DCLGEN name END-EXEC or we directly hardcode it in the working storage section. PLAN CREATION: BIND PLAN(????????) - **********>>> ENTER PLAN NAME PKLIST(SEALAND.????????, - **********>>> ENTER MEMBER NAME SEALAND.????????, - **********>>> (MULTIPLE MEMBERS SEALAND.????????) - **********>>> FOR EACH PLAN) QUALIFIER(TEST) - **********>>> MUST ALWAYS BE TEST OWNER(????) - **********>>> ENTER YOUR TSO ID ACTION(REPLACE) - RETAIN - VALIDATE(BIND) - ISOLATION(CS) - FLAG(I) - ACQUIRE(USE) - RELEASE(COMMIT) - EXPLAIN(YES) PLAN EXECUTION: DSN SYSTEM(DB2T) RUN PROG(TESTPROG) PLAN(TESTPLAN) END PACKAGE parameters. BIND PACKAGE(RR16388.TEST) VERSION(TEST) BIND PACKAGE(RR16388.PROD) VERSION(PROD) 1) What is happening above is that same package has two versions, One being TEST and the other PROD. Just used to maintain different regions. Next important thing is COLLECTION ID. Collection ID is the HLQ of the package name. Follow the example: BIND PLAN(PLANNAME) PKLIST(RR16388.*) 2) All the packages with collection ID "RR16388" are bound into a PLAN 3) SQLERROR(CONTINUE|NOPACKAGE) : If there is an SQL error create a PACKAGE, NOERROR BIND PARAMETERS: 1) MEMBER(MEMNAME): MEMBER is the member name in which the DBRM is stored 2) LIB('DBRMLIB'): PDS in which DBRM is present 3) ISOLATION LEVEL(CS|RR|RS|UR) 4) ACTION(REPLACE) REPLACE is default replace the PLAN with the same name 5) ACQUIRE(ALLOCATE|USE) RELEASE(COMMIT|DEALLOCATE) 6) VALIDATE(RUN|BIND): Validate for PACKAGE not found and privilege issues during RUN time iF RUN is mention, Else throw error message during the bind process 7) EXPLAIN(YES|NO) : PLAN_TABLE is updated with the access path by the optimizer SQL CODES: SQLCODE The SQLCODE field contains the SQL return code. The code can be zero (0), negative or positive. 0 means successful execution. Negative means unsuccessful with an error. An example is 911 which means a timeout has occurred with a rollback . Positive means successful execution with a warning. An example is +100 which means no rows found. Here is a more comprehensive list of the SQLCODEs for DB2: [ edit ] Zero (Successful) 0 Successful [ edit ] Negative values (Errors) 102 String constant is too long. 117 The number of values in the INSERT does not match the number of columns. 180 Bad data in Date/Time/Timestamp. 181 Bad data in Date/Time/Timestamp. 199 Illegal use of the specified keyword. 204 Object not defined to DB2. 205 Column name not in table. 206 Column does not exist in any table of the SELECT. 216 Not the same number of expressions on both sides of the comparison in a SELECT . 224 FETCH cannot make an INSENSITIVE cursor SENSITIVE. 229 The locale specified in a SET LOCALE statement was not found. 305 Null indicator needed. 311 Varchar, insert or update. LEN field with the right data length not set. 482 The procedure returned no locators. 501 Cursor not open on FETCH. 502 Opening cursor that is already open. 503 Updating column needs to be specified. 530 Referential integrity preventing the INSERT/UPDATE 532 Referential integrity (DELETE RESTRICT rule) preventing the DELETE. 536 Referential integrity (DELETE RESTRICT rule) preventing the DELETE. 545 Check constraint preventing the INSERT/UPDATE. 551 Authorization failure 747 The table is not available. 803 Duplicate key on insert or update. 805 DBRM or package not found in plan. 811 More than one row retrieved in SELECT INTO. 818 Plan and program: timestamp mismatch. 904 Unavailable resource. Someone else is locking your data. 911 Deadlock or timeout. Rollback has been done. 913 Deadlock or timeout. No rollback. 922 Authorization needed. 927 The language interface was called but no connection had been made. 936 1741 20000 302 Data that is fetched from DB2 is more than the host variable [ edit ] Positive Values (Warnings) +100 Row not found or end of cursor. +222 Trying to fetch a row within a DELETE statement. +223 Trying to fetch a row within an UPDATE statement. +231 FETCH after a BEFORE or AFTER but not on a valid row. +304 Value cannot be assigned to this host variable because it is out of range. +802 The null indicator was set to 2 as an arithmetic statement didn't work. Null Indicators: While select, If you doubt that the returned value might be null use a null indicator. While update if you want to move null values then pass -1 into the null indicator and then update/insert the table ******IMP*** while update , if you set the db2 field to a value that is stored in the host variable and for example assume that host variable does have some value and if the respective null indicator has -1 in it then the value in the host variable will not be inserted, it will be set to NULL S9(4) USAGE COMP means --> Small int as it occupies two bytes SEGMENTED table space: Each page is of size 4 kb to 64 KB A page is divided into segments Each segment can relate to only one table. So if a page lock is applied only relevant segments to the particular table are locked. If rows are retrieved only relevant segments are accessed CREATE TABLESPACE MYTS IN MYDB USING STOGROUP MYSTOGRP PRIQTY 30720 SECQTY 10240 SEGSIZE 32 LOCKSIZE TABLE BUFFERPOOL BP0 CLOSE NO; Bufferpool: When DB2 tables are picked up from the disk to the Main memory The area of Main memory that will be used by the DB2 tables is bufferpool Segmented table space: One table per page. ALTER TABLE: ALTER TABLE IBMGRP.ALTER ALTER COLUMN NAME SET DATA TYPE VARCHAR(100); VIEW:--> WITH CHECK OPTION WILL THROW ERRORS IF ANY CREATE VIEW PRIORITY_ORDERS AS SELECT * FROM ORDERS WHERE RESPONSE_TIME < 4 WITH CHECK OPTION Now, suppose a user tries to insert a record into this view that has a RESPONSE_TIME value of 6. The insert operation will fail because the record violates the view’s definition. Had the view not been created with the WITH CHECK OPTION clause, the insert operation would have been successful, even though the new record would not be visible to the view that was used to add it. Trigger :<-- Every time an insert happens the emp no is incremented by 1 CREATE TRIGGER NAME_INC AFTER INSERT ON IBMGRP.ALTER FOR EACH ROW MODE DB2SQL UPDATE NAMID SET NAMID = NAMID + 1; Delete <-- Always use it with where to avoid mass delete of rows DELETE FROM SALES WHERE COMPANY = ‘XYZ’ The SELECT statement : SELECT <DISTINCT> [* | [Expression] <<AS> [NewColumnName]> ,...] FROM [[TableName] | [ViewName] <<AS> [CorrelationName]> ,...] <WhereClause> <GroupByClause> <HavingClause> <OrderByClause> <FetchFirstClause> Order of execution: · The DISTINCT clause · The FROM clause · The WHERE clause · The GROUP BY clause · The HAVING clause · The ORDER BY clause · The FETCH FIRST clause Where can be used with : · Relational Predicates (Comparisons) · BETWEEN · LIKE · IN · EXISTS · NULL Relational predicates · < (Less than) · > (Greater than) · <= (Less than or equal to) · >= (Greater than or equal to) · = (Equal to) · <> (Not equal to) · NOT (Negation) BETWEEN: SELECT EMPNO, SALARY FROM EMPLOYEES WHERE SALARY BETWEEN 10000.00 AND 20000.00 >= 10K and <= 20000 The LIKE predicate: · The underscore character (_) is treated as a wild card character that stands for any single alphanumeric character. · The percent character (%) is treated as a wild card character that stands for any sequence of alphanumeric characters. SELECT EMPNO, LASTNAME FROM EMPLOYEES WHERE LASTNAME LIKE ‘S%’ IN predicate: SELECT LASTNAME, WORKDEPT FROM EMPLOYEES WHERE WORKDEPT IN (SELECT DEPTNO FROM DEPARTMENTS WHERE DEPTNAME = ‘OPERATIONS’ OR DEPTNO = ‘SOFTWARE SUPPORT’) *** The EXISTS CLAUSE ***** The EXISTS predicate is used to determine whether or not a particular value exists in a given table. The EXISTS predicate is always followed by a subquery , and it returns either TRUE or FALSE to indicate whether a specific value is found in the result data set produced by the subquery. Thus, if you wanted to find out which values found in the column named DEPTNO in a table named DEPARTMENT are used in the column named WORKDEPT found in a table named EMPLOYEES, you could do so by executing a SELECT statement that looks something like this: SELECT DEPTNO, DEPTNAME FROM DEPARTMENT WHERE EXISTS (SELECT WORKDEPT FROM EMPLOYEES WHERE WORKDEPT = DEPTNO) AGGREGATE FUNCTION: When MAX,MIN,SUM,AVG,COUNT(*) are used, the rows having null values are discarded. FOr example: MyTable ID Name Amount 1 John 37 2 Jack NULL 3 Jim 5 4 Joe 12 5 Josh NULL When avg(amount) is asked then DB2 will consider only 37+5+12/3 not (37+NULL + 5+ NULL+ 12)/5 Having Clause: SELECT DEPTNAME, AVG(SALARY) AS AVG_SALARY FROM DEPARTMENT D, EMPLOYEES E WHERE E.WORKDEPT = D.DEPTNO GROUP BY DEPTNAME HAVING AVG(SALARY) > 30000.00 Inner join Vs Outer Join Inner join only returns matching rows Outer join returns matching rows and non matching rows(Depending on Left,Right,Full) SELECT LASTNAME, DEPTNAME FROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENT D ON E.WORKDEPT = D.DEPTNO Union Vs Union all: Union will return combined result of two different queries , Any duplicates will be eliminated, Union All will not eliminate duplicates Types of Locks: Intent Share/ Intent Upddate. The above two locks are only the ones which can get a lock at row level or page level Share/Update/eXclusive locks:- These locks are obtained at table level Intent share : Lock is obtained at a row or page level. other application ./ user can update other rows Share: Everybody can read the rows in table but nobody can update the table Update: For the application to update any data , lock has to be promoted to X EXEC SQL LOCK TABLE TAB1 IN SHARE MODE END-EXEC Lets say SQL query is accessing 500 rows but requires only 10 rows from that for the use RR-500 RS-10 CS-1 UR-none(read only) DECLARE CURSOR C1 FOR SELECT WITH RR/RS/CS/UR The above will override bind isolation levels Example for DB2 SQLCODE: -922 READY DSN SYSTEM(DB2R) DSN BIND PLAN(FCURF2) PKLIST(DB2RLOC.IBMGRP.*) ACT(REP) ISOLATION(CS) DSNT210I -DB2R BIND AUTHORIZATION ERROR USING R06388 AUTHORITY PLAN = FCURF2 PRIVILEGE = BINDADD DSNT201I -DB2R BIND FOR PLAN FCURF2 NOT SUCCESSFUL DSN EXPLAIN (NO) OWNER(IBMGRP) DSNE118E EXPLAIN NOT VALID COMMAND DSN END Authorization(BINDADD) not present to add a DBRM to a PACKAGE DB2 FAq's: http://muraliwebworld.com/db2.aspx If SELECT statement has to be used within DECLARE CURSOR, there is no other place where in we can retrieve rows . Declare cursor can be used with UPDATE/DELETE (In the sence select statement should be there with UPDATE / DELETE statements like FOR UPDATE OF) INSERT is not allowed with DECLARE CURSOR