25 July, 2015

How Many Ways a Cursor Can Be Defined In Oracle

Wandering down the roads of Oracle resources, I found an open article related to Oracle Cursors. It is a blog by Steven Feuerstein who has written many books on pl sql and Oracle in general.
The article is about the ways a cursor can be defined in Oracle.

Oracle PL SQL | Pending Questions

1. The validity of a package depends upon the validity of the other database objects it references to; So if we try to create 2 packages which have dependency on each other, then how will that contention be resolved?

Resources | Multiple Edits | Updated Periodically

1. SQL, PL/SQL The programming language of Oracle - Ivan Bayross

24 July, 2015

More on Oracle Autotrace and TKprof

 

Autotrace is quite easy to use and provides useful info about the query statistics. It should be the first tool to be used for perf. Testing an application.

Autotrace provides many of the TRACE and TKPROF statistics such as disk reads and total reads.

The main difference between the AUTOTRACE and EXPLAIN PLAN commands in Oracle is that AUTOTRACE actually executes the query (in the way TRACE does) and automatically queries the plan table, whereas EXPLAIN PLAN does neither.

 

It can be used from SQL*Plus and provides query stats on the screen.

 

Options for the Autotrace –

• autotrace on – Enables all options.
• autotrace on explain – Displays returned rows and the explain plan.
• autotrace on statistics – Displays returned rows and statistics. 
• autotrace trace explain – Displays the execution plan for a select statement without actually executing it. "set autotrace trace explain"
• autotrace traceonly – Displays execution plan and statistics without displaying the returned rows. This option should be used when a large result set is expected.

Performance Tuning | Components of a trace file

 

Components of a trace –

 

Sample of a TKPROF’ed file

 

PARSE – the phase where Oracle finds the query in the shared pool(called soft parse) or creates a new plan(hard parse)

EXECUTE – this is the work done by Oracle in the OPEN or EXECUTE part of the statement. It will be empty for SELECT stmt.

FETCH – will have the most part of processing in case of a SELECT stmt, but would be mostly empty in case of an UPDATE stmt.

 

COUNT – Gives count on how many times this phase of the query was performed. Ideally, the parse count of a query should be 1 and execute count can be 1 or more. In a properly written application, the parse count will be 1.

CPU – amount of cpu time spent in thousands of seconds.

ELAPSED – The actual clock time spent on the query. If the elapsed time is quite large than the value of cpu time, then it means oracle spent time waiting for something.

DISK – how many physical I/Os were performed on the query. Like we have 34 physical I/O reads in the above query.

 

QUERY – Number of logical I/Os performed to retrieve consistent mode blocks. Generally all physical I/Os result into a logical I/O.

CURRENT – number of logical I/Os performed to retrieve blocks as of now. This is used in cases when DML is performed in the query, like an UPDATE stmt. In this case, the query data must be retrieved in the current mode.

ROWS – The number of rows processed/ affected by this phase. For update, this value would be populated in the Execute phase, and in case of a SELECT stmt, this value would be in Parse phase.

Implicit vs. Explicit cursors

Implicit vs. Explicit

 

Both the above are purely conceptual things and for Oracle engine, both are same. But implicit cursors are more efficient and easy to deal with.

 

Implicit

Explicit

begin

  for x in ( select * from t )

  loop

     process x;

   end loop;

end;

declare

   cursor c is select * from t;

   l_rec c%rowtype;

begin

   open c;

   loop

      fetch c into l_rec;

      exit when (c%notfound);

      process l_rec;

   end loop;

   close c;

end;

/

 

Both these have no performance benefit over the other. But for explicitly defined cursors, there is more code that needs to be written and hence chances of programmatic errors are more.

Oracle pointers - Part 001

Composite Index

In a composite index, the selected columns should be chosen wisely as this impacts the index performance. The more the columns of a composite index are used in the WHERE clause , the faster would be the execution. The rule is most commonly used column should do first in the composite index.

---------

Cardinality

This is the measure of distinct values of a set. And in terms of database, cardinality is defined as the number of distinct rows returned by a query.

-----------

HINTS -

ALL_ROWS- It instructs the optimizer to fetch the last row of the result-set as fast as possible. non-interactive, batch mode type of application would benefit from this.

