YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 1: PlSql Technical Stuff

1.What is Autonomous Transaction..

A transaction which is independent of other transaction is called Autonomous Transaction.

Explain him with an Example ........

2.What is Pragma Autonomous_Transaction.

The pragma instructs the PL/SQL compiler to establish a PL/SQL block as autonomous or independent.

both are one and the same..

3.cursor attributes....

%found,%notfound,%rowcount,%isopen

in addition to that they will ask for %bulk_rowcount

4.what is procedure and function .diiferences between them.......

1. Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter.

2. Function can be called from SQL statements where as procedure can not be called from the sql statements

3. Functions are normally used for computations where as procedures are normally used for executing business logic.

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

5.A Function returns 1 value only. Procedure can return multiple values (max 1024).

6. Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error Function won’t support deferred name resolution.

7.Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values

Page 2: PlSql Technical Stuff

8. Stored procedure is precompiled execution plan where as functions are not.

9.A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller.

5.In how many ways that procedure parameters can be referenced...

postional anad named parameters can be passed

6.briefly about IN,OUT AND INOUT parameters

7.advantage of packages

A. Modularity

- Encapsulate related constructs.

B. Easier Application Design

- Code and compile specification and body separately.

C. Hiding Information

- Only the declarations in the pacakge specification

are visible and accessible to application.

- Private constructs in the package body are hidden

and inaccesible.

- All coding is hidden in the package body.

D. Added Functionality

Page 3: PlSql Technical Stuff

- Persistency of variables and coursors.

E. Better Performance

- The entire package is loaded into memory when the

package is first referenced.

- There is only one copy in memory for all users.

- The dependency hierarchy is simplified.

F. Overloading

- Multiple subprograms of the same name.

U can explain them each with an example....

8.why Pl/sql is Advantageous than pro*c.

Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused.

Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops).

 Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic.

Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.

9.Advantages of procedures and triggers…

.Advsntsge of Stored Procedures:================================ Stored Procedures are precompiled one. it is the group of sql statements. stored procedure like a application programming. stored procedure is a fast one because it is already precompiled. stored procedure is the one is easy to maintain.

2.Advantage of Triggers:

Page 4: PlSql Technical Stuff

======================== Triggers is a special kind of procedure. the Main advantage of the trigger is automatic. whenever the table affected by insert update or delete query that time the triggers will implicitely call. 10.Disadvantages of procedures,packages and triggers

Disadvantages of Triggers It is easy to view table relationships , constraints, indexes, stored procedure in database but triggers are difficult to view. Triggers execute invisible to client-application. They are not visible or can be traced in debugging code. It is hard to follow their logic as it they can be fired before or after the database insert/update happens. It is easy to forget about triggers and if there is no documentation it will be difficult to figure out for new developers for their existence. Triggers run every time when the database fields are updated and it is overhead on system. It makes system run slower.

Disadvantage of packages: Unnecessary module loading. Unable to load large packages into memory. Unable to compile large packages. Lack of synonym support. No version control.

11.What is Pragma EXECPTION_INIT ? Explain the usage ?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error.

e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

12. What is Global temporary table? and what are the benefits of it?

GLOBAL TEMPORARY TABLE statement defines a temporary table for the current session. The declared temporary table description does not appear in the system catalog. It is not persistent and cannot be shared with other sessions. Each session that defines a declared global temporary table of the same name has its own unique description of the temporary table. When the session terminates, the rows of the table are deleted, and the description of the temporary table is dropped.

13. what are purity rules for functions? why they use ? what effects if not follow these rules?

The purity level defines what structure the function reads or modifies.the types of purity level:

Page 5: PlSql Technical Stuff

1)wnds--write no database stage I.e the function does not modify any database or tables.2)rnds--reads no database state. i.e function does not read any database tables.3)wnps--write no package state i.efunction does not modify any packaged variables.4)rnps-read no package state i.e function does not read any package variables.

