Sie sind auf Seite 1von 138

The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table


ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
TRUNCATE - cleans all data
RENAME- renames a table name
2. Operators used in SELECT statements.
= Equal
<> or != Not equal
> Greater than
<>= Greater than or equal
<= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern
3. SELECT statements:
SELECT column_name(s) FROM table_name
SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column)
condition value
Note that single quotes around text values and numeric values should not be enclosed in quotes.
Double quotes may be acceptable in some databases.
4. The SELECT INTO Statement is most often used to create backup copies of tables or for
archiving records.
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE
column_name operator value
5. The INSERT INTO Statements:
INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
6. The Update Statement:
UPDATE table_name SET column_name = new_value WHERE column_name = some_value
7. The Delete Statements:
DELETE FROM table_name WHERE column_name = some_value
Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name
8. Sort the Rows:
SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..

SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC


SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC
9. The IN operator may be used if you know the exact value you want to return for at least one of
the columns.
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
10. BETWEEN ... AND
SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND
value2 The values can be numbers, text, or dates.
11. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a
child table exists.
12. Why does the following command give a compilation error?
DROP TABLE &TABLE NAME; Variable names should start with an alphabet. Here the table
name starts with an '&' symbol.
13. Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
14. Which system table contains information on constraints on all the tables created?obtained?
USER_CONSTRAINTS.
15. State true or false. !=, <>, ^= all denote the same operation?
True.
16. State true or false. EXISTS, SOME, ANY are operators in SQL?
True.
17. What will be the output of the following query?
SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN',
'**'),'*','TROUBLE') FROM DUAL;?
18. What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;?
This displays the total salary of all employees. The null values in the commission column will be
replaced by 0 and added to salary.
19. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
The privilege receiver can further grant the privileges he/she has obtained from the owner to
any other user.
20. Which command executes the contents of a specified file?

START or @.
21. What is the value of comm and sal after executing the following query if the initial value of
sal is 10000
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?
sal = 11000, comm = 1000.
22. Which command displays the SQL command in the SQL buffer, and then executes it?
RUN.
23. What command is used to get back the privileges offered by the GRANT command?
REVOKE.
24. What will be the output of the following query? SELECT
DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.
Explanation : The query checks whether a given string is a numerical digit.
26. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.
27. What operator performs pattern matching?
LIKE operator.
28. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
29. What operator tests column for the absence of data?
IS NULL operator.
30. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all.
31. Which function is used to find the largest integer less than or equal to a specific value?
FLOOR.
32. Which is the subset of SQL commands used to manipulate Oracle Database structures,
including tables?
Data Definition Language (DDL).
33. What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in
descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on
ENAME in descending order.

34. What command is used to create a table by copying the structure of another table?
CREATE TABLE .. AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain a
FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied
to the new table.
35. TRUNCATE TABLE EMP;DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP..
36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?
1200.
37. What are the wildcards used for pattern matching.?
_ for single character substitution and % for multi-character substitution.
38. What is the parameter substitution symbol used with INSERT INTO command?
&
39. What's an SQL injection?
SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query
to be run.
40. What is difference between TRUNCATE & DELETE
TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do
not fire on TRUNCATE
DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database
triggers fire on DELETE.
41. What is a join? Explain the different types of joins?
Join is a query, which retrieves related columns or rows from multiple tables.
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have
corresponding join value in the other table.
42. What is the sub-query?
Sub-query is a query whose return values are used in filtering conditions of the main query.
43. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.


44. Explain CONNECT BY PRIOR?
Retrieves rows in hierarchical order eg.
select empno, ename from emp where.
45. Difference between SUBSTR and INSTR?
INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins
from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.
46. Explain UNION, MINUS, UNION ALL and INTERSECT?
INTERSECT - returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query, including all duplicates.
47. What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno,
rownumber are the components of ROWID.
48. What is the fastest way of accessing a row in a table?
Using ROWID.
CONSTRAINTS
49. What is an integrity constraint?
Integrity constraint is a rule that restricts values to a column in a table.
50. What is referential integrity constraint?
Maintaining data integrity through a set of rules that restrict the values of one or more columns
of the tables based on the values of primary key or unique key of the referenced table.
51. What is the usage of SAVEPOINTS?
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part
of a transaction. Maximum of five save points are allowed.
52. What is ON DELETE CASCADE?
When ON DELETE CASCADE is specified Oracle maintains referential integrity by
automatically removing dependent foreign key values if a referenced primary or unique key
value is removed.
53. What are the data types allowed in a table?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for
each type?
CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.
For CHAR the maximum length is 255 and 2000 for VARCHAR2.
55. How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or
ORDER BY clause.
56. What are the pre-requisites to modify datatype of a column and to add a column with NOT
NULL constraint?
- To modify the datatype of a column the column must be empty.
- To add a column with NOT NULL constrain, the table must be empty.
57. Where the integrity constraints are stored in data dictionary?
The integrity constraints are stored in USER_CONSTRAINTS.
58. How will you activate/deactivate integrity constraints?
The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE
CONSTRAINT / DISABLE CONSTRAINT.
59. If unique key constraint on DATE column is created, will it validate the rows that are
inserted with SYSDATE?
It won't, Because SYSDATE format contains time attached with it.
60. What is a database link?
Database link is a named path through which a remote database can be accessed.
61. How to access the current value and next value from a sequence? Is it possible to access the
current value in a session before accessing next value?
Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next
value in the session, current value can be accessed.
62.What is CYCLE/NO CYCLE in a Sequence?
CYCLE specifies that the sequence continue to generate values after reaching either maximum
or minimum value. After pan-ascending sequence reaches its maximum value, it generates its
minimum value. After a descending sequence reaches its minimum, it generates its maximum.
NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum
or minimum value.
63. What are the advantages of VIEW?
- To protect some of the columns of a table from other users.

- To hide complexity of a query.


- To hide complexity of calculations.
64. Can a view be updated/inserted/deleted? If Yes - under what conditions?
A View can be updated/deleted/inserted if it has only one base table if the view is based on
columns from one or more tables then insert, update and delete is not possible.
65. If a view on a single base table is manipulated will the changes be reflected on the base table?
If changes are made to the tables and these tables are the base tables of a view, then the changes
will be reference on the view.
66. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.
67. Which of the following is not a feature of a cursor FOR loop?
1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.
66. A developer would like to use referential datatype declaration on a variable. The variable
name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and
LNAME, respectively. How would the developer define this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.
67. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype
68. If left out, which of the following would cause an infinite loop to occur in a simple loop?
1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT
69. Which line in the following statement will produce an error?

1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.
70. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.
71. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values
72. Read the following code:
10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT
73. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;
The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3.
Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75

3. WHERE (new.cost_per_ticket > 3.75)


4. WHERE (:new.cost_per_ticket > 3.75)
74. What is the maximum number of handlers processed before the PL/SQL block is exited
when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None
77. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger
78. Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;
RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
31. CREATE OR REPLACE PROCEDURE update_theater
32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33. BEGIN
34. UPDATE theater
35. SET name = v_name
36. WHERE id = v_theater_id;
37. END update_theater;
79. When invoking this procedure, you encounter the error:
ORA-000:Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. An user defined exception must be declared and associated
with the error code and handled in the EXCEPTION section.

2. Handle the error in EXCEPTION section by referencing the error


code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined
exception.
4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE
statement.
80. Read the following code:
40. CREATE OR REPLACE PROCEDURE calculate_budget IS
41. v_budget studio.yearly_budget%TYPE;
42. BEGIN
43. v_budget := get_budget(11);
44. IF v_budget < 30000
45. THEN
46. set_budget(11,30000000);
47. END IF;
48. END; You are about to add an argument to CALCULATE_BUDGET.
What effect will this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled before the next
execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled before the next
execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.
81. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR
82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command
can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;
83. Examine this database trigger
52. CREATE OR REPLACE TRIGGER prevent_gross_modification
53. {additional trigger information}
54. BEGIN
55. IF TO_CHAR(sysdate, DY) = MON
56. THEN
57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);

58. END IF;


59. END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only
once for the entire DELETE statement. What additional information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt
84. Examine this function:
61. CREATE OR REPLACE FUNCTION set_budget
62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
63. BEGIN
64. UPDATE studio
65. SET yearly_budget = v_new_budget WHERE id = v_studio_id; IF SQL%FOUND THEN
RETURN TRUEl; ELSE RETURN FALSE; END IF; COMMIT; END; Which code must be added
to successfully compile this function?
1. Add RETURN right before the IS keyword.
2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.
85. Under which circumstance must you recompile the package body after recompiling the
package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package constructs
86. Procedure and Functions are explicitly executed. This is different from a database trigger.
When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed
87. Which Oracle supplied package can you use to output values and messages from database
triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY
2. DBMS_OUTPUT
3. DBMS_LIST
4. DBMS_DESCRIBE
88. What occurs if a procedure or function terminates with failure without being handled?
1. Any DML statements issued by the construct are still pending and can be committed or rolled