FIRST_ROWS - It instructs the optimizer to fetch the first row to the client as fast as possible. An interactive, typical end-user application would benefit from it.

Some tables used by optimizer to gather statistics

It’s a list of some tables which optimizer uses to gather various statistics related to the database tables.

select * from user_tables
where table_name ='EMP'

 
select * from user_tab_statistics
where table_name ='EMP'
 

select * from user_tab_col_statistics
where table_name ='EMP'

 
select * from user_tab_histograms
where table_name ='EMP'
and column_name = 'EMPID'

08 July, 2015

Oracle Collections : Introduction

A collection is an ordered group of elements which have the same data type and we use subscripts to actually access those elements.

There are three types of collections provided by Oracle:

  1. Index-by Tables / Associative Arrays
  2. Nested Table
  3. Variable size array / Varray

Index by Table / Associative Array
Each stored data unit is in the form of KEY-VALUE pair. The keys are unique and it can be either a string or an integer.

TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY sucscript_type;

table_name type_name;

Below is an example showing how to use associatibe array:

TYPE salary IS TABLE OF NUMBER INDEX BY varchar2(20);
salary_list salary;

--Adding elements to this ass. array

salary_list('ram') = 15000;
salary_list('lakshman') = 7050;
salary_list('bharat') = 35000;
salary_list('shatrugan') = 5000;

--Now using the collection elements

