You are on page 1of 34

DB2 / SQL Interview Questions

Q1. What are the different types of SQL? A1. BASED ON FUNCTIONALITY : i) Data Control Language (DCL) - Provides the control statements that govern data security with GRANT and REVOKE verbs. ii). Data Definition Language (DDL) - Creates and maintains the physical data structure with the CREATE , ALTER , DROP SQL verbs. iii) Data Manupulation language (DML) - Accesses and modifies data with the SELECT , INSERT , DELETE and UPDATE verbs. EXECUTION : i) Production ii) Adhoc DYNAMISM : i) Dynamic SQL ii) Static SQL Q2. What is the theory behind the JOIN statement in DB2? A2. i)As many as 15 DB2 tables can be joined in one SQL statement. ii)Inner join & outer join iii)Self join iv) Cartesian product - Result of a join that does not specify matchng columns. JOIN EXAMPLES ============= 1. Select Empname, salary, deptno, empno FROM table.emp, table.dept

WHERE empdept = compdep; In the above example all the rows from the employee table would be selected where the department code is same in the Employee table and the department table. This is done by comparing the variables empdept and compdep in the tables table.emp and table.dept respectively. The intersting part in the above example is that there is no keyword JOIN in the statement. This was introduced in the DB2 ver4.The above mentioned example can also be coded by the following two ways: 2. Select Empname, salary, deptno, empno FROM table.emp JOIN table.dept ON empdept = compdep;

Select Empname, salary, deptno, empno FROM table.emp INNER JOIN table.dept ON empdept = compdep;

Tables can also be joined amongst themselves as follows: Select empname, bossname, empno, bossno FROM emp.table A, emp.table B, WHERE A.empno = B.bossno The above query would give the name of the CEO who reports to himself. Q3. What do you know about subqueries? A3. When one or more SELECT statements are nested in another SELECT statement, the query is referred to as subquery They are expressed in the following ways: i) Using the IN predicate.

ii) Using the exists predicate. iii) Specifying the equality predicate (=) or the inequality predicate (<>)

