Tuesday, July 15, 2014

Oracle SQL/PLSQL Interview Questions with Answers

 What are joins and Types of join?
Ans. We need retrive data from two or more tables to make our result complete. We need to perform a join.
This join returns rows when there is at least one match in both the tables.
There are three different Outer Join methods.
This join returns all the rows from the left table with the matching rows from the right table. If there are no field matching in the right table then it returns NULL values
Right outer join returns all the rows from the right table with the matching rows from the left table. If there are no field matching in the left table then it returns NULL values
Full outer join merge left outer join and right outer join.  this returns row from either table when the conditions are met and returns null value when there is no match
Corss join is  does not necessary any condition to join. The output result contains records that are multiplication of record  from both the tables.
Ans:If there r any values in one table that do not have corresponding values in the other,in an equi join that row will not be selected.Such rows can be forcefully selected by using outer join symbol(+) on either of the sides(left or right)  based on the requirement.
What are different datatypes supported by sql in oracle?
Ans: Char (size), Nchar (size), Varchar2 (size), Nvarchar2 (size) data types for character values, Number (precision, scale), Number, Number (n), Float, Float (binary precision) data types for numerical values, Date data type for date values, Long, Raw (size),  Long Raw,  Clob, Blob, Nclob, Bfile for large objects.
What is difference between long and lob datatypes?
1) The maximum size is 4GB. 2) LOBs (except NCLOB) can be attributes of an object type. 3) LOBs support random access to data. 4) Multiple LOB columns per table or LOB attributes in an object type.
1) The maximum size is 2GB.  2) LONGs cannot.    3) LONGs support only sequential access. 4) Only one LONG column was allowed in a table
How much memory is allocated for date datatype? What is default date format in oracle?
Ans: For Date data type oracle allocates 7 bytes Memory.   Default Date Format is: DD-MON-YY.
What is range for each datatype of sql?
Ans: Datatype Range Char  Varchar2  Number    Float     LONG, RAW, LONGRAW  Large Objects (LOB’s) 2000 bytes  4000 bytes  Precision
1 to 38 Scale -84 to 127  Precision 38 decimals Or 122 binary precision   2 GB  4GB
What is a constraint? What are its various levels?
Ans: Constraint: Constraints are representators of the column to enforce data entity and consistency.There r two levels
1)Column-level constraints 2)Table-level constraints.
List out all the constraints supported by oracle
Primary Key , Foreign Key or Referential Integrity, Not Null, Unique, Check.

Select 3 product which having highest  sale price
 SELECT * FROM ( SELECT * FROM product ORDER BY sales_price DESC) WHERE rownum <= 3
Delete the records from product which having null description
delete from product where product_name is null
Display detail of product which having maximum sale 
( SELECT product_id, count(product_id)as cnt FROM sales group by product_id order by cnt desc) WHERE rownum = 1 
Select customer details and produtct details of cutomer imran
Select p.product_name, c.cutomer_name, p.sale_price from product p, cutomer c, sale s
where p.product_id=s.product_id and c.cutomer_id=s.ccustomer_id and customer_name=’imran’
Difference between DELETE & TRUNCATE statement
Ans. Delete is a DML command. Truncate is a DDL command.
In Delete statement we can use where clause But we can’t use where clause in truncate statement.
Delete activates trigger. Truncate does not activate trigger.
We can rollback delete command. We can not rollback truncate command. Delete does not reset identity of table. Truncate resets identity of table.

 Difference between Primary key and Unique Key
Ans. Primary key and Unique key enforce uniqueness of the column on which they are defined. But by default, the primary key creates a clustered index on the column, where as unique key creates a non-clustered index by default. Another major difference is that primary key does not allow NULL value, but unique key allows one NULL value only.
What are  oracle number, character, date, conversion, other
Oracle Number Functions –
Round (m, [n]),
Trunc (m, [n]),
Power (m, n),
Abs (m),
Ceil (m),
Floor (m),
Mod (m, n)
Oracle Character Functions-
Chr (x)
Concert (string1, string2)
Lower (string)
Upper (string)
Substr (string, from_str, to_str)
ASCII (string)
Length (string)
Initcap (string).
Oracle Date Functions-
Months between (d1, d2)
To_char (d, format)
Last day (d)
Next_day (d, day).
Oracle Conversion Functions-
What is syntax of PL/SQL BLOCK

What are different types of oracle PL/SQL BLOCKS?
Oracle PL/SQL DECLARE BLOCK – In DECLARE BLOCK all the declarations of the variable used in the program is made. If no variables are used this block will become optional.
Oracle PL/SQL BEGIN BLOCK -  In BEGIN BLOCK all the executable statements are placed. This block is Mandatory.
Oracle EXCEPTION BLOCK – In EXCEPTION BLOCK all the exceptions are handled. this block is optional.
 what is a Oracle PL/SQL cursor? and how to create cursor syntax?
Ans: Cursor is Private SQL area in PL/SQL.
     Declare the Cursor,
     Open the Cursor,
     Fetch values from SQL into the local Variables,
     Close the Cursor.
Type of cursors are supported by oracle pl/sql?
Ans.  There are two types of cursors namely Implicit Cursor, Explicit Cursor.
What is a cursor for loop?
Ans: Cursor For Loop is shortcut process for Explicit Cursors because the Cursor is Open, Rows are fetched once for each iteration and the cursor is closed automatically when all the rows have been processed.
What are cursor attributes?
Ans:  %Found, %NotFound,   %IsOpen, %RowCount are the cursor attributes.
 Use of cursor with “for update of” clause?
Ans: This Clause stop accessing of other users on the particular columns used by the cursor until the COMMIT is issued.
How Exception is different from error?
Ans: Whenever an error occurs Exception raises. Error is a bug whereas the Exception is a warning or error condition.

PL SQL Interview Questions - New Oracle Interview question

