0% found this document useful (0 votes)
155 views

PL SQL

Here are the steps to create an Oracle table containing an object with a nested table: 1. Create the nested table type: CREATE TYPE DEMO_TAB_TYPE1 AS TABLE OF DEMO_TYPE1; 2. Create the object type containing the nested table: CREATE TYPE DEMO_TYPE2 AS OBJECT (B1 NUMBER, B2 DEMO_TAB_TYPE1); 3. Create the table containing the object: CREATE TABLE DEMO_TAB1 (C1 NUMBER, C2 DEMO_TYPE2) NESTED TABLE C2.B2 STORE AS B2_TAB; The key points: - The nested table

Uploaded by

sreejtih
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views

PL SQL

Here are the steps to create an Oracle table containing an object with a nested table: 1. Create the nested table type: CREATE TYPE DEMO_TAB_TYPE1 AS TABLE OF DEMO_TYPE1; 2. Create the object type containing the nested table: CREATE TYPE DEMO_TYPE2 AS OBJECT (B1 NUMBER, B2 DEMO_TAB_TYPE1); 3. Create the table containing the object: CREATE TABLE DEMO_TAB1 (C1 NUMBER, C2 DEMO_TYPE2) NESTED TABLE C2.B2 STORE AS B2_TAB; The key points: - The nested table

Uploaded by

sreejtih
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

14.Explain Commit, Rollback and Savepoint.

For a COMMIT statement, the following is true:

Other users can see the data changes made by the transaction.
The locks acquired by the transaction are released.
The work done by the transaction becomes permanent.
A ROLLBACK statement gets issued when the transaction ends, and the following is true.

The work done in a transition is undone as if it was never issued.


All locks acquired by transaction are released.
It undoes all the work done by the user in a transaction. With SAVEPOINT, only part of
transaction can be undone.

16.Explain mutating table error.


It occurs when a trigger tries to update a row that it is currently using. It is fixed by using
views or temporary tables, so database selects one and updates the other.

44.Explain polymorphism in PL SQL.


Polymorphism is a feature of OOP. It is the ability to create a variable, an object or function
with multiple forms. PL/SQL supports Polymorphism in the form of program unit overloading
inside a member function or package..Unambiguous logic must be avoided whilst
overloading is being done.

50.Explain SPOOL
Spool command can print the output of sql statements in a file.

spool/tmp/sql_outtxt

select smp_name, smp_id from smp where dept=’accounts’;

spool off;

What are % TYPE and % ROWTYPE? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.

The advantages are: I. need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.

What is the difference between FUNCTION, PROCEDURE AND PACKAGE


in PL/SQL?
Function: The main purpose of a PL/SQL function is generally to compute and return a single value. A function has a return
type in its specification and must return a value specified in that type.
Procedure: A procedure does not have a return type and should not return any value but it can have a return statement that
simply stops its execution and returns to the caller. A procedure is used to return multiple values otherwise it is generally
similar to a function.
Package: A package is schema object which groups logically related PL/SQL types , items and subprograms. You can also
say that it is a group of functions, procedure, variables and record type statement. It provides modularity, due to this facility it
aids application development. It is used to hide information from unauthorized users.

7) How exception is different from error?


Whenever an Error occurs Exception arises. Error is a bug whereas exception is a warning or error condition.

What is stored Procedure?


A stored procedure is a sequence of statement or a named PL/SQL block which performs one or more specific functions. It is
similar to a procedure in other programming languages. It is stored in the database and can be repeatedly executed. It is
stored as schema object. It can be nested, invoked and parameterized.

What are the cursor attributes used in PL/SQL?


%ISOPEN: it checks whether the cursor is open or not.
%ROWCOUNT: returns the number of rows affected by DML operations: INSERT,DELETE,UPDATE,SELECT.
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
%NOTFOUND: it checks whether cursor has fetched any row. If no - TRUE.

What is cursor and why it is required?


A cursor is a temporary work area created in a system memory when an SQL statement is executed.
A cursor contains information on a select statement and the row of data accessed by it. This temporary work area stores 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. Cursor are required to process rows individually for queries.

Oracle PL/SQL Nested Tables


Oracle PL/SQL Nested Tables

Nested tables are similar to index by table but these can be stored in database columns but index by
tables cannot be stored in database columns.

A Nested table can be considered as a single-column table that can either be in memory, or as a column
in a database table. A nested table is quite similar to a VARRAY with the exception that the order of the
elements is not static. Elements can be deleted or added anywhere in the nested table where as a
VARRAY can only add or delete elements from the end of the array. Nested Table is known as a sparse
collection because a nested table can contain empty elements.

Nested tables are a superior choice when:


 You need to delete or update some elements, but not all the elements at once.
 The index values are not consecutive.
 We don’t have any predefined upper bound for index values.
Example 1 of Pl/SQL Nested Table
DECLARE
TYPE n_tab_T IS TABLE OF NUMBER;
nt n_tab_T := n_tab_T();