name := salary_list.FIRST;
WHILE name IS NOT NULL LOOP
DBMS_OUTPUT.PUT_LINE ('Salary of '||name||' is '||TO_CHAR(salary_list(name));

name := salary_list.NEXT(name);


END LOOP;

END;
/

Elements of a index-by table can be %ROWTYPE data of a database table; or it could be %TYPE of a single column of the table.


NESTED TABLES

Its like a one-dimensional array where the elements are stored with their subscript. 
But its not conventional type of array as the no. of elements in the nested table is unbound compared to normal array. And its also not as dense as arrays are because the elements keep on changing making it sparse.

The syntax of nested tables is similar to that of the index-by collection except the fact that nested tables do not use INDEX BY clause.

Nested tables can be stored in the database tables where as index-by doesn't.

06 July, 2015

Analytical Functions - Introduction

1. What we can do with analytical functions can be done through simple joins and subqueries, but aggregate functions are always faster or atleast equal to native SQL queries.

2. The “group by” works similar to the aggregate function, but the “non-group by” columns are not allowed in the query. In aggregate func, this restriction is omitted and we can see the non-group by data also and the grouped value is repeated for all the results.

select student_class, count(*) cnt from students
where class in ('6A','6B')
group by class

select student_class, house, count(*) over (partition by student_class) cnt from students
where class in ('CF','CHILD')

3. The Analytical functions are computed after all the where, join, group by and having clauses are complete and before the order by clause. So, the analytical functions can appear only in the select clause and main order by clause of the query.

4. If the condition inside the OVER() clause is left empty, the analytical functions works on the entire resultset. We can use any non-analytical function in the OVER() clause.
select status, ext_batch_id, count(*) over () cnt from gefi_batch_header
where status in ('CF','CHILD')

5. The functions SUM, COUNT, AVG, MIN, MAX are the common analytic functions the result of which does not depend on the order of the records.
Functions like LEAD, LAG, RANK, DENSE_RANK, ROW_NUMBER, FIRST, FIRST VALUE, LAST, LAST VALUE depends on order of records. In the next example we will see how to specify that. We can order the records using the ORDER BY clause inside the OVER() clause.

Now , we will explore each of the above mentioned analytical functions in detail:

ROW_NUMBER, RANK and DENSE_RANK

The order by clause of the row_number() function, does not need to be in the select part of the query. This is not possible in the normal order by clause used in the query.
select status, ext_batch_id, row_number() over (partition by status order by batch_id) cnt from gefi_batch_header
where status in ('CF','CHILD')

You can even omit the partitioning clause and still use the order by in the OVER() clause.
select status, ext_batch_id, row_number() over (order by batch_id) cnt from gefi_batch_header
where status in ('CF','CHILD')

RANK and DENSE_RANK, both provide a rank to the resultset rows, but there is a slight difference in the 2 approaches:
SELECT empno, deptno, sal,
RANK() OVER (PARTITION BY deptno
ORDER BY sal DESC NULLS LAST) RANK,
DENSE_RANK() OVER (PARTITION BY
deptno ORDER BY sal DESC NULLS
LAST) DENSE_RANK
FROM emp
WHERE deptno IN (10, 20)
ORDER BY 2, RANK;
 
EMPNO  DEPTNO   SAL  RANK DENSE_RANK
------ ------- ----- ----- ----------
  7839      10  5000     1          1
  7782      10  2450     2          2
  7934      10  1300     3          3
  7788      20  3000     1          1
  7902      20  3000     1          1
  7566      20  2975     3          2
  7876      20  1100     4          3
  7369      20   800     5          4
 
8 rows selected.


As you can see from the query and its result, the RANK skips the rank number, if it finds 2 results with the same rank level. The next in order is assigned the next possible rank. But in case if DENSE_RANK, the values are not skipped and hence it is dense[may be].

List of Analytical functions

The list is analytical functions as found on Ora documentation.

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 *

05 July, 2015

Oracle Storage Structures : Pointers


There are different storage structures available in Oracle. The choice depends upon the purpose and usage of the table.

There are the following types :

  1. Heap Tables (used by default)
  2. Clusters (master-detail type tables)
  3. Index Organized Tables (data stored acc to its key value)

Now adding few basic detials about each of these types.

HEAP STRUCTURED TABLE

  • Got its name from the way data is added/removed from it. When inserting, the first free storage block is used by oracle.
  • And when any data is deleted from heap table, it can be used by new records.
  • Default structure for oracle.
  • Each row has its unique ROWID associated with it and if the record position changes, this ROWID is also changed.

CLUSTER

  • Clusters are further divided into 2 types - hash cluster and index cluster.
  • Index cluster uses index to maintain the records in table.
  • Hash cluster uses a hash algorithm to locate a row in the table and are better suited for searches where equality operator is used.

These are few points of difference between hash and index based clusters.


INDEX ORGANIZED TABLES

  • Normally the index and the rowdata are stored separately; it increases the storage space . But IOTs store the rowdata in the index itself; which makes it fast and low on memory.
  • Uses a B-Tree index structure to store index.
  • The PK is a must for using IOTs. Data is stored in the PK itself.

Honorable mention for a storage structure used by oracle internally.

To minimize the loss of data, oracle uses redo log files. The size of the files can be configured. 
The lesser the size, the smaller the loss of data be.
And to create even more safeguard for failure, we can use redo log groups.
redo log files can be multiplexed as well and in this, multiple copies of the updates are saved.These multiple copies create a group.


The process of archiving the redo log files is called archiving.  
 But server has to be run in the archivelog mode.
Log Writer process(LGWR) is not allowed to reuse or overwrite redo log files until its archived.

Oracle can start multiple archived processes and this can be initiated multiple times. At a single time maximum of 10 archival processes can be started.


SELECT * FROM v$log;
If you want to see the information on redo log files.

02 July, 2015

RDBMS Performance Tuning Material | Part one

1. There are two levels of perf. tuning ; one is at the application level and other is at the database level.

2. Application Tuning - deals with the tuning of applications like forms, reports; an application is a program which interacts with the database and hense
application tuning involves  controlling the frequency and amount of data the app requests the database to send and receive.

3. Pointers for application tuning
                3.1 Generate EXPLAIN PLAN for all the queries used in the application and ensure tuning is done.
                3.2 Generate EXPLAIN PLAN for the db views as well. Views actually are complex compared to tables as actually a DB request to a view is
translated into a table call internally. And a view might have its own joins so can itself hamper performance if not created correctly. Also take due note if you
have joins of views in the queries.
                3.3 As the size of data increases, there may be a need to create indexes on table columns to ensure performance. But it also involves ensuring
that the queries use the indexes created and there are not too many indexes created.
                3.4 Always prefer to use PK or indexed columns.
                3.5 Use specific scenarios to ensure good throughput. Ex- using ROWID is better compared to using the LIKE operator.
                3.6 Reuse the queries as much as possible as it facilitates the use of shated SQL which helps improve performance.
                3.7 Always remember -"Tuning does not solve the problems of poor design"

4. Pointers for database tuning
                4.1 At DB level, there can three areas where tuning can be done -
                                4.1.1 Memory Tuning - cache and buffers
                                4.1.2 I/O Tuning - data access efficient
                                4.1.3 Contention Tuning - resolve resource availability issues
                4.2 Four basic steps involved in the process of DB tuning which are true for all the above mentioned three areas -
                                4.2.1 Gather information
                                4.2.2 Determine optimal changes
                                4.2.3 Implement changes
                                4.2.4 Monitor database

5. Performance Tools

6. Begin Statistics Utility (UTLBSTAT) and End Statistics Utility(UTLESTAT)
     These scripts help in taking snapshot of oracle instance at a specific interval of time. They use oracle's dynamic performance views(V$) to gather this info.
     First, utlBstat is run and after that oracle instance starts gathering all the performance statistics. It keeps on doing that until instance is stopped or utlEstat
is run. After you run utlEstat, the DB creates a REPORTS.TXT file which contains all the statistical info gathered.

7. EXPLAIN PLAN
     This utility helps DBA to pass a query to optimizer and see how it performs within it.
     To run explain plan, you must have a table created in your schema where you want to gather the statistics.
    >$ORACLE_HOME/rdbms/admin/utlxplain.sql;
    The query used to get the explain plan for any sql statement is:
    EXPLAIN PLAN
    SET STATEMENT_ID = 'QUERY1'
     INTO CORE_TABLE FOR
    SELECT transid, policyno, canx_code
    FROM policy
    WHERE policyno = 100;
    Explain plan works for only DML statements.

8. SQL*Trace and TKPROF
     Unlike explain plan which only generates the query execution path of the optimizer; sqlTrace also generates info like the cpu usage, no of rows fetched
etc.
    Parameters which need to be set in INIT.ORA file before you can run sqlTrace are: MAX_DUMP_FILE_SIZE - max size of the trace file, SQL_TRACE - makes
a trace result to be written to file for every database user; not preferred though, USER_DUMP_DEST - destination where the dump files are written.
    ALTER SESSION SET SQL_TRACE = TRUE; The syntax of the query used to start sqlTrace in sql session.
   For generating the trace file for an application, we can use the PLSQL code; the syntax is:
    BEGIN
                DBMS_SESSION.SET_SQL_TRACE(TRUE);
                     -- the code goes here whose statistics are to be gathered
                     DBMS_SESSION.SET_SQL_TRACE(FALSE);
    END
    Once the file is generated , it needs to be converted into a readable format. TKPROF utility is used for that. The syntax -
    % tkprof trace_file.trc new_file.log
    TKPROF utility converts the unreadable trc file into a log file. There are certain optional parameters present in the syntax.
    EXPLAIN - username password
    INSERT - where to dump both the sql statements and data for each statement
    PRINT - no of queries to be picked in the trace file
    RECORD - specify the output file
    SORT - order the results of tkprof

9. With both explain plan and trace files, few pointers help to estimate the performance parameters:
                9.1 There should be a few logical I/O blocks versus a large no of rows returned. Optimal ratio is 2:1
                9.2 mostly, execute value should be higher than the parse value. but if no of parses is higher compared to the no of executions, try incresing the
size of the shared pool.
                9.3 No of logical I/O should be higher compared to the physical I/O.

10. Dynamic performance tables - are actually views despite the name.
      are created when the db instance starts.
      these are SGA held memory structures.
      useful for perf. tuning and backup and recovery.


01 July, 2015

PLSQL Interview Questions | Third Set

1. What is PL/SQL ?PL/SQL is a procedural language which has interactive SQL, as well as procedural programming language constructs like conditional branching and iteration.


2. Differentiate between % ROWTYPE and TYPE RECORD.% ROWTYPE is used when a query returns an entire row of a table or view.TYPE RECORD, on the other hand, is used when a query returns column of different tables or views.Eg. TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname %type)e_rec smp ROWTYPECursor c1 is select smpno,dept from smp;e_rec c1 %ROWTYPE


