Sie sind auf Seite 1von 151

Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.

com
1

ORACLE


COMPLETE
REFERENCE

Frequently asked Questions


Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
2
1. Autonomous transaction:-
An autonomous transaction is an independent transaction that is initiated by another
transaction. It must contain at least one Structured Query Language (SQL) statement.
Autonomous transactions allow a single transaction to be subdivided into multiple
commit/rollback transactions, each of which will be tracked for auditing purposes.
When an autonomous transaction is called, the original transaction (calling
transaction) is temporarily suspended. The autonomous transaction must commit or
roll back before it returns control to the calling transaction. Once changes have been
made by an autonomous transaction, those changes are visible to other transactions
in the database.
Autonomous transactions can be nested. That is, an autonomous transaction can
operate as a calling transaction, initializing other autonomous transactions within itself.
In theory, there is no limit to the possible number of nesting levels
2. Where we use bitmap index ?

Bitmap indexes are most appropriate for columns having low distinct values
3. What is an extent?
extent is the smallest unit of storage allocation comprising collecion of Blocks. , Well
an extent is a chunk of a space that is used by database segments when a segmant
is created it alocates extents.
4. Explain the difference between a hot backup and a cold backup and the benefits
associated with each.
A hot backup is basically taking a backup of the database while it is still up and
running and it must be in archive log mode. A cold backup is taking a backup of the
database while it is shut down and does not require being in archive log mode. The
benefit of taking a hot backup is that the database is still available for use while the
backup is occurring and you can recover the database to any point in time. The
benefit of taking a cold backup is that it is typically easier to administer the backup
and recovery process. In addition, since you are taking cold backups the database
does not require being in archive log mode and thus there will be a slight
performance gain as the database is not cutting archive logs to disk.
5. You have just had to restore from backup and do not have any control files. How
would you go about bringing up this database?
I would create a text based backup control file, stipulate where on disk all the data
files where and then issue the recover command with the using backup control file
clause.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
3
6. How do you switch from an init.ora file to a spfile?
Issue the create spfile from pfile command.
7. Explain the difference between a data block, an extent and a segment
A data block is the smallest unit of logical storage for a database object. As objects
grow they take chunks of additional storage that are composed of contiguous data
blocks. These groupings of contiguous data blocks are called extents. All the extents
that an object takes when grouped together are considered the segment of the
database object.
8. Give two examples of how you might determine the structure of the table DEPT.
Use the describe command or use the dbms_metadata.get_ddl package.
9. Where would you look for errors from the database engine?
In the alert log.
10. Compare and contrast TRUNCATE and DELETE for a table.
Both the truncate and delete command have the desired outcome of getting rid of
all the rows in a table. The difference between the two is that the truncate command
is a DDL operation and just moves the high water mark and produces a no rollback.
The delete command, on the other hand, is a DML operation, which will produce a
rollback and thus take longer to complete.
11. Give the reasoning behind using an index.
Faster access to data blocks in a table.
12. Give the two types of tables involved in producing a star schema and the type
of data they hold.
Fact tables and dimension tables. A fact table contains measurements while
dimension tables will contain data that will help describe the fact tables.
13. What type of index should you use on a fact table?
A Bitmap index.
14. Give two examples of referential integrity constraints.
A primary key and a foreign key.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
4
15. A table is classified as a parent table and you want to drop and re-create it. How
would you do this without affecting the children tables?
Disable the foreign key constraint to the parent, drop the table, re-create the table,
enable the foreign key constraint.
16. Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode
and the benefits and disadvantages to each.
ARCHIVELOG mode is a mode that you can put the database in for creating a
backup of all transactions that have occurred in the database so that you can
recover to any point in time. NOARCHIVELOG mode is basically the absence of
ARCHIVELOG mode and has the disadvantage of not being able to recover to any
point in time. NOARCHIVELOG mode does have the advantage of not having to write
transactions to an archive log and thus increases the performance of the database
slightly.
17. What command would you use to create a backup control file?
Alter database backup control file to trace.
18. Give the stages of instance startup to a usable state where normal users may
access it.
STARTUP NOMOUNT - Instance startup
STARTUP MOUNT - The database is mounted
STARTUP OPEN - The database is opened
19. What column differentiates the V$ views to the GV$ views and how?
The INST_ID column which indicates the instance in a RAC environment the
information came from.
20. How would you go about generating an EXPLAIN plan?
Create a plan table with utlxplan.sql.
Use the explain plan set statement_id ='tst1' into plan_table for a SQL statement
Look at the explain plan with utlxplp.sql or utlxpls.sql
21. How would you go about increasing the buffer cache hit ratio?
Use the buffer cache advisory over a given workload and then query the
v$db_cache_advice table. If a change was necessary then I would use the alter
system set db_cache_size command.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
5
22. Explain an ORA-01555
You get this error when you get a snapshot too old within rollback. It can usually be
solved by increasing the undo retention or increasing the size of rollbacks. You should
also look at the logic involved in the application getting the error message.
23. Explain the difference between $ORACLE_HOME and $ORACLE_BASE.
ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath
ORACLE_BASE is where the oracle products reside.
24. How would you determine the time zone under which a database was
operating?
select DBTIMEZONE from dual;
25. Explain the use of setting GLOBAL_NAMES equal to TRUE.
Setting GLOBAL_NAMES dictates how you might connect to a database. This variable
is either TRUE or FALSE and if it is set to TRUE it enforces database links to have the
same name as the remote database to which they are linking.
26. What command would you use to encrypt a PL/SQL application?
WRAP
27. Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.
A function and procedure are the same in that they are intended to be a collection
of PL/SQL code that carries a single task. While a procedure does not have to return
any values to the calling application, a function will return a single value. A package
on the other hand is a collection of functions and procedures that are grouped
together based on their commonality to a business function or application.
28. Explain the use of table functions.
Table functions are designed to return a set of rows through PL/SQL logic but are
intended to be used as a normal table or view in a SQL statement. They are also used
to pipeline information in an ETL process.
29. Name three advisory statistics you can collect.
Buffer Cache Advice, Segment Level Statistics, & Timed Statistics
30. Where in the Oracle directory tree structure are audit traces placed?
In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
6
31. Explain materialized views and how they are used.
Materialized views are objects that are reduced sets of information that have been
summarized, grouped, or aggregated from base tables. They are typically used in
data warehouse or decision support systems.
32. When a user process fails, what background process cleans up after it?
PMON
33. What background process refreshes materialized views?
The J ob Queue Processes.
34. How would you determine what sessions are connected and what resources they
are waiting for?
Use of V$SESSION and V$SESSION_WAIT
35. Describe what redo logs are.
Redo logs are logical and physical structures that are designed to hold all the
changes made to a database and are intended to aid in the recovery of a
database.
36. How would you force a log switch?
ALTER SYSTEM SWITCH LOGFILE;
37. Give two methods you could use to determine what DDL changes have been
made.
You could use Logminer or Streams
38. What does coalescing a tablespace do?
Coalescing is only valid for dictionary-managed tablespaces and de-fragments
space by combining neighboring free extents into large single extents.
39. What is the difference between a TEMPORARY tablespace and a PERMANENT
tablespace?
A temporary tablespace is used for temporary objects such as sort structures while
permanent tablespaces are used to store those objects meant to be used as the true
objects of the database.
40. Name a tablespace automatically created when you create a database.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
7
The SYSTEM tablespace.
41. When creating a user, what permissions must you grant to allow them to connect
to the database?
Grant the CONNECT to the user.
42. How do you add a data file to a tablespace?
ALTER TABLESPACE <tablespace_name>ADD DATAFILE <datafile_name>SIZE <size>
43. How do you resize a data file?
ALTER DATABASE DATAFILE <datafile_name>RESIZE <new_size>;
44. What view would you use to look at the size of a data file?
DBA_DATA_FILES
45. What view would you use to determine free space in a tablespace?
DBA_FREE_SPACE
46. How would you determine who has added a row to a table?
Turn on fine grain auditing for the table.
47. How can you rebuild an index?
ALTER INDEX <index_name>REBUILD;
48. Explain what partitioning is and what its benefit is.
Partitioning is a method of taking large tables and indexes and splitting them into
smaller, more manageable pieces.
49. You have just compiled a PL/SQL package but got errors, how would you view
the errors?
SHOW ERRORS
50. How can you gather statistics on a table?
The ANALYZE command. ANALYZE TABLE <TAB NAME>COMPUTE STATISTICS;
51. How can you enable a trace for a session?
DBMS_SESSION.SET_SQL_TRACE OR ALTER SESSION SET SQL_TRACE =TRUE;
52. What is the difference between the SQL*Loader and IMPORT utilities?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
8
These two Oracle utilities are used for loading data into the database. The difference
is that the import utility relies on the data being produced by another Oracle utility
EXPORT while the SQL*Loader utility allows data to be loaded that has been
produced by other utilities from different data sources just so long as it conforms to
ASCII formatted or delimited files.
53. Name two files used for network connection to a database.
TNSNAMES.ORA and SQLNET.ORA
54. What is the maximum buffer size that can be specified using the
DBMS_OUTPUT.ENABLE function?
10,00000 (Ten Lakhs)
55. Can you use a commit statement within a database trigger?
Yes, Only if you are using autonomous transactions in the Database triggers.
56. What is an UTL_FILE? What are different procedures and functions associated with
it?
The UTL_FILE package lets your PL/SQL programs read and write operating system (OS)
text files. It provides a restricted version of standard OS stream file input/output (I/O).
Subprogram -Description
FOPEN function-Opens a file for input or output with the default line size.
IS_OPEN function -Determines if a file handle refers to an open file.
FCLOSE procedure -Closes a file.
FCLOSE_ALL procedure -Closes all open file handles.
GET_LINE procedure -Reads a line of text from an open file.
PUT procedure-Writes a line to a file. This does not append a line terminator.
NEW_LINE procedure-Writes one or more OS-specific line terminators to a file.
PUT_LINE procedure -Writes a line to a file. This appends an OS-specific line terminator.
PUTF procedure -A PUT procedure with formatting.
FFLUSH procedure-Physically writes all pending output to a file.
FOPEN function -Opens a file with the maximum line size specified.
57. Difference between database triggers and form triggers?
Database triggers are fired whenever any database action like INSERT, UPATE, DELETE,
LOGON LOGOFF etc occurs. Form triggers on the other hand are fired in response to
any event that takes place while working with the forms, say like navigating from one
field to another or one block to another and so on.
58. What is OCI. What are its uses?
OCI is Oracle Call Interface. When applications developers demand the most
powerful interface to the Oracle Database Server, they call upon the Oracle Call
Interface (OCI). OCI provides the most comprehensive access to all of the Oracle
Database functionality. The newest performance, scalability, and security features
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
9
appear first in the OCI API. If you write applications for the Oracle Database, you likely
already depend on OCI. Some types of applications that depend upon OCI are:
PL/SQL applications executing SQL
C++applications using OCCI
J ava applications using the OCI-based J DBC driver
C applications using the ODBC driver
VB applications using the OLEDB driver
Pro*C applications
Distributed SQL
59. What are ORACLE PRECOMPILERS?
A precompiler is a tool that allows programmers to embed SQL statements in high-
level source programs like C, C++, COBOL, etc. The precompiler accepts the source
program as input, translates the embedded SQL statements into standard Oracle
runtime library calls, and generates a modified source program that one can
compile, link, and execute in the usual way. Examples are the Pro*C Precompiler for
C, Pro*Cobol for Cobol, SQLJ for J ava etc.
60. What is syntax for dropping a procedure and a function? Are these operations
possible?
Drop Procedure/Function ; yes, if they are standalone procedures or functions. If they
are a part of a package then one have to remove it from the package definition and
body and recompile the package.
61. Can a function take OUT parameters. If not why?
yes, IN, OUT or IN OUT.
62. Can the default values be assigned to actual parameters?
Yes. In such case you dont need to specify any value and the actual parameter will
take the default value provided in the function definition.
63. What is difference between a formal and an actual parameter?
The formal parameters are the names that are declared in the parameter list of the
header of a module. The actual parameters are the values or expressions placed in
the parameter list of the actual call to the module.
64. What are different modes of parameters used in functions and procedures?
There are three different modes of parameters: IN, OUT, and IN OUT.
IN - The IN parameter allows you to pass values in to the module, but will not pass
anything out of the module and back to the calling PL/SQL block. In other words, for
the purposes of the program, its IN parameters function like constants. J ust like
constants, the value of the formal IN parameter cannot be changed within the
program. You cannot assign values to the IN parameter or in any other way modify its
value.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
10
IN is the default mode for parameters. IN parameters can be given default values in
the program header.
OUT- An OUT parameter is the opposite of the IN parameter. Use the OUT parameter
to pass a value back from the program to the calling PL/SQL block. An OUT
parameter is like the return value for a function, but it appears in the parameter list
and you can, of course, have as many OUT parameters as you like.
Inside the program, an OUT parameter acts like a variable that has not been
initialised. In fact, the OUT parameter has no value at all until the program terminates
successfully (without raising an exception, that is). During the execution of the
program, any assignments to an OUT parameter are actually made to an internal
copy of the OUT parameter. When the program terminates successfully and returns
control to the calling block, the value in that local copy is then transferred to the
actual OUT parameter. That value is then available in the calling PL/SQL block.
IN OUT - With an IN OUT parameter, you can pass values into the program and return
a value back to the calling program (either the original, unchanged value or a new
value set within the program). The IN OUT parameter shares two restrictions with the
OUT parameter:
An IN OUT parameter cannot have a default value.
An IN OUT actual parameter or argument must be a variable. It cannot be a
constant, literal, or expression, since these formats do not provide a receptacle in
which PL/SQL can place the outgoing value.
65) Difference between procedure and function.
A function always returns a value, while a procedure does not. When you call a
function you must always assign its value to a variable.
66) Can cursor variables be stored in PL/SQL tables. If yes how. If not why?
Yes. Create a cursor type - REF CURSOR and declare a cursor variable of that type.
DECLARE
/* Create the cursor type. */
TYPE company_curtype IS REF CURSOR RETURN company%ROWTYPE;
/* Declare a cursor variable of that type. */
company_curvar company_curtype;
/* Declare a record with same structure as cursor variable. */
company_rec company%ROWTYPE;
BEGIN
/* Open the cursor variable, associating with it a SQL statement. */
OPEN company_curvar FOR SELECT * FROM company;
/* Fetch from the cursor variable. */
FETCH company_curvar INTO company_rec;
/* Close the cursor object associated with variable. */
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
11
CLOSE company_curvar;
END;
67. How do you pass cursor variables in PL/SQL?
Pass a cursor variable as an argument to a procedure or function. You can, in
essence, share the results of a cursor by passing the reference to that result set.
68. How do you open and close a cursor variable. Why it is required?
Using OPEN cursor_name and CLOSE cursor_name commands. The cursor must be
opened before using it in order to fetch the result set of the query it is associated with.
The cursor needs to be closed so as to release resources earlier than end of
transaction, or to free up the cursor variable to be opened again.
69. What should be the return type for a cursor variable. Can we use a scalar data
type as return type?
The return type of a cursor variable can be %ROWTYPE or record_name%TYPE or a
record type or a ref cursor type. A scalar data type like number or varchar cant be
used but a record type may evaluate to a scalar value.
70. What is use of a cursor variable? How it is defined?
Cursor variable is used to mark a work area where Oracle stores a multi-row query
output for processing. It is like a pointer in C or Pascal. Because it is a TYPE, it is defined
as TYPE REF CURSOR RETURN ;
71. What WHERE CURRENT OF clause does in a cursor?
The Where Current Of statement allows you to update or delete the record that was
last fetched by the cursor.
72. Difference between NO DATA FOUND and %NOTFOUND
NO DATA FOUND is an exception which is raised when either an implicit query returns
no data, or you attempt to reference a row in the PL/SQL table which is not yet
defined. SQL%NOTFOUND, is a BOOLEAN attribute indicating whether the recent SQL
statement does not match to any row.
73. What is a cursor for loop?
A cursor FOR loop is a loop that is associated with (actually defined by) an explicit
cursor or a SELECT statement incorporated directly within the loop boundary. Use the
cursor FOR loop whenever (and only if) you need to fetch and process each and
every record from a cursor, which is a high percentage of the time with cursors.
74. What are cursor attributes?
Cursor attributes are used to get the information about the current status of your
cursor. Both explicit and implicit cursors have four attributes, as shown:
Name Description
%FOUND Returns TRUE if record was fetched successfully, FALSE otherwise.
%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise.
%ROWCOUNT Returns number of records fetched from cursor at that point in time.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
12
%ISOPEN Returns TRUE if cursor is open, FALSE otherwise.
75. Difference between an implicit & an explicit cursor.
The implicit cursor is used by Oracle server to test and parse the SQL statements and
the explicit cursors are declared by the programmers.
76. What is a cursor?
A cursor is a mechanism by which you can assign a name to a select statement
and manipulate the information within that SQL statement.
77. What is the purpose of a cluster?
A cluster provides an optional method of storing table data. A cluster is comprised of
a group of tables that share the same data blocks, which are grouped together
because they share common columns and are often used together. For example, the
EMP and DEPT table share the DEPTNO column. When you cluster the EMP and DEPT,
Oracle physically stores all rows for each department from both the EMP and DEPT
tables in the same data blocks. You should not use clusters for tables that are
frequently accessed individually.
78. What is a pseudo column. Give some examples?
Information such as sysdate , row numbers and row descriptions are automatically
stored by Oracle and is directly accessible, ie. not through tables. This information is
contained within pseudo columns. These pseudo columns can be retrieved in queries.
These pseudo columns can be included in queries which select data from tables.
Available Pseudo Columns
ROWNUM - row number. Order number in which a row value is retrieved.
ROWID - physical row (memory or disk address) location, ie. unique row
identification.
SYSDATE - system or todays date.
UID - user identification number indicating the current user.
USER - name of currently logged in user.
79. How you will avoid your query from using indexes?
By changing the order of the columns that are used in the index, in the Where
condition, or by concatenating the columns with some constant values.
80. What is a OUTER J OIN?
An OUTER J OIN returns all rows that satisfy the join condition and also returns some or
all of those rows from one table for which no rows from the other satisfy the join
condition.
81. Which is more faster - IN or EXISTS?
Well, the two are processed very differently.
Select * from T1 where x in ( select y from T2 )
is typically processed as:
select *
from t1, ( select distinct y from t2 ) t2
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
13
where t1.x =t2.y;
The sub query is evaluated, distincted, indexed (or hashed or sorted) and then joined
to the original table typically. As opposed to
select * from t1 where exists ( select null from t2 where y =x )
That is processed more like:
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y =x.x )
then
OUTPUT THE RECORD
end if
end loop
It always results in a full scan of T1 whereas the first query can make use of an index on
T1(x). So, when is where exists appropriate and in appropriate? Lets say the result of
the sub query ( select y from T2 ) is huge and takes a long time. But the table T1 is
relatively small and executing ( select null from t2 where y =x.x ) is very fast (nice
index on t2(y)). Then the exists will be faster as the time to full scan T1 and do the index
probe into T2 could be less then the time to simply full scan T2 to build the sub query
we need to distinct on.
Lets say the result of the sub query is small then IN is typically more appropriate. If
both the sub query and the outer table are huge either might work as well as the
other depends on the indexes and other factors.
82. When do you use WHERE clause and when do you use HAVING clause?
The WHERE condition lets you restrict the rows selected to those that satisfy one or
more conditions. Use the HAVING clause to restrict the groups of returned rows to
those groups for which the specified condition is TRUE.
83. There is a % sign in one field of a column. What will be the query to find it?
SELECT column_name FROM table_name WHERE column_name LIKE %\ %% ESCAPE
\ ;
84. What is difference between SUBSTR and INSTR?
INSTR function search string for sub-string and returns an integer indicating the position
of the character in string that is the first character of this occurrence. SUBSTR function
return a portion of string, beginning at character position, substring_length characters
long. SUBSTR calculates lengths using characters as defined by the input character
set.
85. Which data type is used for storing graphics and images?
Raw, Long Raw, and BLOB.
86. What is difference between SQL and SQL*PLUS?
SQL is the query language to manipulate the data from the database. SQL*PLUS is the
tool that lets to use SQL to fetch and display the data.
87. What is difference between UNIQUE and PRIMARY KEY constraints?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
14
An UNIQUE key can have NULL whereas PRIMARY key is always not NOT NULL. Both
bears unique values.
88. What is difference between Rename and Alias?
Rename is actually changing the name of an object whereas Alias is giving another
name (additional name) to an existing object. Rename is a permanent name given
to a table or column whereas Alias is a temporary name given to a table or column
which do not exist once the SQL statement is executed.
89. What are various joins used while writing SUBQUERIES?
A) =, , IN, NOT IN, IN ANY, IN ALL, EXISTS, NOT EXISTS.
90. Display the number value in Words?
A)select sal,(to_char(to_date(sal,j'),jsp)) from emp;
J means J ulian day, the number of days since J anuary 1, 4712 BC
and sp means to spell out.
91. What is the difference between Hot Backup and Cold Backup?
Hot Backup : It is tablespace wise backup. Archive log mode.Restores all the old valid
backup & apply the archive log.
Advantage - While the DB is on the backup can be taken.
Disadvantage -
Cold Backup : Shutdown cleanly and then the backup is taken.Restores all the data
files, control files(log files, temp..)
Advantage- Safest, troublefree.
Disadvantage- not for production, can be used for Online Banking etc...
92. What is a functional index - explain?
Function-based indexes can use any Function or Object method that is declared as
repeatable.
Queries using expressions can use the index.
Ex:- CREATE INDEX sales_margin_inx ON sales(revenue - cost);
Sql>SELECT ordid FROM sales WHERE (revenue - cost) >1000;

We have to enable Function-based indexes by enableing the following initialization
parameters
ALTER SESSION SET QUERY_REWRITE_ENABLED =TRUE;
ALTER SESSION SET QUERY_REWRITE_INTEGRITY =TRUSTED;
93. Describe the difference between a procedure, function and anonymous pl/sql
block.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
15
Candidate should mention use of DECLARE statement, a function must return a value
while a procedure doesn?t have to.
94. What is a mutating table error and how can you get around it?
This happens with triggers. It occurs because the trigger is trying to update a row it is
currently using. The usual fix involves either use of views or temporary tables so the
database is selecting from one while updating the other.
95. Describe the use of %ROWTYPE and %TYPE in PL/SQL
%ROWTYPE allows you to associate a variable with an entire table row. The %TYPE
associates a variable with a single column type.
96. What packages (if any) has Oracle provided for use by developers?
Oracle provides the DBMS_ series of packages. There are many which developers
should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_J OB, 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.
97. Describe the use of PL/SQL tables
PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can
be used to hold values for use in later queries or calculations. In Oracle 8 they will be
able to be of the %ROWTYPE designation, or RECORD.
98. When is a declare statement needed ?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone,
non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is
used.
99. In what order should a open/fetch/loop set of commands in a PL/SQL block be
implemented if you use the %NOTFOUND cursor variable in the exit when statement?
Why?
OPEN then FETCH then LOOP followed by the exit when. If not specified in this order
will result in the final return being done twice because of the way the %NOTFOUND is
handled by PL/SQL.
100. What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
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.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
16
101. How can you find within a PL/SQL block, if a cursor is open?
Use the %ISOPEN cursor status variable.
102. How can you generate debugging output from PL/SQL?
Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW
ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used
to show intermediate results from loops and the status of variables as the procedure is
executed. The new package UTL_FILE can also be used.
103. What are the types of triggers?
There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE,
AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT etc.
104 . Give one method for transferring a table from one schema to another:
There are several possible methods, export-import, CREATE TABLE... AS SELECT, or
COPY.
105. What is the purpose of the IMPORT option IGNORE? What is it?s default setting?
The IMPORT IGNORE option tells import to ignore "already exists" errors. If it is not
specified the tables that already exist will be skipped. If it is specified, the error is
ignored and the tables data will be inserted. The default value is N.
106. You have a rollback segment in a version 7.2 database that has expanded
beyond optimal, how can it be restored to optimal?
Use the ALTER TABLESPACE ..... SHRINK command.
107. If the DEFAULT and TEMPORARY tablespace clauses are left out of a CREATE USER
command what happens? Is this bad or good? Why?
The user is assigned the SYSTEM tablespace as a default and temporary tablespace.
This is bad because it causes user objects and temporary segments to be placed into
the SYSTEM tablespace resulting in fragmentation and improper table placement
(only data dictionary objects and the system rollback segment should be in SYSTEM).
108. What are some of the Oracle provided packages that DBAs should be aware of?
Oracle provides a number of packages in the form of the DBMS_ packages owned by
the SYS user. The packages used by DBAs may include: DBMS_SHARED_POOL,
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
17
DBMS_UTILITY, DBMS_SQL, DBMS_DDL, DBMS_SESSION, DBMS_OUTPUT and
DBMS_SNAPSHOT. They may also try to answer with the UTL*.SQL or CAT*.SQL series of
SQL procedures. These can be viewed as extra credit but aren?t part of the answer.
109. What happens if the constraint name is left out of a constraint clause?
The Oracle system will use the default name of SYS_Cxxxx where xxxx is a system
generated number. This is bad since it makes tracking which table the constraint
belongs to or what the constraint does harder.
110. What happens if a tablespace clause is left off of a primary key constraint
clause?
This results in the index that is automatically generated being placed in then users
default tablespace. Since this will usually be the same tablespace as the table is
being created in, this can cause serious performance problems.
111. What is the proper method for disabling and re-enabling a primary key
constraint?
You use the ALTER TABLE command for both. However, for the enable clause you
must specify the USING INDEX and TABLESPACE clause for primary keys.
112. What happens if a primary key constraint is disabled and then enabled without
fully specifying the index clause?
The index is created in the user?s default tablespace and all sizing information is lost.
Oracle doesn?t store this information as a part of the constraint definition, but only as
part of the index definition, when the constraint was disabled the index was dropped
and the information is gone.
113. (On UNIX) When should more than one DB writer process be used? How many
should be used?
If the UNIX system being used is capable of asynchronous IO then only one is required,
if the system is not capable of asynchronous IO then up to twice the number of disks
used by Oracle number of DB writers should be specified by use of the db_writers
initialization parameter.
114. You are using hot backup without being in archivelog mode, can you recover in
the event of a failure? Why or why not?
You can?t use hot backup without being in archivelog mode. So no, you couldn?t
recover.
115. What causes the "snapshot too old"ORA-01555 error? How can this be
prevented or mitigated?
This is caused by large or long running transactions that have either wrapped onto
their own rollback space or have had another transaction write on part of their
rollback space. This can be prevented or mitigated by breaking the transaction into a
set of smaller transactions or increasing the size of the rollback segments and their
extents.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
18
116. How can you tell if a database object is invalid?
By checking the status column of the DBA_, ALL_ or USER_OBJ ECTS views, depending
upon whether you own or only have permission on the view or are using a DBA
account.
117. A user is getting an ORA-00942 error yet you know you have granted them
permission on the table, what else should you check?
You need to check that the user has specified the full name of the object (select
empid from scott.emp; instead of select empid from emp;) or has a synonym that
points to the object (create synonym emp for scott.emp;)
118. A developer is trying to create a view and the database won?t let him. He has
the "DEVELOPER" role which has the "CREATE VIEW" system privilege and SELECT grants
on the tables he is using, what is the problem?
You need to verify the developer has direct grants on all tables used in the view. You
can?t create a stored object with grants given through views.
119. If you have an example table, what is the best way to get sizing data for the
production table implementation?
The best way is to analyze the table and then use the data provided in the
DBA_TABLES view to get the average row length and other pertinent data for the
calculation. The quick and dirty way is to look at the number of blocks the table is
actually using and ratio the number of rows in the table to its number of blocks
against the number of expected rows.
120. How can you find out how many users are currently logged into the database?
How can you find their operating system id?
There are several ways. One is to look at the v$session or v$process views. Another
way is to check the current_logins parameter in the v$sysstat view. Another if you are
on UNIX is to do a "ps -ef| grep oracle| wc -l? command, but this only works against a
single instance installation.
121. A user selects from a sequence and gets back two values, his select is:
SELECT pk_seq.nextval FROM dual; ---- What is the problem?
Somehow two values have been inserted into the dual table. This table is a single row,
single column table that should only have one value in it.
122. How can you determine if an index needs to be dropped and rebuilt?
Run the ANALYZE INDEX command on the index to validate its structure and then
calculate the ratio of LF_BLK_LEN/LF_BLK_LEN+BR_BLK_LEN and if it isn?t near 1.0 (i.e.
greater than 0.7 or so) then the index should be rebuilt. Or if the ratio
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
19
BR_BLK_LEN/ LF_BLK_LEN+BR_BLK_LEN is nearing 0.3.
123. How can variables be passed to a SQL routine?
By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1,
&2,...,&8) to pass the values after the command into the SQLPLUS session. To be
prompted for a specific variable, place the ampersanded variable in the code itself:
"select * from dba_tables where owner=&owner_name;" . Use of double ampersands
tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a
single ampersand will cause a reprompt for the value unless an ACCEPT statement is
used to get the value from the user.
124. You want to include a carriage return/linefeed in your output from a SQL script,
how can you do this?
The best method is to use the CHR() function (CHR(10) is a return/linefeed) and the
concatenation function "| | ". Another method, although it is hard to document and
isn?t always portable is to use the return/linefeed as a part of a quoted string.
125. How can you call a PL/SQL procedure from SQL?
By use of the EXECUTE (short form EXEC) command.
126. How do you execute a host operating system command from within SQL?
By use of the exclamation point "!" (in UNIX and some other OS) or the HOST (HO)
command.
127. You want to use SQL to build SQL, what is this called and give an example
This is called dynamic SQL. An example would be:
set lines 90 pages 0 termout off feedback off verify off
spool drop_all.sql
select ?drop user ?| | username| | ? cascade;? from dba_users
where username not in ("SYS?,?SYSTEM?);
spool off
Essentially you are looking to see that they know to include a command (in this case
DROP USER...CASCADE;) and that you need to concatenate using the ?| | ? the
values selected from the database.
128. What SQLPlus command is used to format output from a select?
This is best done with the COLUMN command.
129. You want to group the following set of select returns, what can you group on?
Max(sum_of_cost), min(sum_of_cost), count(item_no), item_no
The only column that can be grouped on is the "item_no" column, the rest have
aggregate functions associated with them.
130. What special Oracle feature allows you to specify how the cost based system
treats a SQL statement?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
20
The COST based system allows the use of HINTs to control the optimizer path selection.
If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX,
STAR, even better.
131. You want to determine the location of identical rows in a table before
attempting to place a unique index on the table, how can this be done?
Oracle tables always have one guaranteed unique column, the rowid column. If you
use a min/max function against your rowid and then select against the proposed
primary key you can squeeze out the rowids of the duplicate rows pretty quick. For
example:
select rowid from emp e
where e.rowid >(select min(x.rowid) from emp x
where x.emp_no =e.emp_no);
In the situation where multiple columns make up the proposed key, they must all be
used in the where clause.
132. What is a Cartesian product?
A Cartesian product is the result of an unrestricted join of two or more tables. The
result set of a three table Cartesian product will have x * y * z number of rows where x,
y, z correspond to the number of rows in each table involved in the join.
133. You are joining a local and a remote table, the network manager complains
about the traffic involved, how can you reduce the network traffic?
Push the processing of the remote data to the remote instance by using a view to
pre-select the information for the join. This will result in only the data required for the
join being sent across.
134. What is the default ordering of an ORDER BY clause in a SELECT statement?
Ascending
135. What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL
statements. You use it by first setting timed_statistics to true in the initialization file and
then turning on tracing for either the entire database via the sql_trace parameter or
for the session using the ALTER SESSION command. Once the trace file is generated
you run the tkprof tool against the trace file and then look at the output from the
tkprof tool. This can also be used to generate explain plan output.
136. What is explain plan and how is it used?
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have
an explain_table generated in the user you are running the explain plan for. This is
created using the utlxplan.sql script. Once the explain plan table exists you run the
explain plan command giving as its argument the SQL statement to be explained. The
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
21
explain_plan table is then queried to see the execution plan of the statement. Explain
plans can also be run using tkprof.
137. How do you set the number of lines on a page of output? The width?
The SET command in SQLPLUS is used to control the number of lines generated per
page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will
generate reports that are 60 lines long with a line width of 80 characters. The PAGESIZE
and LINESIZE options can be shortened to PAGES and LINES.
138. How do you prevent output from coming to the screen?
The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off
screen output. This option can be shortened to TERM.
139. How do you prevent Oracle from giving you informational messages during and
after a SQL statement execution?
The SET options FEEDBACK and VERIFY can be set to OFF.
140. How do you generate file output from SQL?
By use of the SPOOL command
141. A tablespace has a table with 30 extents in it. Is this bad? Why or why not.
Multiple extents in and of themselves aren?t bad. However if you also have chained
rows this can hurt performance.
142. How do you set up tablespaces during an Oracle installation?
You should always attempt to use the Oracle Flexible Architecture standard or
another partitioning scheme to ensure proper separation of SYSTEM, ROLLBACK, REDO
LOG, DATA, TEMPORARY and INDEX segments.
143. You see multiple fragments in the SYSTEM tablespace, what should you check
first?
Ensure that users don?t have the SYSTEM tablespace as their TEMPORARY or DEFAULT
tablespace assignment by checking the DBA_USERS view.
144. What are some indications that you need to increase the SHARED_POOL_SIZE
parameter?
Poor data dictionary or library cache hit ratios, getting error ORA-04031. Another
indication is steadily decreasing performance with all other tuning parameters the
same.
145. What is the general guideline for sizing db_block_size and db_multi_block_read
for an application that does many full table scans?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
22
Oracle almost always reads in 64k chunks. The two should have a product equal to 64
or a multiple of 64.
146. What is the fastest query method for a table?
Fetch by rowid
147. When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If
bad -How do you correct it?
If you get excessive disk sorts this is bad. This indicates you need to tune the sort area
parameters in the initialization files. The major sort are parameter is the
SORT_AREA_SIZE parameter.
148. When should you increase copy latches? What parameters control copy
latches?
When you get excessive contention for the copy latches as shown by the "redo copy"
latch hit ratio. You can increase copy latches via the initialization parameter
LOG_SIMULTANEOUS_COPIES to twice the number of CPUs on your system.
149. Where can you get a list of all initialization parameters for your instance? How
about an indication if they are default settings or have been changed?
You can look in the init.ora file for an indication of manually set parameters. For all
parameters, their value and whether or not the current value is the default value, look
in the v$parameter view.
150. Describe hit ratio as it pertains to the database buffers. What is the difference
between instantaneous and cumulative hit ratio and which should be used for
tuning?
The hit ratio is a measure of how many times the database was able to read a value
from the buffers verses how many times it had to re-read a data value from the disks.
A value greater than 80-90% is good, less could indicate problems. If you simply take
the ratio of existing parameters this will be a cumulative value since the database
started. If you do a comparison between pairs of readings based on some arbitrary
time span, this is the instantaneous ratio for that time span. Generally speaking an
instantaneous reading gives more valuable data since it will tell you what your
instance is doing for the time it was generated over.
151. Discuss row chaining, how does it happen? How can you reduce it? How do you
correct it?
Row chaining occurs when a VARCHAR2 value is updated and the length of the new
value is longer than the old value and won?t fit in the remaining block space. This
results in the row chaining to another block. It can be reduced by setting the storage
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
23
parameters on the table to appropriate values. It can be corrected by export and
import of the effected table.
152. When looking at the estat events report you see that you are getting busy buffer
waits. Is this bad? How can you find what is causing it?
Buffer busy waits could indicate contention in redo, rollback or data blocks. You need
to check the v$waitstat view to see what areas are causing the problem. The value of
the "count" column tells where the problem is, the "class" column tells you with what.
UNDO is rollback segments, DATA is data base buffers.
153. If you see contention for library caches how can you fix it?
Increase the size of the shared pool.
154. If you see statistics that deal with "undo" what are they really talking about?
Rollback segments and associated structures.
155. If a tablespace has a default pctincrease of zero what will this cause (in
relationship to the smon process)?
The SMON process won?t automatically coalesce its free space fragments.
156. If a tablespace shows excessive fragmentation what are some methods to
defragment the tablespace? (7.1,7.2 and 7.3 only)
In Oracle 7.0 to 7.2 The use of the 'alter session set events 'immediate trace name
coalesce level ts#';? command is the easiest way to defragment contiguous free
space fragmentation. The ts# parameter corresponds to the ts# value found in the ts$
SYS table. In version 7.3 the ?alter tablespace coalesce;? is best. If the free space isn?t
contiguous then export, drop and import of the tablespace contents may be the only
way to reclaim non-contiguous free space.
157. How can you tell if a tablespace has excessive fragmentation?
If a select against the dba_free_space table shows that the count of a tablespaces
extents is greater than the count of its data files, then it is fragmented.
158. You see the following on a status report:
redo log space requests 23
redo log space wait time 0
Is this something to worry about? What if redo log space wait time is high? How can
you fix this?
Since the wait time is zero, no. If the wait time was high it might indicate a need for
more or larger redo logs.
159. What can cause a high value for recursive calls? How can this be fixed?
A high value for recursive calls is cause by improper cursor usage, excessive dynamic
space management actions, and or excessive statement re-parses. You need to
determine the cause and correct it By either relinking applications to hold cursors, use
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
24
proper space management techniques (proper storage and sizing) or ensure repeat
queries are placed in packages for proper reuse.
160. If you see a pin hit ratio of less than 0.8 in the estat library cache report is this a
problem? If so, how do you fix it?
This indicate that the shared pool may be too small. Increase the shared pool size.
161. If you see the value for reloads is high in the estat library cache report is this a
matter for concern?
Yes, you should strive for zero reloads if possible. If you see excessive reloads then
increase the size of the shared pool.
162. You look at the dba_rollback_segs view and see that there is a large number of
shrinks and they are of relatively small size, is this a problem? How can it be fixed if it is
a problem?
A large number of small shrinks indicates a need to increase the size of the rollback
segment extents. Ideally you should have no shrinks or a small number of large shrinks.
To fix this just increase the size of the extents and adjust optimal accordingly.
163. You look at the dba_rollback_segs view and see that you have a large number of
wraps is this a problem?
A large number of wraps indicates that your extent size for your rollback segments are
probably too small. Increase the size of your extents to reduce the number of wraps.
You can look at the average transaction size in the same view to get the information
on transaction size.
164. In a system with an average of 40 concurrent users you get the following from a
query on rollback extents:
ROLLBACK CUR EXTENTS
--------------------- --------------------------
R01 11
R02 8
R03 12
R04 9
SYSTEM 4
You have room for each to grow by 20 more extents each. Is there a problem? Should
you take any action?
No there is not a problem. You have 40 extents showing and an average of 40
concurrent users. Since there is plenty of room to grow no action is needed.
165. You see multiple extents in the temporary tablespace. Is this a problem?
As long as they are all the same size this isn?t a problem. In fact, it can even improve
performance since Oracle won?t have to create a new extent when a user needs
one.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
25
166. Define OFA.
OFA stands for Optimal Flexible Architecture. It is a method of placing directories and
files in an Oracle system so that you get the maximum flexibility for future tuning and
file placement.
167. How do you set up your tablespace on installation?
The answer here should show an understanding of separation of redo and rollback,
data and indexes and isolation os SYSTEM tables from other tables. An example would
be to specify that at least 7 disks should be used for an Oracle installation so that you
can place SYSTEM tablespace on one, redo logs on two (mirrored redo logs) the
TEMPORARY tablespace on another, ROLLBACK tablespace on another and still have
two for DATA and INDEXES. They should indicate how they will handle archive logs
and exports as well. As long as they have a logical plan for combining or further
separation more or less disks can be specified.
168. What should be done prior to installing Oracle (for the OS and the disks)?
Adjust kernel parameters or OS tuning parameters in accordance with installation
guide. Be sure enough contiguous disk space is available.
169. You have installed Oracle and you are now setting up the actual instance. You
have been waiting an hour for the initialization script to finish, what should you check
first to determine if there is a problem?
Check to make sure that the archiver isn?t stuck. If archive logging is turned on during
install a large number of logs will be created. This can fill up your archive log
destination causing Oracle to stop to wait for more space.
170. When configuring SQLNET on the server what files must be set up?
INITIALIZATION file, TNSNAMES.ORA file, SQLNET.ORA file
171. When configuring SQLNET on the client what files need to be set up?
SQLNET.ORA, TNSNAMES.ORA
172. What must be installed with ODBC on the client in order for it to work with Oracle?
SQLNET and PROTOCOL (for example: TCPIP adapter) layers of the transport
programs.
173. You have just started a new instance with a large SGA on a busy existing server.
Performance is terrible, what should you check for?
The first thing to check with a large SGA is that it isn?t being swapped out.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
26
174. What OS user should be used for the first part of an Oracle installation (on UNIX)?
You must use root first.
175. When should the default values for Oracle initialization parameters be used as is?
Never
175. How many control files should you have? Where should they be located?
At least 2 on separate disk spindles. Be sure they say on separate disks, not just file
systems.
176. How many redo logs should you have and how should they be configured for
maximumrecoverability?
You should have at least three groups of two redo logs with the two logs each on a
separate disk spindle (mirrored by Oracle). The redo logs should not be on raw
devices on UNIX if it can be avoided.
177. You have a simple application with no "hot" tables (i.e. uniform IO and access
requirements). How many disks should you have assuming standard layout for SYSTEM,
USER, TEMP and ROLLBACK tablespaces?
At least 7, see disk configuration answer above.
178. Describe third normal form?
In third normal form all attributes in an entity are related to the primary key and only to
the primary key
179. Is the following statement true or false:"All relational databases must be in third
normal form"
Why or why not?
False. While 3NF is good for logical design most databases, if they have more than just
a few tables, will not perform well using full 3NF. Usually some entities will be
denormalized in the logical to physical transfer process.
180. What is an ERD?
An ERD is an Entity-Relationship-Diagram. It is used to show the entities and
relationships for a database logical model.
181. Why are recursive relationships bad? How do you resolve them?
A recursive relationship (one where a table relates to itself) is bad when it is a hard
relationship (i.e. neither side is a "may" both are "must") as this can result in it not being
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
27
possible to put in a top or perhaps a bottom of the table (for example in the
EMPLOYEE table you couldn?t put in the PRESIDENT of the company because he has
no boss, or the junior janitor because he has no subordinates). These type of
relationships are usually resolved by adding a small intersection entity.
182. What does a hard one-to-one relationship mean (one where the relationship on
both ends is "must")?
This means the two entities should probably be made into one entity.
183. How should a many-to-many relationship be handled?
By adding an intersection entity table
184. What is an artificial (derived) primary key? When should an artificial (or derived)
primary key be used?
A derived key comes from a sequence. Usually it is used when a concatenated key
becomes too cumbersome to use as a foreign key.
185. When should you consider denormalization?
Whenever performance analysis indicates it would be beneficial to do so without
compromising data integrity.
186. How can you determine if an Oracle instance is up from the operating system
level?
There are several base Oracle processes that will be running on multi-user operating
systems, these will be smon, pmon, dbwr and lgwr. Any answer that has them using
their operating system process showing feature to check for these is acceptable. For
example, on UNIX a ps -ef| grep dbwr will show what instances are up.
187. Users from the PC clients are getting messages indicating :
ORA-06114: (Cnct err, can't get err txt. See Servr Msgs & Codes Manual)
What could the problem be?
The instance name is probably incorrect in their connection string.
188. Users from the PC clients are getting the following error stack:
ERROR: ORA-01034: ORACLE not available
ORA-07318: smsget: open error when opening sgadef.dbf file.
HP-UX Error: 2: No such file or directory
What is the probable cause?
The Oracle instance is shutdown that they are trying to access, restart the instance.
189. How can you determine if the SQLNET process is running for SQLNET V1? How
about V2?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
28
For SQLNET V1 check for the existence of the orasrv process. You can use the
command "tcpctl status" to get a full status of the V1 TCPIP server, other protocols
have similar command formats. For SQLNET V2 check for the presence of the LISTENER
process(s) or you can issue the command "lsnrctl status".
190 . What file will give you Oracle instance status information? Where is it located?
The alert.ora log. It is located in the directory specified by the
background_dump_dest parameter in the v$parameter table.
191. Users aren?t being allowed on the system. The following message is received:
ORA-00257 archiver is stuck. Connect internal only, until freed
What is the problem?
The archive destination is probably full, backup the archive logs and remove them
and the archiver will re-start.
192. Where would you look to find out if a redo log was corrupted assuming you are
using Oracle mirrored redo logs?
There is no message that comes to the SQLDBA or SRVMGR programs during startup in
this situation, you must check the alert.log file for this information.
193. You attempt to add a datafile and get:
ORA-01118: cannot add anymore datafiles: limit of 40 exceeded
What is the problem and how can you fix it?
When the database was created the db_files parameter in the initialization file was set
to 40. You can shutdown and reset this to a higher value, up to the value of
MAX_DATAFILES as specified at database creation. If the MAX_DATAFILES is set to low,
you will have to rebuild the control file to increase it before proceeding.
194. You look at your fragmentation report and see that smon hasn?t coalesced any
of you tablespaces, even though you know several have large chunks of contiguous
free extents. What is the problem?
Check the dba_tablespaces view for the value of pct_increase for the tablespaces. If
pct_increase is zero, smon will not coalesce their free space.
195. Your users get the following error:
ORA-00055 maximum number of DML locks exceeded
What is the problem and how do you fix it?
The number of DML Locks is set by the initialization parameter DML_LOCKS. If this value
is set to low (which it is by default) you will get this error. Increase the value of
DML_LOCKS. If you are sure that this is just a temporary problem, you can have them
wait and then try again later and the error should clear.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
29
196. You get a call from you backup DBA while you are on vacation. He has
corrupted all of the control files while playing with the ALTER DATABASE BACKUP
CONTROLFILE command. What do you do?
As long as all datafiles are safe and he was successful with the BACKUP controlfile
command you can do the following:
CONNECT INTERNAL
STARTUP MOUNT
(Take any read-only tablespaces offline before next step ALTER DATABASE DATAFILE ....
OFFLINE;)
RECOVER DATABASE USING BACKUP CONTROLFILE
ALTER DATABASE OPEN RESETLOGS;
(bring read-only tablespaces back online)
Shutdown and backup the system, then restart
If they have a recent output file from the ALTER DATABASE BACKUP CONTROL FILE TO
TRACE; command, they can use that to recover as well.
If no backup of the control file is available then the following will be required:
CONNECT INTERNAL
STARTUP NOMOUNT
CREATE CONTROL FILE .....;
However, they will need to know all of the datafiles, logfiles, and settings for
MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES for the database
to use the command.
197. What are materialized views? when are they used?

Materialized view is like a view but stores both definition of a view plus the rows
resulting from execution of the view. It uses a query as the bases and the query is
executated at the time the view is created and the results are stored in a table. You
can define the Materialized view with the same storage parametes as any other table
and place it in any tablespace of your choice. You can also index and partition the
Materialized view table like other tables to improve performance of queries executed
aginst them.
Use of Meterialized view:-
Expensive operations such as joins and aggregations do not need to be reexecuted.
If the query is astisfied with data in a Meterialized view, the server transforms the query
to reference the
view rather than the base tables.
198. What is an Oracle instance?
Overview of an Oracle Instance
Every running Oracle database is associated with an Oracle instance. When a
database is started on a database server (regardless of the type of computer),
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
30
Oracle allocates a memory area called the System Global Area (SGA) and startsone
or more Oracle processes. This combination of the SGA and the Oracle
processes is called an Oracle instance. The memory and processes of an instance
manage the associated databases data efficiently and serve the one or multiple
users of the database.
The Instance and the Database After starting an instance, Oracle associates the
instance with the specified database. This is called mounting the database. The
database is then ready to be
opened, which makes it accessible to authorized users.
Multiple instances can execute concurrently on the same computer, each accessing
its own physical database. In clustered and massively parallel systems (MPP),
the Oracle Parallel Server allows multiple instances to mount a single database.
Only the database administrator can start up an instance and open the database.
If a database is open, the database administrator can shut down the database so
that it is closed. When a database is closed, users cannot access the
information that it contains.
Security for database startup and shutdown is controlled via connections to
Oracle with administrator privileges. Normal users do not have control over the
current status of an Oracle database.
199 . What is a view?
A view is a tailored presentation of the data contained in one or more tables(or other
views). Unlike a table, a view is not allocated any storage space, nor does a view
actually contain data; rather, a view is defined by a query that extracts or derives
data from the tables the view references. These tables are
called base tables.
Views present a different representation of the data that resides within the base
tables. Views are very powerful because they allow you to tailor the presentation of
data to different types of users.
Views are often used to:
provide an additional level of table security by restricting access to a
predetermined set of rows and/or
columns of a table
hide data complexity
simplify commands for the user
present the data in a different perspective from that of the base table
isolate applications from changes in definitions of base tables
express a query that cannot be expressed without using a view
200. What is referential integrity?
Rules governing the relationships between primary keys and foreign keys of tables
within a relational database that determine data consistency. Referential integrity
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
31
requires that the value of every foreign key in every table be matched by the value of
a primary key in another table.
201. Name the data dictionary that stores user-defined constraints?
USER_CONSTRAINTS
202. What is a collection of privileges?
collection of privilages is role.
they are available in tow views , user_tab_privs_made, user_tab_privs_recd
203 . Snapshot: A snapshot is a read-only copy of a table or a subset of a table.
204. What is a cursor?
cursor is a private sql work area used to perform manipulations on data using pl\ sql.
adv:
1.mainly used for multiple row manipulations and locking columns.
note: data which is populated into the cursor is known as active dataset.
cursors are of two types
1.implicit
2.explicit
implicit

attributes or properties for implicit cursor


1.sql%is open:attribute returns a boolean value stating wether the cursor is open or
closed.
2.sql % found: returns boolean value stating whether the record is found in the cursor.
3.sql%notfound : returns a boolean value stating whether the record is not found in
the cursor
4.sql %rowcount :returns a pneumeric value stating no.of rows executed in the cursor.
explicit cursorsretrives multiple rows.
************
adv: users can perform locks on th data in the cursor
attributes
1.% is open
2.% found
3.% not found
4.% rowcount
Note: DATA which is populated in the cursor is known as active data set.
WE CAN WRITE TWO CURSORS IN ONE PROGRAM
WE CAN WRITE A CURSOR SPECIFYING PARAMETERS
CURSOR WITH UPDATE CLAUSE IS USED TO PERFORM LOCKS ON DATA.
205. What is a sequence? It is a database object to auto generate numbers.
206 Name the data dictionary that stores user-defined Stored procedures?
user_objects
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
32
207. Why Use Sql* Loader in Oracle Database?
The Sql Loader module of the oracle database Management System loads data into
an existing ORACLE table from an external files.It is available locally only on CMS and
PCs with oracle version 5. Throughout this documentation the CAR database
described in Referance A is used for illustration.
There are several methods others than using SQL *Loader of inserting data into a
table.
1. The Sql insert command may be used from the SQL * Plus module,
for Example :
insert into CAR values()
where the values to be inserted into a row of the table are listed inside the
parentheses. Dates and Characters data must be Surrounded by single quotes; items
are seperated by commas.
2. Sql*Forms allows you to add rows interactively using forms. The forms may contain
default values and checks for invalid data.
3. ODL loads the table from a control file and separate fixed format data file. ODL is
available on all versions of ORACLE . SQL * Loader is much more flexible than ODL and
will eventually supersede it on all systems.
208. ODBC
stands for open database connectivity
209. Explain Normalization
Normalization is the techinque of designing the database with the least redundancy
and duplicacy of data. Types of Normalization:
1 NF
2 NF
3 NF
BCNF
5 NF
6NF : Impossible to achieve this level of normalization
210. what is a synonym ?
A synonym is an alternative name for tables,views,procedures and other database
objectsgenerally when we have more than one schema and we wish to access an
object of a different schema then we create synonyms for that object in the schema
where we wish to access the object.
create synonym <synonymname>for <schemaname>.<object-name>
211. what is an exception ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
33
Exception is an event that causes suspension of normal program execution.
In oracle there are serveral types of exceptions
1) Pre-defined exceptions like NO_DATA_FOUND,TOO_MANY_ROWS
2) User-defined exceptions which would validate the business logic
3) unnamed system exceptions which are raised due to errors in the application code
.. you can name these exceptions using PRAGMA EXCEPTION_INIT
4)Unnamed programmer-defined exceptions. Exceptions that are defined and raised
in the server by the programmer. In this case, the programmer provides both an error
number (between -20000 and -20999) and an error message, and raises that
exception with a call to RAISE_APPLICATION_ERROR.
for all the exceptions raised oracle fills in sqleerm and sqlcode variable which provide
the error message and error code for the exception raised.
212. What are pseudo-columns in SQL? Provide examples?
A pseudocolumn behaves like a table column, but is not actually stored in the table.
You can select from pseudocolumns, but you cannot insert, update, or delete their
values. Examples: CURRVAL,NEXTVAL,ROWID,LEVEL
213. What is a schema ?
A schema is a logical collection of database objects like tables, views, pkgs,
procedures, triggers, etc. It usually has an associated database user.
214. What is a co-related sub-query?
It is very similar to sub-queries where the parent query is executed based on the
values returned by sub-quries. but when comes to co-related subqueries for every
instance of parent query subquery is executed and based on the result of sub-query
the parent query will display the record as we will have refernce of parent quries in su-
queries we call these as corelated subquries.
so, we can define co-related sub query as for every record retrival from the sub query
is processed and based on result of process the parent record is displayed.
215. what is trigger?
Trigger is an event. It is used prevent the invalid entries of the data.There
has a different types of trigger are available.
1)rowlevel trigger
before insert,before delete,before update
after insert,after delete,after update
2)statement level trigger
before insert,before delete,before update
after insert,after delete,after update
3)INSTEAD OF trigger
4)Schema level Triggers
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
34
5)System level Triggers
216. What is an oracle instance?
An Oracle instance consists of the System Global Area (SGA) memory structure and
the background processes used to manage a database. An instance is identified by
using methods specific to each operating system. The instance can open and use
only one database at a time.
217. Is there any solution to delete a particular colum in a database by sql?
Alter table drop column
or
First mark the column unused
alter table set unused column
then drop it
alter table drop unused columns.
This will drop all the columns marked as unused. If a particular column has to be
dropped, mention the column name after columns
218. What is data Modal.
The logical data structure developed during the logical database design process is a
data model or entity model. It is also a description of the structural properties that
define all entries represented in a database and all the relationships that exist among
them.
219. %ROWTYPE & %TYPE
%ROWTYPE is used to declare a record with the same types as found in the specified
database table, view or cursor
%TYPE is used to declare a field with the same type as that of a specified tables
column.
220. INDEX & TABLE PARTITION
Index for a physical structure (b-tree) to help you query run faster.
Table partition is a method of breaking a large table into smaller tables grouped by
some logical separators. in your case, having both index and partition will make things
faster.
221. Data Control statements
These are used to control the data using DCL (data control language) ex: Grant etc.
222. Relation: Mathematical term for a table.
223. Redo Log: A set of files that record all changes made to an Oracle database. A
database MUST have at least two redo log files. Log files can be multiplexed on
multiple disks to ensure that they will not get lost.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
35
224. Oracle ARCHiver Process.
ARCH is an Oracle background process created when you start an instance in
ARCHIVE LOG MODE. The ARCH process will archive on-line redo log files to some
backup media.
225. Buffer Cache: The portion of the SGA that holds copies of Oracle data blocks. All
user processes that connect to an instance share access to the buffer cache.
Performance of the buffer cache is indicated by the BCHR (Buffer Cache Hit Ratio).
226. Background Process: Non-user process that is created when a database instance
is started. These processes are used to manage and monitor database operations.
Example background processes: SMON, PMON etc.
227. Two-Phase Commit: A strategy in which changes to a database are temporarily
applied. Once it has been determined that all parts of a change can be made
successfully, the changes are permanently posted to the database. The steps
involved are the prepared and commit request
228. SET OPERATIONS
Union: All the distinct rows are selected by either query.
Intersect: All distinct rows selected by both queries
Minus: All distinct rows that are selected by the first SELECT statement and that are not
selected in the second SELECT statement.
J oin: The process of combining data from two or more tables using matching
columns. Types of join are Equi J oin, Outer J oin, Self J oin, Natural J oin, etc.
Equi J oin: An Equi J oin (aka. Inner J oin or Simple J oin) is a join statement that uses an
equivalency operation (i.e: colA =colB) to match rows from different tables. The
converse of an equi join is a nonequijoin operation.
Outer J oin: Similar to the Equi J oin, but Oracle will also return non matched rows from
the tale with the outer join operator (+). Missing values are filled with null values.
Self J oin: A join in which a table is joined with itself.
Natural J oin: A join statement that compares the common columns of both tables
with each other. One should check whether common columns exist in both tables
before doing a natural join.
229. Denormalization:
The opposite of data normalization (almost). In a denormalized database, some
duplicated data storage is allowed. The benefits are quicker data retrieval and/or a
database structure that is easier for end-users.
230. ORACLE INSTANCE
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
36
Every running Oracle database is associated with an Oracle instance. When a
database is started on a database server (regardless of the type of computer),
Oracle allocates a memory area called the System Global Area (SGA) and starts
one or more Oracle processes. This combination of the SGA and the Oracle
processes is called an Oracle instance. The memory and processes of an instance
manage the associated databases data efficiently and serve the one or multiple
users of the database.
The Instance and the Database
After starting an instance, Oracle associates the instance with the specified
database. This is called mounting the database. The database is then ready to be
opened, which makes it accessible to authorized users.
Multiple instances can execute concurrently on the same computer, each accessing
its own physical database. In clustered and massively parallel systems (MPP),
the Oracle Parallel Server allows multiple instances to mount a single database.
Only the database administrator can start up an instance and open the database.
If a database is open, the database administrator can shut down the database so
that it is closed. When a database is closed, users cannot access the
information that it contains.
Security for database startup and shutdown is controlled via connections to
Oracle with administrator privileges. Normal users do not have control over the
current status of an Oracle database.
The instance can open and use only one database at a time.
231: What is a view?
A view is a tailored presentation of the data contained in one or more tables
(or other views). Unlike a table, a view is not allocated any storage space, nor
does a view actually contain data; rather, a view is defined by a query that
extracts or derives data from the tables the view references. These tables are
called base tables.
Views present a different representation of the data that resides within the
base tables. Views are very powerful because they allow you to tailor the
presentation of data to different types of users.
Views are often used to:
provide an additional level of table security by restricting access to a
predetermined set of rows and/or columns of a table
hide data complexity
simplify commands for the user
present the data in a different perspective from that of the base table
isolate applications from changes in definitions of base tables
express a query that cannot be expressed without using a view
232. What is referential integrity?
Rules governing the relationships between primary keys and foreign keys of
tables within a relational database that determine data consistency. Referential
integrity requires that the value of every foreign key in every table be matched
by the value of a primary key in another table.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
37
233. Name the data dictionary that stores user-defined constraints?
USER_CONSTRAINTS
234. ODBC stands for Open DataBase Connectivity: It is used to connect the front-end
with the backend (database)
234. Normalization is the technique of designing the database with the least
redundancy and duplicity of data. Types of Normalization:
1 NF
2 NF
3 NF
BCNF a.k.a 4 NF
5 NF
6NF : Impossible to achieve this level of normalization
235. What is a synonym?
A synonym is an alternative name for tables, views, procedures and other database
objects generally when we have more than one schema and we wish to access an
object of a different schema then we create synonyms for that object in the schema
where we wish to access the object.
Create synonym <synonym-name>for <schemaname.object-name>
CREATE SYNONYM EMP_CPY FOR SCOTT.EMP;
236. What is an exception?
Exception is an event that causes suspension of normal program execution.
In oracle there are several types of exceptions
1) Pre-defined exceptions like NO_DATA_FOUND, TOO_MANY_ROWS, and
ZERO_DIVIDE, DUPLICATE_ROWS_ON_INDEX.
2) User-defined exceptions which would validate the business logic.
3) Unnamed system exceptions which are raised due to errors in the application
code. You can name these exceptions using PRAGMA EXCEPTION_INIT
4) Unnamed programmer-defined exceptions. Exceptions that are defined and raised
in the server by the programmer. In this case, the programmer provides both an error
number (between -20000 and -20999) and an error message, and raises that
exception with a call to RAISE_APPLICATION_ERROR.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
38
For all the exceptions raised, Oracle fills in SQLERRM and SQLCODE variable which
provide the error message and error code for the exception raised.
237.What are pseudo-columns in SQL?
A pseudocolumn behaves like a table column, but is not actually stored in the table.
You can select from pseudocolumns, but you cannot insert, update, or delete their
values. These are used with sequences to retrieve the next sequence value and
current sequence value.
ex: rownum, rowid, level, currval, nextval etc
Suppose abc is the sequence name if i want to see the currval of the sequence we
issue the sql statement
SQL>select abc.currval from dual;
if we want to see the next value of the sequence we issue the command
SQL>select abc.nextval from dual;
238. How can we know the user id from which we have logged into Oracle?
In SQL*Plus, enter the command show user
239.Name of the database to which the user is connected?
select * from global_name;
240.Inserting into multiple tables using a single statement is possible:
Table ord_item_qty has the following data:
ITEM QTY PRICE
-
apples 10 2
oranges 15 1.5
We now insert into two other tables, ORD_ITEM_QTY (this has columns ITEM and QTY)
and ITEM_SALE (this has columns ITEM and AMT), as follows:
INSERT ALL
INTO ord_item_qty (item, qty) values (item, qty)
INTO item_sale (item, amt) values (item, qty * price)
SELECT item, qty, price from ord_items;
241. AUTONOMOUS TRANSACTION
An autonomous transaction starts with the first sql statement of the pl/sql block and
ends with a commit. It starts within the context of an another transaction called
parent transaction and independent of it(parent transaction).
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
39
To make a transaction autonomous u have to declare PRAGMA
AUTONOMOUS_TRANSACTION at the beginning.
The main adv. of using PRAGMA AUTONOMOUS_TRANSACTION is that whether the
transaction made by the parent may be rolled back due to some error, the
autonomous transaction has no effect on it. Suppose there is any error in autonomous
transaction then what would happen ? Dont worry It will save all the transactions just
before the error occurred. Only the last transaction that has error will be rolled back
only if there is no error handler.
242. The following are table names followed by column names present in it
emp_company(ename,cname,salary,jdate)
company(cname,city)
manager(ename,mname)
employee(ename,city)
emp_shift(ename,shift)
where
ename=employee name
cname=company name
jdate=date of join
city in employee table means city in which employee resides
city in company table mean city in which company presents
mname=manager name
shift means the time in which employee works
now please give the queries for the following tasks
1.give the names of employees living in the same city where their manager is also
living
2.give the salary of manager 0f employees living in city bombay
This is the answer for your first query
select m1.ename,e1.city from employee e1,manager m1,(select distinct
managername,city from manager,employee where employee.ename =
manager.managername) q1
where e1.ename =m1.ename and e1.city =q1.city and m1.managername =
q1.managername;
This is the answer for your second query
select distinct m1.mname,ec.salary from emp_company ec,manager m1,
(select distinct ename from employee where employee.city =bombay) q1
where m1.mname =ec.ename and m1.ename =q1.ename;
243. What happens if a primary key constraint is disabled and then enabled without
fully specifying the index clause?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
40
The index is created in the users default tablespace and all sizing information is lost.
Oracle doesnt store this information as a part of the constraint definition, but only as
part of the index definition, when the constraint was disabled the index was dropped
and the information is gone
244. A table is created with a primary key and some other constrains such as not
null,check etc.if the same table is copied into another table with other name.
Is the same constraints applicable to the copied table or not
When any other table is created using other table, constraints are not copied only
table structure and data would be copied.
245. what is the use of rollback segment in oracle. when we delete some record in the
table where it is stored. so that latter we can rollback in to it.
If you delete any record it would be temporarily deleted from database table, when
you commit the transaction it would be permanently deleted from database table.
All update delete, or manipulation information is stored in rollback segment in rollback
files that are multiplexed into different disks. There is a background process ARCH
which keep on taking ARCHIVE of online redo files in some backup space. We can
recover undo those changes by using redo log files.
246. Usually we use char,varchar,varchar2,number,date in data types in oracle. what
r the advantages and disadvantages of using an integer in oracle 10g
INTEGER Datatype in Oracle is an alias for Number(38) so there is no difference in
them just Integer have No scale and No decimal.
247. Describe the difference between a procedure, function and anonymous pl/sql
block.
Candidate should mention use of DECLARE statement, a function must return a value
while a procedure doesnt have to.
248. What is a mutating table error and how can you get around it?
This happens with triggers. It occurs because the trigger is trying to update a row it is
currently using. The usual fix involves either use of views or temporary tables so the
database is selecting from one while updating the other.
249. Describe the use of %ROWTYPE and %TYPE in PL/SQL
%ROWTYPE allows you to associate a variable with an entire table row. The %TYPE
associates a variable with a single column type.
250. What packages (if any) has Oracle provided for use by developers?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
41
Oracle provides the DBMS_ series of packages. There are many which developers
should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_J OB, 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.
251. Describe the use of PL/SQL tables
PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can
be used to hold values for use in later queries or calculations. In Oracle 8 they will be
able to be of the %ROWTYPE designation, or RECORD.
252. When is a declare statement needed?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone,
non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is
used.
253. In what order should a open/fetch/loop set of commands in a PL/SQL block be
implemented if you use the %NOTFOUND cursor variable in the exit when statement?
Why?
OPEN then FETCH then LOOP followed by the exit when. If not specified in this order
will result in the final return being done twice because of the way the %NOTFOUND is
handled by PL/SQL.
254. What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
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.
255. How can you find within a PL/SQL block, if a cursor is open?
Use the %ISOPEN cursor status variable.
256. How can you generate debugging output from PL/SQL?
Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW
ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used
to show intermediate results from loops and the status of variables as the procedure is
executed. The new package UTL_FILE can also be used.
257. Give one method for transferring a table from one schema to another:
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
42
There are several possible methods, export-import, CREATE TABLE... AS SELECT, or
COPY.
258. What is the purpose of the IMPORT option IGNORE? What is default setting for it ?
The IMPORT IGNORE option tells import to ignore "already exists" errors. If it is not
specified the tables that already exist will be skipped. If it is specified, the error is
ignored and the tables data will be inserted. The default value is N.
259. What is the proper method for disabling and re-enabling a primary key
constraint?
You use the ALTER TABLE command for both. However, for the enable clause you must
specify the USING INDEX and TABLESPACE clause for primary keys.
260. (On UNIX) When should more than one DB writer process be used? How many
should be used?
If the UNIX system being used is capable of asynchronous IO then only one is required,
if the system is not capable of asynchronous IO then up to twice the number of disks
used by Oracle number of DB writers should be specified by use of the db_writers
initialization parameter.
261. If you have an example table, what is the best way to get sizing data for the
production table implementation?
The best way is to analyze the table and then use the data provided in the
DBA_TABLES View to get the average row length and other pertinent data for the
calculation. The quick and dirty way is to look at the number of blocks the table is
actually using and ratio the number of rows in the table to its number of blocks
against the number of expected rows.
262. How can you determine if an index needs to be dropped and rebuilt?
Run the ANALYZE INDEX command on the index to validate its structure and then
calculate the ratio of LF_BLK_LEN/LF_BLK_LEN+BR_BLK_LEN and if it isnt near 1.0 (i.e.
greater than 0.7 or so) then the index should be rebuilt. Or if the ratio BR_BLK_LEN/
LF_BLK_LEN+BR_BLK_LEN is nearing 0.3.
263. You want to determine the location of identical rows in a table before
attempting to place a unique index on the table, how can this be done?
Oracle tables always have one guaranteed unique column, the rowid column. If you
use a min/max function against your rowid and then select against the proposed
primary key you can squeeze out the rowids of the duplicate rows pretty quick. For
example:
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
43
Select rowid from emp_cpy e
Where e.rowid >(select min (x.rowid) From emp_cpy x
Where x.emp_no =e.emp_no);
In the situation where multiple columns make up the proposed key, they must all be
used in the where clause.
264. What is a Cartesian product?
A Cartesian product is the result of an unrestricted join of two or more tables. The
result set of a three table Cartesian product will have x * y * z number of rows where x,
y, z correspond to the number of rows in each table involved in the join.
265. What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL
statements. You use it by first setting timed_statistics to true in the initialization file and
then turning on tracing for either the entire database via the sql_trace parameter or
for the session using the ALTER SESSION command. Once the trace file is generated
you run the tkprof tool against the trace file and then look at the output from the
tkprof tool. This can also be used to generate explain plan output.
266. What is explain plan and how is it used?
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have
an explain_table generated in the user you are running the explain plan for. This is
created using the utlxplan.sql script. Once the explain plan table exists you run the
explain plan command giving as its argument the SQL statement to be explained. The
explain_plan table is then queried to see the execution plan of the statement. Explain
plans can also be run using tkprof.
267. Where can you get a list of all initialization parameters for your instance? How
about an indication if they are default settings or have been changed?
You can look in the init.ora file for an indication of manually set parameters. For all
parameters, their value and whether or not the current value is the default value, look
in the v$parameter view.
268. Discuss Row-Chaining, how does it happen? How can you reduce it? How do you
correct it?
Row chaining occurs when a VARCHAR2 value is updated and the length of the new
value is longer than the old value and wont fit in the remaining block space. This
results in the row chaining to another block. It can be reduced by setting the storage
parameters on the table to appropriate values. It can be corrected by export and
import of the effected table.
269. If you see contention for library caches how can you fix it?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
44
Increase the size of the shared pool.
270. If you see statistics that deal with "undo" what are they really talking about?
Rollback segments and associated structures.
271. If a tablespace has a default pctincrease of zero what will this cause (in
relationship to the smon process)?
The SMON process wont automatically coalesce its free space fragments.
272. How can you tell if a tablespace has excessive fragmentation?
If a select against the dba_free_space table shows that the count of a tablespaces
extents is greater than the count of its data files, then it is fragmented.
273. You see multiple extents in the temporary tablespace. Is this a problem?
As long as they are all the same size this isnt a problem. In fact, it can even improve
performance since Oracle wont have to create a new extent when a user needs
one.
274. How many control files should you have? Where should they be located?
At least 2 on separate disk spindles. Be sure they say on separate disks, not just file
systems.
275. How many redo logs should you have and how should they be configured for
maximum recoverability?
You should have at least three groups of two redo logs with the two logs each on a
separate disk spindle (mirrored by Oracle). The redo logs should not be on raw
devices on UNIX if it can be avoided.
276. Describe third normal form?
In third normal form all attributes in an entity are related to the primary key and only to
the primary key
277. Is the following statement true or false:
"All relational databases must be in third normal form" Why or why not?
False. While 3NF is good for logical design most databases, if they have more than just
a few tables, will not perform well using full 3NF. Usually some entities will be
denormalized in the logical to physical transfer process.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
45
278. What is an ERD?
An ERD is an Entity-Relationship-Diagram. It is used to show the entities and
relationships for a database logical model.
279. Why are recursive relationships bad? How do you resolve them?
A recursive relationship (one where a table relates to itself) is bad when it is a hard
relationship (i.e. neither side is a "may" both are "must") as this can result in it not being
possible to put in a top or perhaps a bottom of the table (for example in the
EMPLOYEE table you couldnt put in the PRESIDENT of the company because he has
no boss, or the junior janitor because he has no subordinates). These type of
relationships are usually resolved by adding a small intersection entity.
280. What does a hard one-to-one relationship mean (one where the relationship on
both ends is "must")?
This means the two entities should probably be made into one entity.
281. How should a many-to-many relationship be handled?
By adding an intersection entity table
282. What is an artificial (derived) primary key? When should an artificial (or derived)
primary key be used?
A derived key comes from a sequence. Usually it is used when a concatenated key
becomes too cumbersome to use as a foreign key.
283. When should you consider denormalization?
Whenever performance analysis indicates it would be beneficial to do so without
compromising data integrity.
284. Change SQL prompt name
SQL>set sqlprompt Manimara > Manimara >
285. Switch to DOS prompt
SQL>host
286. How do I eliminate the duplicate rows ?
SQL>delete from table_name where rowid not in (select max(rowid) from table
group by duplicate_values_field_name);
or
SQL>delete duplicate_values_field_name dv from table_name ta where rowid
<(select min(rowid) from table_name tb where ta.dv=tb.dv);
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
46
Example.
Table Emp
Empno Ename
101 Scott
102 J iyo
103 Millor
104 J iyo
105 Smith
delete ename from emp a where rowid <( select min(rowid) from emp b where
a.ename =b.ename);
The output like,
Empno Ename
101 Scott
102 Millor
103 J iyo
104 Smith
287. How do I display row number with records?
To achive this use rownum pseudocolumn with query, like SQL>select rownum,
ename from emp;
Output:
1 Scott
2 Millor
3 J iyo
4 Smith
6. Display the records between two range
select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER
288. I know the nvl function only allows the same data type(ie. number or char or
date Nvl(comm, 0)), if commission is null then the text Not Applicable want to
display, instead of blank space. How do I write the query?
SQL>select nvl(to_char(comm.),'NA') from emp;
Output :
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
47
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA
289. Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly
declared.
290. Explicit Cursor attributes
There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT,
cursor_name%ISOPEN
291. Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit
cursor after executing SQL statements.
: 2. All are Boolean attributes.
292. Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N =(SELECT COUNT (DISTINCT (b.sal))
FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
---------
3700
293. To view installed Oracle version information
SQL>select banner from v$version;
294. Display the number value in Words
SQL>select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
48
SAL (TO_CHAR(TO_DATE(SAL,'J '),'J SP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL>select sal "Salary ",
(' Rs. '| | (to_char(to_date(sal,'j'), 'J sp'))| | ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
295. Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
296. Which date function returns number value?
months_between
297. What are PL/SQL Cursor Exceptions?
CURSOR_ALREADY_OPEN, INVALID_CURSOR
298. Other way to replace query result null value with a text
SQL>Set NULL N/A
to reset SQL>Set NULL
289. What are the more common pseudo-columns?
SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM
290. What is the output of SIGN function?
1 for positive value, 0 for Zero, -1 for Negative value.
291. What is the maximum number of triggers, can apply to a single table?
12 triggers.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
49
292. Explain the difference between a hot backup and a cold backup and the
benefits associated with each.
A hot backup is basically taking a backup of the database while it is still up and
running and it must be in archive log mode. A cold backup is taking a backup of the
database while it is shut down and does not require being in archive log mode. The
benefit of taking a hot backup is that the database is still available for use while the
backup is occurring and you can recover the database to any point in time. The
benefit of taking a cold backup is that it is typically easier to administer the backup
and recovery process. In addition, since you are taking cold backups the database
does not require being in archive log mode and thus there will be a slight
performance gain as the database is not cutting archive logs to disk.
293. You have just had to restore from backup and do not have any control files.
How would you go about bringing up this database?
I would create a text based backup control file, stipulating where on disk all the data
files where and then issue the recover command with the using backup control file
clause.
294. How do you switch from an init.ora file to a spfile?
Issue the create spfile from pfile command.
295. Explain the difference between a data block, an extent and a segment.
A data block is the smallest unit of logical storage for a database object. As objects
grow they take chunks of additional storage that are composed of contiguous data
blocks. These groupings of contiguous data blocks are called extents. All the extents
that an object takes when grouped together are considered the segment of the
database object.
296. Give the reasoning behind using an index.
Faster access to data blocks in a table.
297. Give the two types of tables involved in producing a star schema and the
type of data they hold.
Fact tables and dimension tables. A fact table contains measurements while
dimension tables will contain data that will help describe the fact tables.
298. What type of index should you use on a fact table? A Bitmap index.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
50
299. A table is classified as a parent table and you want to drop and re-create it. How
would you do this without affecting the children tables?
Disable the foreign key constraint to the parent, drop the table, re-create the table,
enable the foreign key constraint.
300. Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode
and the benefits and disadvantages to each.
ARCHIVELOG mode is a mode that you can put the database in for creating a
backup of all transactions that have occurred in the database so that you can
recover to any point in time. NOARCHIVELOG mode is basically the absence of
ARCHIVELOG mode and has the disadvantage of not being able to recover to any
point in time. NOARCHIVELOG mode does have the advantage of not having to write
transactions to an archive log and thus increases the performance of the database
slightly.
301. How would you determine the time zone under which a database was
operating?
SQL>select DBTIMEZONE from dual;
302. Explain the use of setting GLOBAL_NAMES equal to TRUE.
Setting GLOBAL_NAMES dictates how you might connect to a database. This variable
is either TRUE or FALSE and if it is set to TRUE it enforces database links to have the
same name as the remote database to which they are linking.
303. What command would you use to encrypt a PL/SQL application?
WRAP
304. Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.
A function and procedure are the same in that they are intended to be a collection
of PL/SQL code that carries a single task. While a procedure does not have to return
any values to the calling application, a function will return a single value. A package
on the other hand is a collection of functions and procedures that are grouped
together based on their commonality to a business function or application.
305. Explain the use of table functions.
Table functions are designed to return a set of rows through PL/SQL logic but are
intended to be used as a normal table or view in a SQL statement. They are also used
to pipeline information in an ETL process.
306. Explain materialized views and how they are used.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
51
Materialized views are objects that are reduced sets of information that have been
summarized, grouped, or aggregated from base tables. They are typically used in
data warehouse or decision support systems.
307. When a user process fails, what background process cleans up after it?
PMONProcess Monitor
308. What background process refreshes materialized views?
The J ob Queue Processes.
308. Describe what redo logs are.
Redo logs are logical and physical structures that are designed to hold all the
changes made to a database and are intended to aid in the recovery of a
database.
309. How would you force a log switch?
ALTER SYSTEM SWITCH LOGFILE;
310. What does coalescing a tablespace do?
Coalescing is only valid for dictionary-managed tablespaces and de-fragments
space by combining neighboring free extents into large single extents.
311. What is the difference between a TEMPORARY tablespace and a
PERMANENT tablespace?
A temporary tablespace is used for temporary objects such as sort structures while
permanent tablespaces are used to store those objects meant to be used as the true
objects of the database.
312. Name a tablespace automatically created when you create a
database.
The SYSTEM tablespace.
313. When creating a user, what permissions must you grant to allow them to
connect to the database?
Grant the CONNECT to the user.
314. How do you add a data file to a tablespace?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
52
ALTER TABLESPACE <tablespace_name>ADD DATAFILE <datafile_name>SIZE <size>
315. How do you resize a data file?
ALTER DATABASE DATAFILE <datafile_name>RESIZE <new_size>;
316. What view would you use to look at the size of a data file?
DBA_DATA_FILES
317. What view would you use to determine free space in a tablespace?
DBA_FREE_SPACE
318. How can you rebuild an index?
ALTER INDEX <index_name>REBUILD;
319. Explain what partitioning is and what its benefit is.
Partitioning is a method of taking large tables and indexes and splitting them into
smaller, more manageable pieces.
320. You have just compiled a PL/SQL package but got errors, how would you
view the errors?
SHOW ERRORS
321. How can you gather statistics on a table?
The ANALYZE command.
322. How can you enable a trace for a session?
Use the DBMS_SESSION.SET_SQL_TRACE or
Use ALTER SESSION SET SQL_TRACE =TRUE;
323. What is the difference between the SQL*Loader and IMPORT utilities?
These two Oracle utilities are used for loading data into the database. The difference
is that the import utility relies on the data being produced by another Oracle utility
EXPORT while the SQL*Loader utility allows data to be loaded that has been
produced by other utilities from different data sources just so long as it conforms to
ASCII formatted or delimited files.
324. Which of the following statements is true about implicit cursors?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
53
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.
325. Which of the following is not a feature of a cursor FOR loop?
5. Record type declaration.
6. Opening and parsing of SQL statements.
7. Fetches records from cursor.
8. Requires exit condition to be defined.
326 . A developer would like to use referential datatype declaration on a
variable. The variable name is EMPLOYEE_LASTNAME, and the
corresponding table and column is EMPLOYEE, and LNAME, respectively.
How would the developer define this variable using referential datatypes?
9. Use employee.lname%type.
10. Use employee.lname%rowtype.
11. Look up datatype for EMPLOYEE column on LASTNAME table and use
that.
12. Declare it to be type LONG.
327. Which three of the following are implicit cursor attributes?
13. %found
14. %too_many_rows
15. %notfound
16. %rowcount
17. %rowtype
328. If left out, which of the following would cause an infinite loop to occur
in a simple loop?
18. LOOP
19. END LOOP
20. IF-THEN
21. EXIT
329. Which line in the following statement will produce an error?
a. cursor action_cursor is
b. select name, rate, action
c. into action_record
d. from action_table;
e. There are no errors in this statement.
330. The command used to open a CURSOR FOR loop is
a. open
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
54
b. fetch
c. parse
d. None, cursor for loops handle cursor opening implicitly.
331. What happens when rows are found using a FETCH statement
a. It causes the cursor to close
b. It causes the cursor to open
c. It loads the current row values into variables
d. It creates the variables to hold the current row values
332. Read the following code:
CREATE OR REPLACE PROCEDURE find_cpt
(v_movie_id {Argument Mode}NUMBER, v_cost_per_ticket {argument mode}NUMBER)
IS
BEGIN
IF v_cost_per_ticket >8.5
THEN
SELECT cost_per_ticket INTO v_cost_per_ticket
FROM gross_receipt
WHERE movie_id =v_movie_id;
END IF;
END;
Which mode should be used for V_COST_PER_TICKET?
a. IN
b. OUT
c. RETURN
d. IN OUT
333. Read the following code:
CREATE OR REPLACE TRIGGER update_show_gross
{trigger information}
BEGIN
{additional code}
END;
The trigger code should only execute when the column, COST_PER_TICKET, is
greater than $3. Which trigger information will you add?
a. WHEN (new.cost_per_ticket >3.75)
b. WHEN (:new.cost_per_ticket >3.75
c. WHERE (new.cost_per_ticket >3.75)
d. WHERE (:new.cost_per_ticket >3.75)
334. What is the maximum number of handlers processed before the
PL/SQL block is exited when an exception occurs?
a. Only one
b. All that apply
c. All referenced
d. None
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
55
335. For which trigger timing can you reference the NEW and OLD
qualifiers?
a. Statement and Row
b. Statement only
c. Row only
d. Oracle Forms trigger
336. Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget INTO v_yearly_budget
FROM studio
WHERE id =v_studio_id;
RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
a. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget :=GET_BUDGET(11);
b. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget :=GET_BUDGET(11);
c. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget :=GET_BUDGET(11);
d. VARIABLE g_yearly_budget NUMBER
:g_yearly_budget :=GET_BUDGET(11);
337. Read the following code
CREATE OR REPLACE PROCEDURE update_theater
(v_name IN VARCHAR v_theater_id IN NUMBER) IS
BEGIN
UPDATE theater
SET name =v_name
WHERE id =v_theater_id;
END update_theater;
When invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
e. An user defined exception must be declared and associated with the
error code and handled in the EXCEPTION section.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
56
f. Handle the error in EXCEPTION section by referencing the error code
directly.
g. Handle the error in the EXCEPTION section by referencing the
UNIQUE_ERROR predefined exception.
h. Check for success by checking the value of SQL%FOUND immediately
after the UPDATE statement.
337. Read the following code:
CREATE OR REPLACE PROCEDURE calculate_budget IS
v_budget studio.yearly_budget%TYPE;
BEGIN
v_budget :=get_budget(11);
IF v_budget <30000
THEN
set_budget(11,30000000);
END IF;
END ;
You are about to add an argument to CALCULATE_BUDGET. What effect will
this have?
a. The GET_BUDGET function will be marked invalid and must be
recompiled before the next execution.
b. The SET_BUDGET function will be marked invalid and must be recompiled
before the next execution.
c. Only the CALCULATE_BUDGET procedure needs to be recompiled.
d. All three procedures are marked invalid and must be recompiled.
338. Which procedure can be used to create a customized error
message?
a. RAISE_ERROR
b. SQLERRM
c. RAISE_APPLICATION_ERROR
d. RAISE_SERVER_ERROR
339. The CHECK_THEATER trigger of the THEATER table has been
disabled. Which command can you issue to enable this trigger?
a. ALTER TRIGGER check_theater ENABLE;
b. ENABLE TRIGGER check_theater;
c. ALTER TABLE check_theater ENABLE check_theater;
d. ENABLE check_theater;
340. Examine this database trigger
CREATE OR REPLACE TRIGGER prevent_gross_modification
{additional trigger information}
BEGIN
IF TO_CHAR(sysdate, DY) =MON
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
57
THEN
RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on
Monday);
END IF;
END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should
fire only once for the entire DELETE statement. What additional information must
you add?
a. BEFORE DELETE ON gross_receipt
b. AFTER DELETE ON gross_receipt
c. BEFORE (gross_receipt DELETE)
d. FOR EACH ROW DELETED FROM gross_receipt
341. Examine this function:
CREATE OR REPLACE FUNCTION set_budget
(v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
BEGIN
UPDATE studio
SET yearly_budget =v_new_budget
WHERE id =v_studio_id;
IF SQL%FOUND THEN
RETURN TRUEl;
ELSE
RETURN FALSE;
END IF;
COMMIT;
END;
Which code must be added to successfully compile this function?
a. Add RETURN right before the IS keyword.
b. Add RETURN number right before the IS keyword.
c. Add RETURN boolean right after the IS keyword.
d. Add RETURN boolean right before the IS keyword.
342. Under which circumstance must you recompile the package
body after recompiling the package specification?
a. Altering the argument list of one of the package constructs
b. Any change made to one of the package constructs
c. Any SQL statement change made to one of the package constructs
d. Removing a local variable from the DECLARE section of one of the
package constructs
343. Procedure and Functions are explicitly executed. This is different from a
database trigger. When is a database trigger executed?
a. When the transaction is committed
b. During the data manipulation statement
c. When an Oracle supplied package references the trigger
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
58
d. During a data manipulation statement and when the transaction is
committed
344. Which Oracle supplied package can you use to output values and
messages from database triggers, stored procedures and functions within
SQL*Plus?
a. DBMS_DISPLAY
b. DBMS_OUTPUT
c. DBMS_LIST
d. DBMS_DESCRIBE
345. What occurs if a procedure or function terminates with failure without
being handled?
a. Any DML statements issued by the construct are still pending and can
be committed or rolled back.
b. Any DML statements issued by the construct are committed
c. Unless a GOTO statement is used to continue processing within the
BEGIN section, the construct terminates.
d. The construct rolls back any DML statements issued and returns the
unhandled exception to the calling environment.
346. Examine this code
BEGIN
theater_pck.v_total_seats_sold_overall :=theater_pck.get_total_for_year;
END;
For this code to be successful, what must be true?
a. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist only in the body of the
THEATER_PCK package.
b. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of
the THEATER_PCK package.
c. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the
specification of the THEATER_PCK package.
d. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist in the specification of the
THEATER_PCK package.
347. A stored function must return a value based on conditions that are
determined at runtime. Therefore, the SELECT statement cannot be hard-
coded and must be created dynamically when the function is executed.
Which Oracle supplied package will enable this feature?
a. DBMS_DDL
b. DBMS_DML
c. DBMS_SYN
d. DBMS_SQL Top of Form
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
59
ANS
1.1
2.2
3.1
4.(1,3,4)
5.2
6.3
7.4
8.2
9.2
10.(3,4)
11.1
12.4
13.1
14.1
15.3
16.3
17.1
18.(1,4)
19.4
20.3
21.4
22.2
23.4
24.3
25.4
Question 13 all the four answers are wrong , the function executed like this
SQL>select get_budget(11) into :g_yearly_budget from dual;
GET_BUDGET(11)

OR
SQL>print g_yearly_budget.
The Answer to the question 5 is 4rd Choice.
If you are missing the END LOOP (2), the loop do not work, procedure does not
compile.
The Answer to the question 5 is 1rd Choice.
Itis imposible that both 3 and 4 are correct. We do not need location (where) we
need time (when).
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
60
The Answer to the question 5 is 3rd Choice.
The 4rd (Oracle Forms trigger) is in some way correct, but oracle triggers and Forms
triggers are not the same. This question is about Oracle triggers (not Forms).
The answer to the question 13 should be 2.
I tried to do and here is the revised answer list. (T means correct answer choice)
1.)1 : T
2.)2 - 4 : 4 - T
3.)1 : T
4.)(1,3,4) - T
5.)2 - 4 : 4 - T
6.)3 - T
7.)4 - T
8.)2 - 3 - 3 : 3 - T
9.)2 - 4 : 4 - T
10.)(3,4) - 1
11.)1 - [I dont know correct answer]
12.)4 - 3 : 3 - T
13.)1 - ? : 2 - T
Thanks.
348 .What are the various types of Exceptions ? User defined and Predefined
Exceptions.
349 .Can we define exceptions twice in same block ? No.
350 .Can you have two functions with the same name in a PL/SQL block ? Yes.
351.Can you have two stored functions with the same name ? Yes.
352.Can you call a stored function in the constraint of a table ? No.
353.What are the various types of parameter modes in a procedure ? IN, OUT AND
INOUT.
354 .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.
355 .Can functions be overloaded ?
Yes.
356.Can 2 functions have same name & input parameters but differ only by return
datatype
No.
357 .What are the constructs of a procedure, function or a package ?
The constructs of a procedure, function or a package are :
variables and constants
cursors , exceptions
358. Why Create or Replace and not Drop and recreate procedures ?
So that Grants are not dropped.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
61
359. Can you pass parameters in packages ? How ?
Yes. You can pass parameters to procedures or functions in a package.
360. 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
361.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.
(3*2*2=12)
362. 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.
363. What is the maximum no. of statements that can be specified in a trigger
statement ?
One
364. Can views be specified in a trigger statement ? No
365.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
367.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.
368. What are mutating triggers ?
A trigger giving a SELECT on the table on which the trigger is written.
369.What are constraining triggers ?
A trigger giving an Insert/Update on a table having referential integrity constraint on
the triggering table.
370.Describe Oracle database's physical and logical structure ?
Physical : Data files, Redo Log files, Control file.
Logical : Tables, Views, Tablespaces, etc.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
62
371.Can you increase the size of a tablespace ? How ?
Yes, by adding datafiles to it.
ALTER TABLESPACE <tablespace_name>ADD DATAFILE <datafile_name>SIZE <size>
372.Can you increase the size of datafiles ? How ?
YES ____
ALTER DATABASE DATAFILE <datafile_name>RESIZE <new_size>;
373.What is the use of Control files ?
Contains pointers to locations of various data files, redo log files, etc.
374.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
375.What are the advantages of clusters ?
Access time reduced for joins.
376.What are the disadvantages of clusters ?
The time for Insert increases.
377.Can Long/Long RAW be clustered ? No.
378.Can null keys be entered in cluster index, normal index ? Yes.
379.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.