BEGIN
FOR i IN 1..10 LOOP
nt.EXTEND;
nt(i) := i;
END LOOP;
END;

Example 2 of Pl/SQL Nested Table

Suppose we have a more complex beer type:


create type BeerBrand as object (
name char(20),
kind char(10),
color char(10) );

We may create a type that is a nested table of objects of this type by:

Create type BeerTableBrand as table of BeerBrand;

Define a relation of manufacturers that will nest their beers inside.


create table manfs (
name char(30),
addr AddrType,
beers BeerTableBrand)
nested table beers store as BeerTable;

The last line in the create table statement indicates that the nested table is not stored "in-line" with the
rest of the table
(Oracle maintains pointers between tables); you cannot refer to BeerTable in any query!

Inserting into nested table

insert into manfs values


(’Budweiser’,
AddrType(’LoopRoad’,’Boga’,’CA’,56789),
BeerTableBrand(
BeerBrand(’sweet’,’ale’,’yellow’),
BeerBrand(’sour’,’lager’,’pale’)
)
);

Querying the nested table


Example: List the beers made by Budweiser:

select beers from manfs


where name = ’Budweiser’;

This query gives you a single value that looks like this:

BeerTableBrand(
BeerBrand(’sweet’,’ale’,’yellow’),
BeerBrand(’sour’,’lager’,’pale’))

NESTED TABLE

NESTED TABLE is an Oracle data type used to support columns containing multivalued attributes, in
this case, columns that can hold an entire sub-table.

Examples
Create a table with NESTED TABLE column:
CREATE OR REPLACE TYPE my_tab_t AS TABLE OF VARCHAR2(30);
/
CREATE TABLE nested_table (id NUMBER, col1 my_tab_t)
NESTED TABLE col1 STORE AS col1_tab;

Insert data into table:


INSERT INTO nested_table VALUES (1, my_tab_t('A'));
INSERT INTO nested_table VALUES (2, my_tab_t('B', 'C'));
INSERT INTO nested_table VALUES (3, my_tab_t('D', 'E', 'F'));
COMMIT;

Select from nested table:


SQL> SELECT * FROM nested_table;
ID COL1
---------- ------------------------
1 MY_TAB_T('A')
2 MY_TAB_T('B', 'C')
3 MY_TAB_T('D', 'E', 'F')

Unnesting the subtable:


SQL> SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2;
ID COLUMN_VALUE
---------- ------------------------
1 A
2 B
2 C
3 D
3 E
3 F
6 rows selected.

A more complicated multi-column nested table where customers can have multiple addresses:
CREATE TYPE address_t AS OBJECT (
street VARCHAR2(30),
city VARCHAR2(20),
state CHAR(2),
zip CHAR(5) );
/
CREATE TYPE address_tab IS TABLE OF address_t;
/
CREATE TABLE customers (
custid NUMBER,
address address_tab )
NESTED TABLE address STORE AS customer_addresses;

INSERT INTO customers VALUES (1,


address_tab(
address_t('101 First', 'Redwood Shores', 'CA', '94065'),
address_t('123 Maple', 'Mill Valley', 'CA', '90952')
) );

Unnesting the subtable:


SQL> select c.custid, u.*
2 from customers c, table (c.address) u
3 ;

CUSTID STREET CITY ST ZIP


---------- ------------------------------ -------------------- -- -----
1 101 First Redwood Shores CA 94065
1 123 Maple Mill Valley CA 90952

How do I create an Oracle table of objects


containing nested tables?
down My question is similar to 9454933 but my nested table is within the object.
vote
favorite I wish to create a table of user defined types where the defined type contains an object, my
simplified setup looks like this

CREATE TYPE DEMO_TYPE1 AS OBJECT (A1 NUMBER, A2 NUMBER);

CREATE TYPE DEMO_TAB_TYPE1 AS TABLE OF DEMO_TYPE1;

CREATE TYPE DEMO_TYPE2 AS OBJECT (B1 NUMBER, B2 DEMO_TAB_TYPE1);


CREATE TABLE DEMO_TAB1 (C1 NUMBER, C2 DEMO_TYPE2);

If I run the above I get the following error

The storage clause is not specified for the nested table column or attribute.

This makes sense but I can't work out the correct syntax to fix this I've tried

CREATE TABLE DEMO_TAB1 (C1 NUMBER, C2 DEMO_TYPE2)


NESTED TABLE B2 STORE AS B2_TAB;

but this and every other variation I've tried result in ORA-00922: missing or invalid option

So how do I resolve this?

The reason of the error is that the C2 is not a nested table. The nested table is the B2 inside C2,
so you should try this:

CREATE TABLE DEMO_TAB1 (C1 NUMBER, C2 DEMO_TYPE2)


NESTED TABLE C2.B2 STORE AS B2_TAB;

See sqlfiddle: sqlfiddle.com/#!4/6c662/1

Monitor
To see what nested tables were created, query the USER_NESTED_TABLES and
USER_NESTED_TABLE_COLS views.

