The Most Important DDL Statements in SQL Are
The Most Important DDL Statements in SQL Are
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?
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.
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
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?
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
'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);
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.
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)
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.
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
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.
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?
?
?
?
?
?
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 ?
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:
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 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:
Java:
Incurs some data conversion overhead between the Database and Java type
Java is an Object Orientated language, and modules are structured into classes
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
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
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)';
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;
=>
=>
=>
=>
=>
'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;
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.
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;
/
Grant direct access on the tables to your user. Do not use roles!
"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;
/
pcalled@DBLINK2(TabX);
END;
/
[edit]What is the difference between stored procedures and functions?
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.
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.
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
%ROWCOU
NT
cursor_name
%ROWCOUNT
%ISOPEN
cursor_name%ISOPEN
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 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.
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
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> /
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.
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)
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...
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.
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.
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
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.
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
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.
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.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.
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
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
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
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);
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 [email protected] 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.
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
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
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.