Oracle PL / SQL Interview Question

  • What’s a PL/SQL table? Its purpose and Advantages?
    A PL/SQL table is one dimensional, indexed, unbounded sparsed collection of homogeneous
    PLSQL tables are used to move data into and out of the database and between client side applications and stored sub-programs. They have attributes such as exits, prior, first, last, delete ,next . These attributes make PLSQL tables easier to use and applications easier to maintain.
    1 PL\SQL tables give you the ability to hold multiple values in a structure in memory so that a PL\SQL block does not have to go to the database every time it needs to retrieve one of these values - it can retrieve it directly from the PL\SQL table in memory.
    2 Global temporary tables act as performance enhancers when compared to standard tables as they greatly reduce the disk IO.
    3 They also offer the ease-of-use of standard tables, since standard SQL can be used with them; no special array-processing syntax is required.
  • What is a Cursor? How many types of Cursor are there?
    A) Cursor is an identifier/name to a work area that we can interact with to access its information. A cursor points to the current row in the result set fetched. There are three types of cursors. They are
    1 Implicit cursors – created automatically by PL/SQL for all SQL Dml statements such as
    Insert Update, delete and Select
    2 Explicit cursors – Created explicitly. They create a storage area where the set of rows
    Returned by a query are placed.
    3 Dynamic Cursors – Ref Cursors( used for the runtime modification of the select querry).
    Declaring the cursor, Opening the cursor, Fetching data , Closing the cursor(Releasing the work area) are the steps involved when using explicit cursors.
  • What is the difference between Function and Procedure?
    1..Procedure is a sub program written to perform a set of actions and returns multiple valuesUsing out parameters or return no value at all.
    2..Function is a subprogram written to perform certain computations and return a single value.
  • What are the modes for passing parameters to Oracle?
    There are three modes for passing parameters to subprograms
    1.IN - An In-parameter lets you pass values to the subprogram being called. In the subprogram it acts like a constant and cannot be assigned a value.
    2. OUT – An out-parameter lets you return values to the caller of the subprogram. It acts like an initialized variable its value cannot be assigned to another variable or to itself.
    3.INOUT – An in-out parameter lets you pass initial values to the subprogram being called and returns updated values to the caller.
  • What is the difference between Truncate and Delete Statement?
    1.Truncate – Data truncated by using truncate statement is lost permanently and cannot be retrieved even by rollback. Truncate command does not use rollback segment during its execution, hence it is fast.
    2. Delete – Data deleted by using the delete statement can be retrieved back by Rollback. Delete statement does not free up the table object allocated space.
  • What are Exceptions? How many types of Exceptions are there?
    Exceptions are conditions that cause the termination of a block. There are two types of exceptions
    1.Pre-Defined – Predefined by PL/SQL and are associated with specific error codes.
    2.User-Defined – Declared by the users and are rose on deliberate request. (Breaking a condition etc.)
    Exception handlers are used to handle the exceptions that are raised. They prevent exceptions from propagating out of the block and define actions to be performed when exception is raised.
  • What is a Pragma Exception_Init? Explain its usage?
    Pragma Exception_Init is used to handle undefined exceptions. It issues a directive to the compiler asking it to associate an exception to the oracle error. There by displaying a specific error message pertaining to the error occurred. Pragma Exception_Init (exception_name, oracle_error_name).
  • What is a Raise and Raise Application Error?
    1.Raise statement is used to raise a user defined exception.
    2. A raise application error is a procedure belonging to dbms_standard package. It allows to display a user defined error message from a stored subprogram.
  • What is the difference between Package, Procedure and Functions?
    1.A package is a database objects that logically groups related PL/SQL types, objects, and Subprograms.
    2.Procedure is a sub program written to perform a set of actions and can return multiple values.
    3.Function is a subprogram written to perform certain computations and return a single value. Unlike subprograms packages cannot be called, passed parameters or nested.
  • How do you make a Function and Procedure as a Private?
    Functions and Procedures can be made private to a package by not mentioning their declaration in the package specification and by just mentioning them in the package body.
  • How do you kick a Concurrent program from PL/SQL?
  • What is an Anonymous block?
    Anonymous Block is a block of instructions in PL/SQL and SQL which is not saved under a name as an object in database schema It is also not compiled and saved in server storage, so it needs to be parsed and executed each time it is run. However, this simple form of program can use variables, can have flow of control logic, can return query results into variables and can prompt the user for input using the SQL*Plus '&' feature as any stored procedure.
  • What are the two basic parameters that we have to pass while registering PL/SQL procedure?
    Error code and Error Buffer.
  • How to display messages in Log file and Output file?
  • What is a Trigger ? How many types of Triggers are there?
    Trigger is a procedure that gets implicitly executed when an insert/update/delete statement is issued against an associated table. Triggers can only be defined on tables not on views, how ever triggers on the base table of a view are fired if an insert/update/delete statement is issued against a view.
    There are two types of triggers, Statement level trigger and Row level trigger.
    After / For each row
    Trigger is fired / Update /
    Before / For Each statement
  • Can we use Commit in a Database Trigger, if ‘No’ then why?
    No. Committing in a trigger will violate the integrity of the transaction.
  • What is Commit, Rollback and Save point?
    Commit – Makes changes to the current transaction permanent. It Erases the savepoints and releases the transaction locks.
    Savepoint –Savepoints allow to arbitrarily hold work at any point of time with option of later committing. They are used to divide transactions into smaller portions.
    Rollback – This statement is used to undo work.
  • What is the difference between DDL, DML and DCL structures?
    DDL statements are used for defining data. Ex: Create, Alter, Drop,Truncate,Rename.
    DML statements are used for manipulating data. Ex: Insert, update, truncate.
    DCL statements are used for to control the access of data. Ex; Grant, Revoke.
    TCL statements are used for data saving.Ex; Commit,Rollback,Savepoint.
  • How can u create a table in PL/SQL procedure?
    By using execute immediate statement we can create a table in PLSQL.
    Execute immediate ‘create table amit as select * from emp’;
    All DDL,DML,DCL commands can be performed by using this command.
  • How do we Tune the Queries?
    Queries can be tuned by Checking the logic (table joins), by creating Indexes on objects in the where clause, by avoiding full table scans. Finally use the trace utility to generate the trace file, use the TK-Prof utility to generate a statistical analysis about the query using which appropriate actions can be taken.
  • What is Explain Plan? How do u use Explain Plan in TOAD?
    It is a utility provided by toad that gives the statistics about the performance of the query. It gives information such as number of full table scans occurred, cost, and usage of indexes
  • What is a TK-PROF and its usage?
    Tk-Prof is a utility that reads the trace files and generates more readable data that gives the statistics about the performance of the query on a line to line basis.
  • What is Optimization? How many types of Optimization are there?
    Rule based Optimization and Cost Based Optimization.
  • What is the default optimization chosen by Oracle?
    Cost based Optimization.
  • What is the difference between the snapshot and synonym?
    7 A snapshot refers to read-only copies of a master table or tables located on a remote node. A snapshot can be queried, but not updated; only the master table can be updated. A snapshot is periodically refreshed to reflect changes made to the master table. In this sense, a snapshot is really a view with periodicity.
    8 A synonym is an alias for table, view, sequence or program unit. They are of two types private and public.
  • What is the difference between data types char and varchar?
    Char reserves the number of memory locations mentioned in the variable declarations, even though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any memory locations when the variable is declared, it stores the values only after they are assigned (it can store a maximum of 32767 bytes).
  • Items are imported from the legacy system using the item import interface using the SRS. How are items imported using the UNIX /PLSQL commands with out using SRS?
    1.From the operating system, use CONCSUB to submit a concurrent program. It's an easiest way to test a concurrent program.
    Normally, CONCSUB submits a concurrent request and returns control to the OS prompt/shell script without waiting for the request to complete. The CONCSUB WAIT parameter can be used to make CONCSUB wait until the request has completed before returning control to the OS prompt/shell script
    By using the WAIT token, the utility checks the request status every 60 seconds and returns to the operating system prompt upon completion of the request. concurrent manager does not abort, shut down, or start up until the concurrent request completes. If your concurrent program is compatible with itself, we can check it for data integrity and deadlocks by submitting it many times so that it runs concurrently with itself.
    To pass null parameters to CONCSUB, use '""' without spaces for each null parameter.
    In words: single quote double quote double quote single quote
    Following is an example of CONCSUB syntax with null parameters:
    CONCSUB oe/oe OE 'Order Entry Super User' JWALSH CONCURRENT XOE XOEPACK 4 3 '""' 3
    2. To Invoke a Concurrent Program using PL/SQL:
    i) Just insert a row in FND_CONCURRENT_REQUESTS with the apropriate parameters and commit.
    ii) Invoke the SUBMIT_REQUEST procedure in FND_REQUEST package.
    FND_REQUEST.SUBMIT_REQUEST( 'AR', 'RAXMTR', '', '', FALSE, 'Autoinvoice Master Program', sc_time, FALSE, 1, 1020, 'VRP', '01-JAN-00', chr(0)
  • How can the duplicate records be deleted from the table?
    delete from t1 a where rowid not in (select max(rowid) from t1 b where a.no=b.no)
  • What is the significance of _all tables?
    All tables are multi-org tables which are associated with the company as a whole. Multiple Organizations is enabled in Oracle
    Applications by partitioning some database tables by the Operating Unit. Other tables are shared across Operating Units (and therefore across set of books). Examples of Applications with partitioned tables are Oracle Payables, Oracle Purchasing, Oracle Receivables, Oracle Projects, Oracle Sales & Marketing etc. The name of each corresponding partitioned table is the view name appended by '_ALL'
  • What are mutating tables? And what is mutating error?
    A mutating table is a table that is currently being modified by an UPDATE, DELETE, or INSERT statement, or it is a table that might need to be updated by the effects of a declarative DELETE CASCADE referential integrity constraint.
    A mutating error occurs when a trigger which fires when updation/deletion/insertion is done on a table A performs insertion/updation/deletion on the same table A. This error results in an infinite loop which is termed as a mutating error.
  • What is difference between oracle 7 andoracle 8i?
    A) Oracle 7 is a simple RDBMS, where as Oracle 8i is ORDBMS i.e., RDBMS with Object Support.
    The main add-ons in version 8 are…
    Abstract Data types
    PL/SQL Tables
    Nested Tables
    Partitioned Tables
  • What is Data cleaning and testing.
    Data Cleaning: Transformation of data in its current state to a pre-defined, standardized format using packaged software or program modules.
    Data Testing: The agreed upon conversion deliverables should be approved by the client representatives who are responsible for the success of the conversion. In addition, three levels of conversion testing have been identified and described in the prepare conversion test plans deliverables.
    Eg: for Summary Balances in GL we set Test Criteria as Record Counts, Hash Totals, Balances, Journal Debit and Credit.

  • While registering a report and a pl/sql block we pass some parameters, for any pl/sql block we pass 2 additional parameters. Can u list them?
    It requires two IN parameters for a PL/SQL procedure that's registered as a concurrent program in Apps. They are
    1. Errcode IN VARCHAR2
    2. Errbuff IN VARCHAR2

  • what is a trace file?
    when ever an internal error is detected by a process in oracle it dumps the information about the error into a trace file.
    Alter session set sql_trace=TRUE
  • When do you use Ref Cursors?
    We base a query on a ref cursor when you want to:
    1.More easily administer SQL
    2. Avoid the use of lexical parameters in your reports
    3. Share data sources with other applications, such as Form Builder
    4. Increase control and securityv) Encapsulate logic within a subprogram