How to update a table column with random values within a range in Oracle?
dbms_random() is what you are looking for:
UPDATE the_table
SET rand_amount = (amount * dbms_random.value(0, 100) ) /
4 down vote

100
WHERE amount IS NOT NULL

Candidate Key – A Candidate Key can be any column or a combination of columns that can
qualify as unique key in database. There can be multiple Candidate Keys in one table. Each
Candidate Key can qualify as Primary Key.
Primary Key – A Primary Key is a column or a combination of columns that uniquely identify a
record. Only one Candidate Key can be Primary Key.
Explain the uses of database trigger?

A PL/SQL program unit associated with a particular database table is called a database trigger. It is
used for :
 Audit data modifications.
 Log events transparently.
 Enforce complex business rules.
 Maintain replica tables
 Derive column values
 Implement Complex security authorizations
What are the benefits of PL/SQL packages?

It provides several benefits like


 Enforced Information Hiding: It offers the liberty to choose whether to keep data private or
public
 Top-down design: You can design the interface to the code hidden in the package before you
actually implemented the modules themselves
 Object persistence: Objects declared in a package specification behaves like a global data for all
PL/SQL objects in the application. You can modify the package in one module and then reference
those changes to another module
 Object oriented design: The package gives developers strong hold over how the modules and
data structures inside the package can be used
 Guaranteeing transaction integrity: It provides a level of transaction integrity
 Performance improvement: The RDBMS automatically tracks the validity of all program
objects stored in the database and enhance the performance of packages.
What is the difference between Views and Materialized Views in
Oracle?
Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.

Views evaluate the data in the tables underlying the view definition at the time the view is queried. It is a
logical view of your tables, with no data stored anywhere else. The upside of a view is that it will always
return the latest data to you. The downside of a view is that its performance depends on how good a select
statement the view is based on. If the select statement used by the view joins many tables, or uses joins
based on non-indexed columns, the view could perform poorly.
Materialized views are similar to regular views, in that they are a logical view of your data (based on a
select statement), however, the underlying query resultset has been saved to a table. The upside of this is
that when you query a materialized view, you are querying a table, which may also be indexed. In addition,
because all the joins have been resolved at materialized view refresh time, you pay the price of the join once
(or as often as you refresh your materialized view), rather than each time you select from the materialized
view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of
your materialized view in such a way that it instead reads from your materialized view. In situations where
you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this
can greatly speed up the response time of your end user application. The downside though is that the data
you get back from the materialized view is only as up to date as the last time the materialized view has been
refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a
change in data from one of the underlying tables. Materialized views can be incrementally updated by
combining them with materialized view logs, which act as change data capture sources on the underlying
tables.
Materialized views are most often used in data warehousing / business intelligence applications where
querying large fact tables with thousands of millions of rows would result in query response times that
resulted in an unusable application.

What is a schema?
Ans: The set of objects owned by user account is called the schema.

Difference between SUBSTR and INSTR?


Ans: INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th
occurrence of the string 2 in string1. The search begins from nth position of
string1.

SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1,


starting from n-th position of string1.

What is difference between CHAR and VARCHAR2? What is the maximum SIZE
allowed for each type?
Ans: CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad
blank spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2

What are the components of physical database structure of Oracle database?


Ans: Oracle database is comprised of three types of files. One or more datafiles,
two are more redo log files, and one or more control files.

How can we refresh a snapshot?


Ans: Refreshing Snapshots: A snapshot can be refreshed automatically or
manually. If a snapshot has to be automatically refreshed then refresh clause
must be specified in the CREATE SNAPSHOT. The FAST, COMPLETE or FORCE
specifies the type of REFRESH used for automatic refresh. For automatic refresh
we can specify the START WITH and NEXT parameter to decide the time interval
for the next update.
COMPLETE refresh: In complete refresh the snapshot query is executed and places
the result in the snapshot.
FAST refresh : In this only the changes made to the master table will be updated
to the snapshot. The corresponding log file is used to update. Fast refresh will be
done only if * The snapshot is a simple snapshot. * The snapshot's master table
has a snapshot log \ * The snapshot log was created before the snapshot was last
refreshed or created.
FORCE refresh : In this ORACLE decides how to refresh the snapshot at the
scheduled refresh time. If a fast refresh is possible it performs a fast refresh else it
does a complete refresh.

What is a tablespace?
Ans: A database is divided into Logical Storage Unit called tablespaces. A
tablespace is used to grouped related logical structures together.

Select nth highest value from a list of values ?


Ans: SELECT a.emp_name,a.sal FROM emp a WHERE &n - 1= (SELECT
COUNT(DISTINCT sal) FROM emp b WHERE b.sal > a.sal )

Explanation :
The distinct keyword is there to deal with duplicate salaries in the table. In order to find
the Nth highest salary, we are only considering unique salaries. Highest salary means no
salary is higher than it, Second highest means only one salary is higher than it, 3rd highest
means two salaries are higher than it, similarly Nth highest salary means N-1 salaries are
higher than it.

What are triggers and its types?