Q5. The capability to query multiple tables where the nested SELECT statement can refer back to columns in previous SELECT statement is called as corelated subquery.table A WHERE A. Q4.studentno FROM student. The following two are good examples of each of them: SELECT studentname.marks) FROM student. studentno . Q6.table B WHERE A. The bottommost query is resolved first and based on its results the higher level query is resolved.studentno) ORDER BY A. Subquery vs Join A6.studentname. A.studentno = B. SELECT A.table where empno = (SELECT empno FROM accounts. In a Non-correlated subquery the approach is from bottom to top.Following is one of the example : SELECT empname FROM emp. What is a Non-corelated subquery? A5.studentno. What is a corelated subquery? A4.marks > (SELECT AVG(B. A classic example of this can be shown while trying to list the students who have scored greater than the average marks scored by the students of the class.table where salary > 70000).

B.table WHERE studentgrade IN (SELECT schoolstudentno FROM school.FROM student.teacherno. The two original rows should be UNION-compatible. The UNION verb eliminates duplicates whereas the UNION ALL eliminates them.classteachername FROM classtable A. . 2.table. A.table WHERE studentgrade = 2 ). WHERE schoolstudentno = studentno AND studentgrade = 2. Explain the UNION operation in SQL. By using UNION one can combine two sets of rows into a single set. This query can be represented as a JOIN by the following query SELECT studentname. Following example can explain this. What is meant by OUTER JOIN ? A8.classname. Following are the two clauses for the tables to be UNION compatible.table. Each column of the first set must be either the same data type as the corresponding column of the second set or convertible to the same data type as the corresponding column of the second set. SELECT DISTINCT A. 1. studentno FROM student. Both of the above queries return the names of the students who are in grade 2. Q8. A7. The two sets must contain the same number of columns. When we desire to get the results of the matching and non matching rows for one or more tables being joined then best option is to use OUTER JOIN. Q7. school.

This returns all the matching and unmatched rows from both the tables.TABLE GROUP BY TEAMNO. In the above case there would be blank rows for the records which donot have teachername.000 then the query becomes. iii) FULL OUTER JOIN .This returns all the matching rows and the unmatched rows of the right table of the SQL. SELECT TEAMNO. ii)RIGHT OUTER JOIN . classteachername FROM classtable LEFT OUTER JOIN teachertable ON teacherno = empno. In case a class does not have a classteacher assigned. i) LEFT OUTER JOIN . '* NO CLASSTEACHER*') FROM classtable LEFT OUTER JOIN teachertable ON teacherno = empno.teachertable B WHERE A. What is meant by SORTING and GROUPONG? A10. Or if the class teacher is not recorded in the teachertable then those classes wont be listed. VALUE(classteachername. Q10. The objective of the above query is to list all the classes in the school with the names of the class teachers. Now if you just want to show the team that scored runs more than 10. teacherno. teacherno. The above situation can be avoided by using the LEFT OUTER JOIN SELECT classname. Following are the example to show their difference. What are the different types of OUTER JOINS? A9. SUM(RUNS) FROM TEAM. Q9.teacherno = B. The above query returns the aggregate runs for each team.empno. .This returns all the matching rows and the unmatched rows of the left table of the SQL code. This can be taken care by the following SQL SELECT classname.

SUM(Runs) FROM SUPERBOWL. SELECT Team. Q12 : Wjat is meant by scrollable cursor? Answer : Lets say you have a table with 100 records and by using cursor you want to fetch records from table. The following query is a classic example of the use of HAVING .. the same way that the pre-V7 FETCH statement functioned . will not show changes made To use scrollable cursors you must use declared temporary tables. can access data changed by the user or other users INSENSITIVE -. Lets say you want To fetch the eigth record and then want to fetch the sixth record again. The following key words are supported when fetching data from a scrollable cursor:  NEXT . WHERE and GROUPBY in one SQL? A11. Scrollable cursors allow developers to move through the results of a query in multiple ways.g.updateable.TABLE WHERE TEAM NOT IN ('Newyork'. C) is required to facilitate a scrollable cursor in DB2 V7.this can be achieved using scrollable cursor A scrollable cursor provides the ability to scroll forward and backward through the data once the cursor is open. COBOL. SUM(RUNS) FROM TEAM.. DB2 uses a declared temporary table to hold and maintain the data returned by a scrollable cursor. This can be achieved using nothing but SQL .not updateable.. another new feature of DB2 Version 7.will FETCH the next row.no host language code (e.. WHERE and GROUPBY in one SQL. The use of HAVING. A scrollable cursor makes navigating through SQL result sets much easier. 'Boston') GROUP BY Team HAVING SUM(Runs) > 5000.SELECT TEAMNO. There are two types of DB2 scrollable cursors: SENSITIVE -.TABLE GROUP BY TEAMNO HAVING SUM(RUNS) > 10000 Q11..

or a list of the top five most expensive products (i. There are several ways to accomplish this prior to DB2 V7 using SQL. and often is not sufficient to produce the results desired . It can be either a positive or a negative number.will FETCH the first row in the results set  LAST . PRIOR .will re-FETCH the current row from the result set  BEFORE ..will FETCH the last row in the results set  CURRENT . The FETCH LAST statement will reposition the cursor to the last row of the results set. Analyze the requirements of your applications and deploy scrollable cursors only where it makes sense to do so. highest price tag). consider the following cursor logic: DECLARE csr1 SENSITIVE STATIC SCROLL CURSOR FOR SELECT FIRSTNAME.positions the cursor after the last row of the results set  ABSOLUTE n . and it can be represented as a numeric constant or as a host variable. maybe you need to list the top ten best selling items from inventory. OPEN csr1. but they are not necessarily efficient.will FETCH the row that is n rows away from the last row fetched  For both ABSOLUTE and RELATIVE. and then FETCH the results into the host variables as specified. Limiting the Number of Rows Fetched Application developers frequently need to retrieve a limited number of qualifying rows from a table. and then FETCH the last row from the cursor's results set. All of the FETCH options for scrollable cursors also reposition the cursor before fetching the data.EMP ORDER BY LASTNME. But as helpful as scrollable cursors are. LASTNME FROM DSN8710. But this is simplistic.positions the cursor before the first row of the results set  AFTER . the number n must be an integer. FETCH LAST csr1 INTO :FN. open that cursor. For example.will FETCH the previous row  FIRST .e. Scrollable cursors reduce the amount of time and effort required to move backward and forward through the results of SQL queries. Issuing this SQL will declare a scrollable cursor named csr1. :LN. Scrollable cursors require substantially more overhead than a traditional. The first reaction is to simply use the WHERE clause to eliminate non-qualifying rows. For example. do not make every cursor a scrollable cursor. nonscrollable cursor.will FETCH the row that is n rows away from the first row in the results set  RELATIVE n .

If it is removed from the query. such as the following: SELECT EMPNO. DB2 V7 provides an easier and less complicated way to limit the results of a SELECT statement .FETCH FIRST ROW ONLY clause -.EMP WHERE A. instead of the default.the FIRST key word. You must specify the ORDER BY clause with the DESC key word. So the results would still be all employees in the table.EMP WHERE 10 > FROM DSN8710. Consider. or top 5. not at the beginning. Without the DESC key word. But that does not really satisfy the requirement . as deemed necessary by the needs of your application. such as Oracle or SQL Server). You can code some "tricky" SQL to support this request for all versions of DB2. You could simply issue a SQL request that retrieves all of the employees in order by salary. Doing so informs DB2 to ignore the other rows. This sorts the results into descending order. You can code FETCH FIRST n ROWS which will limit the number of rows that are fetched and returned by a SELECT statement. which is ascending. The ideal solution should return only the top ten employees with the highest salary and not merely a sorted list of all employees. the "top ten" would be at the very end of the results set. FIRSTNME.SALARY AND SALARY IS ORDER BY SALARY DESC. for example. but in the correct order so you can view the "top ten" salaries very easily. (SELECT < NOT SALARY COUNT(*) A A B. of course. SALARY FROM DSN8710. What if the program only requires that the top ten results be returned? This can be a somewhat difficult request to formulate using SQL alone. LASTNAME. thereby retrieving the top 20. but they will be in no particular order.retrieving only the top ten. Since the SALARY column is nullable in the EMP table.on SELECT INTO statements when the query can return more than one row in the answer set.EMP ORDER BY SALARY DESC. And the ORDER BY is required to sort the results in the right order. FIRSTNME. That is easy. you can specify a new clause -. It merely sorts the results into descending sequence. you can change the constant 10 to any number you wish.in an optimal manner. the results will still contain the top ten. for example: SELECT EMPNO. And. but only use the first ten retrieved. Additionally.SALARY) NULL This SQL is portable from version to version of DB2 (as well as to another DBMS. an application that needs to retrieve only the top ten most highly paid employees from the EMP sample table. . LASTNAME. FROM DSN8710. you must remove the nulls from the results set.

Using the FIRST key word DB2 will limit the number of rows returned to ten. select. \ birthdate date. update or modify your tables. The previous query we examined may return more than 10 rows if there are multiple rows with the same value for price within the top ten. Hence. \ salary decimal(10. 2) Let us see a more realistic example of defining a table with more data types in addition to constraints and primary keys. use the revoke command to revoke access to your tables. primary key(name)) Here the name field is defined to be the primary key. update. update on table people to a343meee Then. create table table1 \ (name char(20) not null. then I can issue the following select statement: select * from a343foo. etc) on table people to all members of a Unix group named c343h01. Notice that it must be defined as not null.There is one difference between the new V7 formulation and the other SELECT statement we reviewed. even if there are other rows with the same value for price as the number ten row in the results set. . ************************************************************************* Some more SQL examples -------------------------------------------------------------------------1) Granting permission to query. the above command may fail to grant permissions to each member of the group. when I run my SQL queries on your table.people which will display all the tuples in your people table. you: grant select. the new V7 feature may not prove to be helpful. However. Note: if a table is to be used in a view definition.2). \ profession varchar(30).people to a343meee me: select * from csc343h. delete. The needs of your application will dictate whether ties are to be ignored or included in the result set. update on table csc343h. if the table resides in a schema called csc343h then both you and I have to use this schema name in our commands. A tie occurs when more than one row contains the same value. If your user name is a343foo. We can now insert the following tuple. and that is the way "ties" are handled.people To grant all privileges (alter. grant select. In such a case grant permissions to each user explicitly. you will not need to use these commands unless you alter your groups. Suppose you wish to grant me (username a343meee) permission to issue select and update commands on the data in your table people which resides in your default schema. insert. If all "ties" need to be included in the results set. If a member leaves your group. I have to distinguish it by your user id. we type GRANT ALL ON TABLE people to c343h01 Members of your 343 group will have all privileges on your group database.

" db2 => -on delete NO ACTION db2 => -on delete RESTRICT db2 => -on delete CASCADE db2 => insert into dept values(1. db2 => select * from dept DEPT NAME ----------. 2) DB20000I The SQL command completed successfully. 'jim'. name char(20).) => foreign key(deptno) references dept on delete set null) DB20000I The SQL command completed successfully.. db2 => insert into dept values(2. then.'bill'.other choices for "on delete . db2 => insert into emp values(2. 'used car salesman'. year() and day() functions. \ db2 (cont.'admin') DB20000I The SQL command completed successfully. we use the fullselect syntax as follows: insert into overachievers \ select * from table1 \ where profession = 'used car salesman' Finally. db2 => select * from emp EMPNO NAME DEPTNO ----------.. 'development') DB20000I The SQL command completed successfully. name char(20).) => deptno integer.insert into table1 values ('Joe Doe'. the referenced emp has its deptno field set null. db2 => insert into emp values(1. \ db2 (cont. db2 => create table dept( dept_no integer not null.'adel'. \ db2 (cont. In addition. 1200. DB2 allows to parse the date attribute using its month(). 1. db2 => insert into emp values(3.) => primary key(dept_no)) DB20000I The SQL command completed successfully. db2 => insert into dept values(3. \ '1943-12-25') Note the format of the date is yyyy-mm-dd. db2 => create table emp( empno integer not null.-------------------.56. 3) DB20000I The SQL command completed successfully. 1) DB20000I The SQL command completed successfully. Assuming that the table overachievers is already defined.----------1 adel 1 2 jim 2 3 bill 3 3 record(s) selected. here is a sample db2 session that creates two tables dept and emp. 'research') DB20000I The SQL command completed successfully. This can be done as follows: select * from table1 where month(birthdate) = 1 and day(birthdate) = 1 3)Inserting into a table from another table: Suppose we want to create a table named overachievers which contains all the tuples from table1 whose profession is 'used car salesman'. Suppose we wish to display everyone in table1 whose birth day falls on January.-------------------1 research 2 development 3 admin . db2 => -. and sets a referential constraint between them so that when the referencing dept tuple is deleted.

A page lock is held only while the cursor is positioned on that page. When a page is locked concurrent application programs cannot update or delete a row of the locked page.-------------------.-------------------2 development 3 admin 2 record(s) selected. the lock is held until the data is committed. the lock is released.----------1 adel 2 jim 2 3 bill 3 3 record(s) selected. it allows other transactions to read or acquire shared locks on the space. An exclusive lock bars all other users from accessing the space. Question 4 Why should you not code a RIGHT OUTER JOIN ? . db2 => delete from dept where name = 'research' DB20000I The SQL command completed successfully. db2 => Notice the value of DEPTNO for employee 1 is set to null (-) as dictated by the constraint. The three types are shared. SELECT MIN(COLA) FROM TABLENAME WHERE COLA > (SELECT MIN(COLA) FROM TABLENAME) . CS applies only to data that is read.3 record(s) selected. db2 => select * from dept DEPT NAME ----------. Question 1 How do you find the second max and second min in a given table? Ans-1 SELECT MAX(COLA) FROM TABLENAME WHERE COLA < (SELECT MAX(COLA) FROM TABLENAME) . The current lock is not released until a new lock is acquired. All changed data remains locked until COMMIT or ROLLBACK What are the three lock types? Ans-3. If an application program updates or deletes data. Shared locks allow two or more programs to read simultaneously but not change the locked space. Question 2 What is Cursor Stability(CS)? Ans-2. An update lock is less restrictive. When the cursor moves to another page. db2 => select * from emp EMPNO NAME DEPTNO ----------. update and exclusive.

click here to read about the coalesce function of DB2.Provides the control statements that govern data security with GRANT and REVOKE verbs.Ans-4 The reason for this is the way DB2 shows EXPLAIN information . EXPLAIN populates the JOIN_TYPE column to describe the outer join method (FULL. There can be some overhead for updating indexes. or a blank for an INNER JOIN or no join. . Question-8 When do we use mass delete and when do we use load : Ans-8 A mass delete is more efficient when one is using segmented table spaces where as loading an empty data set is more efficient when one is using simple or partitioned tablespaces. RIGHT or LEFT).  No DB2 objects are created so they do not need object management. Question-5 Why is the COALESCE function used ? Ans-5 The COALESCE function avoids the use of nulls in the result coulmn of OUTER JOIN statements. Q9. So to avoid this one should drop the indexes then insert the data and then recreate the indexes. so there is no R value forJOIN_TYPE. EXPLAIN always converts right outer joins to left outer joins. What are the different types of SQL? A9.This makes the left outer join easier to tune. Data Definition Language (DDL) . ii). the SQL is clearly displayed in the body of the SELECT statement. Question-6 Why do we use inline views ? Ans-6 Following are the three reasons for using Inline views :  Easy to understand. Large insertions can cause poor performance because of a disorganized index. The last thing to remember is to run RUNSTATS immediately after the dropped indexes are built. BASED ON FUNCTIONALITY : i) Data Control Language (DCL) . The column contains the value F for a FULL OUTER JOIN. Question-7 Why do we drop indexes before large insertions Ans-7 When a large number of inserts is being taking place then it is a good idea that every index must be updated with the columns and the appropriate RIDs for each inserted row. L for a LEFT OUTER JOIN or RIGHT OUTER JOIN. This explains why interpreting a PLAN_TABLE data is more difficult for a RIGHT OUTER JOIN than a LEFT OUTER JOIN.  They are great if detailed information is required from a single table.Creates and maintains the physical data structure with the CREATE . Instead of attempting to query the DB2 catalog to extract the SQL definition of a view.

