You are on page 1of 70

1. What is major difference between sql and plsql?

---- SQL is a query language that allows you to issue a single query or execute a single
insert/update/delete. PL-SQL is Oracle's "Programming Language" SQL, which allows you
to write a full program (loops, variables, etc.) to accomplish multiple
selects/inserts/updates/deletes.
---- 1.) SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL
is a procedural language to create applications.

2.) PL/SQL can be the application language just like Java or PHP can. PL/SQL might be the
language we use to build, format and display those screens, web pages and reports.SQL
may be the source of data for our screens, web pages and reports.

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

4.) 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).

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

6.) We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL
statement.

---- 1.) SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL
is a procedural language to create applications. 

2.) PL/SQL can be the application language just like Java or PHP can. PL/SQL might be the
language we use to build, format and display those screens, web pages and reports.SQL
may be the source of data for our screens, web pages and reports. 

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

4.) 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).

5.) SQL is used to code queries, DML and DDL statements. PL/SQL is used to


code program blocks, triggers, functions, procedures and packages.

6.) We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL
statement.

7.) SQL is a language that is used by relational database technologies such as Oracle,
Microsoft Access, and Sybase etc., PL/SQL is commonly used to write data-centric
programs to manipulate data in an Oracle database. PL/SQL language includes object
oriented programming techniques such as encapsulation, function overloading, and
information hiding (all but inheritance).

2. What is join and how many types of joins?


---- SQL JOIN is a method to retrieve data from two or more database tables.

---- An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them.

The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN return all rows from multiple tables where the join condition is met.

---- 1. JOIN or INNER JOIN :

In this kind of a JOIN, we get all records that match the condition in both the tables, and
records in both the tables that do not match are not reported.

In other words, INNER JOIN is based on the single fact that : ONLY the matching entries in
BOTH the tables SHOULD be listed.

Note that a JOIN without any other JOIN keywords (like INNER, OUTER, LEFT, etc) is an
INNER JOIN. In other words, INNER JOIN is a Syntactic sugar for JOIN (see : Difference
between JOIN and INNER JOIN).
2. OUTER JOIN :

Outer Join retrieves