back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section,the
construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled exception to
the calling environment.
89. Examine this code
71. BEGIN
72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73. END; For this code to be successful, what must be true?
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR
function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the
THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the
THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR
function must exist in the specification of the THEATER_PCK package.
90. A stored function must return a value based on conditions that are determined at runtime.
Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when
the function is executed. Which Oracle supplied package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL
91 How to implement ISNUMERIC function in SQL *Plus ? Method
1: Select length (translate(trim (column_name),'+-.0123456789',''))from dual; Will give you a
zero if it is a number or greater than zero if not numeric (actually gives the count of non numeric
characters) Method 2: select instr(translate('wwww','abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
X XXXXXXXXXXXXXXXXX'),'X') FROM dual; It returns 0 if it is a number, 1 if it is not.
92 How to Select last N records from a Table? select * from (select rownum a,
CLASS_CODE,CLASS_DESC from clm) where a > ( select (max(rownum)-10) from clm) Here N
= 10
The following query has a Problem of performance in the execution of the following
query where the table ter.ter_master have 22231 records. So the results are obtained
after hours.
Cursor rem_master(brepno VARCHAR2) IS
select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno = 'ALL' or a.repno > brepno)

Order by a.repno
What are steps required tuning this query to improve its performance?
-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO
-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution
path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that
your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:
SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno = 'ALL' or a.repno > a.brepno)
ORDER BY a.repno;
93. What is the difference between Truncate and Delete interms of Referential Integrity?
DELETE removes one or more records in a table, checking referential Constraints (to see if there
are dependent child records) and firing any DELETE triggers. In the order you are deleting
(child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it
only checks for the existence (and status) of another foreign key Pointing to the
table. If one exists and is enabled, then you will get The following error. This
is true even if you do the child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing
the TRUNCATE command, then re-enable them afterwards.
1. Describe the difference between a procedure, function and anonymous pl/sql block.
Level: Low
Expected answer : Candidate should mention use of DECLARE statement, a function
must
return a value while a procedure doesn?t have to.
2. What is a mutating table error and how can you get around it?
Level: Intermediate
Expected answer: This happens with triggers. It occurs because the trigger is trying
to update a row it is currently using. The usual fix involves either use of views
or temporary tables so the database is selecting from one while updating the other.
3. Describe the use of %ROWTYPE and %TYPE in PL/SQL
Level: Low
Expected answer: %ROWTYPE allows you to associate a variable with an entire table
row.
The %TYPE associates a variable with a single column type.
4. What packages (if any) has Oracle provided for use by developers?
Expected answer: Oracle provides the DBMS_ series of packages. There are many
which developers should be aware of such as DBMS_SQL, DBMS_PIPE,

DBMS_TRANSACTION,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY,
DBMS_DDL, UTL_FILE. If
they can mention a few of these and describe how they used them, even better. If
they include the SQL routines provided by Oracle, great, but not really what
was asked.
5. Describe the use of PL/SQL tables
Expected answer: PL/SQL tables are scalar arrays that can be referenced by a
binary integer. They can be used to hold values for use in later queries
or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation,
or RECORD.
6. When is a declare statement needed ?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone,
non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is
used.
7. In what order should a open/fetch/loop set of commands in a PL/SQL block be
implemented if you use the NOTFOUND cursor variable in the exit when statement?
Why?
Expected answer: OPEN then FETCH then LOOP followed by the exit when. If not
specified in this order will result in the final return being done twice because of the way
the %NOTFOUND is handled by PL/SQL.
8. What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
Expected answer: SQLCODE returns the value of the error number for the last error
encountered. The SQLERRM returns the actual error message for the last error
encountered. They can be used in exception handling to report, or, store in an error log
table, the error that occurred in the code. These are especially useful for the WHEN
OTHERS exception.
9. How can you find within a PL/SQL block, if a cursor is open?
Expected answer: Use the %ISOPEN cursor status variable.
10. How can you generate debugging output from PL/SQL?
Expected answer: Use the DBMS_OUTPUT package. Another possible method is to just
use the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT
package can be used to show intermediate results from loops and the status of variables
as the procedure is executed. The new package UTL_FILE can
also be used.
11. What are the types of triggers?
Expected Answer: There are 12 types of triggers in PL/SQL that consist of

combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and
ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT etc.
2. How can variables be passed to a SQL routine?
Expected answer: By use of the & symbol. For passing in variables the numbers
1-8 can be used (&1, &2,...,&8) to pass the values after the command into the
SQLPLUS session. To be prompted for a specific variable, place the ampersanded
variable in the code itself:
"select * from dba_tables where owner=&owner_name;" . Use of double
ampersands tells SQLPLUS to resubstitute the value for each subsequent
use of the variable, a single ampersand will cause a reprompt for the
value unless an ACCEPT statement is used to get the value from the user.
2. You want to include a carriage return/linefeed in your output from a SQL script, how
can you do this?
Expected answer: The best method is to use the CHR() function (CHR(10) is a
return/linefeed) and the concatenation function "". Another method, although it is hard
to document and isn?t always portable is to use the return/linefeed as a part of a quoted
string.
3. How can you call a PL/SQL procedure from SQL?
Expected answer: By use of the EXECUTE (short form EXEC) command.
4. How do you execute a host operating system command from within SQL?
Expected answer: By use of the exclamation point "!" (in UNIX and some other OS) or
the HOST (HO) command.
5. You want to use SQL to build SQL, what is this called and give an example
Expected answer: This is called dynamic SQL. An example would be:
set lines 90 pages 0 termout off feedback off verify off
spool drop_all.sql
select ?drop user ?username? cascade;? from dba_users
where username not in ("SYS?,?SYSTEM?);
spool off
Essentially you are looking to see that they know to include a command (in this case
DROP USER...CASCADE;) and that you need to concatenate using the ?? the values
selected from the database.
6. What SQLPlus command is used to format output from a select?
Expected answer: This is best done with the COLUMN command.
7. You want to group the following set of select returns, what can you group on?

Max(sum_of_cost), min(sum_of_cost), count(item_no), item_no


Expected answer: The only column that can be grouped on is the "item_no" column, the
rest have aggregate functions associated with them.
8. What special Oracle feature allows you to specify how the cost based system treats a
SQL statement?
Level: Intermediate to high Expected answer: The COST based system allows the use of
HINTs to control the optimizer path selection. If they can give some example hints such
as FIRST ROWS, ALL ROWS, USING INDEX, STAR, even better.
9. You want to determine the location of identical rows in a table before attempting to
place a unique index on the table, how can this be done?
Level: High Expected answer: Oracle tables always have one guaranteed unique column,
the rowid column. If you use a min/max function against your rowid and then select
against the proposed primary key you can squeeze out the rowids of the duplicate rows
pretty quick. For example: select rowid from emp e where e.rowid > (select min(x.rowid)
from emp x where x.emp_no = e.emp_no); In the situation where multiple columns
make up the proposed key, they must all be used in the where clause.
10. What is a Cartesian product?
Expected answer: A Cartesian product is the result of an unrestricted join of two or more
tables. The result set of a three table Cartesian product will have x * y * z number of rows
where x, y, z correspond to the number of rows in each table involved in the join.
11. You are joining a local and a remote table, the network manager complains about the
traffic involved, how can you reduce the network traffic?
Level: High Expected answer: Push the processing of the remote data to the remote
instance by using a view to pre-select the information for the join. This will result in only
the data required for the join being sent across.
12. What is the default ordering of an ORDER BY clause in a SELECT statement?
Expected answer: Ascending
13. What is tkprof and how is it used?
Level: Intermediate to high Expected answer: The tkprof tool is a tuning tool used to
determine cpu and execution times for SQL statements. You use it by first setting
timed_statistics to true in the initialization file and then turning on tracing for either the
entire database via the sql_trace parameter or for the session using the ALTER SESSION
command. Once the trace file is generated you run the tkprof tool against the trace file
and then look at the output from the tkprof tool. This can also be used to generate
explain plan output.
14. What is explain plan and how is it used?
Level: Intermediate to high Expected answer: The EXPLAIN PLAN command is a tool to
tune SQL statements. To use it you must have an explain_table generated in the user you

are running the explain plan for. This is created using the utlxplan.sql script. Once the
explain plan table exists you run the explain plan command giving as its argument the
SQL statement to be explained. The explain_plan table is then queried to see the
execution plan of the statement. Explain plans can also be run using tkprof.
15. How do you set the number of lines on a page of output? The width?
Level: Low Expected answer: The SET command in SQLPLUS is used to control the
number of lines generated per page and the width of those lines, for example SET
PAGESIZE 60 LINESIZE 80 will generate reports that are 60 lines long with a line width
of 80 characters. The PAGESIZE and LINESIZE options can be shortened to PAGES and
LINES.
16. How do you prevent output from coming to the screen?
Level: Low
Expected answer: The SET option TERMOUT controls output to the screen. Setting
TERMOUT OFF turns
off screen output. This option can be shortened to TERM.
17. How do you prevent Oracle from giving you informational messages during and after
a SQL statement execution?
Level: Low Expected answer: The SET options FEEDBACK and VERIFY can be set to
OFF.
18. How do you generate file output from SQL?
Answer: By use of the SPOOL command
1. Write a query to copy table structure without the data.
CREATE TABLE emp_new AS
SELECT * FROM emp WHERE 1 = 2;
2. Write a query to rename a column phone to phone_number.
CREATE TABLE emp_new (emp_id, emp_name, address, phone_number, salary) AS
SELECT emp_id, emp_name, address, phone, salary FROM emp;
DROP TABLE emp;
RENAME emp_new TO emp;
3. Write a query to display 1 row selected while there is no data in the table.
SELECT COUNT(*) FROM emp;
4. Write a query which display emp_id & emp_name along with an extra field * & All
Employees like this.
Employee Code
Employee Name
*
All Employees
E001
Susheel
E002

Jain
SELECT emp_id "Employee Code", emp_name "Employee Name" FROM emp
UNION
SELECT '*' "Employee Code", 'All Employees' "Employee Name" FROM emp
ORDER BY 1;
5. Write a query to display alternate odd or even rows.
SELECT * FROM emp WHERE (ROWID, 0) NOT IN
(SELECT ROWID, MOD(ROWNUM, 2) FROM emp);
6. Display the name of employees and their managers from emp table by using self
join
SELECT e.emp_name, m.emp_name FROM emp e, emp m WHERE e.manager_id =
m.emp_id
ORDER BY e.emp_id;
7. Write a query to display the departments and no. of employees working in those
departments
SELECT dept_id, COUNT(emp_id) FROM emp GROUP BY dept_id;
8. Write a query which displays those entries which are not duplicate.
SELECT * FROM emp WHERE ROWID NOT IN(SELECT MIN(ROWID) FROM emp GROUP
BY emp_id);
9. Write a query which display emp_id and min & max salary in same column like
this.
Employee
Salary
E001
1,000 min(salary)
E005
10,000 max(salary)
SELECT emp_id "Employee", salary "Salary" FROM emp
WHERE salary = (SELECT MIN(salary) FROM emp)
UNION
SELECT emp_id "Employee", salary "Salary" FROM emp
WHERE salary = (SELECT MAX(salary) FROM emp);
SELECT emp_id, salary FROM emp
WHERE salary <= all (SELECT salary FROM emp)
UNION
SELECT emp_id, salary FROM emp
WHERE salary >= all (SELECT salary FROM emp);
10. Write a query to display nearest min and nearest max from average salary.

SELECT emp_id, salary FROM emp WHERE salary <= (SELECT MAX(salary) FROM
emp WHERE salary = (SELECT AVG(salary) FROM emp))
UNION
SELECT emp_id, salary FROM emp WHERE salary >= (SELECT MIN(salary) FROM
emp WHERE salary = (SELECT AVG(salary) FROM emp));
11. Display the list of top n employees getting highest salary
SELECT empno, sal FROM (SELECT empno, sal FROM emp ORDER BY sal DESC)
WHERE rownum < = &n;
12. Find Maximum salary Department and Employee wise
SELECT a.empno, a.deptno, b.sal
FROM emp a, (SELECT * FROM (SELECT empno, deptno, sal, dense_rank()
over(partition by deptno order by sal desc) rn FROM emp)) b
WHERE a.deptno = b.deptno(+) AND b.empno(+) = a.empno AND b.rn(+) = 1;
13. Display the list of employee getting nth highest salary.
SELECT empno, sal FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM <= &n
MINUS
SELECT empno, sal FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM <= &n-1;
OR,
SELECT rn, empno, sal FROM (SELECT rownum rn, empno, sal FROM
(SELECT empno, sal FROM emp ORDER BY sal DESC)) WHERE rn = &n;
OR,
SELECT DISTINCT a.empno, a.sal FROM emp a WHERE &n =
(SELECT COUNT(DISTINCT b.sal) FROM emp b WHERE a.sal <= b.sal);
OR,
SELECT * FROM (SELECT empno,sal,rank() over (ORDER BY sal DESC) rnk FROM
emp)
WHERE rnk <= &n;
OR,
SELECT level, max(salary) FROM emp WHERE level = &n
CONNECT BY PRIOR salary > salary GROUP BY level;
14. Delete duplicate entries from a table.
DELETE FROM emp WHERE ROWID NOT IN
(SELECT MIN(ROWID) FROM emp GROUP BY emp_id);
15. Delete the entries from emp table which are not matching from emp_history
table by using correlated subquery.
DELETE FROM emp e WHERE (e.emp_id, e.manager_id, e.salary) NOT IN
(SELECT h.emp_id, h.manager_id, h.salary FROM emp_history h

WHERE e.emp_id = h.emp_id AND e.manager_id = h.manager_id AND e.salary =


h.salary);
16. Select last name from emp table of an employee while name is given full.
SELECT LTRIM(SUBSTR(name,INSTR(name,' ',1)),' ') FROM emp;
18. Write a query which shows all data if the NULL is also exists while passing NULL.
SELECT t.*, t.rowid FROM emp t WHERE NVL(t.empno,0) =
NVL(&emp,nvl(t.empno,0));
19. Update the name of an employee in swaping manner for eg. If name is amit
then rehan and rehan then amit by single update.
UPDATE emp SET empname = DECODE(empname, 'Amit', 'Rehan', 'Rehan', 'Amit');
20. Write a query to sort all columns independently
select tab_x.a, tab_y.b
from (select tab_a.a, rownum r1
from (select a from a_1 order by 1) tab_a) tab_x,
(select tab_b.b, rownum r2
from (select b from a_1 order by 1) tab_b) tab_y
where tab_x.r1 = tab_y.r2;
21. Write a query to print distinct data in a single row
select a, b, sum(x), 'A' T1, sum(y), 'B' T2
from (select a a, b b, c x, 0 y from a_dummy where d = 'A'
union
select a a, b b, 0 x, C y from a_dummy where d = 'B')
group by a, b;
22. Write a query to select all tables in database does not contain any row.
select table_name, sum(num_nulls + num_distinct) table_rows
from user_tab_columns
group by table_name
having sum(num_nulls + num_distinct) = 0;
OR,
select table_name, num_rows table_rows
from user_tables
where a.num_rows = 0;
23. Write a query to change the amount in different formats.
SELECT ltrim(to_char(&P_AMOUNT,
'999G999G999G999D99',

'NLS_NUMERIC_CHARACTERS = ''.'''''),
' ') amt_converter
FROM dual;
SELECT ltrim(to_char(&P_AMOUNT,
'999999999G999D99MI',
'NLS_NUMERIC_CHARACTERS = '',.'''),
' ') amt_converter
FROM dual;
24. Write a query to convert the amount in words
SELECT to_char(to_date(&P_AMOUNT_LESS_THAN_5373484, 'J'), 'Jsp') || ' Only'
amount_in_word
FROM dual;
25. Write a query to find out number of particular character in a string
SELECT COUNT(NO_OF_CHAR) NO_OF_CHAR
FROM (SELECT UPPER(SUBSTR('&str', ROWNUM, 1)) NO_OF_CHAR
FROM USER_OBJECTS
WHERE ROWNUM <= LENGTH('&str'))
WHERE NO_OF_CHAR = UPPER('&char');
28. Count Numbers, Upper-Lower Characters, and Symbols
-- Just For Numbers
select LENGTH('&STRING') LEN#,
LENGTH(TRANSLATE('&STRING', 'A1234567890', 'A')) "-- Non-Numeric Charcters
--"
from dual;
LEN#
-- Non-Numeric Charcters ----------- --------------------------36
33
-- For Numbers, Upper-Lower Characters, Others
select length('&STRING') - LENGTH(TRANSLATE('&STRING', 'A1234567890', 'A')) "-Numeric --",
LENGTH(TRANSLATE('&STRING', 'A1234567890', 'A')) "-- Non-Numeric Charcters
--",
SUM(length('&STRING') - LENGTH(REPLACE('&STRING', Single_UpperChar)))
Upper#,
SUM(length('&STRING') - LENGTH(REPLACE('&STRING', Single_LowerChar)))
Lower#
from (select CHR(64 + ROWNUM) Single_UpperChar,
CHR(96 + ROWNUM) Single_LowerChar
from all_synonyms
where rownum < 27);

-- Numeric -- -- Non-Numeric Charcters -- UPPER# LOWER#


------------- --------------------------- ------ -------3
33
7
18
29. Write a query to display total vowels and consonants in a string
SELECT LENGTH(REGEXP_REPLACE('&STR', '([aeiouAEIOU])|.', '\1')) tot_vowels,
LENGTH(REGEXP_REPLACE('&STR',
'([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])|.',
'\1')) tot_consonants
FROM DUAL;
What are the components of a PL/SQL Block?
Declarative part
Executable part
Exception part
What are the datatypes a available in PL/SQL?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG,
BOOLEAN. Some composite data types such as RECORD & TABLE.
What are % TYPE and % ROWTYPE? What are the advantages of using these over
datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.
The advantages are:
I. Need not know about variables data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
What is difference between % ROWTYPE and TYPE RECORD?
% ROWTYPE is to be used whenever query returns an entire row of a table or view. TYPE
RECORD is to be used whenever query returns columns of different table or views and
variables.
Explain the two types of Cursors?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.
What are the cursor attributes used in PL/SQL?
% ISOPEN Used to check whether a cursor is open or not.
% ROWCOUNT Used to check the number of rows fetched/updated/deleted.
% FOUND Used to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND Used to check whether cursor has fetched any row. True if no rows are
fetched.
What is a cursor for loop?

Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of
values from active set into fields in the record and closes when all the records have been
processed.
What is the difference between implicit and explicit cursors?
An explicit cursor is declared opened and fetched from in the program block where as an implicit
cursor is automatically generated for SQL statements that process a single row only.
What are the different types of joins available in Oracle?
Equi Join: When primary and foreign key relationship exists between the tables that are going to
be joined.
Self Join: If comparison comes in a single table
Cartesian Join: When tables are joined without giving any join condition.
Inner Join: The resultant set includes all the rows that satisfy the join condition.
Outer Join: The resultant set includes the rows which doesnt satisfy the join condition. The
outer join operator Plus sign (+) will be included in the join condition.
What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM
returns the actual error message for the last error encountered. They can be used in exception
handling to report, or, store in an error log table, the error that occurred in the code. These are
especially useful for the WHEN OTHERS exception.
What is an autonomous transaction?
An autonomous transaction is an independent transaction that is initiated by another transaction
(the parent transaction). An autonomous transaction can modify data and commit or rollback
independent of the state of the parent transaction.
What is the difference between View and Materialized view?
Materialized view will not be refreshed every time you query the view. So to have good
performance when data is not changed so rapidly, we use Materialized views rather than normal
views which always fetches data from tables every time you run a query on it.
What is dynamic SQL?
Dynamic SQL allows you to construct a query, a DELETE statement, a CREATE TABLE
statement, or even a PL/SQL block as a string and then execute it at runtime.
Can you use COMMIT in a trigger?
Yes but by defining an autonomous transaction.
What is the difference between anonymous blocks and stored procedures?
Anonymous block is compiled only when called. Stored procedure is compiled and stored in
database with the dependency information as well. Former is PL/SQL code directly called from
an application. Latter is stored in database. Former has declare statement. Latter doesnt.
What is a package spec and package body? Why the separation?
Spec declares public constructs. Body defines public constructs, additionally declares and
defines Private constructs.
Separation helps make development easier. Dependency is simplified. You can modify body
without invalidating dependent objects.

What is Correlated Subquery?


Correlated Subquery is a subquery that is evaluated once for each row processed by the parent
statement. Parent statement can be Select, Update or Delete.
What is Sequence?
Sequences are used for generating sequence numbers without any overhead of locking.
Drawback is that after generating a sequence number if the transaction is rolled back, then that
sequence number is lost.
What is SQL Deadlock?
Deadlock is a unique situation in a multi user system that causes two or more users to wait
indefinitely for a locked resource. First user needs a resource locked by the second user and
the second user needs a resource locked by the first user. To avoid dead locks, avoid using
exclusive table lock and if using, use it in the same sequence and use Commit frequently to
release locks.
What is SQL*Loader?
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To
load data from external files into an Oracle database, two types of input must be provided to
SQL*Loader: the data itself and the control file.
What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a
child table exists.
Explain forward declaration used in functions?
A forward declaration means that modules (procedures and functions) are declared in
advance of their actual body definition. This declaration makes that module available to be
called by other modules even before the programs body is defined. A forward declaration
consists simply of the module header, which is just the name of the module followed by the
parameter list (and a RETURN clause in case the module is a function), no more no less.
Forward declarations are required in one specific situation: mutual recursion.
What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM
returns the actual error message for the last error encountered. They can be used in exception
handling to report, or, store in an error log table, the error that occurred in the code. These are
especially useful for the WHEN OTHERS exception.
What is the difference between Truncate and Delete Commands?
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE
operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause
can be used with DELETE and not with TRUNCATE.
What is the Purpose of HAVING Clause?
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
What is INLINE View in SQL?

The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM,
clause, just as if the query was a table name.
While creating a sequence, what does cache and nocache options mean?
With respect to a sequence, the cache option specifies how many sequence values will be
stored in memory for faster access.
Does the view exist if the table is dropped from the database?
Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based
on) is dropped from the database. However, if you try to query the view after the table has been
dropped, you will receive a message indicating that the view has errors.
What is an Index?
An index is a performance-tuning method of allowing faster retrieval of records. An index
creates an entry for each value that appears in the indexed columns. By default, Oracle creates
B-tree indexes.
What types of index data structures can you have?
An index helps to faster search values in tables. The three most commonly used index-types
are:

B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value.
Needs a lot of space and is the default index type for most databases.

Bitmap: string of bits for each possible value of the column. Each bit string has one
bit for each row. Needs only little space and is very fast. (However, domain of value
cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD)

Hash: A hashing algorithm is used to assign a set of characters to represent a text


string such as a composite of keys or partial keys, and compresses the underlying data.
Takes longer to build and is supported by relatively few databases.
What is the difference between a where clause and a having clause?
Where is a kind of restriction statement. You use where clause to restrict all the data from DB.
Where clause is used before result retrieving. But Having clause is using after retrieving the
data. Having clause is a kind of filtering command.
Can a view be updated/inserted/deleted? If Yes under what conditions?
A View can be updated/deleted/inserted if it has only one base table if the view is based on
columns from one or more tables then insert, update and delete is not possible.
What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements.
You use it by first setting timed_statistics to true in the initialization file and then turning on
tracing for either the entire database via the sql_trace parameter or for the session using the
ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the
trace file and then look at the output from the tkprof tool. This can also be used to generate
explain plan output.
What is explain plan and how is it used?
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an
explain_table generated in the user you are running the explain plan for. This is created using
the utlxplan.sql script. Once the explain plan table exists you run the explain plan command

giving as its argument the SQL statement to be explained. The explain_plan table is then
queried to see the execution plan of the statement. Explain plans can also be run using tkprof.
What are the Lock types?
Share Lock: It allows the other users for only reading not to insert or update or delete.
Exclusive Lock: Only one user can have the privileges of insert or update and delete of
particular object, others can only read.
Update Lock: Multiple user can read, update delete .
What is Pragma EXECPTION_INIT? Explain the usage?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle
error.
E.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
What is Raise_application_error?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue a
user_defined error messages from stored sub-program or database trigger.
What are the modes for passing parameters to Oracle?
There are three modes for passing parameters to subprograms
IN An In-parameter lets you pass values to the subprogram being called. In the subprogram it
acts like a constant and cannot be assigned a value.
OUT An out-parameter lets you return values to the caller of the subprogram. It acts like an
initialized variable its value cannot be assigned to another variable or to itself.
INOUT An in-out parameter lets you pass initial values to the subprogram being called and
returns updated values to the caller.
What is the difference between Package, Procedure and Functions?
A package is a database objects that logically groups related PL/SQL types, objects, and
Subprograms.
Procedure is a sub program written to perform a set of actions and can return multiple values.
Function is a subprogram written to perform certain computations and return a single value.
Unlike subprograms packages cannot be called, passed parameters or nested.
How do you make a Function and Procedure as a Private?
Functions and Procedures can be made private to a package by not mentioning their
declaration in the package specification and by just mentioning them in the package body.
What is Commit, Rollback and Save point?
Commit Makes changes to the current transaction permanent. It erases the savepoints and
releases the transaction locks.
Savepoint Savepoints allow to arbitrarily hold work at any point of time with option of later
committing. They are used to divide transactions into smaller portions.
Rollback This statement is used to undo work.
What is the difference between DDL, DML and DCL structures?
DDL statements are used for defining data. Ex: Create, Alter, Drop, Truncate, Rename.
DML statements are used for manipulating data. Ex: Insert, update, truncate.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
TCL statements are used for data saving. Ex; Commit, Rollback, Savepoint.

What is the difference between the snapshot and synonym?


A snapshot refers to read-only copies of a master table or tables located on a remote node. A
snapshot can be queried, but not updated; only the master table can be updated. A snapshot is
periodically refreshed to reflect changes made to the master table. In this sense, a snapshot is
really a view with periodicity.
A synonym is an alias for table, view, sequence or program unit. They are of two types private
and public.
What is the difference between data types char and varchar?
Char reserves the number of memory locations mentioned in the variable declarations, even
though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any
memory locations when the variable is declared, it stores the values only after they are assigned
(it can store a maximum of 32767 bytes).
Can one call DDL statements from PL/SQL?
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the
EXECUTE IMMEDATE statement.
Tell some new features in PL/SQL in 10g?
-Regular expression functions REGEXP_LIKE, REGEXP_INSTR, REGEXP_REPLACE, and
REGEXP_SUBSTR
-Compile time warnings
- Conditional compilation
- Improvement to native compilation
- BINARY_INTEGER made similar to PLS_INTEGER
- Implicit conversion between CLOB and NCLOB
- Improved Overloading
- New datatypes BINARY_FLOAT, BINARY_DOUBLE
- Global optimization enabled
- PLS_INTEGER range increased to 32bit
- DYNAMIC WRAP using DBMS_DDL
What is Overloading in PL/SQL?
Overloading is an oops concept (Object Oriented Programming). By using the same name we
can write any number of Procedures or functions in a package but either number of parameters
in the procedure/function must vary or parameter datatype must vary.
What is a mutating and constraining table?
Mutating means changing. A mutating table is a table that is currently being modified by an
update, delete, or insert statement. When a trigger tries to reference a table that is in state of
flux (being changed), it is considered mutating and raises an error since Oracle should not
return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign
or unique key columns of the table off which it fires. If you must have triggers on tables that
have referential constraints, the workaround is to enforce the referential integrity through
triggers as well.
What is Nested Table?

A nested table is a table within a table. A nested table is a collection of rows, represented as a
column within the main table. For each record within main table, the nested table may contain
multiple rows. In a sense, its a way of storing a one-to many relationship within one table.
What is Varying Array?
A varying array is a set of objects, each with the same data types. The size of the array is
limited when it is created. (When the table is created with a varying array, the array is a nested
table with a limited set of rows). Varying arrays also known as VARRAYS, allows storing
repeated attributes in tables.
Give some most often used predefined exceptions?
a) NO_DATA_FOUND (Select Statement returns no rows)
b) TOO_MANY_ROWS (Single row Select statement returns more than 1 row)
c) INVALID_CURSOR (Illegal cursor operations occurred)
d) CURSOR_ALREADY_OPEN (If cursor is opened & we are trying to reopen it)
e) INVALID_NUMBER (Conversion of Character to number fails)
f) ZERO_DIVIDE
g) DUP_VAL_ON_INDEX (Attempted to insert a duplicate value)
Give some important Oracle supplied packages?
DBMS_SQL: It is used to write Procedures & Anonymous blocks that use Dynamic SQL.
DBMS_JOB: Using it, we can submit PL/SQL programs for execution, execute PL/SQL
programs on a schedule, identify when programs should run, remove programs from the
schedule & suspend programs from running.
DBMS_OUTPUT: This package outputs values & messages from any PL/SQL block.
UTL_FILE: With this package, you can read from & write to Operating system files
UTL_HTTP: This package allows to make HTTP Requests directly from the database.
What is Instead Of Trigger?
This trigger is used to perform DML operation directly on the underlying tables, because a view
cannot be modified by normal DML Statements if it contains joins or Group Functions. These
triggers are Only Row Level Triggers. The CHECK option for views is not enforced when DML to
the view are performed by Instead of Trigger.
What is the Sequence of Firing Database Triggers?
a) Before Row Level Trigger
b) Before Statement Level Trigger
c) After Row Level Trigger
d) Statement Operation
e) After Statement Level Trigger
What is the Difference between PL/SQL Table & Nested Table?
PL/SQL Table: Index by Tables are not Stored in Database.
Nested Table: Nested Tables are Stored in Database as Database Columns.
What is the Difference between Nested Table & Varray?
Nested Tablea) This are Sparse
b) We can Delete its Individual Elements
c) It do not have an Upper Boundary
d) This are Stored in System Generated Table

Varraya) This are Dense


b) We cannot Delete its Elements
c) This are Fixed Size & always need to specify the size
d) These are Stored in Tablespaces
What are the various SQL Statements?
a) Data Retrieval: Select
b) DML: Insert, Update, Delete
c) DDL: Create, Alter, Drop, Rename, Truncate
d) Transaction Control: Commit, Rollback, Savepoint
e) DCL: Grant, Revoke
f) Session Control: Alter Session, Set Role
g) System Control: Alter System
h) Embedded SQL Statements: Open, Close, Fetch & Execute.
What is Rowid?
It is a Hexadecimal Representation of a Row in a Table. Rowid can only be Changed if we
Enable Row Movement on a Partitioned Table. Rowids of Deleted Rows can be Reused if
Transaction is Committed.
What is Partitioning?
It Enables Tables & Indexes or Index-Organized tables to be subdivided into smaller
manageable Pieces & these each small Piece is called Partition.
They are of following Types:
a) Range Partitioning
b) Hash Partitioning
c) List Partitioning
d) Composite Range-Hash Partitioning
What is a Cluster?
A cluster provides an optional method of storing table data. A cluster is comprised of a group of
tables that share the same data blocks, which are grouped together because they share
common columns and are often used together. For example, the EMP and DEPT table share
the DEPTNO column. When you cluster the EMP and DEPT, Oracle physically stores all rows
for each department from both the EMP and DEPT tables in the same data blocks. You should
not use Clusters for tables that are frequently accessed individually.
What is the Difference between Nested Subquery & Correlated Subquery?
Nested Subquerya) Inner Query runs first and executes once, returning values which are to be
used by the Main query or outer query
b) Outer query is driver by Inner Query
Correlated Subquerya) A Correlated Subquery or Inner Query execute once for each candidate
row considered by outer query
b) Inner Query is Driven by Outer Query
What is the Difference between Translate & Replace?
Translate function converts each character in String with specified one whereas Replace
function replaces part of the string in continuity by another sub-string.
PL/SQL
1. What?s a PL/SQL table? Its purpose and Advantages?
A. A PL/SQL table is one dimensional, indexed, unbounded sparsed collection of
homogeneous

Data.
PLSQL tables are used to move data into and out of the database and between client side
applications and stored sub-programs. They have attributes such as exits, prior, first, last, delete
,next . These attributes make PLSQL tables easier to use and applications easier to maintain.
Advantages:
? PL\SQL tables give you the ability to hold multiple values in a structure in memory so that a
PL\SQL block does not have to go to the database every time it needs to retrieve one of these
values - it can retrieve it directly from the PL\SQL table in memory.
? Global temporary tables act as performance enhancers when compared to standard tables
as they greatly reduce the disk IO.
? They also offer the ease-of-use of standard tables, since standard SQL can be used with
them; no special array-processing syntax is required.
2. What is a Cursor? How many types of Cursor are there?
A) Cursor is an identifier/name to a work area that we can interact with to access its information.
A cursor points to the current row in the result set fetched. There are three types of cursors.
They are
? Implicit cursors ? created automatically by PL/SQL for all SQL-DML statements such as
Insert Update, delete and Select
? Explicit cursors ? Created explicitly. They create a storage area where the set of rows
Returned by a query are placed.
? Dynamic Cursors ? Ref Cursors( used for the runtime modification of the select querry).
Declaring the cursor, Opening the cursor, Fetching data , Closing the cursor(Releasing the work
area) are the steps involved when using explicit cursors.
3. What is the difference between Function and Procedure?
? Procedure is a sub program written to perform a set of actions and returns multiple values
Using out parameters or return no value at all.
? Function is a subprogram written to perform certain computations and return a single value.
4. What are the modes for passing parameters to Oracle?
A) There are three modes for passing parameters to subprograms
? IN - An In-parameter lets you pass values to the subprogram being called. In the
subprogram it acts like a constant and cannot be assigned a value.
? OUT ? An out-parameter lets you return values to the caller of the subprogram. It acts like
an initialized variable its value cannot be assigned to another variable or to itself.
? INOUT ? An in-out parameter lets you pass initial values to the subprogram being called and
returns updated values to the caller.
5. What is the difference between Truncate and Delete Statement?
? Truncate ? Data truncated by using truncate statement is lost permanently and cannot be
retrieved even by rollback. Truncate command does not use rollback segment during its
execution, hence it is fast.
? Delete ? Data deleted by using the delete statement can be retrieved back by Rollback.
Delete statement does not free up the table object allocated space.
6. What are Exceptions? How many types of Exceptions are there?
A) Exceptions are conditions that cause the termination of a block. There are two types of
exceptions
? Pre-Defined ? Predefined by PL/SQL and are associated with specific error codes.
? User-Defined ? Declared by the users and are rose on deliberate request. (Breaking a
condition etc.)
Exception handlers are used to handle the exceptions that are raised. They prevent exceptions
from propagating out of the block and define actions to be performed when exception is raised.

7. What is a Pragma Exception_Init? Explain its usage?


A) Pragma Exception_Init is used to handle undefined exceptions. It issues a directive to the
compiler asking it to associate an exception to the oracle error. There by displaying a specific
error message pertaining to the error occurred.
Pragma Exception_Init (exception_name, oracle_error_name).
8. What is a Raise and Raise Application Error?
A) Raise statement is used to raise a user defined exception.
B) A raise application error is a procedure belonging to dbms_standard package. It allows to
display a user defined error message from a stored subprogram.
8. What is the difference between Package, Procedure and Functions?
? A package is a database objects that logically groups related PL/SQL types, objects, and
Subprograms.
? Procedure is a sub program written to perform a set of actions and can return multiple
values.
? Function is a subprogram written to perform certain computations and return a single value.
Unlike subprograms packages cannot be called, passed parameters or nested.
9. How do you make a Function and Procedure as a Private?
A) Functions and Procedures can be made private to a package by not mentioning their
declaration in the package specification and by just mentioning them in the package body.
10. What is an Anonymous block?
A) Anonymous Block is a block of instructions in PL/SQL and SQL which is not saved under a
name as an object in database schema. It is also not compiled and saved in server storage, so
it needs to be parsed and executed each time it is run. However, this simple form of program
can use variables, can have flow of control logic, can return query results into variables and can
prompt the user for input using the SQL*Plus '&' feature as any stored procedure.
12. What are the two basic parameters that we have to pass while registering PL/SQL
procedure?
A) Error code and Error Buffer.
11. How do you kick a Concurrent program from PL/SQL?
A) Using FND_SUBMIT.SUBMIT_REQUEST.
12. How to display messages in Log file and Output file?
A) Using FND_FILE.PUT_LINE
13. What is a Trigger ? How many types of Triggers are there?
A) Trigger is a procedure that gets implicitly executed when an insert/update/delete statement is
issued against an associated table. Triggers can only be defined on tables not on views, how
ever triggers on the base table of a view are fired if an insert/update/delete statement is issued
against a view.
There are two types of triggers, Statement level trigger and Row level trigger.
Insert
After
/
For each row
Trigger is fired
/
Update /
Before
/
For Each statement
Delete
14. Can we use Commit in a Database Trigger, if ?No? then why?
A) No. Committing in a trigger will violate the integrity of the transaction.
15. What is Commit, Rollback and Save point?
Commit ? Makes changes to the current transaction permanent. It Erases the savepoints and
releases the transaction locks.
Savepoint ?Savepoints allow to arbitrarily hold work at any point of time with option of later