To be callable from SQL statements a stored function (and any subprograms called by that function) must obey certain purity rules which are meant to control side effects:

When called from a SELECT statement or a parallelized INSERT UPDATE or DELETE statement

the function cannot modify any database tables.

When called from an INSERT UPDATE or DELETE statement the function cannot query or modify

any database tables modified by that statement.

When called from a SELECT INSERT UPDATE or DELETE statement the function cannot execute

SQL transaction control statements (such as COMMIT) session control statements (such as SET

ROLE) or system control statements (such as ALTER SYSTEM). Also it cannot execute DDL

statements (such as CREATE) because they are followed by an automatic commit.

If any SQL statement inside the function body violates a rule you get an error at run time (when the statement is parsed).

To check for violations of the rules you can use the pragma (compiler directive) RESTRICT_REFERENCES. The pragma asserts that a function does not read or write database tables or package variables. For example the following pragma asserts that packaged function credit_ok writes no

database state (WNDS) and reads no package state (RNPS):

14. What is mutating trigger? How do you resolve it?If a trigger body is trying to update dependent tables, will it get a mutating error?

To avoid Mutating trigger there are many ways. One of the best approach is to make use of the after trigger which clearly takes care of concurrency problems associated with mutating triggers .When after trigger is used only after the process of current updating is finished the next process gets processed.

if the trigger attempts to select or modify the table while the trigger has not completed (ie. table is in transition). then mutating trigger error occurs.

because the table is in middle of a transaction so it causes the trigger to mutate.you can change the trigger to statement level and apply the logic there.

15. Types of Triggers in Oracle

there are mainily 3 types of triggers

Page 6: PlSql Technical Stuff

1> dml trigger2>instead of trigger written on only view3>system trigger

dml trigger written on table that gets fired on dml events like insert or delete or update operationthat trigger may fire 1>after dml event 2> before dml event these are timings for trigger firing

instead of trigger written only on view that view is not modifiable that also gets fired when dml event occurs

system trigger gets fired on system event like before log off or after log on or before shutdownthis trigger may be written on database level schema level

16. Difference between Varray and Nested Table

They are Oracle data types those who knoww any language like C and java then it is easy to understand the concept of Varray as it is related to ARRAY structure of C or java language.

where as Nested Table concept is related to Struct data type of C or java langauge.

17. What is the difference between REF Cursor & Normal Cursor?

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.

18.What is difference between PL/SQL tables and arrays?

PL/SQL tables are temporary array like objects used in a PL/SQL Block. The size of pl/sql table is unconstrained. For varrays we need to specify upperbound.

Pl/sql tables can not be stored in database where as varrays can be stored in database.

We can use negetive index for pl/sql tables. In varrays negetive index is not allowed.

In pl/sql tables data need not be stored in consecutive rows. Varrays are dense and retain their order while storing in database.

Page 7: PlSql Technical Stuff

You can not perform DML operations on PL/SQL table . DML operations can be performed on Varrays.

19.Difference Between SQL%BULK_ROWCOUNT and SQL%ROWCOUNT

20. what is data integrityData integrity allows to define certain data quality requirements that the data in the database needs to meet. If a user tries to insert data that doesn't meet these

requirements, Oracle will not allow

21. There is a table, In one column it has implemented a index, but the index is disturbed by the regular dml statements.. but still we need to keep the index. how it is possible?

GENERALLY INDEX WILL BE CREATED ON LESS NUMBER OF DML OPERATION COLUMNS.EVENTHOUGH IF WE WANT PERFORM BETTER THEN BEFORE INSERTING DATA INTO THE COLUMN WE HAVE TO DISABLE THE INDEX i.eALTER INDEX IDX_NAME UNUSABLE;

22. How can I create a table from another table without copying any values from the old table?create table table_name as ( select * from old_table where 1=2)

from this query we can create a new table structure from old table structure without data.

23. If a procedure within a package is invalidated whether the entire package will be invalid and has to be recompiled again?

Yes, the total package body will become invalid and has to be recompiled again