ii)Inner join & outer join iii)Self join iv) Cartesian product .Accesses and modifies data with the SELECT . INSERT . iii) Data Manupulation language (DML) .emp. JOIN EXAMPLES ============= 1. i)As many as 15 DB2 tables can be joined in one SQL statement.dept WHERE empdept = compdep. deptno. EXECUTION : i) Production ii) Adhoc DYNAMISM : i) Dynamic SQL ii) Static SQL Q10. DROP SQL verbs. table. What is the theory behind the JOIN statement in DB2? A10.Result of a join that does not specify matchng columns. empno FROM table. In the above example all the rows from the employee table would be selected where the department code is same .ALTER . DELETE and UPDATE verbs. salary. Select Empname.

emp JOIN table.in the Employee table and the department table. bossno FROM emp.dept ON empdept = compdep. deptno. salary. This is done by comparing the variables empdept and compdep in the tables table. Tables can also be joined amongst themselves as follows : Select empname.table B. empno.empno = B.emp and table. Select Empname. empno FROM table. Select Empname. salary. WHERE A. The intersting part in the above example is that there is no keyword JOIN in the statement. bossname.bossno The above query would give the name of the CEO who reports to himself. . emp. This was introduced in the DB2 ver4.emp INNER JOIN table.The above mentioned example can also be coded by the following two ways : 2.dept ON empdept = compdep.table A. deptno. empno FROM table.dept respectively.