committing. They are used to divide transactions into smaller portions.


Rollback ? This statement is used to undo work.
16. What is the difference between DDL, DML and DCL structures?
A) DDL statements are used for defining data. Ex: Create, Alter, Drop.
DML statements are used for manipulating data. Ex: Insert, update, truncate, delete, select.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
17. How can u create a table in PL/SQL procedure?
A) By using execute immediate statement we can create a table in PLSQL.
Begin
Execute immediate ?create table amit as select * from emp?;
End;
All DDL,DML,DCL commands can be performed by using this command.
18. How do we Tune the Queries?
A) Queries can be tuned by Checking the logic (table joins), by creating Indexes on objects in
the where clause, by avoiding full table scans. Finally use the trace utility to generate the trace
file, use the TK-Prof utility to generate a statistical a nalysis about the query using which
appropriate actions can be taken.
21. What is Explain Plan? How do u use Explain Plan in TOAD?
A) It is a utility provided by toad that gives the statistics about the performance of the query. It
gives information such as number of full table scans occurred, cost, and usage of indexes
19. What is a TK-PROF and its usage?
A) Tk-Prof is a utility that reads the trace files and generates more readable data that gives the
statistics about the performance of the query on a line to line basis.
20. What is Optimization? How many types of Optimization are there?
A) Rule based Optimization and Cost Based Optimization.
21. What is the default optimization chosen by Oracle?
A) Cost based Optimization.
22. What is the difference between When no data Found and cursor attribute % DATA
FOUND?
A) When no Data Found is a predefined internal exception in PLSQL. Where as % Data found is
a cursor attribute that returns YES when zero rows are retrieved and returns NO when at least
one row is retrieved.
23. What is the difference between the snapshot and synonym?
? A snapshot refers to read-only copies of a master table or tables located on a remote node.
A snapshot can be queried, but not updated; only the master table can be updated. A snapshot
is periodically refreshed to reflect changes made to the master table. In this sense, a snapshot
is really a view with periodicity.
? A synonym is an alias for table, view, sequence or program unit. They are of two types
private and public.
25. What is the difference between data types char and varchar?
A) Char reserves the number of memory locations mentioned in the variable declarations, even
though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any
memory locations when the variable is declared, it stores the values only after they are assigned
(it can store a maximum of 32767 bytes).
26. How can we place index to a second column in the table i.e. there is already one index and I
want to place another index for the column on the table?
27. Items are imported from the legacy system using the item import interface using the SRS.
How are items imported using the UNIX /PLSQL commands with out using SRS?
A) From the operating system, use CONCSUB to submit a concurrent program. It's an easiest

way to test a concurrent program.


Normally, CONCSUB submits a concurrent request and returns control to the OS prompt/shell
script without waiting for the request to complete. The CONCSUB WAIT parameter can be used
to make CONCSUB wait until the request has completed before returning control to the OS
prompt/shell script
By using the WAIT token, the utility checks the request status every 60 seconds and returns to
the operating system prompt upon completion of the request. concurrent manager does not
abort, shut down, or start up until the concurrent request completes. If your concurrent program
is compatible with itself, we can check it for data integrity and deadlocks by submitting it many
times so that it runs concurrently with itself.
Syntax: CONCSUB <ORACLE ID> <Responsibility Application Short Name> <Responsibility
Name> <User Name> [WAIT=<Wait Flag] CONCURRENT <Concurrent Program Application
Short Name> <Concurrent Program Name> [START=<Requested Start Date>]
[REPEAT_DAYS=<Repeat Interval>] [REPEAT_END=<Request Resubmission End Date>]
<Concurrent Program Arguments ...>
To pass null parameters to CONCSUB, use '""' without spaces for each null parameter.
In words: single quote double quote double quote single quote
Following is an example of CONCSUB syntax with null parameters:
CONCSUB oe/oe OE 'Order Entry Super User' JWALSH CONCURRENT XOE XOEPACK 4 3
'""' 3
B) To Invoke a Concurrent Program using PL/SQL:
i) Just insert a row in FND_CONCURRENT_REQUESTS with the apropriate parameters and
commit.
ii) Invoke the SUBMIT_REQUEST procedure in FND_REQUEST package.
FND_REQUEST.SUBMIT_REQUEST( 'AR', 'RAXMTR', '', '', FALSE, 'Autoinvoice Master
Program', sc_time, FALSE, 1, 1020, 'VRP', '01-JAN-00', chr(0), '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
28. What is pipelining?
29) How can the duplicate records be from the table?
SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table_name1;
SQL> rename table_name2 to table_name1;
30) What is the significance of _all tables?
A) _all tables are multi-org tables which are associated with the company as a whole. Multiple
Organizations is enabled in Oracle
Applications by partitioning some database tables by the Operating Unit. Other tables are
shared across Operating Units (and therefore across set of books). Examples of Applications
with partitioned tables are Oracle Payables, Oracle Purchasing, Oracle Receivables, Oracle
Projects, Oracle Sales & Marketing etc. The name of each corresponding partitioned table is the
view name appended by '_ALL'
31)What are mutating tables? And what is mutating error?
A) A mutating table is a table that is currently being modified by an UPDATE, DELETE, or
INSERT statement, or it is a table that might need to be updated by the effects of a declarative
DELETE CASCADE referential integrity constraint.

A mutating error occurs when a trigger which fires when updation/deletion/insertion is done on a
table A performs insertion/updation/deletion on the same table A. This error results in an infinite
loop which is termed as a mutating error.
32) What is difference between oracle 7 and oracle 8?
A) Oracle 7 is a simple RDBMS, where as Oracle 8 is ORDBMS i.e., RDBMS with Object
Support.
The main add-ons in version 8 are?
?
?
?
?
?

Abstract Data types


Varrays
PL/SQL Tables
Nested Tables
Partitioned Tables

33.What is Data cleaning and testing.


A) Data Cleaning: Transformation of data in its current state to a pre-defined, standardized
format using packaged software or program modules.
Data Testing: The agreed upon conversion deliverables should be approved by the client
representatives who are responsible for the success of the conversion. In addition, three levels
of conversion testing have been identified and described in the prepare conversion test plans
deliverables.
Eg: for Summary Balances in GL we set Test Criteria as Record Counts, Hash Totals, Balances,
Journal Debit and Credit.
34. While registering a report and a pl/sql block we pass some parameters, for any pl/sql block
we pass 2 additional parameters. Can u list them?
A) It requires two IN parameters for a PL/SQL procedure that's registered as a concurrent
program in Apps. They are
1. Errcode IN VARCHAR2
2. Errbuff IN VARCHAR2
35) what is a trace file?
A) when ever an internal error is detected by a process in oracle it dumps the information about
the error into a trace file.
Alter session set sql_trace=TRUE
36 ) When do you use Ref Cursors?
We base a query on a ref cursor when you want to:
i) More easily administer SQL
ii) Avoid the use of lexical parameters in your reports
iii) Share data sources with other applications, such as Form Builder
iv) Increase control and security
v) Encapsulate logic within a subprogram
Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT
in Database Trigger? Why?
It is not possible. As triggers are defined for each table, if you use COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.

19.What are two virtual tables available during database trigger execution?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name
values only available.
For triggers related to DELETE only OLD.column_name values only available.
20.What happens if a procedure that updates a column of table X is called in a
database trigger of the same table?
Mutation of table occurs.
21.Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
22.What is an Exception? What are types of Exception?
Exception is the error handling part of PL/SQL block. The types are Predefined
and user_defined. Some of Predefined execptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
23.What is Pragma EXECPTION_INIT? Explain the usage?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception
with an oracle error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
24.What is Raise_application_error?
Raise_application_error is a procedure of package DBMS_STANDARD which
allows to issue an user_defined error messages from stored sub-program or
database trigger.
25.What are the return values of functions SQLCODE and SQLERRM?

SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.
26.Where the Pre_defined_exceptions are stored?
In the standard package.
Procedures, Functions & Packages;
27.What is a stored procedure?
A stored procedure is a sequence of statements that perform specific function.
30.What is difference between a PROCEDURE & FUNCTION?
A FUNCTION is alway returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not
return at all.
31.What are advantages of Stored Procedures?
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
32.What are the modes of parameters that can be passed to a procedure?
IN,OUT,IN-OUT parameters.
33.What are the two parts of a procedure?
Procedure Specification and Procedure Body.
34.Give the structure of the procedure?
PROCEDURE name (parameter list.....)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;
35.Give the structure of the function?
FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
36.Explain how procedures and functions are called in a PL/SQL block ?

Function is called as part of an expression.


sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');
37.What is Overloading of procedures?
The Same procedure name is repeated with parameters of different datatypes
and parameters in different positions, varying number of parameters is called
overloading of procedures.
e.g. DBMS_OUTPUT put_line
38.What is a package? What are the advantages of packages?
Package is a database object that groups logically related procedures.
The advantages of packages are Modularity, Easier Applicaton Design, and
Information.
Hiding,. Reusability and Better Performance.
39.What are two parts of package?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and
local to the schema.
Package Body contains actual procedures and local declaration of the
procedures and cursor declarations.
40.What is difference between a Cursor declared in a procedure and Cursor
declared in a package specification?
A cursor declared in a package specification is global and can be accessed by
other procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be
accessed by other procedures.
41.How packaged procedures and functions are called from the following ?
a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS
a. PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.
BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any
out/in-out parameters. A function can not be called.

42.Name the tables where characteristics of Package, procedure and functions are
stored?
User_objects, User_Source and User_error
43. What is Overloading of procedures?
The Same procedure name is repeated with parameters of different datatypes and
parameters in different positions, varying number of parameters is called overloading of
procedures.
e.g. DBMS_OUTPUT put_line
What is a package ? What are the advantages of packages ?
What is PL/SQL and what is it used for?
SQL is a declarative language that allows database programmers to write a SQL declaration
and hand it to the database for execution. As such, SQL cannot be used to execute procedural
code with conditional, iterative and sequential statements. To overcome this limitation, PL/SQL
was created.
PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax,
structure and data types are similar to that of Ada. Some of the statements provided by PL/SQL:
Conditional Control Statements:

IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF;

CASE ... WHEN ... THEN ... ELSE ... END CASE;

Iterative Statements:

LOOP ... END LOOP;

WHILE ... LOOP ... END LOOP;

FOR ... IN [REVERSE] ... LOOP ... END LOOP;

Sequential Control Statements:

GOTO ...;

NULL;

The PL/SQL language includes object oriented programming techniques such as encapsulation,
function overloading, information hiding (all but inheritance).
PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle
database.
Example PL/SQL blocks:
/* Remember to SET SERVEROUTPUT ON to see the output */
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');

END;
/
BEGIN
-- A PL/SQL cursor
FOR cursor1 IN (SELECT * FROM table1) -- This is an embedded SQL
statement
LOOP
DBMS_OUTPUT.PUT_LINE('Column 1 = ' || cursor1.column1 ||
', Column 2 = ' || cursor1.column2);
END LOOP;
END;
/
[edit]What is the difference between SQL and PL/SQL?
Both SQL and PL/SQL are languages used to access data within Oracle databases.
SQL is a limited language that allows you to directly interact with the database. You can write
queries (SELECT), manipulate objects (DDL) and data (DML) with SQL. However, SQL doesn't
include all the things that normal programming languages have, such as loops and
IF...THEN...ELSE statements.
PL/SQL is a normal programming language that includes all the features of most other
programming languages. But, it has one thing that other programming languages don't have:
the ability to easily integrate with SQL.
Some of the differences:

SQL is executed one statement at a time. PL/SQL is executed as a block of code.

SQL tells the database what to do (declarative), not how to do it. In contrast, PL/SQL tell
the database how to do things (procedural).

SQL is used to code queries, DML and DDL statements. PL/SQL is used to code
program blocks, triggers, functions, procedures and packages.

You can embed SQL in a PL/SQL program, but you cannot embed PL/SQL within a SQL
statement.
[edit]Should one use PL/SQL or Java to code procedures and triggers?

Both PL/SQL and Java can be used to create Oracle stored procedures and triggers. This often
leads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL
in favour of Java?".
Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever
desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it.
Many enhancements are still being made to PL/SQL. For example, Oracle 9i supports native
compilation of PL/SQL code to binaries. Not to mention the numerous PL/SQL enhancements
made in Oracle 10g and 11g.

PL/SQL and Java appeal to different people in different job roles. The following table briefly
describes the similarities and difference between these two language environments:
PL/SQL:

Can be used to create Oracle packages, procedures and triggers

Data centric and tightly integrated into the database

Proprietary to Oracle and difficult to port to other database systems

Data manipulation is slightly faster in PL/SQL than in Java

PL/SQL is a traditional procedural programming language

Java:

Can be used to create Oracle packages, procedures and triggers

Open standard, not proprietary to Oracle

Incurs some data conversion overhead between the Database and Java type

Java is an Object Orientated language, and modules are structured into classes

Java can be used to produce complete applications

PS: Starting with Oracle 10g, .NET procedures can also be stored within the database
(Windows only). Nevertheless, unlike PL/SQL and JAVA, .NET code is not usable on nonWindows systems.
PS: In earlier releases of Oracle it was better to put as much code as possible in procedures
rather than triggers. At that stage procedures executed faster than triggers as triggers had to be
re-compiled every time before executed (unless cached). In more recent releases both triggers
and procedures are compiled when created (stored p-code) and one can add as much code as
one likes in either procedures or triggers. However, it is still considered a best practice to put as
much of your program logic as possible into packages, rather than triggers.
[edit]How can one see if somebody modified any code?
The source code for stored procedures, functions and packages are stored in the Oracle Data
Dictionary. One can detect code changes by looking at the TIMESTAMP and LAST_DDL_TIME
column in the USER_OBJECTS dictionary view. Example:
SELECT OBJECT_NAME,
TO_CHAR(CREATED,
'DD-Mon-RR HH24:MI') CREATE_TIME,
TO_CHAR(LAST_DDL_TIME, 'DD-Mon-RR HH24:MI') MOD_TIME,
STATUS
FROM
USER_OBJECTS

WHERE

LAST_DDL_TIME > '&CHECK_FROM_DATE';

Note: If you recompile an object, the LAST_DDL_TIME column is updated, but the TIMESTAMP
column is not updated. If you modified the code, both the TIMESTAMP and LAST_DDL_TIME
columns are updated.
[edit]How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where certain tables, columns and expressions
are referenced in your PL/SQL source code.
SELECT type, name, line
FROM
user_source
WHERE UPPER(text) LIKE UPPER('%&KEYWORD%');
If you run the above query from SQL*Plus, enter the string you are searching for when
prompted for KEYWORD. If not, replace &KEYWORD with the string you are searching for.
[edit]How does one keep a history of PL/SQL code changes?
One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or
database) level trigger (available from Oracle 8.1.7). This will allow you to easily revert to
previous code should someone make any catastrophic changes. Look at this example:
CREATE TABLE SOURCE_HIST
-- Create history table
AS SELECT SYSDATE CHANGE_DATE, ALL_SOURCE.*
FROM
ALL_SOURCE WHERE 1=2;
CREATE OR REPLACE TRIGGER change_hist
-- Store code in hist
table
AFTER CREATE ON SCOTT.SCHEMA
-- Change SCOTT to your schema
name
DECLARE
BEGIN
IF ORA_DICT_OBJ_TYPE in ('PROCEDURE', 'FUNCTION',
'PACKAGE',
'PACKAGE BODY',
'TYPE',
'TYPE BODY')
THEN
-- Store old code in SOURCE_HIST table
INSERT INTO SOURCE_HIST
SELECT sysdate, all_source.* FROM ALL_SOURCE
WHERE TYPE = ORA_DICT_OBJ_TYPE -- DICTIONARY_OBJ_TYPE
IN 8i
AND NAME = ORA_DICT_OBJ_NAME; -- DICTIONARY_OBJ_NAME
IN 8i
END IF;
EXCEPTION
WHEN OTHERS THEN

raise_application_error(-20000, SQLERRM);
END;
/
show errors
A better approach is to create an external CVS or SVN repository for the scripts that install the
PL/SQL code. The canonical version of what's in the database must match the latest CVS/SVN
version or else someone would be cheating.
[edit]How can I protect my PL/SQL source code?
Oracle provides a binary wrapper utility that can be used to scramble PL/SQL source code. This
utility was introduced in Oracle7.2 (PL/SQL V2.2) and is located in the ORACLE_HOME/bin
directory.
The utility use human-readable PL/SQL source code as input, and writes out portable binary
object code (somewhat larger than the original). The binary code can be distributed without fear
of exposing your proprietary algorithms and methods. Oracle will still understand and know how
to execute the code. Just be careful, there is no "decode" command available. So, don't lose
your source!
The syntax is:
wrap iname=myscript.pls oname=xxxx.plb
Please note: there is no legal way to unwrap a *.plb binary file. You are supposed to backup and
keep your *.pls source files after wrapping them. However it is possible for skilled hackers to
unwrapyour wrapped Oracle PL/SQL code.
[edit]How can I know which stored PL/SQL code is wrapped?
The following query gives the list of all wrapped PL/SQL code:
select owner, name, type
from dba_source
where line = 1
and instr(text, ' wrapped'||chr(10))+instr(text, ' wrapped '||
chr(10)) > 0
order by 1, 2, 3
/
[edit]Can one print to the screen from PL/SQL?
One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer
can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT
ON; command. For example:
set serveroutput on
begin

dbms_output.put_line('Look Ma, I can print from PL/SQL!!!');


end;
/
DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the
output buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput
on size 200000
If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and
then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable
procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy
PL/SQL block.
To display an empty line, it is better to use new_line procedure than put_line with an empty
string.
[edit]Can one read/write files from PL/SQL?
The UTL_FILE database package can be used to read and write operating system files.
A DBA user needs to grant you access to read from/ write to a specific directory before using
this package. Here is an example:
CONNECT / AS SYSDBA
CREATE OR REPLACE DIRECTORY mydir AS '/tmp';
GRANT read, write ON DIRECTORY mydir TO scott;
Provide user access to the UTL_FILE package (created by catproc.sql):
GRANT EXECUTE ON UTL_FILE TO scott;
Copy and paste these examples to get you started:
Write File
DECLARE
fHandler UTL_FILE.FILE_TYPE;
BEGIN
fHandler := UTL_FILE.FOPEN('MYDIR', 'myfile', 'w');
UTL_FILE.PUTF(fHandler, 'Look ma, Im writing to a file!!!\n');
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'Invalid path. Create directory
or set UTL_FILE_DIR.');
END;
/
Read File

DECLARE
fHandler UTL_FILE.FILE_TYPE;
buf
varchar2(4000);
BEGIN
fHandler := UTL_FILE.FOPEN('MYDIR', 'myfile', 'r');
UTL_FILE.GET_LINE(fHandler, buf);
dbms_output.put_line('DATA FROM FILE: '||buf);
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'Invalid path. Create directory
or set UTL_FILE_DIR.');
END;
/
NOTE: UTL_FILE was introduced with Oracle 7.3. Before Oracle 7.3 the only means of writing a
file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
[edit]Can one call DDL statements from PL/SQL?
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the
"EXECUTE IMMEDIATE" statement (native SQL). Examples:
begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
end;
begin execute Immediate 'TRUNCATE TABLE emp'; end;
DECLARE
var VARCHAR2(100);
BEGIN
var := 'CREATE TABLE temp1(col1 NUMBER(2))';
EXECUTE IMMEDIATE var;
END;
NOTE: The DDL statement in quotes should not be terminated with a semicolon.
Users running Oracle versions below Oracle 8i can look at the DBMS_SQL package (see FAQ
about Dynamic SQL).
[edit]Can one use dynamic SQL statements from PL/SQL?
Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic
SQL and PL/SQL statements (statements created at run-time). Look at these examples. Note
that the statements within quotes are NOT semicolon terminated:
EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)';
-- Using bind variables...'
sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';

EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;


-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic
statements. Look at these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows
integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x',
DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||
sqlcode||' '||sqlerrm);

END;
/
[edit]What is the difference between %TYPE and %ROWTYPE?
Both %TYPE and %ROWTYPE are used to define variables in PL/SQL as it is defined within the
database. If the datatype or precision of a column changes, the program automatically picks up
the new definition from the database without having to make any code changes.
The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance
costs, and allows programs to adapt as the database changes to meet new business needs.
%TYPE
%TYPE is used to declare a field with the same type as that of a specified table's column.
Example:
DECLARE
v_EmpName emp.ename%TYPE;
BEGIN
SELECT ename INTO v_EmpName FROM emp WHERE ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE('Name = ' || v_EmpName);
END;
/
%ROWTYPE
%ROWTYPE is used to declare a record with the same types as found in the specified
database table, view or cursor. Examples:
DECLARE
v_emp emp%ROWTYPE;
BEGIN
v_emp.empno := 10;
v_emp.ename := 'XXXXXXX';
END;
/
[edit]How does one get the value of a sequence into a PL/SQL variable?
Starting with 11g you can directly do the following:
i := sq_sequence.NEXTVAL;
On the previous versions you have to use embedded SQL statements to obtain sequence
values:
select sq_sequence.NEXTVAL into :i from dual;

[edit]Can one execute an operating system command from PL/SQL?