24. how do you restrict number of rows for a particular value in a column.For example:there is a table called fruits,having apples,bananas ,papayas.I dont want to have more than 100 apples in that table ,so how can u restrict number of rows for apple to hundred?Using row level and statement level trigger

25.what is sql_profiler

SQL Profiler is a graphical tool that allows system administrator to monitor events in an instance od MSSQL.u can save and capture data about each events to a file 26.What happens when pacakge is created withot a pacakage specification….The pacakage become parivate package..

Page 8: PlSql Technical Stuff

27. There is a sequence with min value 100. I want to alter this sequence to min value as 101. If the table has already data in the sequence column as 100,101,102... Is it possible to do so ?

we can only alter MINVALUE,MAXVALYE,Incremented by and CACHE of sequence.but not alter START WITH.

Alter sequence sequanceName incremented by 2 minvalue 101;

or

CREATE SEQUENCE SEQ_TET INCREMENT BY 1 START WITH 100 MAXVALUE 1000000 MINVALUE 99;

Sequence created.

SQL> rename SEQ_TET to seq_test;

Table renamed.

SQL> select * from user_sequences;

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE------------------------------ ---------- ---------- ------------ - - ----------LAST_NUMBER-----------SEQ_TEST 99 1000000 1 N N 20 100

28. i have a table eno dno sal 1 10 200 2 10 150 3 10 100 4 20 75 5 20 100 i want to get sal which is less than the avg sal of thri dept. eno dno sal 2 10 150 3 10 100 4 20 75

select e.eno,e.dno,e.salfrom emp_t e,(select dno,avg(sal) avgsal from emp_t group by dno) b where e.sal<b.avgsal and e.dno=b.dno

29.What does SELECT COUNT(1) FROM TAB would result….

select count(1) from tab will give the total number of tables,views and synonms present in the current schema.

Page 9: PlSql Technical Stuff

30. How many database objects (trigger, packages, sequence etc) uses a particular field in a given table. For ex: I want to know how many database object uses the ATTRIBUTE1 in the PO_VENDORS table. What query will give me the result showing the database object name(package, trigger etc), field_name used (in this case ATTRIBUTE1) and table_name (in this case PO_VENDORS).

select * from user_source where upper(text) like '%PO_VENDORS%'

31. How to improve the performance of a pl/sq stored procedures or functions or triggers and packages ?

By using index (not always)by using bulk fetchby using exists and not exists in place of in and not in clause.by avoiding implicit conversion by oracle ex: if in employee table emp_no is varchar thenif we query the data from employee table by where cluase like employee_number = 123 then oracle will have to implictly convert the number 123 to varhcar '123'and will require time

By avoiding sql statements & select INTO kind of statements.To improve better creating cursors to hold data.Indexing is the way to tune the database tables.so, mostly try to avoid Hard Coding in the select statements..

32.what is the sqlcodes for different exceptions….Sqlcode----exception type….0 -----no exception1-----user defined exception +100 ---no data found-ve----another orcale server error number.

33. What packages (if any) has Oracle provided for use by developers?Expected answer: Oracle provides the DBMS_ series of packages. There are manywhich developers should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION,DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they can mention a few of these and describe how they used them, even better. If they include the SQL routines provided by Oracle, great, but not really what was asked.

34.Which DBMS package is used for to retrive the web portal into the PL/SQL block..Utl_http package

Page 10: PlSql Technical Stuff

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

36.What happens if we TRUNCATE a GlobalTemporary table?

The Data Is Removed Only From That Specificsession Where The TRUNCATE Is Issued. It Wont Affect The Data In The Same Globaltemporary Table In Other Sessions

37.What is materialized view …explain with an example

1. What is a materialized view?

A materialized view is a snapshot of data which could be refreshed at defined intervals. From the