Either, the matched rows from one table and all rows in the other table Or, all rows in all
tables (it doesn't matter whether or not there is a match).

There are three kinds of Outer Join :

2.1 LEFT OUTER JOIN or LEFT JOIN


This join returns all the rows from the left table in conjunction with the matching rows from
the right table. If there are no columns matching in the right table, it returns NULL values.

2.2 RIGHT OUTER JOIN or RIGHT JOIN


This join returns all the rows from the right table in conjunction with the matching rows from
the left table. If there are no columns matching in the left table, it returns NULL values.

2.3 FULL OUTER JOIN or FULL JOIN


This join combines left outer join and right outer join. It returns row from either table when
the conditions are met and returns null value when there is no match.

In other words, OUTER JOIN is based on the fact that : ONLY the matching entries in ONE
OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.

Note that OUTER JOIN is a loosened form of INNER JOIN.


3. NATURAL JOIN :

It is based on the two conditions :

1. the JOIN is made on all the columns with the same name for equality.
2. Removes duplicate columns from the result.
This seems to be more of theoretical in nature and as a result (probably) most DBMS don't
even bother supporting this.

4. CROSS JOIN :

It is the Cartesian product of the two tables involved. The result of a CROSS JOIN will not
make sense in most of the situations. Moreover, we wont need this at all (or needs the
least, to be precise).

5. SELF JOIN :

It is not a different form of JOIN, rather it is a JOIN (INNER, OUTER, etc) of a table to itself.

3. Differences between count(1) and count(*)?


Count(1):counts the total no.of records in the first column of the table.here 1 means first
column of the table.
Count(*):counts the total no.of records of the table based on all columns(*) of the table.
Most of cases both gives the same output.

4. What is the difference between joins and set operators?


---joins:
A JOIN is a Query which is used to retreive the data from more than two tables in a single
Query.
Set operators:
A set operator is used in a Query, to retreive the data from multiple queries(select
statements) which are having same number of attributes or objects in select query and
matching data types.
………………………………………………………………………
 Set operators
o combine multiple SELECTs
o Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries.
 Joins
o combine multiple tables
o An SQL JOIN clause is used to combine rows from two or more tables, based on a
common field between them
o SQL Joins are used to relate information in different tables. A Join condition is a part of the sql
query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE
Clause of select, update, delete statements.

5. How to display the 3rd highest salary in the employee table?


----SELECT SAL FROM EMP E1 WHERE &N-1=(SELECT COUNT(DISTINCT(SAL))
FROM EMP E2 WHERE E2.SAL>E1.SAL)

----SELECT ENAME,SAL,SAL_RANK FROM (SELECT


ENAME,SAL,DENSE_RANK()OVER(ORDER BY SAL DESC) SAL_RANK) WHERE
SAL_RANK =&N;

6. How to display the employee who joined after 15 th of any month?

7. What is view? Tell me different views?


----A view is a logical or virtual component used for fast retrieval of data from database
tables.It stores in user_views system table in database and sharable across users.
Different types of views:
1.simple view
2.complex view
3.read only view
4.force view
5.join view
6.materialized view

8. What is materialized view and difference between view and mview?


Materialized view:
----Materialized views are disk based and update periodically base upon the query definition.

What is Materialized View in database


Materialized views are also logical view of our data driven by select query but the result of the
query will get stored in the table or disk, also definition of the query will also store in the
database .When we see the performance of Materialized view it is better than normal View because
the data of materialized view will stored in table and table may be indexed so faster for joining also
joining is done at the time of materialized views refresh time so no need to every time fire join
statement as in case of view.

View:

---- Views are virtual only and run the query definition each time they are accessed

Views are logical virtual table created by “select query” but the result is not stored anywhere
in the disk and every time we need to fire the query when we need data, so always we get updated
or latest data from original tables. Performance of the view depend upon our select query. If we want
to improve the performance of view we should avoid to use join statement in our query or if we need
multiple joins between table always try to use index based column for joining as we know index
based columns are faster than non index based column. View allow to store definition of the query in
the database itself.

9. What is inline view ?have you ever used in your project?


---- 1.An inline view is a SELECT statement in the FROM-clause of another SELECT statement. In-line views
are commonly used to simplify complex queries by removing join operations and condensing several separate
queries into a single query. This feature was introduced in Oracle 7.2.

2.This feature is commonly referred to in the MSSQL community as a derived table, and in the Postgres
community simply refers to it as a subselect (subselects are inline views + subqueries in Oracle nomenclature

Select statement follows from clause of the sub query is called inline view
Example:
SELECT ENAME,SAL,E1.DEPTNO,E2.MAXSAL FROM EMP E1,
 (SELECT DEPTNO,MAX(SAL) MAXSAL FROM EMP GROUP BY DEPTNO order by deptno)E2
WHERE E1.DEPTNO=E2.DEPTNO AND E1.SAL<E2.MAXSAL;
(Or)

select max(age)
from (
-- this part of the query is an inline view:
select age from table
)

10. Difference between where clause and having clause?


----1. the difference between the having and where clause in sql is that the where clause can not be used
with aggregates, but the having clause can. One way to think of it is that the having clause is an additional
filter to the where clause.
2.the where clause doesn’t work with aggregates – like sum, avg, max, etc.. Instead, what we will need to
use is the having clause. The having clause was added to sql just so we could compare aggregates to other
values – just how the ‘where’ clause can be used with non-aggregates.
Example:

GOOD SQL:
select employee, sum(bonus) from emp_bonus
group by employee having sum(bonus) > 1000;
where clause+having clause ---posible
where clause +group by clause ----not possible
groupby clause+having clause ----posible
 We can write orderby clause with all clauses based on condition.

11. Difference between sub query and correlated subquery?


----Query with in a query is calle sub query.
Subquery :- The inner query is executed only once The inner query will get executed first and
the output of the inner query used by the outer query.The inner query is not dependent on
outer query.

Eg:- SELECT cust_name, dept_no FROM Customer WHERE cust_name IN (SELECT cust_name
FROM Customer);

Correlated subquery:-The outer query will get executed first and for every row of outer query,
inner query will get executed. So the inner query will get executed as many times as no.of
rows in result of the outer query.The outer query output can use the inner query output for
comparison. This means inner query and outer query dependent on each other

Eg:- SELECT cust_name,dept_id FROM Cust


WHERE cust_name in (SELECT cust_name FROM dept WHERE cust.dept_id=dept.dept_id);

12. What is the difference between CUBE and ROLLUP operators

1. CUBE generates a result set that shows aggregates for all combinations of values in the
selected columns.

In addition to the subtotals generated by the ROLLUP extension, the CUBE extension will generate subtotals for
all combinations of the dimensions specified. If "n" is the number of columns listed in the CUBE, there will be
2nsubtotal combinations.

SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY CUBE (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67
2 5 4508.74
2 26237.04
1 10016.39(4363.55+5652.84)
2 9377.78(4794.76+4583.02)
3 10274.02(4718.25+5555.77)
4 11324.12 SO ON…
5 9536.08
50528.39

18 rows selected.

2. ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected
columns.

----the ROLLUP extension produces group subtotals from right to left and a grand total. If "n" is the
number of columns listed in the ROLLUP, there will be n+1 levels of subtotals. Looking at the output in
a SQL*Plus or a grid output, you can visually identify the rows containing subtotals as they have null
values in the ROLLUP columns. Obviously, if the raw data contains null values, using this visual
identification is not an accurate approach

SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY ROLLUP (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67
2 5 4508.74
2 26237.04
50528.39

13 rows selected.

13. What is the use of the group by clause?


----The SQL GROUP BY Clause can be used in a SQL SELECT query to collect data across multiple records
and group the results by one or more columns.
----The GROUP BY clause will gather all of the rows together that contain data in
the specified column(s) and will allow aggregate functions to be performed on
the one or more columns.

Let's say you would like to retrieve a list of the highest paid salaries in each
dept:

SELECT max(salary), dept

FROM employee

GROUP BY dept;

This statement will select the maximum salary for the people in each unique
department. Basically, the salary for the person who makes the most in each
department will be displayed. Their, salary and their department will be
returned.

14. IN vs EXISTS operators..give me one scenario?


EXISTS:
Oracle provides multiple operators under various categories which can be used in queries to filter the
result set. In SQL, EXISTS is an operator which can be used in WHERE clause to validate an “IT
EXISTS” condition
EXISTS is a Comparison operator, which is used to check and match records between two queries on
correlation basis and returns a BOOLEAN output (TRUE or FALSE). The two queries are designated as
the Outer (or) Parent query and the Sub query.

Note: NOT EXISTS is the negation format of EXISTS.

SELECT EMPNO, ENAME, DEPARTMENT_ID


FROM EMPLOYEE E
WHERE EXISTS (SELECT 1 FROM EMP_CLUB WHERE EMPNO = E.EMPNO)

IN:
The Oracle PL/SQL IN operator allows testing a term of a condition by comparing it for equality
with a list of fixed values. The condition defined using the IN operator is also known as
themembership condition. IN works with values of all data types. When using characters, dates,
or other non-numeric strings, the list items must be enclosed with single quotation marks (for
example, '2010-09-22'), as shown in the second example below.

Example Syntax:

1)
SELECT *

FROM EMPLOYEES

WHERE SALARY IN (1500, 3000, 2500)


2)
SELECT *

FROM EMPLOYEES

WHERE CITY IN ('Seattle', 'Memphis', 'Los Angeles')

15. Rownum vs rowid ?


 ----an Oracle ROWID uniquely identifies where a row resides on disk.  The
information in a ROWID gives Oracle everything he needs to find your row, the
disk number, the cylinder, block and offset into the block. 
----  ROWID is a semi-physical value specifying the location of a row (in terms of data file, extent,
etcetera). ROWID is not very useful in day-to-day programming, as it is not a constant value (it changes
with table re-organizations, imports, and things like that). Therefore it requires caution in its use.
- ROWNUM is a logical value for the sequence of row retrieval in the resultset. This is the position before
sorting, so rownum is not always the same as the position in the resultset presented to you. This also
requires some caution.
Rownum:
Rownum is unique number assigned to the records in result set.it comes along with select
statement but not store in database.it is used only for display purpose in result set.
Rowed:
Row id is a 18 bit hexadecimal unique number,which is used to locate specific record in the
database.it stores permanently in database and reusable component.

Select rowid,row num from emp;

16. Pseudo columns ?

---- A pseudo-column is an Oracle assigned value (pseudo-field) used in the same context as an
Oracle Database column, but not stored on disk. SQL and PL/SQL recognizes the following SQL
pseudocolumns, which return specific data items: SYSDATE, SYSTIMESTAMP, ROWID,
ROWNUM, UID, USER, LEVEL, CURRVAL, NEXTVAL, ORA_ROWSCN, etc.

Pseudocolumns are not actual columns in a table but they behave like columns. For example, you can
select values from a pseudocolumn. However, you cannot insert into, update, or delete from a
pseudocolumn. Also note that pseudocolumns are allowed in SQL statements, but not in procedural
statements.

17. Lag vs lead functions


Lag: The LAG function is used to access data from a previous row. The following query
returns the salary from the previous row to calculate the difference between the salary of
the current row and that of the previous row. Notice that the ORDER BY of the LAG function is
used to order the data by salary.

The LAG function is used to access data from a previous row. The following query returns the salary from the
previous row to calculate the difference between the salary of the current row and that of the previous row.
Notice that the ORDER BY of the LAG function is used to order the data by salary.

SELECT empno,
ename,
job,
sal,
LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_prev,
sal - LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_diff
FROM emp;

EMPNO ENAME JOB SAL SAL_PREV SAL_DIFF


---------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 800 0 800
7900 JAMES CLERK 950 800 150
7876 ADAMS CLERK 1100 950 150
7521 WARD SALESMAN 1250 1100 150
7654 MARTIN SALESMAN 1250 1250 0
7934 MILLER CLERK 1300 1250 50
7844 TURNER SALESMAN 1500 1300 200

Lead: The LEAD function is used to return data from the next row. The following query
returns the salary from the next row to calulate the difference between the salary of the
current row and the following row.

The LEAD function is used to return data from the next row. The following query returns the salary from the
next row to calulate the difference between the salary of the current row and the following row.

SELECT empno,
ename,
job,
sal,
LEAD(sal, 1, 0) OVER (ORDER BY sal) AS sal_next,
LEAD(sal, 1, 0) OVER (ORDER BY sal) - sal AS sal_diff
FROM emp;

EMPNO ENAME JOB SAL SAL_NEXT SAL_DIFF


---------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 800 950 150
7900 JAMES CLERK 950 1100 150
7876 ADAMS CLERK 1100 1250 150
7521 WARD SALESMAN 1250 1250 0
7654 MARTIN SALESMAN 1250 1300 50
7934 MILLER CLERK 1300 1500 200
7844 TURNER SALESMAN 1500 1600 100

18. What are analytical functions?

the aggregate function reduces the number of rows returned by the query. The GROUP BY clause allows us to
apply aggregate functions to subsets of rows.

Analytic functions also operate on subsets of rows, similar to aggregate functions in GROUP BY queries, but
they do not reduce the number of rows returned by the query. For example, the following query reports the
salary for each employee, along with the average salary of the employees within the department.

SELECT empno, deptno, sal,


AVG(sal) OVER (PARTITION BY deptno) AS avg_dept_sal
FROM emp;

EMPNO DEPTNO SAL AVG_DEPT_SAL


---------- ---------- ---------- ------------
7782 10 2450 2916.66667
7839 10 5000 2916.66667
7934 10 1300 2916.66667
7566 20 2975 2175
7902 20 3000 2175
7876 20 1100 2175
7369 20 800 2175
7788 20 3000 2175
7521 30 1250 1566.66667
7844 30 1500 1566.66667
7499 30 1600 1566.66667
7900 30 950 1566.66667
7698 30 2850 1566.66667
7654 30 1250 1566.66667

SQL>

This time AVG is an analytic function, operating on the group of rows defined by the contents of
the OVER clause. This group of rows is known as a window, which is why analytic functions are sometimes
referred to as window[ing] functions. Notice how the AVG function is still reporting the departmental average,
like it did in the GROUP BY query, but the result is present in each row, rather than reducing the total number
of rows returned. This is because analytic functions are performed on a result set after all join, WHERE, GROUP
BY and HAVING clauses are complete, but before the final ORDER BY operation is performed.

these functions allow for the full analytic syntax,

 AVG *
 CORR *
 COUNT *
 COVAR_POP *
 COVAR_SAMP *
 CUME_DIST
 DENSE_RANK
 FIRST
 FIRST_VALUE *
 LAG
 LAST
 LAST_VALUE *
 LEAD
 LISTAGG
 MAX *
 MIN *
 NTH_VALUE *
 NTILE
 PERCENT_RANK
 PERCENTILE_CONT
 PERCENTILE_DISC
 RANK
 RATIO_TO_REPORT
 REGR_ (Linear Regression) Functions *
 ROW_NUMBER
 STDDEV *
 STDDEV_POP *
 STDDEV_SAMP *
 SUM *
 VAR_POP *
 VAR_SAMP *
 VARIANCE *

19. How to delete duplicate values in table?


SYNTAX: delete from <table_name>
where rowid not in ( select min(rowid)
from <Table_name>
group by column1..,column2,...column3..)

20. What are the conversion functions?


---- To_char(),To_date(),To_number()

Conversion functions convert a value from one datatype to another. Generally, the form of
the function names follows the convention datatype TO datatype. The first datatype is the
input datatype. The second datatype is the output datatype. The SQL conversion functions
are:

ASCIISTR
BIN_TO_NUM
CAST
CHARTOROWID
COMPOSE
CONVERT
DECOMPOSE
HEXTORAW
NUMTODSINTERVAL
NUMTOYMINTERVAL
RAWTOHEX
RAWTONHEX
ROWIDTOCHAR
ROWIDTONCHAR
SCN_TO_TIMESTAMP
TIMESTAMP_TO_SCN
TO_BINARY_DOUBLE
TO_BINARY_FLOAT
TO_CHAR (character)
TO_CHAR (datetime)
TO_CHAR (number)
TO_CLOB
TO_DATE
TO_DSINTERVAL
TO_LOB
TO_MULTI_BYTE
TO_NCHAR (character)
TO_NCHAR (datetime)
TO_NCHAR (number)
TO_NCLOB
TO_NUMBER
TO_DSINTERVAL
TO_SINGLE_BYTE
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_YMINTERVAL
TO_YMINTERVAL
TRANSLATE ... USING
UNISTR

21. How to display the column count?


---- Select count(column_name) from table_name;

22. What is difference between CEIL and FLOOR?


---- Thae CEIL function will give the Highest value of the given number
where as FLOOR function will give the lowest value to the given Number
see the Examples:
SQL> select ceil(23.4) from dual;
CEIL(23.4)
----------
24

SQL> select ceil(23.8) from dual;


CEIL(23.8)
----------
24
-- what ever the value 23.4 or 23.8 it will give Higher value
SQL> select floor(23.8) from dual;
FLOOR(23.8)
-----------
23

23. What is difference between BTREE INDEX and BINARY INDEX?


 B-Trees are the typical index type used when you do CREATE INDEX ... in a database:
1. They are very fast when you are selecting just a small very subset of the index data (5%-
10% max typically)
2. They work better when you have a lot of distinct indexed values.
3. Combining several B-Tree indexes can be done, but simpler approaches are often more
efficient.
4. They are not useful when there are few distinct values for the indexed data, or when you
want to get a large (>10% typically) subset of the data.
5. Each B-Tree index impose a small penalty when inserting/updating values on the indexed
table. This can be a problem if you have a lot of indexes in a very busy table.

This characteristics make B-Tree indexes very useful for speeding searches in OLTP applications,
when you are working with very small data sets at a time, most queries filter by ID, and you want
good concurrent performance.

 Bitmap indexes are a more specialized index variant:


1. They encode indexed values as bitmaps and so are very space efficient.
2. They tend to work better when there are few distinct indexed values
3. DB optimizers can combine several bitmap indexed very easily, this allows for efficient
execution of complex filters in queries.
4. They are very inefficient when inserting/updating values.

Bitmap indexes are mostly used in data warehouse applications, where the database is read only
except for the ETL processes, and you usually need to execute complex queries against a star
schema, where bitmap indexes can speed up filtering based on conditions in your dimension tables,
which do not usually have too many distinct values.
As a very short summary: use B-Tree indexes (the "default" index in most databases) unless you are a
data warehouse developer and know you will benefit for a bitmap index.

----Difference Between B-Tree Index & Bitmap Index.

1. B-tree Index has low cardinality values, where as Bitmap Index has High Cardinality values.
2. B-tree Index is userful for OLTP, where as Bitmap Index is useful for Dataware Housing.
3. B-tree index updates on key values has relatively inexpensive, where as Bitmap index has more expensive.

24. What is the global temporary tables?

he DECLARE GLOBAL TEMPORARY TABLE statement defines a temporary table for


the current connection.

These tables do not reside in the system catalogs and are not persistent. Temporary tables
exist only during the connection that declared them and cannot be referenced outside of
that connection. When the connection closes, the rows of the table are deleted, and the in-
memory description of the temporary table is dropped.

Temporary tables are useful when:

 The table structure is not known before using an application.


 Other users do not need the same table structure.
 Data in the temporary table is needed while using the application.
 The table can be declared and dropped without holding the locks on the system
catalog.

Syntax
DECLARE GLOBAL TEMPORARY TABLE table-Name
{ column-definition [ , column-definition ] * }
[ ON COMMIT {DELETE | PRESERVE} ROWS ]
NOT LOGGED [ON ROLLBACK DELETE ROWS]
25. What is the difference between primary key and forigen key?
Primary Key:

It will not allow "Null values" and "Duplicate values"

Foreign Key:
It will allow "Null values" and "Duplicte values" and it refers to a primary key in
anoter table.
Difference between Primary Key & Foreign Key
Primary Key
Foreign Key
Primary key uniquely identify a record in the table.
Foreign key is a field in the table that is primary key in another table.
Primary Key can't accept null values.
Foreign key can accept multiple null value.
By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.
Foreign key do not automatically create an index, clustered or non-
clustered. You can manually create an index on foreign key.
We can have only one Primary key in a table.
We can have more than one foreign key in a table.

26. What is MERG ? Give me syntax?


The MERGE statement was introduced in Oracle 9i to conditionally insert or update data depending on its
presence, a process also known as an "upsert". The MERGE statement reduces table scans and can perform
the operation in parallel if required.

Syntax

Consider the following example where data from the HR_RECORDS table is merged into the EMPLOYEES table.

MERGE INTO employees e


USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
27. Tell me something about synonyms?
A synonym is an alias or alternate name for a table, view, sequence, or other schema
object. They are used mainly to make it easy for users to access database objects owned
by other users. They hide the underlying object's identity and make it harder for a malicious
program or user to target the underlying object

28. What is index organized table?


An index-organized table has a storage organization that is a variant of a primary B-tree.
Unlike an ordinary (heap-organized) table whose data is stored as an unordered collection
(heap), data for an index-organized table is stored in a B-tree index structure in a primary
key sorted manner. Each leaf block in the index structure stores both the key and nonkey
columns.

29. How to get last day of the month?


SELECT LAST_DAY(to_date('04/04/1924','MM/DD/YYYY')) from dual;

SELECT LAST_DAY(ADD_MONTHS(to_date('04/04/1924','MM/DD/YYYY'), -1)) from dual;

SELECT LAST_DAY(ADD_MONTHS(to_date('04/04/1924','MM/DD/YYYY'), -2)) from dual;

30. What is save point and commit ?


save point:

Savepoint names must be distinct within a given transaction. If you create a second
savepoint with the same identifier as an earlier savepoint, then the earlier savepoint is
erased. After a savepoint has been created, you can either continue processing, commit
your work, roll back the entire transaction, or roll back to the savepoint.

Example

Creating Savepoints: Example To update the salary for Banda and Greene in the sample


table hr.employees, check that the total department salary does not exceed 314,000, then
reenter the salary for Greene:

UPDATE employees
SET salary = 7000
WHERE last_name = 'Banda';
SAVEPOINT banda_sal;

UPDATE employees
SET salary = 12000
WHERE last_name = 'Greene';
SAVEPOINT greene_sal;

SELECT SUM(salary) FROM employees;

ROLLBACK TO SAVEPOINT banda_sal;


UPDATE employees
SET salary = 11000
WHERE last_name = 'Greene';

COMMIT;

Commit:
Make permanent changes to data (inserts, updates, deletes) in the database. Before
changes are committed, both the old and new data exist so that changes can be stored or
the data can be restored to its prior state.

Example

insert into emp (empno,ename,sal) values (101,’Abid’,2300);


commit

31. What is pragma? types in pragma?


In Oracle PL/SQL, PRAGMA refers to a compiler directive or "hint" it is used to provide an
instruction to the compiler. The 5 types of Pragma directives available in Oracle are listed
below:

* PRAGMA AUTONOMOUS_TRANSACTION
* PRAGMA SERIALLY_REUSABLE
* PRAGMA RESTRICT_REFRENCES
* PRAGMA EXCEPTION_INIT
* PRAGMA INLINE

32. What is difference between procedure and trigger ?

1. We can execute a stored procedure whenever we want with the help of the exec command,
but a trigger can only be executed whenever an event (insert, delete, and update) is fired on
the table on which the trigger is defined.
2. We can call a stored procedure from inside another stored procedure but we can't directly call
another trigger within a trigger. We can only achieve nesting of triggers in which the action
(insert, delete, and update) defined within a trigger can initiate execution of another trigger
defined on the same table or a different table.
3. Stored procedures can be scheduled through a job to execute on a predefined time, but we
can't schedule a trigger.
4. Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.
5. Stored procedures can return values but a trigger cannot return a value.
6. We can use Print commands inside a stored procedure for debugging purposes but we can't
use print commands inside a trigger.
7. We can use transaction statements like begin transaction, commit transaction, and rollback
inside a stored procedure but we can't use transaction statements inside a trigger.
8. We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but
we can't call a trigger from these files.
9. Stored procedures are used for performing tasks. Stored procedures are normally used for
performing user specified tasks. They can have parameters and return multiple results sets.
10. The Triggers for auditing work: Triggers normally are used for auditing work. They can be
used to trace the activities of table events.

33. What is collesce and nullif, nvl and nvl2 function?

These functions work with any data type and pertain to the use of null values in the expression list.
These functions use of null value and returns result value.

NVL : Converts null value to an actual value.


NVL2 : If first expression is not null, return second expression. If first expression is null, return third
expression. the first expression can have any data type.
COALESCE : Return first not null expression in the expression list.
NULLIF : Compares two expressions and returns null if they are equal,returns the first expression

if they are not equal.

Example

Sample Table : employees

ID SALARY COMMISSION
1 10000 0.05
2 8000 null
3 5000 0.1
select ID, SALARY, (NVL(COMMISSION,1)*SALARY)+SALARY as COM_SALARY from
employees;

Result :

ID SALARY COM_SALARY
1 10000 10500
2 8000 8000
3 5000 5500
If you do not use NVL function, when COM_SALARY have a null value, print null.

34. What is mutating error ..how to avoid it.


Most of us who have worked in Oracle have encountered ORA-04091 (table xxx is mutating. Trigger/function

might not see it) at some time or the other during the development process.  In this blog post, we will cover why
this error occurs and how we can resolve it using different methodology.

Mutating error normally occurs when we are performing some DML operations and we are trying to select the

affected record from the same trigger. So basically we are trying to select records in the trigger from the table

that owns the trigger. This creates inconsistency and Oracle throws a mutating error. Let us take a simple

scenario in which we have to know total number of invalid objects after any object status is updated to

‘INVALID’. We will see it with an example. First let us create a table and then trigger.

SQL> CREATE TABLE TEST


2  AS SELECT * FROM USER_OBJECTS;

Table created.

CREATE OR REPLACE TRIGGER TUA_TEST

AFTER UPDATE OF STATUS ON TEST

FOR EACH ROW

DECLARE

v_Count NUMBER;

BEGIN

SELECT count(*)

INTO v_count

FROM TEST

WHERE status = ‘INVALID’;

dbms_output.put_line(‘Total Invalid Objects are ‘ || v_count);

END;

Now if we try to change the status of any object to ‘INVALID’, we will run into mutating error as we are trying to

update the record and trigger is trying to select total number of records in ‘INVALID’ status from the same table.

SQL> update test


2  set status = 'INVALID'
3  where object_name = 'TEST1';
update test
*
ERROR at line 1:
ORA-04091: table SCOTT.TEST is mutating, trigger/function may not see it

Having said that there are different ways we can handle mutating table errors. Let us start taking one

by one scenario.

First one is to create statement level trigger instead of row level. If we omit the ‘for each row’ clause

from above trigger, it will become statement level trigger. Let us create a new statement level trigger.

CREATE OR REPLACE TRIGGER TUA_TEST


AFTER UPDATE OF STATUS ON TEST
DECLARE
v_Count NUMBER;
BEGIN

SELECT count(*)

INTO v_count

FROM TEST

WHERE status = ‘INVALID’;

dbms_output.put_line(‘Total Invalid Objects are ‘ || v_count);

END;

Now let us fire the same update statement again.

SQL> UPDATE TEST


2     SET status = 'INVALID'
3   WHERE object_name = 'TEST1';

Total Invalid Objects are 6

1 row updated.

When we defined statement level trigger, update went through fine and it displayed the total number of invalid

objects.

Why this is a problem when we are using ‘FOR EACH ROW’ clause? As per Oracle documentation, the session,

which issues a triggering statement on the table, cannot query the same table so that trigger cannot see

inconsistent data. This restriction applies to all the row level triggers and hence we run into mutating table error.
Second way of dealing with the mutating table issue is to declare row level trigger as an autonomous

transaction so that it is not in the same scope of the session issuing DML statement. Following is the row level

trigger defined as pragma autonomous transaction.

CREATE OR REPLACE TRIGGER TUA_TEST


AFTER UPDATE OF STATUS ON TEST
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
v_Count NUMBER;
BEGIN

SELECT count(*)

INTO v_count

FROM TEST

WHERE status = ‘INVALID’;

dbms_output.put_line(‘Total Invalid Objects are ‘ || v_count);

END;

Now let is issue the update statement again and observe the results.

SQL> UPDATE TEST


2     SET status = 'INVALID'
3   WHERE object_name = 'TEST1';

Total Invalid Objects are 5

1 row updated.

If you closely look at the output, you will see only 5 objects shown in invalid status while statement level trigger

showed 6 objects in invalid status. Let us try to update multiple objects at the same time.

SQL> UPDATE TEST


2     SET status = 'INVALID'
3   WHERE object_name IN ('T1','T2');

Total Invalid Objects are 6


Total Invalid Objects are 6

2 rows updated.

By defining row level trigger as an autonomous transaction, we got rid of mutating table error but result is not

correct. The latest updates are not getting reflected in our result set as oppose to statement level trigger. So one

has to be very careful when using this approach.

In version 11g, Oracle made it much easier with introduction of compound triggers. We have covered compound

triggers in a previous blog post. Let us see in this case how a compound trigger can resolve mutating table

error. Let’s create a compound trigger first:

CREATE OR REPLACE TRIGGER TEST_TRIG_COMPOUND


FOR UPDATE
ON TEST
COMPOUND TRIGGER

/* Declaration Section*/

v_count NUMBER;

AFTER EACH ROW IS

BEGIN

dbms_output.put_line(‘Update is done’);

END AFTER EACH ROW;

AFTER STATEMENT IS

BEGIN

SELECT count(*)

INTO v_count

FROM TEST

WHERE status = ‘INVALID’;

dbms_output.put_line(‘Total Invalid Objects are ‘ || v_count);

END AFTER STATEMENT;

END TEST_TRIG_COMPOUND;
/

Now let us check how many objects are invalid in the test table.

SQL> select count(*) from test where status = 'INVALID';

COUNT(*)

———-

Here is the update statement followed by an output.

SQL> UPDATE TEST


2     SET status = 'INVALID'
3   WHERE object_name = 'T2';

Update is done

Total Invalid Objects are 7

1 row updated.

Here we get correct result without getting mutating table error. This is also one very good advantage of

compound triggers. There are other ways also to resolve mutating table error using temporary tables but we

have discussed common ones in this blog post.

35. What is dynamic sql?

Dynamic SQL is a programming technique that enables you to build SQL statements dynamically at
runtime. You can create more general purpose, flexible applications by using dynamic SQL because
the full text of a SQL statement may be unknown at compilation. For example, dynamic SQL lets
you create a procedure that operates on a table whose name is not known until runtime.

In past releases of Oracle, the only way to implement dynamic SQL in a PL/SQL application was by
using the DBMS_SQL package. Oracle8i introduces native dynamic SQL, an alternative to the
DBMS_SQL package. Using native dynamic SQL, you can place dynamic SQL statements directly into
PL/SQL blocks

You should use dynamic SQL in cases where static SQL does not support the operation
you want to perform, or in cases where you do not know the exact SQL statements that
must be executed by a PL/SQL procedure. These SQL statements may depend on user
input, or they may depend on processing work done by the program. The following
sections describe typical situations where you should use dynamic SQL and typical
problems that can be solved by using dynamic SQL

Executing DDL and SCL Statements in PL/SQL

In PL/SQL, you can only execute the following types of statements using dynamic SQL,
rather than static SQL:

 Data definition language (DDL) statements, such as CREATE, DROP, GRANT, and REVOKE


 Session control language (SCL) statements, such as ALTER SESSION and SET ROLE

Ex:

DECLARE
deptid NUMBER;
ename VARCHAR2(20);
BEGIN
EXECUTE IMMEDIATE 'SELECT d.id, e.name
FROM dept_new d, TABLE(d.emps) e -- not allowed in static SQL
-- in PL/SQL
WHERE e.id = 1'
INTO deptid, ename;
END;

36. Tell me everything about cursors?

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A
cursor contains information on a select statement and the rows of data accessed by it.

This temporary work area is used to store the data retrieved from the database, and manipulate this data.
A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor
holds is called the active set.

Implicit cursors
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are
executed. They are also created when a SELECT statement that returns just one row is executed. 

Explicit cursors
They must be created when you are executing a SELECT statement that returns more than one row. Even
though the cursor stores multiple records, only one record can be processed at a time, which is called as
current row. When you fetch a row the current row position moves to next row.

Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

37. Can you tell me about exceptions?


Exceptions:
An exception is a PL/SQL error that is raised during program execution, either implicitly by
TimesTen or explicitly by your program. Handle an exception by trapping it with a handler
or propagating it to the calling environment.

For example, if your SELECT statement returns multiple rows, TimesTen returns an error


(exception) at runtime. As the following example shows, you would see TimesTen error
8507, then the associated ORA error message. (ORA messages, originally defined for Oracle
Database, are similarly implemented by TimesTen.)

Command> DECLARE
> v_lname VARCHAR2 (15);
> BEGIN
> SELECT last_name INTO v_lname
> FROM employees
> WHERE first_name = 'John';
> DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
> END;
> /

8507: ORA-01422: exact fetch returns more than requested number of rows
8507: ORA-06512: at line 4
The command failed.

You can handle such exceptions in your PL/SQL block so that your program completes
successfully. For example:

Command> DECLARE
> v_lname VARCHAR2 (15);
> BEGIN
> SELECT last_name INTO v_lname
> FROM employees
> WHERE first_name = 'John';
> DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
> EXCEPTION
> WHEN TOO_MANY_ROWS THEN
> DBMS_OUTPUT.PUT_LINE (' Your SELECT statement retrieved multiple
> rows. Consider using a cursor.');
> END;
> /
Your SELECT statement retrieved multiple rows. Consider using a cursor.

PL/SQL procedure successfully completed.

Exception types

There are three types of exceptions:

 Predefined exceptions are error conditions that are defined by PL/SQL.


 Non-predefined exceptions include any standard TimesTen errors.
 User-defined exceptions are exceptions specific to your application.

In TimesTen, these three types of exceptions are used in the same way as in Oracle
Database.

Exception Description How to handle


Predefined One of approximately 20 You are not required to declare these
TimesTen error errors that occur most exceptions. They are predefined by
often in PL/SQL code. TimesTen. TimesTen implicitly raises the
error.
Non-predefined Any other standard Must be declared in the declarative section of
TimesTen error TimesTen error. your application. TimesTen implicitly raises
the error and you can use an exception
handler to catch the error.
User-defined Error defined and raised by Must be declared in the declarative section.
error the application. Developer raises the exception explicitly.

Trapping predefined TimesTen errors

Trap a predefined TimesTen error by referencing its predefined name in your exception-
handling routine. PL/SQL declares predefined exceptions in theSTANDARD package.

 Predefined exceptions
Oracle
error
Exception name number SQLCODE Description

ACCESS_INTO_NULL ORA-06530 -6530 Program attempted to assign values to


the attributes of an uninitialized object.
CASE_NOT_FOUND ORA-06592 -6592 None of the choices in the WHEN clauses of
a CASEstatement were selected and there
is no ELSE clause.
COLLECTION_IS_NULL ORA-06531 -6531 Program attempted to apply collection
methods other than EXISTS to an
uninitialized nested table or varray, or
program attempted to assign values to
the elements of an uninitialized nested
table or varray.
CURSOR_ALREADY_OPENED ORA-06511 -6511 A program attempted to open an already
opened cursor.
DUP_VAL_ON_INDEX ORA-00001 -1 A program attempted to insert duplicate
values in a column that is constrained by
a unique index.
INVALID_CURSOR ORA-01001 -1001 Illegal cursor operation.
INVALID_NUMBER ORA-01722 -1722 Conversion of character string to number
failed.
NO_DATA_FOUND ORA-01403 +100 Single row SELECT returned no rows or
your program referenced a deleted
element in a nested table or an
uninitialized element in an associative
array (index-by table).
PROGRAM_ERROR ORA-06501 -6501 PL/SQL has an internal problem.
ROWTYPE_MISMATCH ORA-06504 -6504 Host cursor variable and PL/SQL cursor
variable involved in an assignment
statement have incompatible return
types.
STORAGE_ERROR ORA-06500 -6500 PL/SQL ran out of memory or memory
was corrupted.
SUBSCRIPT_BEYOND_COUNT ORA-06533 -6533 A program referenced a nested table or
varray using an index number larger than
the number of elements in the collection.
Oracle
error
Exception name number SQLCODE Description

SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532 A program referenced a nested table or


varray element using an index number
that is outside the legal range (for
example, -1).
SYS_INVALID_ROWID ORA-01410 -1410 The conversion of a character string into
a universal rowid failed because the
character string does not represent a
value ROWID.
TOO_MANY_ROWS ORA-01422 -1422 Single row SELECT returned multiple rows.
VALUE_ERROR ORA-06502 -6502 An arithmetic, conversion, truncation, or
size constraint error occurred.
ZERO_DIVIDE ORA-01476 -1476 A program attempted to divide a number
by zero.

Trapping user-defined exceptions

You can define your own exceptions in PL/SQL in TimesTen, and you can raise user-defined
exceptions explicitly with either the PL/SQL RAISE statement or
theRAISE_APPLICATION_ERROR procedure.

Using the RAISE statement

The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers


control to an exception handler. RAISE statements can raise predefined exceptions, or user-
defined exceptions whose names you decide.

Example 4-2 Using RAISE statement to trap user-defined exception

In this example, the department number 500 does not exist, so no rows are updated in
the departments table. The RAISE statement is used to explicitly raise an exception and
display an error message, returned by the SQLERRM built-in function, and an error code,
returned by the SQLCODE built-in function. Use theRAISE statement by itself within an
exception handler to raise the same exception again and propagate it back to the calling
environment.

Command> DECLARE
> v_deptno NUMBER := 500;
> v_name VARCHAR2 (20) := 'Testing';
> e_invalid_dept EXCEPTION;
> BEGIN
> UPDATE departments
> SET department_name = v_name
> WHERE department_id = v_deptno;
> IF SQL%NOTFOUND THEN
> RAISE e_invalid_dept;
> END IF;
> ROLLBACK;
> EXCEPTION
> WHEN e_invalid_dept THEN
> DBMS_OUTPUT.PUT_LINE ('No such department');
> DBMS_OUTPUT.PUT_LINE (SQLERRM);
> DBMS_OUTPUT.PUT_LINE (SQLCODE);
> END;
> /
No such department
User-Defined Exception
1

PL/SQL procedure successfully completed.

The command succeeded.


Note:
Given the same error condition in TimesTen and Oracle Database, SQLCODE will return the same
error code, but SQLERRM will not necessarily return the same error message. This is also noted
in "TimesTen error messages and SQL codes".

Using the RAISE_APPLICATION_ERROR procedure

Use the RAISE_APPLICATION_ERROR procedure in the executable section or exception section


(or both) of your PL/SQL program. TimesTen reports errors to your application so you can
avoid returning unhandled exceptions.

Use an error number between -20,000 and -20,999. Specify a character string up to 2,048
bytes for your message.

Example 4-3 Using the RAISE_APPLICATION_ERROR procedure

This example attempts to delete from the employees table where last_name=Patterson.


The RAISE_APPLICATION_ERROR procedure raises the error, using error number -20201.

Command> DECLARE
> v_last_name employees.last_name%TYPE := 'Patterson';
> BEGIN
> DELETE FROM employees WHERE last_name = v_last_name;
> IF SQL%NOTFOUND THEN
> RAISE_APPLICATION_ERROR (-20201, v_last_name || ' does not exist');
> END IF;
> END;
> /
8507: ORA-20201: Patterson does not exist
8507: ORA-06512: at line 6
The command failed.

38. What are advantages of packages?

Packages offer several advantages: modularity, easier application design, information


hiding, added functionality, and better performance.

Modularity

Packages let you encapsulate logically related types, items, and subprograms in a named
PL/SQL module. Each package is easy to understand, and the interfaces between
packages are simple, clear, and well defined. This aids application development.

Easier Application Design

When designing an application, all you need initially is the interface information in the
package specs. You can code and compile a spec without its body. Then, stored
subprograms that reference the package can be compiled as well. You need not define the
package bodies fully until you are ready to complete the application.

Information Hiding

With packages, you can specify which types, items, and subprograms are public (visible
and accessible) or private (hidden and inaccessible). For example, if a package contains
four subprograms, three might be public and one private. The package hides the
implementation of the private subprogram so that only the package (not your application)
is affected if the implementation changes. This simplifies maintenance and enhancement.
Also, by hiding implementation details from users, you protect the integrity of the
package.

Added Functionality
Packaged public variables and cursors persist for the duration of a session. So, they can be
shared by all subprograms that execute in the environment. Also, they allow you to
maintain data across transactions without having to store it in the database.

Better Performance

When you call a packaged subprogram for the first time, the whole package is loaded into
memory. So, later calls to related subprograms in the package require no disk I/O. Also,
packages stop cascading dependencies and thereby avoid unnecessary recompiling. For
example, if you change the implementation of a packaged function, Oracle need not
recompile the calling subprograms because they do not depend on the package body.

Modularity

Packages let you encapsulate logically related types, items, and subprograms in a named
PL/SQL module. Each package is easy to understand, and the interfaces between
packages are simple, clear, and well defined. This aids application development.

Easier Application Design

When designing an application, all you need initially is the interface information in the
package specs. You can code and compile a spec without its body. Then, stored
subprograms that reference the package can be compiled as well. You need not define the
package bodies fully until you are ready to complete the application.

Information Hiding

With packages, you can specify which types, items, and subprograms are public (visible
and accessible) or private (hidden and inaccessible). For example, if a package contains
four subprograms, three might be public and one private. The package hides the
implementation of the private subprogram so that only the package (not your application)
is affected if the implementation changes. This simplifies maintenance and enhancement.
Also, by hiding implementation details from users, you protect the integrity of the
package.

Added Functionality

Packaged public variables and cursors persist for the duration of a session. So, they can be
shared by all subprograms that execute in the environment. Also, they allow you to
maintain data across transactions without having to store it in the database.

Better Performance

When you call a packaged subprogram for the first time, the whole package is loaded into
memory. So, later calls to related subprograms in the package require no disk I/O. Also,
packages stop cascading dependencies and thereby avoid unnecessary recompiling. For
example, if you change the implementation of a packaged function, Oracle need not
recompile the calling subprograms because they do not depend on the package body.

39. What is difference between cursor and ref cursor?

REF cursor is typically used to return record set or a cursor from stored procedure. REF Cursor is
basically a data type. It is normally declared as type r_cursor is REF CURSOR; REF cursor supports
dynamic change of query.

Normal cursor is a static cursor in which the query is assigned at design time and cant be changed at
run time.

Difference between REF Cursor & Normal Cursor in Oracle - April 08, 2009 at 13:00 PM by Rajmeet Ghai

What is the difference between REF Cursor & Normal Cursor in oracle?

Normal cursors fall under the category of static cursors while REF cursors are dynamic. This means
that normal cursors can only be used again not defined. Ref cursors on the other hand can be
changed. A Ref cursor can be passed from one procedure to another. A normal cursor cannot.

Differencebetween REF CURSOR and CURSORwith Example


DECLARE
TYPErcIS REFCURSOR;
CURSORcIS SELECT*FROMdual;
l_cursor rc;
BEGIN
IF (to_char(SYSDATE,''dd'')=30)THEN
OPENl_cursor FORSELECT* FROM emp;
ELSIF(to_char(SYSDATE,''dd'')=29)THEN
OPENl_cursor FORSELECT* FROMdept;
ELSE
OPENl_cursorFOR SELECT*FROMdual;
ENDIF;
OPENc;
CLOSEc;
END;
1) Ref cursors are used fordynamicquery building and explicit cursors are used for static
queries.
2) Ref cursors can be passed as parameters in procedures/functionswhereasexplicit
cursors cannot be passed.
3) Explicit cursors should be defined at design time, whereas ref cursors canbedefined at
runtime.
4. A "normal" plsql cursor is static in defintion. Ref cursors may be dynamically opened or
opened based on logic. Cursor C will always be select * from dual. The ref cursor can be
anything.
5. Cursor can be global -- a ref cursor cannot (you cannot define them OUTSIDE of a
procedure / function).
6. Ref cursor can be passed from subroutine to subroutine -- a cursor cannot be.
7. Another difference is a ref cursor can be returned to a client. a plsql "cursor cursor"
cannot be returned to a client.