There is no direct way to execute operating system commands from PL/SQL. PL/SQL doesn't
have a "host" command, as with SQL*Plus, that allows users to call OS commands.
Nevertheless, the following workarounds can be used:
Database Pipes
Write an external program (using one of the precompiler languages, OCI or Perl with Oracle
access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL
program then put requests to run commands in the pipe, the listener picks it up and run the
requests. Results are passed back on a different database pipe. For a Pro*C example, see
chapter 8 of the Oracle Application Developers Guide.
CREATE OR REPLACE FUNCTION host_command( cmd IN VARCHAR2 )
RETURN INTEGER IS
status
NUMBER;
errormsg VARCHAR2(80);
pipe_name VARCHAR2(30);
BEGIN
pipe_name := 'HOST_PIPE';
dbms_pipe.pack_message( cmd );
status := dbms_pipe.send_message(pipe_name);
RETURN status;
END;
/
External Procedure Listeners:
From Oracle 8 one can call external 3GL code in a dynamically linked library (DLL or shared
object). One can write a library in C/ C++ to do whatever is required. Defining this C/C++
function to PL/SQL makes it executable. Look at this External Procedure example.
Using Java
See example at http://www.orafaq.com/scripts/plsql/oscmd.txt
DBMS_SCHEDULER
In Oracle 10g and above, one can execute OS commands via
the DBMS_SCHEDULER package. Look at this example:
BEGIN
dbms_scheduler.create_job(job_name
job_type
job_action
enabled
auto_drop
END;
/

=>
=>
=>
=>
=>

'myjob',
'executable',
'/app/oracle/x.sh',
TRUE,
TRUE);

exec dbms_scheduler.run_job('myjob');
[edit]How does one loop through tables in PL/SQL?
One can make use of cursors to loop through data within tables. Look at the following nested
loops code example.
DECLARE
CURSOR
SELECT
FROM
ORDER

dept_cur IS
deptno
dept
BY deptno;

-- Employee cursor all employees for a dept number


CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line('Employees in Department '||
TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP
dbms_output.put_line('...Employee is '||emp_rec.ename);
END LOOP;
END LOOP;
END;
/
[edit]How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
Contrary to popular belief, one should COMMIT less frequently within a PL/SQL loop to prevent
ORA-1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the
extents in the undo/ rollback segments will be cleared for new transactions, causing ORA-1555
errors.
To fix this problem one can easily rewrite code like this:
FOR records IN my_cursor LOOP
...do some stuff...
COMMIT;
END LOOP;
COMMIT;
... to ...

FOR records IN my_cursor LOOP


...do some stuff...
i := i+1;
IF mod(i, 10000) = 0 THEN
COMMIT;
END IF;
END LOOP;
COMMIT;

-- Commit every 10000 records

If you still get ORA-1555 errors, contact your DBA to increase the undo/ rollback segments.
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI
standard.
Issuing frequent commits is bad, bad, BAD! Its the WORST thing you can do just dont do it!
In the following example I will create around 7 million rows and then attempt to update a portion
of them serially. In addition, I will issue a commit every thousandth row.
Example 1.1: Creating a somewhat large table
SQL> create table big_employee_table
2
as
3
select rownum as eid
4
, e.*
5
from hr.employees e
6
, dba_objects do;
Table created.
Elapsed: 00:00:12.23
SQL>
select count(*)
2
from big_employee_table;
COUNT(*)
---------7838713
Elapsed: 00:00:08.11
Before I go on, notice that Oracles Create Table As (CTAS) method blazed thru table creation.
Thats 7.84 Million rows in 12.23 seconds. Sometimes, this is the very best method of updating
large data sets. The following block updates 100,000 rows, serially, committing every 1000
rows:
Example 1.2: Updating serially
SQL> declare
2
cursor c is
3
select *

4
5
6
7
8
9
10
11
12
13
14
15
16
17

from
where

big_employee_table
rownum <= 100000;

begin
for r in c loop
update big_employee_table
set salary = salary * 1.03
where eid = r.eid;
if mod ( r.eid, 1000 ) = 0 then
commit;
end if;
end loop;
end;
/

Observe that the update took more time than I have patience for ;). At 20 minutes I killed the
session. It is painfully slow and should never be done. Moreover, it chewed up an entire CPU
core for the duration. If youre only updating a few rows, why do it in PL/SQL at all? I like Tom
Kytes approach (paraphrasing):
1.
2.
3.
4.

Do
If
If
If

it in SQL.
SQL cant do it, do it in PL/SQL.
PL/SQL cant do it, do it in Java.
Java cant do it ask yourself if it needs to be done.

The following block does the same work in bulk:


Example 1.3: Updating in bulk and committing at the end
SQL> declare
2
type obj_rowid is table of rowid
3
index by pls_integer;
4
5
lr_rowid
obj_rowid;
6
lr_salary
dbms_sql.number_table;
7
8
cursor c is
9
select rowid rid
10
, salary
11
from big_employee_table
12
where rownum <= 100000;
13 begin
14
open c;
15
loop
16
fetch c bulk collect

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

into lr_rowid
, lr_salary
limit 500;
for a in 1 .. lr_rowid.count loop
lr_salary ( a ) := lr_salary ( a ) * 1.03;
end loop;
forall b in 1 .. lr_rowid.count
update big_employee_table
set salary = lr_salary ( b )
where rowid in ( lr_rowid ( b ));
exit when c%notfound;
end loop;
close c;
commit; -- there! not in the loop
exception
when others then
rollback;
dbms_output.put_line ( sqlerrm );
end;
/

PL/SQL procedure successfully completed.


Elapsed: 00:00:02.11
SQL>
Notice that the update completed in 2 seconds! Ive seen faster but my two-gerbil sandbox
machine doesnt have the power that our newer servers do. The point is that the update was
incredibly fast and chewed up only 10% of one core. So, in answer to the question of how often
should I commit? I say dont until you absolutely have to.
[edit]I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
PL/SQL respect object privileges given directly to the user, but does not observe privileges
given through roles. The consequence is that a SQL statement can work in SQL*Plus, but will
give an error in PL/SQL. Choose one of the following solutions:

Grant direct access on the tables to your user. Do not use roles!

GRANT select ON scott.emp TO my_user;

Define your procedures with invoker rights (Oracle 8i and higher);

create or replace procedure proc1


authid current_user is
begin
...

Move all the tables to one user/schema.


[edit]What is a mutating and constraining table?

"Mutating" means "changing". A mutating table is a table that is currently being modified by an
update, delete, or insert statement. When a trigger tries to reference a table that is in state of
flux (being changed), it is considered "mutating" and raises an error since Oracle should not
return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign
or unique key columns of the table off which it fires. If you must have triggers on tables that
have referential constraints, the workaround is to enforce the referential integrity through
triggers as well.
There are several restrictions in Oracle regarding triggers:

A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD
still can be accessed by the trigger).

A statement-level trigger cannot query or modify a mutating table if the trigger is fired as
the result of a CASCADE delete.

Etc.
[edit]Can one pass an object/table as an argument to a remote procedure?

The only way to reference an object type between databases is via a database link. Note that it
is not enough to just use "similar" type definitions. Look at this example:
-- Database A: receives a PL/SQL table from database B
CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS
BEGIN
-- do something with TabX from database B
null;
END;
/

-- Database B: sends a PL/SQL table to database A


CREATE OR REPLACE PROCEDURE pcalling IS
TabX DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN

pcalled@DBLINK2(TabX);
END;
/
[edit]What is the difference between stored procedures and functions?

Functions MUST return a value, procedures don't need to.


You can have DML (insert,update, delete) statements in a function. But, you cannot call
such a function in a SQL query. (However an autonomous transaction function can.)

You cannot call a procedure in a SQL query.


[edit]Is there a PL/SQL Engine in SQL*Plus?

No. Unlike Oracle Forms, SQL*Plus does not have an embedded PL/SQL engine. Thus, all your
PL/SQL code is sent directly to the database engine for execution. This makes it much more
efficient as SQL statements are not stripped off and sent to the database individually.
[edit]Is there a limit on the size of a PL/SQL block?
Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when
you compile the code. You can run the following select statement to query the size of an existing
package or procedure:
SQL> select * from dba_object_size where name = 'procedure_name';
[edit]What are the PL/SQL compiler limits for block, record, subquery and label nesting?
The following limits apply:
Level of Block Nesting: 255
Level of Record Nesting: 32
Level of Subquery Nesting: 254
Level of Label Nesting: 98
[edit]Can one COMMIT/ ROLLBACK from within a trigger?
A commit inside a trigger would defeat the basic definition of an atomic transaction (see ACID).
Trigger logic is by definition an extension of the original DML operation. Changes made
within triggersshould thus be committed or rolled back as part of the transaction in which they
execute. For this reason, triggers are NOT allowed to
execute COMMIT or ROLLBACK statements (with the exception of autonomous triggers). Here
is an example of what will happen when they do:
SQL> CREATE TABLE tab1 (col1 NUMBER);
Table created.
SQL> CREATE TABLE log (timestamp DATE, operation VARCHAR2(2000));
Table created.

SQL> CREATE TRIGGER tab1_trig


2
AFTER insert ON tab1
3 BEGIN
4
INSERT INTO log VALUES (SYSDATE, 'Insert on TAB1');
5
COMMIT;
6 END;
7 /
Trigger created.
SQL> INSERT INTO tab1 VALUES (1);
INSERT INTO tab1 VALUES (1)
*
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at "SCOTT.TAB1_TRIG", line 3
ORA-04088: error during execution of trigger 'SCOTT.TAB1_TRIG'
Autonomous transactions:
As workaround, one can use autonomous transactions. Autonomous transactions execute
separate from the current transaction.
Unlike regular triggers, autonomous triggers can contain COMMIT and ROLLBACK statements.
Example:
SQL> CREATE OR REPLACE TRIGGER tab1_trig
2
AFTER insert ON tab1
3 DECLARE
4
PRAGMA AUTONOMOUS_TRANSACTION;
5 BEGIN
6
INSERT INTO log VALUES (SYSDATE, 'Insert on TAB1');
7
COMMIT; -- only allowed in autonomous triggers
8 END;
9 /
Trigger created.
SQL> INSERT INTO tab1 VALUES (1);
1 row created.
What special operators does Oracle provide for dealing with NULLs?
NVL - Converts a NULL to another specified value, as in:
my_var := NVL (your_var, 'Hello');
IS NULL and IS NOT NULL
You can use this syntax to check specificaly to see if a variable's value is NULL or NOT NULL.

Explain three different rules that apply to NULLs when doing comparisons?
1. For all operators except for concatenation (||), if a value in an expression is a NULL, that
expression evaluates to NULL
2. NULL is never equal or not equal to another value
3. NULL is never TRUE or FALSE
What command would you use to encrypt a PL/SQL application?
WRAP
Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.
A function has a return type in its specification and must return a value specified in that type. A
procedure does not have a return type in its specification and should not return any value, but it
can have a return statement that simply stops its execution and returns to the caller.
What steps are included in the compilation process of a PL/SQL block?
The compilation process includes syntax checking, binding, and p-code generation. Syntax
checking involves checking PL/SQL code for compilation errors. After syntax errors have been
corrected, a storage address is assigned to the variables that are used to hold data for Oracle.
This process is called binding. Next, p-code is generated for the PL/SQL block. P-code is a list
of instructions to the PL/SQL engine. For named blocks, p-code is stored in the database, and it
is used the next time the program is executed.
How does a syntax error differ from a runtime error?
A syntax error can be detected by the PL/SQL compiler. A runtime error occurs while the
program is running and cannot be detected by the PL/SQL compiler.
A misspelled keyword is an example of a syntax error. For example, this script:
BEIN
DBMS_OUTPUT.PUT_LINE ('This is a test');
END;
contains a syntax error. Try to find it.
A SELECT INTO statement returning no rows is an example of a runtime error. This error can be
handled with the help of the exception-handling section of the PL/SQL block.
Define Commit, Rollback and Savepoint.
When a COMMIT statement is issued to the database, the transaction has ended, and the
following results are true:
. All work done by the transaction becomes permanent.

. Other users can see changes in data made by the transaction.


. Any locks acquired by the transaction are released.
When a ROLLBACK statement is issued to the database, the transaction has ended, and the
following results are true:
. All work done by the transaction is undone, as if it hadnt been issued.
. Any locks acquired by the transaction are released.
The ROLLBACK statement undoes all the work done by the user in a specific transaction. With
the SAVEPOINT command, however, only part of the transaction can be undone.
Explain Implicit and Explicit cursors
Oracle automatically declares an implicit cursor every time a SQL statement is executed. The
user is unaware of this and cannot control or process the information in an implicit cursor.
The program defines an explicit cursor for any query that returns more than one row of data.
This means that the programmer has declared the cursor within the PL/SQL code block. This
declaration allows the application to sequentially process each row of data as the cursor returns
it.
How an Implicit cursor works?
1. Any given PL/SQL block issues an implicit cursor whenever a SQL statement is
executed, as long as an explicit cursor does not exist for that SQL statement.
2. A cursor is automatically associated with every DML (data manipulation) statement
(UPDATE, DELETE, INSERT).
3. All UPDATE and DELETE statements have cursors that identify the set of rows that will
be affected by the operation.
4. An INSERT statement needs a place to receive the data that is to be inserted into the
database; the implicit cursor fulfills this need.
5. The most recently opened cursor is called the SQL cursor.
How an Explicit cursor works?
The process of working with an explicit cursor consists of the following steps:
1. Declaring the cursor. This initializes the cursor into memory.
2. Opening the cursor. The declared cursor is opened, and memory is allotted.
3. Fetching the cursor. The declared and opened cursor can now retrieve data.

4. Closing the cursor. The declared, opened, and fetched cursor must be closed to release the
memory allocation.
What are Explicit Cursor attributes
%NOTFOU
ND

cursor_name
%NOTFOUND

%FOUND cursor_name%FOUND

A Boolean attribute that returns TRUE if the


previous FETCH did not return a row and FALSE if
it did.
A Boolean attribute that returns TRUE if the
previous FETCH returned a row and FALSE if it
did not.

%ROWCOU
NT

cursor_name
%ROWCOUNT

The number of records fetched from a cursor at


that point in time.

%ISOPEN

cursor_name%ISOPEN

A Boolean attribute that returns TRUE if the


cursor is open and FALSE if it is not.

Answer any three PL/SQL Exceptions?


Too_many_rows,
No_Data_Found,
Value_Error,
Zero_Error,
Others
What are PL/SQL Cursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
What is the maximum number of triggers, can apply to a single table?
12 triggers.
What is a mutating table error and how can you get around it?
This happens with triggers. It occurs because the trigger is trying to update a row it is currently
using. The usual fix involves either use of views or temporary tables so the database is
selecting from one while updating the other.
What packages (if any) has Oracle provided for use by developers?
Oracle provides the DBMS_ series of packages. There are many which developers should be
aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK,
DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they
can mention a few of these and describe how they used them, even better. If they include the
SQL routines provided by Oracle, great, but not really what was asked.
Describe the use of PL/SQL tables

PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to
hold values for use in later queries or calculations. In Oracle 8 they will be able to be of the
%ROWTYPE designation, or RECORD.
When is a declare statement needed?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, nonstored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.
In what order should a open/fetch/loop set of commands in a PL/SQL block be
implemented if you use the %NOTFOUND cursor variable in the exit when statement?
Why?
OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result
in the final return being done twice because of the way the %NOTFOUND is handled by
PL/SQL.
What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM
returns the actual error message for the last error encountered. They can be used in exception
handling to report, or, store in an error log table, the error that occurred in the code. These are
especially useful for the WHEN OTHERS exception.
How can you find within a PL/SQL block, if a cursor is open?
Use the %ISOPEN cursor status variable.
How can you generate debugging output from PL/SQL?
Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR
command, but this only shows errors. The DBMS_OUTPUT package can be used to show
intermediate results from loops and the status of variables as the procedure is executed. The
new package UTL_FILE can also be used.
What are the types of triggers?
There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER,
ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT etc.
How can I define a two-dimensional array of numbers in PL/SQL?
Although PL/SQL does not natively support the declaration and manipulation of
multidimensional arrays, you can emulate these structures using nested collection definitions,
which were first supported in Oracle9i Database Release 1.

Here is a brief example to get you started and introduce you to some of the challenges you may
encounter as you use collections in this way.
First, create a collection of associative arrays.
CREATE OR REPLACE PACKAGE twodim_aa
IS
TYPE data_t IS TABLE OF NUMBER
INDEX BY PLS_INTEGER;
TYPE array_t IS TABLE OF data_t
INDEX BY PLS_INTEGER;
END twodim_aa;
/
The first, inner collectiondata_tcontains the data for each cell in the two-dimensional array.
Each row in the outer collectionarray_tcontains a collection of the first type.
Now declare a variable based on that outer collection type array_t, which will serve as a
two-dimensional array. In the following script, I declare such a collection
DECLARE
l_2d_grid twodim_aa.array_t;
and then assign values to three cells: (1,1), (1,2), and (200,206). Notice that the syntax is
different from that used in traditional array cell specification, namely: (1)(1), (1)(2), and (200)
(206). Also, since I am using associative arrays to define my two-dimensional array, I do not
have to specify a size for this two-dimensional array.
DECLARE
l_2d_grid twodim_aa.array_t;
BEGIN
l_2d_grid (1) (1) := 100;
l_2d_grid (1) (2) := 120;
l_2d_grid (200) (206) := 200;
IF l_2d_grid (1)(2)
What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and ROLLBACK
statements.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created by
Oracle for each individual SQL.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and
packages ?
Answer: Public synonyms
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is PL/SQL?
Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language includes
object oriented programming techniques such as encapsulation, function overloading,
information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle
database server and a variety of Oracle tools.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all your
PL/SQL are send directly to the database engine for execution.This makes it much more
efficient as SQL statements are not stripped off and send to the database individually.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is there a limit on the size of a PL/SQL block?
Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the
maximum code size is 100K.You can run the following select statement to query the size of an
existing package or procedure. SQL> select * from dba_object_size where name =
'procedure_name'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The
directory you intend writing to has to be in your INIT.ORA file (see
UTL_FILE_DIR=...parameter).
Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the
SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------How can I protect my PL/SQL source code?
Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL
programs to protect the source code.This is done via a standalone utility that transforms the
PL/SQL source code into portable binary object code (somewhat larger than the original).This
way you can distribute software without having to worry about exposing your proprietary

algorithms and methods.SQL*Plus and SQL*DBA will still understand and know how to execute
such scripts.Just be careful, there is no "decode" command available. The syntax
is:
wrap name=myscript.sql
oname=xxxx.yyy
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL
statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)',
DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the various types of Exceptions ?
Answer: User defined and Predefined Exceptions.
Can we define exceptions twice in same block ?
Answer: No.
What is the difference between a procedure and a function ?
Answer: Functions return a single variable by value whereas procedures do not return any
variable by value.Rather they return multiple variables by passing variables by reference
through their OUT parameter.
Can you have two functions with the same name in a PL/SQL block ?
Answer: Yes.
Can you have two stored functions with the same name ?
Answer: Yes.
Can you call a stored function in the constraint of a table ?
Answer: No.
What are the various types of parameter modes in a procedure ?
Answer: IN, OUT AND INOUT.
What is Over Loading and what are its restrictions ?
Answer: OverLoading means an object performing different functions depending upon the no.of
parameters or the data type of the parameters passed to it.
Can functions be overloaded ?
Answer: Yes.
Can 2 functions have same name & input parameters but differ only by return datatype
Answer: No.

What are the constructs of a procedure, function or a package ?


Answer: The constructs of a procedure, function or a package are :
variables and constants
cursors
exceptions
Why Create or Replace and not Drop and recreate procedures ?
Answer: So that Grants are not dropped.
Can you pass parameters in packages ? How ?
Answer: Yes.You can pass parameters to procedures or functions in a package.
What are the parts of a database trigger ?
Answer: The parts of a trigger are:
A triggering event or statement
A trigger restriction
A trigger action
What are the various types of database triggers ?
Answer: There are 12 types of triggers, they are combination of :Insert, Delete and Update
Triggers.
Before and After Triggers.
Row and Statement Triggers.
What is the advantage of a stored procedure over a database trigger ?
Answer: We have control over the firing of a stored procedure but we have no control over the
firing of a trigger.
What is the maximum no.of statements that can be specified in a trigger statement ?
Answer: One.
Can views be specified in a trigger statement ?
Answer: No
What are the values of :new and :old in Insert/Delete/Update Triggers ?
Answer: INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value

What are cascading triggers? What is the maximum no of cascading triggers at a time?
Answer: When a statement in a trigger body causes another trigger to be fired, the triggers are
said to be cascading.Max = 32.
What are mutating triggers ?
Answer: A trigger giving a SELECT on the table on which the trigger is written.
What are constraining triggers ?
Answer: A trigger giving an Insert/Updat e on a table having referential integrity constraint on the
triggering table.
Describe Oracle database's physical and logical structure ?
Answer:
Physical : Data files, Redo Log files, Control file.
Logical : Tables, Views, Tablespaces, etc.

Can you increase the size of a tablespace ? How ?


Answer: Yes, by adding datafiles to it.
Can you increase the size of datafiles ? How ?
Answer: No (for Oracle 7.0)
Yes (for Oracle 7.3 by using the Resize clause )
What is the use of Control files ?
Answer: Contains pointers to locations of various data files, redo log files, etc.
What is the use of Data Dictionary ?
Answer: It Used by Oracle to store information about various physical and logical Oracle
structures e.g.Tables, Tablespaces, datafiles, etc
What are the advantages of clusters ?
Answer: Access time reduced for joins.
What are the disadvantages of clusters ?
Answer: The time for Insert increases.
Can Long/Long RAW be clustered ?
Answer: No.
Can null keys be entered in cluster index, normal index ?
Answer: Yes.
Can Check constraint be used for self referential integrity ? How ?
Answer: Yes.In the CHECK condition for a column of a table, we can reference some other
column of the same table and thus enforce self referential integrity.
What are the min.extents allocated to a rollback extent ?
Answer: Two
What are the states of a rollback segment ? What is the difference between partly available and
needs recovery ?
Answer: The various states of a rollback segment are :
ONLINE
OFFLINE
PARTLY AVAILABLE
NEEDS RECOVERY
INVALID.
What is the difference between unique key and primary key ?
Answer: Unique key can be null; Primary key cannot be null.
An insert statement followed by a create table statement followed by rollback ? Will the rows be
inserted ?
Answer: No.
Can you define multiple savepoints ?
Answer: Yes.
Can you Rollback to any savepoint ?
Answer: Yes.
What is the maximum no.of columns a table can have ?
Answer: 254.
What is the significance of the & and && operators in PL SQL ?
Answer: The & operator means that the PL SQL block requires user input for a variable.The &&

operator means that the value of this variable should be the same as inputted by the user
previously for this same variable
Can you pass a parameter to a cursor ?
Answer: Explicit cursors can take parameters, as the example below shows.A cursor parameter
can appear in a query wherever a constant can appear.CURSOR c1 (median IN NUMBER) IS
SELECT job, ename FROM emp WHERE sal > median;
What are the various types of RollBack Segments ?
Answer: The types of Rollback sagments are as follows :
Public Available to all instances
Private Available to specific instance
Can you use %RowCount as a parameter to a cursor ?
Answer: Yes
Is the query below allowed :
Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of Number(4)
and Char(15))
Answer: Yes
Is the assignment given below allowed :
ABC = PQR (Where ABC and PQR are records)
Answer: Yes
Is this for loop allowed : For x in &Start..&End Loop
Answer: Yes
How many rows will the following SQL return : Select * from emp Where rownum < 10;
Answer: 9 rows
How many rows will the following SQL return : Select * from emp Where rownum = 10;
Answer: No rows
Which symbol preceeds the path to the table in the remote database ?
Answer: @
Are views automatically updated when base tables are updated ?
Answer: Yes
Can a trigger written for a view ?
Answer: No
If all the values from a cursor have been fetched and another fetch is issued, the output will be :
error, last record or first record ?
Answer: Last Record
A table has the following data : [[5, Null, 10]].What will the average function return ?
Answer: 7.5
Is Sysdate a system variable or a system function?
Answer: System Function
Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval
reference we get the next number 2.Suppose at this point we issue an rollback and again issue

a nextval.What will the output be ?