name, it is unclear that a materialized view can hold data, since views dont. Views are nothing but a query stored in a Database. Whenever we do a select * from view, it runs the saved query and fetches data. Sometimes there would be a need for a huge query with many join operations between more than 10-20 tables containing millions of records and many where conditions. Especially in a datawarehousing environment or for reporting purposes. In such conditions, running the query each time whenever required, is not a feasible option. So, there should be a technique to store the data such that we should run the query only if there is a change in data in the underlying tables.There comes the usage of a materialized views as they can store the data they have queried 2. Different type of materialized views?

a. a. Primary Key materialized viewsb. b. ROWID materialized viewsc. c. Object materialized views

-- Created based on Object types other than tablesd. d. Complex materialized views

3. How to create a Materialized view?

Eg: A Materialized view which gets refreshed automatically every day at 4 AM.

CREATE OR REPLACE MATERIALIZED VIEWTABLESPACE <tb_name>NOCACHENOLOGGINGNOPARALLELBUILD IMMEDIATE

--or < DEFFERED>REFRESH COMPLETE

Page 11: PlSql Technical Stuff

WITH ROWIDSTART WITH SYSDATENEXT UPDATE SYSDATE+4/24SELECT <COLUMNS> FROM <T1,T2,T3> WHERE

<CONDITIONS, JOINS> TABLESPACE - in which tablespace MV is to be created LOGGING/NOLOGGING - Lets you specify whether the

creation log of the MV would be written to the Redo

log file (LOGGING) or not (NOLOGGING)

CACHE/NOCACHE - For data that will be accessed

frequently, CACHE specifies those blocks

retrieved are placed in the most recently used place of LRU list in the buffer cache when full table scan is done.

DEFERRED - DEFFERED is another option

instead of the BUILD IMMEDIATE one. When this is given MV will be populated

only by next REFRESH Operation. First DEFERRED REFRESH must always be a complete refresh

IMMEDIATE - This asks the MV to populate the data as soon as it is created. REFRESH

<do> FAST - Incremental refresh method, which performs according to the changes that have

occurred in the master tables. Note: MV Log is a must for using this method to

store the changes.

<do> FORCE - This is the default if none of these options are specified. This indicates that

whenever a refresh occurs, Oracle will perform a fast refresh, if one is possible else

a complete refresh.

<do> ON COMMIT - When this option is specified,

Page 12: PlSql Technical Stuff

Oracle performs a FAST REFRESH whenever the DB commits a

transaction on the Master Table/s

<do> ON DEMAND - Refresh according to user need. Use the DBMS_MVIEW package WITH ROWID - This option is used if the underlying tables used doesnot have any primary key/s. WITH PRIMARY KEY - This option is used if the underlying tables used have primary key/s START WITH SYSDATE - This option required only if user

wants to get the MV refreshed automatically

NEXT UPDATE SYSDATE+<interval> at specified time intervals FOR UPDATE - Could be added if the MV needs to be updated.

38.What is SQL_TRACE AND TKPROOF

Start Oracle SQLTRACE: In Oracle, to start an SQLTRACE for the current session, execute:

ALTER SESSION SET SQL_TRACE = TRUE; Stop Oracle SQLTRACE In Oracle, to stop SQL tracing for the current session, execute:

ALTER SESSION SET sql_trace = false;

Oracle SQLTRACE provides generates the following statistics for each SQL statement:

Count Number of times OCI procedure was executed

CPU CPU time in seconds executing

Page 13: PlSql Technical Stuff

Elapsed Elapsed time in seconds executing

Disk Number of physical reads of buffers from disk

Query Number of buffers gotten for consistent read

Current Number of buffers gotten in current mode (usually for update)

Rows Number of rows processed by the fetch or execute call

Misses in library cache during parse Parsing user id Optimizer goal

When Oracle SQLTRACE facility is enabled, all the statistics for all SQL statements executed after that are placed into trace files. These trace files are not in readable format. Here comes the usage of TKPROF. TKPROF is used for formatting the trace files to produce a more readable format. It stores the following statistics of a Query:

Resources used by the SQL statement. No. of times that the statement was called No of records processed.