Ans: A trigger is a piece of code attached to a table that is executed after
specified DML statements executed on that table. There are 12 types of triggers in
PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, STATEMENT,
TABLE, INSERT, UPDATE, DELETE and ALL key words: For eg: BEFORE ALL ROW
INSERT AFTER ALL ROW INSERT BEFORE INSERT AFTER INSERT

What is the maximum number of triggers, can apply to a single table?


Ans: 12 triggers(Oracle).

Do we use commit in triggers.


Ans: No

How will the fetch the last inserted record in any table ?
Ans: select column 1, column 2.... From where rowid = (select max(rowid) from
table);

What is Referential Integrity and Referential integrity constraint ?


Ans: Referential Integrity : Referential integrity defines the relationships among
different columns and tables in a relational database. It’s called referential
integrity because the values in one column or set of columns refer to or must
match the values in a related column or set of columns.

A referential integrity constraint requires that for each row of a table, the value in
the foreign key matches a value in a parent key.

What are Advantages of TRUNCATE Command over DELETE/DROP TABLE


Command ?
Ans: The TRUNCATE command provides a fast, efficient method for deleting all
rows from a table or cluster.

1. A TRUNCATE statement does not generate any rollback information and it


commits immediately; it is a DDL statement and cannot be rolled back.

2. A TRUNCATE statement does not affect any structures associated with the table
being truncated (constraints and triggers) or authorizations (grants).

3. A TRUNCATE statement also specifies whether space currently allocated for the
table is returned to the containing tablespace after truncation.

4. As a TRUNCATE statement deletes rows from a table (or clustered table),


triggers associated with the table are not fired.

5. Also, a TRUNCATE statement does not generate any audit information


corresponding to DELETE statements if auditing is enabled. Instead, a single audit
record is generated for the TRUNCATE statement being issued.

46.What are steps involved in Execution of SQL statements?


Ans: STEPS IN EXECUTION OF SQL STATEMENTS :

1. Create a cursor

2. Parse the statement


3. Describe Results

4. Defining outputs

5. Bind any variables

6. Execute the statement

7. Fetch rows of a query result

What do you mean by Parsing?


Ans: Parsing : Parsing is the process of: 1. Translating a SQL statement, verifying it
to be a valid statement 2. Performing data dictionary lookups to check table and
column definitions 3. Acquiring parse locks on required objects so that their
definitions do not change during the statement's parsing 4. Checking privileges to
access referenced schema objects 5. Determining the execution plan to be used
when executing the statement 6. Loading it into a shared SQL area 7. For
distributed statements, routing all or part of the statement to remote nodes that
contain referenced data

What is a HINT and what are types HINT?


Ans: Hints are suggestions that you give the optimizer for optimizing a SQL
statement. Hints allow you to make decisions usually made by the optimizer.

TYPES OF HINTS :

ALL_ROWS : The ALL_ROWS hint explicitly chooses the cost-based approach to


optimize a statement block with a goal of best throughput.

FIRST_ROWS : The FIRST_ROWS hint explicitly chooses the cost-based approach to


optimize a statement block with a goal of best response time.

FULL : The FULL hint explicitly chooses a full table scan for the specified table.

ROWID : The ROWID hint explicitly chooses a table scan by ROWID for the
specified table.

CLUSTER : The CLUSTER hint explicitly chooses a cluster scan to access the
specified table.
HASH : The HASH hint explicitly chooses a hash scan to access the specified table.

INDEX : The INDEX hint explicitly chooses an index scan for the specified table.

AND_EQUAL: The AND_EQUAL hint explicitly chooses an execution plan that uses
an access path that merges the scans on several single-column indexes. (You can
specify multiple indexes through this hint) INDEX_ASC: The INDEX_ASC hint
explicitly chooses an index scan for the specified table. If the statement uses an
index range scan, ORACLE scans the index entries in ascending order of their
indexed values.

INDEX_DESC: The INDEX_DESC hint explicitly chooses an index scan for the
specified table. If the statement uses an index range scan, ORACLE scans the
index entries in descending order of their indexed values.

ORDERED : The ORDERED hint causes ORACLE to join tables in the order in which
they appear in the FROM clause.

USE_NL : The USE_NL hint causes ORACLE to join each specified table to another
row source with a nested loops join using the specified table as the inner table.

USE_MERGE : The USE_MERGE hint causes ORACLE to join each specified table
with another row source with a sort-merge join.

Can a trigger written for a view ?


Ans: No

Can you create index on view ?

Ans: No

What do u mean by EXCEPTION_INIT Pragma ?


Ans: EXCEPTION_INIT Pragma : To handle unnamed internal exceptions, you must
use the OTHERS handler or the pragma EXCEPTION_INIT. A "pragma" is a compiler
directive, which can be thought of as a parenthetical remark to the compiler.
Pragmas (also called "pseudoinstructions") are processed at compile time, not at
run time. They do not affect the meaning of a program; they simply convey
information to the compiler. The predefined pragma EXCEPTION_INIT tells the
PL/SQL compiler to associate an exception name with an Oracle error number.
That allows you to refer to any internal exception by name and to write a specific
handler for it. You code the pragma EXCEPTION_INIT in the declarative part of a
PL/SQL block, subprogram, or package