Answer: 3
Definition of relational DataBase by Dr.Codd (IBM)?
Answer: A Relational Database is a database where all data visible to the user is organized
strictly as tables of data values and where all database operations work on these tables.
What is Multi Threaded Server (MTA) ?
Answer: In a Single Threaded Architecture (or a dedicated server configuration) the database
manager creates a separate process for each database user.But in MTA the database manager
can assign multiple users (multiple user processes) to a single dispatcher (server process), a
controlling process that queues request for work thus reducing the databases memory
requirement and resources.
Which are initial RDBMS, Hierarchical & N/w database ?
Answer:
RDBMS - R system
Hierarchical - IMS
N/W - DBTG
Difference between Oracle 6 and Oracle 7
Answer:
ORACLE 7
ORACLE 6
Cost based optimizer
Rule based optimizer
Shared SQL Area
SQL area allocated for each user
Multi Threaded Server
Single Threaded Server
Hash Clusters
Only B-Tree indexing
Roll back Size
Adjustment No provision
Truncate command
No provision
Distributed Database
Distributed Query
Table replication & snapshots
No provision
Client/Server Tech
No provision
What is Functional Dependency?
Answer: Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and
only if each X-value has associated with it precisely one -Y value in R
What is Auditing ?
Answer: The database has the ability to audit all actions that take place within it. a) Login
attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL)
NULL
While designing in client/server what are the 2 imp.things to be considered ?
Answer: Network Overhead (traffic), Speed and Load of client server
What are the disadvantages of SQL ?
Answer: Disadvantages of SQL are :
Cannot drop a field
Cannot rename a field
Cannot manage memory

Procedural Language option not provided


Index on view or index on index not provided
View updation problem
When to create indexes ?
Answer: To be created when table is queried for less than 2% or 4% to 25% of the table rows.
How can you avoid indexes ?
Answer: To make index access path unavailable Use FULL hint to optimizer for full table scan
Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of
another. Use an expression in the Where Clause of the SQL.
What is the result of the following SQL : Select 1 from dual UNION Select 'A' from dual;
Answer: Error
Can database trigger written on synonym of a table and if it can be then what would be the
effect if original table is accessed.
Answer: Yes, database trigger would fire.
Can you alter synonym of view or view ?
Answer: No
Can you create index on view
Answer: No.
What is the difference between a view and a synonym ?
Answer: Synonym is just a second name of table used for multiple link of database.View can be
created with many tables, and with virtual columns and with conditions.But synonym can be on
view.
What's the length of SQL integer ?
Answer: 32 bit length
What is the difference between foreign key and reference key ?
Answer: Foreign key is the key i.e.attribute which refers to another table primary key. Reference
key is the primary key of table referred by another table.
Can dual table be deleted, dropped or altered or updated or inserted ?
Answer: Yes
If content of dual is updated to some value computation takes place or not ?
Answer: Yes
If any other table same as dual is created would it act similar to dual?
Answer: Yes
For which relational operators in where clause, index is not used ?
Answer: <> , like '%...' is NOT functions, field +constant, field||''
Assume that there are multiple databases running on one machine.How can you switch from
one to another ?
Answer: Changing the ORACLE_SID
What are the advantages of Oracle ?
Answer: Portability : Oracle is ported to more platforms than any of its competitors, running on
more than 100 hardware platforms and 20 networking protocols. Market Presence : Oracle is by
far the largest RDBMS vendor and spends more on R & D than most of its competitors earn in
total revenue.This market clout means that you are unlikely to be left in the lurch by Oracle and
there are always lots of third party interfaces available. Backup and Recovery : Oracle provides
industrial strength support for on-line backup and recovery and good software fault tolerence to

disk failure.You can also do point-in-time recovery. Performance : Speed of a 'tuned' Oracle
Database and application is quite good, even with large databases.Oracle can manage >
100GB databases. Multiple database support : Oracle has a superior ability to manage multiple
databases within the same transaction using a two-phase commit protocol.
What is a forward declaration ? What is its use ?
Answer: PL/SQL requires that you declare an identifier before using it.Therefore, you must
declare a subprogram before calling it.This declaration at the start of a subprogram is called
forward declaration.A forward declaration consists of a subprogram specification terminated by
a semicolon.
What are actual and formal parameters ?
Answer: Actual Parameters : Subprograms pass information using parameters.The variables or
expressions referenced in the parameter list of a subprogram call are actual parameters.For
example, the following procedure call lists two actual parameters named emp_num and
amount:
Eg.raise_salary(emp_num, amount);Formal Parameters : The variables declared in a
subprogram specification and referenced in the subprogram body are formal parameters.For
example, the following procedure declares two formal parameters named emp_id and increase:
Eg.PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL;
What are the types of Notation ?
Answer: Position, Named, Mixed and Restrictions.
What all important parameters of the init.ora are supposed to be increased if you want to
increase the SGA size ?
Answer: In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 &
3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB)
open_cursors was changed from 200 to 300 (std values are 200 & 300) db_block_size was
changed from 2048 (2K) to 4096 (4K) {at the time of database creation}. The initial SGA was
around 4MB when the server RAM was 32MB and The new SGA was around 13MB when the
server RAM was increased to 128MB.
If I have an execute privilege on a procedure in another users schema, can I execute his
procedure even though I do not have privileges on the tables within the procedure ?
Answer: Yes
What are various types of joins ?
Answer: Types of joins are:
Equijoins
Non-equijoins
self join
outer join
What is a package cursor ?
Answer: A package cursor is a cursor which you declare in the package specification without an
SQL statement.The SQL statement for the cursor is attached dynamically at runtime from calling
procedures.
If you insert a row in a table, then create another table and then say Rollback.In this case will
the row be inserted ?
Answer: Yes.Because Create table is a DDL which commits automatically as soon as it is

executed.The DDL commits the transaction even if the create statement fails internally (eg table
already exists error) and not syntactically.
"I'm passing a ref cursor back from a function, how do I use the data in that ref cursor in my
select statement/query"
And, equally as often, the problem comes from a lack of understanding what a ref cursor
actually is. So I thought I'd give a quick summary of the basics behind ref cursors with a view to
giving a clearer understanding of them. (Please excuse any errors or ommissions)
1. What is a ref cursor and how is the data fetched
Let's start with a simple function that opens a ref cursor and passes it back..
(We'll just select some employee details for a specified department)
SQL> create or replace function get_dept_emps(p_deptno in number)
return sys_refcursor is
2
v_rc sys_refcursor;
3 begin
4
open v_rc for 'select empno, ename, mgr, sal from emp where
deptno = :deptno' using p_deptno;
5
return v_rc;
6 end;
7 /
Function created.
Now, if we look at using this through SQL*Plus we first create ourselves a ref cursor variable to
accept the results of the function, and then call the function to get the ref cursor back..
(Note: SQL*Plus variable type of "refcursor" is the equivalent of PL/SQL's "sys_refcursor")
SQL> var rc refcursor
SQL> exec :rc := get_dept_emps(10);
PL/SQL procedure successfully completed.
Ok, so our variable "rc" has our ref cursor.
If we use SQL*Plus' print command now we get..
SQL> print rc;
EMPNO ENAME
MGR
SAL
---------- ---------- ---------- ---------7782 CLARK
7839
2450
7839 KING
5000
7934 MILLER
7782
1300
Brilliant, so our ref cursor returns the rows we wanted from the employee table.
Let's look at that again..
SQL> print rc;
SP2-0625: Error printing variable "rc"
Uh oh! What's happened here? Why can't we print the data that's in our ref cursor again?
A common mistake is that people believe that a ref cursor actually contains the result data from
the query. In truth, the ref cursor doesn't contain any data at all, it's just a pointer to the query.

So why did the first print statement print out the results?
SQL*Plus looked at the ref cursor and saw that it was an open cursor. As such it went into a
loop, fetching each row of data from the database, using the ref cursor as it's reference (pointer)
to the relevant query, and displaying each row of data until it had no more rows to fetch. Once
it's fetched all the rows it closes the cursor. The power of SQL*Plus's "print" command eh!
Therefore, when we tried to print the ref cursor a second time, we got an error because
SQL*Plus looked at the cursor, saw it was not an open cursor and couldn't perform the task of
printing anything. Let's look at this in a bit more detail so it's a little clearer.
We'll use some PL/SQL code so that we can see the type of thing SQL*Plus us doing internally..
Firstly, let's get the open cursor and ask it how many rows it has..
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_rc
sys_refcursor;
3 begin
4
v_rc := get_dept_emps(10); -- This returns an open cursor
5
dbms_output.put_line('Rows: '||v_rc%ROWCOUNT);
6
close v_rc;
7* end;
SQL> /
Rows: 0
PL/SQL procedure successfully completed.
Yep, sure enough it's reporting 0 rows.
It's important that we remember that ROWCOUNT reports how many rows have
been fetched through the cursor. Just after opening the cursor we haven't fetched any rows
yet. If we fetch a row of data then we can see this change..
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_rc
sys_refcursor;
3
v_empno number;
4
v_ename varchar2(10);
5
v_mgr
number;
6
v_sal
number;
7 begin
8
v_rc := get_dept_emps(10); -- This returns an open cursor
9
dbms_output.put_line('Pre Fetch: Rows: '||v_rc%ROWCOUNT);
10
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
11
dbms_output.put_line('Post Fetch: Rows: '||v_rc%ROWCOUNT);
12
close v_rc;
13* end;
SQL> /

Pre Fetch: Rows: 0


Post Fetch: Rows: 1
PL/SQL procedure successfully completed.
So let's fetch all our data and display it..
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_rc
sys_refcursor;
3
v_empno number;
4
v_ename varchar2(10);
5
v_mgr
number;
6
v_sal
number;
7 begin
8
v_rc := get_dept_emps(10); -- This returns an open cursor
9
loop
10
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
11
exit when v_rc%NOTFOUND; -- Exit the loop when we've run out
of data
12
dbms_output.put_line('Row: '||v_rc%ROWCOUNT||' # '||
v_empno||','||v_ename||','||v_mgr||','||v_sal);
13
end loop;
14
close v_rc;
15* end;
SQL> /
Row: 1 # 7782,CLARK,7839,2450
Row: 2 # 7839,KING,,5000
Row: 3 # 7934,MILLER,7782,1300
PL/SQL procedure successfully completed.
And what happens if we try and fetch more data after it's finished, just like we tried to do in
SQL*Plus..
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_rc
sys_refcursor;
3
v_empno number;
4
v_ename varchar2(10);
5
v_mgr
number;
6
v_sal
number;
7 begin
8
v_rc := get_dept_emps(10); -- This returns an open cursor
9
loop
10
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
11
exit when v_rc%NOTFOUND; -- Exit the loop when we've run out
of data
12
dbms_output.put_line('Row: '||v_rc%ROWCOUNT||' # '||

v_empno||','||v_ename||','||v_mgr||','||v_sal);
13
end loop;
14
close v_rc;
15
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
16* end;
SQL> /
Row: 1 # 7782,CLARK,7839,2450
Row: 2 # 7839,KING,,5000
Row: 3 # 7934,MILLER,7782,1300
declare
*
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 15
As expected we get an error.
So now we understand the basics of what a ref cursor is.
You can clearly see that it is just a pointer to the query and it doesn't contain any data itself, it
just allows us to reference the query so that we can fetch data as we require it.
2. How can we use a ref cursor in a SQL query?
Ok, so now you've got your ref cursor you want to use it. But how can you fetch the data from
the ref cursor inside another SQL Select statement?
Perhaps we can just select from it?
SQL> select * from get_dept_emps(10);
select * from get_dept_emps(10)
*
ERROR at line 1:
ORA-00933: SQL command not properly ended
Nope. How about if we tell SQL to treat it as a table?
SQL> select * from table(get_dept_emps(10));
select * from table(get_dept_emps(10))
*
ERROR at line 1:
ORA-22905: cannot access rows from a non-nested table item
What about using it as a set of data in an IN condition?
SQL> select * from emp where empno in (get_dept_emps(10));
select * from emp where empno in (get_dept_emps(10))
*
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got CURSER
N.B. The spelling error of "CURSER" is Oracle's, not mine.
(Ok, I know the ref cursor is referencing more than just the empno in that example, but it would
still result in the same error if it just referenced the empno)

The problem we're having is because the ref cursor isn't a table of data either in the literal
database sense or in an array sense, and it's not a set of data that can be compared with the IN
clause.
So what's the point in these ref cursors? Is there a way we can use them?
Yes there is..
First let's create a type structure on the database. Remember, SQL cannot access PL/SQL
table structures so the type must be a database object..
SQL> create or replace type emptype as object(empno number,
2
ename varchar2(10),
3
mgr
number,
4
sal
number);
5 /
Type created.
SQL> create or replace type t_emptype as table of emptype;
2 /
Type created.
Ok, so we have a structure to hold a record and a type that is a table of that structure. So far so
good. But in order to populate that structure with data coming from the ref cursor we can't just
select from it as we saw above. Instead we need to provide some PL/SQL to actually do the
fetching of data for us and populate the structure..
SQL> ed
Wrote file afiedt.buf
1 create or replace function populate_emps(deptno in number :=
null)
2 return t_emptype is
3
v_emptype t_emptype := t_emptype(); -- Declare a local table
structure and initialize it
4
v_cnt
number := 0;
5
v_rc
sys_refcursor;
6
v_empno
number;
7
v_ename
varchar2(10);
8
v_mgr
number;
9
v_sal
number;
10 begin
11
v_rc := get_dept_emps(deptno);
12
loop
13
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
14
exit when v_rc%NOTFOUND;
15
v_emptype.extend;
16
v_cnt := v_cnt + 1;
17
v_emptype(v_cnt) := emptype(v_empno, v_ename, v_mgr, v_sal);
18
end loop;
19
close v_rc;

20
return v_emptype;
21* end;
SQL> /
Function created.
The above function calls the function that opens the ref cursor, then loops through, fetching each
row and populating our SQL type structure. When all rows have been fetched, the ref cursor is
closed and the SQL table structure is passed back from the function.
So now we have something in an structure that SQL understands, we should be able to query
directly from it..
SQL> select * from table(populate_emps(30));
EMPNO ENAME
MGR
SAL
---------- ---------- ---------- ---------7499 ALLEN
7698
1600
7521 WARD
7698
1250
7654 MARTIN
7698
1250
7698 BLAKE
7839
2850
7844 TURNER
7698
1500
7900 JAMES
7698
950
6 rows selected.
and
SQL> select * from emp where empno in (select empno from
table(populate_emps(30)));
EMPNO ENAME
JOB
MGR HIREDATE
SAL
COMM
DEPTNO
---------- ---------- --------- ---------- ----------- ------------------- ---------7499 ALLEN
SALESMAN
7698 20-FEB-1981
1600
300
30
7521 WARD
SALESMAN
7698 22-FEB-1981
1250
500
30
7654 MARTIN
SALESMAN
7698 28-SEP-1981
1250
1400
30
7698 BLAKE
MANAGER
7839 01-MAY-1981
2850
30
7844 TURNER
SALESMAN
7698 08-SEP-1981
1500
0
30
7900 JAMES
CLERK
7698 03-DEC-1981
950
30
6 rows selected.
SQL>
Hoorah!
We've successfully taken our ref cursor (pointer) and used it to fetch the data back that we want
in a structure that SQL can understand. Ok, the examples are pretty meaningless as they stand

as we could easily have achieved the same results through a basic select, but the method is
what is important to understand here.
3. What is the point of ref cursors?
A good question. Many people learn about ref cursors and then try and use them everywhere.
Although I personally know how to write and use ref cursors, I've found very little use for them in
my production code. If you are thinking of using a ref cursor, the first thing you
should ask yourself is "Why do I need one?"
If your answer is that you need to write your code to dynamically generate SQL, then perhaps
you should look at what you are trying to achieve. Typically dynamic SQL, in a lot of cases, is
unnecessary and a major cause of unmaintainable and unscalable code as well as possible
performance issues and SQL injection.
If you really have a valid need to dynamically create SQL and you fully understand the
implications and risks involved, then a ref cursor is useful for this task. What you will find
however is that you are limited with ref cursors to a fixed result structure, so it may not be as
generic a solution as you had initially planned for. If you consider the examples from above, you
will see that we had to define a SQL structure of known columns in order to receive the data
from the ref cursor. So, whilst the function that opens the ref cursor could do so for any piece of
query text, the only way of successfully getting the data out of that ref cursor is to know what
columns we are expecting back from it.
There is a way around this however. Either use the DBMS_SQL package to dynamically
generate and process your queries or, from 11g onwards, take your ref cursor and convert it to a
DBMS_SQL cursor using 11g's new DBMS_SQL.TO_CURSOR_NUMBER feature (
Exception Handling
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. Exceptions within code within the exception block
1. Understanding Execution Blocks (part 1)
The first thing that one needs to understand is almost taking us back to the basics of PL/SQL...
how a PL/SQL execution block is constructed.
Essentially an execution block is made of 3 sections...
+---------------------------+
|
Declaration Section
|

+---------------------------+
|
Statements Section
|
+---------------------------+
|
Exception Section
|
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or
the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the
EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory
section)
The Exception section is where any exception handling goes and lies between the EXCEPTION
keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name>
[(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This may seem a simple concept, but it's surprising how many people have issues showing they
haven't grasped it. When an Execution block is entered, the declaration section is processed,
creating a scope of variables, types , cursors, etc. to be visible to the execution block and then
execution enters into the Statements section. Each statment in the statements section is

executed in turn and when the execution completes the last statment the execution block is
exited back to whatever called it.
3. Exceptions
Exceptions generally happen during the execution of statements in the Statements section.
When an exception happens the execution of statements jumps immediately into the exception
section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one
of the two following things...
(Note: The exception section still has access to all the declared items in the declaration section)
3.i) Handle the exception
We do this when we recognise what the exception is (most likely it's something we expect to
happen) and we have a means of dealing with it so that our application can continue on.
Example...
(without the exception handler the exception is passed back to the calling code, in this case
SQL*Plus)
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_name VARCHAR2(20);
3 begin
4
select ename
5
into
v_name
6
from
emp
7
where empno = &empno;
8
dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old
7:
where empno = &empno;
new
7:
where empno = 123;
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling
code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf

1
2
3
4
5
6
7
8
9

declare
v_name VARCHAR2(20);
begin
select ename
into
v_name
from
emp
where empno = &empno;
dbms_output.put_line(v_name);
exception
10
when no_data_found then
11
dbms_output.put_line('There is no employee with this employee
number.');
12* end;
SQL> /
Enter value for empno: 123
old
7:
where empno = &empno;
new
7:
where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.

3.ii) Raise the exception


We do this when:a) we recognise the exception, handle it but still want to let the calling code know that it
happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_name VARCHAR2(20);
3
v_empno NUMBER := &empno;
4 begin
5
select ename
6
into
v_name
7
from
emp
8
where empno = v_empno;
9
dbms_output.put_line(v_name);
10 EXCEPTION
11
WHEN no_data_found THEN
12
INSERT INTO sql_errors (txt)

13
VALUES ('Search for '||v_empno||' failed.');
14
COMMIT;
15
RAISE;
16* end;
SQL> /
Enter value for empno: 123
old
3:
v_empno NUMBER := &empno;
new
3:
v_empno NUMBER := 123;
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
----------------------------------------------------Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_name VARCHAR2(20);
3
v_empno NUMBER := &empno;
4 begin
5
select ename
6
into
v_name
7
from
emp
8
where empno = v_empno;
9
dbms_output.put_line(v_name);
10 EXCEPTION
11
WHEN no_data_found THEN
12
INSERT INTO sql_errors (txt)
13
VALUES ('Search for '||v_empno||' failed.');
14
COMMIT;
15
RAISE;
16
WHEN others THEN
17
RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old
3:
v_empno NUMBER := &empno;
new
3:
v_empno NUMBER := 'ABC';

declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number
conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
-----------------------------------------------------------------------------Search for 123 failed.
SQL>
As you can see from the sql_errors log table, no log was written so the WHEN others exception
was the exception that raised the error to the calling code (SQL*Plus)
4. Understanding Execution Blocks (part 2)
Ok, so now we understand the very basics of an execution block and what happens when an
exception happens. Let's take it a step further...
Execution blocks are not just a single simple block in most cases. Often, during our statements
section we have a need to call some reusable code and we do that by calling a procedure or
function. Effectively this nests the procedure or function's code as another execution block
within the current statement section so, in terms of execution, we end up with something like...
+---------------------------------+
|
Declaration Section
|
+---------------------------------+
|
Statements Section
|
|
.
|
| +---------------------------+ |
| |
Declaration Section
| |
| +---------------------------+ |
| |
Statements Section
| |
| +---------------------------+ |
| |
Exception Section
| |
| +---------------------------+ |
|
.
|
+---------------------------------+
|
Exception Section
|
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)

SQL> create or replace procedure a as