Monday, July 14, 2014

Complete Oracle Interview Questions and Answers - part 10

What are the triggers available in the reports?
Before report, Before form, After form , Between page, After report.
Why is a Where clause faster than a group filter or a format trigger?
Because, in a where clause the condition is applied during data retrievalthan after retrieving the data.
Can one selectively load only the records that one need? (for DBA)
Look at this example, (01) is the first character, (30:37) are characters 30 to 37:
INFILE 'mydata.dat' BADFILE 'mydata.bad' DISCARDFILE 'mydata.dis'
INTO TABLE my_selective_table
WHEN (01) <> 'H' and (01) <> 'T' and (30:37) = '19991217'
region CONSTANT '31',
call_b_no POSITION(12:29) CHAR
Can one skip certain columns while loading data? (for DBA)
One cannot use POSTION(x:y) with delimited data. Luckily, from Oracle 8i one can specify FILLER columns. FILLER columns are used to skip columns/fields in the load file, ignoring fields that one does not want. Look at this example: -- One cannot use POSTION(x:y) as it is stream data, there are no positional fields-the next field begins after some delimiter, not in column X. -->
( field1,
field2 FILLER,
How does one load multi-line records? (for DBA)
One can create one logical record from multiple physical records using one of the following two clauses:
. CONCATENATE: - use when SQL*Loader should combine the same number of physical records together to form one logical record.
. CONTINUEIF - use if a condition indicates that multiple records should be treated as one. Eg. by having a '#' character in column 1.
How can get SQL*Loader to COMMIT only at the end of the load file? (for DBA)
One cannot, but by setting the ROWS= parameter to a large value, committing can be reduced. Make sure you have big rollback segments ready when you use a high value for ROWS=.
Can one improve the performance of SQL*Loader? (for DBA)
A very simple but easily overlooked hint is not to have any indexes and/or constraints (primary key) on your load tables during the load process. This will significantly slow down load times even with ROWS= set to a high value.
Add the following option in the command line: DIRECT=TRUE. This will effectively bypass most of the RDBMS processing. However, there are cases when you can't use direct load. Refer to chapter 8 on Oracle server Utilities manual.
Turn off database logging by specifying the UNRECOVERABLE option. This option can only be used with direct data loads. Run multiple load jobs concurrently.
How does one use SQL*Loader to load images, sound clips and documents? (for DBA)
SQL*Loader can load data from a "primary data file", SDF (Secondary Data file - for loading nested tables and VARRAYs) or LOGFILE. The LOBFILE method provides and easy way to load documents, images and audio clips into BLOB and CLOB columns. Look at this example:
Given the following table:
CREATE TABLE image_table (
image_id NUMBER(5),
file_name VARCHAR2(30),
image_data BLOB);
Control File:
INTO TABLE image_table
image_id INTEGER(5),
file_name CHAR(30),
image_data LOBFILE (file_name) TERMINATED BY EOF
What is the difference between the conventional and direct path loader? (for DBA)
The conventional path loader essentially loads the data by using standard INSERT statements. The direct path loader (DIRECT=TRUE) bypasses much of the logic involved with that, and loads directly into the Oracle data files. More information about the restrictions of direct path loading can be obtained from the Utilities Users Guide.
What are the various types of Exceptions ?

User defined and Predefined Exceptions.
Can we define exceptions twice in same block ?
What is the difference between a procedure and a function ?
Functions return a single variable by value whereas procedures do not return any variable by value. Rather they return multiple variables by passing variables by reference through their OUT parameter.
Can you have two functions with the same name in a PL/SQL block ?
Can you have two stored functions with the same name ?
Can you call a stored function in the constraint of a table ?
What are the various types of parameter modes in a procedure ?
What is Over Loading and what are its restrictions ?
OverLoading means an object performing different functions depending upon the no. of parameters or the data type of the parameters passed to it.
Can functions be overloaded ?
Can 2 functions have same name & input parameters but differ only by return datatype ?
What are the constructs of a procedure, function or a package ?
The constructs of a procedure, function or a package are :
variables and constants
Why Create or Replace and not Drop and recreate procedures ?
So that Grants are not dropped.
Can you pass parameters in packages ? How ?
Yes. You can pass parameters to procedures or functions in a package.
What are the parts of a database trigger ?
The parts of a trigger are:
A triggering event or statement
A trigger restriction
A trigger action
What are the various types of database triggers ?
There are 12 types of triggers, they are combination of :
Insert, Delete and Update Triggers.
Before and After Triggers.
Row and Statement Triggers.

What is the advantage of a stored procedure over a database trigger ?
We have control over the firing of a stored procedure but we have no control over the firing of a trigger.
What is the maximum no. of statements that can be specified in a trigger statement ?
Can views be specified in a trigger statement ?
What are the values of :new and :old in Insert/Delete/Update Triggers ?
INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value
What are cascading triggers? What is the maximum no of cascading triggers at a time?
When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading. Max = 32.
What are mutating triggers ?
A trigger giving a SELECT on the table on which the trigger is written.
What are constraining triggers ?
A trigger giving an Insert/Update on a table having referential integrity constraint on the triggering table.
Describe Oracle database's physical and logical structure ?
Physical : Data files, Redo Log files, Control file.
Logical : Tables, Views, Tablespaces, etc.
Can you increase the size of a tablespace ? How ?
Yes, by adding datafiles to it.
What is the use of Control files ?
Contains pointers to locations of various data files, redo log files, etc.
What is the use of Data Dictionary ?
Used by Oracle to store information about various physical and logical Oracle structures e.g. Tables, Tablespaces, datafiles, etc
What are the advantages of clusters ?
Access time reduced for joins.
What are the disadvantages of clusters ?
The time for Insert increases.
Can Long/Long RAW be clustered ?
Can null keys be entered in cluster index, normal index ?
Can Check constraint be used for self referential integrity ? How ?
Yes. In the CHECK condition for a column of a table, we can reference some other column of the same table and thus enforce self referential integrity.
What are the min. extents allocated to a rollback extent ?
What are the states of a rollback segment ? What is the difference between partly available and needs recovery ?
The various states of a rollback segment are :
What is the difference between unique key and primary key ?
Unique key can be null; Primary key cannot be null.
An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ?
an you define multiple savepoints ?
Can you Rollback to any savepoint ?
What is the maximum no. of columns a table can have ?
What is the significance of the & and && operators in PL SQL ?
The & operator means that the PL SQL block requires user input for a variable. The && operator means that the value of this variable should be the same as inputted by the user previously for this same variable. If a transaction is very large, and the rollback segment is not able to hold the rollback information, then will the transaction span across different rollback segments or will it terminate ? It will terminate (Please check ).
Can you pass a parameter to a cursor ?
Explicit cursors can take parameters, as the example below shows. A cursor parameter can appear in a query wherever a constant can appear. CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal > median;
What are the various types of RollBack Segments ?
Public Available to all instances
Private Available to specific instance
Can you use %RowCount as a parameter to a cursor ?
Is the query below allowed :
Select sal, ename Into x From emp Where ename = 'KING'
(Where x is a record of Number(4) and Char(15))

Is the assignment given below allowed :
ABC = PQR (Where ABC and PQR are records)

Is this for loop allowed :
For x in &Start..&End Loop

How many rows will the following SQL return :
Select * from emp Where rownum < 10;

9 rows
How many rows will the following SQL return :
Select * from emp Where rownum = 10;

No rows
Which symbol preceeds the path to the table in the remote database ?
Are views automatically updated when base tables are updated ?
Can a trigger written for a view ?
If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last record or first record ?
Last Record
A table has the following data : [[5, Null, 10]]. What will the average function return ?
Is Sysdate a system variable or a system function?
System Function
Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we get the next number 2. Suppose at this point we issue an rollback and again issue a nextval. What will the output be ?
Definition of relational DataBase by Dr. Codd (IBM)?
A Relational Database is a database where all data visible to the user is organized strictly as tables of data values and where all database operations work on these tables.
What is Multi Threaded Server (MTA) ?
In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates a separate process for each database user. But in MTA the database manager can assign multiple users (multiple user processes) to a single dispatcher (server process), a controlling process that queues request for work thus reducing the databases memory requirement and resources.
Which are initial RDBMS, Hierarchical & N/w database ?
RDBMS - R system
Hierarchical - IMS
What is Functional Dependency
Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each X-value has associated with it precisely one -Y value in R

What is Auditing ?
The database has the ability to audit all actions that take place within it.
a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL
While designing in client/server what are the 2 imp. things to be considered ?
Network Overhead (traffic), Speed and Load of client server
When to create indexes ?
To be created when table is queried for less than 2% or 4% to 25% of the table rows.
How can you avoid indexes ?
TO make index access path unavailable - Use FULL hint to optimizer for full table scan - Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another. - Use an expression in the Where Clause of the SQL.
What is the result of the following SQL :
Select 1 from dual
Select 'A' from dual;

Can database trigger written on synonym of a table and if it can be then what would be the effect if original table is accessed.
Yes, database trigger would fire.
Can you alter synonym of view or view ?
Can you create index on view ?
What is the difference between a view and a synonym ?
Synonym is just a second name of table used for multiple link of database. View can be created with many tables, and with virtual columns and with conditions. But synonym can be on view.
What is the difference between alias and synonym ?
Alias is temporary and used with one query. Synonym is permanent and not used as alias.
What is the effect of synonym and table name used in same Select statement ?
What's the length of SQL integer ?
32 bit length
What is the difference between foreign key and reference key ?
Foreign key is the key i.e. attribute which refers to another table primary key. Reference key is the primary key of table referred by another table.
Can dual table be deleted, dropped or altered or updated or inserted ?
If content of dual is updated to some value computation takes place or not ?
If any other table same as dual is created would it act similar to dual?
For which relational operators in where clause, index is not used ?
<> , like '% ...' is NOT functions, field +constant, field || ''
Assume that there are multiple databases running on one machine. How can you switch from one to another ?
Changing the ORACLE_SID
What are the advantages of Oracle ?
Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100 hardware platforms and 20 networking protocols.
Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than most of its competitors earn in total revenue. This market clout means that you are unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces available.
Backup and Recovery : Oracle provides industrial strength support for on-line backup and recovery and good software fault tolerence to disk failure. You can also do point-in-time recovery.
Performance : Speed of a 'tuned' Oracle Database and application is quite good, even with large databases. Oracle can manage > 100GB databases.
Multiple database support : Oracle has a superior ability to manage multiple databases within the same transaction using a two-phase commit protocol.
What is a forward declaration ? What is its use ?
PL/SQL requires that you declare an identifier before using it. Therefore, you must declare a subprogram before calling it. This declaration at the start of a subprogram is called forward declaration. A forward declaration consists of a subprogram specification terminated by a semicolon.
What are actual and formal parameters ?
Actual Parameters : Subprograms pass information using parameters. The variables or expressions referenced in the parameter list of a subprogram call are actual parameters. For example, the following procedure call lists two actual parameters named emp_num and amount:
Eg. raise_salary(emp_num, amount);
Formal Parameters : The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters. For example, the following procedure declares two formal parameters named emp_id and increase: Eg. PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL;
What are the types of Notation ?
Position, Named, Mixed and Restrictions.
What all important parameters of the init.ora are supposed to be increased if you want to increase the SGA size ?
In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 & 3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database creation}.
The initial SGA was around 4MB when the server RAM was 32MB and The new SGA was around 13MB when the server RAM was increased to 128MB.
If I have an execute privilege on a procedure in another users schema, can I execute his procedure even though I do not have privileges on the tables within the procedure ?
What are various types of joins ?
Equijoins, Non-equijoins, self join, outer join
What is a package cursor ?
A package cursor is a cursor which you declare in the package specification without an SQL statement. The SQL statement for the cursor is attached dynamically at runtime from calling procedures.
If you insert a row in a table, then create another table and then say Rollback. In this case will the row be inserted ?
Yes. Because Create table is a DDL which commits automatically as soon as it is executed. The DDL commits the transaction even if the create statement fails internally (eg table already exists error) and not syntactically.
What are the various types of queries ??
Normal Queries
Sub Queries
Co-related queries
Nested queries
Compound queries
What is a transaction ?
A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.
What is implicit cursor and how is it used by Oracle ?
An implicit cursor is a cursor which is internally created by Oracle. It is created by Oracle for each individual SQL.
Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ?
Public synonyms
What is PL/SQL?
PL/SQL is Oracle's Procedural Language extension to SQL. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools.
Is there a PL/SQL Engine in SQL*Plus?
No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your PL/SQL are send directly to the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and send to the database individually.
Is there a limit on the size of a PL/SQL block?
Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K. You can run the following select statement to query the size of an existing package or procedure.
SQL> select * from dba_object_size where name = 'procedure_name'
Can one read/write files from PL/SQL?
Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
How can I protect my PL/SQL source code?
PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand and know how to execute such scripts. Just be careful, there is no "decode" command available.
The syntax is:
wrap iname=myscript.sql oname=xxxx.yyy
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ?
From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements.
cur integer;
rc integer;
rc := DBMS_SQL.EXECUTE(cur);