380.What are the min. extents allocated to a rollback extent ?
Two
381.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 :
ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID.

382.What is the difference between unique key and primary key ?
Unique key can be null; Primary key cannot be null.
383.An insert statement followed by a create table statement followed by rollback ?
Will the rows be inserted ?
YES
384.Can you define multiple savepoints ? Yes.
385.Can you Rollback to any savepoint ?Yes.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
63
386.What is the maximum no. of columns a table can have ?
254
387.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.
388. 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. ( ORA -01555) SNAPSHOT TOO OLD WHEN ROLLBACK SEGMENT
INSUFFICIENT
389.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;
390.What are the various types of RollBack Segments ?
Public Available to all instances
Private Available to specific instance

391.Can you use %RowCount as a parameter to a cursor ?
Yes

392.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))
Yes
393. Is the assignment given below allowed :
ABC =PQR (Where ABC and PQR are records)
Yes
394. Is this for loop allowed :
For x in &Start..&End Loop
Yes
395.How many rows will the following SQL return :
Select * from emp Where rownum <10;
9 rows
396.How many rows will the following SQL return :
Select * from emp Where rownum =10;
No rows
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
64
397.Which symbol precedes the path to the table in the remote database ?
@
398.Are views automatically updated when base tables are updated? Yes

399.Can a trigger written for a view? No
400.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
401.A table has the following data : [[5, Null, 10]]. What will the average function
return : 7.5 as Group functions does not consider NULLS
402. Is Sysdate a system variable or a system function?
System Function
403.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 a rollback
and again issue a nextval. What will the output be? 3

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