using the syntax PRAGMA EXCEPTION_INIT(exception_name,


Oracle_error_number); where "exception_name" is the name of a previously
declared exception. For internal exceptions, SQLCODE returns the number of the
associated Oracle error. The number that SQLCODE returns is negative unless the
Oracle error is "no data found," in which case SQLCODE returns +100. SQLERRM
returns the message associated with the Oracle error that occurred. The message
begins with the Oracle error code. For user-defined exceptions, SQLCODE returns
+1 and SQLERRM returns the message “User-Defined Exception” unless you used
the pragma EXCEPTION_INIT to associate the exception name with an Oracle error
number, in which case SQLCODE returns that error number and SQLERRM returns
the corresponding error message. The maximum length of an Oracle error
message is 512 characters including the error code, nested messages, and
message inserts such as table and column names.

What do u mean by JSP query?

Ans: JSP Query : The JSP Query is a standard query for number to words
conversion, used especially for converting amount in number into equivalent
amount in words. The query is as follows : Select to_char ( to_date ( ‘&no’, ‘J’ ),
‘JSP’ ) words from dual; For eg : Select to_char ( to_date ( '23949','j' ), 'JSP' )
"words" from dual; The value that can pass to &no cannot exceed 7 digits.

What is “Check Constraints” and “with check options” and “Default Specification”?
Ans: CHECK Integrity Constraints: A CHECK integrity constraint on a column or a
set of columns requires that a specified condition be true or unknown (ie. Not
false) for every row of the table. If a DML statement is issued so that the condition
of the CHECK constraint evaluates to false, the statement is rolled back. With
check Option: With Check option restricts inserts and updates performed through
the view to prevent them from creating rows that the view cannot itself select
.based on where clause of the create view statement. For eg: Create or replace
view Women As select name from Employee Where Sex= ‘Female’ With Check
Option; Default Specification It supplies a default value if column value is not
specified on INSERT It can contain literals (constants) and SQL functions, USER,
SYSDATE, sequence It cannot include references to any columns.

What is the difference between alias and synonym ?


Ans: Alias is temporary and used with one query. Synonym is permanent and not
used as alias.

What is tkprof and how is it used?


Ans: The tkprof tool is a tuning tool used to determine cpu and execution times for
SQL statements. You use it by first setting timed_statistics to true in the
initialization file and then turning on tracing for either the entire database via the
sql_trace parameter or for the session using the ALTER SESSION command. Once
the trace file is generated you run the tkprof tool against the trace file and then
look at the output from the tkprof tool . This can also be used to generate explain
plan output.

What is explain plan and how is it used?


Ans: The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you
must have an explain_table generated in the user you are running the explain
plan for. This is created using the utlxplan.sql script. Once the explain plan table
exists you run the explain plan command giving as its argument the SQL
statement to be explained. The explain_plan table is then queried to see the
execution plan of the statement. Explain plans can also be run using tkprof.

What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
Ans: SQLCODE returns the value of the error number for the last error
encountered. The SQLERRM returns the actual error message for the last error
encountered. They can be used in exception handling to report, or, store in an
error log table, the error that occurred in the code. These are especially useful for
the WHEN OTHERS exception.

How can you generate debugging output from PL/SQL?


Expected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR
command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results
from loops and the status of variables as the procedure is executed. The new package UTL_FILE can also be
used.

Can one pass an object/table as an argument to a remote procedure?


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

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


CREATE OR REPLACE PROCEDURE pcalling IS
TabX DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN
pcalled@DBLINK2(TabX);
END;
/

REF CURSOR

A REF Cursor is a datatype that holds a cursor value in the same way that a VARCHAR2 variable will
hold a string value.
A REF Cursor can be opened on the server and passed

Example[edit]
Create a function that opens a cursor and returns a reference to it:

CREATE OR REPLACE FUNCTION f RETURN SYS_REFCURSOR


AS
c SYS_REFCURSOR;
BEGIN
OPEN c FOR select * from dual;
RETURN c;
END;
/

Call the above function and fetch all rows from the cursor it returns:

set serveroutput on
DECLARE
c SYS_REFCURSOR;
v VARCHAR2(1);
BEGIN
c := f(); -- Get ref cursor from function
LOOP
FETCH c into v;
EXIT WHEN c%NOTFOUND;
dbms_output.put_line('Value from cursor: '||v);
END LOOP;
END;
/

the difference is that a ref cursor can be assigned to different result sets whereas a cursor is
always associated with the same result set.

The real purpose of ref cursors is to be able to share cursors and result sets between the client
and the Oracle server or between different subroutines. For example you might open a cursor in
an Oracle Forms client and then continue working with the cursor on the server or you might open
a cursor in a Java program and then continue working with it in an Oracle PL/SQL stored
procedure.