Complete Oracle Interview Questions and Answers - Part 9

What is the function of Optimizer ?
The goal of the optimizer is to choose the most efficient way to execute a SQL statement.
What is Execution Plan ?
The combinations of the steps the optimizer chooses to execute a statement is called an execution plan.
Can one resize tablespaces and data files? (for DBA)
One can manually increase or decrease the size of a datafile from Oracle 7.2 using the command.
Because you can change the sizes of datafiles, you can add more space to your database without adding more datafiles. This is beneficial if you are concerned about reaching the maximum number of datafiles allowed in your database.
Manually reducing the sizes of datafiles allows you to reclaim unused space in the database. This is useful for correcting errors in estimations of space requirements.
Also, datafiles can be allowed to automatically extend if more space is required. Look at the following command:
DATAFILE 'c:\ora_apps\pcs\pcsdata1.dbf' SIZE 3M
NEXT 10240
What is SAVE POINT ?
For long transactions that contain many SQL statements, intermediate markers or savepoints can be declared which can be used to divide a transaction into smaller parts. This allows the option of later rolling back all work performed from the current point in the transaction to a declared savepoint within the transaction.
What are the values that can be specified for OPTIMIZER MODE Parameter ?
Can one rename a tablespace? (for DBA)
No, this is listed as Enhancement Request 148742. Workaround:
Export all of the objects from the tablespace
Drop the tablespace including contents
Recreate the tablespace
Import the objects
What is RULE-based approach to optimization ?
Choosing an executing planbased on the access paths available and the ranks of these access paths.
What are the values that can be specified for OPTIMIZER_GOAL parameter of the ALTER SESSION Command ?
How does one create a standby database? (for DBA)
While your production database is running, take an (image copy) backup and restore it on duplicate hardware. Note that an export will not work!!!
On your standby database, issue the following commands:
On systems prior to Oracle 8i, write a job to copy archived redo log files from the primary database to the standby system, and apply the redo log files to the standby database (pipe it). Remember the database is recovering and will prompt you for the next log file to apply.
Oracle 8i onwards provide an "Automated Standby Database" feature, which will send archived, log files to the remote site via NET8, and apply then to the standby database.
When one needs to activate the standby database, stop the recovery process and activate it:
How does one give developers access to trace files (required as input to tkprof)? (for DBA)
The "alter session set sql_trace=true" command generates trace files in USER_DUMP_DEST that can be used by developers as input to tkprof. On Unix the default file mask for these files are "rwx r-- ---".
There is an undocumented INIT.ORA parameter that will allow everyone to read (rwx r-r--) these trace files:
_trace_files_public = true
Include this in your INIT.ORA file and bounce your database for it to take effect.
What are the responsibilities of a Database Administrator ?
Installing and upgrading the Oracle Server and application tools. Allocating system storage and planning future storage requirements for the database system. Managing primary database structures (tablespaces) Managing primary objects (table,views,indexes) Enrolling users and maintaining system security. Ensuring compliance with Oralce license agreement Controlling and monitoring user access to the database. Monitoring and optimizing the performance of the database. Planning for backup and recovery of database information. Maintain archived data on tape Backing up and restoring the database. Contacting Oracle Corporation for technical support.
What is a trace file and how is it created ?
Each server and background process can write an associated trace file. When an internal error is detected by a process or user process, it dumps information about the error to its trace. This can be used for tuning the database.
What are the roles and user accounts created automatically with the database?
DBA - role Contains all database system privileges.
SYS user account - The DBA role will be assigned to this account. All of the base tables and views for the database's dictionary are store in this schema and are manipulated only by ORACLE. SYSTEM user account - It has all the system privileges for the database and additional tables and views that display administrative information and internal tables and views used by oracle tools are created using this username.
What are the minimum parameters should exist in the parameter file (init.ora) ?
DB NAME - Must set to a text string of no more than 8 characters and it will be stored inside the datafiles, redo log files and control files and control file while database creation.
DB_DOMAIN - It is string that specifies the network domain where the database is created. The global database name is identified by setting these parameters
(DB_NAME & DB_DOMAIN) CONTORL FILES - List of control filenames of the database. If name is not mentioned then default name will be used.
DB_BLOCK_BUFFERS - To determine the no of buffers in the buffer cache in SGA.
PROCESSES - To determine number of operating system processes that can be connected to ORACLE concurrently. The value should be 5 (background process) and additional 1 for each user.
ROLLBACK_SEGMENTS - List of rollback segments an ORACLE instance acquires at database startup. Also optionally LICENSE_MAX_SESSIONS,LICENSE_SESSION_WARNING and LICENSE_MAX_USERS.
Why and when should I backup my database? (for DBA)
Backup and recovery is one of the most important aspects of a DBAs job. If you lose your company's data, you could very well lose your job. Hardware and software can always be replaced, but your data may be irreplaceable!
Normally one would schedule a hierarchy of daily, weekly and monthly backups, however consult with your users before deciding on a backup schedule. Backup frequency normally depends on the following factors:
. Rate of data change/ transaction rate
. Database availability/ Can you shutdown for cold backups?
. Criticality of the data/ Value of the data to the company
. Read-only tablespace needs backing up just once right after you make it read-only
. If you are running in archivelog mode you can backup parts of a database over an extended cycle of days
. If archive logging is enabled one needs to backup archived log files timeously to prevent database freezes
. Etc.
Carefully plan backup retention periods. Ensure enough backup media (tapes) are available and that old backups are expired in-time to make media available for new backups. Off-site vaulting is also highly recommended.
Frequently test your ability to recover and document all possible scenarios. Remember, it's the little things that will get you. Most failed recoveries are a result of organizational errors and miscommunications.
What strategies are available for backing-up an Oracle database? (for DBA)
The following methods are valid for backing-up an Oracle database:
Export/Import - Exports are "logical" database backups in that they extract logical definitions and data from the database to a file.
Cold or Off-line Backups - Shut the database down and backup up ALL data, log, and control files.
Hot or On-line Backups - If the databases are available and in ARCHIVELOG mode, set the tablespaces into backup mode and backup their files. Also remember to backup the control files and archived redo log files.
RMAN Backups - While the database is off-line or on-line, use the "rman" utility to backup the database.
It is advisable to use more than one of these methods to backup your database. For example, if you choose to do on-line database backups, also cover yourself by doing database exports. Also test ALL backup and recovery scenarios carefully. It is better to be save than sorry.
Regardless of your strategy, also remember to backup all required software libraries, parameter files, password files, etc. If your database is in ARCGIVELOG mode, you also need to backup archived log files.
What is the difference between online and offline backups? (for DBA)
A hot backup is a backup performed while the database is online and available for read/write. Except for Oracle exports, one can only do on-line backups when running in ARCHIVELOG mode.
A cold backup is a backup performed while the database is off-line and unavailable to its users.
What is the difference between restoring and recovering? (for DBA)
Restoring involves copying backup files from secondary storage (backup media) to disk. This can be done to replace damaged files or to copy/move a database to a new location.
Recovery is the process of applying redo logs to the database to roll it forward. One can roll-forward until a specific point-in-time (before the disaster occurred), or roll-forward until the last transaction recorded in the log files. Sql> connect SYS as SYSDBA
How does one backup a database using the export utility? (for DBA)
Oracle exports are "logical" database backups (not physical) as they extract data and logical definitions from the database into a file. Other backup strategies normally back-up the physical data files.
One of the advantages of exports is that one can selectively re-import tables, however one cannot roll-forward from an restored export file. To completely restore a database from an export file one practically needs to recreate the entire database.
Always do full system level exports (FULL=YES). Full exports include more information about the database in the export file than user level exports.
What are the built_ins used the display the LOV?
How do you call other Oracle Products from Oracle Forms?
Run_product is a built-in, Used to invoke one of the supported oracle tools products and specifies the name of the document or module to be run. If the called product is unavailable at the time of the call, Oracle Forms returns a message to the operator.
What is the main diff. bet. Reports 2.0 & Reports 2.5?
Report 2.5 is object oriented.
What are the Built-ins to display the user-named editor?
A user named editor can be displayed programmatically with the built in procedure SHOW-EDITOR, EDIT_TETITEM independent of any particular text item.
How many number of columns a record group can have?
A record group can have an unlimited number of columns of type CHAR, LONG, NUMBER, or DATE provided that the total number of column does not exceed 64K.
What is a Query Record Group?
A query record group is a record group that has an associated SELECT statement. The columns in a query record group derive their default names, data types, had lengths from the database columns referenced in the SELECT statement. The records in query record group are the rows retrieved by the query associated with that record group.
What does the term panel refer to with regard to pages?
A panel is the no. of physical pages needed to print one logical page.
What is a master detail relationship?
A master detail relationship is an association between two base table blocks- a master block and a detail block. The relationship between the blocks reflects a primary key to foreign key relationship between the tables on which the blocks are based.
What is a library?
A library is a collection of subprograms including user named procedures, functions and packages.
What is an anchoring object & what is its use? What are the various sub events a mouse double click event involves?
An anchoring object is a print condition object which used to explicitly or implicitly anchor other objects to itself.
Use the add_group_column function to add a column to record group that was created at a design time?
What are the various sub events a mouse double click event involves? What are the various sub events a mouse double click event involves?
Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse down & mouse up events.