40. What is advantage of procedure and function?


-----
1. A function will return a value, A "value" have be one of many things including PL/SQL tables,
ref cursors etc. Adding to that, it is possible to use a function in SQL statements, whereas
procedures cannot be used.
2. Procedures are used to execute business logic, where we can return multiple values from the
procedure using OUT or IN OUT parameters.
3. Personally I use function for computations - For example: check for a specific condition like
retrieving a value based on the condition, checking the condition for true or false.
4. You can have DML(insert, update, delete) statements in a function. But, you cannot call such a
function in a SQL query. *Eg: If you have a function that is updating a table, you can't call that
function in any SQL query.

select myFunction(field) from sometable; --will throw error.


It is on your choice whether to use procedure or function depends on you requirement and your
comfortability.

ADVATAGES OF PROCEDURES AND FUNCTIONS:

Code Sharing
Stored procedures guarantee common code sharing, regardless of tool, language, or DML statement
origination. The code needs testing only once; it does not have to be retested every time it is used in a new
program.

Object Security
EXECUTE privilege is granted to a database user for the stored procedure, not for the tables that the
procedure may reference. This means that a DBA does not have to grant DML access on database objects for
a user to be able to update those objects. The owner of the stored procedure needs the correct privileges on
the underlying objects, but the calling user does not. The calling user does not even have to know the
procedure tables exist. The user needs only to be concerned about the fact that a result is achieved when he
or she calls a procedure, not how that result is arrived at.