Ref cursors also come in two variants: strongly typed and weakly typed depending on how likely
you are (or want to) reuse a cursor variable. Weak ref cursor types can be associated with any
query whereas strong ref cursor types can only be associated with cursors of the same type.

select case when null = null then 'Yup' else 'Nope' end as Result;
This query will actually yield “Nope”, seeming to imply that null is not equal to
itself! The reason for this is that the proper way to compare a value to null in SQL
is with the is operator, not with =.
Accordingly, the correct version of the above query that yields the expected result
(i.e., “Yup”) would be as follows:
select case when null is null then 'Yup' else 'Nope' end as Result;

Given a table TBL with a field Nmbr that has rows with
thwing values:
1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1
write a query to add 2 where nmbr is 0 and add 3
when nmbr is 1
update TBL set Nmbr = case when Nmbr > 0 then Nmbr+3 else Nmbr+2 end;

Write a SQL query to find the 10th highest employee


salary from an Employee table. Explain your answer.
(Note: You may assume that there are at least 10
records in the Employee table.)
SELECT TOP (1) Salary FROM
(
SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
) AS Emp ORDER BY Salary

What is the difference between


the RANK() and DENSE_RANK() functions? Provide an example.
The only difference between the RANK() and DENSE_RANK() functions is in cases
where there is a “tie”; i.e., in cases where multiple values in a set have the same
ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values
in the set (resulting in gaps between the integer ranking values when there is a
tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set
(so there will be no gaps between the integer ranking values in the case of a tie).
For example, consider the set {25, 25, 50, 75, 75, 100}. For such a
set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are
skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.
Question 26. What is the difference between sub query and correlated query

Answer-
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.

Please check out the example below-

SELECT * FROM Visits WHERE CustomerId IN (SELECT CustomerId FROM Visits


1
WHERE VisitDate = '2013-09-03 00:00:00.000')
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 number 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

Please check out the famous example below- ( 2nd Highest Salary )

SELECT * FROM NthHighest N WHERE 1 = (SELECT DISTINCT(COUNT(*)) FROM


1
NthHighest m WHERE n.Salary < m.Salary )

What exactly you check in the query execution plan window?


Answer –
Query Execution Plans describe the steps and the order used to access data in the database.
Normally we check the execution plan for missing indexes, if any. We also check the execution
plans if the query or stored procedure is working slowly. If working slowly we need to check for Red
flags and see how we can remove them.

You can use execution plan to check out following things –

• Missing Indexes
• Missing Statistics
• Red Flags
• How data is being retrieved (Which path , what all indexes are used)

What is the output of SELECT Len(1234.56)


Answer – 7 (In this case it will consider all the characters including.)

Can we fire a trigger manually?


Answer-
No you can’t. If you want a procedure that can be executed manually, then you should just create
a stored procedure.

Self Join example


E.g., an Employee table may have a SupervisorID column that points to the employee that is the
boss of the current employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

nth highest salary example and explanation


2nd highest Salary value in our table above, so our N is 2. This means that the query will look like this:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

Let’s assume that we are using this data:


Employee
Employee ID Salary
3 200
4 800
7 450
For the sake of our explanation, let’s assume that N is 2 – so the query is trying to find the 2nd highest
salary in the Employee table. The first thing that the query above does is process the very first row of the
Employee table, which has an alias of Emp1.
The salary in the first row of the Employee table is 200. Because the subquery is correlated to the outer
query through the alias Emp1, it means that when the first row is processed, the query will essentially look
like this – note that all we did is replace Emp1.Salary with the value of 200:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 200)

So, what exactly is happening when that first row is processed? Well, if you pay special attention to the
subquery you will notice that it’s basically searching for the count of salary entries in the Employee table that
are greater than 200. Basically, the subquery is trying to find how many salary entries are greater than 200.
Then, that count of salary entries is checked to see if it equals 1 in the outer query, and if so then everything
from that particular row in Emp1 will be returned.
Note that Emp1 and Emp2 are both aliases for the same table – Employee. Emp2 is only being used in the
subquery to compare all the salary values to the current salary value chosen in Emp1. This allows us to find
the number of salary entries (the count) that are greater than 200. And if this number is equal to N-1 (which
is 1 in our case) then we know that we have a winner – and that we have found our answer.
But, it’s clear that the subquery will return a 2 when Emp1.Salary is 200, because there are clearly 2 salaries
greater than 200 in the Employee table. And since 2 is not equal to 1, the salary of 200 will clearly not be
returned.
So, what happens next? Well, the SQL processor will move on to the next row which is 800, and the resulting
query looks like this:

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > 800)

Since there are no salaries greater than 800, the query will move on to the last row and will of course find
the answer as 450. This is because 800 is greater than 450, and the count will be 1. More precisely, the
entire row with the desired salary would be returned, and this is what it would look like:

EmployeeID Salary
7 450
It’s also worth pointing out that the reason DISTINCT is used in the query above is because there may be
duplicate salary values in the table. In that scenario, we only want to count repeated salaries just once,
which is exactly why we use the DISTINCT operator.