3. Explain uses of cursor.Cursor is a named private area in SQL from which information can be accessed. They are required to process each row individually for queries which return multiple rows.


4. Show code of a cursor for loop.Cursor declares %ROWTYPE as loop index implicitly. It then opens a cursor, gets rows of values from the active set in fields of the record and shuts when all records are processed.Eg. FOR smp_rec IN C1 LOOPtotalsal=totalsal+smp_recsal;ENDLOOP;


5. 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 :1)Audit data modifications.2)Log events transparently.3)Enforce complex business rules.4)Maintain replica tables5)Derive column values6)Implement Complex security authorizations


6. What are the two types of exceptions.Error handling part of PL/SQL block is called Exception. They have two types : user_defined and predefined.


7. Show some predefined exceptions.DUP_VAL_ON_INDEXZERO_DIVIDENO_DATA_FOUNDTOO_MANY_ROWSCURSOR_ALREADY_OPENINVALID_NUMBERINVALID_CURSORPROGRAM_ERRORTIMEOUT _ON_RESOURCESTORAGE_ERRORLOGON_DENIEDVALUE_ERRORetc.


8. Explain Raise_application_error.It is a procedure of package DBMS_STANDARD that allows issuing of user_defined error messages from database trigger or stored sub-program.


9.Show how functions and procedures are called in a PL/SQL block.Function is called as a part of an expression.total:=calculate_sal(‘b644’)Procedure is called as a statement in PL/SQL.calculate_bonus(‘b644’);