Variable Parameter Passing


One valuable feature of stored procedures (and library procedures) is their ability to pass values to and
receive results from them. This functionality can be exploited by providing variable defaults (e.g., := NULL),
named notational variables (e.g., Param =>), or a combination of both, to pass a nonuniform number of
parameters to the same procedure. This flexibility allows us to extend the functionality of an older procedure
by adding more command line information to the procedure while supporting all of the previous procedure
calls. 

Procedure Overlaying
Procedure overlaying is another powerful extension of stored procedures (and library procedures) that
developers should exploit. This overlaying can be a very elegant way to retrospectively alter and/or extend
business functionality. Overlaying allows the developer to define a procedure with several alternative
definitions to choose from. Each definition is checked until a parameter list type match is found.

Automatic Dependency Tracking


Oracle automatically tracks all object interdependencies for every PL/SQL stored object. Object dependencies
include all tables, views, sequences, and synonyms in both local and remote databases that a procedure may
reference. Whenever an object that is referenced in a stored procedure is altered (dropped and/or re-created,
column definitions changed, or new columns added), that procedure is marked as INVALID. Oracle
automatically recompiles the procedure the next time it is called. If the compilation is successful, processing
proceeds as usual; otherwise an error is reported back to the calling application.

Retrospective Business Rules