.table where empno = (SELECT empno FROM accounts. ii) Using the exists predicate. When one or more SELECT statements are nested in another SELECT statement. The capability to query multiple tables where the nested SELECT statement can refer back to columns in previous SELECT statement is called as corelated subquery. the query is referred to as subquery they are expressed in the following ways : i) Using the IN predicate. What do you know about subqueries? A11. iii) Specifying the equality predicate (=) or the inequality predicate (<>) Following is one of the example : SELECT empname FROM emp. Q12. A classic example of this can be shown while trying to list the students who have scored greater than the average marks scored by the students of the class.Q11.table where salary > 70000). What is a corelated subquery? A12.

The following two are good examples of each of them : SELECT studentname. What is a Non-corelated subquery? A13.marks) FROM student.studentname. In a Non-correlated subquery the approach is from bottom to top.studentno = B. A. Subquery vs Join A14.table B WHERE A.studentno) ORDER BY A. The bottommost query is resolved first and based on its results the higher level query is resolved. This query can be represented as a JOIN by the following query .SELECT A. Q14.table A WHERE A. Q13. studentno FROM student.table WHERE studentgrade IN (SELECT schoolstudentno FROM school.studentno.table WHERE studentgrade = 2 ).marks > (SELECT AVG(B.studentno FROM student.

studentno FROM student.table. The two original rows should be UNION-compatible. WHERE schoolstudentno = studentno AND studentgrade = 2. Q15. What is meant by OUTER JOIN ? A16. The two sets must contain the same number of columns.SELECT studentname. Following example can explain this. By using UNION one can combine two sets of rows into a single set. The UNION verb eliminates duplicates whereas the UNION ALL eliminates them. Each column of the first set must be either the same data type as the corresponding column of the second set or convertible to the same data type as the corresponding column of the second set. Both of the above queries return the names of the students who are in grade 2. Q16. 2. Explain the UNION operation in SQL. school. When we desire to get the results of the matching and non matching rows for one or more tables being joined then best option is to use OUTER JOIN.table. . Following sre the two clauses for the tables to be UNION compatible. 1. A15.

.teacherno.classteachername FROM classtable A. Or if the class teacher is not recorded in the teachertable then those classes wont be listed. B. '* NO CLASSTEACHER*') FROM classtable LEFT OUTER JOIN teachertable ON teacherno = empno. teacherno.empno. A. VALUE(classteachername. teachertable B WHERE A. In the above case there would be blank rows for the records which donot have teachername. The above situation can be avoided by using the LEFT OUTER JOIN SELECT classname. This can be taken care by the following SQL SELECT classname. teacherno.teacherno = B. classteachername FROM classtable LEFT OUTER JOIN teachertable ON teacherno = empno. In case a class does not have a classteacher assigned.classname.SELECT DISTINCT A. the objective of the above query is to list all the classes in the school with the names of the class teachers.

The above query returns the aggregate runs for each team. SUM(RUNS) FROM TEAM. SUM(RUNS) FROM TEAM.TABLE GROUP BY TEAMNO HAVING SUM(RUNS) > 10000 Q19. SELECT TEAMNO. The following query is a classic example of the use of HAVING . iii) FULL OUTER JOIN .This returns all the matching rows and the unmatched rows of the right table of the SQL. WHERE and GROUPBY in one SQL. Q18.This returns all the matching rows and the unmatched rows of the left table of the SQL code.000 then the query becomes.Q17. What is meant by SORTING and GROUPONG? A18. The use of HAVING . SELECT TEAMNO. What are the different types of OUTER JOINS? A17.This returns all the matching and unmatched rows from both the tables. Following are the example to show their difference. . ii)RIGHT OUTER JOIN . Now if you just want to show the team that scored runs more than 10.TABLE GROUP BY TEAMNO. WHERE and GROUPBY in one SQL? A19. i) LEFT OUTER JOIN .