10. Explain two virtual tables available at the time of database trigger execution.Table columns are referred as THEN.column_name and NOW.column_name.For INSERT related triggers, NOW.column_name values are available only.For DELETE related triggers, THEN.column_name values are available only.For UPDATE related triggers, both Table columns are available.


11. What are the rules to be applied to NULLs whilst doing comparisons?1) NULL is never TRUE or FALSE2) NULL cannot be equal or unequal to other values3) If a value in an expression is NULL, then the expression itself evaluates to NULL except for concatenation operator (||)


12. How is a process of PL/SQL compiled?Compilation process includes syntax check, bind and p-code generation processes.Syntax checking checks the PL/SQL codes for compilation errors. When all errors are corrected, a storage address is assigned to the variables that hold data. It is called Binding. P-code is a list of instructions for the PL/SQL engine. P-code is stored in the database for named blocks and is used the next time it is executed.


13. Differentiate between Syntax and runtime errors.A syntax error can be easily detected by a PL/SQL compiler. For eg, incorrect spelling.A runtime error is handled with the help of exception-handling section in an PL/SQL block. For eg, SELECT INTO statement, which does not return any rows.


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.


15. Define Implicit and Explicit Cursors.A cursor is implicit by default. The user cannot control or process the information in this cursor.If a query returns multiple rows of data, the program defines an explicit cursor. This allows the application to process each row sequentially as the cursor returns it.


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.


17. When is a declare statement required?DECLARE statement is used by PL/SQL anonymous blocks such as with stand alone, non-stored procedures. If it is used, it must come first in a stand alone file.


18. How many triggers can be applied to a table?A maximum of 12 triggers can be applied to one table.


19. What is the importance of SQLCODE and SQLERRM?SQLCODE returns the value of the number of error for the last encountered error whereas SQLERRM returns the message for the last error.


20. If a cursor is open, how can we find in a PL/SQL Block?the %ISOPEN cursor status variable can be used.


21. Show the two PL/SQL cursor exceptions.Cursor_Already_OpenInvaid_cursor


22. What operators deal with NULL?NVL converts NULL to another specified value.var:=NVL(var2,’Hi’);IS NULL and IS NOT NULL can be used to check specifically to see whether the value of a variable is NULL or not.


23. Does SQL*Plus also have a PL/SQL Engine?No, SQL*Plus does not have a PL/SQL Engine embedded in it. Thus, all PL/SQL code is sent directly to database engine. It is much more efficient as each statement is not individually stripped off.


24. What packages are available to PL/SQL developers?DBMS_ series of packages, such as, DBMS_PIPE, DBMS_DDL, DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_SQL, DBMS_TRANSACTION, UTL_FILE.


25. Explain 3 basic parts of a trigger.

A triggering statement or event.

A restriction

An action


26. What are character functions?INITCAP, UPPER, SUBSTR, LOWER and LENGTH are all character functions. Group functions give results based on groups of rows, as opposed to individual rows. They are MAX, MIN, AVG, COUNT and SUM.


27. Explain TTITLE and BTITLE.TTITLE and BTITLE commands that control report headers and footers.