405. 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. However 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.
406.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

407.What is Auditing?
The database has the ability to audit all actions that take place within it.
a) Login attempts, b) Object Access, c) Database Action
408. Result of Greatest(1,NULL) or Least(1,NULL)
NULL

409.While designing in client/server what are the 2 imp. things to be considered ?
Network Overhead (traffic), Speed and Load of client server

410.What are the disadvantages of SQL ?

Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
65
Disadvantages of SQL are:
Cannot drop a field
Cannot rename a field
Cannot manage memory
Procedural Language option not provided
Index on view or index on index not provided
View updation problem
411.When to create indexes ?
To be created when table is queried for less than 2% or 4% to 25% of the table rows.

412. 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.
413. What is the result of the following SQL:
Select 1 from dual
UNION
Select 'A' from dual;
Error
414.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.
415. Can you alter synonym of view or view?
No
416.Can you create index on view
No.
417.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.

418. What is the difference between alias and synonym?
Alias is temporary and used with one query. Synonym is permanent and not used as
alias.

419. What is the effect of synonym and table name used in same Select statement ?
Valid
420.What's the length of SQL integer?
32 bit length
421.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.

Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
66
422. Can dual table be deleted, dropped or altered or updated or inserted?
Yes

423.If content of dual is updated to some value computation takes place or
not ?
Yes
424 .If any other table same as dual is created would it act similar to dual?
Yes