What is the use of break group? What are the various sub events a mouse double click event involves?
A break group is used to display one record for one group ones. While multiple related records in other group can be displayed.
What tuning indicators can one use? (for DBA)
The following high-level tuning indicators can be used to establish if a database is performing optimally or not:
. Buffer Cache Hit Ratio
Formula: Hit Ratio = (Logical Reads - Physical Reads) / Logical Reads
Action: Increase DB_CACHE_SIZE (DB_BLOCK_BUFFERS prior to 9i) to increase hit ratio
. Library Cache Hit Ratio
Action: Increase the SHARED_POOL_SIZE to increase hit ratio
What tools/utilities does Oracle provide to assist with performance tuning? (for DBA)
Oracle provide the following tools/ utilities to assist with performance monitoring and tuning:
. TKProf
. UTLBSTAT.SQL and UTLESTAT.SQL - Begin and end stats monitoring
. Statspack
. Oracle Enterprise Manager - Tuning Pack
What is STATSPACK and how does one use it? (for DBA)
Statspack is a set of performance monitoring and reporting utilities provided by Oracle from Oracle8i and above. Statspack provides improved BSTAT/ESTAT functionality, though the old BSTAT/ESTAT scripts are still available. For more information about STATSPACK, read the documentation in file $ORACLE_HOME/rdbms/admin/spdoc.txt.
Install Statspack:
cd $ORACLE_HOME/rdbms/admin
sqlplus "/ as sysdba" @spdrop.sql -- Install Statspack -
sqlplus "/ as sysdba" @spcreate.sql-- Enter tablespace names when prompted
Use Statspack:
sqlplus perfstat/perfstat
exec statspack.snap; -- Take a performance snapshots
exec statspack.snap;
o Get a list of snapshots
@spreport.sql -- Enter two snapshot id's for difference report
Other Statspack Scripts:
. sppurge.sql - Purge a range of Snapshot Id's between the specified begin and end Snap Id's
. spauto.sql - Schedule a dbms_job to automate the collection of STATPACK statistics
. spcreate.sql - Installs the STATSPACK user, tables and package on a database (Run as SYS).
. spdrop.sql - Deinstall STATSPACK from database (Run as SYS)
. sppurge.sql - Delete a range of Snapshot Id's from the database
. spreport.sql - Report on differences between values recorded in two snapshots
. sptrunc.sql - Truncates all data in Statspack tables
What are the common RMAN errors (with solutions)? (for DBA)
Some of the common RMAN errors are:
RMAN-20242: Specification does not match any archivelog in the recovery catalog.
Add to RMAN script: sql 'alter system archive log current';
RMAN-06089: archived log xyz not found or out of sync with catalog
Execute from RMAN: change archivelog all validate;
How can you execute the user defined triggers in forms 3.0 ?
Execute Trigger (trigger-name)
What ERASE package procedure does ?
Erase removes an indicated global variable.
What is the difference between NAME_IN and COPY ?
Copy is package procedure and writes values into a field.
Name in is a package function and returns the contents of the variable to which you apply.
What package procedure is used for calling another form ?
Call (E.g. Call(formname)
When the form is running in DEBUG mode, If you want to examine the values of global variables and other form variables, What package procedure command you would use in your trigger text ?
The value recorded in system.last_record variable is of type
a. Number
b. Boolean
c. Character. ?

b. Boolean.
What is mean by Program Global Area (PGA) ?
It is area in memory that is used by a Single Oracle User Process.
What is hit ratio ?
It is a measure of well the data cache buffer is handling requests for data. Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.
How do u implement the If statement in the Select Statement
We can implement the if statement in the select statement by using the Decode statement. e.g. select DECODE (EMP_CAT,'1','First','2','Second'Null); Here the Null is the else statement where null is done .
How many types of Exceptions are there
There are 2 types of exceptions. They are
a) System Exceptions
e.g. When no_data_found, When too_many_rows
b) User Defined Exceptions
e.g. My_exception exception
When My_exception then
What are the inline and the precompiler directives
The inline and precompiler directives detect the values directly
How do you use the same lov for 2 columns
We can use the same lov for 2 columns by passing the return values in global values and using the global values in the code
How many minimum groups are required for a matrix report
The minimum number of groups in matrix report are 4
What is the difference between static and dynamic lov
The static lov contains the predetermined values while the dynamic lov contains values that come at run time
How does one manage Oracle database users? (for DBA)
Oracle user accounts can be locked, unlocked, forced to choose new passwords, etc. For example, all accounts except SYS and SYSTEM will be locked after creating an Oracle9iDB database using the DB Configuration Assistant (dbca). DBA's must unlock these accounts to make them available to users.
Look at these examples:
ALTER USER scott ACCOUNT LOCK -- lock a user account
ALTER USER scott ACCOUNT UNLOCK; -- unlocks a locked users account
ALTER USER scott PASSWORD EXPIRE; -- Force user to choose a new password
What is the difference between DBFile Sequential and Scattered Reads?(for DBA)
Both "db file sequential read" and "db file scattered read" events signify time waited for I/O read requests to complete. Time is reported in 100's of a second for Oracle 8i releases and below, and 1000's of a second for Oracle 9i and above. Most people confuse these events with each other as they think of how data is read from disk. Instead they should think of how data is read into the SGA buffer cache.
db file sequential read:
A sequential read operation reads data into contiguous memory (usually a single-block read with p3=1, but can be multiple blocks). Single block I/Os are usually the result of using indexes. This event is also used for rebuilding the control file and reading data file headers (P2=1). In general, this event is indicative of disk contention on index reads.
db file scattered read:
Similar to db file sequential reads, except that the session is reading multiple data blocks and scatters them into different discontinuous buffers in the SGA. This statistic is NORMALLY indicating disk contention on full table scans. Rarely, data from full table scans could be fitted into a contiguous buffer area, these waits would then show up as sequential reads instead of scattered reads.
The following query shows average wait time for sequential versus scattered reads:
select a.average_wait "SEQ READ", b.average_wait "SCAT READ"
from sys.v_$system_event a, sys.v_$system_event b
where a.event = 'db file sequential read'
and b.event = 'db file scattered read';
What is the use of PARFILE option in EXP command ?
Name of the parameter file to be passed for export.
What is the use of TABLES option in EXP command ?
List of tables should be exported.ze)
What is the OPTIMAL parameter?
It is used to set the optimal length of a rollback segment.
How does one use ORADEBUG from Server Manager/ SQL*Plus? (for DBA)
Execute the "ORADEBUG HELP" command from svrmgrl or sqlplus to obtain a list of valid ORADEBUG commands. Look at these examples:
SQLPLUS> REM Trace SQL statements with bind variables
SQLPLUS> oradebug setospid 10121
Oracle pid: 91, Unix process pid: 10121, image: oracleorcl
SQLPLUS> oradebug EVENT 10046 trace name context forever, level 12
Statement processed.
SQLPLUS> ! vi /app/oracle/admin/orcl/bdump/ora_10121.trc
SQLPLUS> REM Trace Process Statistics
SQLPLUS> oradebug setorapid 2
Unix process pid: 1436, image: ora_pmon_orcl
SQLPLUS> oradebug procstat
Statement processed.
SQLPLUS> REM List semaphores and shared memory segments in use
SQLPLUS> oradebug ipc
SQLPLUS> REM Dump Error Stack
SQLPLUS> oradebug setospid <pid>
SQLPLUS> oradebug event immediate trace name errorstack level 3
SQLPLUS> REM Dump Parallel Server DLM locks
SQLPLUS> oradebug lkdebug -a convlock
SQLPLUS> oradebug lkdebug -a convres
SQLPLUS> oradebug lkdebug -r <resource handle> (i.e 0x8066d338 from convres dump)
Are there any undocumented commands in Oracle? (for DBA)
Sure there are, but it is hard to find them. Look at these examples:
From Server Manager (Oracle7.3 and above): ORADEBUG HELP
It looks like one can change memory locations with the ORADEBUG POKE command. Anyone brave enough to test this one for us? Previously this functionality was available with ORADBX (ls -l $ORACLE_HOME/rdbms/lib/oradbx.o; make -f oracle.mk oradbx) SQL*Plus: ALTER SESSION SET CURRENT_SCHEMA = SYS