Dynamic SQL
Dynamic SQL is a SQL statement that is constructed and executed at program execution time. In contrast to
this, static SQL statements are hard-coded in the program and executed "as-is" at run-time. Dynamic SQL
provides more flexibility, nevertheless, static SQL is faster and more secure than dynamic SQL.

Ways to write dynamic SQL


PL/SQL provides two ways to write dynamic SQL
1.NDS – Native Dynamic SQL
2.DBMS_SQL

NDS
Native Dynamic SQL is the easier way to write dynamic SQL. It uses the 'EXECUTE
IMMEDIATE' command to create and execute the SQL at run-time. But to use this way, the
datatype and number of variable that to be used at run time needs to be known before. It also
gives better performance and less complexity when compares to DBMS_SQL.
Syntax Explanation:
The above syntax shows EXECUTE IMMEDIATE command.
Clause INTO is optional and used only if the dynamic SQL contains a select
statement that fetches values. The variable type should match with the variable type of
the select statement.
Clause USING is optional and used only if the dynamic SQL contains any bind
variable.
Example1: In this example, we are going to fetch the data from emp table for emp_no '1001'
using NDS statement.

Code Explanation:
Code line 2-6: Declaring variables.
Code line 8: Framing the SQL at run-time. SQL contains the bind variable in where
condition ':empno'.
Code line 9: Executing the framed SQL text (which is done in code line 8) using the
NDS command 'EXECUTE IMMEDIATE'
The variables in 'INTO' clause (lv_emp_name, ln_emp_no, ln_salary, ln_manager) is
used to hold the fetched values from the SQL query (emp_name, emp_no, salary,
manager)
'USING' clause gives the values to the bind variable in the SQL query (:emp_no).
Code line 10-13: Displaying the fetched values.

DBMS_SQL for Dynamic SQL


PL/SQL provide the DBMS_SQL package that allows you to work with dynamic SQL. The
process of creating and executing the dynamic SQL contains the following process
OPEN CURSOR: The dynamic SQL will execute in the same way as a cursor. So in
order to execute the SQL statement, we must open the cursor.
PARSE SQL: The next step is to parse the dynamic SQL. This process will just check
the syntax and keep the query ready to execute.
BIND VARIABLE Values: The next step is to assign the values for bind variables if
any.
DEFINE COLUMN: The next step is to define the column using their relative positions
in the select statement.
EXECUTE: The next step is to execute the parsed query.
FETCH VALUES: The next step is to fetch the executed values.
CLOSE CURSOR: Once the results are fetched, the cursor should be closed.
Example1: In this example, we are going to fetch the data from emp table for emp_no '1001'
using DBMS_SQL statement.

Code Explanation:
Code line 1-9: Variable declaration.
Code line 10: Framing the SQL statement.
Code line 11: Opening the cursor using DBMS_SQL.OPEN_CURSOR. It will return
the cursor id which is opened.
Code line 12: After the cursor is opened, the SQL is parsed.
Code line 13: Bind variable '1001' is assigning to the cursor id instead ':empno'.
Code line 14-17: Defining the column name based on their relative position in the
SQL statement. In our case, the relative position is (1) emp_name, (2) emp_no (3)
salary (4) manager. So based on this position we are defining the target variable.
Code line 18: Executing the query using DBMS_SQL.EXECUTE. It returns the
number of records processed.
Code line 19-33: Fetching the records using a loop and displaying the same.
Code line 20: DBMS_SQL.FETCH_ROWS will fetch one record from the rows
processed. It can be called repeatedly to fetch all the rows. If it cannot fetch rows, it will
return 0, thus exiting the loop.
Summary
In this section, we have discussed dynamic SQL and the ways to execute DYNAMIC SQL.
We have also seen the different steps in executing the dynamic SQL in both the ways. We
have also seen the examples in which the same scenario is handled in both NDS and
DBMS_SQL ways to perform execution at run-time.

Returning n Random Records from a Table

Use the built-in function VALUE, found in the built-in package DBMS_RANDOM, in conjunction
with ORDER BY and the built-in function ROWNUM:

1 select *
2 from (
3 select ename, job
4 from emp
6 order by dbms_random.value()
7 )
8 where rownum <= 5

What is a Dual Table?

Dual table is owned by the user SYS and can be accessed by all users. It contains one
columnDummy and one row with the value X. The Dual Table is useful when you want to
return a value only once. The value can be a constant, pseudocolumn or expression that is not
derived from a table with user data.

Describe different types of General Function used in SQL?

General functions are of following types:

1.NVL: Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then
NVL function return value of exp2.
2.NVL2: If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The
argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)
3.NULLIF: Compares two expressions and returns null if they are equal or the first
expression if they are not equal. NULLIF (exp1, exp2)
4.COALESCE: Returns the first non-null expression in the expression list. COALESCE
(exp1, exp2… expn). The advantage of the COALESCE function over NVL function is
that the COALESCE function can take multiple alternative values.
5.Conditional Expressions: Provide the use of IF-THEN-ELSE logic within a SQL
statement. Example: CASE Expression and DECODE Function.
6.
What is a difference between “VERIFY” and “FEEDBACK” command?
VERIFY Command: Use VERIFY Command to confirm the changes in the SQL statement (Old
and New values). Defined with SET VERIFY ON/OFF.