.SELECT Team. 5) How do you find the maximum value in a column? – Use SELECT MAX(. 2) How do you eliminate duplicate values in SELECT? – Use SELECT DISTINCT .. 1) How would you find out the total number of rows in a table? – Use SELECT COUNT(*) .. 3) How do you select a row using indexes? – Specify the indexed columns in the WHERE clause. . Why? Because SALARY is not declared to have NULLs and the employees for whom the salary is not known are also counted. 4) What are aggregate functions? Bulit-in mathematical functions for use in SELECT clause. 6) Can you use MAX on a CHAR column? YES.. 7) My SQL statement SELECT AVG(SALARY) FROM EMP yields inaccurate results. SUM(Runs) FROM SUPERBOWL...TABLE WHERE TEAM NOY IN ('Newyork'. 'Boston') GROUP BY Team HAVING SUM(Runs) > 5000.

17) What is the meaning of underscore ( ‘_’ ) in the LIKE statement? – . to search employee by name. using LIKE. how many times should I specify UNION to eliminate the duplicate rows? Once.UNION ALL? – UNION : eliminates duplicates UNION ALL: retains duplicates Both these are used to combine the results of different SELECT statements. Substitute a numeric value for any nulls used in computation 11) What is UNION. 10) What is the use of VALUE function? 1. Avoid -ve SQLCODEs by handling nulls and zeroes in computations 2. Suppose I have five SQL SELECT statements connected by UNION/UNION ALL. you need not specify the complete name.1. 13) In the WHERE clause what is BETWEEN and IN? – BETWEEN supplies a range of values while IN supplies a list of values. ‘%’ ( for a string of any character ) and ‘_’ (for any single character ) are the two wild card characters. 12) What is the restriction on using UNION in embedded SQL? It has to be in a CURSOR.8) How do you retrieve the first 5 characters of FIRSTNAME column of EMP table? SELECT SUBSTR(FIRSTNAME. 14) Is BETWEEN inclusive of the range values specified? – Yes.5) FROM EMP. you can search for partial string matches. 9) How do you concatenate the FIRSTNAME and LASTNAME from EMP table to give a complete name? SELECT FIRSTNAME || ‘ ‘ || LASTNAME FROM EMP. 16) When do you use a LIKE statement? To do partial search e.g. 15) What is 'LIKE' used for in WHERE clause? What are the wildcard characters? – LIKE is used for partial string matches.