Stored procedures allow the retrospective fitting of any new or modified business rules. You can retrofit in
several different ways. First, if the original functionality is contained in a single, global stored procedure, any
modification to that procedure will automatically be applied to the hundreds of application modules that may be
using it. Second, use procedure overlaying to modify the functionality of an existing stored procedure by
adding option procedure parameters.

Suited to Client-Server Applications


Stored procedures are very efficient in client-server environments. Stored procedures are executed with a
single procedure call, potentially processing thousands of lines of PL/SQL code rather than transmitting all the
code across the network. Only one copy of the source, held in the database, needs to exist.

41. What is difference between procedure v/s package?


Packages & stored procedures are database objects. 

Packages are having so many features like..!!

Modularity
*************

Packages let you encapsulate logically related types, items, and subprograms
in a named PL/SQL module.
Each package is easy to understand, and the interfaces between packages are
simple, clear, and well

defined. This aids application development.

Easier Application Design


**************************

When designing an application, all you need initially is the interface


information in the package

specs. You can code and compile a spec without its body. Then, stored
subprograms that reference the

package can be compiled as well. You need not define the package bodies
fully until you are ready to

complete the application.

Information Hiding
*******************

With packages, you can specify which types, items, and subprograms are
public (visible and accessible)

or private (hidden and inaccessible). For example, if a package contains


four subprograms, three might

be public and one private. The package hides the implementation of the
private subprogram so that only

the package (not your application) is affected if the implementation


changes. This simplifies

maintenance and enhancement. Also, by hiding implementation details from


users, you protect the

integrity of the package.

Added Functionality
********************

Packaged public variables and cursors persist for the duration of a session.
They can be shared by allsubprograms that execute in the environment. They
let you maintain data across transactions without

storing it in the database.

Better Performance
*******************

When you invoke a packaged subprogram for the first time, the whole package
is loaded into memory.

Later calls to related subprograms in the package require no disk I/O.


Packages stop cascading dependencies and avoid unnecessary recompiling. For
example, if you change the

body of a packaged function, the database does not recompile other


subprograms that invoke the

function; these subprograms only depend on the parameters and return value
that are declared in the

spec, so they are only recompiled if the spec changes.

Function Overloading
*****************
you can use same procedure name more than one procedure with diff parameters
and their datatypes.

Procedure : Procedure does not return any values with return clause, however can return data with "out"
parameter to calling program

Function : Funcation must return values to calling program with return statement. Funcation can also returns
values with "out" parameter to calling program. 

Package : Package is group of procedure, fuctions and data types ete. The package is faster as compared to
procedure or function. The package will be loaded on the memory when first execution and will be available
for subsequent calls, this way package is faster compared to procedure and functions.
Function Procedure
1. Can be used as column Cant used in select statement
in select statement
2. Can be used in where Cant used in where condition
condition 
2. It must return value Return keyword can be used but will
with return keyword only pass control back to the main program.

Benefits
Functions:
Complex logic can be embedded in the function which can be used in query to filter the record selection.

Procedure:
It can be called standalone and process list of actions (although function can also do the same) to perform.
The only difference with respect to function is that it do not require any placeholder to hold the return value.

Package:
If any of the package component called the whole package gets compiled and remain loaded in the memory
untill flushed out (restart or using pragma serially_reusable).
Therefore whenever any function/procedure called the response time is fast.

Drawbacks:
Function:
1. If function has group by or any DML statement it cant be used inside select query.

Procedure:
It cant be called inside select/where statement.

Package:
If package procedure/function needs to be used only once, unnecessary the whole package gets loaded in the
memory.

42. What are the collection types please brief?

PL/SQL offers these collection types:

 Associative arrays, also known as index-by tables, let you look up elements using
arbitrary numbers and strings for subscript values. These are similar to hash tables
in other programming languages.

 Nested tables hold an arbitrary number of elements. They use sequential numbers as
subscripts. You can define equivalent SQL types, allowing nested tables to be stored
in database tables and manipulated through SQL.

 Varrays (short for variable-size arrays) hold a fixed number of elements (although
you can change the number of elements at runtime). They use sequential numbers
as subscripts. You can define equivalent SQL types, allowing varrays to be stored in
database tables. They can be stored and retrieved through SQL, but with less
flexibility than nested tables.

Although collections have only one dimension, you can model multi-dimensional arrays by
creating collections whose elements are also collections.

To use collections in an application, you define one or more PL/SQL types, then define
variables of those types. You can define collection types in a procedure, function, or
package. You can pass collection variables as parameters to stored subprograms.

To look up data that is more complex than single values, you can store PL/SQL records or
SQL object types in collections. Nested tables and varrays can also be attributes of object
types.

Understanding Nested Tables

PL/SQL nested tables represent sets of values. You can think of them as one-dimensional
arrays with no declared number of elements. You can model multi-dimensional arrays by
creating nested tables whose elements are also nested tables.

Within the database, nested tables are column types that hold sets of values. Oracle stores
the rows of a nested table in no particular order. When you retrieve a nested table from the
database into a PL/SQL variable, the rows are given consecutive subscripts starting at 1.
That gives you array-like access to individual rows.

Nested tables differ from arrays in two important ways:

1. Nested tables do not have a declared number of elements, while arrays have a
predefined number as illustrated in Figure 5-1. The size of a nested table can
increase dynamically; however, a maximum limit is imposed. See "Referencing
Collection Elements".

2. Nested tables might not have consecutive subscripts, while arrays are always dense
(have consecutive subscripts). Initially, nested tables are dense, but they can
become sparse (have nonconsecutive subscripts). You can delete elements from a
nested table using the built-in procedure DELETE. The built-in function NEXT lets you
iterate over all the subscripts of a nested table, even if the sequence has gaps.

Figure 5-1 Array versus Nested Table

Description of the illustration lnpls016.gif

Understanding Varrays

Items of type VARRAY are called varrays. They let you reference individual elements for array
operations, or manipulate the collection as a whole. To reference an element, you use
standard subscripting syntax (see Figure 5-2). For example, Grade(3) references the third
element in varray Grades.

Figure 5-2 Varray of Size 10

Description of the illustration lnpls017.gif