2
v_dummy NUMBER := log_trace('Procedure A''s Declaration
Section');
3 begin
4
v_dummy := log_trace('Procedure A''s Statement Section');
5
v_dummy := 1/0; -- cause an exception
6 exception
7
when others then
8
v_dummy := log_trace('Procedure A''s Exception Section');
9
raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2
v_dummy NUMBER := log_trace('Procedure B''s Declaration
Section');
3 begin
4
v_dummy := log_trace('Procedure B''s Statement Section');
5
a; -- HERE the execution passes to the
declare/statement/exception sections of A
6 exception
7
when others then
8
v_dummy := log_trace('Procedure B''s Exception Section');
9
raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
-----------------------------------------------------------------------Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section

Procedure A's Exception Section


Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One of the common questions asked is how to return execution to the statement after the one
that created the exception and continue on.
Well, firstly, you can only do this for statements you expect to raise an exception, such as when
you want to check if there is no data found in a query.
If you consider what's been shown above you could put any statement you expect to cause an
exception inside it's own procedure or function with it's own exception section to handle the
exception without raising it back to the calling code. However, the nature of procedures and
functions is really to provide a means of re-using code, so if it's a statement you only use once it
seems a little silly to go creating individual procedures for these.
Instead, you nest execution blocks directly, to give the same result as shown in the diagram at
the start of part 4 of this article.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2
v_dummy NUMBER := log_trace('Procedure B''s Declaration
Section');
3 begin
4
v_dummy := log_trace('Procedure B''s Statement Section');
5
-- Here we start another execution block nested in the first one...
6
declare
7
v_dummy NUMBER := log_trace('Nested Block Declaration
Section');
8
begin
9
v_dummy := log_trace('Nested Block Statement Section');
10
select empno
11
into
v_dummy
12
from
emp
13
where empno = p_empno; -- Note: the parameters and variables
from
parent execution block are

available to use!
14
exception
15
when no_data_found then
16
-- This is an exception we can handle so we don't raise it
17
v_dummy := log_trace('No employee was found');
18
v_dummy := log_trace('Nested Block Exception Section Exception Handled');
19
when others then
20
-- Other exceptions we can't handle so we raise them
21
v_dummy := log_trace('Nested Block Exception Section Exception Raised');
22
raise;
23
end;
24
-- ...Here endeth the nested execution block
25
-- As the nested block handled it's exception we come back to
here...
26
v_dummy := log_trace('Procedure B''s Statement Section
Continued');
27 exception
28
when others then
29
-- We'll only get to here if an unhandled exception was raised
30
-- either in the nested block or in procedure b's statement
section
31
v_dummy := log_trace('Procedure B''s Exception Section');
32
raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
-------------------------------------------------------------------------------------Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued

7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
*
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
-------------------------------------------------------------------------------------Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>

You can see from this that, very simply, the code that we expected may have an exception was
able to either handle the exception and return to the outer execution block to continue execution,
or if an unexpected exception occurred then it was able to be raised up to the outer exception
section.
6. User defined exceptions
There are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business
logic) where, for example, certain criteria are not met to complete a task, and there are existing
Oracle errors that you wish to give a name to in order to capture them in the exception section.
The third is raising your own exception messages with our own exception numbers. Let's look at
the first one...
Let's say I have tables which detail stock availablility and reorder levels...

SQL> select * from reorder_level;


ITEM_ID STOCK_LEVEL
---------- ----------1
20
2
20
3
10
4
2
5
2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
---------- ---------- ----------1 Pencils
10
2 Pens
2
3 Notepads
25
4 Stapler
5
5 Hole Punch
3
SQL>
Now, our Business has told the administrative clerk to check stock levels and re-order anything
that is below the re-order level, but not to hold stock of more than 4 times the re-order level for
any particular item. As an IT department we've been asked to put together an application that
will automatically produce the re-order documents upon the clerks request and, because our
company is so tight-ar*ed about money, they don't want to waste any paper with incorrect
printouts so we have to ensure the clerk can't order things they shouldn't.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
from stock s join reorder_level r on (s.item_id = r.item_id)
7
where s.item_id = p_item_id;
8
-9
v_stock cur_stock_reorder%ROWTYPE;
10 begin
11
OPEN cur_stock_reorder;
12
FETCH cur_stock_reorder INTO v_stock;
13
IF cur_stock_reorder%NOTFOUND THEN
14
RAISE no_data_found;
15
END IF;

16
CLOSE cur_stock_reorder;
17
-18
IF v_stock.stock_level >= v_stock.reorder_level THEN
19
-- Stock is not low enough to warrant an order
20
DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level
yet!');
21
ELSE
22
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit
THEN
23
-- Required amount is over-ordering
24
DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max
for this item: '
||to_char(v_stock.reorder_limitv_stock.stock_level));
25
ELSE
26
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27
-- Here goes our code to print the order
28
END IF;
29
END IF;
30
-31 exception
32
WHEN no_data_found THEN
33
CLOSE cur_stock_reorder;
34
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much.

Max for this item: 70

PL/SQL procedure successfully completed.


SQL> exec re_order(2,50);
Order OK. Printing Order...

PL/SQL procedure successfully completed.


SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a
cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
from stock s join reorder_level r on (s.item_id = r.item_id)
7
where s.item_id = p_item_id;
8
-9
v_stock cur_stock_reorder%ROWTYPE;
10
-11
-- Let's declare our own exceptions for business logic...
12
exc_not_warranted EXCEPTION;
13
exc_too_much
EXCEPTION;
14 begin
15
OPEN cur_stock_reorder;
16
FETCH cur_stock_reorder INTO v_stock;
17
IF cur_stock_reorder%NOTFOUND THEN
18
RAISE no_data_found;
19
END IF;
20
CLOSE cur_stock_reorder;
21
-22
IF v_stock.stock_level >= v_stock.reorder_level THEN
23
-- Stock is not low enough to warrant an order
24
RAISE exc_not_warranted;
25
END IF;
26
-27
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28
-- Required amount is over-ordering
29
RAISE exc_too_much;
30
END IF;
31
-32
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33
-- Here goes our code to print the order
34
--

35 exception
36
WHEN no_data_found THEN
37
CLOSE cur_stock_reorder;
38
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39
WHEN exc_not_warranted THEN
40
DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level
yet!');
41
WHEN exc_too_much THEN
42
DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for
this item: '
||to_char(v_stock.reorder_limitv_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much.

Max for this item: 70

PL/SQL procedure successfully completed.


SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
That's better. And now we don't have to use all those nested IF statements and worry about it
accidently getting to code that will print the order out as, once one of our user defined
exceptions is raised, execution goes from the Statements section into the Exception section and
all handling of errors is done in one place.
Now for the second sort of user defined exception...

A new requirement has come in from the Finance department who want to have details shown
on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock current stock)/re-order quantity), so this needs calculating and passing to the report...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
,(((r.stock_level*4)-s.stock_level)/p_quantity) as
finance_factor
7
from stock s join reorder_level r on (s.item_id = r.item_id)
8
where s.item_id = p_item_id;
9
-10
v_stock cur_stock_reorder%ROWTYPE;
11
-12
-- Let's declare our own exceptions for business logic...
13
exc_not_warranted EXCEPTION;
14
exc_too_much
EXCEPTION;
15 begin
16
OPEN cur_stock_reorder;
17
FETCH cur_stock_reorder INTO v_stock;
18
IF cur_stock_reorder%NOTFOUND THEN
19
RAISE no_data_found;
20
END IF;
21
CLOSE cur_stock_reorder;
22
-23
IF v_stock.stock_level >= v_stock.reorder_level THEN
24
-- Stock is not low enough to warrant an order
25
RAISE exc_not_warranted;
26
END IF;
27
-28
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29
-- Required amount is over-ordering
30
RAISE exc_too_much;
31
END IF;
32
-33
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34
-- Here goes our code to print the order, passing the
finance_factor

35
-36 exception
37
WHEN no_data_found THEN
38
CLOSE cur_stock_reorder;
39
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40
WHEN exc_not_warranted THEN
41
DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level
yet!');
42
WHEN exc_too_much THEN
43
DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for
this item: '
||to_char(v_stock.reorder_limitv_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-06512: at line 1
SQL>

Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an
unhandled exception.
Well, we could put a condition/check into our code to make sure the parameter is not zero, but
again we would be wrapping our code in an IF statement and not dealing with the exception in
the exception handler.
We could do as we did before and just include a simple IF statement to check the value and
raise our own user defined exception but, in this instance the error is standard Oracle error
(ORA-01476) so we should be able to capture it inside the exception handler anyway...
however...

EXCEPTION
WHEN ORA-01476 THEN
... is not valid. What we need is to give this Oracle error a name.
This is done by declaring a user defined exception as we did before and then associating that
name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration
section.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
,(((r.stock_level*4)-s.stock_level)/p_quantity) as
finance_factor
7
from stock s join reorder_level r on (s.item_id = r.item_id)
8
where s.item_id = p_item_id;
9
-10
v_stock cur_stock_reorder%ROWTYPE;
11
-12
-- Let's declare our own exceptions for business logic...
13
exc_not_warranted EXCEPTION;
14
exc_too_much
EXCEPTION;
15
-16
exc_zero_quantity EXCEPTION;
17
PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19
OPEN cur_stock_reorder;
20
FETCH cur_stock_reorder INTO v_stock;
21
IF cur_stock_reorder%NOTFOUND THEN
22
RAISE no_data_found;
23
END IF;
24
CLOSE cur_stock_reorder;
25
-26
IF v_stock.stock_level >= v_stock.reorder_level THEN
27
-- Stock is not low enough to warrant an order
28
RAISE exc_not_warranted;
29
END IF;
30
-31
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32
-- Required amount is over-ordering

33
RAISE exc_too_much;
34
END IF;
35
-36
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37
-- Here goes our code to print the order, passing the
finance_factor
38
-39 exception
40
WHEN exc_zero_quantity THEN
41
DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42
WHEN no_data_found THEN
43
CLOSE cur_stock_reorder;
44
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45
WHEN exc_not_warranted THEN
46
DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level
yet!');
47
WHEN exc_too_much THEN
48
DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for
this item: '
||to_char(v_stock.reorder_limitv_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
,(((r.stock_level*4)-s.stock_level)/p_quantity) as
finance_factor
7
from stock s join reorder_level r on (s.item_id = r.item_id)
8
where s.item_id = p_item_id;
9
-10
v_stock cur_stock_reorder%ROWTYPE;

11
-12
exc_zero_quantity EXCEPTION;
13
PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15
OPEN cur_stock_reorder;
16
FETCH cur_stock_reorder INTO v_stock;
17
IF cur_stock_reorder%NOTFOUND THEN
18
RAISE no_data_found;
19
END IF;
20
CLOSE cur_stock_reorder;
21
-22
IF v_stock.stock_level >= v_stock.reorder_level THEN
23
-- Stock is not low enough to warrant an order
24
[b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached reorder level yet!');[/b]
25
END IF;
26
-27
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28
-- Required amount is over-ordering
29
RAISE_APPLICATION_ERROR(-20001, 'Quantity specified is too
much. Max for this item: '
||to_char(v_stock.reorder_limitv_stock.stock_level));
30
END IF;
31
-32
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33
-- Here goes our code to print the order, passing the
finance_factor
34
-35 exception
36
WHEN exc_zero_quantity THEN
37
DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
38
WHEN no_data_found THEN
39
CLOSE cur_stock_reorder;
40
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
41
WHEN OTHERS THEN
42
RAISE;
43* end;
SQL> /
Procedure created.
SQL> exec re_order(2,100);
BEGIN re_order(2,100); END;
*
ERROR at line 1:
ORA-20001: Quantity specified is too much. Max for this item: 78

ORA-06512: at "SCOTT.RE_ORDER", line 42


ORA-06512: at line 1
SQL> exec re_order(3,40);
BEGIN re_order(3,40); END;
*
ERROR at line 1:
ORA-20000: Stock has not reached re-order level yet!
ORA-06512: at "SCOTT.RE_ORDER", line 42
ORA-06512: at line 1
SQL>
As you can see from this we have raised exceptions with our own error numbers. You can use
any number from -20000 to -20999 for your own error messages.
As with previous examples, these error numbers can be associated with exception names using
the EXCEPTION datatypes and the PRAGMA EXCEPTION_INIT statements in the declaration
section.
So there we have it, capturing existing Oracle errors and handling business logic through raising
exceptions of our own.
7. Line number / Source of exception
One of the common problems people experience when they use exceptions is actually knowing
which line of their code the error occured on. The problem here is that when you include an
exception section in your execution block and then you raise an error from there to the calling
code, the calling code sees the exception as having orginated from the line of code in the
exception section that raised the error rather than the original line of code. Look at that last
example from the previous section of this article. It shows that the error happened on line 42 of
the re_order procedure, but if we look at line 42, that is the RAISE; statement in the exception
block, not the actual line of code where the exception happened.
So how do we find out where the error occurred?
One answer (perhaps the simplest) is to remove the actual exception handler that is dealing with
that error...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is

3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
,(((r.stock_level*4)-s.stock_level)/p_quantity) as
finance_factor
7
from stock s join reorder_level r on (s.item_id = r.item_id)
8
where s.item_id = p_item_id;
9
-10
v_stock cur_stock_reorder%ROWTYPE;
11
-12
exc_zero_quantity EXCEPTION;
13
PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15
OPEN cur_stock_reorder;
16
FETCH cur_stock_reorder INTO v_stock;
17
IF cur_stock_reorder%NOTFOUND THEN
18
RAISE no_data_found;
19
END IF;
20
CLOSE cur_stock_reorder;
21
-22
IF v_stock.stock_level >= v_stock.reorder_level THEN
23
-- Stock is not low enough to warrant an order
24
RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached reorder level yet!');
25
END IF;
26
-27
IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28
-- Required amount is over-ordering
29
RAISE_APPLICATION_ERROR(-20001, 'Quantity specified is too
much. Max for this item: '
||
to_char(v_stock.reorder_limit-v_stock.stock_level));
30
END IF;
31
-32
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33
-- Here goes our code to print the order, passing the
finance_factor
34
-35 exception
36
WHEN exc_zero_quantity THEN
37
DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
38
WHEN no_data_found THEN
39
CLOSE cur_stock_reorder;
40
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');

41* end;
SQL> /
Procedure created.
SQL> exec re_order(3,40);
BEGIN re_order(3,40); END;
*
ERROR at line 1:
ORA-20000: Stock has not reached re-order level yet!
ORA-06512: at "SCOTT.RE_ORDER", line 24
ORA-06512: at line 1
SQL>
Now, because the code is not capturing the exception itself, the original line number is passed
up until it gets to a point where it is handled (in this case where it is displayed by SQL*Plus)
An alternative is to use the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE function. Whilst
this doesn't provide the error itself, it does provide a full trace back through execution blocks to
the source of the error.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity
NUMBER) is
2
cursor cur_stock_reorder is
3
select s.stock_level
4
,r.stock_level as reorder_level
5
,(r.stock_level*4) as reorder_limit
6
,(((r.stock_level*4)-s.stock_level)/p_quantity) as
finance_factor
7
from stock s join reorder_level r on (s.item_id = r.item_id)
8
where s.item_id = p_item_id;
9
-10
v_stock cur_stock_reorder%ROWTYPE;
11
-12
exc_zero_quantity EXCEPTION;
13
PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15
OPEN cur_stock_reorder;
16
FETCH cur_stock_reorder INTO v_stock;
17
IF cur_stock_reorder%NOTFOUND THEN
18
RAISE no_data_found;
19
END IF;
20
CLOSE cur_stock_reorder;
21
--

22
23
24
order
25
26
27
28
29
much.

IF v_stock.stock_level >= v_stock.reorder_level THEN


-- Stock is not low enough to warrant an order
RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached relevel yet!');
END IF;
-IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
-- Required amount is over-ordering
RAISE_APPLICATION_ERROR(-20001, 'Quantity specified is too
Max for this item: '
||
to_char(v_stock.reorder_limit-v_stock.stock_level));
30
END IF;
31
-32
DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33
-- Here goes our code to print the order, passing the
finance_factor
34
-35 exception
36
WHEN exc_zero_quantity THEN
37
DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
38
WHEN no_data_found THEN
39
CLOSE cur_stock_reorder;
40
DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
41
WHEN OTHERS THEN
42
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRA
CE);
43
RAISE;
44* end;
SQL> /
Procedure created.
SQL> exec re_order(3,40);
ORA-06512: at "SCOTT.RE_ORDER", line 24
BEGIN re_order(3,40); END;
*
ERROR at line 1:
ORA-20000: Stock has not reached re-order level yet!
ORA-06512: at "SCOTT.RE_ORDER", line 43
ORA-06512: at line 1
SQL>

Another issue often encountered is when there are nested execution blocks that raise, capture,
raise again etc. the exceptions. It can be quite messy to keep track of the source of an error, so

a good error logging mechanism writing the error information as it happens to a table using
autonomous transactions and the information in the
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE is a well worthwhile method of dealing with
this
SQL> ed
Wrote file afiedt.buf
1 begin
2
begin
3
begin
4
raise no_data_found;
5
exception
6
when others then
7
raise_application_error(-20000,'nesting level 3
exception');
8
end;
9
exception
10
when others then
11
raise_application_error(-20000,'nesting level 2 exception');
12
end;
13 exception
14
when others then
15
raise_application_error(-20000,'nesting level 1 exception');
16* end;
SQL> /
begin
*
ERROR at line 1:
ORA-20000: nesting level 1 exception
ORA-06512: at line 15
Here we can only see that an error occured in the top level of execution.
There is another parameter on RAISE_APPLICATION_ERROR we can use if we are using that
procedure in our code...
SQL> ed
Wrote file afiedt.buf
1 begin
2
begin
3
begin
4
raise no_data_found;
5
exception
6
when others then
7
raise_application_error(-20000,'nesting level 3
exception', true);

8
9

end;
exception
when others then
raise_application_error(-20000,'nesting level 2 exception',

10
11
true);
12
end;
13 exception
14
when others then
15
raise_application_error(-20000,'nesting level 1 exception',
true);
16* end;
SQL> /
begin
*
ERROR at line 1:
ORA-20000: nesting level 1 exception
ORA-06512: at line 15
ORA-20000: nesting level 2 exception
ORA-20000: nesting level 3 exception
ORA-01403: no data found

This propagates the error stack back up to the calling level, so at least now we can see that the
error occured at the 3rd nested level and that it was a "no data found" error.
Finally, if we incorporate the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE with that we can
show all the information back down to the actual line where the error occurred.
SQL> ed
Wrote file afiedt.buf
1 begin
2
begin
3
begin
4
raise no_data_found;
5
exception
6
when others then
7
dbms_output.put_line(dbms_utility.format_error_backtrace);
8
raise_application_error(-20000,'nesting level 3
exception', true);
9
end;
10
exception
11
when others then
12
dbms_output.put_line(dbms_utility.format_error_backtrace);
13
raise_application_error(-20000,'nesting level 2 exception',
true);

14
end;
15 exception
16
when others then
17
dbms_output.put_line(dbms_utility.format_error_backtrace);
18
raise_application_error(-20000,'nesting level 1 exception',
true);
19* end;
SQL> /
ORA-06512: at line 4
ORA-06512: at line 8
ORA-06512: at line 13
begin
*
ERROR at line 1:
ORA-20000: nesting level 1 exception
ORA-06512: at line 18
ORA-20000: nesting level 2 exception
ORA-20000: nesting level 3 exception
ORA-01403: no data found
SQL>
In summary there are various means and methods for tracing where the exception occurred and
which method you use depends on your own requirements and needs for logging and/or
handling errors.
8. Exceptions within code within the exception block
This last section of the article is just a light finishing touch to it really.
What happens when an exception occurs inside the exception section of the execution block?
Well it's quite simple really, if you haven't figured it out already...
There are two things that will happen... either...
a) The exception will be raised up to the exception handler of the calling execution block to be
dealt with...
SQL> ed
Wrote file afiedt.buf
1 begin
2
begin
3
begin
4
raise no_data_found;
5
exception
6
when others then
7
dbms_output.put_line(1/0); -- Ooops!
8
raise_application_error(-20000,'nesting level 3

exception', true);
9
end;
10
exception
11
when others then
12
dbms_output.put_line(dbms_utility.format_error_backtrace);
13
raise_application_error(-20000,'nesting level 2 exception',
true);
14
end;
15 exception
16
when others then
17
dbms_output.put_line(dbms_utility.format_error_backtrace);
18
raise_application_error(-20000,'nesting level 1 exception',
true);
19* end;
SQL> /
ORA-06512: at line 7
ORA-06512: at line 13
begin
*
ERROR at line 1:
ORA-20000: nesting level 1 exception
ORA-06512: at line 18
ORA-20000: nesting level 2 exception
ORA-01476: divisor is equal to zero
ORA-01403: no data found
SQL>
From this example you can see that the exception that happened on line 7 (within the exception
handler) has prevented the continuing execution of the code in that exception handler and has
raised the exception straight back to the nested level above (2 in this case), although we do still
have the "no data found" exception on the error stack so we can detect two errors at once.
Smart eh!
b) The other thing that can happen is if the exception handler itself has a nested execution
block...
+---------------------------------+
|
Declaration Section
|
+---------------------------------+
|
Statements Section
|
+---------------------------------+
|
Exception Section
|
|
.
|
| +---------------------------+ |

| |
Declaration Section
| |
| +---------------------------+ |
| |
Statements Section
| |
| +---------------------------+ |
| |
Exception Section
| |
| +---------------------------+ |
|
.
|
+---------------------------------+
In this case the exception will be handled, if possible, in the exception handler of that execution
block before returning to the following statement in the exception handler...
SQL> ed
Wrote file afiedt.buf
1 begin
2
begin
3
begin
4
raise no_data_found;
5
exception
6
when others then
7
[b]begin -- nested execution block in the exception
handler
8
dbms_output.put_line(1/0);
9
exception
10
when others then
11
null; -- exception handled!
12
end;[/b]
13
raise_application_error(-20000,'nesting level 3
exception', true);
14
end;
15
exception
16
when others then
17
dbms_output.put_line(dbms_utility.format_error_backtrace);
18
raise_application_error(-20000,'nesting level 2 exception',
true);
19
end;
20 exception
21
when others then
22
dbms_output.put_line(dbms_utility.format_error_backtrace);
23
raise_application_error(-20000,'nesting level 1 exception',
true);
24* end;
SQL> /
ORA-06512: at line 13
ORA-06512: at line 18

begin
*
ERROR at line 1:
ORA-20000: nesting
ORA-06512: at line
ORA-20000: nesting
ORA-20000: nesting
ORA-01403: no data

level 1 exception
23
level 2 exception
level 3 exception
found

SQL>
By the way, I wouldn't recommend using WHEN OTHERS THEN NULL; in
production code otherwise you'll prevent any real errors from being found and probably get
the sack. I just did it to demonstrate
Q.What is a stored procedure?
A stored procedure is a sequence of statements that perform specific function.
A stored procedure is a named pl/sql block which performs an action.It is stored in the database
as a schema object and can be repeatedly executed.It can be invoked, parameterised and
nested.
Q.What is SQL*Loader?
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To
load data from external files into an Oracle database, two types of input must be provided to
SQL*Loader : the data itself and the control file. The control file describes the data to be loaded.
It describes the Names and format of the data files, Specifications for loading data and the Data
to be loaded (optional). Invoking the loader sqlload username/password controlfilename.
Q.What are the two parts of a procedure ?
the above person have answerd wrong. Or rather the question may be wrong. It should be
packages instead of procedures. What are the 2 parts of package ? But the question is what are
the 2 parts for procedue!!!
Procedure Specification and Procedure Body.
Q.What is Date Functions?
Date Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN &
SYSDATE.
Q.What is NVL?
NVL: Null value function converts a null value to a non-null value for the purpose of evaluating
an expression. Numeric Functions accept numeric I/P & return numeric values. They are MOD,
SQRT, ROUND, TRUNC & POWER.

Q.What is Intersect?
Intersect is the product of two tables listing only the matching rows.
Q.How to know the last executed procedure?
Execute procedure name (parameter1,parameter2)
Select timestamps, owner, obj_name, action_name from dba_audit_trail;this statement gives
last executed time for procedure , function & package.
Q.What are the Restrictions on Cursor Variables?
Currently, cursor variables are subject to the following restrictions:You cannot declare cursor
variables in a package spec. For example, the following declaration is not allowed:CREATE
PACKAGE emp_stuff AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
emp_cv EmpCurTyp; not allowedEND emp_stuff;You cannot pass cursor variables to a
procedure that is called through a database link.If you pass a host cursor variable to PL/SQL,
you cannot fetch from it on the server side unless you also open it there on the same server
call.You cannot use comparison operators to test cursor variables for equality, inequality, or
nullity.You cannot assign nulls to a cursor variable.Database columns cannot store the values of
cursor variables. There is no equivalent type to use in a CREATE TABLE statement.You cannot
store cursor variables in an associative array, nested table, or varray.Cursors and cursor
variables are not interoperable; that is, you cannot use one where the other is expected. For
example, you cannot
reference a cursor variable in a cursor FOR loop
Q.What is Minus?
Minus is the product of two tables listing only the non-matching rows.
Q.What are the cursor attributes used in PL/SQL?
% ISOPEN To check whether cursor is open or not
% ROWCOUNT Number of rows fetched/updated/deleted.
% FOUND To check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND To check whether cursor has fetched any row. True if no rows are featched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit
Cursors.
Q.What is Consistency?
consistency: states that until commit the data will not be reflected to other users,in order to
maintain proper consistency.
consider a example: if user A transfer money to user B. The changes are updates in A account
(debit) but until it will be updated in B (credit) too till then others will not be able to see the debit
of A. when debit to A and credit to B happen then one can see the updates hence maintain
consistency
Q.What are % TYPE and % ROWTYPE? What are the advantages of using these over data
types?
% TYPE provides the data type of a variable or a database column to that variable.

% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.
The advantages are : I. Need not know about variables data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
Q.What will the Output for this Coding
Declare
Cursor c1 is select * from emp FORUPDATE;
Z c1%rowtype;
Begin
Open C1;
Fetch c1 into Z;
Commit;
Fetch c1 in to Z;
end;
By declaring this cursor we can update the table emp through z,means wo not need to write
table name for updation,it may be only by z.
By issuing the TCL like commit or rollback, the cursor will be closed automatically, you cannat
fetch again. You will get an error if you
Q.What is Commit?
Commit is an event that attempts to make data in the database identical to the data in the form.
It involves writing or posting data to the database and committing data to the database. Forms
check the validity of the data in fields and records during a commit. Validity check are
uniqueness, consistency and db restrictions.
Q.Give the structure of the function?
FUNCTION name (argument list ..) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
Q.What is a cursor ? Why Cursor is required?
Cursor is a named private SQL area from where information can be accessed. Cursors are
required to process rows individually for queries returning multiple rows.
Q.If the application is running very slow? At what points you need to go about the
database in order to improve the performance?
For improving performance, we need to check the sql statement blocks , because for every sql

satement execution transfor to sql engine and come back to plsq engine that process takes
more time to process the plsql block.
Q.What are advantages fo Stored Procedures?
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
Q.What is difference b/w stored procedures and application procedures, stored function
and application function?
Stored procedures are subprogrammes stored in the database and can be called &executee
multiple times wherein an application procedure is the one being used for a particular
application same is the way for function.
Both can be executed any number of times. Only difference is that stored procedures/ functions
are stored in database in complied format while the application procedures/functions are not in
precomplied format and at run time has to be compiled.
Q.What is a cursor ? Why Cursor is required?
Cursor is a named private SQL area from where information can be accessed. Cursors are
required to process rows individually for queries returning multiple rows.
Q.State the difference between implicit and explicit cursors.
Implicit Cursor are declared and used by the oracle internally. whereas the explicit cursors are
declared and used by the user. more over implicitly cursors are no need to declare oracle
creates and process and closes autometically. the explicit cursor should be declared and closed
by the user.
Q.How to avoid using cursors? What to use instead of cursor and in what cases to do
so?
just use subquery in for clause
ex:
for emprec in (select * from emp)
loop
dbms_output.put_line(emprec.empno);
end loop;
no exit statement needed
implicit open,fetch,close occurs
Q.What is pl/sql?what are the advantages of pl/sql?
PL/SQL(a product of Oracle) is the programming language extension of sql.
It is a full-fledged language although it is specially designed for database centric activities.
Q.How to disable multiple triggers of a table at at a time?
ALTER TABLE
DISABLE ALL TRIGGER

Q.How many types of database triggers can be specified on a table ? What are they ?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
Q.Explain how procedures and functions are called in a PL/SQL block ?
Function can be called from SQL query + explicitly as well
e.g 1)select empno,salary,fn_comm(salary)from employee;
2)commision=fn_comm(salary);
Procedure can be called from begin-end clause.
e.g.
Begin
(
proc_comm(salary);
)
end
Function is called as part of an expression.
sal := calculate_sal (a822);
procedure is called as a PL/SQL statement
calculate_bonus (A822);
Q.What will happen after commit statement ?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;
commit;
end loop;
end;
The cursor having query as SELECT . FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT. does not get closed even after COMMIT/ROLLBACK.
Q.What happens if a procedure that updates a column of table X is called in a database
trigger of the same table ?
Trigger will be called Based on the event what trigger as to do. if trigger is also doing the

same update statment then Mutating Table occurs. if trigger is not doing any DML statment
nothing happens just Trigger will be called..
Q.Can we declare a column having number data type and its scale is larger than
pricesion
ex: column_name NUMBER(10,100),
column_name NUMBAER(10,-84)
Yes,
we can declare a column with above condition.
table created successfully.
Q.The IN operator may be used if you know the exact value you want to return for at least
one of the columns.
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
Q.What is SQL Deadlock?
Deadlock is a unique situation in a multi user system that causes two or more users to wait
indefinitely for a locked resource. First user needs a resource locked by the second user and
the second user needs a resource locked by the first user. To avoid dead locks, avoid using
exclusive table lock and if using, use it in the same sequence and use Commit frequently to
release locks.
Q.Where the Pre_defined_exceptions are stored ?
In the standard package.
Procedures, Functions & Packages ;
Q. Below is the table
city gender name
delhi male a
delhi female b
mumbai male c
mumbai female d
delhi male e
I want the o/p as follows:
male female
delhi 2 1
mumbai 1 1
Please help me in writing the query that can yield the o/p mentioned above?
select city, sum(decode(gender,male,1,0)) Male_cnt, sum(gender,female,1,0) female_cnt
from table_name
group by city
select a.city,a.male,b.female from
(select city,count(gender) male from city where gender=m'group by city,gender)a
join

(select city,count(gender) female from city where gender=f group by city,gender)b


on a.city=b.city
Q.What is Sequences?
Sequences are used for generating sequence numbers without any overhead of locking.
Drawback is that after generating a sequence number if the transaction is rolled back, then that
sequence number is lost
Q.What are % TYPE and % ROWTYPE ? What are the advantages of using these over
datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.
The advantages are : I. Need not know about variables data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
Q.What is Mutating SQL Table?
Mutating Table is a table that is currently being modified by an Insert, Update or Delete
statement. Constraining Table is a table that a triggering statement might need to read either
directly for a SQL statement or indirectly for a declarative Referential Integrity constraints.
Pseudo Columns behaves like a column in a table but are not actually stored in the table. E.g.
Currval, Nextval, Rowid, Rownum, Level etc.
Q.What is PL/SQL table ?
Objects of type TABLE are called PL/SQL tables, which are modeled as (but not the same as)
database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a
primary key.
Cursors
PL/SQL tables are PL/SQL?s way of providing arrays. Arrays are like tem-porary
tables in memory and thus are processed very quickly. It is impor-tant
for you to realize that they are not database tables, and DML
statements cannot be issued against them. This type of table is indexed
by a binary integer counter (it cannot be indexed by another type of
number) whose value can be referenced using the number of the index.
Remember that PL/SQL tables exist in memory only, and therefore dont
exist in any persistent way, disappearing after the session ends.
A PL/SQL TABLE DECLARATION
There are two steps in the declaration of a PL/SQL table. First, you must define the table
structure using the TYPE statement. Second, once a table type is created, you then declare the
actual table.
FOR EXAMPLE
DECLARE
Table structure definition

TYPE NameType IS TABLE OF


Customer.name_name%TYPE
INDEX BY BINARY_INTEGER;
Create the actual table
CnameTab NameType;
KnameTab NameType;
BEGIN
NULL;
END;
Q.In a Distributed Database System Can we execute two queries simultaneously?
Justify?
Yes, Distributed database system based on 2 phase commit,one query is independent of 2 nd
query so of course we can run.
Q.What are the modes of parameters that can be passed to a procedure ?
IN parameter is the default mode which acts as a constant inside calling environment.value
passed in this parameter can not be changed.OUT parameter mode is used to pass value from
calling environment into main block,here we can change the value.It acts as a variable inside
calling environment.
INOUT parameter mode which pass value into calling environment and will get the value back in
main block.
IN parameter mode uses call by reference method to pass value from formal parameter to
actual parameter.
OUT & INOUT parameter mode uses call by value method to pass values.
IN,OUT,IN-OUT parameters.
Q.Name the tables where characteristics of Package, procedure and functions are
stored?
User_objects, User_Source and User_error.
Q.How many types of database triggers can be specified on a table? What are they?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
Q.How can a function retun more than one value in oracle with proper example?
Basically as per property of function it has to return one value. So the other values can be
returned from the out parameter of the function.

But its advised if you want more that one return value go for procedure however function will
also yield the same result.
Q.Explain If the entire disk is corrupted how will you and what are the steps to recover
the database?
if the entire disk is corrupted and no backup is there don nothing sit and relax their is no
possibility of recovery a backup is required for restoration and for recovery redo log and
archive logs.
Once if you have theses than think of recovering ..a dba should always plan for the recovery
scenario depending upon the criticality of the database.oracle provides 0% data loss facilty
through data guard and online backup .its dba who has to decide.
Q.What is Rollback?
Rollback causes work in the current transaction to be undone.
Q.What is a cursor for loop ?
Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of
values from active set into fields in the record and closes when all the records have been
processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;
Q.How to sort the rows in SQL?
Sort the Rows:
SELECT column1, column2, FROM table_name ORDER BY columnX, columnY, ..
SELECT column1, column2, FROM table_name ORDER BY columnX DESC
SELECT column1, column2, FROM table_name ORDER BY columnX DESC, columnY
ASC1.
select column1,column2,column3 from table1
where
column1>10
order by 1,3,2;
Inthis case it sorts based on the columns position in the select query i.e. in the above query it
will sort first based on column1 then on column3 and then by column2. By default the sort is in
ascending order, if you want it to be in descending order, you need to specify the key word
DESC in ORDER BY clause.
2.select * from emp order by eno desc;
You can sort your results based on any column in the tables because you are select all the
columns.
3.select eno,ename from emp order by deptno;
This is wrong because the column deptno is not present in the select clause.

Q.What is Pragma EXECPTION_INIT? Explain the usage?


The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle
error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number
Q.Whats the use of dyanamic sql in oracle?
Dynamic SQL enables you to write programs that reference SQL statements whose full text is
not known until runtime.
Q.How we can create a table in PL/SQL block. insert records into it? is it possible by
some procedure or function? please give example?
CREATE OR REPLACE PROCEDURE ddl_create_proc (p_table_name IN VARCHAR2)
AS
l_stmt VARCHAR2(200);
BEGIN
DBMS_OUTPUT.put_line(STARTING );
l_stmt := create table || p_table_name || as (select * from emp );
execute IMMEDIATE l_stmt;
DBMS_OUTPUT.put_line(end );
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(exception ||SQLERRM || message||sqlcode);
END;
Q.What is a JOIN?
JOIN is the form of SELECT command that combines info from two or more tables.
Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.
Equijoin returns rows from two or more tables joined together based upon a equality condition in
the WHERE clause.
Non-Equijoin returns rows from two or more tables based upon a relationship other than the
equality condition in the WHERE clause.
Outer Join combines two or more tables returning those rows from one table that have no direct
match in the other table.
Self Join joins a table to itself as though it were two separate tables.
Q.what is the starting oracle error number?
what is meant by forward declaration in functions?
One must declare an identifier before referencing it. Once it is declared it can be referred even
before defining it in the PL/SQL. This rule applies to function and procedures also.
Q.Can we declare a column having number data type and its scale is larger than
pricesion
ex: column_name NUMBER(10,100),
column_name NUMBAER(10,-84)

No, you cant. May be your table might be created successfully but if you try to insert values it
will shows you an error.
Numeric or Value Error
NUMBER (p,s)
p- precision, which is the total size of digits
s- scale , which represents the total number of digits that are present to the right side of the
decimal.
s should be strictly less than p. If I am missing somthing. Please fill me in.
Yes,we can declare a column with above condition.table created successfully.
yes, 100 is the total size and 10 is included in 100
Q.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in
Database Trigger? Why?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a
trigger, it affects logical transaction processing.
yes WE can use COMMIT and ROLLBACK triggers, but by using PRAGAMA
AUTONAMOUS_TRANSATIONS. Now the transation treated as a autonomous tansation.
Q.What is COLUMN?
COLUMN command define column headings & format data values.
Q.SELECT statements in SQL?
SELECT column_name(s) FROM table_name
SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column)
condition value
Note that single quotes around text values and numeric values should not be enclosed in
quotes. Double quotes may be acceptable in some databases.
Q.What is the Delete Statements in SQL?
Delete statement in SQL is used to delete partial/all data.
Especially delete statement is useful in case of partial delete depending upon our criterias
otherwise use TRUNCATE to delete whole data from table.
When delete command fires then:
1) Triggers will fire (If created on that table)
2) This will not auto commit changes made So there is one chance to rollback.
3) If u delete whole data then HWM (Highest Water Mark) will not change which gets changed in
case of Truncate.

Q.What is Posting?
Posting is an event that writes Inserts, Updates & Deletes in the forms to the database but not
committing these transactions to the database.
Q.Where the Pre_defined_exceptions are stored?
In the standard package.
Procedures, Functions & Packages ;
Q.What are two parts of package?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package
Specification contains declarations that are global to the packages and local to the schema.
Package Body contains actual procedures and local declaration of the procedures and cursor
declarations.
Q.What are the data types a available in PL/SQL?
Some scalar data types such as
NUMBER,
VARCHAR2,
DATE,
CHAR,
LONG,
BOOLEAN.
Some composite data types such as RECORD & TABLE.
Q.What is an Exception? What are types of Exception?
Exception is the error handling part of PL/SQL block. The types are Predefined and user
defined. Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
exception is an identifier and error handling part of pl/sql types := 1)predifined 2) user defined.