22) What are the issues related with correlated subqueries? – ??? 23) 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. How can you get a list of employees who are not assigned to any project? SELECT EMPNO FROM EMP WHERE PROJECT IS NULL. The chance of an index only scan is lost. 20) What is the result of this query if no rows are selected: SELECT SUM(SALARY) FROM EMP WHERE QUAL=‘MSC’.. NULL 21) Why SELECT * is not preferred in embedded SQL programs? For three reasons: If the table structure is changed ( a field is added ). the program will have to be modified Program might retrieve the columns which it might not use. .Match for any single character.. 18) What do you accomplish by GROUP BY . Correlated subqueries must be evaluated for each qualified row of the outer query that is referred to. HAVING clause? – GROUP BY partitions the selected rows on the distinct values of the column on which you group by. Cursor should be used because the host language can deal with only one row at a time. What are correlated subqueries? A subquery in which the inner ( nested ) query refers back to the table in the outer query. HAVING selects GROUPs which match the criteria specified 19) Consider the employee table with column PROJECT nullable. leading on I/O over head.

27) What happens when you say OPEN CURSOR? If there is an ORDER BY clause. is the cursor closed? Yes. sorted and made available for the FETCH statement. 29) Can you have more than one cursor open at any one time in a program ? – Yes.3 or above only ) Use WITH HOLD option in DECLARE CURSOR statement. it has not effect in psuedoconversational CICS programs. 28) Is DECLARE CURSOR executable? No. what other ways are available to you to retrieve a row from a table in embedded SQL? Single row SELECTs. .. FETCH rows in a loop and finally CLOSE. 49 REMARKS-TEXT PIC X(1920). 10 REMARKS. 25) Where would you specify the DECLARE CURSOR statement? – See answer to next question. to specify the SELECT statement.24) How would you retrieve rows from a DB2 table in embedded SQL? – Either by using the single row SELECT statements.. Apart from cursor. or by using the CURSOR. 32) Give the COBOL definition of a VARCHAR field. rows are fetched. Then use OPEN. But. 30) When you COMMIT. Other wise simply the cursor is placed on the first row. 26) How do you specify and use a cursor in a COBOL program? – Use DECLARE CURSOR statement either in working storage or in procedure division(before open cursor). 49 REMARKS-LEN PIC S9(4) USAGE COMP. 31) How do you leave the cursor open after issuing a COMMIT? ( for DB2 2. A VARCHAR column REMARKS would be defined as follows: .

33) What is the physical storage length of each of the following DB2 data types: DATE. 11 indicates the size of the data type and 2 indicates the precision. This is used by the pre-compiler to validate the table-name. view-name. helps detect wrongly spelt column names etc. TIME. during the pre-compile stage itself ( because of the DECLARE TABLE ). TIMESTAMP? DATE: 4bytes TIME: 3bytes TIMESTAMP: 10bytes 34) What is the COBOL picture clause of the following DB2 data types: DATE. Using DCLGEN.2)? PIC S9(9)V99 COMP-3. 38) Is it mandatory to use DCLGEN? If not. EXEC SQL DECLARE TABLE statement which gives the layout of the table/view in terms of DB2 datatypes. Also creates the DECLARE table. DCLGEN being a tool. would generate accurate host variable definitions for the table reducing chances of error. column name etc. Note: In DECIMAL(11. . during pre-compile. why would you use it at all? It is not mandatory to use DCLGEN. 39) Is DECLARE TABLE in DCLGEN necessary? Why it used? It not necessary to have DECLARE TABLE statement in DCLGEN.. TIMESTAMP? DATE: PIC X(10) TIME : PIC X(08) TIMESTAMP: PIC X(26) 35) What is the COBOL picture clause for a DB2 column defined as DECIMAL(11. A host language copy book that gives the host variable definitions for the column names.2). TIME. 37) What are the contents of a DCLGEN? 1. 2. 36) What is DCLGEN ? DeCLarations GENerator: used to create the host language copy books for the table definitions.

Assuming that a site’s standard is that pgm name = plan name.PLAN_TABLE 47) EXPLAIN has output with MATCHCOLS = 0. SQLERRM. An example is shown: DSN SYSTEM(DSP3) RUN PROGRAM(EDD470BD) PLAN(EDD470BD) LIB('ED 01T. 42) Name some fields from SQLCA. what is the easiest way to find out which pgms are affected by change in a table’s structure ? Query the catalogue tables SYSPLANDEP and SYSPACKDEP. 45) What do you need to do before you do EXPLAIN? Make sure that the PLAN_TABLE is created under the AUTHID. Use DSN utility to run a DB2 batch program from native TSO. 44) What is EXPLAIN? – EXPLAIN is used to display the access path as determined by the optimizer for a SQL statement. It can be used in SPUFI (for single SQL statement ) or in BIND step (for embedded SQL ). if DB2 is down? No. 41) How is a typical DB2 batch pgm executed ? 1. Include EXPLAIN command in the embedded dynamic SQL statements . Use IKJEFT01 utility program to run the above DSN command in a JCL.OBJ. SQLERRD 43) How can you quickly find out the # of rows updated after an update statement? Check the value stored in SQLERRD(3). 46) Where is the output of EXPLAIN stored? – In userid. Because the precompiler does not refer to the DB2 catalogue tables. 48) How do you do the EXPLAIN of a dynamic SQL statement? 1. Use SPUFI or QMF to EXPLAIN the dynamic SQL statement 2.LOADLIB') END 2. SQLCODE. What does it mean? – a nonmatching index scan if ACCESSTYPE = I.40) Will precompile of an DB2-COBOL program bomb.