A varray has a maximum size, which you specify in its type definition. Its index has a fixed
lower bound of 1 and an extensible upper bound. For example, the current upper bound for
varray Grades is 7, but you can increase its upper bound to maximum of 10. A varray can
contain a varying number of elements, from zero (when empty) to the maximum specified
in its type definition.

Understanding Associative Arrays (Index-By Tables)

Associative arrays are sets of key-value pairs, where each key is unique and is used to
locate a corresponding value in the array. The key can be an integer or a string.

Assigning a value using a key for the first time adds that key to the associative array.
Subsequent assignments using the same key update the same entry. It is important to
choose a key that is unique. For example, key values might come from the primary key of a
database table, from a numeric hash function, or from concatenating strings to form a
unique string value.

43. What is SQLCODE and SQLERRM?

SQLCODE and SQLERRM

Oracle provides a way to capture the error codes when a SQL statement raises an
exception by using the SQLCODEand SQLERRM globally-defined variables.  Both
SQLCODEand SQLERRM can be useful in tracking exceptions that are handled by the
OTHERS clauseof the exception handler.  SQLCODE returns the current error code from
the error stack.  SQLERRM returns the error message from the current error code as
shown below.
SQL> declare
  2    n_numb number := &Number;
  3    n_2 number := 0;
  4  begin
  5    test_var(n_numb, n_2);
  6    dbms_output.put_line(n_2);
  7  exception
  8    when others then
  9      begin
 10        dbms_output.put_line('SQLCODE: '||SQLCODE);
 11        dbms_output.put_line('Message: '||SQLERRM);
 12      end;
 13  end;
 14  /
Enter value for number: 105
old   2:   n_numb number := &Number;
new   2:   n_numb number := 105;
SQLCODE: -20010
Message: ORA-20010: Number Too Large

Using the same function from the previous example, a value greater than 100 will raise an
exception.  The OTHERS clausein the exception handler caught the exception and printed
out the SQLCODEand SQLERRM.  Once you know the error code, you can
programmatically handle the exception, like this:
SQL> declare
  2    n_numb number := &Number;
  3    n_2 number := 0;
  4  begin
  5    test_var(n_numb, n_2);
  6    dbms_output.put_line(n_2);
  7  exception
  8    when others then
  9      begin
 10        if SQLCODE = -20010
 11          then dbms_output.put_line('Value Too 
                  Large');
 12        else dbms_output.put_line('Unknown 
                Exception');
 13        end if;
 14      end;
 15  end;
 16  / 

Enter value for number: 105

old   2:   n_numb number := &Number;


new   2:   n_numb number := 105; 

Value Too Large

Handling exceptions is an important programming practice that is all too often


overlooked.  Many times, exception handling is added too late, after the code is written
and deployed, or when the developer is attempting to stop or locate programming
errors.  Exception handling should be a part of the program design and should be
included in all appropriate PL/SQL blocks.  Properly raising and handling exceptions will
allow the developer to effectively track and maintain the code.  The ability to
programmatically recover from system, application, and user errors is important in
keeping the application running and the users happy

44. What is exception? Tell me some seeded exceptions?

Exceptions are notifications that identify issues that need resolution. Oracle Collaborative
Planning generates an exception whenever an actual process does not match the required
process. For example, if you and your supplier's forecasts do not match, Oracle
Collaborative Planning generates a forecast mismatch exception. Exceptions ensure that the
decision-making process remains focused, occurs in a timely manner, and makes the supply
chain more responsive.

Oracle Collaborative Planning exceptions are grouped into several categories that
correspond to supply chain problems. The categories are:(seeded exceptions)

 Late orders

 Early orders

 Potential late orders

 Material shortage

 Material excess

 Forecast mismatch

 Response required

 Change orders

 Forecast accuracy

 Performance below target

Exception notifications for an item are sent to the supply chain collaboration planner for the
item. If no planner is specified for an item, notification is sent to an Administrator. Any
planner can view an exception through the Exceptions tab. You can also view counts for a
given exception type.

45. What are the conditional statements?

CONDITIONAL STATEMENTS

IF-THEN-ELSE Statement

There are three different syntaxes for these types of statements.

SYNTAX #1: IF-THEN


IF condition THEN

{...statements...}

END IF;

SYNTAX #2: IF-THEN-ELSE

IF condition THEN

{...statements...}

ELSE

{...statements...}

END IF;

SYNTAX #3: IF-THEN-ELSIF

IF condition THEN

{...statements...}

ELSIF condition THEN

{...statements...}

ELSE

{...statements...}

END IF;

Here is an example of a function that uses the IF-THEN-ELSE statement:


CREATE OR REPLACE Function IncomeLevel

( name_in IN varchar2 )

RETURN varchar2

IS

monthly_value number(6);

ILevel varchar2(20);

cursor c1 is

SELECT monthly_income

FROM employees
WHERE name = name_in;

BEGIN

open c1;
fetch c1 into monthly_value;
close c1;

IF monthly_value <= 4000 THEN


ILevel := 'Low Income';

ELSIF monthly_value > 4000 and monthly_value <= 7000 THEN


ILevel := 'Avg Income';

ELSIF monthly_value > 7000 and monthly_value <= 15000 THEN


ILevel := 'Moderate Income';

ELSE
ILevel := 'High Income';

END IF;

RETURN ILevel;

END;

Case Statement

The Oracle/PLSQL CASE statement has the functionality of an IF-THEN-ELSE statement. Starting in Oracle


9i, you can use the CASE statement within a SQL statement.

CASE STATEMENT SYNTAX

The syntax for the Oracle/PLSQL CASE statement is:

CASE [ expression ]

WHEN condition_1 THEN result_1

WHEN condition_2 THEN result_2

...

WHEN condition_n THEN result_n

ELSE result

END

CASE STATEMENT EXAMPLES

The CASE statement can be used in Oracle/PLSQL.

You could use the CASE statement in a SQL statement as follows: (includes the expression clause)

select table_name,

CASE owner

WHEN 'SYS' THEN 'The owner is SYS'

WHEN 'SYSTEM' THEN 'The owner is SYSTEM'

ELSE 'The owner is another value'

END

from all_tables;
GOTO Statement

The GOTO statement causes the code to branch to the label after the GOTO statement.

For example:

GOTO label_name;

Then later in the code, you would place your label and code associated with that label.

Label_name: {statements}

LOOPS

Loop Statement
FOR Loop
CURSOR FOR Loop
While Loop
Repeat Until Loop
Exit Statement

46. What is NOCOPY? And where we can use this?


NOCOPY is a IN OUT COPY Which is used avoid the overhad of copying IN OUT
Parameter Values.  If IN OUT parameter returns huge records we can specify the NOCOPY
to copy the values.

      The PLSQL Engine first makes a copy of the record and then during program executing
makes a changes to that copy.

---- The NOCOPY hint tells the PL/SQL compiler to pass OUT and IN OUT parameters
by reference, rather than by value.

When parameters are passed by value, the contents of the OUT and IN OUT parameters
are copied to temporary variables, which are then used by the subprogram being called. 
On successful completion of the subprogram the values are copied back to the actual
parameters, but unhandled exceptions result in the original parameter values being left
unchanged.  The process of copying large parameters, such as records, collections, and
objects requires both time and memory which affects performance.
With the NOCOPY hint the parameters are passed by reference and on successful
completion the outcome is the same, but unhandled exceptions may leave the parameters
in an altered state, so programs must handle errors or cope with the suspect values.

The use of the NOCOPY hint does come with some drawbacks, as it can result in
parameter aliasing when global variables are passed as parameters to subprograms.  A
parameter alias occurs when two variable names point to the same memory location.  The
update_global.sql script shows how aliasing can occur if a global variable is accessed
directly from a procedure when it has also been passed as a NOCOPY parameter.

47. What is difference between raise and raise application error


Raise:

In Oracle PL/SQL, the RAISE statement is used to explicitly raise an exception within a PL/SQL


block. It immediately stops normal execution of a PL/SQL block or subprogram and transfers
control to an exception handler. It can be used to raise both system defined and user defined
exceptions.

If an exception is raised and PL/SQL cannot find a handler for it in the current block, the
exception then propagates to successive enclosing blocks, until a handler is found or there are
no more blocks to propagate to. If no handler is found, PL/SQL returns an unhandled
exception error to the host environment.

Example Syntax:

RAISE [EXCEPTION NAME]

Example Usage:

The PL/SQL block below selects an employee corresponding to a given employee IDd. If no
employee record is found it raises the NO_DATA_FOUND exception and displays a message.
Note that NO_DATA_FOUND is a system defined exception.

DECLARE

L_EMP VARCHAR2(1000);

CURSOR C IS

SELECT ENAME

FROM EMPLOYEE
WHERE EMPNO = 300;

BEGIN

OPEN C;

FETCH C INTO L_EMP;

CLOSE C;

IF L_EMP IS NULL THEN

RAISE NO_DATA_FOUND;

END IF;

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('No Employee exists for this employee ID.');

END;

No Employee exists for this employee ID.

PL/SQL procedure successfully c

raise application error:

The RAISE_APPLICATION_ERROR procedure lets you issue user-defined ORA-n error messages


from stored subprograms. That way, you can report errors to your application and avoid
returning unhandled exceptions.

To invoke RAISE_APPLICATION_ERROR, use the following syntax:

raise_application_error(
error_number, message[, {TRUE | FALSE}]);

where error_number is a negative integer in the range -20000..-20999 and message is a


character string up to 2048 bytes long. If the optional third parameter is TRUE, the error is
placed on the stack of previous errors. If the parameter is FALSE (the default), the error
replaces all previous errors. RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD, and as
with package STANDARD, you need not qualify references to it.

An application can invoke raise_application_error only from an executing stored


subprogram (or method). When invoked, raise_application_error ends the subprogram and
returns a user-defined error number and message to the application. The error number and
message can be trapped like any Oracle Database error.

In Example 11-5, you invoke RAISE_APPLICATION_ERROR if an error condition of your choosing


happens (in this case, if the current schema owns less than 1000 tables).

Example 11-5 Raising an Application Error with RAISE_APPLICATION_ERROR

DECLARE
num_tables NUMBER;
BEGIN
SELECT COUNT(*) INTO num_tables FROM USER_TABLES;
IF num_tables < 1000 THEN
/* Issue your own error code (ORA-20101)
with your own error message. You need not
qualify RAISE_APPLICATION_ERROR with
DBMS_STANDARD */
RAISE_APPLICATION_ERROR
(-20101, 'Expecting at least 1000 tables');
ELSE
-- Do rest of processing (for nonerror case)
NULL;
END IF;
END;

48. What are formal and actual parameters?


-----Formal parameter and actual parameter are two different terms related parameters used in the
procedures and functions:
 A formal parameter is a term used to refer to a parameter defined in the procedure or function
declaration statement.
 An actual parameter is a term used to refer to a parameter provided by the calling statement to a
procedure or a function.

----- 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;
---- There are two different kinds of parameters: actual and formal parameters.

The formal parameters are the names that are declared in the parameter list of the header of a
module.

The actual parameters are the values or expressions placed in the parameter list of the actual call to
the module.

Let’s examine the differences between actual and formal parameters using the example of tot_sales. Here is
tot_sales’ header:

FUNCTION tot_sales
(company_id_in IN company.company_id%TYPE,
status_in IN order.status_code%TYPE := NULL)
RETURN std_types.dollar_amount;
The formal parameters of tot_sales are:

company_id_in - The primary key of the company


status_in - The status of the orders to be included in the sales calculation

They do not exist outside of the function. You can think of them as place holders for real or actual parameter
values that are passed into the function when it is used in a program.

When you use tot_sales in your code, the formal parameters disappear. In their place you list the actual
parameters or variables, whose values will be passed to tot_sales. In the following example, the company_id
variable contains the primary key pointing to a company record. In the first three calls to tot_sales a different,
hardcoded status is passed to the function. The last call to tot_sales does not specify a status; in this case the
function assigns the default value (provided in the function header) to the status_in parameter:

new_sales := tot_sales (company_id, 'N');


paid_sales := tot_sales (company_id, 'P');
shipped_sales := tot_sales (company_id, 'S');
all_sales := tot_sales (company_id);
When tot_sales is called, all the actual parameters are evaluated. The results of the evaluations are then
assigned to the formal parameters inside the function to which they correspond.

The actual parameters must be evaluated because they can be expressions, as well as pointers, to non-
PL/SQL objects such as bind variables in the development tool.

The formal parameter and the actual parameter that corresponds to the formal parameter (when called) must
be of the same or compatible datatypes. PL/SQL will perform datatype conversions for you in many situations.
Generally, however, you are better off avoiding all implicit datatype conversions so you are sure of what is
happening in your code. Use a formal conversion function like TO_CHAR or TO_DATE, so you know exactly
what kind of data you are passing into your modules.

49. Difference between nested tables and varrays?


A Varray is an ordered array (elements are indexed 1,2,3,...), which is physically stored in
the table it belongs to.
A Nested Table is actually a separate physical table but made to look like it is nested within
the table it belongs to. There is no implicit ordering (no index 1,2,3,... defined), rather you
reference the data by key values.

I would never use either in the database as they add a lot of SQL complexity for no gain. In
a PL/SQL program you might use a nested table so that you can select from an in-memory
array as if it were a real table.

50. What is bulk collect and give me syntax?


BULK COLLECT: SELECT statements that retrieve multiple rows with a single fetch, improving the speed of data
retrieval
FORALL: INSERTs, UPDATEs, and DELETEs that use collections to change multiple rows of data very quickly

authors first fetch data from a table by using bulk collect statements. After that, they are inserting it into
target table by using the forall statement.
DECLARE
TYPE prod_tab IS TABLE OF products%ROWTYPE;
products_tab prod_tab := prod_tab();
BEGIN
-- Populate a collection - 100000 rows
SELECT * BULK COLLECT INTO products_tab FROM source_products;

FORALL i in products_tab.first .. products_tab.last


INSERT INTO target_products VALUES products_tab(i);

51. What is weak and strong refcursor and give example?


What is Ref Cursor :
---------------------------------------------------------------------------------
------

-->It is aslo a user defined type


-->ref cursor allows you to declare the  cursor variable those are independent of
select statement
i .e
   the cursor variable declared using ref cursor type is ready to accept any
select statement dynamically at the time of opening

-->Ref cursor are of two types

  1) A Strong ref cursor(also called static structure type)


2)Weak ref cursor(also  called dynamic structure type )