28. Show the cursor attributes of PL/SQL.%ISOPEN : Checks if the cursor is open or not%ROWCOUNT : The number of rows that are updated, deleted or fetched.%FOUND : Checks if the cursor has fetched any row. It is true if rows are fetched%NOT FOUND : Checks if the cursor has fetched any row. It is True if rows are not fetched.


29. What is an Intersect?Intersect is the product of two tables and it lists only matching rows.


30. What are sequences?Sequences are used to generate sequence numbers without an overhead of locking. Its drawback is that the sequence number is lost if the transaction is rolled back.


31. How would you reference column values BEFORE and AFTER you have inserted and deleted triggers?Using the keyword “new.column name”, the triggers can reference column values by new collection. By using the keyword “old.column name”, they can reference column vaues by old collection.


32. What are the uses of SYSDATE and USER keywords?SYSDATE refers to the current server system date. It is a pseudo column. USER is also a pseudo column but refers to current user logged onto the session. They are used to monitor changes happening in the table.


33. How does ROWID help in running a query faster?ROWID is the logical address of a row, it is not a physical column. It composes of data block number, file number and row number in the data block. Thus, I/O time gets minimized retrieving the row, and results in a faster query.


34. What are database links used for? Database links are created in order to form communication between various databases, or different environments like test, development and production. The database links are read-only to access other information as well.


35. What does fetching a cursor do?Fetching a cursor reads Result Set row by row.


36. What does closing a cursor do?Closing a cursor clears the private SQL area as well as de-allocates memory


37. Explain the uses of Control File.It is a binary file. It records the structure of the database. It includes locations of several log files, names and timestamps. They can be stored in different locations to help in retrieval of information if one file gets corrupted.


38. Explain ConsistencyConsistency shows that data will not be reflected to other users until the data is commit, so that consistency is maintained.


39. Differ between Anonymous blocks and sub-programs.Anonymous blocks are unnamed blocks that are not stored anywhere whilst sub-programs are compiled and stored in database. They are compiled at runtime.


40. Differ between DECODE and CASE.DECODE and CASE statements are very similar, but CASE is extended version of DECODE. DECODE does not allow Decision making statements in its place.select decode(totalsal=12000,’high’,10000,’medium’) as decode_tesr from smp where smpno in (10,12,14,16);This statement returns an error.CASE is directly used in PL/SQL, but DECODE is used in PL/SQL through SQL only.


41. Explain autonomous transaction.An autonomous transaction is an independent transaction of the main or parent transaction. It is not nested if it is started by another transaction.There are several situations to use autonomous transactions like event logging and auditing.


42. Differentiate between SGA and PGA.SGA stands for System Global Area whereas PGA stands for Program or Process Global Area. PGA is only allocated 10% RAM size, but SGA is given 40% RAM size.


43. What is the location of Pre_defined_functions.They are stored in the standard package called “Functions, Procedures and Packages”


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.


45. What are the uses of MERGE?MERGE is used to combine multiple DML statements into one.Syntax : merge into tablenameusing(query)on(join condition)when not matched then[insert/update/delete] commandwhen matched then[insert/update/delete] command


46. Can 2 queries be executed simultaneously in a Distributed Database System?Yes, they can be executed simultaneously. One query is always independent of the second query in a distributed database system based on the 2 phase commit.


47. Explain Raise_application_error.It is a procedure of the package DBMS_STANDARD that allow issuing a user_defined error messages from the database trigger or stored sub-program.


48. What is out parameter used for eventhough return statement can also be used in pl/sql?Out parameters allows more than one value in the calling program. Out parameter is not recommended in functions. Procedures can be used instead of functions if multiple values are required. Thus, these procedures are used to execute Out parameters.


49. How would you convert date into Julian date format?We can use the J format string :SQL > select to_char(to_date(‘29-Mar-2013’,’dd-mon-yyyy’),’J’) as julian from dual;JULIAN


50. Explain SPOOLSpool command can print the output of sql statements in a file.spool/tmp/sql_outtxtselect smp_name, smp_id from smp where dept=’accounts’;spool off;


51. Mention what PL/SQL package consists of?A PL/SQL package consists of

PL/SQL table and record TYPE statements

Procedures and Functions

Cursors