Feedback Command: Displays the number of records returned by a query.

Describe few restrictions on using “LONG” data type?

A LONG column is not copied when a table is created using a sub query. A LONG column
cannot be included in a GROUP BY or an ORDER BY clause. Only one LONG column can be
used per table. No constraint can be defined on a LONG column.

TCS PL/SQL Interview Questions

How to know which version is currently running in your database?


Do you have any experience in data modeling?
How to disable all triggers in a table?
How many triggers are you created?
How many triggers created on one table?
Which will fire default first statement level or row level trigger?
What is bulkcollect? And any restrictions in bulkcollect?
What is the use of limit clause in bulkcollect?
How to debugg your code?
How to trace error handling?
How to find which line error was raised?
What are the methods there in save exceptions?
What is functional based index? Write syntax?
How to update complex view?
Can you alter procedure with in package?
Is it possible to open cursor which is in package in another procrdure?
What is substr()&instr()?
Difference between case and decode?
Can you use sysdate in check constraints? If no, why?
Difference between column level constraints & table level constraints?
What is optimizer?

Difference between Syntax and Runtime errors in PL/SQL??


1.Explain what is COMMIT, ROLLBACK and SAVEPOINT??
2.How many types of Triggers are there in PL/SQL and what are they?
3.How to generate Debugging Information in PL/SQL?
4.In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented?
5.Name any 5 PL/SQL exception types
6.What are the two different types of Exceptions in PL/SQL?
7.What is IN parameter and OUT parameter in PLSQL?
8.What is Public and Private Procedures in PL/SQL?
9.What is Referential Integrity?
10.What is SQLCODE and SQLERRM in PL/SQL?
11.What is the difference between CASE and DECODE?
12.What is the difference between VARCHAR and VARCHAR2 in PL/SQL?
13.What is %TYPE and %ROWTYPE in PL/SQL??
14.What is the disadvantage of using %ROWTYPE in PL/SQL?
15.What are the advantages of using %TYPE and $ROWTYPE in PL/SQL?
16.List all different types of Data Types in PL/SQL?
17.What is the difference between Views and Materialized Views in Oracle?
18.What is difference between a PROCEDURE & a FUNCTION ?
19.What are the Advantages of Using Database Triggers??
20.What are two virtual tables available during database trigger execution in PL/SQL?
21.Is it mandatory to close the Cursor in a PL/SQL block ?
22.What is difference between % ROWTYPE and TYPE RECORD?
23.How does an Explicit Cursor work in PL/SQL?
24.Can we use RETURN STATEMENT and RETURN key word in Procedure, if we use what will happen?
25.How to debug your PL/SQL procedure?
Does SQL*PLUS has embedded PLSQL engine?
1.How does an Implicit Cursor work in PL/SQL?
2.How does ROWID help in running a query faster?
3.How to return more than one value from a Function in PL/SQL
4.How to use COMMIT in PL/SQL Trigger?
5.In a PL/SQL block of code how do you find if a Cursor is STILL open?
6.What are all the special operators does Oracle provide for dealing with NULLs?
7.What are Explicit Cursor attributes and what are they?
8.What are Implicit Cursor attributes and what are they?
9.What are the rules to be applied to NULL while doing comparison in an expression?
10.What is a trigger and what is the difference between Row Level and Statement Level trigger??
11.What is Autonomous transaction in PL/SQL?
12.What is Global Temporary Tables and What is it Purpose?
13.What is Mutating error in PL/SQL Triggers?
14.What is RAISE_APPLICATION_ERROR is PL/SQL?
15.What is SYS_GUID() function? and what is the purpose of SYS_GUID function?
16.What is the maximum number of triggers, can apply to a single table?
17.What steps are included in the compilation process of a PL/SQL block?
18.How to avoid usage of Cursors in PL/SQL?
19.How to return more than one value from a Function in PL/SQL
20.How is the Cursor declared in Procedure is different from Cursor defined in Package Specification?
21.What is RAISE_APPLICATION_ERROR in PL/SQL Exception handling??
22.What is PRAGMA EXECPTION_INIT?
23.What happens if a procedure which updates a column of table X is called in a database trigger of the same
table?

24.What is the purpose of WHERE CURRENT OF statement in PL/SQL?


25.Why cant we use SQLERRM and SQLCODE in INSERT Statement?
26.Can we write When OTHERS Exception at the beginning of the exception block and some other exceptions
after that ?

27.What is Cursor Variables or REF CURSOR ?


28.What are the Disadvantages of Cursor Variables?
29.What are the advantages of using %TYPE and $ROWTYPE in PL/SQL?
30.How to find Package/Procedure name and Line Number where the program got errored out???
31.What is BULK COLLECT in PL/SQL?

You might also like