1)Strong ref cursor:


-->When return type included then it is called strong or static structure type
-->static ref cursor support different  type of select statement but all of same
strucure ,but not neccessary that the table should be same
2)Weak Ref  Cursor:

  this ref cursor allows us to any  type of select statement irrespective of data
structure . i .e any table
---There are 2 types in this.
1.strong ref cursor:
This has a return type defined.
2. weak ref cursor.
this doesnt have a return type
normal cursor:
Nothing but the named memory location.
it has 2 types
1. explicit cursor
Need to be defined  whenever required.
2.Implicit cursor
need not defined and used by oracle  implicitly in DML operation.
Answer Question

--- In case of an normal explict cursor, the SQL query has to be defined at the time of declaring the cursor
itself.  In case of REF Cursor, the cursor declartion is not associated with any SQL query, it is associated with
a query at a later stage this brings in a lot of flexibility as different SQL queries can be associated with the
cursor (one at a time, offcourse) programatically.  REF Cursors also provide the feature of passing
parameters.  Though there is something dynamic with REF Cursor when compared to a normal explicit cursor,
it is not a truly perfect dynamic cursor.  Truly perfect dynamic cursors are the one constructed using
DBMS_SQL package.  

52. Primary key vs unique

Primary Key:

i) Can be only one in a table

ii) It never allows null values

iii) Primary Key is unique key identifier and can not be null and must be unique.

Unique Key:

i) Can be more than one unique key in one table.

ii) Unique key can have null values


iii) It can’t be candidate key

iv) Unique key can be null and may not be unique.

53. What is authid clause ?


The AUTHID clause instructs Oracle as to whether the routine is to be run with the invoker's
rights (CURRENT_USER), or with the Owner rights (DEFINER). If the clause is not
specified, Oracle will default to using the AUTHID DEFINER.

Note that to enable code to run with Invoker rights, the AUTHID clause must be used before
the IS or AS keyword in the routine header.
Invoker Rights
Invoker rights is a method present in Oracle 8i and greater that is used to resolve
references to database elements in a PL/SQL program unit. Using Invoker rights we can
instruct Oracle if a given program unit should run with the authority of the definer or of the
invoker. The result is that multiple schemas can share the same piece of code while
accessing only the elements which belong to the invoker.
---- There are lot of times we get error in Oracle Apps while trying to execute the API's at
development time, due to the AUTHID DEFINER and AUTHID CURRENT_USER. This article gives
you good understanding about the AUTHID DEFINER and AUTHID CURRENT_USER.

A stored procedure runs either with the rights of the caller (AUTHID CURRENT_USER) or with
the rights of the procedure's owner (AUTHID DEFINER). This behaviour is specified with
the AUTHID clause. This authid clause immediatly follows thecreate procedure, create
function, create package or create type statement. It can be ommited, in which case the
defaultauthid definer is taken.

AUTHID DEFINER and AUTHID CURRENT_USER


-----------------------------------------------------------
AUTHID DEFINER:-
--------------------

Example:-
---------
The following are done in APPS scheme.

create table a (a_a number);

CREATE OR REPLACE PACKAGE XYZ AUTHID DEFINER


AS
PROCEDURE XYZ_1;
END XYZ;

CREATE OR REPLACE PACKAGE body XYZ


AS
PROCEDURE XYZ_1
IS
BEGIN
INSERT INTO A VALUES (1);
END XYZ_1;
END XYZ;

begin
xyz.XYZ_1;
end;

select * from a;

Provide grants for this package to other schema (scott) and create the synonym for the xyz
package in scott.

grant all on to 

Example:-
---------

grant all on xyz to scott

Above command is run from the apps schema.

Now for the other schema SCOTT try to run the same query.

begin
xyz.XYZ_1;
end;

It have inserted new record in the 'A' table. Note there is no synonym for the table A in
SCOTT schema.

Running this program from anywhere, it is as good as running from APPS schema in case
of AUTHID DEFINER.

10.2) CURRENT_USER:-
----------------------

Example:-
-----------

The following are done in the APPS schema.

create table a (a_a number);

CREATE OR REPLACE PACKAGE XYZ AUTHID CURRENT_USER


AS
PROCEDURE XYZ_1;
END XYZ;

CREATE OR REPLACE PACKAGE body XYZ


AS
PROCEDURE XYZ_1
IS
BEGIN
INSERT INTO A VALUES (1);
END XYZ_1;
END XYZ;

begin
xyz.XYZ_1;
end;

select * from a;

Provide grants for this package to other schema (scott) and create the synonym for the xyz
package in scott.

grant all on to 

Example:-
-----------

grant all on xyz to scott

Above command is run from the apps schema.

Now for the other schema (scott) try to run the same query.

begin
xyz.XYZ_1;
end;

Got the error message table or view doesn't exist for the A table.

Create view for the a table and run the same program again.

create synonym 'A' for table 'A'

begin
xyz.XYZ_1;
end;
select * from a;

Now there is no error. It is inserting the record with no issue.

-----   The authid current_user is used when you want a piece of code (PL/SQL) to
execute with the privileges of the current user, and NOT the user ID that created the
procedure.  This is termed a "invoker rights", the opposite of "definer rights".

The authid current_user is the opposite of authid definer.

In the same sense, the authid current_user is the reverse of the "grant execute" where the
current user does not matter, the privileges of the creating user are used.

PL/SQL, by default, run with the privileges of the schema within which they are created no matter
who invokes the procedure. In order for a PL/SQL package to run with invokers rights AUTHID
CURRENT_USER has to be explicitly written into the package.

To understand the authid current_user, consider this type definition:


CREATE TYPE address_t 
   AUTHID CURRENT_USER 
AS OBJECT (
   address_line1 varchar2(80),
   address_line2 varchar2(80), 
   street_name varchar2(30), 
   street_number number, 
   city varchar2(30), 
   state_or_province varchar2(2), 
   zip number(5), 
   zip_4 number(4), 
   country_code varchar2(20));

The authid current_user clause tells the kernel that any methods that may be used in the
type specification (in the above example, none) should execute with the privilege of the
executing user, not the owner.

The default option is authid definer, which would correspond to the behavior in pre-
Oracle8i releases, where the method would execute with the privileges of the user
creating the type.

See this example of authid current_user to understand how this syntax causes invoker
rights, which, in turn, changes the behavior of the PL/SQL code.

WARNING: Writing PL/SQL code with the default authid definer, can facilitate SQL


injection attacks, because an intruder would get privileges that they would not get if they
used authid current_user.

54. Where current of clause

If you plan on updating or deleting records that have been referenced by a SELECT FOR UPDATE
statement, you can use the WHERE CURRENT OF statement.

The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either:

UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;

OR

DELETE FROM table_name


WHERE CURRENT OF cursor_name;

The WHERE CURRENT OF statement allows you to update or delete the record that was last
fetched by the cursor.

---- If you plan on updating or deleting records that have been referenced by a SELECT FOR
UPDATE statement, you can use the WHERE CURRENT OF statement.
The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either:
UPDATE table_name

SET set_clause

WHERE CURRENT OF cursor_name;

OR

DELETE FROM table_name

WHERE CURRENT OF cursor_name;

The WHERE CURRENT OF statement allows you to update or delete the record that was last fetched by the
cursor.

UPDATING USING THE WHERE CURRENT OF STATEMENT

Here is an example where we are updating records using the WHERE CURRENT OF Statement:
CREATE OR REPLACE Function FindCourse

( name_in IN varchar2 )

RETURN number

IS

cnumber number;

CURSOR c1

IS

SELECT course_number

FROM courses_tbl

WHERE course_name = name_in

FOR UPDATE of instructor;

BEGIN

OPEN c1;
FETCH c1 INTO cnumber;

if c1%notfound then
cnumber := 9999;

else
UPDATE courses_tbl
SET instructor = 'SMITH'
WHERE CURRENT OF c1;

COMMIT;

end if;

CLOSE c1;

RETURN cnumber;

END;