425. For which relational operators in where clause, index is not used?
<>, like '% ...' is NOT functions, field +constant, field | | ''

426.Assume that there are multiple databases running on one machine. How can you
switch from one to another?
Changing the ORACLE_SID

427.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 tolerance 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.

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

429.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
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
67
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;

430.What are the types of Notation ?
Position, Named, Mixed and Restrictions.

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

432. 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?
Yes

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

434. What are the various types of queries?
Normal Queries
Sub Queries
Co-related queries
Nested queries
Compound queries
435.What is a transaction?
A transaction is a set of SQL statements between any two COMMIT and ROLLBACK
statements.
436. Which of the following is not a schema object : Indexes, tables, public synonyms,
triggers and packages ?
Public synonyms.

Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
68
437. 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.

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

439. 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'

440. 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.
DECLARE
file Handler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler :=UTL_FILE.FOPEN('/home/ oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
441.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. J ust be careful, there is no
"decode" command available.
The syntax is:
wrap iname=myscript.sql oname=xxxx.yyy

442.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.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL
AS
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
69
cur integer;
rc integer;
BEGIN
cur :=DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc :=DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
423. Normalization
It's a technique in which we can design the DB.
During normalization dependencies can be identified which can cause problems
during deletion & updation .It is used in simplifying the structure of table.

1NF-Unnormalised data transfer to normalized form.
2NF-Functional dependencies can be find out & decompose the table without loss of
data.
3NF-Transist dependencies, Every non key attribute is functionally dependant on just
PK.
4NF(BCNF)-The relation which has multiple candidate keys ,then we have to go for
BCNF.

424. Denormalization-
At the same time when information is required from more than one table at faster rate
then it is wiser to add some sort of dependencies.
425. Rolling Forward -To reapply to Data file to all changes that are recorded in Redo
log file due to which data file contains committed & uncommitted data.
426 Does Trigger Accepts arguments?
A Trigger doesn't accept argument & have same name as table or procedure as it
exist in separate namespace.

427. Shared/exclusive LOCKS
Shared/exclusive -When 2 transaction wants to read/write from db at the same time.
Dead- 1trans updates emp and dep
2 trans update dep and emp
428. Dynamic Sql -Which uses late binding
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
70
429. ORACLE INFO
Packages- Encapsulation,Overloading,improve performance as I/O reduces.

PL/SQL Signature Method- To determine when remote dependant object get invalid.

Object Previledge - On a particular object- I/U/D/Exec

System Previledge -Entire collection object -C/A/D

SGA Comprises-Data Buffer, Redo Log Buffer,Shared pool Buffer.

Shared Pool - Req to process unique SQL stmt submitted to DB.
It contains information such as parse tree and execution plan .

PGA -A memory buffer that contains data and control information for a server
process.

Dedicated server - Handles request. For single user.

Multithread Server-Handles request. For multiple user.
Background process-DBWR,LGWR,PMON,SMON,CKPT
DBWR-Writes modified data blocks from DB buffer to data file.

LGWR- writes all the changes been made to redo log buffer

CKPT-Responsible to check DBWR and update control file to indicate most recent
CKPT.

SMON-Instance recovery at Start Up, Clean Temporary Segment.

PMON-Responsible for process recovery and user process fails, cleaning up cache,
freeing a resource which was using process.
Buffer Cache-To improve data block recently used by user in order to improve the
performance.


Data Dictionary -V$SESSION, information abt integrity constraints,space allocated for
schema object.
USER_TAB_COLUMNS gives you a list of tables as per Column.
Queries-- Important
430. 3rd Max
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
71
select distinct sal
from emp a
where 3=(select count(distinct sal)
from emp b
where a.sal=2). Not clear
431. Delete Duplicate rows
Delete Emp
where rowid not in(select max(rowid)
from emp
group by emp_no)

432. First 5 Max No
SQL>SELECT sal FROM(SELECT ABS(-sal) sal FROM emp GROUP BY -sal)
WHERE ROWNUM<6;
433. Views--
-No Aggr function,group by,having
-U/D without PK but not Insert.
-J oin -No DML
-No join-DML
Index-are used for row selection in where and order by only if indexing on column
DBMS_ALERT is a Transaction Processing Package while DBMS_PIPE is an Application
Development package
435. Three Steps in creating DB.--
-Creating physical location for data in tables and indexes to be stored in DB.
-To create the file that still store log entries.
-To create logical structure of data dictionary.

This is accomplished by create DB
1. Back up existing DB.
2.Create or Edit the init.ora file
3.Varify the instance name
4. Start Application management DB tool.
5.start instance
6.Create and Backup the new DB.
Control file -250K
Oracle Administration Assistant for W-NT is a DB management tool that enables to
create DB administartor, operator, Users and role. To manage Oracle DB services, DB
start up, shut down, Edit registry parameter setting, views oracle process information.
Database Configuration Assistant -To create DB
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
72
436. Oracle environment-
OLTP-Many users can read and update, hight response time.
DSS-Read only.
Hybrid-both OLTP & DSS App. are running with this App.
437. RANDOM INFO
Init.ora-is a parameter file like DB_NAME, CONTROL_FILE, DB_BLOCK _SIZE

RowID-BlockIDRowIdDatafileId

Cluster Segment-To support use of cluster on the DB.

Hash Cluster-By placing data in close proximity k/s Hashing.

Index column be in order by clause.
438. DATABASE-
Profile -To control system resources like memory, disk space, and CPU time.
Role -Collection of privileges.
Type of segment- Rollback, Temp, Data, Index

439. Diff bet Trigger and Procedure-

-Trigger need not required to be call (Implicitly fire on event)
-No TCL used
-Proc/fun can be used in trigger
-No use of Long raw,LOB,LONG
-Procedure is prefered over trigger as proc stored in compile form as trigg p_code
stores.

440. TO check time nbetwen 8 am and 6 pm.
Create or replace trigger ptpt
before insert on batch
for each row
declare
A varchar2 (20);
begin
Select substr (to_char (sysdate,'HH: MI: SSSS) 1,2) into a from dual;
If (a between '08' and 18) then
Raise_application_error (-20001,'Invalid Time');
End if;
End;
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
73
441. Snapshot too old-We have to refresh the snapshot
Alter snapshot as
Select * from batch@dmaster.link
Refresh after seven days.
442. We can reduce network traffic-
-By using snapshot
-By storing related table in same tablespace
-By avoiding Row chain.
443. Oracle DB uses three types of file structure.
Data files-store actual data for tablespace, which is a logical unit of storage. Every
tablespace has one or more data file to store actual data for tables, indexes, and
clusters. Data is read and write to data file as needed.
Redo log file-Two or more redo log file make up a logical redo log, which is used to
recover modifications that have not been written to data files in event of power
outage.
Control file-Used at start up to identify the DB and determine which redo log file and
data file are created.
1 data file, 1 control file, 2 redo log file.
444. SET TRANSACTION-We use set transaction statement to login a read only or read-
write or to assign the current transaction to specified rollback segment.
Actual parameter- when call, Formal parameter Parameters define in definition.
445. Sql Statement Execution-
-Reserves an area in memory called Private Sql Area.
-Populate this area with application data.
-Process data in memory area.
-Free the, memory area when execution is complete.
Active set- A set of rows return by a mult-row query.
Export-Putting data of tables in file, which can be, handles by OS.
446.Auditing-
is used for noting down user's activity and statistics about the operations in data
objects. The auditing are
1-Stmt
2-Previliges
3-Object
1-It is done to audit stmt activity .The auditing information abt. date & time of
information, nature of operation is stored in table AUD$ which is used by user sys.
Audit select on itemmaster;
Then app. auditing is done and stored in table .
-To record the usage of privilege
-To record the activity on object.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
74
Nature of Auditing-
Auditing is done on
-Per session basis-one record is generated.
-Per statement basis per session/stmt
Audit any allows user to audit any schema object in the DB.
447. Table partitioning-
Table partitioning divides table data between two or more tablespaces and physical
data file on separate disk.
We can use it to improve transaction throughout and certain type of queries for large
tables.
Restriction-
-A table that is a part of cluster can't be partitioned.
-A table can be partitioned based on ranges column values only.
-Attribute of partitioned table can't include long, long raw or any lob data type.
-Bitmap indexes can't be defined on partitioned tables.
We add partition using ALTER TABLE OR
Create table aa (
a date,
B number
C varchar2 (10))
partion by range(a,b)
(partition pa1 values less than ('01-jan-99', 2) tablespace tsp1,
-----------------------------------);
Accessing partition table-
Select * from aa partion(pa1);
Drop partion
-Alter table AA
drop partion pa1;
448. The UTLBSTAT and UTLESTAT script to get general overview of database 's
performance over a certain period of time.
UTLBSTAT creates table and views containing cumulative database performance
summary information at the time when the script runs .All the objects create by
UTLBSTAT contain word login.
Utlbstat.sql
UTLESTAT creates table and views containing cumulative database performance
summary information at the time when the script runs .All the objects create by
UTLESTAT contain word end.
UTLESTAT spools the results of these SQL statements to a file called REPORT.TXT
Utlestat.sql
449.
Edit the parameter initialization file.
Log_archieve_start =true -turn it on
Log_archieve_dest=c:/oracle/ora81/archieve -location
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
75
log_archieve_format="ARCH%S.LOG" - name format for archieve file .
%S for log sequence number .
By querying the V$SESSION view , we can determine who is logged on ,as well as
information such as the time of logon .
Kill a session - ALTER system kill session '&sid,&serial'
Select Sid,serial#,status from V$session where username='name';
450. Unbalanced Index

if we do have lot of indexes on a table and we are doing I/U/D frequently then there
is a problem of disk contention . To check this problem sees the BLEVEL value in
DBA_INDEXES and if it is 1,2,3,4 then its ok else rebuild the index .
Alter index a_idx1 rebuild unrecoverable ;
451. Detect row chaining and row migration in tables

Row migration occurs when a database block doesnt contain enough free space to
accommodate an update statement. In that case server moves the row to another
block and maintains a pointer to to new block in the rows original block .when
pctfree is 0.
Row chaining in contrast , occurs when no single db block is larger enough to
accommodate a particular row . this is common when table contain several large
data types. It will reside in multiple database blocks .
An unpleasant side effect of both chaining and migration is that the oracle * server
must read more than one db block to read a single row . solution move rows to a
temp table and then delete rows from original table and then insert it from temp table
452. What is the output of SIGN function?
1 for positive value,
0 for Zero,
-1 for Negative value.
453. You want to declare a record variable to have the same structure as
record in a given table. How do you accomplish this?
You can declare it using recordcursorname tablename%ROWTYPE; where recordcursorname
is the name of the cursor variable and tablename is the table in the database on which the
cursor's structure (columns and datatypes) will be modelled.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
76
454. What is the difference between Oracle's Rule Based and Cost Based optimizers?
Rule Based Optimizer (RBO) RBO follows a set of 15 hard-coded rules to generate
query execution plans. It does not take advantage of statistics. RBO is not supported
in Oracle 10g.
Cost Based Optimizer (CBO) CBO uses statistics on tables and indexes to generate
execution plans. CBO analyzes the following information to come up with a query
execution plan: Tables: number of rows, rows per block, etc. Indexes: uniqueness,
number of levels in B*tree structure, etc.
455. How do you raise an exception in PL/SQL?
Use RAISE errormessagename; to raise a previously defined exception (can be a
standard error or custom defined error) or simply Raise; if you want to re-raise an
exception in an exception block.
456. How do you get the error number and error message associated with a given
exception?
SQLCODE gives the error number and SQLERRM gives the error message. Both of these
are predefined Oracle functions.
457. you want to declare a variable in PL/SQL to be of the same type as a column in a
given table. How do you do this?
Use this syntax: variablename tablename.columnname%TYPE;
Example: employeeAgeType employees.emp_age%TYPE;
458. What are the components of physical database structure of Oracle database?
Oracle database is comprised of three types of files. One or more datafiles, two are
more redo log files, and one or more control files.
459. What are the components of logical database structure of Oracle database?
There are tablespaces and database's schema objects.
460. What is a tablespace?
A database is divided into Logical Storage Unit called tablespaces. A tablespace is
used to grouped related logical structures together.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
77
461. What is SYSTEM tablespace and when is it created?
Every Oracle database contains a tablespace named SYSTEM, which is automatically
created when the database is created. The SYSTEM tablespace always contains the
data dictionary tables for the entire database.
462. Explain the relationship among database, tablespace and data file.
Each databases logically divided into one or more tablespaces one or more data files
are explicitly created for each tablespace.
463. What is schema? A schema is collection of database objects of a user.
464. What are Schema Objects? Schema objects are the logical structures that
directly refer to the database's data. Schema objects include tables, views,
sequences, synonyms, indexes, clusters, database triggers, procedures, functions
packages and database links.
465. Can objects of the same schema reside in different tablespaces? Yes.
466. Can a tablespace hold objects from different schemes? Yes.
467. What is Oracle table? A table is the basic unit of data storage in an Oracle
database. The tables of a database hold all of the user accessible data. Table data is
stored in rows and columns.
468. What is an Oracle view? A view is a virtual table. Every view has a query
attached to it. (The query is a SELECT statement that identifies the columns and rows
of the table(s) the view uses.)
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
78
469. Give the stages of instance startup to a usable state where normal users may
access it.
STARTUP NOMOUNT- Instance startup
STARTUP MOUNT- The database is mounted
STARTUP OPEN - The database is opened
470. The most important DDL statements in SQL are:
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
471. Operators used in SELECT statements.
=Equal
<>or !=Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
472. SELECT statements:
SELECT column_name(s) FROM table_name
SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition
value
Note that single quotes around text values and numeric values should not be enclosed in
quotes. Double quotes may be acceptable in some databases.
473. The SELECT INTO Statement is most often used to create backup copies of tables
or for archiving records. ??Kindly Confirm??
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE
column_name operator value
474. The INSERT INTO Statements:
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
79
INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
475. The Update Statement:
UPDATE table_name SET column_name =new_value WHERE column_name =
some_value
476. The Delete Statements:
DELETE FROM table_name WHERE column_name =some_value
Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name
477. Sort the Rows:
SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC
478. The IN operator may be used if you know the exact value you want to return for
at least one of the columns.
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
479. BETWEEN ... AND
SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND
value2 The values can be numbers, text, or dates.
480. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped
even when a child table exists.
481. Why does the following command give a compilation error?
DROP TABLE &TABLE NAME;
Variable names should start with an alphabet. Here the table name starts with an '&'
symbol.
482. Which system tables contain information on privileges granted and privileges
obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
483. Which system table contains information on constraints on all the tables
created?obtained? USER_CONSTRAINTS.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
80
484. State true or false. !=, <>, ^=all denote the same operation? True.
485. State true or false. EXISTS, SOME, ANY are operators in SQL? True.
486. What is the advantage of specifying WITH GRANT OPTION in the GRANT
command?
The privilege receiver can further grant the privileges he/she has obtained from the
owner to any other user.
487. Which command executes the contents of a specified file? START or @.
488. What is the value of comm and sal after executing the following query if the initial
value of sal is 10000
UPDATE EMP SET SAL =SAL +1000, COMM =SAL*0.1;?
sal =11000, comm =1000.
489. which command displays the SQL command in the SQL buffer, and then
executes it? RUN.
490. What command is used to get back the privileges offered by the GRANT
command? REVOKE.
491. What will be the output of the following query? SELECT
DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.
Explanation : The query checks whether a given string is a numerical digit.
492. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.
493. What operator performs pattern matching? LIKE operator.
494. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
495. What operator tests column for the absence of data? IS NULL operator.
496. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all.
497. Which function is used to find the largest integer less than or equal to a specific
value? FLOOR.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
81
498. Which is the subset of SQL commands used to manipulate Oracle Database
structures, including tables?
Data Definition Language (DDL).
499. What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows
from table in descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted
on ENAME in descending order.
500. What command is used to create a table by copying the structure of another
table?
CREATE TABLE .. AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain
a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be
copied to the new table.
501. What are the wildcards used for pattern matching.?
_ for single character substitution and % for multi-character substitution.
502. What is the parameter substitution symbol used with INSERT INTO command? &
503. What's an SQL injection?
SQL Injection is when form data contains an SQL escape sequence and injects a new
SQL query to be run.
504. What is a join? Explain the different types of joins?
J oin is a query, which retrieves related columns or rows from multiple tables.
Self J oin - J oining the table with itself.
Equi J oin - J oining two tables by equating two common columns.
Non-Equi J oin - J oining two tables by equating two common columns.
Outer J oin - J oining two tables in such a way that query can also retrieve rows that do
not have corresponding join value in the other table.
505. What is the sub-query?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
82
Sub-query is a query whose return values are used in filtering conditions of the main
query.
506. What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long,
blockno, rownumber are the components of ROWID.
507. What is the fastest way of accessing a row in a table? Using ROWID.
508. What is an integrity constraint?
Integrity constraint is a rule that restricts values to a column in a table.
509. What is referential integrity constraint?
Maintaining data integrity through a set of rules that restrict the values of one or more
columns of the tables based on the values of primary key or unique key of the
referenced table.
510. What is the usage of SAVEPOINTS?
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling
back part of a transaction. Maximum of five save points are allowed.
511. What is ON DELETE CASCADE?
When ON DELETE CASCADE is specified Oracle maintains referential integrity by
automatically removing dependent foreign key values if a referenced primary or
unique key value is removed.
512. What are the data types allowed in a table?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.
513. What is difference between CHAR and VARCHAR2? What is the maximum SIZE
allowed for each type?
CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank
spaces. For CHAR the maximum length is 255 and 2000 is for VARCHAR2.
514. How many LONG columns are allowed in a table? Is it possible to use LONG
columns in WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or
ORDER BY clause.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
83
515. What are the pre-requisites to modify datatype of a column and 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.
516. Where the integrity constraints are stored in data dictionary?
The integrity constraints are stored in USER_CONSTRAINTS.
517. How will you activate/deactivate integrity constraints?
The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE
CONSTRAINT / DISABLE CONSTRAINT.
518. If unique key constraint on DATE column is created, will it validate the rows that
are inserted with SYSDATE?
It won't, Because SYSDATE format contains time attached with it.
519. What is a database link?
Database link is a named path through which a remote database can be accessed.
520. How to access the current value and next value from a sequence? Is it possible
to access the current value in a session before accessing next value?
Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you
access next value in the session, current value can be accessed.
521.What is CYCLE/NO CYCLE in a Sequence?
CYCLE specifies that the sequence continue to generate values after reaching either
maximum or minimum value. After an ascending sequence reaches its maximum
value, it generates its minimum value. After a descending sequence reaches its
minimum, it generates its maximum.
NO CYCLE specifies that the sequence cannot generate more values after reaching
its maximum or minimum value.
522. What are the advantages of VIEW?
- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.
523. Can a view be updated/inserted/deleted? If Yes - under what conditions?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
84
A View can be updated/deleted/inserted if it has only one base table if the view is
based on columns from one or more tables then insert, update and delete is not
possible.
524. If a view on a single base table is manipulated will the changes be reflected on
the base table?
If changes are made to the tables and these tables are the base tables of a view,
then the changes will be reference on the view.
525. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.
526. Which of the following is not a feature of a cursor FOR loop?
1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.
527. A developer would like to use referential datatype declaration on a variable. The
variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is
EMPLOYEE, and LNAME, respectively. How would the developer define this variable
using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.
528. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype
529. If left out, which of the following would cause an infinite loop to occur in a simple
loop?
1. LOOP
2. END LOOP
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
85
3. IF-THEN
4. EXIT
560. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.
561. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.
562. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values
563. Read the following code:
1. CREATE OR REPLACE PROCEDURE find_cpt
2. (v_movie_id {Argument Mode}NUMBER, v_cost_per_ticket {argument mode}NUMBER)
3. IS
4. BEGIN
5. IF v_cost_per_ticket >8.5 THEN
6. SELECT cost_per_ticket
7. INTO v_cost_per_ticket
8. FROM gross_receipt
9. WHERE movie_id =v_movie_id;
10. END IF;
11. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT
564. Read the following code:
1 CREATE OR REPLACE TRIGGER update_show_gross
2 {trigger information}
3 BEGIN
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
86
4 {additional code}
5 END;
The trigger code should only execute when the column, COST_PER_TICKET, is greater
than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket >3.75)
2. WHEN (:new.cost_per_ticket > 3.75)
3. WHERE (new.cost_per_ticket >3.75)
4. WHERE (:new.cost_per_ticket >3.75)
565. What is the maximum number of handlers processed before the PL/SQL block is
exited when an exception occurs?
1. Only one
2. All that applies
3. All referenced
4. None
567. which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row
2. Statement only
3. Row only
4. Oracle Forms trigger
568. Read the following code:
CREATE OR REPLACE FUNCTION get_budget (v_studio_id IN NUMBER)
RETURN NUMBER IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget INTO v_yearly_budget FROM studio WHERE id =v_studio_id;
RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget :=GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget :=GET_BUDGET(11);
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
87
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget :=GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
569. When invoking this procedure, you encounter the error:
ORA-000:Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. CREATE OR REPLACE PROCEDURE update_theater
2. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
3. BEGIN
4. UPDATE theater
5. SET name =v_name
6. WHERE id =v_theater_id;
7. END update_theater;
1. An user defined exception must be declared and associated with the error code
and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR
predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately after the
UPDATE statement.
570. Read the following code:
CREATE OR REPLACE PROCEDURE calculate_budget IS
v_budget studio.yearly_budget%TYPE;
BEGIN
v_budget :=get_budget(11);
IF v_budget <30000
THEN
set_budget(11,30000000);
END IF;
END;
You are about to add an argument to CALCULATE_BUDGET. What effect will
this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled
before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled
before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.
571. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
88
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR
572. The CHECK_THEATER trigger of the THEATER table has been disabled.
Which command can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;
573. Examine this database trigger
CREATE OR REPLACE TRIGGER prevent_gross_modification
{additional trigger information}
BEGIN
IF TO_CHAR(sysdate, DY) =MON
THEN
RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
END IF;
END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table.
It should fire only once for the entire DELETE statement. What additional
information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt
574. Examine this function:
CREATE OR REPLACE FUNCTION set_budget (v_studio_id IN NUMBER, v_new_budget IN
NUMBER) IS
BEGIN
UPDATE studio
SET yearly_budget =v_new_budget
WHERE id =v_studio_id;
IF SQL%FOUND THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
COMMIT;
END;
Which code must be added to successfully compile this function?
1. Add RETURN right before the IS keyword.
2. Add RETURN number right before the IS keyword.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
89
3. Add RETURN Boolean right after the IS keyword.
4. Add RETURN Boolean right before the IS keyword.
578. Under which circumstance must you recompile the package body after
recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the
package constructs
579. Procedure and Functions are explicitly executed. This is different from a database
trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed
580. Which Oracle supplied package can you use to output values and messages
from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE
581. What occurs if a procedure or function terminates with failure without being
handled?
1. Any DML statements issued by the construct are still pending and can be
committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section,
the construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled
exception to the calling environment.
582. Examine this code
BEGIN
theater_pck.v_total_seats_sold_overall:=theater_pck.get_total_for_year;
END;
For this code to be successful, what must be true?
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR
function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the
THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the
specification of the THEATER_PCK package.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
90
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist in the specification of the
THEATER_PCK package.
583. A stored function must return a value based on conditions that are determined at
runtime. Therefore, the SELECT statement cannot be hard-coded and must be
created dynamically when the function is executed. Which Oracle supplied package
will enable this feature? ?????
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL
584 How to select last N records from a Table?
Select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm) where a >( select
(max(rownum)-10) from clm) Here N =10
585. The following query has a Problem of performance in the execution of the
following
query where the table ter.ter_master have 22231 records. So the results are obtained
after hours.
Cursor rem_master(brepno VARCHAR2) IS
select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno ='ALL' or a.repno >brepno)
Order by a.repno
What are steps required tuning this query to improve its performance?
-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO
-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution
path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that
your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:
SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno ='ALL' or a.repno >a.brepno)
ORDER BY a.repno;
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
91
586. What is the difference between Truncate and Delete interms of Referential
Integrity?
DELETE removes one or more records in a table, checking referential Constraints (to
see if there are dependent child records) and firing any DELETE triggers. In the order
you are deleting (child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it
only checks for the existence (and status) of another foreign key Pointing to the
table. If one exists and is enabled, then you will get the following error. This
is true even if you do the child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing
the TRUNCATE command, then re-enable them afterwards.
587. Describe the use of PL/SQL tables
PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can
be used to hold values for use in later queries or calculations. In Oracle 8 they will be
able to be of the %ROWTYPE designation, or RECORD.
588. When is a declare statement needed?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand
alone, non-stored PL/SQL procedures. It must come first in a PL/SQL stand
alone file if it is used.
589. In what order should a open/fetch/loop set of commands in a PL/SQL block be
implemented if you use the NOTFOUND cursor variable in the exit when statement?
Why?
OPEN then FETCH then LOOP followed by the exit when. If not specified in this order
will result in the final return being done twice because of the way the %NOTFOUND is
handled by PL/SQL.
589. What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?
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.
590. How can you find within a PL/SQL block, if a cursor is open?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
92
Use the %ISOPEN cursor status variable.
591. How can you generate debugging output from PL/SQL?
Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW
ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used
to show intermediate results from loops and the status of variables as the procedure is
executed. The new package UTL_FILE can also be used.
592. What are the types of triggers?
There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE,
AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT etc.
593. What is 3rd normal form?
All items are atomic, all tables have a primary key, every row is determined by its
primary key, there are no duplicate rows, every column is dependent on ONLY the
primary key.
594. What are cascading triggers? Executing one trigger may cause another trigger
to also be executed.
595. What are snapshots? Snapshots are copies of remote data, based upon queries.
In their simplest form, they can be thought of as a table created by a command such
as: create table t as select * from z;
596. What Oracle package allows you to schedule one-off or recurring jobs in your
database? DBMS_J OBS
597. What happens if a tablespace clause is left off a primary key constraint?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
93
This results in the index automatically generated being placed in the users' default
tablespace, which is usually the same tablespace as where the table is being
created which can cause performance problems.
598. Where is most tuning done? 80-90 percent at application level, 10-20 percent at
database level.
599. What is a mutating table? A mutating table is a table that is in the process of
being modified by an UDPATE, DELETE or INSERT statement. For example, if your trigger
contains a select statement or an update statement referencing the table it is
triggering off of you will receive the error.
600. What is a bind variable and why is it important?
A bind variable is a placeholder in a query. The way the Oracle shared pool (a
very important shared memory data structure) operates is predicated on
developers using bind variables.
601. How are reads and writes handled in Oracle that is different than almost every
other database? Reads are not blocked by writes.
602. Why should you care about the NLS_DATE_FORMAT?
Because its' value (dd-mon-yy or dd-mon-rr) determines the results of your date
arithmetic when you are dealing with years of 99 and 00..nn.
603. What is the purpose of the SUBSTR string function? To return a specified substring
from a string.
604. What's the difference between an Equijoins and a self-join?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
94
An Equijoins does an equality test between two fields in two different tables; a self
join does the same thing on a copy of the same table.
605. In a Select statement, what is the difference between a & and &&?
Both pass in values at runtime, but if the && is used the user will not be bothered
with a second prompt for the value.
606. What is the TRANSLATE function? TRANSLATE is a simple function that does an
orderly character-by-character substitution in a string. The format is
TRANSLATE(string,if,then). Example: select TRANSLATE (7671234,234567890,'BCDEFGHIJ ')
from DUAL; The result would be: GFG1BCD. I have found this useful during some data
migrations where special characters needed to be translated.
607. What are PL/SQL Tables (or Arrays)? This is dependent upon your Oracle version.
PL/SQL Tables have only one dimension, but after PL/SQL 2.3 that dimension could be
a record. Their main advantage is that when relatively small tables must be constantly
consulted, if they can be put in memory via a PL/SQL table, performance can be
enhanced.
608. What's the most important 'Best Practice' guideline you follow? Ask for Help if you
find yourself spending more than 30 minutes to solve a problem. I follow this advice
when at a client site; when I'm at home, I act like the Duracell bunny and just keep
going and going.
609. What's another Best Practice? Make code reviews a regular part of your
development process.
610. Describe the PL/SQL Block structure. Declare Begin Exception End
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
95
611. Describe a nested PL/SQL Block. Declare Begin Begin End; Begin End; End;
612. What is %TYPE used for? v_min_bal sales.balance%TYPE :=10.00; - the var
v_min_bal takes on the Type of sales.balance and the value of 10.00.
613. What is %ROWTYPE used for? Similar to %TYPE but for a record, not just a field.
614. What is an anonymous block? A PL/SQL Block without a name.
615. Is PL/SQL truly compiled when stored in the database or is it interpreted? PL/SQL
on the server is run in much the same fashion as J ava is run anywhere. PL/SQL is
compiled into PCode and the PCode is interpreted at runtime.
616. What is the purpose of the PL/SQL FETCH command? The FETCH command
retrieves values returned by the cursor from the active set into the local variables.
617. What does truncating a table do? It deletes the data from the table.It resets the
high water mark for a table if the REUSE STORAGE clause is not used.
618. Why is the high water mark important? The high water mark is used in association
with each individual table and tells Oracle 1. Where
to start loading data during a SQL*Loader process 2. How far
to scan a table's information when doing a full-table scan.
619. What does the TO_NUMBER function do? It converts VARCHAR2 values to
numbers.
620. What is the default length of the CHAR column? 1
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
96
621. What is the purpose of a referential integrity constraint? Enforce the rule that a
child foreign key must have a valid parent primary key.
622. What is the purpose of the SQL*Plus command GET? Get the contents of a
previously saved operating system file into the buffer.
623. What is the order of the stages of the system development cycle?
1. Strategy and analysis
2. Design
3. Build and document
4. Transition
5. Production.
624. in a SELECT statement, which character is used to pass in a value at runtime? The
'&' character or the '&&' characters.
625. What is DNS? What does it stand for and why do we care that it exists? Dynamic
Name Server is what allows us to type in names instead of IP addresses to get to Web
servers, use Telnet, FTO, etc.
626. What are realms? Application security in Oracle Applications is maintained and
managed by assigning responsibilities, excluding attributes, and securing attributes to
users. Internet Procurement 11i uses a security realm as an additional layer for
application security. A security realm is a list of objects (item source or a category) to
which a user is granted access.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
97
627. What occurs during the production phase of the system development cycle?
Perform normal routine maintenance.
628. A database trigger is fired automatically when what is executed? A DML
statement
629. In a PL/SQL block, what needs to be followed with a semicolon? All SQL
statements, all PL/SQL statements and the END clause
630. What character do you type to execute an anonymous block? The / character.
631. What data type is used to store large binary objects outside the database? The
BFILE data type
632. Which variable type accepts only character strings of a specified length? CHAR
633. Which variable type accepts any length of character up to 32767 bytes?
VARCHAR2
634. What operator is used to assign a value to a variable that doesn't have a typical
value? :=
635. What keyword is used to assign a value to a variable that has a typical value?
DEFAULT
636. How frequently are block declared variables initialized? Every time a block is
executed
637. With which symbol do you prefix a bind variable when you reference it in PL/SQL? :
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
98
638. What are two statements that are true about the INTO clause? 1. You have to
specify the same number of variables in the INTO clause as the values returned by the
SELECT statement. 2. The data types of the variables specified in the INTO clause need
to correspond with the values returned by the SELECT statement.
639. What keyword is used when you populate a host variable from the SQL prompt?
The VARIABLE keyword
640. How do you end each SQL statement in a PL/SQL block? With a ;
641. Can you have more than one transaction in a PL/SQL block? Yes
642. What is common among these cursor attributes; SQL%FOUND, SQL%NOTFOUND,
SQL%ISOPEN? They are all Boolean attributes.
643. What does it mean when the cursor attribute SQL%FOUND returns the result TRUE?
The most recent SQL statement issued affects one or more rows.
645. What are two true statements concerning the index in a FOR loop?
1. You can't reference it outside the loop.
2. You can use an expression to reference its existing value within the loop.
646. How do you begin defining a record type? TYPE emp_record_type IS RECORD.
647. Do PL/SQL records have a predefined data type? No.
648. Give an example of the correct syntax to reference a row in a PL/SQL table.
Dept_table(15)
649. The primary key of a PL/SQL table must be of what data type? Scalar
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
99
650. What is the term used for the rows produced by a query? Active set
651. Name three things that are true about explicit cursors. 1.
They are manipulated through specific statements in the block's executable actions.
2. They individually process each row returned by a multi row SELECT statement. 3.
They need to be declared and named before they can be used.
652. Name two things true about cursor FOR loops.
1. They process rows in an explicit cursor.
2. They automate processing as the cursor is automatically opened and the rows fetched for
each iteration in the loop, and the cursor is closed when all the rows have been processed.
653. What are four attributes that provide status information about a cursor? 1.
%ISOPEN 2. %NOTFOUND 3 . %FOUND 4. %ROWCOUNT
654. Describe at least one way explicit cursor attributes are used.
1. %ISOPEN 2. %NOTFOUND 3. %FOUND 4. %ROWCOUNT
655. What clause do you use to apply updates and deletes to the row currently being
addressed, without having to explicitly reference the ROWID?
You can use the explicit cursor attributes to test the success of each fetch before any further
references are made to the cursor.
656. How long does the Oracle server wait if it cannot acquire the locks on the rows it needs in
a SELECT FOR UPDATE? Indefinitely
657. Name three things about using cursors with parameters.
1. You can use parameters to pass values to a cursor when it is open.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
100
2. Parameters are used in a query when it executes.
3. In the OPEN statement, each formal parameter in the cursor declaration must have a
corresponding real parameter.
658. Name three things true about trapping exceptions.
1. When an exception occurs, PL/SQL processes only one handler before leaving the block.
2. If you use the OTHERS clause, it should be placed last of all the exception-handling clauses.
3. Exceptions cannot appear in assignment statements or SQL statements.
659. Describe two aspects about exceptions.
1. Once an Oracle error occurs, the associated exception is raised automatically.
2. You can raise an exception explicitly by issuing the RAISE statement within the block.
660. What exception occurs when the conversion of a character string to a number fails?
INVALID_NUMBER
661. Name three things about user-defined exceptions.
1. When defining your own exceptions, you need to declare them in the DECLARE section of a
PL/SQL block.
2. They are raised explicitly with RAISE statements.
3. You need to reference your declared exception within the corresponding exception-
handling routine.
662. What's another Best Practice?
Set standards and guidelines for your application before anyone starts writing code.
1. Selection of development tools
2. How SQL is written in PL/SQL code.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
101
3. How the exception handling architecture is designed.
4. Processes for code review and testing.
663. Explain the relationship between a Conceptual Data Model (CDM) and a Physical Data
Model (PDM). Most of the objects in the logical model correspond to a related object in the
physical model, e.g. the logical model contains entities, attributes, and key groups, which are
represented in the physical model as tables, columns, and indexes, respectively. The CDM
allows the designer to concentrate solely on defining the objects in the information system and
the relationships between them, without having to consider the numerous parameters
associated with the physical implementation such as data integrity constraints, data access
speed and data storage efficiency. The CDM thus provides a clear and succinct picture of the
information system, which is independent of the targeted DBMS. A single CDM may therefore
be associated with a number of PDMs targeting different DBMSs. The conceptual level
schema, should present to the user a simple, physical implementation-independent clear view
of the format of the data sets and their descriptions. A Conceptual Data Model lays the
foundation for building shared databases and re-engineering the business.
664. Elaborating on 74, describe conceptual vs logical vs physical designs.
Conceptual database design is the process of building a model of the essential part of the
enterprise business process and the used information, independent of all physical
considerations. Logical database design - The process of constructing a model of information
used in an enterprise based on a specific data model, using natural objects of information and
natural associations between them. The model of information is independent of a particular
implementation and other physical consideration. Physical database design - The process of
producing a description of the implementation of the database on secondary storage. It
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
102
describes the storage structures and access methods used to achieve efficient access to the
data.
665. What is a pseudo-column? A pseudo-column is a "column" that yields a value when
selected, but which is not an actual column of the table.
666. What are the more common pseudo-columns? sequence.CurrVal, sequence.NextVal,
RowID, RowNum, SysDate, UID, User
667. What is the difference between VARCHAR and VARCHAR2? The VARCHAR data type is
currently synonymous with the VARCHAR2 data type. It is recommended that you use
VARCHAR2 rather than VARCHAR. In a future version of Oracle, VARCHAR might be a
separate data type used for variable length character strings compared with different
comparison semantics.
668. Give an example of overloaded Built-in functions.
date_string :=TO_CHAR (SYSDATE, 'MMDDYY'); number_string :=TO_CHAR (10000); If
overloading was not supported in PL/SQL (TO_CHAR is a function in the STANDARD package),
then two different functions would be required to support conversions to character format.
669. What is the difference between call and execute sqlplus commands.? The CALL
statement is SQL(and only understands SQL types). EXEC is really shorthand for begin/end;.
670. What is another name for ref cursors? cursor variables
671. What data type column can not be used with INTERSECT? LONG
672. When is the MINUS keyword used? To remove those rows which are retrieved by one
SELECT from those retrieved by another SELECT statement.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
103
673. Give an example of the MINUS keyword. List the numbers of all managers who do not hold
advanced degrees. SELECT MGRNO FROM DEPT WHERE MGRNO IS NOT NULL MINUS SELECT
EMPNO FROM EMP WHERE EDLEVEL >=18;
674. When is the INTERSECT keyword used? To return only those rows that are the result of two
or more SELECT statements.
675. Give an example of the INTERSECT keyword. List the numbers of all managers who do not
hold advanced degrees. SELECT MGRNO FROM DEPT WHERE MGRNO IS NOT NULL INTERSECT
SELECT EMPNO FROM EMP WHERE EDLEVEL <18;
676. Write a query to find the duplicate record(s) of column a, b and c in a table of columns
a..z. SELECT count(*), a, b, c FROM t GROUP BY a, b, c HAVING COUNT(*) >1;
677. Give an example of the NOT keyword.SELECT c FROM t WHERE c !='x'; SELECT c FROM t
WHERE NOT c ='x';
678. Give an example of the LIKE keyword.
SELECT c FROM t WHERE c LIKE '_EU%L'; ie the first character can be any character, the next
two must be EU and the last must be L. Any number of chararcters or numbers could be
between the U and L.
679. What is SQLCODE?
A predefined symbol that contains the Oracle error status of the previously executed PL/SQL
statement. If a SQL statement executes without errors, SQLCODE is equal to 0.
680. What is SQLERRM? A PL/SQL symbol that contains the error message associated with
SQLCODE. If a SQL statement executes successfully, SQLCODE is equal to 0 and SQLERRM
contains the string ORA-0000: normal, successful completion
681. What is ROWNUM?
A pseudocolumn that indicates the order of the retrieved row. The ROWNUM for the first
returned row is 1, ROWNUM can limit the number of rows that are returned by a query.
682. What are the benefits of using the PLS_INTEGER Data type in PL/SQL?
If you have a whole-number counter, for example in a loop or record counter, consider using
a data type of PLS_INTEGER instead of INTEGER or NUMBER. When declaring an integer
variable, PLS_INTEGER is the most efficient numeric data type because its values require less
storage than INTEGER or NUMBER values, which are represented internally as 22-byte Oracle
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
104
numbers. Also, PLS_INTEGER operations use machine arithmetic, so they are faster than
BINARY_INTEGER, INTEGER, or NUMBER operations, which use library arithmetic.
683. Explain the difference between NVL and NVL2.
NVL(expr1,expr2); NVL2(expr1,expr2,expr3); NVL - If expr1 is null then return expr2 else return
expr1. NVL2 - If expr1 is not null then the function will return expr2. Otherwise, the function will
return expr3. The expr1 can have any data type and arguments expr2 and expr3 can be of
any data type other than LONG. The data type of the return value is that of expr2.
684. Describe RTRIM.
RTRIM (string [,'set']) RTRIM is the opposite of RPAD and similar to LTRIM. The function removes
characters from the right-hand portion of a string. The string passed as the first parameter is
returned with all characters contained in the string passed as the second parameter removed
from the right of the last character not found in the remove string. The second parameter is
optional and defaults to a single space. rtrim('ORACLE UPDATE ') -->'ORACLE UPDATE' rtrim('ORACLE
UPDATE','EDATPU') -->'ORACLE ' rtrim('ORACLE UPDATE',' EDATPU') -->'ORACL'
685. Describe UNION and UNION ALL. UNION returns distinct rows selected by both queries
while UNION ALL returns all the rows. Therefore, if the table has duplicates, UNION will remove
them. If the table has no duplicates, UNION will force a sort and cause performance
degradation as compared to UNION ALL.
686. What is 1st normal form? Each cell must have one and only one value, and that value
must be atomic: there can be no repeating groups in a table that satisfies first normal form.
687. What is 2nd normal form? Every nonkey column must depend on the entire primary key.
688. What is 3rd normal form? (another explanation than #1)
No nonkey column depends on another nonkey column.
689. What is 4th normal form? Fourth normal form forbids independent one-to-many
relationships between primary key columns and nonkey columns.
700. What is 5th normal form? Fifth normal form breaks tables into the smallest possible pieces
in order to eliminate all redundancy within a table. Tables normalized to this extent consist of
little more than the primary key.
701. What does pragma mean to Oracle? A pragma is simply a compiler directive, a method
to instruct the compiler to perform some compilation option.
702. What is a Latch? A Latch is a low level serialization mechanism that ( released as quickly
as it is acquired ) protects shared data structures. A process acquires and holds the latch as
long as the the data structure is in use. The basic idea is to prevent concurrent access to
shared data structures in the SGA. In case the process dies without releasing the latch, the
PMON process will clean up the lock on the data structure and release the latch. If a process is
not able to obtain a latch, it must wait for the latch to be freed up by the process holding it.
This causes additional spinning ( looking for availability at fixed intervals of time ) of the
process, thereby causing extra load on the CPU. This process will spin until the latch is
available. A dba has to monitor the latches for contention and make sure that CPU cycles are
not being burnt on process spinning.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
105
703. Does ROLLUP work with multiple columns? The ROLLUP feature can in fact be applied to
multiple columns. The result is multiple levels of rollup, as illustrated here:
select deptno, job, count(*), grouping(deptno), grouping(job)
from emp group by rollup(deptno, job); DEPTNO J OB COUNT(*) GROUPING(DEPTNO) GROUPING(J OB)
10 CLERK 1 0 0 10
MANAGER 1 0 0 10
PRESIDENT 1 0 0
10 3 0 1
20 ANALYST 2 0 0 20 CLERK 2
0 0 20 MANAGER 1 0
0 20 5 0 1
30 CLERK 1 0 0
30 MANAGER 1 0 0
30 SALESMAN 4 0 0 30
6 0 1 14 1 1 As shown in this example, we're able to count the employees by 1) department and
job; 2) department; and 3) grand total.
704. What is an inline view? A sub query in the from clause of your main query.
705. Give an example of an inline view and Top-N Query.
SELECT ename, job, sal, rownum FROM (SELECT ename, job, sal FROM emp ORDER BY sal)
WHERE rownum <=3; SMITH CLERK 800 1 J AMES CLERK 950 2 ADAMS CLERK 1100 3
706. What SQL*Plus command is useful for determining whether the "N rows selected" message
will appear? Feedback
707. What SQL*Plus keyword is used for defining formats for how SQL*Plus displays column
information? Set
708. This phrase describes a query that feeds one row of results to a parent query for the
purpose of selection when the exact where clause criteria is not known? Single-row subquery.
709. Use of what command requires that you first run the plustrce.sql script? autotrace
710. The database for an international athletic competition consists of one table, ATHLETES,
containing contestant name, age, and represented country. To determine the youngest
athlete representing each country, how do you write the code?
SELECT name, country, age FROM athletes WHERE ( country, age ) IN ( SELECT country,
min(age) FROM athletes GROUP BY country);
711. What is a single-row sub query? The main query expects the subquery to return only one
value.
712. What is an inline view? A sub query in a from clause used for defining an intermediate
result set to query from.
713. What does AUTOTRACE do? Allows us to see the execution plan of the queries we've
executed and the resources they used, without having to use the EXPLAIN PLAN command.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
106
714. What does SQL_TRACE do? Enables logging of all application SQL, performance stats and
query plan used.
715. What does TKPROF do? Formats the raw trace files into a readable report.
716. What are the two main index types that Oracle uses? B*Tree and Bitmap
718. When are Bitmap indexes appropriate? In situations of low cardinality data, i.e. data with
few distinct values.
719. What is a top-n query? select * from ( select ename from emp order by sal ) where
rownum <=3; In general it refers to getting the top-n rows from a result set.
720. What is PostgreSQL? PostgreSQL is a sophisticated Object-Relational DBMS, supporting
almost all SQL constructs, including subselects, transactions, and user-defined types and
functions. It is the most advanced open-source database available anywhere. Commercial
Support is also available.
721. What are the three main reasons for partitioning a database? 1. To increase availability
(derived from the fact that partitions are independent entities). 2. To ease administration
burdens (derived from the fact that performing operations on small objects is inherently easier,
faster, and less resource intensive than performing the same operation on a large object). 3. To
enhance DML and query performance (potential to perform parallel DML).
722. What are the two types of cursors? Implicit (Oracle's) and explicit (yours).
723. Does the order of stored procedures in a package matter?
It does if one procedure calls another; if that happens, the calling procedure must be the earlier of
the two.
722. What is a NOCOPY parameter? Where it is used?
NOCOPY Parameter Option
Prior to Oracle 8i there were three types of parameter-passing options to procedures and
functions:
IN: parameters are passed by reference
OUT: parameters are implemented as copy-out
IN OUT: parameters are implemented as copy-in/copy-out
The technique of OUT and IN OUT parameters was designed to protect original values of them in case
exceptions were raised, so that changes could be rolled back. Because a copy of the parameter set
was made, rollback could be done. However, this method imposed significant CPU and memory
overhead when the parameters were large data collectionsfor example, PL/SQL Table or VARRAY
types.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
107
With the new NOCOPY option, OUT and IN OUT parameters are passed by reference, which avoids
copy overhead. However, parameter set copy is not created and, in case of an exception rollback,
cannot be performed and the original values of parameters cannot be restored.
Here is an example of using the NOCOPY parameter option:
TYPE Note IS RECORD( Title VARCHAR2(15), Created_By VARCHAR2(20), Created_When DATE,
Memo VARCHAR2(2000));TYPE Notebook IS VARRAY(2000) OF Note;CREATE OR REPLACE PROCEDURE
Update_Notes(Customer_Notes IN OUT NOCOPY Notebook) ISBEGIN ...END;
724. What are the advantages & disadvantages of packages ?
Advantages: Modular approach, Encapsulation/hiding of business logic, security, performance
improvement, reusability
Disadvantages: More memory may be required on the Oracle database server when using Oracle
PL/SQL packages as the whole package is loaded into memory as soon as any object in the package
is accessed.
725. Mention the differences between aggregate functions and analytical functions clearly with
examples?
Aggregate functions are sum(), count(), avg(), max(), min()
like: select sum(sal) , count(*) , avg(sal) , max(sal) , min(sal) from emp;
analytical fuction differ from aggregate function
some of examples:
SELECT ename "Ename", deptno "Deptno", sal "Sal", SUM(sal) OVER (ORDER BY deptno, ename) "Running Total",
SUM(SAL) OVER (PARTITION BY deptno
ORDER BY ename) "Dept Total", ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY ENAME) "Seq"
FROM emp ORDER BY deptno, ename
SELECT * FROM (
SELECT deptno, ename, sal, ROW_NUMBER()
OVER ( PARTITION BY deptno ORDER BY sal DESC )
Top3 FROM emp
)
WHERE Top3 <=3
SELECT * FROM ( SELECT deptno, ename, sal, DENSE_RANK() OVER (
PARTITION BY deptno ORDER BY sal desc
) TopN FROM emp
)
WHERE TopN <=3
ORDER BY deptno, sal DESC
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
108
726. what is the difference between database trigger and schema trigger?
Database triggers are executed in response to particular events on tables in a databaseSchema
triggers are fired when schema objects (tables) are modified. It can be like before create, later,drop
'Whats the diff. between database triggers on database or schema?
Database triggers can be system triggers on a database or a schema.
With a database,triggers fire for each event for all users...
With a schema,triggers fire for each event for that specific user...
May be the question is like this...
In database trigger: Trigger for a table /view is a database trigger
like ( before , insert * update, delete, insert * row level, statement level)
2 * 3 * 2 =12 +instead off trigger for views
schema triggers reffersto : before logoff, after logon, before create, drop, alter on schema ( these
trigger are also called DDL trigger)
Application trigger: before shutdown, after startup, on error (any error occur in database, after
starting the orcalce instance, before closing the instance)
727. what is the difference between database server and data dictionary
Database Server have many schemas, and users, it has only one instance for the organisation, or lets
say its an instance of the data with all schema info whereas the data dictionary contains raw data, of
the entire data of the database alongwith compiled code of all packages, procedures, funtions and
the all tables.infact the database server stores everything in raw format in the datadictionary they are
not diff but areone and the same
Database server is base on which everything resides,It Contains all the schemas,triggers,views etc..
Data Dictionary contains meta data information about each and every schemas object like tables
procedures..etc.
Database server is a server on which the instance of oracle as server runs..whereas datadictionary is
the collection of information about all those objects like tables indexes views triggers etc in a
database..
728. How do we display the column values of a table using cursors without knowing the column
names inside the loop?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
109
Declare a variable using PL/SQL %ROWTPE ( l_Record EMP%ROWTYPE)In the cursor, you can say ..
cursor cursorname is select * from emp..Open cursor; loop .. fetch cursorname into l_Record.. Display
the values from l_Record using dbms_output.put_line.Close the loop and cursor
DECLARE
CURSOR cr_data
IS
SELECTROWID, A.* FROM EMP A where rownum<10;
l_table_name VARCHAR2(2000) :='FND_USER';
-- IMP--This table name should be same as your from table in the above cursor
l_value VARCHAR2 (2000);
l_str VARCHAR2 (2000);
CURSOR column_names (p_table_name VARCHAR2)
IS
SELECT*
FROM all_tab_columns
WHERE table_name =p_table_name;
-- You can use order by clause here if you want.
BEGIN
FOR cr_rec IN cr_data
LOOP
-- We should pass the same Table Name
FOR cr_columc_rec IN column_names (l_table_name)
LOOP
l_str :=
'Select '
| | cr_columc_rec.column_name
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
110
| | ' from '| | l_table_name| | ' where rowid ='| | chr(39)
| | cr_rec.ROWID| | chr(39);
DBMS_OUTPUT.put_line ('Query is ' | | l_str);
EXECUTE IMMEDIATE l_str
INTO l_value;
DBMS_OUTPUT.put_line ( 'Column is '
| | cr_columc_rec.column_name
| | ' and Value is '
| | l_value
);
END LOOP;
END LOOP;
END;
729.What is Flashback query in Oracle9i...?
Flahsback is used to take your database at old state like a system restore in windows. No DDL and
DML is allowed when database is in flashback condition. User should have execute permission on
dbms_flashback package
for example:
at 10:30 am
from scott user : delete from emp;
commit;
at 10:40 am I want all my data from emp table then ?
declare
cursor c1 is select * from emp;
emp_cur emp%rowtype;
begin
dbms_flashback.enable_at_time(sysdate - 15/1440);
open c1;
dbms_flashback.disable;
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
111
loop
fetch c1 into emp_cur;
exit when c1%notfound;
insert into emp values(emp_cur.empno, emp_cur.ename, emp_cur.job,
emp_cur.mgr,emp_cur.hiredate, emp_cur.sal, emp_cur.comm,
emp_cur.deptno);
end loop;
Commit;
end;
/
select * from emp;
14 rows selected
730. the difference between instead of trigger, database trigger, and schema trigger?
INSTEAD OF Trigger control operation on view, not table. They can be used to make non-updateable
views updateable and to override the behavior of view that are updateable.
Database triggers fire whenever the database startup or is shutdown, whenever
a user logs on or log off, and whenever an oracle error occurs. these tigger provide a means of
tracking activity in the database
Instead of trigger : A view cannot be updated , so if the user tries to update a view, then this trigger
can be used , where we can write the code so that the data will be updated in the table, from which
the view was created. Database trigger : this trigger will be fired when a database event ( dml
operation ) occurs in the database table, like insert , update or delete. System triggers : this trigger will
fire for database events like dtartup / shutdown of the server, logon / logoff of the user, and server
errors ... and also for the ddl events, like alter, drop, truncate etc.
In database trigger: Trigger for a table /view is a database trigger
like ( before , insert * update, delete, insert * row level, statement level)
2 * 3 * 2 =12 +instead off trigger for views
schema triggers reffers to : before logoff, after logon, before create, drop,alter on schema ( these
trigger are also called DDL trigger)
Application trigger: before shutdown, after startup, on error( any error occur in database, after
starting the orcalce instance, before closing the instance)
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
112
731. What are the components of Physical database structure of Oracle Database?
ORACLE database is comprised of three types of files. One or more Data files, two are more
Redo Log files, and one or more Control files.
732. What are the components of Logical database structure of ORACLE database?
Tablespaces and the Database's Schema Objects.
733. What is a Tablespace? A database is divided into Logical Storage Unit called
tablespaces. A tablespace is used to grouped related logical structures together.
734. What is SYSTEM tablespace and when is it Created? Every ORACLE database contains
a tablespace named SYSTEM, which is automatically created when the database is
created. The SYSTEM tablespace always contains the data dictionary tables for the entire
database.
735. Explain the relationship among Database, Tablespace and Data file.
Each databases logically divided into one or more tablespaces One or more data files are
explicitly created for each tablespace.
736. What is schema? A schema is collection of database objects of a User.
737. What are Schema Objects ? Schema objects are the logical structures that directly
refer to the database's data. Schema objects include tables, views, sequences, synonyms,
indexes, clusters, database triggers, procedures, functions packages and database links.
738. Can objects of the same Schema reside in different tablespaces.? Yes.
739. Can a Tablespace hold objects from different Schemes ? Yes.
740. What is Table ? A table is the basic unit of data storage in an ORACLE database. The
tables of a database hold all of the user accessible data. Table data is stored in rows and
columns.
741. What is a View ? A view is a virtual table. Every view has a Query attached to it. (The
Query is a SELECT statement that identifies the columns and rows of the table(s) the view
uses.)
742. Do views contain Data ? Views do not contain or store data.
743. Can a View based on another View ? Yes.
744. What are the advantages of Views ?
--Provide an additional level of table security, by restricting access to a predetermined
Set of rows and columns of a table.
--Hide data complexity.
--Simplify commands for the user.
--Present the data in a different perspective from that of the base table.
--Store complex queries.
745. What is a Sequence ? A sequence generates a serial list of unique numbers for numerical
columns of a database's tables.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
113
746. What is a Synonym ? A synonym is an alias for a table, view, sequence or program unit.
747. What are the types of Synonyms? There are two types of Synonyms Private and Public.
748. What is a Private Synonyms ? A Private Synonyms can be accessed only by the owner.
749. What is a Public Synonyms ? A Public synonym can be accessed by any user on the
database.
750. What are synonyms used for ?
--Synonyms are used to : Mask the real name and owner of an object.
---Provide public access to an object
--Provide location transparency for tables, views or program units of a remote database.
--Simplify the SQL statements for database users.
751. What is an Index ? An Index is an optional structure associated with a table to have
direct access to rows, which can be created to increase the performance of data retrieval.
Index can be created on one or more columns of a table.
752. How is Indexes Update ? Indexes are automatically maintained and used by ORACLE.
Changes to table data are automatically incorporated into all relevant indexes.
753. What are Clusters ? Clusters are groups of one or more tables physically stores together
to share common columns and are often used together.
754. What is cluster Key ? The related columns of the tables in a cluster are called the Cluster
Key.
755. What is Index Cluster ? A Cluster with an index on the Cluster Key.
756. What is Hash Cluster ? A row is stored in a hash cluster based on the result of applying a
hash function to the row's cluster key value. All rows with the same hash key value are stores
together on disk.
757. When can Hash Cluster used ? Hash clusters are better choice when a table is often
queried with equality queries. For such queries the specified cluster key value is hashed. The
resulting hash key value points directly to the area on disk that stores the specified rows.
758. What is Database Link ? A database link is a named object that describes a "path" from
one database to another.
759. What are the types of Database Links ? Private Database Link, Public Database Link &
Network Database Link.
760. What is Private Database Link ? Private database link is created on behalf of a specific
user. A private database link can be used only when the owner of the link specifies a
global object name in a SQL statement or in the definition of the owner's views or procedures.
761. What is Public Database Link ? Public database link is created for the special user group
PUBLIC. A public database link can be used when any user in the associated database
specifies a global object name in a SQL statement or object definition.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
114
762. What is Network Database link ? Network database link is created and managed by a
network domain service. A network database link can be used when any user of any
database in the network specifies a global object name in a SQL statement or object
definition.
763. What is Data Block ? ORACLE database's data is stored in data blocks. One data block
corresponds to a specific number of bytes of physical database space on disk.
764. How to define Data Block size ? A data block size is specified for each ORACLE
database when the database is created. A database users and allocated free database
space in ORACLE data blocks. Block size is specified in INIT.ORA file and cant be changed
latter.
765. What is Row Chaining ? In Circumstances, all of the data for a row in a table may not be
able to fit in the same data block. When this occurs , the data for the row is stored in a
chain of data block (one or more) reserved for that segment.
766. What is an Extent ? An Extent is a specific number of contiguous data blocks, obtained
in a single allocation, used to store a specific type of information.
767. What is a Segment ? A segment is a set of extents allocated for a certain logical
structure.
768. What are the different types of Segments ? Data Segment, Index Segment, Rollback
Segment and Temporary Segment.
769. What is a Data Segment ? Each Non-clustered table has a data segment. All of the
table's data is stored in the extents of its data segment. Each cluster has a data segment. The
data of every table in the cluster is stored in the cluster's data segment.
770. What is an Index Segment ? Each Index has an Index segment that stores all of its data.
771. What is Rollback Segment ? A Database contains one or more Rollback Segments to
temporarily store "undo" information.
772. What are the uses of Rollback Segment ? Rollback Segments are used to generate read-
consistent database information during database recovery to rollback uncommitted
transactions for users.
773. What is a Temporary Segment ? Temporary segments are created by ORACLE when a
SQL statement needs a temporary work area to complete execution. When the statement
finishes execution, the temporary segment extents are released to the system for future use.
774. What is a Data File ? Every ORACLE database has one or more physical data files. A
database's data files contain all the database data. The data of logical database
structures such as tables and indexes is physically stored in the data files allocated for a
database.
775. What are the Characteristics of Data Files ? A data file can be associated with only one
database. Once created a data file can't change size. One or more data files form a
logical unit of database storage called a tablespace.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
115
776. What is a Redo Log ? The set of Redo Log files for a database is collectively known as
the database's redo log.
777. What is the function of Redo Log ? The Primary function of the redo log is to record all
changes made to data.
778. What is the use of Redo Log Information ? The Information in a redo log file is used only to
recover the database from a system or media failure prevents database data from being
written to a database's data files.
779. What does a Control file Contain ? A Control file records the physical structure of the
database. It contains the following information.
--Database Name.
--Names and locations of a database's files and redo log files.
--Time stamp of database creation.
780. What is the use of Control File ? When an instance of an ORACLE database is started, its
control file is used to identify the database and redo log files that must be opened for
database operation to proceed. It is also used in database recovery.
781. What is a Data Dictionary ? The data dictionary of an ORACLE database is a set of tables and
views that are used as a read-only reference about the database.
It stores information about both the logical and physical structure of the database, the valid users of
an ORACLE database, integrity constraints defined for tables in the database and space allocated for a
schema object and how much of it is being used.
782. What is an Integrity Constrains ? An integrity constraint is a declarative way to define a
business rule for a column of a table.
783. Can an Integrity Constraint be enforced on a table if some existing table data does not
satisfy the constraint ? No.
784. Describe the different type of Integrity Constraints supported by ORACLE ?
NOT NULL Constraint - Disallows NULLs in a table's column.
UNIQUE Constraint - Disallows duplicate values in a column or set of columns.
PRIMARY KEY Constraint - Disallows duplicate values and NULLs in a column or set of columns.
FOREIGN KEY Constrain - Require each value in a column or set of columns match a value in a
related table's UNIQUE or PRIMARY KEY.
CHECK Constraint - Disallows values that do not satisfy the logical expression of the constraint.
785. What is difference between UNIQUE constraint and PRIMARY KEY constraint ?
A column defined as UNIQUE can contain NULLs while a column defined as PRIMARY KEY
can't contain Nulls.
786. Describe Referential Integrity ? A rule defined on a column (or set of columns) in one table
that allows the insert or update of a row only if the value for the column or set of columns
(the dependent value) matches a value in a column of a related table (the referenced
value). It also specifies the type of data manipulation allowed on referenced data and
the action to be performed on dependent data as a result of any action on referenced data.
787. What are the Referential actions supported by FOREIGN KEY integrity constraint ?
UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion
of referenced data.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
116
DELETE Cascade - When a referenced row is deleted all associated dependent rows are
deleted.
788. What is self-referential integrity constraint ? If a foreign key reference a parent key of
the same table is called self-referential integrity constraint.
789. What are the Limitations of a CHECK Constraint ?
The condition must be a Boolean expression evaluated using the values in the row being
inserted or updated And can't contain sub queries, sequence, the SYSDATE,UID,USER or
USERENV SQL functions, or the pseudo columns LEVEL or ROWNUM.
790. What is the maximum number of CHECK constraints that can be defined on a column ?
No Limit.
791. What constitute an ORACLE Instance ? SGA and ORACLE background processes
constitute an ORACLE instance. (or) Combination of memory structure and background
process.
792. What is SGA ? The System Global Area (SGA) is a shared memory region allocated by
ORACLE that contains data and control information for one ORACLE instance.
793. What are the components of SGA ? Database buffers, Redo Log Buffer the Shared Pool
and Cursors.
794. What do Database Buffers contain ? Database buffers store the most recently used
blocks of database data. It can also contain modified data that has not yet been
permanently written to disk.
795. What do Redo Log Buffers contain ? Redo Log Buffer stores redo entries a log of changes
made to the database.
796. What is Shared Pool ? Shared Pool is a portion of the SGA that contains shared memory
constructs such as shared SQL areas.
797. What is Shared SQL Area ?
A Shared SQL area is required to process every unique SQL statement submitted to a
database and contains information such as the parse tree and execution plan for the
corresponding statement.
798. What is Cursor ? A Cursor is a handle ( a name or pointer) for the memory associated with
a specific statement.
799. What is PGA ? Program Global Area (PGA) is a memory buffer that contains data and
control information for a server process.
800. What is User Process ? A user process is created and maintained to execute the software
code of an application program. It is a shadow process created automatically to facilitate
communication between the user and the server process.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
117
Second Set



1. What is Server Process ? Server Process handles requests from connected user process. A
server process is in charge of communicating with the user process and interacting with
ORACLE carry out requests of the associated user process.
2. What are the two types of Server Configurations ? Dedicated Server Configuration and
Multi-threaded Server Configuration.
3. What is Dedicated Server Configuration ? In a Dedicated Server Configuration a Server
Process handles requests for a Single User Process.
4. What is a Multi-threaded Server Configuration ? In a Multi-threaded Server Configuration
many user processes share a group of server process.
5. What is a Parallel Server option in ORACLE ? A configuration for loosely coupled systems
where multiple instances share a single physical database is called Parallel Server.
6. Name the ORACLE Background Process ?
DBWR - Database Writer.
LGWR - Log Writer
CKPT - Check Point
SMON - System Monitor
PMON - Process Monitor
ARCH - Archiver
RECO - Recover
Dnnn - Dispatcher
LCKn - Lock
Snnn - Server.
7. What Does DBWR do ? Database writer writes modified blocks from the database buffer
cache to the data files.
8. When Does DBWR write to the database ? DBWR writes when more data needs to be
read into the SGA and too few database buffers are free. The least recently used data is
written to the data files first. DBWR also writes when Checkpoint occurs.
9. What does LGWR do ? Log Writer (LGWR) writes redo log entries generated in the redo log
buffer of the SGA to on-line Redo Log File.
10. When does LGWR write to the database ? LGWR writes redo log entries into an on-line
redo log file when transactions commit and the log buffer files are full.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
118
11. What is the function of checkpoint(CKPT)? The Checkpoint (CKPT) process is responsible
for signaling DBWR at checkpoints and updating all the data files and control files of the
database.
12. What are the functions of SMON ?
System Monitor (SMON) performs instance recovery at instance start-up. In a multiple instance
system (one that uses the Parallel Server), SMON of one instance can also perform instance
recovery for other instance that have failed SMON also cleans up temporary segments that
are no longer in use and recovers dead transactions skipped during crash and instance
recovery because of file-read or off-line errors. These transactions are eventually recovered
by SMON when the tablespace or file is brought back on-line SMON also coalesces free
extents within the database to make free space contiguous and easier to allocate.
13. What are functions of PMON ? Process Monitor (PMON) performs process recovery when
a user process fails PMON is responsible for cleaning up the cache and Freeing resources
that the process was using PMON also checks on dispatcher and server processes and
restarts them if they have failed.
14. What is the function of ARCH ? Archiver (ARCH) copies the on-line redo log files to
archival storage when they are full. ARCH is active only when a database's redo log is used
in ARCHIVELOG mode.
15. What is function of RECO ? Recover (RECO) is used to resolve distributed transactions that
are pending due to a network or system failure in a distributed database. At timed intervals,
the local RECO attempts to connect to remote databases and automatically complete
the commit or rollback of the local portion of any pending distributed transactions.
16. What is the function of Dispatcher (Dnnn)? Dispatcher (Dnnn) process is responsible for
routing requests from connected user processes to available shared server processes and
returning the responses back to the appropriate user processes.
17. How many Dispatcher Processes are created ? At least one Dispatcher process is created
for every communication protocol in use.
18. What is the function of Lock (LCKn) Process ? Lock (LCKn) is used for inter-instance locking
when the ORACLE Parallel Server option is used.
19. What is the maximum number of Lock Processes used ?
Though a single LCK process is sufficient for most Parallel Server systems
upto Ten Locks (LCK0,....LCK9) are used for inter-instance locking.
20. Define Transaction ? A Transaction is a logical unit of work that comprises one or more
SQL statements executed by a single user.
21. When does a Transaction end ? When it is committed or Rollbacked.
22. What does COMMIT do ? COMMIT makes permanent the changes resulting from all SQL
statements in the transaction. The changes made by the SQL statements of a transaction
become visible to other user sessions transactions that start only after transaction is committed.
23. What does ROLLBACK do ? ROLLBACK retracts any of the changes resulting from the SQL
statements in the transaction.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
119
24. What is SAVE POINT ?
For long transactions that contain many SQL statements, intermediate markers or save
points 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 save point within the transaction.
25. What is Read-Only Transaction ? A Read-Only transaction ensures that the results of each
query executed in the transaction are consistent with respect to the same point in time.
26. What is the function of Optimizer ? The goal of the optimizer is to choose the most efficient
way to execute a SQL statement.
27. What is Execution Plan ? The combination of the steps the optimizer chooses to execute a
statement is called an execution plan.
28. What are the different approaches used by Optimizer in choosing an execution plan ?
Rule-based and Cost-based.
29. What are the factors that affect OPTIMIZER in choosing an Optimization approach ?
The optimizer_mode initialization parameter statistics in the Data Dictionary the
optimizer_goal parameter of the ALTER SESSION command hints in the statement.
30. What are the values that can be specified for OPTIMIZER MODE Parameter ?
COST and RULE.
31. Will the Optimizer always use COST-based approach if OPTIMIZER_MODE is set to "Cost'?
Presence of statistics in the data dictionary for at least one of the tables accessed by the
SQL statements is necessary for the OPTIMIZER to use COST-based approach. Otherwise
OPTIMIZER chooses RULE-based approach.
32. What is the effect of setting the value of OPTIMIZER_MODE to 'RULE' ?
This value causes the optimizer to choose the rule_based approach for all SQL statements
issued to the instance regardless of the presence of statistics.
33. What are the values that can be specified for OPTIMIZER_GOAL parameter of the ALTER
SESSION Command ? CHOOSE, ALL_ROWS, FIRST_ROWS and RULE.
34. What is the effect of setting the value "choose" for optimizer_goal, parameter of the ALTER
SESSION Command ? The Optimizer chooses Cost_based approach and optimizes with the
goal of best throughput if statistics for at least one of the tables accessed by the SQL
statement exist in the data dictionary. Otherwise the OPTIMIZER chooses RULE based
approach.
35. What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOAL parameter of the
ALTER SESSION command ? This value causes the optimizer to the cost-based approach for
all SQL statements in the session regardless of the presence of statistics and to optimize with a
goal of best throughput.
36. What is the effect of setting the value 'FIRST_ROWS' for OPTIMIZER_GOAL parameter
of the ALTER SESSION command ? This value causes the optimizer to use the cost-based
approach for all SQL statements in the session regardless of the presence of statistics and to
optimize with a goal of best response time.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
120
37. What is the effect of setting the 'RULE' for OPTIMIER_GOAL parameter of the ALTER SESSION
Command ?
This value causes the optimizer to choose the rule-based approach for all SQL statements in a
session regardless of the presence of statistics.
38. What is RULE-based approach to optimization ? Choosing an executing plan based on the
access paths available and the ranks of these access paths.
39. What is COST-based approach to optimization ? Considering available access paths and
determining the most efficient execution plan based on statistics in the data dictionary for
the tables accessed by the statement and their associated clusters and indexes.
40. What are the different types of PL/SQL program units that can be defined and stored in
ORACLE database ? Procedures and Functions, Packages and Database Triggers.
41. What is a Procedure ? A Procedure consist of a set of SQL and PL/SQL statements that are
grouped together as a unit to solve a specific problem or perform a set of related tasks.
42. What is difference between Procedures and Functions ? A Function returns a value to the
caller where as a Procedure does not.
43. What is a Package ? A Package is a collection of related procedures, functions, variables
and other package constructs together as a unit in the database.
44. What are the advantages of having a Package ? Increased functionality (for example,
global package variables can be declared and used by any procedure in the package)
and performance (for example all objects of the package are parsed compiled, and
loaded into memory once)
45. What is Database Trigger ? A Database Trigger is procedure (set of SQL and PL/SQL
statements) that is automatically executed as a result of an insert in, update to, or delete
from a table.
46. What are the uses of Database Trigger ? Database triggers can be used to automatic
data generation, audit data modifications, enforce complex Integrity constraints, and
customize complex security authorizations.
47. What are the differences between Database Trigger and Integrity constraints ?
A declarative integrity constraint is a statement about the database that is always true. A
constraint applies to existing data in the table and any statement that manipulates the table.
A trigger does not apply to data loaded before the definition of the trigger, therefore, it
does not guarantee all data in a table conforms to the rules established by an associated
trigger.
A trigger can be used to enforce transitional constraints where as a declarative integrity
constraint cannot be used.
48. What are Roles ? Roles are named groups of related privileges that are granted to users
or other roles.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
121
49. What are the uses of Roles ?
Reduced Granting of Privileges - Rather than explicitly granting the same set of privileges to
many users a database administrator can grant the privileges for a group of related users
granted to a role and then grant only the role to each member of the group.
DYNAMIC PRIVILEGE MANAGEMENT - When the privileges of a group must change, only the
privileges of the role need to be modified. The security domains of all users granted the
group's role automatically reflect the changes made to the role.
SELECTIVE AVAILABILITY OF PRIVILEGES- The roles granted to a user can be selectively enable
(available for use) or disabled (not available for use). This allows specific control of a
user's privileges in any given situation.
APPLICATION AWARENESS - A database application can be designed to automatically enable
and disable selective roles when a user attempts to use the application.
50. How to prevent unauthorized use of privileges granted to a Role ? By creating a Role with a
password.
51. What is default tablespace ? The Tablespace to contain schema objects created
without specifying a tablespace name.
52. What is Tablespace Quota ? The collective amount of disk space available to the objects
in a schema on a particular tablespace.
53. What is a profile ? Each database user is assigned a Profile that specifies limitations on
various system resources available to the user.
54. What are the system resources that can be controlled through Profile ?
The number of concurrent sessions the user can establish the CPU processing time available to
the user's session the CPU processing time available to a single call to ORACLE made by a
SQL statement the amount of logical I/O available to the user's session the amout of logical
I/O available to a single call to ORACLE made by a SQL statement the allowed amount of
idle time for the user's session the allowed amount of connect time for the user's session.
55. What is Auditing ? Monitoring of user access to aid in the investigation of database use.
56. What are the different Levels of Auditing ? Statement Auditing, Privilege Auditing and
Object Auditing.
57. What is Statement Auditing ? Statement auditing is the auditing of the powerful system
privileges without regard to specifically named objects.
58. What is Privilege Auditing ? Privilege auditing is the auditing of the use of powerful system
privileges without regard to specifically named objects.
59. What is Object Auditing ? Object auditing is the auditing of accesses to specific
schema objects without regard to user.
60. What is Distributed database ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
122
A distributed database is a network of databases managed by multiple database servers
that appears to a user as single logical database. The data of all databases in the
distributed database can be simultaneously accessed and modified.
61. What is Two-Phase Commit ? Two-phase commit is mechanism that guarantees a
distributed transaction either commits on all involved nodes or rolls back on all involved nodes
to maintain data consistency across the global distributed database. It has two phases, a
Prepare Phase and a Commit Phase.
62. Describe two phases of Two-phase commit ?
Prepare phase - The global coordinator (initiating node) ask a participants to prepare (to
promise to commit or rollback the transaction, even if there is a failure)
Commit-Phase - If all participants respond to the coordinator that they are prepared, the
coordinator asks all nodes to commit the transaction, if all participants cannot prepare, the
coordinator asks all nodes to roll back the transaction.
63. What is the mechanism provided by ORACLE for table replication ?
Snapshots and SNAPSHOT LOGs
64. What is a SNAPSHOT ?
Snapshots are read-only copies of a master table located on a remote node which is
periodically refreshed to reflect changes made to the master table.
65. What is a SNAPSHOT LOG ?
A snapshot log is a table in the master database that is associated with the master table.
ORACLE uses a snapshot log to track the rows that have been updated in the master table.
Snapshot logs are used in updating the snapshots based on the master table.
66. What is a SQL* NET? SQL *NET is Oracles mechanism for interfacing with the
communication protocols used by the networks that facilitate distributed processing and
distributed databases. It is used in client-server and server-server communications.
67. What are the steps involved in Database Startup ? Start an instance, Mount the Database
and Open the Database.
68. What are the steps involved in Database Shutdown ? Close the Database, Dismount the
Database and Shutdown the Instance.
69. What is Restricted Mode of Instance Startup ?
An instance can be started in (or later altered to be in) restricted mode so that when the
database is open connections are limited only to those whose user accounts have been
granted the Restricted Session system privilege.
70. What are the different modes of mounting a Database with the Parallel Server ?
1)Exclusive Mode If the first instance that mounts a database does so in exclusive
mode, only that Instance can mount the database.
2) Parallel Mode If the first instance that mounts a database is started in parallel
mode, other instances that are started in parallel mode can also mount the database.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
123
71. What is Full Backup? A full backup is an operating system backup of all data files, on-line
redo log files and control file that constitute ORACLE database and the parameter.
72. Can Full Backup be performed when the database is open? No.
73. What is Partial Backup? A Partial Backup is any operating system backup short of a full
backup, taken while the database is open or shut down.
74.WhatisOn-lineRedoLog?
The On-line Redo Log is a set of two or more on-line redo files that record all committed
changes made to the database. Whenever a transaction is committed, the corresponding
redo entries temporarily stores in redo log buffers of the SGA are written to an on-line redo log
file by the background process LGWR. The on-line redo log files are used in cyclical fashion.
75. What is Mirrored on-line Redo Log? A mirrored on-line redo log consists of copies of on-line
redo log files physically located on separate disks, changes made to one member of the
group are made to all members.
76. What is Archived Redo Log? Archived Redo Log consists of Redo Log files that have
archived before being reused.
77. What are the advantages of operating a database in ARCHIVELOG mode over operating
it in NO ARCHIVELOG mode ? Complete database recovery from disk failure is possible only in
ARCHIVELOG mode. Online database backup is possible only in ARCHIVELOG mode.
78. What is Log Switch ? The point at which ORACLE ends writing to one online redo log file
and begins writing to another is called a log switch.
79. What are the steps involved in Instance Recovery ?
1. Rolling forward to recover data that has not been recorded in data files, yet has been
recorded in the on-line redo log, including the contents of rollback segments.
2. Rolling back transactions that have been explicitly rolled back or have not been committed
as indicated by the rollback segments regenerated in step a.
Releasing any resources (locks) held by transactions in process at the time of the failure.
3. Resolving any pending distributed transactions undergoing a two-phase commit at the
time of the instance failure.
80. What is a Database instance ? Explain? A database instance (Server) is a set of memory
structure and background processes that access a set of database files.
The process can be shared by all users.
The memory structure that are used to store most queried data from database. This
helps up to improve database performance by decreasing the amount of I/O performed
against data file.
81. What is Parallel Server ? Multiple instances accessing the same database (Only In Multi-
CPU environments)
82. What is a Schema ? The set of objects owned by user account is called the schema.
83. What is an Index ? How it is implemented in Oracle Database ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
124
An index is a database structure used by the server to have direct access of a row in a table.
An index is automatically created when a unique of primary key constraint clause is specified
in create table comman (Ver 7.0)
84. What are clusters ? Group of tables physically stored together because they share
common columns and are often used together is called Cluster.
85. What is a cluster Key ? The related columns of the tables are called the cluster key. The
cluster key is indexed using a cluster index and its value is stored only once for multiple tables
in the cluster.
86. What are the basic elements of Base configuration of an oracle Database ?
It consists of
--One or more data files.
--One or more control files.
--Two or more redo log files.
The Database contains
--Multiple users/schemas
--One or more rollback segments
--One or more tablespaces
--Data dictionary tables
--User objects (table, indexes, views etc.,)
The server that access the database consists of
SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)
SMON (System MONito)
PMON (Process MONitor)
LGWR (LoG Write)
DBWR (Data Base Write)
ARCH (ARCHiver)
CKPT (Check Point)
RECO
Dispatcher
User Process with associated PGS
87. What is a deadlock ? Explain. Two processes waiting to update the rows of a table which
are locked by the other process then deadlock arises. In a database environment this will
often happen because of not issuing proper row lock commands. Poor design of front-end
application may cause this situation and the performance of server will reduce drastically.
These locks will be released automatically when a commit/rollback operation performed or
any one of these processes being killed externally.
88. What is SGA ? The System Global Area in a Oracle database is the area in memory to
facilitates the transfer of information between users. It holds the most recently requested
structural information between users. It holds the most recently requested structural information
about the database.
89. What is a Shared SQL pool ? The data dictionary cache is stored in an area in SGA called
the Shared SQL Pool. This will allow sharing of parsed SQL statements among concurrent
users.
90. What is mean by Program Global Area (PGA) ? It is area in memory that is used by a Single
Oracle User Process.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
125
91. What is a data segment ? Data segment are the physical areas within a database block
in which the data associated with tables and clusters are stored.
92. What are the factors causing the reparsing of SQL statements in SGA?
Due to insufficient Shared SQL pool size. Monitor the ratio of the reloads takes place while
executing SQL statements. If the ratio is greater than 1then increase the SHARED_POOL_SIZE.
93. What is Database Buffers ? Database buffers are cache in the SGA used to hold the data
blocks that are read from the data segments in the database such as tables, indexes and
clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.
94. What is dictionary cache ? Dictionary cache is information about the database objects
stored in a data dictionary table.
95. What is meant by recursive hints ?
Number of times processes repeatedly query the dictionary table is called recursive hints. It
is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE
parameter we can optimize the size of Data Dictionary Cache.
96. What is meant by redo log buffer ? Changes made to entries are written to the on-line
redo log files. So that they can be used in roll forward operations during database
recoveries. Before writing them into the redo log files, they will first brought to redo log
buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide
the size.
97. How will you swap objects into a different table space for an existing database ?
1 Export the user
2. Perform import using the command imp system/manager file=export.dmp
indexfile=newrite.sql. This will create all definitions into newfile.sql.
3. Drop necessary objects.
4. Run the script newfile.sql after altering the tablespaces.
5. Import from the backup for the necessary objects.
98. List the Optional Flexible Architecture (OFA) of Oracle database ? or How can we
organize the tablespaces in Oracle database to have maximum performance ?
SYSTEM - Data dictionary tables.
DATA - Standard operational tables.
DATA2 - Static tables used for standard operations
INDEXES - Indexes for Standard operational tables.
INDEXES1 - Indexes of static tables used for standard operations.
TOOLS - Tools table.
TOOLS1 - Indexes for tools table.
RBS - Standard Operations Rollback Segments,
RBS1,RBS2 - Additional/Special Rollback segments.
TEMP - Temporary purpose tablespace
TEMP_USER - Temporary tablespace for users.
USERS - User tablespace.
99. How will you force database to use particular rollback segment ?
SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
126
100. What is meant by free extent ? A free extent is a collection of continuous free blocks in
tablespace. When a segment is dropped its extents are reallocated and are marked as free.
101. How free extents are managed in Ver 6.0 and Ver 7.0 ?
Free extents cannot be merged together in Ver 6.0.
Free extents are periodically coalesces with the neighboring free extent in Ver 7.0
102.Which parameter in Storage clause will reduce no. of rows per block?
PCTFREE parameter, Row size also reduces no of rows per block.
103. What is the significance of having storage clause ?
We can plan the storage for a table as how much initial extents are required, how much
can be extended next, how much % should leave free for managing row updations etc.,
104. How does Space allocation take place within a block ?
Each block contains entries as follows
Fixied block header
Variable block header
Row Header,row date (multiple rows may exists)
PCTEREE (% of free space for row updation in future)
105. What is the role of PCTFREE parameter is Storage clause ?
This is used to reserve certain amount of space in a block for expansion of rows.
106. What is the OPTIMAL parameter ?
It is used to set the optimal length of a rollback segment.
107. What is the functionality of SYSTEM table space ?
To manage the database level transactions such as modifications of the data dictionary table
that record information about the free space usage.
107. How will you create multiple rollback segments in a database ?
1) Create a database which implicitly creates a SYSTEM Rollback Segment in a SYSTEM
tablespace.
2) Create a Second Rollback Segment name R0 in the SYSTEM tablespace.
3) Make new rollback segment available (After shutdown, modify init.ora file and Start
database)
4) Create other tablespaces (RBS) for rollback segments.
5) Deactivate Rollback Segment R0 and activate the newly created rollback segments.
108. How the space utilisation takes place within rollback segments ?
It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an
extent is in use then it forced to acquire a new extent (No. of extents is based on the optimal
size)
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
127
109. Why query fails sometimes ?
1) Rollback segment dynamically extent to handle larger transactions entry loads.
2) A single transaction may wipeout all avaliable free space in the Rollback Segment
Tablespace. This prevents other user using Rollback segments.
110. How will you monitor the space allocation ?
By quering DBA_SEGMENT table/view.
111. How will you monitor rollback segment status ?
Querying the DBA_ROLLBACK_SEGS view
IN USE - Rollback Segment is on-line.
AVAILABLE - Rollback Segment available but not on-line.
OFF-LINE - Rollback Segment off-line
INVALID - Rollback Segment Dropped.
NEEDS RECOVERY - Contains data but need recovery or corupted.
PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed
database.
112. List the sequence of events when a large transaction that exceeds beyond its
optimal value when an entry wraps and causes the rollback segment to expand into
another extend.
1) Transaction Begins.
2) An entry is made in the RES header for new transactions entry
3) Transaction acquires blocks in an extent of RBS
4) The entry attempts to wrap into second extent. None is available, so that
the RBS must extent.
5) The RBS checks to see if it is part of its OPTIMAL size.
6) RBS chooses its oldest inactive segment.
7) Oldest inactive segment is eliminated.
8) RBS extents
9) The Data dictionary table for space management are updated.
10) Transaction Completes.
113. How can we plan storage for very large tables ?
Limit the number of extents in the table
Separate Table from its indexes.
Allocate Sufficient temporary storage.
114. How will you estimate the space required by non-clustered tables?
Calculate the total header size
Calculate the available data space per data block
Calculate the combined column lengths of the average row
Calculate the total average row size.
Calculate the average number rows that can fit in a block
Calculate the number of blocks and bytes required for the table.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
128
After arriving the calculation, add 10 % additional space to calculate the initial extent size for
a working table.
115. It is possible to use raw devices as data files and what is the advantages over file.
system files ?
Yes. I/O will be improved because Oracle is bye-passing the kernnel which writing into
disk. Disk Corruption will be very less.
116. What is a Control file ?
Database's overall physical architecture is maintained in a file called control file. It will be
used to maintain internal consistency and guide recovery operations. Multiple copies of
control files are advisable.
117. How to implement the multiple control files for an existing database ?
Shutdown the database
Copy one of the existing control file to new location
Edit config. ora file by adding new control file.name
Restart the database.
118. What is meant by Redo Log file mirrorring ? How it can be achieved?
Process of having a copy of redo log files is called mirroring.
This can be achieved by creating group of log files together, so that LGWR will automatically
writes them to all the members of the current on-line redo log group. If any one group fails
then database automatically switch over to next group. It degrades performance.
119. What is advantage of having disk shadowing/ Mirroring?
Shadow set of disks save as a backup in the event of disk failure. In most Operating System if
any disk failure occurs it automatically switchover to place of failed disk.
Improved performance because most OS support volume shadowing can direct file I/O
request to use the shadow set of files instead of the main set of files. This reduces I/O load on
the main set of disks.
120. What is use of Rollback Segments in Database?
They allow the database to maintain read consistency between multiple transactions.
121. What is a Rollback segment entry?
It is the set of before image data blocks that contain rows that are modified by a
transaction. Each Rollback Segment entry must be completed within one rollback
segment. A single rollback segment can have multiple rollback segment entries.
122. 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.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
129
123. When will be a segment released ?
When Segment is dropped.
When Shrink (RBS only)
When truncated (TRUNCATE used with drop storage option)
124. What are disadvantages of having raw devices ?
We should depend on export/import utility for backup/recovery (fully reliable)
The tar command cannot be used for physical file backup, instead we can use dd command
which is less flexible and has limited recoveries.
127. List the factors that can affect the accuracy of the estimations ?
1) The space used transaction entries and deleted records does not become free immediately
after completion due to delayed cleanout.
2) Trailling nulls and length bytes are not stored.
3)Inserts of, updates to and deletes of rows as well as columns larger than a single datablock,
can cause fragmentation an chained row pieces.
128. What is user Account in Oracle database?
A user account is not a physical structure in Database but it is having important relationship to
the objects in the database and will be having certain privileges.
129. How will you enforce security using stored procedures?
Don't grant user access directly to tables within the application. Instead grant the ability to
access the procedures that access the tables. When procedure executed it will execute the
privilege of procedures owner. Users cannot access tables except via the procedure.
130. What are the dictionary tables used to monitor a database spaces?
DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.
131. 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 basetables 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.
132. What are the database administrators utilities available?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
130
SQL * DBA - This allows DBA to monitor and control an ORACLE database.
SQL * Loader- It loads data from standard operating system files (Flat files) into ORACLE
database tables.
Export (EXP) and Import (imp) utilities allow you to move existing data in ORACLE format to and
from ORACLE database.
133. 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.
134. 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.
135. What are roles ? How can we implement roles ?
Roles are the easiest way to grant and manage common privileges needed by different
groups of database users. Creating roles and assigning provies to roles.
Assign each role to group of users. This will simplify the job of assigning privileges to individual
users.
136. What are the steps to switch a database's archiving mode between NO ARCHIVELOG
and ARCHIVELOG mode ?
1. Shutdown the database instance.
2. Backup the database
3. Perform any operating system specific steps (optional)
4. Start up a new instance and mount but do not open the databse.
5. Switch the databse's archiving mode.
137. How can you enable automatic archiving?
1) Shut the database
2) Backup the database
3) Modify/Include LOG_ARCHIVE_START_TRUE in init.ora file.
4) Start up the database.
138. How can we specify the Archived log file name format and destination ?
By setting the following values in init.ora file.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
131
LOG_ARCHIVE_FORMAT=arch %S/s/T/tarc (%S - Log sequence number and is zero left paded,
%s - Log sequence number not padded. %T - Thread number lef-zero-paded and %t -
Thread number not padded). The file name created is arch 0001 are if %S is used.
LOG_ARCHIVE_DEST =path.
139. What is the use of ANALYZE command ?
To perform one of these function on an index,table, or cluster:
- to collect statisties about object used by the optimizer and store them in the data dictionary.
- to delete statistics about the object used by object from the data dictionary.
- to validate the structure of the object.
- to identify migrated and chained rows of the table or cluster.
140. How can we reduce the network traffic ?
- Replication of data in distributed environment.
- Using snapshots to replicate data.
- Using remote procedure calls.
141. What is snapshots? Snapshot is an object used to dynamically replicate data between
distributed databases at specified time intervals. In ver 7.0 they are read only.
142. What are the various type of snapshots? Simple and Complex.
143. Differentiate simple and complex, snapshots ?
- A simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT
BY clauses, J oins, sub-query or snapshot of operations.
- A complex snapshots contain at least any one of the above.
145. What dynamic data replication? Updating or Inserting records in remote database
through database triggers. It may fail if remote database is having any problem.
146. How can you Enforce Referential Integrity in snapshots?
Time the references to occur when master tables are not in use.
Perform the reference the manually immediately locking the master tables. We can join
tables in snapshots by creating a complex snapshots that will based on the master tables.
147. What are the options available to refresh snapshots?
COMPLETE - Tables are completely regenerated using the snapshots query and the master
tables every time the snapshot referenced.
FAST- If simple snapshot used then a snapshot log can be used to send the changes to the
snapshot tables.
FORCE- Default value. If possible it performs a FAST refresh; otherwise it will perform a complete
refresh.
148. What is snapshot log?
It is a table that maintains a record of modifications to the master table in a snapshot. It is
stored in the same database as master table and is only available for simple snapshots. It
should be created before creating snapshots.
149. When will the data in the snapshot log be used ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
132
1) We must be able to create a after row trigger on table (i.e., it should be not be already available )
2) After giving table privileges.
3) We cannot specify snapshot log name because oracle uses the name of the master table in the
name of the database objects that support its snapshot log.
4) The master table name should be less than or equal to 23 characters.
(The table name created will be MLOGS_tablename, and trigger name will be TLOGS name).
150. What are the benefits of distributed options in databases ?
Database on other servers can be updated and those transactions can be grouped
together with others in a logical unit. Database uses a two phase commit.
151. What are the different methods of backing up oracle database ?
- Logical Backups
- Cold Backups
- Hot Backups (Archive log)
152. What is a logical backup?
Logical backup involves reading a set of database records and writing them into a file. Export
utility is used for taking backup and Import utility is used to recover from backup.
153. What is cold backup? What are the elements of it?
Cold backup is taking backup of all physical files after normal shutdown of database. We
need to take.
- All Data files.
- All Control files.
- All on-line redo log files.
- The init.ora files (Optional)
154. What are the different kinds of export backups?
Full back - Complete database
Incremental - Only affected tables from last incremental date/full backup date.
Cumulative backup - Only affected table from the last cumulative date/full backup date.
155. What is hot backup and how it can be taken?
Taking backup of archive log files when database is open. For this the ARCHIVELOG mode
should be enabled. The following files need to be backed up.
All data files. All Archive log, redo log files. All control files.
156. What is the use of FILE option in EXP command ? To give the export file name.
157. What is the use of COMPRESS option in EXP command ?
Flag to indicate whether export should compress fragmented segments into single extents.
158 . What is the use of GRANT option in EXP command ?
A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or 'N'.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
133
159. What is the use of INDEXES option in EXP command ?
A flag to indicate whether indexes on tables will be exported.
160. What is the use of ROWS option in EXP command ?
Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the
databse objects will be created.
161. What is the use of CONSTRAINTS option in EXP command ?
A flag to indicate whether constraints on table need to be exported.
162. What is the use of FULL option in EXP command ?
A flag to indicate whether full databse export should be performed.
163. What is the use of OWNER option in EXP command ?
List of table accounts should be exported.
164. What is the use of TABLES option in EXP command ?
List of tables should be exported.
165. What is the use of RECORD LENGTH option in EXP command ?
Record length in bytes.
166. What is the use of INCTYPE option in EXP command ?
Type export should be performed COMPLETE, CUMULATIVE, INCREMENTAL.
167. What is the use of RECORD option in EXP command ?
For Incremental exports, the flag indirects whether a record will be stores data dictionary
tables recording the export.
168. What is the use of PARFILE option in EXP command ?
Name of the parameter file to be passed for export.
169. What is the use of ANALYSE ( Ver 7) option in EXP command ?
A flag to indicate whether statistical information about the exported objects should be
written to export dump file.
170. What is the use of CONSISTENT (Ver 7) option in EXP command ?
A flag to indicate whether a read consistent version of all the exported objects should be
maintained.
171. What is use of LOG (Ver 7) option in EXP command ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
134
The name of the file which log of the export will be written.
172.What is the use of FILE option in IMP command ?
The name of the file from which import should be performed.
173. What is the use of SHOW option in IMP command ?
A flag to indicate whether file content should be displayed or not.
174. What is the use of IGNORE option in IMP command ?
A flag to indicate whether the import should ignore errors encounter when issuing CREATE
commands.
175. What is the use of GRANT option in IMP command ?
A flag to indicate whether grants on database objects will be imported.
176. What is the use of INDEXES option in IMP command ?
A flag to indicate whether import should import index on tables or not.
177. What is the use of ROWS option in IMP command ?
A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for
database objects will be exectued.
178. What are the types of SQL Statement ?
Data Definition Language : CREATE,ALTER,DROP,TRUNCATE,REVOKE,NO AUDIT & COMMIT.
Data Manipulation Language : INSERT,UPDATE,DELETE,LOCK TABLE,EXPLAIN PLAN & SELECT.
Transactional Control : COMMIT & ROLLBACK
Session Control : ALTERSESSION & SET ROLE
System Control : ALTER SYSTEM.
179. What is a transaction ?
Transaction is logical unit between two commits and commit and rollback.
180. What is a join? Explain the different types of joins?
J oin is a query which retrieves related columns or rows from multiple tables.
Self J oin - J oining the table with itself.
Equi J oin - J oining two tables by equating two common columns.
Non-Equi J oin - J oining two tables by equating two common columns.
Outer J oin - J oining two tables in such a way that query can also retrive rows that do not
have corresponding join value in the other table.
181. What is the Subquery ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
135
Subquery is a query whose return values are used in filtering conditions of the main query.
182. What is correlated sub-query ?
Correlated sub_query is a sub_query which has reference to the main query.
183. Explain Connect by Prior?
Retrives rows in hierarchical order.
e.g. select empno, ename from emp where.
184. Difference between SUBSTR and INSTR ?
INSTR (String1,String2(n,(m)),
INSTR returns the position of the mth occurrence of the string 2 in
string1. The search begins from nth position of string1.
SUBSTR (String1 n,m)
SUBSTR returns a character string of size m in string1, starting from nth postion of string1.
185. Explain UNION,MINUS,UNION ALL, INTERSECT ?
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 query
UNION ALL - returns all rows selected by either query,including all duplicates.
186. What is ROWID ?
ROWID is a pseudo column attached to each row of a table. It is 18 character long,
blockno, rownumber are the components of ROWID.
187. What is Referential Integrity ?
Maintaining data integrity through a set of rules that restrict the values of one or more
columns of the tables based on the values of primary key or unique key of the referenced
table.
188. What is ON DELETE CASCADE? When ON DELETE CASCADE is specified ORACLE maintains
referential integrity by automatically removing dependent foreign key values if a referenced
primary or unique key value is removed.
189. What are the data types allowed in a table ?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.
190. What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
136
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type
);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
191. Explain the usage of WHERE CURRENT OF clause in cursors ?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched
from a cursor.

192. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in
Database Trigger ? Why ?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in
a trigger, it affects logical transaction processing.
193. What are two virtual columns available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.
194. What happens if a procedure that updates a column of table X is called in a database
trigger of the same table ?
Mutation of table occurs.
195. Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
I & ii.
196. What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue
an user defined error messages from stored sub-program or database trigger.
197. Where the Pre_defined_exceptions are stored ? In the standard package.
198. What are advantages fo Stored Procedures ?
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
199. Name the tables where characteristics of Package, procedure and functions are
stored ?
User_objects, User_Source and User_error.
200. SNAPSHOT is used for
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
137
a] Synonym, b] Table space, c] System server, d] Dynamic data replication
201. We can create SNAPSHOTLOG for
a] Simple snapshots, b] Complex snapshots, c] Both A & B, d] Neither A nor B
202. Transactions per rollback segment is derived from
a] Db_Block_Buffers, b] Processes, c] Shared_Pool_Size, d] None
of the above
203. SET TRANSACTION USE ROLLBACK SEGMENT is used to create user
Objects in a particular Tablespace
a] True, b] False
204. Databases overall structure is maintained in a file called
a] Redolog file, b] Data file, c] Control file, d] All of the above.
205. These following parameters are optional in init.ora parameter file
DB_BLOCK_SIZE, PROCESSES
a] True, b] False
206. Constraints cannot be exported through EXPORT command
a] True, b] False
207. In a CLIENT/SERVER environment , which of the following would not be
done at the client ?
a] User interface part, b] Data validation at entry line, c] Responding to user events,
d] None of the above
208. Why is it better to use an INTEGRITY CONSTRAINT to validate data in a
table than to use a STORED PROCEDURE ?
a] Because an integrity constraint is automatically checked while data
is inserted into or updated in a table while a stored procedure has to be
specifically invoked
b] Because the stored procedure occupies more space in the database
than a integrity constraint definition
c] Because a stored procedure creates more network traffic than a
integrity constraint definition
209. Which of the following is not an advantage of a client/server model ?
a] A client/server model allows centralised control of data and
centralised implementation of business rules.
b] A client/server model increases developer;s productivity
c] A client/server model is suitable for all applications
d] None of the above.
210. What does DLL stands for ?
a] Dynamic Language Library
b] Dynamic Link Library
c] Dynamic Load Library
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
138
d] None of the above
211. What is a trigger
a] A piece of logic written in PL/SQL
b] Executed at the arrival of a SQL*FORMS event
c] Both A & B
d] None of the above
212. All datafiles related to a Tablespace are removed when the Tablespace
is dropped
a] TRUE
b] FALSE
213. Size of Tablespace can be increased by
a] Increasing the size of one of the Datafiles
b] Adding one or more Datafiles
c] Cannot be increased
d] None of the above
214. Multiple Tablespaces can share a single datafile
a] TRUE
b] FALSE
215. A set of Dictionary tables are created
a] Once for the Entire Database
b] Every time a user is created
c] Every time a Tablespace is created
d] None of the above
216. Datadictionary can span across multiple Tablespaces
a] TRUE
b] FALSE
217. A Transaction ends
a] Only when it is Committed
b] Only when it is Rolledback
c] When it is Committed or Rolledback
d] None of the above
218. A Database Procedure is stored in the Database
a] In compiled form
b] As source code
c] Both A & B
d] Not stored
219. A database trigger doesnot apply to data loaded before the definition
of the trigger
a] TRUE
b] FALSE
Ans : A
220. Dedicated server configuration is
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
139
a] One server process - Many user processes
b] Many server processes - One user process
c] One server process - One user process
d] Many server processes - Many user processes
221. Which of the following does not affect the size of the SGA
a] Database buffer
b] Redolog buffer
c] Stored procedure
d] Shared pool
222. Which of the following is TRUE
1] Host variables are declared anywhere in the program
2] Host variables are declared in the DECLARE section
a] Only 1 is TRUE
b] Only 2 is TRUE
c] Both 1 & 2are TRUE
d] Both are FALSE
Ans : B
221. Which of the following is NOT VALID is PL/SQL
a] Bool boolean;
b] NUM1, NUM2 number;
c] deptname dept.dname%type;
d] date1 date :=sysdate
222. Declare
fvar number :=null;
svar number :=5
Begin
goto <<fproc>>