If the maximum record retrieved property of the query is set to 10 then a summary value will be calculated?
Only for 10 records.
What are the different objects that you cannot copy or reference in object groups?
Objects of different modules
Another object groups
Individual block dependent items
Program units.
What is an OLE?
Object Linking & Embedding provides you with the capability to integrate objects from many Ms-Windows applications into a single compound document creating integrated applications enables you to use the features form .
Can a repeating frame be created without a data group as a base?
Is it possible to set a filter condition in a cross product group in matrix reports?
What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures. e.g. DBMS_OUTPUT put_line
What are the return values of functions SQLCODE and SQLERRM ? What is Pragma EXECPTION_INIT ? Explain the usage ?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
What are the datatypes a available in PL/SQL ?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite data types such as RECORD & TABLE.
What are the two parts of a procedure ?
Procedure Specification and Procedure Body.
What is the basic structure of PL/SQL ?
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL
What is PL/SQL table ?
Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key. Cursors
Recovery Manager is a tool that: manages the process of creating backups and also manages the process of restoring and recovering from them.
No extra costs …Its available free
?RMAN introduced in Oracle 8 it has become simpler with newer versions and easier than user managed backups
?Proper security
?You are 100% sure your database has been backed up.
?Its contains detail of the backups taken etc in its central repository
Facility for testing validity of backups also commands like crosscheck to check the status of backup.
Faster backups and restores compared to backups without RMAN
RMAN is the only backup tool which supports incremental backups.
Oracle 10g has got further optimized incremental backup which has resulted in improvement of performance during backup and recovery time
Parallel operations are supported
Better querying facility for knowing different details of backup
No extra redo generated when backup is taken..compared to online
backup without RMAN which results in saving of space in hard disk
RMAN an intelligent tool
Maintains repository of backup metadata
Remembers backup set location
Knows what need to backed up
Knows what is required for recovery
Knows what backups are redundant
An oracle RMAN comprises of
RMAN EXECUTABLE This could be present and fired even through client side
TARGET DATABASE This is the database which needs to be backed up .
RECOVERY CATALOG Recovery catalog is optional otherwise backup details are stored in target database controlfile .
It is a repository of information queried and updated by Recovery Manager
It is a schema or user stored in Oracle database. One schema can support many databases
It contains information about physical schema of target database datafile and archive log ,backup sets and pieces Recovery catalog is a must in following scenarios
. In order to store scripts
. For tablespace point in time recovery

Media Management Software
Media Management software is a must if you are using RMAN for storing backup in tape drive directly.

Backups in RMAN
Oracle backups in RMAN are of the following type
RMAN complete backup OR RMAN incremental backup
These backups are of RMAN proprietary nature

The advantage of uing Image copy is its not in RMAN proprietary format..

Backup Format
RMAN backup is not in oracle format but in RMAN format. Oracle backup comprises of backup sets and it consists of backup pieces. Backup sets are logical entity In oracle 9i it gets stored in a default location There are two type of backup sets Datafile backup sets, Archivelog backup sets One more important point of data file backup sets is it do not include empty blocks. A backup set would contain many backup pieces.
A single backup piece consists of physical files which are in RMAN proprietary format.

Example of taking backup using RMAN
Taking RMAN Backup
In non archive mode in dos prompt type
You get the RMAN prompt
RMAN > Connect Target
Connect to target database : Magic
using target database controlfile instead of recovery catalog