SELECT EMP_NAME FROM EMP WHERE EMP_SALARY > ? 50) What are the isolation levels possible ? – CS: Cursor Stability RR: Repeatable Read 51) What is the difference between CS and RR isolation levels? CS: Releases the lock on a page after use RR: Retains all locks acquired till end of transaction 52) Where do you specify them ? ISOLATION LEVEL is a parameter for the bind process.. I use CS and update a page. ISOLATION ( CS/RR ). TABLESPACE 55) How does DB2 determine what lock-size to use? 1. DB2 usually chooses a lock-size of PAGE 56) What are the disadvantages of PAGE level lock? High resource utilization if large updates are to be done . Programmer can direct the DB2 what lock-size to use 3. Will the lock be released after I am done with that page? No. e. 54) What are the various locking levels available? PAGE.49) How do you simulate the EXPLAIN of an embedded SQL statement in SPUFI/QMF? Give an example with a host variable in WHERE clause. 53) When do you specify the isolation level? How? During the BIND process.g. TABLE.. Based on the lock-size given while creating the tablespace 2. If lock-size ANY is specified.) Use a question mark in place of a host variable ( or an unknown value ).

. take lock on the underlying tables. PLAN: A result of the BIND process. Avoid the entire transaction being unavailable during bind and automatic rebind of a plan 4. EXCLUSIVE. 63) What else is there in the PLAN apart from the access path? – PLAN has the executable code for the SQL statements in the host program 64) What happens to the PLAN if index used by it is dropped? Plan is marked as invalid. To lock a view. including intent locks. It has the executable code for the SQL statements in the DBRM. The next time the plan is accessed. Locks should be taken on objects in single tablespace for escalation to occur. 66) What are the advantages of using a PACKAGE? 1. 65) What are PACKAGES ? – They contain executable code for SQL statements for one DBRM. it is rebound. 61) What is a DBRM. has the SQL statements extracted from the host language program by the pre-compiler. Minimize fallback complexities if changes result in an error. 58) What are the various locks available? SHARE. Avoid cost of a large bind 3. Avoid having to bind a large number of DBRM members into a plan 2.57) What is lock escalation? Promoting a PAGE lock-size to table or tablespace lock-size when a transaction has acquired more locks than specified in NUMLKTS. PLAN ? DBRM: DataBase Request Module. 62) What is ACQUIRE/RELEASE in BIND? Determine the point at which DB2 acquires or releases locks against table and tablespaces. 60) What is ALTER ? – SQL command used to change the definition of DB2 objects. UPDATE 59) Can I use LOCK TABLE on a view? No.

Probably RUNSTATS is done and optimizer has chosen a wrong access path based on the latest statistics.67) What is a collection? a user defined name that is the anchor for packages. but the select returns only 200 rows. DO a REORG of the indexes. 76) How do you retrieve the data from a nullable column? – Use null indicators. when the PREPARE statement is issued. I find that the performance has deteriorated. Main usage is to group packages. What do you do? – Looks like index page split has occurred. It has not physical existence. 75) How does DB2 store NULL physically? as an extra-byte prefix to the column value. the nul prefix is Hex ’00’ if the value is present and Hex ‘FF’ if it is not. Syntax .. INTO :HOSTVAR:NULLIND . 73) When is the access path determined for dynamic SQL? – At run time. of 1000 rows . What happened? – Probably RUN STATS is not done and the program is using a wrong index due to incorrect stats. 68) What are the 2 sqlcodes that are returned? – 100 ( for successful completion of the query ). 0 (for successful COMMIT if AUTOCOMMIT is set to Yes). 72) What is dynamic SQL? – Dynamic SQL is a SQL statement created at program execution time. Off late. 70) How do you pull up a query which was previously saved in QMF ? – ?? 71) Lot of updates have been done on a table due to which indexes have gone haywire. 74) Suppose I have a program which uses a dynamic SQL and it has been performing well till now. 69) How would you print the output of an SQL statement from SPUFI? – Print the output dataset.. In SPUFI suppose you want to select max. physically.