if fvar is null then
<<fproc>>
svar :=svar +5
end if;
End;
What will be the value of svar after the execution ?
a] Error
b] 10
c] 5
d] None of the above
223. Which of the following is not correct about an Exception ?
a] Raised automatically / Explicitly in response to an ORACLE_ERROR
b] An exception will be raised when an error occurs in that block
c] Process terminates after completion of error sequence.
d] A Procedure or Sequence of statements may be processed.
224. Which of the following is not correct about User_Defined Exceptions ?
a] Must be declared
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
140
b] Must be raised explicitly
c] Raised automatically in response to an Oracle error
d] None of the above
225. A Stored Procedure is a
a] Sequence of SQL or PL/SQL statements to perform specific function
b] Stored in compiled form in the database
c] Can be called from all client environmets
d] All of the above
226. Which of the following statement is false
a] Any procedure can raise an error and return an user message and
error number
b] Error number ranging from 20000 to 20999 are reserved for user
defined messages
c] Oracle checks Uniqueness of User defined errors
d] Raise_Application_error is used for raising an user defined error.
227. Is it possible to open a cursor which is in a Package in another
procedure ?
a] Yes
b] No
228. Is it possible to use Transactional control statements in Database
Triggers ?
a] Yes
b] No
229. Is it possible to Enable or Disable a Database trigger ?
a] Yes
b] No
230. PL/SQL supports datatype(s)
a] Scalar datatype
b] Composite datatype
c] All of the above
d] None of the above
261. Find the ODD datatype out
a] VARCHAR2
b] RECORD
c] BOOLEAN
d] RAW
262. Which of the following is not correct about the "TABLE" datatype ?
a] Can contain any no of columns
b] Simulates a One-dimensional array of unlimited size
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
141
c] Column datatype of any Scalar type
d] None of the above
263. Find the ODD one out of the following
a] OPEN
b] CLOSE
c] INSERT
d] FETCH
264. Which of the following is not correct about Cursor ?
a] Cursor is a named Private SQL area
b] Cursor holds temporary results
c] Cursor is used for retrieving multiple rows
d] SQL uses implicit Cursors to retrieve rows
265. Which of the following is NOT VALID in PL/SQL ?
a] Select ... into
b] Update
c] Create
d] Delete
266. What is the Result of the following 'VIK'| | NULL| | 'RAM' ?
a] Error
b] VIK RAM
c] VIKRAM
d] NULL
267. Declare
a number :=5;
b number :=null;
c number :=10;
Begin
if a >b AND a <c then
a :=c * a;
end if;
End;
What will be the value of 'a' after execution ?
a] 50
b] NULL
c] 5
d] None of the above
268. Does the Database trigger will fire when the table is TRUNCATED ?
a] Yes
b] No
269. SUBSTR(SQUARE ANS ALWAYS WORK HARD,14,6) will return
a] ALWAY
b}S ALWA
c] ALWAYS
d] WAYS W
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
142
270. REPLACE('J ACK AND J UE','J ','BL') will return
a] J ACK AND BLUE
b] BLACK AND J ACK
c] BLACK AND BLUE
d] None of the above
271. TRANSLATE('333SQD234','0123456789ABCDPQRST','0123456789') will return
a] 333234
b] 333333
c] 234333
d] None of the above
273. Is it possible to modify a Datatype of a column when column contains
data ?
a] Yes
b] No
274. Which of the following is not correct about a View ?
a] To protect some of the columns of a table from other users
b] Ocuupies data storage space
c] To hide complexity of a query
d] To hide complexity of a calculations
275. Which is not part of the Data Definiton Language ?
a] CREATE
b] ALTER
c] ALTER SESSION
276. The Data Manipulation Language statements are
a] INSERT
b] UPDATE
c] SELECT
d] All of the above
277. EMPNO ENAME SAL
A822 RAMASWAMY 3500
A812 NARAYAN 5000
A973 UMESH
A500 BALAJ I 5750
Using the above data
Select count(sal) from Emp will retrieve
a] 1
b] 0
c] 3 as Group functions does not consider nulls
d] None of the above
278. If an UNIQUE KEY constraint on DATE column is created, will it accept
the rows that are inserted with SYSDATE ?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
143
a] Will
b] Won't
279. What are the different events in Triggers ?
a] Define, Create
b] Drop, Comment
c] Insert, Update, Delete
d] All of the above
280. What built-in subprogram is used to manipulate images in image items ?
a] Zoom_out
b] Zoom_in'
c] Image_zoom
d] Zoom_image
281. Can we pass RECORD GROUP between FORMS ?
a] Yes
b] No
282. SHOW_ALERT function returns
a] Boolean
b] Number
c] Character
d] None of the above
283. What SYSTEM VARIABLE is used to refer DATABASE TIME ?
a] $$dbtime$$
b] $$time$$
c] $$datetime$$
d] None of the above
284. :SYSTEM.EFFECTIVE.DATE varaible is
a] Read only
b] Read & Write
c] Write only
d] None of the above
285. What is built_in Subprogram ?
a] Stored procedure & Function
b] Collection of Subprogram
c] Collection of Packages
d] None of the above
286 . Sequence of events takes place while starting a Database is
a] Database opened, File mounted, Instance started
b] Instance started, Database mounted & Database opened
c] Database opened, Instance started & file mounted
d] Files mounted, Instance started & Database opened
287. SYSTEM TABLESPACE can be made off-line
a] Yes
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
144
b] No
288. ENQUEUE_RESOURCES parameter information is derived from
a] PROCESS or DDL_LOCKS & DML_LOCKS
b] LOG BUFFER
c] DB_BLOCK_SIZE
d] DB_BLOCK_BUFFERS
289. SMON process is used to write into LOG files
a] TRUE
b] FALSE
290. EXP command is used
a] To take Backup of the Oracle Database
b] To import data from the exported dump file
c] To create Rollback segments
d] None of the above
291. SNAPSHOTS cannot be refreshed automatically
a] TRUE
b] FALSE
292. The User can set Archive file name formats
a] TRUE
b] FALSE
293. The following parameters are optional in init.ora parameter file
DB_BLOCK_SIZE, PROCESS
a}TRUE
b] FALSE
294. NOARCHIEVELOG parameter is used to enable the database in Archieve
mode
a] TRUE
b] FALSE
295. Constraints cannot be exported through Export command?
a] TRUE
b] FALSE
296. It is very difficult to grant and manage common priveleges needed by
different groups of database users using roles
a] TRUE
b] FALSE
297. The status of the Rollback segment can be viewed through
a] DBA_SEGMENTS
b] DBA_ROLES
c] DBA_FREE_SPACES
d] DBA_ROLLBACK_SEG
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
145
298. Explicitly we can assign transaction to a rollback segment
a] TRUE
B] FALSE
299. What file is read by ODBC to load drivers ?
a] ODBC.INI
b] ODBC.DLL
c] ODBCDRV.INI
d] None of the above
300. Where would you look for errors from the database engine? In the alert log.
301. Give the reasoning behind using an index. Faster access to data blocks in a table.
302. Give the two types of tables involved in producing a star schema and the type of data
they hold.
Fact tables and dimension tables. A fact table contains measurements while dimension tables
will contain data that will help describe the fact tables.
303. What type of index should you use on a fact table? A Bitmap index.
304. Give two examples of referential integrity constraints. A primary key and a foreign key.
305. What command would you use to create a backup control file?
Alter database backup control file to trace.
306. Give the stages of instance startup to a usable state where normal users may access it.
STARTUP
NOMOUNT - Instance startup
MOUNT - The database is mounted
OPEN - The database is opened
307. How would you go about generating an EXPLAIN plan?
Create a plan table with utlxplan.sql.
Use the explain plan set statement_id ='tst1' into plan_table for a SQL statement
Look at the explain plan with utlxplp.sql or utlxpls.sql
308. How would you go about increasing the buffer cache hit ratio?
Use the buffer cache advisory over a given workload and then query the v$db_cache_advice
table. If a change was necessary then I would use the alter system set db_cache_size
command.
309. What is a mutating table error and how can you get around it?
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
146
This happens with triggers. It occurs because the trigger is trying to update a row it is currently
using. The usual fix involves either use of views or temporary tables so the database is selecting
from one while updating the other.
310. A tablespace has a table with 30 extents in it. Is this bad? Why or why not.
Multiple extents in and of themselves aren?t bad. However if you also have chained rows this
can hurt performance.
311. How do you set up tablespaces during an Oracle installation?
You should always attempt to use the Oracle Flexible Architecture standard or another
partitioning scheme to ensure proper separation of SYSTEM, ROLLBACK, REDO LOG, DATA,
TEMPORARY and INDEX segments.
312. Explain the use of TKPROF? What initialization parameter should be turned on to get full
TKPROF output?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements.
You use it by first setting timed_statistics to true in the initialization file and then turning on
tracing for either the entire database via the sql_trace parameter or for the session using the
ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the
trace file and then look at the output from the tkprof tool. This can also be used to generate
explain plan output.
313. When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If bad -How
do you correct it?
If you get excessive disk sorts this is bad. This indicates you need to tune the sort area
parameters in the initialization files. The major sort are parameter is the SORT_AREA_SIZE
parameter.
314. How do you prevent Oracle from giving you informational messages during and after a
SQL statement execution
The SET options FEEDBACK and VERIFY can be set to OFF.
315. What is a CO-RELATED SUBQUERY
A CO-RELATED SUBQUERY is one that has a correlation name as table or view designator in the
FROM clause of the outer query and the same correlation name as a qualifier of a search
condition in the WHERE clause of the subquery.
eg
SELECT field1 from table1 X
WHERE field2>(select avg(field2) from table1 Y
where
field1=X.field1);
(The subquery in a correlated subquery is revaluated for every row of the table or view named
in the outer query.)
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
147
316. What are various constraints used in SQL
NULL
NOT NULL
CHECK
DEFAULT
317. What are various privileges that a user can grant to another user
SELECT
CONNECT
RESOURCE
318. There is a '%' sign in one field of a column. What will be the query to find it.
'\ ' Should be used before '%'.
319. Which is more faster - IN or EXISTS
EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.
320. What a SELECT FOR UPDATE cursor represent.
SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT] The processing done in a fetch
loop modifies the rows that have been retrieved by the cursor.
A convenient way of modifying the rows is done by a method with two parts: the FOR UPDATE
clause in the cursor declaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration
statement.
321. What 'WHERE CURRENT OF ' clause does in a cursor.
LOOP
SELECT num_credits INTO v_numcredits FROM classes
WHERE dept=123 and course=101;
UPDATE students
SET current_credits=current_credits+v_numcredits
WHERE CURRENT OF X;
END LOOP
COMMIT;
END;
322. How you were passing cursor variables in PL/SQL 2.2.
In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for
a cursor variable has to be allocated using Pro*C or OCI with version 2.2,the only means of
passing a cursor variable to a PL/SQL block is via bind variable or a procedure parameter.
323. Can cursor variables be stored in PL/SQL tables.If yes how.If not why.
No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.
324. Can a function take OUT parameters.If not why.
No.A function has to return a value,an OUT parameter cannot return a value.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
148
325. What are ORACLE PRECOMPILERS.
Using ORACLE PRECOMPILERS ,SQL statements and PL/SQL blocks can be contained inside
3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND ADA.
The Precompilers are known as Pro*C,Pro*Cobol,... This form of PL/SQL is known as embedded
pl/sql,the language in which pl/sql is embedded is known as the host language.
The prcompiler translates the embedded SQL and pl/sql ststements into calls to the
precompiler runtime library.The output must be compiled and linked with this library to creater
an executable.
326. What is OCI. What are its uses.
Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No
precompiler is required,PL/SQL blocks are executed like other DML statements.
The OCI library provides
-functions to parse SQL statemets
-bind input variables
-bind output variables
-execute statements
-fetch the results
327. Difference between database triggers and form triggers.
a) Data base trigger(DBT) fires when a DML operation is performed on a data base table.Form
trigger(FT) Fires when user presses a key or navigates between fields on the screen
b) Can be row level or statement level No distinction between row level and statement level.
c) Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables
as well as variables in forms.
d) Can be fired from any session executing the triggering DML statements. Can be fired only
from the form that define the trigger.
e) Can cause other database triggers to fire.Can cause other database triggers to fire,but not
other form triggers.
328. What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE
function? 1,000,000
329. If you see contention for library caches how can you fix it
Increase the size of the shared pool.
330. If you see statistics that deal with "undo" what are they really talking about
Rollback segments and associated structures.
331. If a tablespace has a default pctincrease of zero what will this cause (in relationship to
the smon process)
The SMON process won?t automatically coalesce its free space fragments.
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
149
332. How can you tell if a tablespace has excessive fragmentation
If a select against the dba_free_space table shows that the count of a tablespaces extents is
greater than the count of its data files, then it is fragmented.
333. How many redo logs should you have and how should they be configured for maximum
recoverability
You should have at least three groups of two redo logs with the two logs each on a separate
disk spindle (mirrored by Oracle). The redo logs should not be on raw devices on UNIX if it can
be avoided.
334. Users from the PC clients are getting the following error stack:
ERROR: ORA-01034: ORACLE not available
ORA-07318: smsget: open error when opening sgadef.dbf file.
HP-UX Error: 2: No such file or directory
What is the probable cause?
The Oracle instance is shutdown that they are trying to access, restart the instance.
335. Users aren?t being allowed on the system. The following message is received:
ORA-00257 archiver is stuck. Connect internal only, until freed
What is the problem
T
he archive destination is probably full, backup the archive logs and remove them and the
archiver will re-start.
336. You attempt to add a datafile and get:
ORA-01118: cannot add anymore datafiles: limit of 40 exceeded
What is the problem and how can you fix it
When the database was created the db_files parameter in the initialization file was set to 40.
You can shutdown and reset this to a higher value, up to the value of MAX_DATAFILES as
specified at database creation. If the MAX_DATAFILES is set to low, you will have to rebuild the
control file to increase it before proceeding.
337. Can you use a commit statement within a database trigger?
Yes, if you are using autonomous transactions in the Database triggers.
338. Can cursor variables be stored in PL/SQL tables. If yes how. If not why?
Yes. Create a cursor type - REF CURSOR and declare a cursor variable of that type.
DECLARE
/* Create the cursor type. */
TYPE company_curtype IS REF CURSOR RETURN company%ROWTYPE;
/* Declare a cursor variable of that type. */
company_curvar company_curtype;
/* Declare a record with same structure as cursor variable. */
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
150
company_rec company%ROWTYPE;
BEGIN
/* Open the cursor variable, associating with it a SQL statement. */
OPEN company_curvar FOR SELECT * FROM company;
/* Fetch from the cursor variable. */
FETCH company_curvar INTO company_rec;
/* Close the cursor object associated with variable. */
CLOSE company_curvar;
END;
339. What should be the return type for a cursor variable. Can we use a scalar data type as
return type?
The return type of a cursor variable can be %ROWTYPE or record_name%TYPE or a record type
or a ref cursor type. A scalar data type like number or varchar cant be used but a record
type may evaluate to a scalar value.
340. Display the number value in Words?
select sal,(to_char(to_date(sal,j'),jsp)) from emp;
J means J ulian day, the number of days since J anuary 1, 4712 BC
and sp means to spell out.
341. Discuss row chaining, how does it happen? How can you reduce it? How do you correct
it?
Row chaining occurs when a VARCHAR2 value is updated and the length of the new value is
longer than the old value and won?t fit in the remaining block space. This results in the row
chaining to another block. It can be reduced by setting the storage parameters on the table
to appropriate values. It can be corrected by export and import of the effected table.
GENERAL INTERVIEW QUESTIONS
342. 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.
J ust be careful, there is no "decode" command available.
The syntax is:
wrap iname=myscript.sql oname=xxxx.yyy
99.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.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL
AS
cur integer;
Oracle Frequently asked Question Gurpreet Singh g6singh@hotmail.com
151
rc integer;
BEGIN
cur :=DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc :=DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
345. Virtual Indexes are another undocumented feature used by Oracle. Virtual indexes, as
the name suggests are pseudo-indexes that will not behave the same way that normal
indexes behave, and are meant for a very specific purpose.A virtual index is created in a
slightly different manner than the normal indexes. A virtual index has no segment pegged to it,
i.e., the DBA_SEGMENTS view will not show an entry for this.
Oracle handles such indexes internally and few required dictionary tables are updated so that
the optimizer can be made aware of its presence and generate an execution plan
considering such indexes.As per Oracle, this functionality is not intended for standalone usage.
It is part of the Oracle Enterprise Manger Tuning Pack (Virtual Index Wizard).
The virtual index wizard functionality allows the user to test a potential new index prior to
actually building the new index in the database.It allows the CBO to evaluate the potential
new index for a selected SQL statement by building an explain plan that is aware of the
potential new index.
This allows the user to determine if the optimizer would use the index, once implemented.
Lets Make World a better place to
work !

Das könnte Ihnen auch gefallen