This utility is also used for monitoring and tuning applications executing against the Oracle server.

Syntax: TKPROF tracefile outputfile [explain=] [table=]

[print=] [insert=] [sys=] [sort=] Table = schema.tablename Explain = user/password to issue

EXPLAIN PLAN Print = Integer List only

the first 'integer' SQL statements. Aggregate = yes/no Insert = filename List SQL

statements and data inside INSERT statements. Sys = no TKPROF

does not list SQL statements run as user SYS. Record = filename Record

non-recursive statements found in the trace file. Waits = yes/no Record

summary for any wait events found in the trace file. Sort = option Set of zero

or more of the following sort options:

Page 14: PlSql Technical Stuff

Sort options are listed as follows: PRSCNT No. of times parsed.PRSCPU CPU parsing timePRSELA Elapsed time parsingPRSDSK Number of disk reads

during parse.PRSQRY Number of consistent mode

block reads during parse.PRSCU Number of current mode

block reads during parse.PRSMIS Number of library cache

misses during parse.EXECNT Number of executes.EXECPU CPU time spent executing.EXEELA Elapsed time spent

executing.EXEDSK Number of physical reads

from disk during execute.EXEDSK Number of physical reads

from disk during execute.EXEQRY Number of consistent mode

block reads during execute.EXECU Number of current mode

block reads during execute.EXEROW Number of rows processed

during execute.EXEMIS Number of library cache

misses during executesFCHCNT Number of fetchesFCHCPU CPU time spent fetching.FCHELA Elapsed time spent fetching.FCHDSK Number of physical reads

from disk during fetch.FCHQRY Number of consistent mode

block reads during fetch.FCHCU Number of current mode

block reads during fetch.FCHROW Number of rows fetched.

Eg: TKPROF trace_output.trc outputfile.txt insert=tkprof.sql record=record.sql Sample output:

Page 15: PlSql Technical Stuff

select * from emp where empno =9334

call count cpu elapsed disk query current rows

------- ------ -------- ---------- ---------- ---------- ---------- ---------- ----------

Parse 20 0.00 0.03 0 0 0 0

Execute 20 0.00 0.07 0 0 0 0

Fetch 40 0.54 0.75 42 13184 0 10

------- ------ -------- ---------- ---------- ---------- ---------- ---------- ----------

total 80 0.54 0.85 42 13184 0 10

Misses in library cache during parse: 2Optimizer goal: CHOOSEParsing user id: 10292

Rows Row Source Operation------- --------------------------------------------------- 1 TABLE ACCESS FULL EMPLOYEE

39.What is nocopy Parameter in pl/sql Procedures.

Explanation of NOCOPY parameter:

When you use a Collection (Records, VARRAY etc having records of data) as a Return type (OUT or IN OUT parameter) as we know, it will be passed by value only. That means the entire data will be copied to the formal parameter location, which leads to lot of CPU and memory consumption.

Here comes the usage of NOCOPY parameter. Provide NOCOPY after the OUT/IN OUT parameter, which instructs the PL/SQL Engine to avoid using the pass by value method. So, the Engine uses pass by reference instead. This helps reducing a lot of CPU usage as well as memory consumption.

Eg: Just an example how to put the NOCOPY parameter.

PROCEDURE PRC_NOCOPY_EXAMPLE

Page 16: PlSql Technical Stuff

(

P_EMPNO IN NUMBER,

P_ENAME IN VARCHAR2(50),

P_SAL OUT NOCOPY RECORD_SAL --PL/SQL Record

);

REC_SAL RECORD_SAL;

Now if you call the Procedure PRC_NOCOPY_EXAMPLE, the parameter P_SAL would only use Pass by reference method.

NOTE:

Disadvantage:

However, you need to be extremely careful while using this method in coding for high priority data transactions. When you pass parameters to a procedure by reference, any change that happens on the passed Parameters gets updated in the same memory location as the Actual parameter. So when an exception occurs in a procedure/function, these changes are not Rolled back . To be precise, the PL/SQL engine cannot rollback these parameter changes. So, if the actual values get changed, then it may result in incorrect results.