Q.Explian rowid, rownum?what are the psoducolumns we have?


ROWID Hexa decimal number each and every row having unique.Used in searching.
ROWNUM It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are
NEXTVAL,CURRVAL Of sequence are some exampls
psudo columns are default columns provided by oracle
Q.How to avoid using cursors? What to use instead of cursor and in what cases to do
so?
Just use subquery in for clause
ex:For emprec in (select * from emp)
loop
dbms_output.put_line(emprec.empno);
end loop;
no exit statement needed
implicit open,fetch,close occurs
Q.what is the starting oracle error number?
what is meant by forward declaration in functions?
One must declare an identifier before referencing it. Once it is declared it can be referred even
before defining it in the PL/SQL. This rule applies to function and procedures also
ORA-20000
Q.What are the components of a PL/SQL block?
A set of related declarations and procedural statements is called block.
DECLARE declaration section BEGIN executable statements main section
EXCEPTION handling possible exceptions occuring in the main section END;
Q.What is difference between stored procedures and application procedures,stored
function and application function?
Stored procedures are sub programs stored in the database and can be called & execute
multiple times where in an application procedure is the one being used for a particular
application same is the way for function
Procedure:Execute as a PL/SQL
statement,No RETURN clause in
the header,Can return none, one,
or many values,Can contain a RETURN
statement
Function:-Invoke as part of an
expression,Must contain a RETURN
clause in the header,Must return a single value,Must contain at least one RETURN statement

Q.What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database
trigger.
Q.What is trigger,cursor,functions in pl-sql and we need sample programs about it?
Trigger is an event driven PL/SQL block. Event may be any DML transaction.
Cursor is a stored select statement for that current session. It will not be stored in the database,
it is a logical component.
Function is a set of PL/SQL statements or a PL/SQL block, which performs an operation and
must return a value.
Q.How we can create a table in PL/SQL block. insert records into it??? is it possible by
some procedure or function?? please give example
CREATE OR REPLACE PROCEDURE ddl_create_proc (p_table_name IN VARCHAR2)
AS
l_stmt VARCHAR2(200);
BEGIN
DBMS_OUTPUT.put_line(STARTING );
l_stmt := create table || p_table_name || as (select * from emp );
execute IMMEDIATE l_stmt;
DBMS_OUTPUT.put_line(end );
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(exception ||SQLERRM || message||sqlcode);
END;
Q.In pl/sql functions what is use of out parameter even though we have return statement.
With out parameters you can get the more than one out values in the calling program. It is
recommended not to use out parameters in functions. If you need more than one out values
then use procedures instead of functions.
Q.How to debug the procedure ?
You can use DBMS_OUTPUT oracle supplied package or DBMS_DEBUG pasckage.
Q.What is ref cursor?
In PL/SQL ,pointer has a datatype REF X where
REF-Reference
X-class of objects
Cursor Variables has a datatype REF-CURSOR
where Cursor Varibales are like pointers which hold the memory location of some item instead
of the item itself.
Q.State the advantage and disadvantage of Cursor?
Advantage :

In pl/sql if you want perform some actions more than one records you should user these cursors
only. bye using these cursors you process the query records. you can easily move the records
and you can exit from procedure when you required by using cursor attributes.
disadvantage:
using implicit/explicit cursors are depended by sutiation. if the result set is les than 50 or 100
records it is better to go for implicit cursors. if the result set is large then you should use exlicit
cursors. other wise it will put burdon on cpu.
Q.What is a database trigger ? Name some usages of database trigger ?
A database triggers is stored PL/SQL program unit associated with a specific database table or
view. The code in the trigger defines the action the database needs to perform whenever some
database manipulation (INSERT, UPDATE, DELETE) takes place.
Unlike the stored procedure and functions, which have to be called explicitly, the database
triggers are fires (executed) or called implicitly whenever the table is affected by any of the
above said DML operations.
Till oracle 7.0 only 12 triggers could be associated with a given table, but in higher versions of
Oracle there is no such limitation. A database trigger fires with the privileges of owner not that of
user
A database trigger has three parts
1. A triggering event
2. A trigger constraint (Optional)
3. Trigger action
A triggering event can be an insert, update, or delete statement or a instance shutdown or
startup etc. The trigger fires automatically when any of these events occur A trigger constraint
specifies a Boolean expression that must be true for the trigger to fire. This condition is specified
using the WHEN clause. The trigger action is a procedure that contains the code to be executed
when the trigger fires.
Database trigger is stored PL/SQL program unit associated with a specific database table.
Usages are Audit data modifications, Log events transparently, Enforce complex business rules
Derive column values automatically, Implement complex security authorizations. Maintain
replicate tables.
Q.What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
Q.How packaged procedures and functions are called from the following?
a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS
a.PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.

BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out
parameters. A function can not be called.
Q.Operators used in SELECT statements are?
= Equal
<> or != Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Q.Give the structure of the procedure ?
basically procedure has three
parts
1.variable declaretion(optional)
2.body(mandetory)
3.Exception(optional)
suppose ex
CREATE OR REPLACEPROCEDURE emp_pro( p_id IN employees.employee_id%TYPE)
IS
v_name employees.last_name%TYPE;
v_mail employees.email%TYPE;
BEGIN
SELECT last_name,email INTO v_name,v_mail FROM employees
WHERE employee_id:=p_id;
DBMS_OUTPUT.PUT_LINE(NAME:||v_name ||MAILID:||v_mail);
END;
/
PROCEDURE name (parameter list..)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;

Q.What is SPOOL?
spool command used for printing the out put of the sql statments in a file. Eg.
spool /tmp/sql_out.txt
select emp_name, emp_id from emp where dept=sales;
spool off;
we can see the out on /tmp/sql_out.txt file.
SPOOL command creates a print file of the report.
Q.What are advantages fo Stored Procedures
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
Q.IS Stored Function Is Pre-Compiled as Stored Procedure ? If No Why
stored procedure means the pre-compiled precedure ,which is used for a specific action to be
executed more than one times whenever you called from coding in the programe.
stored procedure is an important concept in the application developement in oracle.
Q.Explain the two type of Cursors ?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries. User defined cursors are called Explicit Cursors. They
can be declared and used.
Q.What is Overloading of procedures ?
Overloading of procedure
name of the procedure is
same but the number of parameters should be different.In that case,procedure will be
overloaded.
2. if the number of parameters are same in that case,data type should be different.
if the two rules are satisfied in that case procedure will be overloaded.
Q.What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural programming
language constructs such as iteration, conditional branching.
Q.What are the PL/SQL Statements used in cursor processing ?
DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record
types, CLOSE cursor name.
Q.What is Set Transaction?
Set Transaction is to establish properties for the current transaction.
Q.What is Character Functions?
Character Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions
are GREATEST & LEAST. Group Functions returns results based upon groups of rows rather
than one result per row, use group functions. They are AVG, COUNT, MAX, MIN & SUM.

Q.What is an Exception ? What are types of Exception?


Exception is the error handling part of PL/SQL block. The types are Predefined and user
defined. Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
Q.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in
Database Trigger? Why?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a
trigger, it affects logical transaction processing.
yes WE can use COMMIT and ROLLBACK triggers, but by using PRAGAMA
AUTONAMOUS_TRANSATIONS. Now the transation treated as a autonomous tansation.
Q.What is Multiple columns?
Multiple columns can be returned from a Nested Subquery.
Q.What is Savepoint?
Savepoint is a point within a particular transaction to which you may rollback without rolling back
the entire transaction.

SQL and PL/SQL Interview Questions-2


Q.Explain the usage of WHERE CURRENT OF clause in cursors ?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row
fetched from a cursor. Database Triggers
Q.In a Distributed Database System Can we execute two queries simultaneously ? Justify
?
When 2 people are using DRL command it is possible to execute multiple queries
simultaneously.

When we are performing DML operation (update,delete) exclusive lock will be applied on
specific record so, DML operation is not possible.
As Distributed database system based on 2 phase commit,one query is independent of 2 nd
query so of course we can run.
Q.Can Commit,Rollback ,Savepoint be used in Database Triggers?If yes than HOW? If no
Why?With Reasons
we cannot commit inside a trigger.
As we all know that when a dml is complete one can issue a commit.
A trigger if created is fired before the dml completes.
so we cannot commit intermediately.
Q.What will the Output for this Coding?
Declare
Cursor c1 is select * from emp FORUPDATE;
Z c1%rowtype;
Begin
Open C1;
Fetch c1 into Z;
Commit;
Fetch c1 in to Z;
end;
By declaring this cursor we can update the table emp through z,means wo not need to write
table name for updation,it may be only by z.
Q.How we can create a table through procedure ?
You can create table from procedure using Execute immediate command.
Q.What are two parts of package ?
package has two parts
1.Package specification
2.Package body
In the specification,where we declare variable,function,procedure
that is global to the package and local to the schema.
package body contains the defination of the function,procedure.we can also declare private
function and procedure which is not accessble
out side the package.
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package
Specification contains declarations that are global to the packages and local to the schema.
Package Body contains actual procedures and local declaration of the procedures and cursor
declarations.
Q.The most important DDL statements in SQL are?
CREATE TABLE creates a new database table

ALTER TABLE alters (changes) a database table