DELETING USING THE WHERE CURRENT OF STATEMENT


Here is an example where we are deleting records using the WHERE CURRENT OF Statement:

CREATE OR REPLACE Function FindCourse

( name_in IN varchar2 )

RETURN number

IS

cnumber number;

CURSOR c1

IS

SELECT course_number

from courses_tbl

where course_name = name_in

FOR UPDATE of instructor;

BEGIN

open c1;

fetch c1 into cnumber;

if c1%notfound then

cnumber := 9999;

else

DELETE FROM courses_tbl

WHERE CURRENT OF c1;

COMMIT;

end if;

close c1;
RETURN cnumber;

END;

55. What is difference and forall loop and for loop?


----The FORALL statement runs one DML statement multiple times, with different values in
the VALUES and WHERE clauses. The different values come from existing, populated collections
or host arrays. The FORALL statement is usually much faster than an
equivalent FOR LOOP statement.
FOR is a loop.
FORALL is a single statement.
----The FORALL statement issues a series of static or dynamic DML statements, and is usually much faster
than an equivalent FOR loop.

You use FORALL when working with collections and it has a better performance than FOR.

If you are working with individual items you have to use FOR.
----- FORALL is:

"The keyword FORALL instructs the PL/SQL engine to bulk-bind input collections before sending them to the
SQL engine. Although the FORALL statement contains an 
iteration scheme, it is not a FOR loop. 

Its syntax follows:

FORALL index IN lower_bound..upper_bound


   sql_statement;

The index can be referenced only within the FORALL statement and only as a collection subscript. The SQL
statement must be an INSERT, UPDATE, or DELETE statement that 
references collection elements. And, the bounds must specify a valid range of consecutive index numbers.
The SQL engine executes the SQL statement once for each index 
number in the range."

So there you go. Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and 10g
PL/SQL that can really make a different to you PL/ SQL performance. 
Hopefully, if you've not come across these areas before.
FORALL Syntax & Example:

FORALL IN .. 
 
 SAVE EXCEPTIONS;
FORALL IN INDICES OF 
 [BETWEEN AND ]
 
 SAVE EXCEPTIONS;
FORALL IN INDICES OF 
VALUES OF 
 
 SAVE EXCEPTIONS;
FOR ‘INSERT’
===========

CREATE TABLE servers2 AS
SELECT *
FROM servers
WHERE 1=2;
DECLARE
  CURSOR s_cur IS 
 SELECT *
  FROM servers;
  TYPE fetch_array IS TABLE OF s_cur%ROWTYPE;
  s_array fetch_array;
BEGIN
   OPEN s_cur;
   LOOP
     FETCH s_cur BULK COLLECT INTO s_array LIMIT 1000;
     FORALL i IN 1..s_array.COUNT
     INSERT INTO servers2 VALUES s_array(i);
     EXIT WHEN s_cur%NOTFOUND;
   END LOOP;
   CLOSE s_cur;
   COMMIT;
END;
 /

56. What is forward declaration and where we can use this?


----PL/SQL allows for a special subprogram declaration called a
forward declaration. It consists of the subprogram
specification in the package body terminated by a semicolon.
You can use forward declarations to do the following:
? Define subprograms in logical or alphabetical order.
? Define mutually recursive subprograms.(both calling each
other).
? Group subprograms in a package

Example of forward Declaration:

CREATE OR REPLACE PACKAGE BODY forward_pack 


IS
PROCEDURE calc_rating(. . .); -- forward declaration 
PROCEDURE award_bonus(. . .) 
IS -- subprograms defined 
BEGIN -- in alphabetical order
calc_rating(. . .); 
...
END;

PROCEDURE calc_rating(. . .) 


IS
BEGIN
...
END;

END forward_pack;
---- Special sub program unit declaration called forward 
declaration, Consider below the example

In this pacakage, the first program unit is calling the 


calc_rating but calc_rating is defined last in the package; 
if we are not declared the fwd declaration then it will 
raise the error While compiling this package. Package 
compilation always happens top to bottom. For resolving 
this compilation issue, you should declare the fwd 
declaration.

CREATE OR REPLACE PACKAGE BODY forward_pack 


IS
PROCEDURE calc_rating(. . .); -- forward 
declaration 
PROCEDURE award_bonus(. . .) 
IS -- subprograms 
defined 
BEGIN -- in alphabetical 
order
calc_rating(. . .); 
...
END;

PROCEDURE calc_rating(. . .) 


IS
BEGIN
...
END;

END forward_pack; 
57. What are who columns? Why we can use in the tables?
LAST_UPDATE_DATE,
LAST_UPDATED_BY,
CREATION_DATE,
CREATED_BY,
LAST_UPDATE_LOGIN
---- WHO columns are used to track the information updated or inserted by the users against the tables.
FND_STANDARD package is used for this purpose. FND_STANDARD.SET_WHO Procedure is used to
update the WHO columns in a Table when a DML operation s (i.e. INSERT, UPDATE) performed.
        1) Created by
        2) Creation date
        3) Last _updated_by
        4) last_update_date
        5) last_update_login

 Use fnd_profile.VALUE (‘USER_ID’) for retrieving the user_id which will be used by created_by
column.
 Creation date and last_update_date will be normally SYSDATE.
 last_updated_by is same as created_by.
 Use USERENV (‘SESSIONID’) for getting the last_update_login id

58.what is the difference between translate and replace?


select translate('Allens','A','B') from dual

select replace(JOB,'MANAGER','BOSS') FROM EMP;

Discoverer :

1. What is discoverer? How to create report in discoverer


----An initiative,ad-hoc query,reporting analysis and web publishing tool
----  Discoverer is a Tools of oracle for Business Intelligence . Discoverer is an
intuitive ad-hoc query , reporting analysis and web publishing toolset that gives
business users immediate access to information of database.
Discoverer provides a business view to hide the complexity of the
underlying data structures, enabling u to focus on solving business problems.

2. What is item class?


----we assign and display a list of values to the parameter by using item clause in
discoverer.

3. Discoverer base tables


EUL5_DOCUMENTS
EUL5_EUL_USERS
EUL5_ACCESS_PRIVS
---- Run the following sequence of queries in APPS schema to find all Discoverer
Reports/Workbooks that exist in the system.

Query1: Run the following query to know the name of table

SELECT owner,table_name
  FROM all_tables
 WHERE owner = 'EUL4_US'
   AND table_name LIKE '%DOCUMENT%';

Generally the above query returns table_name as 'EUL4_DOCUMENTS' 


Meaning, all the discoverer report/Workbook names are stored in this table

Query 2: Run the following query to see all reports


SELECT DOC_ID,
       DOC_NAME,
       DOC_DEVELOPER_KEY,
       DOC_CREATED_BY
  FROM EUL4_US.EUL4_DOCUMENTS;

Note:
If the First Query is not returning any data then try the following query and manually find the
table name.
   SELECT owner,table_name
     FROM all_tables
    WHERE table_name LIKE '%EUL%DOCUMENT%';

You have to modify the 2nd query in this case with the new OWNER.TABLE_NAME

4. What is business area?


Business area is a logical group of information where we can categorize different module
reports for effective maintenance.
----  Business Area : It is a containers of related information, While creating the
business area we can load the database table containing the related
information.
---- Business area is a logical grouping of database and views that apply to your
specific data requirement and exact combinations of tables and views for each
departments is usually unique.
Example : the accounting departments wants data about budgets and finance.

5. What is the major difference between discoverer and rdf report?


1.discover has administrator edition and desktop edition but rdf has data model and layout
model.
2.discoverer report is easy to create
3.we can import ,export and share work books across multiple users from tool .
4.In discoverer,we can’t design the report structure but,In rdf we can design report in layout
model.
5.discover output format is excel,rdf output format is text.
6.views are used in discoverer,complete is used in rdf.

6. How to create the parameter in discoverer?


Goto toolsparametersclick on new.

7. How many types of folders in discoverer?


Three folder are there in discoverer,
1.simple folder
2.complex folder
3.custom folder

8. What is query governer?


by using query governer,we can apply the following output conditions in work sheet.
1.putting limitation on retrieval data
2.retrieve data incrementally in a group of some figure
3.cancel value retrieval after some output

9. What is fan trap in discoverer?

10. Discoverer registration steps?

11. What is eul?significance of eul?


----EUL means end user layer.which is an interface between discoverer and oracle data
base.

12. If disocverer report takes too much time..what is your approach


We can manage the scheduling by using scheduling manager.
Filemanage workbooksscheduling managers.

13. what is the difference between cross-validation rules and security-rules?


Cross –validation is assigned to chart of accounts and security-rules are assigned to
responsibility level.

14. What are the different types of journals in general ledger ?

15. What is FSG? What are the components of FSG ?


16. What is difference b/n interface & conversion

17. Tell me end to end one interface/conversion.

18. How to resolve error records?

19. Tell me outbound interface end to end

20. Tell me complete information about sql loader.

21. Explain me any 5 conversions along with the interface tables,errors tables and
validations

22. How to issue the commit in the control file?

23. How many types of executable methods in aol

24. How to delete concurrent program,executable,request group ,responsibility from


back end

25. How to register table and column in oracle apps

26. How to submit concurrent program from back end

27. What is the multi org..?How to find multi org is installed in back end.
28. What are the changes in r12 related to it.

29. Request group vs request set

30. What is incompatibility ?can you set the same program incompatible to itself
31. What is the profile options and its levels and its back end tables?

32. What is flexfields and types

33. What are the steps involved into developing flexfields..

34. Flexfield qualifier and segment qualifier

35. Difference between custom schema and apps schema

36. How to generate the trace file for a plsql concurrent program for tuning

37. Org id vs organization id

38. Where we can find log file and outputfile after submitting the concrrent program

39. How to get the data from 11i views and r12 synonyms

40. What is the value set and explain detail

41. How to register the shellscript in oracle apps

42. What are the defualt types in concurrent program

43. Rdf reports vs disocverer reports

Module related queries :

1. Explain end to end p2p cycle along with the tables

2. Explain end to end o2c cycle along with the tables


3. What is the requisition and types of requisitions

4. Types of purchase order and difference between them

5. What are match approval options

6. How many ways to create the invoice

7. What is debit memo and credit memo

8. What is prepayment

9. How to find out the requisition approver ..back end

10. Link between requisition and rfq,po and requisition,po and invoice,invoice and
payment

11. What are the inventory tables affected at po receipts level

12. Link between ap and gl module

13. Link between om and ar module

14. What are the bank tables and accounting tables in 11i as well as r12

15. What are the payment types in ap

16. What are the subledger tables

17. What are the order types and order hold types in om
18. Tell me about pick slip report trip stop report

19. Where we can find applied amount and unapplied amount and balance amt in ar

20. Link between po and om

21. Tell me ar module table minimum 10

22. What are the new features in om module and ar module in r12

23. Tell me internal sales order

24. Explain back to back order flow

25. Explain drop shipment flow

26. Explain tca architecture

27. 11i vs r12 differences

28. Tell me pa module tables minimum 10

29. What is auto lock box

30. What are the important inventory tables

31. Cycle counting vs physical inventory

32. Subinventory transfer vs move order transfer

33. What is auto invoice and auto accounting

You might also like