Thus, to conclude, it is up to a Developer to take a trade-off between using or not using the NOCOPY parameter. NOCOPY could provide better performance by reducing Memory and CPU cost, but at the same time, could result in incorrect results too.

40.what is index.what are are the types of indexes and briefly explain them…..

Page 17: PlSql Technical Stuff

What is an Index?

To explain in plain English, an Index could be considered as a unique bookmark to a database cell (of those columns which are indexed).

For each cell in an indexed column, there will be a unique identifer, which is known as the index. Indexes are stored in the Index segments in Oracle database (unless it is an Index Organized table (IOT) which we are not discussing here). In Oracle 9i, Indexes contain an entry for each cell value that appears in the indexed column(s) of the table or cluster.

So, when an index is used in a query, Oracle Engine first searches through the indexes and reaches the index of the particluar cell value, it is searching for. Then it goes to the table and fetches only that particular value. Thus we could avoid Full table scans. Thus an index is a performance-tuning method which allows faster retrieval of records.

Oracle supports different types of indexes:

B-Tree indexes (Normal) Bitmap indexes Partitioned indexes Function-based indexes Domain indexes

Here we are going to discuss about B-Tree and Bitmap Indexes.

I. Oracle - Binary Tree Index:

As the name suggests it makes use of the B-Tree parsing method to find the value being searched for. When it gets a value to be searched, it gets the nearest possible index value. Then it goes to the left node if the value it lesser or to the right if the value is higher. It goes on doing this until it reaches the leaf node which contains the value it is searching for.

Page 18: PlSql Technical Stuff

Fig 1.1 Binary Tree

How to Create an Index?

CREATE INDEX IDX_NAMEON TABLE_NAME (Col_nam1,Col_nam2, )COMPUTE STATISTICS ; --optional

** Note: by default, Oracle creates B-tree indexes

How to Rename an Index? ALTER INDEX IDX_NAME RENAME TO NEW_IDX_NAME;

How to Collect Statistics on an Index ALTER INDEX IDX_NAME 

COMPUTE STATISTICS;

How to Drop an IndexDROP INDEX IDX_NAME

II. Oracle - Bitmap Index:

Oracle Bitmap Indexes are different from Standard B-Tree Indexes in the way they store the information about the indexes. Bitmap Indexes stores the information about the value in bits; with 0s and 1s; thus called Bitmaps. Something like this:

Page 19: PlSql Technical Stuff

Fig 1.2 Show how Bitmap Indexes are stored.

Bitmap Index creates a two-dimensional array with one column for every row in the table being indexed. If

the value being indexed is found in the row, it will specify a 1 and if not found then a 0 . So while

searching, Oracle takes only the information from those rows which shows a 1 in the Bitmap Index. That

means, the records which are pointed by the 1 s in the Index, have got the searched/indexed value.

And from a performance point of view, during the data retrieval time, Oracle decompresses the bitmap into the RAM data buffers so that it can rapidly scan for matching values. These matching values are the given to the Oracle engine in the form of a ROWID list, and ROWIDs as we know are unique identifiers to records/rows.

Q. How to Create a Bitmap Index?

CREATE BITMAP INDEX IDX_NAMEON TABLE_NAME (Col_nam1,Col_nam2, )COMPUTE STATISTICS ;

B-Tree Versus - Bitmap Indexes

These are some differences between B-Tree and Bitmap Indexes in Structure and performance and their usage.

1. DML Operations:

Page 20: PlSql Technical Stuff

If you have too much DML operations (insert/update/delete) on a table on which the columns are indexed, it is better to use B-Tree indexes.

For eg: if you work on a batch processing environment, then it is obvious that you would have frequent DML operations on the tables involved.

Updating bitmapped indexes consumes lot of resources. So, it is better to use Bitmap Indexes on columns of Tables which are updated/inserted/deleted less frequently .