84) What is IMAGECOPY ? – It is full backup of a DB2 table which can be used in recovery. 85) When do you use the IMAGECOPY? – To take routine backup of tables . move -1 to the null indicator To insert a valid value. inserts. or after mass updates. It also collects statistics used for space management. to reclaim space. 78) What does it mean if the null indicator has -1. or after REORG. 81) When will you chose to run RUNSTATS? After a load. inserts and delete activity and after segments of a segmented tablespace have become fragmented. move 0 to the null indicator 80) What is RUNSTATS? – 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 is used after heavy updates. 82) Give some example of statistics collected during RUNSTATS? # of rows in the table Percent of rows in clustering sequence # of distinct values of indexed column # of rows moved to a nearby/farway page due to row length increase 83) What is REORG? When is it used? REORG reorganizes data on physical storage to reclutser rows. positioning overflowed rows in their proper sequence. to restore free space. These statistics are stored in DB2 catalog tables.77) What is the picture clause of the null indicator variable? – S9(4) COMP. -2? – -1 : the field is null 0 : the field is not null -2 : the field value is truncated 79) How do you insert a record with a nullable column? To insert a NULL. 0. deletes.

88) What is QUIESCE? A QUIESCE flushes all DB2 buffers on to the disk. 95) Are views updateable ? . the table is available only for queries. 91) What is the difference between primary key & unique index ? Primary : a relational database constraint.After a LOAD with LOG NO After REORG with LOG NO 86) What is COPY PENDING status? A state in which. 90) How many clustering indexes can be defined for a table? Only one. For a normalized relation. Unique index: a physical object that stores only unique values. then the table is left in CHECK PENDING status. To remove the COPY PENDING status. This gives a correct snapshot of the database and should be used before and after any IMAGECOPY to maintain consistency. There can be one or more unique indexes on a table. A mandatory index defined on a partitioned table space. 89) What is a clustering index ? – Causes the data rows to be stored in the order specified in the index. an image copy on a table needs to be taken. 94) What does the sqlcode of -818 pertain to? – This is generated when the consistency tokens in the DBRM and the load module are different. you take an image copy or use REPAIR utility. Primary key consists of one or more columns that uniquely identify a row in the table. there is one designated primary key. It means that the LOAD utility did not perform constraint checking. You cannot update this table. In this status. 87) What is CHECK PENDING ? When a table is LOADed with ENFORCE NO option. 92) What is sqlcode -922 ? Authorization failure 93) What is sqlcode -811? SELECT statement has resulted in retrieval of more than one row.

it can be simulated by combining a join and a correlated sub query with a UNION. Some views are updateable e. 99) What is FREEPAGE and PCTFREE in TABLESPACE creation? PCTFREE: percentage of each page to be left free FREEPAGE: Number of pages to be loaded with data between each free page 100) What are simple. 96) If I have a view which is a join of two or more tables. Outer join is one in which you want both matching and non matching rows to be returned.Not all of them. CICS.g. Examples of non-updateable views are views which are joins. IMS and BATCH 98) What is an inner join. can this view be updateable? – No. DB2 has no specific operator for outer joins. and an outer join ? 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. and views that have GROUP BY clause. segmented and partitioned table spaces ? Simple Tablespace: Can contain one or more tables Rows from multiple tables can be interleaved on a page under the DBAs control and maintenance Segmented Tablespace: Can contain one or more tables Tablespace is divided into segments of 4 to 64 pages in increments of 4 pages. 101) What is filter factor? . single table view with all the fields or mandatory fields. 97) What are the 4 environments which can access DB2 ? TSO. A table can occupy multiple segments Partitioned Tablespace: Can contain one table Tablespace is divided into parts and each part is put in a separate VSAM dataset. Each segment is dedicated to single table. views that contain aggregate functions(such as MIN). This kind of join which involve a match in both columns are called inner joins.

spaces or date/time depending on whether it is numeric. 102) What is index cardinality? – The number of distinct values a column or columns contain. 108) What are the disadvantages of using VARCHAR? 1. Relocation of rows to different pages can lead to more I/Os on retrieval. 2. 105) What do you mean by NOT NULL WITH DEFAULT? When will you use it? This column cannot have nulls and while insertion.g. When is the authorization check on DB2 objects done . 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. MANAGER) where MANAGER is a foreign key which references to EMP# in the same table? Give the exact DDL. Then ALTER it to define the foreign key. 103) What is a synonym ? Synonym is an alternate name for a table or view used mainly to hide the leading qualifier of a table or view. 107) When would you prefer to use VARCHAR? When a column which contains long text. ALIAS can be created even if the table does not exist. remarks. Can lead to high space utilization if most of the values are close to maximum. 106) What do you mean by NOT NULL? When will you use it? The column cannot have nulls. 104) What is the difference between SYNONYM and ALIAS? SYNONYM: is dropped when the table or tablespace is dropped.. e.at BIND time or run time? . 3.one divided by the number of distinct values of a column. if no value is supplied then it wil have zeroes. It is used mainly in distributed environment to hide the location info from programs. notes. may have in most cases less than 50% of the maximum length. Positioning of VARCHAR column has to be done carefully as it has performance implications. A synonym is accessible only by the creator. ALIAS: is retained even if table or tablespace is dropped. Use it for key fields. Alias is a global object & is available to all. character or date/time. First CREATE MANAGER table with EMP# as the primary key. 109) How do I create a table MANAGER ( EMP#. Synonym is available only to the creator.

Specified at table creation time or through alter. 110) What is auditing? Recording SQL statements that access a table.At run time. .