Lets take a simple backup of database in non archive mode
shutdown immediate ; - - Shutdowns the database
startup mount
backup database ;- its start backing the database
alter database open;
We can fire the same command in archive log mode
And whole of datafiles will be backed
Backup database plus archivelog;

Restoring database
Restoring database has been made very simple in 9i .
It is just
Restore database..
RMAN has become intelligent to identify which datafiles has to be restored
and the location of backuped up file.

Oracle Enhancement for RMAN in 10 G

Flash Recovery Area
Right now the price of hard disk is falling. Many dba are taking oracle database backup inside the hard disk itself since it results in lesser mean time between recoverability.
The new parameter introduced is
DB_RECOVERY_FILE_DEST = /oracle/flash_recovery_area
By configuring the RMAN RETENTION POLICY the flash recovery area will automatically delete obsolete backups and archive logs that are no longer required based on that configuration Oracle has introduced new features in incremental backup

Change Tracking File
Oracle 10g has the facility to deliver faster incrementals with the implementation of changed tracking file feature.This will results in faster backups lesser space consumption and also reduces the time needed for daily backups

Incrementally Updated Backups
Oracle database 10g Incrementally Updates Backup features merges the image copy of a datafile with RMAN incremental backup. The resulting image copy is now updated with block changes captured by incremental backups.The merging of the image copy and incremental backup is initiated with RMAN recover command. This results in faster recovery.

Binary compression technique reduces backup space usage by 50-75%.

With the new DURATION option for the RMAN BACKUP command, DBAs can weigh backup performance against system service level requirements. By specifying a duration, RMAN will automatically calculate the appropriate backup rate; in addition, DBAs can optionally specify whether backups should minimize time or system load.

New Features in Oem to identify RMAN related backup like backup pieces, backup sets and image copy

Oracle 9i New features Persistent RMAN Configuration
A new configure command has been introduced in Oracle 9i , that lets you configure various features including automatic channels, parallelism ,backup options, etc.
These automatic allocations and options can be overridden by commands in a RMAN command file.

Controlfile Auto backups
Through this new feature RMAN will automatically perform a controlfile auto backup. after every backup or copy command.

Block Media Recovery
If we can restore a few blocks rather than an entire file we only need few blocks.
We even dont need to bring the data file offline.
Syntax for it as follows
Block Recover datafile 8 block 22;

Configure Backup Optimization
Prior to 9i whenever we backed up database using RMAN our backup also used take backup of read only table spaces which had already been backed up and also the same with archive log too.
Now with 9i backup optimization parameter we can prevent repeat backup of read only tablespace and archive log. The command for this is as follows Configure backup optimization on

Archive Log failover
If RMAN cannot read a block in an archived log from a destination. RMAN automatically attempts to read from an alternate location this is called as archive log failover