2. Performance:

Bitmap Indexes have highly compressed structure, making them fast to read and their structure makes it possible for the system to combine multiple indexes together for fast access to the underlying table/s.

3. Structure:

Compressed structure in Bitmap Indexes makes it faster to read from disk; but utilises more CPU to decompress the information.

Uncompressed structure in B-Tree involves a lesser CPU load compared to Bitmap but it requires more bandwidth to read since it is uncompressed data.

4. Cardinality:

Cardinality means, the ratio of distinct values to the total number of records. So, a low cardinality means, distinct values are very less. In such a scenario, Bitmap indexes are considered to be more efficient thatB-Tree indexes.

41. If a procedure is referring a table and if the structure of the table is changed, lets say data type of the any column is changed, then is it possible that the status of the procedure remains valid? Explain

The status becomes invalid. You will have to recompile the procedure.

42.Bulk Data OperationsYou are developing a PL/SQL block designed for bulk data operations. When attemping to store table data

for multiple rows in a PL/SQL variable, which one of the following choices identifies the mechanism best suited for this task (choose one)?

A. cursor B. varchar2 C. record D. table of records

We need multiple rows on a variable so we use here Table of records .it uses just like as collection of records.Cursor is used for selecting multiple rows from stored table.Varchar stores only single value.

Record used to store a single row thus for store multiple rows on a variable use Table of records

Page 21: PlSql Technical Stuff

43.can we use TCL Commands on a TRIGGERS..

The trigger is fired when an event occurs while manipulating the data in table. So the trigger applies a lock on it restricting others to modify it.Locks are released when a TCL command is executed. The trigger can't understand whether to release the locks applied or to continue and hence hangs.Hence TCL commands

are not entertained in the triggers.

44.what is size of dbms_output.put_line( ) package….

the maximum output is determined by the size you specified in dbms_output.enable(<size>).

45.what are the Flash back queries in oracle…

Flashback query is used to retrieve data which is errantly deleted or updated in the database. Or we can say we can see data prior to commit the data in the database.

Flashback only available in system managed undo database.

There are two method to retrieve data.1. Enable_at_time2. Enable_at_system_change_number

In built package for the same is DBMS_FLASHBACK Flash back query is used to retrive the data.For ex if a table is dropped and we want the table again so at that time.syn: FLASHBACK TABLE table_name TO BEFORE DROP.This will work only if recycled bin is not purged.

45. what are optimizer hints?

Optimizer hints are used to alter execution plan of SQL statement. For ex, certain index can be sometimes more selective for certain queries. Based on the information you can choose a more efficient execution plan by using hint and telling the optimizer to choose a more optimal path. Hints used for Optimization are : All_rowsFirst_rows

46. Why we use instead of trigger. what is the basic structure of the instead of trigger. Explain specific business reason of it's use

Page 22: PlSql Technical Stuff

Instead of triggers are used:1) To control the DML operations on Views(Insert/Update/Delete)2) Makes the non updatable views updatable

47. what is the order of execution if there is a statement level and row level trigger on a same table?

The Order will be:

Before Statement levelBefore Row levelAfter Row levelAfter Statement level

48. what happens when commit is given in executable section and an error occurs ?please tell me what happens if exception block is committed at the last?

Whenever the exception is raised ..all the transaction made before will be commited. If the exception is not raised then all the transaction will be rolled back.

49. State the advatage and disadvantage of Cursor's

Whenever we execute DML statements oracle assigns a work area called private sql area to store information. Cursors meachanism allows us to name that private sql area there by access information stored it.

The main disadvantage of cursors is that it process records sequentially. It increases number of context switches between sql and pl/sql. It hampers the performance. We may overcome this problem by using collections.

50. Can any one explain Perforance Tuning in PL/SQL

Performance tuning can be improved by using FOR ALL and BULK COLLECT clauses in place of FOR LOOP and CURSORS which makes the application faster and better.