Variables ( tables, scalars, records, etc.) and constants

Exception names and pragmas for relating an error number with an exception

Cursors


52. Mention 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.


53. Mention what are different methods to trace the PL/SQL code?Tracing code is a crucial technique to measure the code performance during the runtime. Different methods for tracing includes

DBMS_APPLICATION_INFO

DBMS_TRACE

DBMS_SESSION and DBMS_MONITOR

trcsess and tkproof utilities


54. Mention what does the hierarchical profiler does?The hierarchical profiler could profile the calls made in PL/SQL, apart from filling the gap between the loopholes and the expectations of performance tracing. The efficiencies of the hierarchical profiler includes

Distinct reporting for SQL and PL/SQL time consumption

Reports count of distinct sub-programs calls made in the PL/SQL, and the time spent with each subprogram call

Multiple interactive analytics reports in HTML format by using the command line utility

More effective than conventional profiler and other tracing utilities


55. Mention what does PLV msg allows you to do?The PLV msg enables you to

Assign individual text message to specified row in the PL/SQL table

It retrieves the message text by number

It substitutes automatically your own messages for standard Oracle error messages with restrict toggle

Batch load message numbers and text from a database table directly PLV msg PL/SQL table


56. Mention what is the PLV (PL/Vision) package offers?

Null substitution value

Set of assertion routines

Miscellaneous utilities

Set of constants used throughout PL vision

Pre-defined datatypes

Mention what is the use of PLVprs and PLVprsps?

PLVprs: It is an extension for string parsing for PL/SQL, and it is the lowest level of string parsing functionality

PLVprsps: It is the highest level package to parse PL/SQL source code into separate atomics. It relies on other parsing packages to get work done.


57. Explain how you can copy a file to file content and file to PL/SQL table in advance PL/SQL?With a single program call – “fcopy procedure”, you can copy the complete contents of one file into another file. While to copy the contents of a file directly into a PL/SQL table, you can use the program “file2pstab”.


58. Explain how exception handling is done in advance PL/SQL?For exception handling PL/SQl provides an effective plugin PLVexc. PLVexc supports four different exception handling actions.

Continue processing

Record and then continue

Halt processing

Record and then halt processing

For those exceptions that re-occurs you can use the RAISE statement.


59. Mention what problem one might face while writing log information to a data-base table in PL/SQL?While writing log information to a database table, the problem you face is that the information is only available only once the new rows are committed to the database. This might be a problem as such PLVlog is usually deployed to track errors and in many such instances the current transaction would fail or otherwise needed a rollback.


60. Mention what is the function that is used to transfer a PL/SQL table log to a database table?To transfer a PL/SQL table log a database log table function “PROCEDURE ps2db” is used.


61. When you have to use a default “rollback to” savepoint of PLVlog?The default “rollback to” savepoint of PLVlog is used when the users has turned on the rollback activity and has not provided an alternative savepoint in the call to put_line. The default savepoint is initialized to the c none constant.


62. Why PLVtab is considered as the easiest way to access the PL/SQL table?The PL/SQL table are the closest to arrays in PL/SQL, and in order to access this table you have to first declare a table type, and then you have to declare PL/SQL table itself. But by using PLVtab, you can avoid defining your own PL/SQL table type and make PL/SQL data-table access easy.


63. Mention what does PLVtab enables you to do when you show the contents of PL/SQL tables?PLVtab enables you to do following things when you show the contents of PL/SQL tables

Display or suppress a header for the table

Display or suppress the row numbers for the table values

Show a prefix before each row of the table


64. Explain how can you save or place your msg in a table?To save msg in a table, you can do it in two ways

Load individual messages with calls to the add_text procedure

Load sets of messages from a database table with the load_from_dbms procedure


65. Mention what is the use of function “module procedure” in PL/SQL?The “module procedure” enables to convert all the lines of code in a definite program unit with one procedure call. There are three arguments for modules

module_in

cor_in

Last_module_in


66. Mention what PLVcmt and PLVrb does in PL/SQL?PL/Vision offers two packages that help you manage transaction processing in PL/SQL application. It is PLVcmt and PLVrb.

PLVcmt: PLVcmt package wraps logic and complexity for dealing with commit processing

PLVrb: It provides a programmatic interface to roll-back activity in PL/SQL