There are additional commands like
backup database not backed up since time '31-jan-2002 14:00:00'
Do not backup previously backed up files
(say a previous backup failed and you want to restart from where it left off).
Similar syntax is supported for restores
backup device sbt backup set all Copy a disk backup to tape
(backing up a backup
Additionally it supports
. Backup of server parameter file
. Parallel operation supported
. Extensive reporting available
. Scripting
. Duplex backup sets
. Corrupt block detection
. Backup archive logs

Pitfalls of using RMAN
Previous to version Oracle 9i backups were not that easy which means you had to allocate a channel compulsorily to take backup You had to give a run etc . The syntax was a bit complex …RMAN has now become very simple and easy to use..
If you changed the location of backup set it is compulsory for you to register it using RMAN or while you are trying to restore backup It resulted in hanging situations
There is no method to know whether during recovery database restore is going to fail because of missing archive log file.
Compulsory Media Management only if using tape backup
Incremental backups though used to consume less space used to be slower since it used to read the entire database to find the changed blocks and also They have difficult time streaming the tape device. .
Considerable improvement has been made in 10g to optimize the algorithm to handle changed block.

Introduced in Oracle 8 it has become more powerful and simpler with newer version of Oracle 9 and 10 g.
So if you really don't want to miss something critical please start using RMAN.

INTERSECT returns all distinct rows selected by both queries.MINUS - returns all distinct rows selected by the first query but not by the second.UNION - returns all distinct rows selected by either queryUNION ALL - returns all rows selected by either query, including all duplicates.
Should the OEM Console be displayed at all times (when there are scheduled jobs)? (for DBA)
When a job is submitted the agent will confirm the status of the job. When the status shows up as scheduled, you can close down the OEM console. The processing of the job is managed by the OIA (Oracle Intelligent Agent). The OIA maintains a .jou file in the agent's subdirectory. When the console is launched communication with the Agent is established and the contents of the .jou file (binary) are reported to the console job subsystem. Note that OEM will not be able to send e-mail and paging notifications when the Console is not started.
Difference between SUBSTR and INSTR ?
INSTR (String1,String2(n,(m)),INSTR returns the position of the mth occurrence of the string 2 instring1. The search begins from nth position of string1.SUBSTR (String1 n,m)SUBSTR returns a character string of size m in string1, starting from nth position of string1.
What kind of jobs can one schedule with OEM? (for DBA)
OEM comes with pre-defined jobs like Export, Import, run OS commands, run sql scripts, SQL*Plus commands etc. It also gives you the flexibility of scheduling custom jobs written with the TCL language.
What are the pre requisites ?
I. to modify data type of a column ? ii. to add a column with NOT NULL constraint ? To Modify the datatype of a column the column must be empty. to add a column with NOT NULL constrain, the table must be empty.
How does one backout events and jobs during maintenance slots? (for DBA)
Managemnet and data collection activity can be suspended by imposing a blackout. Look at these examples:
agentctl start blackout # Blackout the entrire agent
agentctl stop blackout # Resume normal monitoring and management
agentctl start blackout ORCL # Blackout database ORCL
agentctl stop blackout ORCL # Resume normal monitoring and management
agentctl start blackout -s jobs -d 00:20 # Blackout jobs for 20 minutes
What are the types of SQL Statement ?
Data Definition Language :

Data Manipulation Language:

TABLE,EXPLAIN PLAN & SELECT.Transactional Control:

ROLESystem Control :
What is the Oracle Intelligent Agent? (for DBA)
The Oracle Intelligent Agent (OIA) is an autonomous process that needs to run on a remote node in the network to make the node OEM manageable. The Oracle Intelligent Agent is responsible for:
. Discovering targets that can be managed (Database Servers, Net8 Listeners, etc.);
. Monitoring of events registered in Enterprise Manager; and
. Executing tasks associated with jobs submitted to Enterprise Manager.
How does one start the Oracle Intelligent Agent? (for DBA)
One needs to start an OIA (Oracle Intelligent Agent) process on all machines that will to be managed via OEM.
For OEM 9i and above:
agentctl start agent
agentctl stop agent

For OEM 2.1 and below:
lsnrctl dbsnmp_start
lsnrctl dbsnmp_status

On Windows NT, start the "OracleAgent" Service.
If the agent doesn't want to start, ensure your environment variables are set correctly and delete the following files before trying again:
1) In $ORACLE_HOME/network/admin: snmp_ro.ora and snmp_rw.ora.
2) Also delete ALL files in $ORACLE_HOME/network/agent/.
Can one write scripts to send alert messages to the console?
Start the OEM console and create a new event. Select option "Enable Unsolicited Event". Select test "Unsolicited Event". When entering the parameters, enter values similar to these:
Event Name: /oracle/script/myalert
Object: *
Severity: *
Message: *
One can now write the script and invoke the oemevent command to send alerts to the console. Look at this example: oemevent /oracle/script/myalert DESTINATION alert "My custom error message" where DESTINATION is the same value as entered in the "Monitored Destinations" field when you've registered the event in the OEM Console.
Where can one get more information about TCL? (for DBA)
One can write custom event checking routines for OEM using the TCL (Tool Command Language) language. Check the following sites for more information about TCL:
. The Tcl Developer Xchange - download and learn about TCL
. OraTCL at Sourceforge - Download the OraTCL package
. Tom Poindexter's Tcl Page - Oratcl was originally written by Tom Poindexter
Are there any troubleshooting tips for OEM? (for DBA)
. Create the OEM repository with a user (which will manage the OEM) and store it in a tablespace that does not share any data with other database users. It is a bad practice to create the repository with SYS and System.
. If you are unable to launch the console or there is a communication problem with the intelligent agent (daemon). Ensure OCX files are registered. Type the following in the DOS prompt (the current directory should be $ORACLE_HOME\BIN:
C:\Orawin95\Bin> RegSvr32 mmdx32.OCX
C:\Orawin95\Bin> RegSvr32 vojt.OCX
. If you have a problem starting the Oracle Agent
Solution A: Backup the *.Q files and Delete all the *.Q Files ($Oracle_home/network/agent folder)
Backup and delete SNMP_RO.ora, SNMP_RW.ora, dbsnmp.ver and services.ora files ($Oracle_Home/network/admin folder) Start the Oracle Agent service.
Solution B: Your version of Intelligent Agent could be buggy. Check with Oracle for any available patches. For example, the Intelligent Agent that comes with Oracle 8.0.4 is buggy.
Sometimes you get a Failed status for the job that was executed successfully.
Check the log to see the results of the execution rather than relying on this status.
What is import/export and why does one need it? (for DBA)
The Oracle export (EXP) and import (IMP) utilities are used to perform logical database backup and recovery. They are also used to move Oracle data from one machine, database or schema to another.
The imp/exp utilities use an Oracle proprietary binary file format and can thus only be used between Oracle databases. One cannot export data and expect to import it into a non-Oracle database. For more information on how to load and unload data from files, read the SQL*Loader FAQ.
The export/import utilities are also commonly used to perform the following tasks:
. Backup and recovery (small databases only)
. Reorganization of data/ Eliminate database fragmentation
. Detect database corruption. Ensure that all the data can be read.
. Transporting tablespaces between databases
. Etc.
What is a display item?
Display items are similar to text items but store only fetched or assigned values. Operators cannot navigate to a display item or edit the value it contains.
How does one use the import/export utilities? (for DBA)
Look for the "imp" and "exp" executables in your $ORACLE_HOME/bin directory. One can run them interactively, using command line parameters, or using parameter files. Look at the imp/exp parameters before starting. These parameters can be listed by executing the following commands: "exp help=yes" or "imp help=yes".
The following examples demonstrate how the imp/exp utilities can be used:
exp scott/tiger file=emp.dmp log=emp.log tables=emp rows=yes indexes=no
exp scott/tiger file=emp.dmp tables=(emp,dept)
imp scott/tiger file=emp.dmp full=yes
imp scott/tiger file=emp.dmp fromuser=scott touser=scott tables=dept
exp userid=scott/tiger@orcl parfile=export.txt
... where export.txt contains:
NOTE: If you do not like command line utilities, you can import and export data with the "Schema Manager" GUI that ships with Oracle Enterprise Manager (OEM).
What are the types of visual attribute settings?
Custom Visual attributes Default visual attributes Named Visual attributes. Window
Can one export a subset of a table? (for DBA)
From Oracle8i one can use the QUERY= export parameter to selectively unload a subset of the data from a table. Look at this example:
exp scott/tiger tables=emp query=\"where deptno=10\"
What are the two ways to incorporate images into a oracle forms application?
Boilerplate Images
Can one monitor how fast a table is imported? (for DBA)
If you need to monitor how fast rows are imported from a running import job, try one of the following methods:
Method 1:
select substr(sql_text,instr(sql_text,'INTO "'),30) table_name,
round((sysdate-to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss'))*24*60,1) minutes,
trunc(rows_processed/((sysdate-to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss'))*24*60)) rows_per_min
from sys.v_$sqlarea
where sql_text like 'INSERT %INTO "%'
and command_type = 2
and open_versions > 0;
For this to work one needs to be on Oracle 7.3 or higher (7.2 might also be OK). If the import has more than one table, this statement will only show information about the current table being imported.
Contributed by Osvaldo Ancarola, Bs. As. Argentina.
Method 2:
Use the FEEDBACK=n import parameter. This command will tell IMP to display a dot for every N rows imported.
Can one import tables to a different tablespace? (for DBA)
Oracle offers no parameter to specify a different tablespace to import data into. Objects will be re-created in the tablespace they were originally exported from. One can alter this behaviour by following one of these procedures: Pre-create the table(s) in the correct tablespace:
. Import the dump file using the INDEXFILE= option
. Edit the indexfile. Remove remarks and specify the correct tablespaces.
. Run this indexfile against your database, this will create the required tables in the appropriate tablespaces
. Import the table(s) with the IGNORE=Y option.
Change the default tablespace for the user:

. Revoke the "UNLIMITED TABLESPACE" privilege from the user
. Revoke the user's quota from the tablespace from where the object was exported. This forces the import utility to create tables in the user's default tablespace.
. Make the tablespace to which you want to import the default tablespace for the user
. Import the table
What do you mean by a block in forms4.0?
Block is a single mechanism for grouping related items into a functional unit for storing, displaying and manipulating records.
How is possible to restrict the user to a list of values while entering values for parameters?
By setting the Restrict To List property to true in the parameter property sheet.
What is SQL*Loader and what is it used for? (for DBA)
SQL*Loader is a bulk loader utility used for moving data from external files into the Oracle database. Its syntax is similar to that of the DB2 Load utility, but comes with more options. SQL*Loader supports various load formats, selective loading, and multi-table loads.
How does one use the SQL*Loader utility? (for DBA)
One can load data into an Oracle database by using the sqlldr (sqlload on some platforms) utility. Invoke the utility without arguments to get a list of available parameters. Look at the following example:
sqlldr scott/tiger control=loader.ctl
This sample control file (loader.ctl) will load an external data file containing delimited data:
load data
infile 'c:\data\mydata.csv'
into table emp
fields terminated by "," optionally enclosed by '"'
( empno, empname, sal, deptno )
The mydata.csv file may look like this:
10001,"Scott Tiger", 1000, 40
10002,"Frank Naude", 500, 20
Another Sample control file with in-line data formatted as fix length records. The trick is to specify "*" as the name of the data file, and use BEGINDATA to start the data section in the control file.
load data
infile *
into table departments
( dept position (02:05) char(4),
deptname position (08:27) char(20)
How can a cross product be created?
By selecting the cross products tool and drawing a new group surrounding the base group of the cross products.
Is there a SQL*Unloader to download data to a flat file? (for DBA)
Oracle does not supply any data unload utilities. However, you can use SQL*Plus to select and format your data and then spool it to a file:
set echo off newpage 0 space 0 pagesize 0 feed off head off trimspool on
spool oradata.txt
select col1 || ',' || col2 || ',' || col3
from tab1
where col2 = 'XYZ';
spool off
Alternatively use the UTL_FILE PL/SQL package:
rem Remember to update initSID.ora, utl_file_dir='c:\oradata' parameter
fp utl_file.file_type;
fp := utl_file.fopen('c:\oradata','tab1.txt','w');
utl_file.putf(fp, '%s, %s\n', 'TextField', 55);
You might also want to investigate third party tools like SQLWays from Ispirer Systems, TOAD from Quest, or ManageIT Fast Unloader from CA to help you unload data from Oracle.
Can one load variable and fix length data records? (for DBA)
Yes, look at the following control file examples. In the first we will load delimited data (variable length):
INTO TABLE load_delimited_data
( data1,
If you need to load positional data (fixed length), look at the following control file example:
INTO TABLE load_positional_data
( data1 POSITION(1:5),
data2 POSITION(6:15)
Can one skip header records load while loading?
Use the "SKIP n" keyword, where n = number of logical rows to skip. Look at this example:
INTO TABLE load_positional_data
( data1 POSITION(1:5),
data2 POSITION(6:15)
Can one modify data as it loads into the database? (for DBA)
Data can be modified as it loads into the Oracle Database. Note that this only applies for the conventional load path and not for direct path loads.
INTO TABLE modified_data
( rec_no "my_db_sequence.nextval",
region CONSTANT '31',
time_loaded "to_char(SYSDATE, 'HH24:MI')",
data1 POSITION(1:5) ":data1/100",
data2 POSITION(6:15) "upper(:data2)",
data3 POSITION(16:22)"to_date(:data3, 'YYMMDD')"
INFILE 'mail_orders.txt'
BADFILE 'bad_orders.txt'
INTO TABLE mailing_list
( addr,
mailing_addr "decode(:mailing_addr, null, :addr, :mailing_addr)",
mailing_city "decode(:mailing_city, null, :city, :mailing_city)",
Can one load data into multiple tables at once? (for DBA)
Look at the following control file:
WHEN empno != ' '
ename POSITION(6:15) CHAR,
deptno POSITION(17:18) CHAR,
WHEN projno != ' '
What is the difference between boiler plat images and image items?
Boiler plate Images are static images (Either vector or bit map) that you import from the file system or database to use a graphical elements in your form, such as company logos and maps. Image items are special types of interface controls that store and display either vector or bitmap images. Like other items that store values, image items can be either base table items(items that relate directly to database columns) or control items. The definition of an image item is stored as part of the form module FMB and FMX files, but no image file is actually associated with an image item until the item is populate at run time.