DROP TABLE deletes a database table
CREATE INDEX creates an index (search key)
DROP INDEX deletes an index
Q.What is difference between a Cursor declared in a procedure and Cursor declared in a
package specification ?
A cursor declared in a package specification is global and can be accessed by other procedures
or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.
Q.What is the basic structure of PL/SQL ?
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be
used in PL/SQL.
Q.What is Correlated Subquery?
Correlated Subquery is a subquery that is evaluated once for each row processed by the parent
statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart
questions whose answer depends on the value in each row processed by parent statement.
Q.Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
I & ii.
Exception
First column should be validated by constraints and then Triggers
Q.What are two virtual tables available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.
Two tables are: OLD and NEW.
Insert Trigger :
OLD no value.
NEW inserted value.
UPDATE TRIGGER OLD- old value.
NEW- new updated value.
DELETE TRIGGER
OLD old value.
NEW no value.

Q.The SELECT INTO Statement is most often used to create backup copies of tables or for
archiving records?
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE
column_name operator value.
Q.What is Data types?
Max. columns in a table is 255. Max. Char size is 255, Long is 64K & Number is 38 digits.
Cannot Query on a long column.
Char, Varchar2 Max. size is 2000 & default is 1 byte.
Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.
Long Character data of variable length upto 2GB.
Date Range from Jan 4712 BC to Dec 4712 AD.
Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.
Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.
Q.What is Pragma EXECPTION_INIT? Explain the usage?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle
error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
Q.What is a cursor ? Why Cursor is required ?
The oracle server uses works areas
called private sql area.Here all the DML statement is executed and to processing
statement.basically
its a implicit cursor.
there are two types of cursor
1.Implicit cursor.
2.Explicit cursor.
Implicit cursor is open for all DML statement.after execute the statement cursor is atomatically
closed.
Explicit cursor is created by programmer.
explicit cursor is needed when
query returns more than one rows.
In that case,programmer creates
explicit cursor.open the cursor.
then fetch the value from the active set.
after fetching all the value,
cursor is closed by programmer.
Q.Explain the usage of WHERE CURRENT OF clause in cursors?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row
fetched from a cursor. Database Triggers

Q.What is the basic structure of PL/SQL?


PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be
used in PL/SQL.
Q.Who to put a unique constraint on column if duplicate data is already present in that column?
If duplicate data is already there then instead of putting unique constraint on one column, put
unique constraint on two or more columns.
Q.What is SET?
SET command changes the system variables affecting the report environment.
Q.What is Locking?
Locking are mechanisms intended to prevent destructive interaction between users accessing
data. Locks are used to achieve.
Q.Explain the usage of WHERE CURRENT OF clause in cursors?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row
fetched from a cursor. Database Triggers
Q.The INSERT INTO Statements in SQL?
INSERT INTO table_name VALUES (value1, value2,.)
INSERT INTO table_name (column1, column2,) VALUES (value1, value2,.)
Q.What is the basic structure of PL/SQL?
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be
used in PL/SQL.
Q.What is difference between a Cursor declared in a procedure and Cursor declared in a
package specification?
A cursor declared in a package specification is global and can be accessed by other procedures
or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.
Q.I can not see the answer of the pl/cql code like addition of two no.s. afterall i write
dbms_output.put_line(addition is|| c). Only the line PL/SQL procedure successfully completed.
is showing when i end the code by /
before executing the procedure,
set serveroutput on;
Q.Where the Pre_defined_exceptions are stored?
In the standard package.
Procedures, Functions & Packages ;

Q.What is difference between a PROCEDURE & FUNCTION?


A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
Q.How can a function retun more than one value in oracle with proper example?
yes we can use objects, arrays to return more than one value
Q.How to know the last executed procedure?
Execute procedure name (parameter1,parameter2)
Select timestamps, owner, obj_name, action_name from dba_audit_trail;this statement gives
last executed time for procedure , function & package.
Q.Name the tables where characteristics of Package, procedure and functions are stored ?
User_objects, User_Source and User_error.
Q.1)What is the starting oracle error number?
2)What is meant by forward declaration in functions?
One must declare an identifier before referencing it. Once it is declared it can be referred even
before defining it in the PL/SQL. This rule applies to function and procedures also
Q.What is difference between a PROCEDURE & FUNCTION ?
A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
In case of function,it must have
return type.
In case of procedure,it may or may nt have return type.
In case of function, only it takes IN parameters
IN case of procedure
only it take IN,OUT,INOUT parameters..
Q.Give the structure of the function ?
FUNCTION name (argument list ..) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
Q.What is Union?
Union is the product of two or more tables. Which is removed duplicate values from the query.
Union is the product of two or more tables.
Q.What are the components of a PL/SQL Block ?
Declare

variable declaration
Begin
Execution part
Exception
Exception handling
End;
Declarative part, Executable part and Exception part.
Datatypes PL/SQL
Q.What are two virtual tables available during database trigger execution?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.
Q.What is Synonyms?
Synonyms is the alias name for table, views, sequences & procedures and are created for
reasons of Security and Convenience.
Two levels are Public created by DBA & accessible to all the users. Private Accessible to
creator only. Advantages are referencing without specifying the owner and Flexibility to
customize a more meaningful naming convention.
Q.What is COMPUTE?
command control computations on subsets created by the BREAK command.When we are
trying to determine the sum of some columns in a result set we can use Compute. This function
is used for reporting purpose.
Q.What is the use of CASCADE CONSTRAINTS?
Integrity key is violated when one tried to delete parent key value when foreign key value.
A parent key value can only be deleted after foreign key value.
Cascade constraints has dual purpose.
1.Alter table command can be issued with ON DELETE CASCADE
When this is done one can run delete command with cascade constriaint to delete parent key
value.
2.To drop a table that has parent values.
With cascade constraint,foreign key constraint on child table and parent table is dropped.The
child table still exits.
When this clause is used with the DROP command, a parent table can be dropped even when a
child table exists.
Q.The Update Statement in SQL.
UPDATE table_name SET column_name = new_value WHERE column_name = some_value

Q.How Can i convert the Columns In to Row in a oracle Select Query ?


By using matrix report query
Example:
select job,sum(DECODE(deptno,10,sal)) d10_sal,
sum(DECODE(deptno,20,sal)) d20_sal,
sum(DECODE(deptno,30,sall)) d30_sal,
sum(sal) total
from emp group by job;
Q.What are two virtual tables available during database trigger execution?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.
Q.What is difference between % ROWTYPE and TYPE RECORD?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
One more point : When we have a variable of typer RECORD we have declare additional
variables but with %rowtype, we can only have the fields that are present in the table
Q.How can a function retun more than one value in oracle with proper example?
yes we can use objects, arrays to return more than one value
Q.Write a PL/SQL block to list all the managers
DECLARE
LV_MANAGER_NAME VARCHAR2(100);
LN_COUNT NUMBER;
CURSOR C1 AS
SELECT * FROM EMP_DETAILS WHERE DESIGNATION = MANAGER
BEGIN
LN_COUNT := 0;
FOR EMPDET IN C1 LOOP
LV_MANAGER_NAME := EMPDET.EMP_NAME;
LN_COUNT = LN_COUNT+1;
DBMS_OUTPUT.PUT_LINE(MANAGER ||LN_COUNT|| -> ||LV_MANAGER_NAME);
END LOOP;
EXCEPTION

WHEN OTHERS THEN


DBMS_OUTPUT.PUT_LINE(EXCEPTION OCCURED:||SQLERRM);
END;
Q.Explian rowid,rownum?What are the pseduocolumns we have?
ROWID Hexa decimal number each and every row having unique.Used in searching
ROWNUM It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are
NEXTVAL,CURRVAL Of sequence are some examples
Q.What is Pragma EXECPTION_INIT ? Explain the usage ?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle
error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
Q.Write a PL/SQL block to update the salary of an employee whose empno is 7839 and print
the message as ?Record Updated?.
begin
update employee(tablename) set salary=(salary)*o.1 where empno=7839;
dbms_output.put_line(record updated);
end;
declare
a exception;
begin
update emp set sal=(sal*0.1) where empno=7839;
if sql%rowcount>0 then
dbms_output.put_line(sql%rowcount || records are updated );
else
raise a;
end if;
exception
when a then
dbms_output.put_line(records are not updated);
end;
Q.How packaged procedures and functions are called from the following?
a.Stored procedure or anonymous block
b.an application program such a PRC *C, PRO* COBOL
c.SQL *PLUS
a.PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)

variable := PACKAGE NAME.FUNCTION NAME (arguments);


END;
END EXEC;
c.EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out
parameters. A function can not be called.
Q.What is TTITLE and BTITLE?
TTITLE & BTITLE are commands to control report headings & footers.
Q.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in
Database Trigger ? Why
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a
trigger, it affects logical transaction processing.
No, we can not use Commit or Rollback, within a trigger. To understand, take one simple
example
Suppose two persons are using one common table and they both have written trigger on that
table. If in the first trigger we are using commit/rollback, then the second use would get some
unwanted result.
That is the reason, why we dont use Commit/Rollback in Triggers.
Yeah. If some type of failure/ breakdown occurs, in that case Oracle automatically Rollback the
data.
Q.select seq1.nextval from dual
It returns two values at a time.
100
100
Is it possible?If so how?
select naw1.nextval,naw1.currval into n from dual;
Well, in a way it is:
SQL> create sequence foo_seq start with 100 increment by 3;
Sequence created.
SQL> create table dual (dummy varchar2(1));
Table created.
SQL> insert into dual values (X);
1 row created.
SQL> insert into dual values (Y);
1 row created.
SQL> commit;
Commit complete.
SQL> select foo_seq.nextval from dual;
NEXTVAL
100
103

SQL>
Its a mean trick to play on developers.
Q.What will the Output for this Coding>
Declare
Cursor c1 is select * from emp FORUPDATE;
Z c1%rowtype;
Begin
Open C1;
Fetch c1 into Z;
Commit;
Fetch c1 in to Z;
end;
By declaring this cursor we can update the table emp through z,means wo not need to write
table name for updation,it may be only by z.
By issuing the TCL like commit or rollback, the cursor will be closed automatically, you cannot
fetch again.
Q.How to avoid using cursors? What to use instead of cursor and in what cases to do so?
Just use subquery in for clause
ex:For emprec in (select * from emp)
loop
dbms_output.put_line(emprec.empno);
end loop;
no exit statement needed
implicit open,fetch,close occurs
Q.What are the return values of functions SQLCODE and SQLERRM?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
Q.Explian rowid, rownum?what are the psoducolumns we have?
ROWID Hexa decimal number each and every row having unique.Used in searching.
ROWNUM It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are
NEXTVAL,CURRVAL Of sequence are some exampls
psudo columns are default columns provided by oracle
Q.Give the Types of modules in a form?
Form
Menu
Library

Q.What happens if a procedure that updates a column of table X is called in a database trigger
of the same table?
Mutation of table occurs.
Q.Can we declare a column having number data type and its scale is larger than pricesion
ex: column_name NUMBER(10,100),
column_name NUMBAER(10,-84)
Yes,we can declare a column with above condition.table created successfully.
yes, 100 is the total size and 10 is included in 100
Q.What is SQL Integrity?
Assures database data and structures reflects all changes made to them in the correct
sequence. Locks ensure data integrity and maximum concurrent access to data. Commit
statement releases all locks. Types of locks are given below.
Data Locks protects data i.e. Table or Row lock.
Dictionary Locks protects the structure of database object i.e. ensures tables structure does not
change for the duration of the transaction.
Internal Locks & Latches protects the internal database structures. They are automatic.
Exclusive Lock allows queries on locked table but no other activity is allowed.
Share Lock allows concurrent queries but prohibits updates to the locked tables.
Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.
Row Exclusive same as Row Share but prohibits locking in shared mode.
Shared Row Exclusive locks the whole table and allows users to look at rows in the table but
prohibit others from locking the table in share or updating them.
Share Update are synonymous with Row Share.
Q.What are the components of a PL/SQL block ?
components of PL/SQL are:
declare:
(optional) variable declare
Begin:
(Mandatory)Procedural statement
Exception:
(optional)
error to be trapped
End:
(Mandatory)
So BEGIN and END are required in PL/SQL block
Q.What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different table or views
and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type);

e_rec emp% ROWTYPE


cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
Q.What are the datatypes a available in PL/SQL ?
1.Character Datatypes:
char(size), nchar(size), varchar2(size), nvarchar2(size),long, raw, longraw
2.Numeric Datatypes number(p,s), numeric(p,s),float, dec(p,s), decimal(p,s),integer, int,
smallint,real, double precision
3.Date/Time Datatypes:
date, timestamp, timestamp with local time zone, timestamp with time zone, interval year to
month, interval day to second
4.LOB data types:
bfile,blob,clob,nclob
5. Rowid Data types:
rowid,urowid
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.
Q.Explian rowid, rownum? what are the psoducolumns we have ?
ROWID Hexa decimal number each and every row having unique.Used in searching.
ROWNUM It is a integer number also unique for sorting Normally TOP N Analysys.
Other Psudo Column are NEXTVAL,CURRVAL Of sequence are some examples
psudo columns are default columns provided by oracle
both rowid n rownum are psedocolumns, but
rowid- is physical address for each record in the memory.
rownum gives the numbering to rows returned by sql select statement.
Q.What is Indexes?
Indexes are optional structures associated with tables used to speed query execution and/or
guarantee uniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of
the rows in a large table and columns are referenced frequently in the WHERE clause. Implied
tradeoff is query speed vs. update speed. Oracle automatically update indexes. Concatenated
index max. is 16 columns.
Q.What is Raise_application_error?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an
user_defined error messages from stored sub-program or database trigger.
Q.State the difference between implict and explict cursors?
Collapse/Expand Answer of Question State the difference between implict and explict cursors?
Implicit Cursor are declared and used by the oracle internally. whereas the explicit cursors are
declared and used by the user. more over implicitly cursors are no need to declare oracle
creates and process and closes autometically. the explicit cursor should be declared and closed

by the user.
Implicit cursors are used for single row query whereas explicit cursor is used for multiple row
query
Do you have any collection of Interview Questions and interested to share with us!!
Please send that collection to iq@GlobalGuideline.Com along with the category and sub
category information
Q.What are the modes of parameters that can be passed to a procedure?
IN,OUT,IN-OUT parameters.
Q.What will happen after commit statement?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;
commit;
end loop;
end;
The cursor having query as SELECT . FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT. does not get closed even after COMMIT/ROLLBACK.
Q.How many types of database triggers can be specified on a table? What are they?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
Q.What will be the Output for this Coding
Declare
Cursor c1 is select * from emp FORUPDATE;
Z c1%rowtype;
Begin
Open C1;
Fetch c1 into Z;
Commit;
Fetch c1 in to Z;

By declaring this cursor we can update the table emp through z,means wo not need to write
table name for updation,it may be only by z.
By issuing the TCL like commit or rollback, the cursor will be closed automatically, you cannat
fetch again.
Q.What will happen after commit statement?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;
commit;
end loop;
end;
The cursor having query as SELECT . FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT. does not get closed even after COMMIT/ROLLBACK.
Q.What is an oracle stored procedure?
A stored procedure is a sequence of statements that perform specific function.
Q.Explain the usage of WHERE CURRENT OF clause in cursors?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row
fetched from a cursor. Database Triggers
ell some new features in PL/SQL in 10g (Intermediate to Advanced)
- Regular expression functions REGEXP_LIKE , REGEXP_INSTR, REGEXP_REPLACE, and
REGEXP_SUBSTR
- Compile time warnings
- Conditional compilation
- Improvement to native compilation
- BINARY_INTEGER made similar to PLS_INTEGER
- INDICES OF , VALUES OF in FORALL lets you work on non-consecutive indices

- Quoting mechanism . Instead of quoting single quotes twice everytime, give your own delimiter
to go on using single quotes.
Ex: q'!I'm a string, you're a string.!'
- Flashback Query functions. SCN_TO_TIMESTAMP, TIMESTAMP_TO_SCN
- Implicit conversion between CLOB and NCLOB
- Improved Overloading
- New datatypes BINARY_FLOAT, BINARY_DOUBLE
- Global optimization enabled
- PLS_INTEGER range increased to 32bit
- DYNAMIC WRAP using DBMS_DDL
3. What tools/utilities might you use to help tune your SQL?
It amazes me that I've in the past picked up books on PL/SQL code and they never
even have a small section on tuning SQL. While tuning SQL might not be on the top
of a PL/SQL developer's list of things to do, properly tuned SQL is at the core of
producing well executing PL/SQL code and applications. Being able to run an
EXPLAIN PLAN, and understanding its output, is critical and I'd never hire a
developer that didn't understand how to produce efficient SQL. The following
EXPLAIN COMMAND utility could be used to produce an explain plan for the given
SELECT statement:
SQL> EXPLAIN PLAN FOR select * from mytable;
4. Besides running an EXAPLAIN PLAN to view the execution path of a SQL
statement, what other means might you use to view explain plans?
After a SQL statement has executed you can view the EXPLAIN PLAN (if it's still in
the shared SQL area) through the V$SQL_PLAN view. It is good to note that, while
obtaining an EXPAIN PLAN through the use of the EXPLAIN PLAN command utility,
as in question #3, viewing the EXPLAIN PLAN through the V$SQL_PLAN view gives
the real access path taken during execution. Overloading modules is nothing more
than a mechanism that allows the coder to reuse the same name for different
programs that are within the same scope. Overloading is probably one of my
favorite mechanisms to share and increase usability within code.

7. Name a tracing utility that helps isolate PL/SQL problems and describe
what it does.
The Trace API, DBMS_TRACE package, enables you to trace the orders in which
subprograms run; allowing you to also specify which subprograms to run and
placement of statistics gathered in database tables for custom reporting.
Q2. What is a mutating and constraining table?
Mutating means changing. A mutating table is a table that is currently being modified by an
update, delete, or insert statement. When a trigger tries to reference a table that is in state of
flux (being changed), it is considered mutating and raises an error since Oracle should not
return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign
or unique key columns of the table off which it fires. If you must have triggers on tables that
have referential constraints, the workaround is to enforce the referential integrity through
triggers as well.

There are several restrictions in Oracle regarding triggers:


A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD

still can be accessed by the trigger).


A statement-level trigger cannot query or modify a mutating table if the trigger is fired as
the result of a CASCADE delete.
Analytic Functions, which have been available since Oracle 8.1.6, are designed to
address such problems as "Calculate a running total", "Find percentages within a
group", "Top-N queries", "Compute a moving average" and many more. Most of
these problems can be solved using standard PL/SQL, however the performance is
often not what it should be. Analytic Functions add extensions to the SQL language
that not only make these operations easier to code; they make them faster than
could be achieved with pure SQL or PL/SQL. These extensions are currently under
review by the ANSI SQL committee for inclusion in the SQL specification.
How Analytic Functions Work ?
Analytic functions compute an aggregate value based on a group of rows. They
differ from aggregate functions in that they return multiple rows for each group.
The group of rows is called a window and is defined by the analytic clause. For
each row, a "sliding" window of rows is defined. The window determines the range
of rows used to perform the calculations for the "current row". Window sizes can be
based on either a physical number of rows or a logical interval such as time.
Analytic functions are the last set of operations performed in a query except for the
final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are

completed before the analytic functions are processed. Therefore, analytic functions
can appear only in the select list or ORDER BY clause.
The Syntax
The Syntax of analytic functions is rather straightforward in appearance
Analytic-Function(<Argument>,<Argument>,...)
OVER (
<Query-Partition-Clause>
<Order-By-Clause>
<Windowing-Clause>
)
o

Analytic-Function

Specify the name of an analytic function, Oracle actually provides many analytic
functions such
as AVG, CORR,COVAR_POP, COVAR_SAMP, COUNT, CUME_DIST, DENSE_RANK,FIR
ST, FIRST_VALUE, LAG, LAST, LAST_VALUE, LEAD, MAX,MIN, NTILE, PERCENT_RA
NK, PERCENTILE_CONT,PERCENTILE_DISC, RANK, RATIO_TO_REPORT, STDDEV,ST
DDEV_POP, STDDEV_SAMP, SUM, VAR_POP, VAR_SAMP,VARIANCE.
o

Arguments

Analytic functions take 0 to 3 arguments.


o

Query-Partition-Clause

The PARTITION BY clause logically breaks a single result set into N groups,
according to the criteria set by the partition expressions. The words "partition" and
"group" are used synonymously here. The analytic functions are applied to each
group independently, they are reset for each group.
o

Order-By-Clause

The ORDER BY clause specifies how the data is sorted within each group (partition).
This will definitely affect the outcome of any analytic function.
o

Windowing-Clause

The windowing clause gives us a way to define a sliding or anchored window of


data, on which the analytic function will operate, within a group. This clause can be
used to have the analytic function compute its value based on any arbitrary sliding
or anchored window within a group. More information on windows can be
found here.

Example: Calculate a running Total


This example shows the cumulative salary within a departement row by row, with
each row including a summation of the prior rows salary.
set autotrace traceonly explain
break on deptno skip 1
column ename format A6
column deptno format 999
column sal format 99999
column seq format 999
SELECT ename "Ename", deptno "Deptno", sal "Sal",
SUM(sal)
OVER (ORDER BY deptno, ename) "Running Total",
SUM(SAL)
OVER (PARTITION BY deptno
ORDER BY ename) "Dept Total",
ROW_NUMBER()
OVER (PARTITION BY deptno
ORDER BY ENAME) "Seq"
FROM emp
ORDER BY deptno, ename
/
Ename Deptno
Sal Running Total Dept Total Seq
------ ------ ------ ------------- ---------- ---CLARK
10
2450
2450
2450
1
KING
5000
7450
7450
2
MILLER
1300
8750
8750
3
ADAMS
FORD
JONES
SCOTT
SMITH

20

1100
3000
2975
3000
800

9850
12850
15825
18825
19625

1100
4100
7075
10075
10875

1
2
3
4
5

ALLEN
BLAKE
JAMES
MARTIN
TURNER
WARD

30

1600
2850
950
1250
1500
1250

21225
24075
25025
26275
27775
29025

1600
4450
5400
6650
8150
9400

1
2
3
4
5
6

Execution Plan
--------------------------------------------------0
SELECT STATEMENT Optimizer=CHOOSE
1
0
WINDOW (SORT)
2
1
TABLE ACCESS (FULL) OF 'EMP'
Statistics
---------------------------------------------------

0
0
3
0
0
1658
503
2
1
0
14

recursive calls
db block gets
consistent gets
physical reads
redo size
bytes sent via SQL*Net to client
bytes received via SQL*Net from client
SQL*Net roundtrips to/from client
sorts (memory)
sorts (disk)
rows processed

The example shows how to calculate a "Running Total" for the entire query. This
is done using the entire ordered result set, via SUM(sal) OVER (ORDER BY deptno,
ename).
Further, we were able to compute a running total within each department, a total
that would be reset at the beginning of the next department. The PARTITION BY
deptno in that SUM(sal) caused this to happen, a partitioning clause was specified
in the query in order to break the data up into groups.
The ROW_NUMBER() function is used to sequentially number the rowsreturned
in each group, according to our ordering criteria (a "Seq" column was added to in
order to display this position).
The execution plan shows, that the whole query is very well performed with only 3
consistent gets, this can never be accomplished with standard SQL or even PL/SQL.