You are on page 1of 297

ORACLE QUESTION BANK AND ANSWERS

1. What is RDBMS? What are different database models?

RDBMS: Relational Database Management System.

In RDBMS the data are stored in the form of tables


i.e. rows & columns.

The different database models


are 1. HDBMS = Hierarchical Database Management system.
2. NDBMs = Network Database Management System.
3. RDBMS = Relational Database Management System.

2. What is SQL?

SQL stands for Structured Query Language. SQL was derived from the
Greek word called "SEQUEL". SQL is a non- procedural language that
is written in simple English.

3. What is a transaction?

Transaction is a piece of logical unit of work done


between two successive commits or commit and rollback.

4. What is a commit?

Commit is transaction statements that make the changes permanent


into the database.

5. What is a Rollback?

Rollback is a transaction statement that undoes all changes to a savepoint


or since the beginning of the transaction.

6. What is DDL?

DDL - Data Definition Language.

It is a set of statements that is used to define or alter the


User_defined objects like tables, views, procedures, functions etc.,
present in a tablespace.

7. What is DML?

DML - Data Manipulation Language.

It is a set of statements that is used for manipulation of data.

E.g. inserting a row into a table, delete a row from a table etc.

8. What is locking?

The mechanism followed by the SQL to control concurrent operations


On a table is called locking.

9. What is a Dead lock?

When two users attempt to perform actions that interfere with one
another,this situation is defined as Deadlock.

E.g.: - If two users try to change both a foreign and its parent key
value at the same time.

10. What is a Shared Lock?

The type of lock that permits other users to perform a query, but
could not manipulate it, i.e. it cannot perform any modification
or insert or delete a data.

11. What is Exclusive Lock?

The type of lock that permits users to query data but not change
it and does not permits another user to any type of lock
on the same data. They are in effect until the end of the transaction.

12. What is Share Row-Exclusive lock?


Share Row Exclusive locks are used to look at a whole table and to
allow others to look at rows in the table but to prohibit others
from locking the table in Share mode or updating rows.

13. What is Group - Functions?

The Functions that are used to get summary information’s about group
Or set of rows in a table.
The group functions are also termed as aggregate functions.

Following are the examples of aggregate functions:

1. AVG () - To find the average value


2. MIN () - To find the minimum value of the set of rows.
3. MAX () - To find the maximum value of the set of rows.
4. COUNT () - To find the total no of rows that has values.
5. SUM () - To find the summation of the data of a given column.

14. What is indexing?

An index is an ordered list of the contents of a column or a group of


columns of a table.
By indexing a table, it reduces the time in performing queries,
especially if the table is large.

15. What are clusters?


A Cluster is a schema object that contains one or more tables that have
one or more columns in common. Rows of one or more tables that share
the same value in these common columns are physically stored together
within the database.
16. What is a View?

View is like a window through which you can view or change the information in table. A view is
also termed as a 'virtual table'.
17. What is a Rowid?

For each row in the database, The ROWID pseudo column returns a row's
address. ROWID values contain information necessary to locate a row:

* Which datablock in the data file


* Which row in the datablock (first row is 0)
* Which data file (first file is 1)
Values of the Rowid pseudocolum have the datatype ROWID.

18. What is a PRIMARY KEY?


PRIMARY KEY CONSTRAINT:

1. Identified the columns or set of columns, which uniquely identify


each row of a table and ensure that no duplicate rows exist in the
table.
2. Implicitly creates a unique index for the column (S) and
specifies the column(s) as being NOT NULL.
3. The name of the index is the same as the constraint name.
4. Limited to one per table.

Example:
CREATE TABLE loans (account NUMBER (6),
loan_number NUMBER(6),
...
CONSTRAINT loan_pk PRIMARY KEY
(account, loan_number));

19. What is a Unique constraint?


UNIQUE Constraint:

1. Ensures that no two rows of a table have duplicate values


in the specified columns(s).
2. Implicitly creates a unique index on the specified columns.
3. Index name is the given constraint name.

Example:
CREATE TABLE loans (
Loan_number NUMBER (6) NOT NULL UNIQUE,
...
);

20. What is the difference between a unique and primary key?


The Primarykey constraint is a constraint that takes care maintaining
the uniqueness of the data, enforcing the not null characteristic,
creates a self-index.
The Unique key constraint maintains only the uniqueness of the
data and does not enforce the not null characteristic to the
data column.

21. What is a foreign key?

FOREIGN KEY Constraint:

1. Enforces referential integrity constraint, which requires that for


each row of a table, the value in the foreign key matches a value in
the primary key or is null.
2. No limit to the number of foreign keys.
3. Can be in the same table as referenced primary key.
4. Can not reference a remote table or synonym.

Examples:

1. Explicit reference to a PRIMARY KEY column

CREATE TABLE accounts (


account NUMBER(10) ,
CONSTRAINT borrower FOREIGN KEY (account)
REFERENCES customer (account),
...);

2. Implicit reference to a PRIMARY KEY column

CREATE TABLE accounts (


account NUMBER(10),
CONSTRAINT borrower FOREIGN KEY (account)
REFERENCES customer,
...);

22. What is data integrity? What are the types of integrity?


1. A mechanism used by the RDBMS to prevent invalid data entry
into the base tables of the database.
2. Defined on tables so conditions remain true regardless of
method of data entry or type of transactions.

The following are the type of integrity

* Entity integrity
* Referential Integrity
* General Business rules

23. What is a Referential Integrity?

1. Enforces master/detail relationship between tables based on keys.

* Foreign key
* Update Delete restricts action
* Delete Cascade action
24. What are different data types?

The following are the different data types available in Oracle


1. Internal Data types
2. Composite Data types

Internal Data types


1. Character Datatype
2. Date Datatype
3. Row and long row data types
4. Rowid Datatype

Composite Data types

1. Table Data type


2. Record Data type

25. What is VARCHAR2? How is it different CHAR?


The Varchar2 datatype specifies a variable length character string. When you
create a varchar2 column, you can supply the maximum number of bytes of data
that it can hold. Oracle Subsequently stores each value in the column exactly
as you specify. If you try to insert a value that exceeds this length, Oracle
returns an error.

The Char datatype length is 1byte. The maximum size of the Char datatype is
255. Oracle compares Char values using the blank-padded comparison semantics.
If you insert a value that is shorter than the column length, Oracle blank-
pads the value to the column length.

26. What is datatype mixing?

There are two data types %TYPE and %ROWTYPE. The first one declares
a variable to be of the data type of the column of the table to which
it is referring.

For example, if you declare a variable like this:

my_empno emp.empno%TYPE

then, my_empno will have the data type of the empno column of the
table emp.

Similarly if you declare the variable like this:

my_emprec emp%ROWTYPE

then, my_emprec will have the data type of all the fields of the emp
table.

For example. Suppose employee table is like this:


empno number(2),
empname varchar2(10),
Sal number (10,2).

Then my_emprec will be of a data type whose first 2 positions will


be of number data type, the next 10 will be of varchar2 data type while the
last 10 will be of data type number.

One can refer to the individual fields of this record variable as


my_emprec.empno, my_emprec.empname, my_emprec.sal.

27. What is NULL?

A data field without any value in it is called a null value.

A Null can arise in the following situation


* Where a value is unknown.
* Where a value is not meaningful (i.e.) in column representing
commission for a row that does not represent salesman.

28. What is a sequence?

A sequence is a database object from which multiple users may generate


unique integers.

29. What are pseudo-columns in ORACLE?

The columns that are not part of the table are called as pseudo columns.

30. What is like operator? How is it different from IN operator?

The type of operator that is used in character string comparisons


with pattern matching.

Like operator is used to match a portion of the one character string


to another whereas IN operator performs equality condition between
two strings.

31. What is Single Row numbers Functions?

The type of function that will return value after every row is being
processed.

Following are some of the row number functions.

Function Name Purpose

1. ABS (n) returns the absolute value of a number

2. Floor (n) returns the largest integer value


equal or less than n.
3. Mod (m, n) returns the remainder of m divided by n.

4. Power (m, n) returns m raised to the n power.


5. Round (n) returns n rounded to m places
right of a decimal point.

6. Sqrt (x) returns the sqrt value of x.

7. Trunk (n, m) Returns n truncated to m decimal


places.

32. What are single row character functions?

The function that processes at value of data, which is of character datatype,


and returns a character datatype after every row is being processed are
termed as single row character functions.

Function Name Purpose.

1. Char (n) returns the character having


an ASCII value.

2. Initcap (n) returns character with first


letter of each argument in
UPPERCASE.
3. Lower (n) returns characters with
all the letters forced to
lower case.

4. ltrim(n) Removes the spaces towards


the left of the string.

5. upper(n) Returns characters with


all the letters forced to
upper case.

33. What are Conversion Functions?


The functions used to convert a value from one datatype to another
are being termed as conversion functions.

Function Name Purpose

To_char (n, (fmt)) converts a value of number datatype


to a value of character datatype.

To_number (n) converts a character value into a number.

Rowidtochar (n) converts rowid values to character datatype.


the result of this conversion is always
18 character long.

34. What are Date functions?


Functions that operate on Oracle Dates are termed as Date functions.

All date functions return a value of date datatype except the \


function months_between returns a numeric value.
Function Purpose

ADD_MONTHS (d, n) returns the date 'd' plus n months.


n must be an integer.
n can be positive or negative.

LAST_DAY (d) returns the date of the last day


of the month containing the date 'd'.

NEXT_DAY (d, char) returns date of first day of week


named after char that is later than
d, char must be a valid day of the
week.

MONTHS_BETWEEN (d, e) returns no of months between dates


d & e.

35. What is NEW_TIME function?


SYNTAX: New_time (d, a, b)

New_time function returns date and time in a time zone b and time in time
zone. a and b are character expressions.

Following are the some of the character expressions:

Character expression Description

AST Atlantic Stand or daylight time


BST, BDT Burning stand or daylight time
GMT Greenwich Mean Time.
PST, PDT Pacific Standard Time.
YST, YDT Yukon standard or daylight time.

36. What is Convert function?


Convert function converts two different implementations of the
same character set .

For instance: from DEC 8 bit multi-lingual characters to HP 8 bit


Multi-lingual character set.

Following are the character sets

US7ASCII - US7bit ASCII character set


WE8DEC - Western European 8 bit ASCII set
WE8HP - HP's Western European 8 bit ASCII set
F7DEC - DEC's French 7-bit ASCII set

Convert (char [destination], [source])

37. What is a translate function?


The function that returns a character after replacing all occurrences
of the character specified with the corresponding character is called
as translate function.
E.g. TRANSLATE ('Hello','l','L') gives you HeLLo

38. What is a soundex function?


Soundex is a function that returns a character string representing
the sound of the words in char. This function returns a phonetic
representation of each word and allows you to compare words
that are spelled differently but sound alike.

Soundex (char);

39. What is a replace function?


Replace function returns character with every occurrence of the
search string replaced with the replacement string. If the replacement
string is not supplied, all occurrences of search_string are being
removed. Replace allows you to substitute one string from another.

40. What is a Floor function?


Floor Function returns the largest integer equal to or than n

Syntax: floor (n);

41. What is INITCAP Function?


The initcap function returns char,with first letter of each word in
uppercase, all other letters in lowercase. A word is delimited by white space

42. What is ASCII Function?


The ASCII function returns the collating sequence of the first character of
lchar. There is no corresponding EBCDIC function.
On EBCDIC systems, the ASCII function will return EBCDIC collating
sequence values.

43. What is a Decode Function?


The Decode function is used to compare an expression to each search
value and returns the result if expr equals the search value.

E.g.: Decode (expr, search1, result1, [search2, result2], [default]);

44. What is Greatest Function?


The Greatest function returns the greatest of a list of values. All expr
after the first are converted to the datatype of the first before
comparison is done.

45. What are Format models?


Format models are used to affect how column values are displayed when
a format retrieved with a select command. Format models
do not affect the actual internal representation of the column.
46. Give 5 examples for DATE, Number function?
Examples for Number Function:

1. Select abs (-15) "Absolute:" from dual


2. Select mod (7,5) "Modula" from dual
3. Select round (1235.85,1) from dual
4. Select power (2,3) from dual
5. Select floor (7.5) "Floor" from dual

Examples for Date Function

1. Select sysdate from dual


2. Select sysdate-to_date (23-Sep-93) from dual
3. Select sysdate + 90 from dual
4. Select sysdate -90 from dual
5. Select next_day (sysdate,"Friday") from dual

47. What is an expression?


An expression is a group of value and operators which may be evaluated a
single values.

48. What are the types of expression?


The different types of expressions are

1. Logical expression
2. Compound expression
3. Arithmetic expression
4. Negating expression.

49. What is a synonym?


The synonym is a user-defined object that is used to define an alias name for
the user defined objects like table view etc.

50. What is a condition?


A Condition could be said to be of the logical datatype that evaluates
the expression to a True or False value.

51. What are the 7 forms of condition?


There are totally 7 forms of condition
1. A comparison with expression or subquery results.
2. A comparison with any or all members in a list or a subquery
3. A test for membership in a list or a subquery
4. A test for inclusion in a range
5. A test for nulls.
6. A test for existence of rows in a subquery
7. A test involving pattern matching
8. A combination of other conditions
51. What are cursors?
Oracle uses work areas called private SQL areas to execute SQL statements and
store processing information. This private SQL work area is known as cursors.

52. What are explicit cursors?


Cursors that are defined for performing a multiple row select are known
as explicit cursors.

Implicit cursors are the type of cursors that is implicitly opened


by the Oracle itself whenever you perform any DML statements like
Update, delete, insert or select into statements.

53. What is a PL/SQL?


PL/SQL is a transaction processing language that offers procedural
solutions.

54.What is an embedded SQL?


All the SQL statements written in a Host language are known
as Embedded SQL statements.

56. What are the different conditional constructs of PL/SQL?


The statements that are useful to have a control over the set
of the statements being executed as a single unit are called as
conditional constructs.

The following are the different type of conditional constructs


of PL/SQL

1. if <condition>
then
elsif<condition> then
end if

2. While <condition>
loop
end loop

3. loop
exit when<conditon>
end loop

4. for <var> in range1..range2


loop
end loop

5. for i in <query/cursor identifier>


loop
end loop
57. How is an array defined in PL/SQL?
Typedef <identifier> table of <datatype>
Index by binary_integer;
58. How to define a variable in PL/SQL?
Variablename datatype<size> <not null> <: = value>

59. How to define a cursor in PL/SQL?


Cursor variable is <query>

60. What are exceptions?


The block where the statements are being defined to handle internally
and userdefined PL/SQL errors.

61. What are the systems exceptions?


When an Oracle error is internally encountered PL/SQL block
raises an error by itself. Such errors are called as internal
or system defined exception.
Following are some of the internal exceptions:
1. Zero_divide, 2. No_data_found 3. Value_error 4. Too_many_rows

62. How to define our own exceptions in PL/SQL?


Define a PL/SQL variable as an exception in the variable declaration section.

In order to invoke the variable that is an exception type


use the raise statement.

Declare a exception;
Begin
statements....
-----
if x > y
then
raise a;
end if;
exception
when a then
statements,
rollback;
when others then
commit;
end;

63. How is the performance of Oracle improved by PL/SQL in Oracle?


Without PL/SQL the ORACLE RDBMS must process SQL statements one at a time,
Each SQL statement results in another call to RDBMS and higher performance
overhead. This overhead can be significant when you are issuing many
statements in a network environment.
With the PL/SQL all the SQL statements can be sent to RDBMS at one time.
This reduces the I/O operations. With PL/SQL a tool like Forms can do
all data calculations quickly and efficiently without calling on
the RDBMS .

64. What is SCHEMA?


A SCHEMA is a logical collection of related items of tables and Views.

65. What are profiles?


A Profile is a file that contains information about the areas that a user can
access.

66. What are roles?


A role is a collection of related privileges that an administrator can grant
collectively to database users.

67. How can we alter a user's password in ORACLE?


Inorder to Alter the password of the user we have to use the following
statement:

ALTER USER user_name identified by passwd

E.g.: Alter user sam identified by Paul

68. What is a tablespace in Oracle?


A tablespace is a partition or logical area of storage in a database that
directly corresponds to one or more physical data files.

69. What is an extent?


An extent is nothing more that a number of contiguous blocks that ORACLE-7
allocates for an object when more space is necessary for the object data.

70. What are PCTFREE and PCTUSED parameters?

PCTFREE: - PCTFREE controls how much of the space in a block is reserved for
statements that update existing rows in the object.
PCTUSED: - PCTUSED is a percentage of used space in a block that triggers the
database to return to the table's free space list.

71. What is a block in Oracle?


The Place where the data related to Oracle are stored physically in an
Operating System is known as block.

72. What is Client-server architecture?


A client/server system has three distinct components
• Focusing on a specific job
• A database server
A client application and a network.
A server (or back end) focuses on efficiently managing its resource Such as
database information. The server's primary job is to manage its resource
optimally among multiple clients that concurrently request the server for the
same resource.

Database servers concentrate on tasks such as

* Managing a single database of information among many concurrent


users.
* Controlling database access and other security requirements.
* Protecting database information with backup and recovery features.
* Centrally enforces global data integrity rules across all
Client applications.

A client application ("the front end") is the part of the system that users
employ to interact with data. The client applications in a client/server
database system focus on jobs such as

* Presenting an interface a user can interact with to accomplish work.


* Managing presentation logic such as popup lists on a
data entry form or bar graphs in a graphical data presentation
tool.
* Performing application logic, such as calculating fields
in a dataentry form.
* Validating data entry.
* Requesting and receiving information from a database server.

A network and communication software is the vehicle that transmit


data between the clients and the server in a system. Both the clients
and the server run communication software that allows them to
talk across a network.

Types of Client Server Architecture:

1. Dedicated Client Server Architecture


2. Multi-threaded Client Server Architecture
3. Single- Task Client Server Architecture

Dedicated Server: Connects the Client Directly to the dedicated server

Multi-Threaded Server: It is a type of architecture that is a combination of


dispatcher, listener and front-end server process to serve the requests of
many clients with minimal process overhead on the database server.

Single-Task server: In host-based database server system a user


employs a dumb terminal or terminal emulator to establish a session
on the host computer and run the client database application.

73. What is a segment in Oracle? Explain the different types?


The places where the data are stored in the allotted tablespace are called as
segments. The data may be a table or index data required by DBMS to operate.
Segments are the next logical level of a storage tablespace.
There are basically 5 types of segments
* Data segment: Contains all the data of each table
* Index segment: Contains all the index data for one or more indexes
Created for a table.

* Rollback segment: Contains the recorded actions, which should be undone


under certain circumstances like
* Transaction rollback
* Read consistency
* Temporary segment:

Whenever a processing occurs Oracle often requires temporary workspace for


intermediate stages of statement processing. These areas are known as
temporary segments.

* Bootstrap segment: Contains information of the data dictionary definition


for the tables to be loaded whenever a database is opened.

74. What is the use of Rollback segment?


It is a portion of a database that records the information about the actions
that should be undone under certain circumstances like

* Transaction Rollback
* Read consistency

75. What is read-consistency in Oracle?


Read consistency in Oracle is a process that ignores the changes by others in
a table whenever a table is queried. Read consistency in Oracle is achieved
by a statement
SET TRANSACTION READ ONLY

76. What is SGA?


SGA is System Global Area.

The library cache and dictionary cache makes up the shared pool. The shared
pool combined with buffer-cache make up the System Global Area.
Library Cache: - It stores the SQL Statements and PL/SQL Procedures.
Dictionary Cache: - Holds dictionary information in memory.
Buffer and Cache: - the place where the data related to recently requested
transaction is stored.

77. What is Back Ground Process?


The Process of server is being classified into two processes namely
Foreground and Background.

Foreground handles the request from client processes while background handle
other specific row of the database server like writing data to data and
transaction Log Files.

78. System Userid?


Whenever you create a database an Userid is automatically created related
with database administration connections. This account/userid is called
System Userid.

79. SYS Userid?


It is a special account through which DBA can execute special database
administration connections. SYS is the owner of database's data dictionary
table.

80. Data Dictionary?


It provides the details on the database objects such as columns, views Etc.,
the oracle users, the privileges and the rights of users over different
objects.

81. SQL*DBA?
SQL*DBA is a utility through which you can manage a database system
effectively.

82. ORACLE ADMINISTRATOR?


The person who takes care of monitoring the entering performances of the
database system is called, as an Oracle Administrator.Oracle Administrator is
the main person who takes care of assigning the set of to act as DBA for
monitoring certain jobs like
1. Creating primary database storage structure.
2. Monitoring database performance and efficiency.
3. Backing up and restoring.
4. Manipulating the physical location of the database.
TO CREATE DATABASE:
1. Determining appropriate values for the file limit parameters of the
create database command.
Parameters
Max data files: Determines the maximum number of data files that can ever
be allocated for the database
Max Log Files: Determines the maximum number of log groups for the
database.
Max Log Members: Maximum number of members for each log group.

84. What are database files?


The physical files of Oracle are known as database files.

85. What is a Log File?


The files that contains information about the information of recovery of
oracle database at the event of a SYSTEM CRASH or a MEDIA Failure.

86. What is an Init file?


Init files are known as Initialization Parameter files.
Init files are used for setting the parameters
* For an Oracle instance
* For Log files

87. What is a control file? What is its significance?


A control is a small binary file. It contains the entire system executable
code named as ORACLE.DCF.

A control file always consists of the following


1: Name of the database
2: Log files
3: Database creation

88. What does an UPDATE statement does?


To update rows in a table.

89. What does a Delete statement does?


To remove the rows from the table.

90. What does an insert statement do?


To insert new rows into a database.

91. What does a Select statement do?


To query data from tables in a database

92. How to create a table using selects and inserts statements?


Using Select statement:

Create table tablename


as
<Query >

Using insert statement we cannot create a table but can only append
the data into the table

Using Insert statement:

Insert into tablename


<Query>

93. How to delete duplicate rows in a table?


Delete from tablename where rowid not in
(Select min (rowid) from tablename group by column1, column2...)

94. What is an instance?


An Oracle instance is a mechanism that provides the mechanism for
processing and controlling the database.

95. What is startup and shutdown?


Startup is a process making the Oracle Database to be accessed by all
the users
There are three phases to database startup
1. Start a new instance for the database
2. Mount the database to the instance
3. Opening the mounted database

Shutdown is a process making the Oracle Database unavailable for all


the users.

There are three phases to database shutdown

1. Close database

2. Dismount the database from the instance

3. Terminate the instance.

96. What is mounting of database?

97. What is a two-phase commit?

98. What are snap-shots?


A Snapshot is a stable that contains the results of query Of one or more
tables or views, often located on a remote database.

99. What are triggers and stored Procedures?


A procedure is a group of PL/SQL statement that you call by a name. Compiled
version of procedure that is stored in a database are known as Stored
Procedures.
A database trigger is a stored procedure that is associated with a table.
Oracle automatically fires or executes when a triggering statement is issued.

100. What are Packages?


A package is an encapsulated collection of related program objects stored
together in the database.

101. What is SQL*Forms3.0? Is it a Client or a server?


Sql*Forms is a general-purpose tool for developing and executing forms based
interactive applications. The component of this tool is specially
designed for application developers and programmers and it is used for the
following tasks :
* Define transactions that combine data from multiple tables into a single
form.
* Customize all aspects of an application definition using std-fill-in-
interface to enhance the productivity and reduce learning time.

Sql*Forms3.0 is a Client.

102. What are Packaged Procedures?


A packaged procedure is a built in PL/SQL procedure that is available in all
forms.

Using packaged procedure we can build triggers to perform the following


Tasks to
* Reduce the amount of repetitive data entry.
* Control the flow of application
* Ensuring the operators always follow sequence of actions when
they use a form.

103. What are different types of triggers?


The following are the different type of triggers they are

1. Key-triggers
2. Navigational Triggers.
3. Transactional Triggers.
4. Query-based Triggers
5. Validation Triggers
6. Message - Error handling Triggers.

104. What is the difference between the restricted and Un-Restricted Packaged Procedure?
Any packaged procedure that does not interfere with the basic function
of SQL*Forms is an unrestricted packaged procedure. The Un-restricted
Packaged procedure can be used in all types of triggers.

Any packaged procedure that affects basic SQL*FORMS function is a restricted


packaged procedure. Restricted packaged procedure can be used only in key-
triggers and user-named triggers.

105. What is a system variable?


A System variable is a SQL*Forms variable that keeps track of some internal
process of SQL*Forms in state. The system variable helps us to control the
way an application behaves. SQL*Forms maintains the value of a system on a
performance basis. That is the values of all the system variables correspond
only to the current form.

106. What are Global Variables?


A Global variable is a SQL*Form variable that is active in any trigger within
a form and is active throughout SQL*Form (Run-Form) session. The variable
stores string value upto 255 characters.
107. What are the different types of objects in SQL*Forms?
A SQL*Form application is made up of objects. These objects contain all
the information that is needed and produce the SQL*Forms application.

Following are the objects of the SQL*Forms:

1. Form
2. Block
3. Fields
4. Pages
5. Triggers
6. Form-Level-Procedures.

108. What are Pages?


Pages are collection of display information such as constant text and
graphics. All fields are displayed in a page.

109. What are a Block and its types? Explain the different types of blocks?
Block is an object of Forms that describes section of a form or a subsection
of a Form and serve as the basis of default database interface.

Types of Blocks:

1. Control Block: Control block is not associated with any table in the
database. It is made up of fields that are base table fields, such as
temporary data fields.

2. Detail Block: Detail Block is associated with a master block in


Master-detail relationship. The detail block displays detail records
associated with master records in a block.

3. Master-Block: A master block is associated with a master-detail


relationship. The master block display master records associated with detail
records in the detail block.

4. Multi-record Block: A multi-record block can display more than one record
at a time.

5. Non-enterable Block: A non-enterable block consists of all non-enterable


fields.

6. Single-record Block: A single record block can display only one record at
a time.

110. What is a Screen Painter?


This is a SQL Forms "work area" where you can modify the layout of forms. The
screen painter displays one page area at a time.

111. What are the different field types?


The different types of fields in SQL*Forms are
1. Base - table field
2. Control-field
3. Enterable-field
4. Hidden-field
5. Look-up field
6. Non-enterable field
7. Scrolled - field

112.What is page Zero?


The place where the hidden fields are being placed in an application

113. What does Message procedure do?


The Message procedure displays specified text on the message line.

114. What does Name_in function do?


The Name_in packaged function returns the contents of the variable to which
you apply it. The returned value is in form of a string.

115. What does CLEAR_EOL procedure do?


Clear_Eol clears the current field's value from the current cursor position
to the end of the line or field.

116. What does On-Error trigger do?


The On-error trigger fires whenever SQL*Forms would normally cause an error
message to display. The actions of an On-Error triggers is used for the
following purposes:

* Trap and recover an error.


* Replace a standard error message with a customized message.

117. What does copy procedure do?


The Copy procedure writes a value into a field. Copy exists specifically to
write a value into that is referenced through NAME_IN packaged function.

118. What is the Arraysize parameter?


The Array-Size parameter is a block-characteristic that specifies the Maximum
number of records that SQL Forms (Run-Form) can fetch from the database at
one time.

119. What does Go_Block packaged procedures do?


The Go_Block packaged procedure navigates to the indicated Block.If the
target is non-enterable an error occurs.

120. What does ANCHOR_VIEW procedure do?


Anchor_view moves a view of a page to a new location on the screen. This
procedure effectively changes where on the screen the operator sees the view.
121. How to call a form from inside a form?
Inorder to call a form from inside a form we have to use the CALL packaged-
procedure.
Inorder to call a form from inside a form the packaged procedure Call is
used.
Syntax: CALL (Formname).

When call runs an indicated form while keeping the parent form active.
SQL*Forms runs the called form with the same SQL*Forms options as the
parent form.

122. How to send parameters to another form?


Inorder to send parameters across the forms we use the global variables.

123. How to give automatic hint text for fields?


Inorder to give automatic hint text for fields, In the field definition
screen of the fields we are having an option called Hint value. Inorder to
activate this option in the Select attribute section invoke the option called
Automatic Hint.

124. How to see key map sequences?


Inorder to see key map sequences we have to press the SHOW KEY screen
key function.

125. What is SYNCHRONIZE procedure does?


The synchronize procedure synchronizes the terminal screen with the internal
state of form, that is synchronize updates the screen display to reflect the
information that SQL*Forms has in its internal representation of the screen.

126. What is EXECUTE_QUERY procedure?


The Execute_query procedure flushes the current block, opens a query and
fetches a number of selected records. If there are changes to commit,
SQL*Forms prompts the operator to commit them during the execute_qury event.

127. How to customize system message in SQL*Forms?


Inorder to customize the system messages the On-Message trigger is used.

128. How to define the fields in WYSIWYG Format?

129. What is an On-Insert trigger? How is it different from Pre-insert


trigger?

An On-insert trigger replaces the default SQL*Forms processing for handling


inserted records during transaction posting. It fires once for each rows that
is marked for insertion into the database. An On-insert Trigger fires during
the Post and Commit Transactions event. Specifically it fires after the Pre-
insert trigger and before the
Post-insert trigger.

130. What is the difference between a Trigger and a Procedure?


Procedures can take in arguments where as Triggers cannot take in arguments.

131. How to call a stored procedure from inside a form?


To call a Stored Procedure inside a form

Trigger Text:

Procdurename<paramaters>

132. What are V2 Triggers?


V2 Triggers are the types of Triggers in which we can perform only a simple
query. And we cannot write a PL/SQL block.

133. How to rename a Form?


To rename a form select the rename option in the Action Menu. Then give the
form name. Press Accept. In the next field give the new name. Press Accept
to Execute.

134. What is a Pop -up page? How to define one?


Pop-Up Pages: -
Pop-Up page is a SQL*Forms object which overlays on an area of the current
displayed page in response to some event or for user call. To define a Pop-Up
page use the page definition form which is in the Image-Modify option. In
that form put an X in the Pop-Up field to make the current page as Pop-Up.

135. What is a Group in SQL * REPORTWRITER?


Group in ReportWriter: -

Group is a collection of fields, or single field. Usually by default a group


will bare the field, which are references by a single query. But we can
change from single query group -multi groups.

136. How do you define a Parent-child relationship in ReportWriter?


Parent - Child Relation: -

To define a Parent-Child relationship first we need more that one


Query. We should first enter the Parent Query and then the Child Query. In
the Child Query Form we should give the Parent Query Name in the desired
position and the common columns in both queries.

137. What is a Rowcount function in ReportWriter?


It is a field level function that is used for generation of automatic row
numbers related to database column that does not have null values.

138. How do you define a matrix report?


Matrix Report: -

Matrix Report is a Report that consists of Two Parent Queries and one Child
Query.

Procedure for Defining a Matrix Report:

1. Define Two Parent Queries.

2. Define a Child Query. In the Definition screen specific which column of


the child is to be related to the Query1 and to Query2.

3. After defining the queries in the Query option, In the


Group option

Place All the Groups in the option called MatrixGroup


Define the Print Direction for Query1 as down
Define the Print Direction for Query2 as across
Define the Print Direction for Child Query as cross tab

139. How do you execute a report from within a form?


Use the following command to run a report from the FORM.

Host ('runrep <rep_name> term<terminal_type> userid=<userid/passwd>);

140. What are exp and imp utilities?


Export & Import: -

Export utility is to write data from database to operating system files


called Export Files. An export does this by changing the data and table
structures in to ASCII or EBCDIC codes.

Import is a utility with which we can write the data from Export file
to database. Export Files can be only read by Import.

RIGHTS RESERVED BY DEEPAK SAMUEL K J

Questions and Answers


---------------------------------
FORMS 4.5
*************************

1. What are the different modules of forms 4.5?


Forms, menus, library.

2. What are the differences between forms 4.5 and forms 3?


Form 4.5: GUI
Forms 3.0: Cui
database objects,forms_ddl.

3. What is the maximum limit for creating blocks and canvas in forms 4.5?
Unlimited
Forms 3.0: triggers (75)
Forms 4.5: triggers (121)

4. In a multi record block can we have an item displayed once?

5. After creation of block can we have create a button palette?


No

6. What are the differences between form4.5 and forms 3.0 with regards to master detail
relationship explain all the properties of master detail in detail?
On clear details, On populate details in forms 3.0 for 1 child only one
parent but not so in forms4.5

7. What are the difference types of triggers that will be created for master deletes
properties such as isolated, non isolated, cascading?
For non-isolated

1) On-clear-details
2) On-populate-details
3) On-check-delete-master (checks for existence for child record)

For isolated

1) On-clear-details
2) On-populate-details

For cascading

1) On-clear-details
2) On-populate-details
3) Pre-delete

Coordination properties
a) Deferred by default false
Autoquery by default false
If deferred true, autoquery true->defered with autoquery
Here the child block waits for navigation once navigated to,
Automatically corresponding child rows will be displayed.
b) Deferred true, autoquery false->child block needs navigation as well as
explicit execute query.
c) Deferred false, autoquery true ->invalid as it has the same effect as
that of first (deferred false, autoquery false) Prevent masterless operation
->if true without going to the master, child rows can't be
manipulated.prevents any manipulation without master record.

8. What is the difference between creating a master detail new block window and creating
relations after creation of the blocks?
9. How to set relation properties dynamically?
Set_relation_property

10.How many types of items are there in form 4.5?


9

11.What are the different types of list items and the triggers
associated with them?
Pop_list, Combo box, T list
When list changed, When list activated

12.Can we change a color of push button?


No

13.What is the significance of other values in property of check box?


User can give a value, which is not in checked or unchecked
Not allowed (entry of other values)

13 what are the different types customs items and the triggers associated with them?
OLE, VBX.Trigger: When custom item event

14 What is the radio group? Is a dummy radio button necessary? What is the associated
trigger? How to disable a radio button dynamically?
Set radio button property (block name.radio group name, button name
, enabled,property false)
When radio changed

15.For, which type of items mouse navigable property, is applicable?


Check box, list box, image item, push button, radio buttons

16 What is the difference between text items and display item?


Text item can be navigable, display item can not be navigated.

17.What is difference between single line text items and multi line
text items?

18.What are the types of items that are always control items?
push button(not available in the base table items.Hence they are control
items)

19.How to invoke lov dynamically?


Show lov, list values

20.What do lov for validation do when it is set true?


If other values other than current listed values are entered, it will not be
accepted till a correct value is entered the list will be invoked.

21.What are the values that a where clause can reference in lov?
Block.item name, parameter, global variable

22 What is the difference between list values and show lov?


For list values we have to attach the lov to item
For show lov it is not needed
Show lov return a Boolean value depending upon that an operation can be
taken

23.What is a record group? Different types record group? How to create query record
group dynamically?
Static, query, non query
Design time->static, query only
For run time you can have all the three

24 How many no. of columns that a record group can have?


Memory should not exceed 64k

25 Give an live example where you can use non query record group?
Multi record validation

26 what does populate group return when a query succeeds?


Arg will be created dynamically it returns a number which must stored in the
variable of data type number.

27.How to change a lov from one record group to another?


Set lov property, get lov property.

28.What are the different types of canvases?


Stacked, content, htb, Vtb

29 Explain raise on entry property?


In a content canvas a stacked canvas.
Content property: raise on entry - >true
when navigation from the pop up block is returned back to content
block,pop should be disappear and this content block should appear .

30.What are the content view?


Base table view

31.What are differences between show_view and replace_content_view?

32.What are the different types of window?


Application window, secondary window
Styles->dialog, document
Depending upon modal property if modal = true modal window
if modal property false modal less window
Console window-> status, message window appears at the bottom of
the screen.

33. How to display window programmatically?


Set_window_property (window name, visible, property_true)
Show_window (window name)

34. To which types of window remove an exit property is meaningful?


For modal less window

35.To, which type of window the scroll bar, do not apply?


Modal window
36 How to scroll a window dynamically?
Set_window_property (window name, x, y)

37 How to resize a window?


Resize_window (window name, width, height)

38 How to increase the size the window dynamically?


Set_window_property (forms_mdi_window, window_status, maximize)
39 What are the window event triggers?
When window activated, when-window-resized
When-window-deactivated, when-window-closed

40 What is the console window? on what window it will be displayed?


Can we change the console window at run time?
Console window is the root window. No dynamic assignment to root
Window.where message line, status line appearing

41 Define a) property class b) Visual attributes what are the differences between property
class and visual attributes?
1.if property class, visual attributes are attached to a particular
item or objects, visual attributes take precedence over property
Class
set_block_property(block name,current_record_attribute,'va name')
Trigger can be written on property class dynamically VA can be attached to
an object but PC can not be attached

42. How to change a VA dynamically?


set_block_property,set_item_property

43. If i change a property in the field, which is, attached to a VA what will happen?
Changes from user_defined to customs

44. What is library?


PL SQL codes can be put and hence can be attached to menus forms library
itself.

45. What is difference between program units and attach library?


It is read only (AL) as it depends on the library all manipulations
Can be done

46.What types of reference can i use in library?


name in(indirect reference)

47. What are the different types of menus?


pull down,bar menu,full screen

48 How to attach menu in the form?


Form properties

49. How to replace menus dynamically?


replace menu(menu name)
50.What are all the different types of menu items?
Plain, radio, check, magic, separator

51.In which platform background menu are supported?


Full screen

52 what are the different types of codes we write in menus?


menu_startup code,menu item code

53 what are the ways of references you will be using in writing a menu code?

54 What is an alert? How to change an alert message dynamically? What types of window
is an alert? What is the max no of char?
Response window, modal window, 200,set_alert_property (an, alert_message_
text,'message');

55 how many triggers are available in forms 4.5->121


56 what is freeze and un freeze?
To see property of more than one object at a time

57 what are the diff bet global vars and para?


Global ->255k para->2
Global-> char para->char, num, data, rg, date

58 what are the objects that i can't create in the objnav?


Boiler plate text, bitmap, image, and timer.

59 what do you mean by copying and referencing?


Copying ->no updating in the main
Refer-> updating takes

60 when you copy a referenced object what will be a resultant object?


Referenced object

61 how to reuse plsql codes?


By either put it in lib or property class triggers

62 how to use ddl stmts. in forms 4.5?


Forms_ddl ();

63 discuss briefly about multi forms functionality?


Restricted procedures->open form, new
Unrestricted procedures->call form

64 how many system vars are there in forms 4.5?


42

65 what does the sys_mouse_button_pressed sys var do?


Will return the button value (left or right)

66 what is sys variable that is used to determine the current mode?


System.mode types: normal, query, enter query (always within quotes
and caps)
67 what are the various categories of triggers explain?

68 what are the diff type of editors?


Systemdefined (notepad), userdefined, default.

69 what is diff between edit_text_item and show_editor?


First one must be attached; second there is no need

70 how many built-in functions and procedures available in forms 4.5?


150.

71 what are the triggers that are valid in enter query mode?
Key-triggers, on-error, on-message, in when triggers except
When-database-record, when-val-item, when-val-rec

72 what does the property called secure? What will happen when it is set true?
For passwords settings at item level

73 what do you mean by ownership, visual views?


74 how to change default where and order by clause dynamically?
1.set_block_property (blname, default_where,'empno >1000');
2.set_block_property (blname, order_by,'itemorcolumn');

75 how to modify default navigation sequence?


In property of any item, navigation’s property's.
If at block nextnavigation block property.

76 what is all the property of items that you can validate without
Writing triggers?
default value,range,data typpe,required,primary key etc.,

77 explain detail about debugger?


78 if you are using procedures created in libs, database, formlevel
which will advantageous?
Libs

79 compare post-fetch trigger post-query trigger, post-forms-commit,


Post-database-commit, pre-query pre-select

80 a) if I have a pk in the table and while creating a block and if I


On constraint option what trigger will be created?
When-validate-item

b) If it’s a composite pk what trigger is generated?


When-validate-record

c) If I have pk, fk in table and if I on the constraint option


What trigger will be created?
When-remove-record
REPORTS 2.5
*****************************
81 what are the different types styles of reports?
Matrix, tabular, forms, form letter, mast-debt, and mail.

82 how many groups are required for a matrix report?


3

83 what are the steps involved in creating a pagewise summary column?


84 explain default layout, layouteditor

85 what is an external query?

86 through which object you are establishing link between groups?


Datalink

87 what is formula column, placeholder column?

88 what is anchor?

89 what is a parameter? Different types of parameters? Trigger associated with them?


Lexical, bind, system

90 can we use ddl statements in reports 2.5?

91 what is a drill down report?

92 trigger associated with push button?


When-button-pressed

93 what are the diff types of report triggers? List the sequence in which they fire?
94 can I use dml stmts. in format triggers?

95 what is the significance of group filter trigger?

96 how to control the number of records retrieved?

97 can we refer to column values in reports?

98 in the table I have a value for ename as Allen but I want to Print it as **** in the
preview screen printer is it possible if so how?
Set_item_property ('itna', secure, property_true);

99 I want three records to displayed in a page?

100 how to integrate reports 2.5 with forms 4.5 how to pass parameters from forms to
reports?
Run_product ();

***********************************************************************
ORACLE NON-DBA FAQ (Frequently Asked Questions)
-----------------------------------------------

TABLE OF CONTENTS
=================

1. GENERAL QUESTIONS
1.1. What is Oracle?
1.2. What are the advantages of Oracle?
1.3. What are potential disadvantages of Oracle?
1.4. What is SQL?
1.5. What is PL/SQL?
1.6. What is Procedural Option?
1.7. What products are available from Oracle?
1.8. What Public Domain interfaces are there?
1.9. What third party interfaces are available?
1.10. How portable is Oracle applications to other RDBMS?
1.11. What Query Optimizers are there?
1.12. Is there an anonymous FTP site for Oracle stuff?
1.13. What mail lists are there?
1.14. What bulletin boards are there?
1.15. What news groups are there?
1.16. How does Oracle compare to...?
2. SQL QUESTIONS
2.1. How can I avoid a divide by zero error?
2.2. Can I update tables from other tables?
2.3. Can I remove duplicate rows?
2.4. Can I update using a view?
2.5. Are views automatically updated when I update base tables?
2.6. Should we use complex views that cruel performance?
2.7. Can I implement tree-structured queries?
2.8. How can I get information on the row based on group information?
2.9. How can I get a name for a temporary table that will not clash?
2.10. How can I find out about what tables, columns and indices
there are ?
2.11. Is there a formatter for SQL statements?
2.12. What is the DUAL table?
2.13. What is the difference between CHAR and VARCHAR?
2.14. What is ROWNUM good for?
2.15. How do I get a top ten?
2.16. How can I control the rollback segment I use?
2.17. How can I order a union?
2.18. How can I rename a column?
2.19. Who are SCOTT/TIGER, SYSTEM and SYS?
2.20. Who do various access methods compare?
2.21. What are clusters?
2.22. How can I update a big table without blowing rollback segments?
2.23. Why don't I get records for the date I want?

3. SQL*PLUS QUESTIONS
3.1. How can I control the startup configuration of SQL*Plus?
3.2. Can I get a column value into a substitution variable?
3.3. How can I change the (hated default) editor to my favorite?
3.4. What is the difference between & and &&?
3.5. What is the difference between "host" and "!”?
3.6. Why can't I use a table name in a substitution variable?
3.7. How can I see all of a LONG?
3.8. How can I force a column to begin on the left of the page?
3.9. Can I alias SQL commands?
3.10. Can I escape significant punctuation marks?

4. SQL*FORMS 3 QUESTIONS
4.1. How can I get a list of values from a hard coded list?
4.2. How can I get find to look at description with list of values?
4.3. Can I edit SQL*Forms code with my text editor?
4.4. Can I edit SQL*Forms code by updating the database?
4.5. Why can't I see data in a control field?
4.6. Why is my terminal scrambled in a user exit?
4.7. What happens to LONGs?
4.8. What are user-written form level functions?
4.9. How can I use regular expressions for field validation?
4.10. What is a user-exit?
4.11. How can I call a popup window for field validation?

5. SQL*FORMS 4 QUESTIONS
5.1. What new features can be expected in forms 4
generator from CASE ?
5.2. What new features can be expected in forms 4?

6. PRO*C QUESTIONS
6.1. Why are my C variables overwritten?
6.2. Can I use C preprocessor definitions for VARCHAR size?
6.3. What can I do about "line too long" errors with version control?
6.4. Why do my compiles crash or weird things happen?
6.6. How do I use OPS$login?

7. CASE QUESTIONS
7.1. Can CASE generate forms with owner propounded to table names?
7.2. Can CASE generate V7 databases?

8. UNIX QUESTIONS
8.1. Can I create a compressed export on the fly without needing to
have the space for both the export file and the compressed file?
8.2. How can I prevent trailing spaces in a spooled report?
8.3. How can I get an environmental variable into SQL*Plus variables?
8.4. Can I pipe stuff through SQL*Plus?
8.5. Why does Pro*C compiles or programs crash on my Sun?
8.6. How can I find a lost Oracle export file?
8.7 How can I tell make about SQL*Forms?

9. MISC QUESTIONS
9.1. How can I alter table storage parameters from an export file?
9.2. What makes the best Oracle server for a network?
9.3. How can I implement version control?
9.4. What books are available about Oracle?

1. GENERAL QUESTIONS
1.1. What is Oracle?
Oracle is a trademark of Oracle Corporation and in common usage
refers to the database engine (which actually looks after the
data) and a range of front-end products.

Oracle is the largest selling SQL based RDBMS and on the whole,
is in my opinion, the most commercially useful.

Major competitors to Oracle include:


DB2 (IBM platforms only)
Informix
Ingress
Sybase
Others worth noting include
Interbase from Borland (Unix/MS-DOS)
shql (free UNIX tool works like ingress isql)
various xbase products
Postgres (Stonebraker's other work - free but
unsupported except for the Net - which is about
the same as commercial support anyway).

It is *not* to be confused with the Oracle of Delphi, which led


the market in executive information systems in the ancient world
Until about 7 BC. The chief data analyst (the Pythia) would get off
her skull on steam and Laurel leaves and mutter gibberish (Said
Quixotically on Laurel, SQL for short) which was then translated by
priests in an ambiguous manner in order to please the end-user and thus
extract a hefty donation. Probably the most famous bit of management
information was to Croesus, (King of Lydia and known in the phrase "as
rich as Croesus"), when he received the advice "If you attack the
Persians, you will destroy a great empire". Well, he did attack, and
lost his own empire. There's a moral to this story I think...

1.2. What are the advantages of Oracle?


a. Portability
Oracle is ported to more platforms than any of its competition,
running on more than 100 hardware platforms and 20 networking
Protocols. This makes writing an Oracle application fairly safe
from changes of direction in hardware and operating system, and
therefore a safe bet. One caveat, however, is that application
using some constructs (such as field level triggers) may have to
be reworked when porting them to a block mode environment. You
can also develop a fairly fully featured application with little
knowledge of the underlying OS. Personally, I have developed
applications on OS systems barely knowing how to copy and edit
text files.

b. 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. Oracle
has the largest independent RDBMS market share in VMS, UNIX and
OS/2 Server fields. 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 supported and also, proficient
staff are relatively easy to get.

c. Version Changes
Oracle seem very good at informing you in detail as to what is
not going to be supported in the next major release and usually
have some knob you can twiddle for good backward compatibility,
or simply leave it working, but with "don't use this, use xxxx
instead" warnings in the manual. Backward compatibility is very
good meaning you will not be in for an application re-write when
You upgrade the DBMS. [Compare this with the Ingress v5-6 OSQL
upgrade from hell.] I've worked with Oracle since V4 Beta and
have never been in for nasty surprises as far as syntax goes.
However, see "Version Changes" under disadvantages.

d. 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. Of course, you need the
archive mechanisms and storage space to do this, but Oracle
supports continuous archiving to tape devices spanning multiple
volumes.

e. Performance
Speed of a *tuned* Oracle database and application is quite good,
even with large databases. Oracle refer to 100 GB databases and
I have personal experience administering 10 GB databases. The
performance is not only "raw", but includes consideration of
performance with locking and transaction control.

f. Cursor Support
Oracle, like Ingress, but unlike Sybase (until Release 10 I think),
supports cursors, which ease programming when performance is needed.
A cursor basically lets you do row-by-row processing. Oracle supports
multiple cursors per Oracle connection in line with ANSI standards.

g. SQL Dialect
The dialect of SQL offered by Oracle is in my opinion superior
to the others in the extensions it offers over ANSI-2, which is
very much a lowest common denominator. Constructs such as the
absolute function and decode keyword are very powerful Oracle
additions to the standard SQL.

h. Multiple Database Support


Oracle has a superior ability to manage multiple databases
within the same transaction using a two-phase commit protocol.
This is best implemented in V7. You can fairly easily move
where data is actually stored from node to node in a network and
have data mirroring, making it easy to optimize the location of
the data from time to time. This is not so easily done with
offerings from other vendors or earlier versions of Oracle,
where you were not able to update more than one database in the
one transaction with any reliability. This meant that you could
not move data around without recoding your programs. With V7,
your DBA can optimize the location without pre-planning by
Programmers or re-examination of the code prior to the move.

i. PL/SQL
PL/SQL, the procedural extensions, is a draft ANSI standard for
procedural DBMS languages. See main discussion on PL/SQL.

j. Declarative Integrity
Oracle V7 supports declarative database integrity (the current
ANSI standard) and V6 permit you to enter the declarations.
With V6, you can get the toolset (such as SQL*Forms 3) to read
the declarations and automatically generate the required code.
With V7, not even this is required, as the database engine
automatically enforces the integrity. This means that you can
open up your database to end-users through simple third party
interfaces as they simply cannot break your business rules even
even if they try. It makes it easy to administer changes in
business and data rules as there is only one spot where the
change needs to be made. This lowers the cost of required
modification to the system because you do not have to edit all
applications code that works with the table.

It is reasonable to expect Oracle to release the first SQL-93


implementation at near-full compliance. As one DBA noted on the net
recently "With Oracle V8 I'll be out of a job because everything
will be in the file".

1.3. What are potential disadvantages of Oracle?


Cost. Oracle isn’t cheap. At least before you consider costs
of porting, programmer availability, etc, etc. Remember, you
will almost certainly need a full-time DBA. Good DBA's are not
cheap, but are worth their weight in gold. You will also need
training for programmers and DBA's. Again, not cheap, but shop
around - both for the cost of the courses and for the content.
Oracle are not the only people who give Oracle training, and
often a smaller consultancy can tailor a course for your needs
and still be cheaper per training hour per person.

If you are getting an application from a VAR, the Oracle


components can often be obtained at a good price.

Oracle is not (currently) as object-oriented as some of the


competition.

Implementation on some systems betrays the heritage of the


system it was developed on (e.g. Mail REEKS of VMS) and can be
Counter-intuitive to programmers used to their (non VMS or non
UNIX) OS. On some systems, performance is not what you would
(or were led to) expect, so you may need to upgrade your
system. (The moral of this story is use systems that are
inexpensively scalable). Joel notes particularly that IBM 9370
implementation is slow. (Hey, so is that news to us UNIX types?)

While quite a few people have commented on buggy code, poor


implementation, different keystrokes for different hardware, etc
(All of which have some justification), this is in my opinion
generally a bit harsh. Sure, when comparing Oracle to more single-
minded systems such as a compiler or programmer tool, Oracle comes of
poorly in quality. But, remember you are talking about a large system
and compare Oracle to other RDBMS systems and you'll find it actually
isn't too bad. Just make sure the DBA runs each new release in a spare
area for a while...

Version control of "source" for your applications in some products is


painful where you do not have editable ASCII files.
See the section on version control.

Version changes can give you nasty surprises. OK, so this


affects everyone, but there have been a few "patches from hell".
(Ask any VMS DBA who applied V6_36 or thereabouts). Personally
I generally start feeling comfortable around Vx.0.15 but much
prefer Vx.1).

Historically, sales staffs were more prone to hyperbolae than


your garden variety marketroid and technical support was poor.
This has improved. Still, installation and upgrade scripts have
copped a *lot* of flack in the newsgroup and I must admit to
requiring a second pass at this sort of stuff, with a decent
browse (and hack) through the install scripts in the meantime.
Just as well I had disk and time to spare that weekend... Also,
there has been quite a bit of criticism, at least here in Oz, of
the way Oracle do not inform you about important patches to the
RDBMS until you ring support with a problem...meanwhile your
data just got corrupted. Apply pressure to your support
representative to improve the situation.

1.4. What is SQL?


SQL (often pronounced SEQUEL) formally stands for Structured (or
Standard) Query Language. In common usage, however, it also
encompasses the DML (Data Manipulation Language - for inserts,
updates and deletes) and DDL (Data Definition Language - for
structuring tables).

The basic idea of SQL is to accept and process requests for the
information you want without you knowing how to extract it (like
you do for network databases).

SQL is NOT the only language available for querying relational


databases - the first versions of Ingress used "Quel", which had
some advantages over SQL. Still, SQL came from IBM, implemented
nicely by Oracle and became the de facto standard.

SQL is the subject of international standards. SQL-87 is


currently the lowest common denominator for most DB engines, but
like any language, each vendor provides extensions to (and
occasionally changes and omissions from) the standard ...

SQL-93, still draft, handles procedural extensions.

1.5. What is PL/SQL?


PL/SQL is a group of procedural extensions to the SQL language
and is available to SQL*Forms (3.0 and above), SQL*ReportWriter
(2.0 and above) and SQL*Plus (3.0 and above). Procedures
written in this language are available to be stored in the
database from version 7 of the core product.

Currently, an ANSI committee is specifying procedural extensions


to SQL, and including these in SQL-93. Oracle PL/SQL was accepted as
the first draft. SQL-93 is still at working draft stage, but the quick
read I have had of it looks like fairly standard PL/SQL with a few
extra statements thrown in. BTW, the spec is currently over 1K pages
and *not* bedtime reading unless you like browsing a cross between
legalese and BNF! Come to think of it, excellent bedtime reading if
you are an insomniac!

Early version of PL/SQL could have no direct I/O with the


process sending it to the server. Forthcoming versions do.

1.6. What is Procedural Option?


The procedural option to Oracle V7 permits you to define
database triggers (e.g. a procedure to carry out when a record
is updated, for example) and use DBMS PIPES, where an external
procedure can effectively be called from one of these triggers.
These triggers are written in PL/SQL. An example is as follows:

create or replace trigger MY_TRIGGER


after update on MY_TABLE
For each row begin
If updating ('MY_SCALAR') then
Insert into MY_AUDIT_TBL (
AUDIT_KEY,
VAL_NOW,
VAL_PREV,
DIFF,
DT,
WHO)
Values (
MY_KEY,
: new. MY_SCALAR,
: old. MY_SCALAR,
: new. MY_SCALAR -: old. MY_SCALAR,
Sysdate,
User);
End if;
End;

Note the new keywords "new" and "old".

This is similar to V6 and "Transaction Processing Option".


Basically it contained most of the "goodies" of the new version
and was licensed $erately. The TPO included sequences and the
ability to run PL/SQL at the back end.

1.7. What products are available from Oracle?


Apart from the core engine and consulting/education services...
This list is NOT exhaustive. If I have missed anything, let me
know, preferably with a quick review.

1. SQL*Plus
Known in days of yore as UFI (User Friendly Interface), this is
the basic "shell" for queries, basic reports and database
manipulation. It can be used interactively or driven from scripts.
It is a must-have, as installation requires scripts to be run
through this interface and most general administration by
programmers will be carried out through it.

Apart from the basic ability to issue SQL and PL/SQL commands,
it has a number of extensions to permit programming (parameter
passing, variables, prompting for user input, etc) and report
formatting.

It operates identically across all platforms.

2. SQL*DBA
A user-unfriendly version of SQL*Plus with extra power for DBA's.
The history editing facilities of SQL*Plus have been removed so
that you do not spend all your time in a product that has extra
(needed but dangerous) capabilities to do things like start up
and shut down your database.

It also has general performance monitoring facilities. Oracle 6


SQL*DBA is mainly line oriented but has a screen oriented
performance monitor. Oracle 7 SQL*DBA is entirely screen based
by default (although you can invoke it as follows to get line
mode)

sqldba lmode=y

3. SQL*Net
Needs to run on PC's and Mac's before you can access Oracle on
other machines. Most mid-range and larger machines have it as
part of the core product.

Needs to be used on ALL machines to communicate across platforms


or via a network. It is a separately licensed product for Unix,
MS-DOS and Macintosh versions and you need both compliant versions
to communicate between a client (which can be an RDBMS) and a server
(which must be an RDBMS).

Note that if you are running mess-Windows, you can get into real
difficulty as the SQL*Net driver cannot handle two cursors
returning data the same instant - mainly because windows is not
true multi-tasking. (Broken As Designed?).

Mind you, SQL*Net v2 is out soon and even gets over the
problem of OPS$logins when you do not actually log in to the
Oracle server.

4. SQL*Async
Gives functionality of SQL*Net but over a dialup-type line.

5. SQL*Connect
SQL Based DBMS Gateways

6. Open Gateway
SQL based and Procedural based DBMS Gateways

7. Net Interchange
Software Protocol Converter

8. SQL*Forms
A development tool for screen based applications that allows
code to be stored in database tables. Version 3.0 and above use
PL/SQL for procedural parts of the code.
Version 4 is coming out and has SQL*Menu facilities built-in.

9. SQL*ReportWriter
Helps write reports and like Forms, permits source code to be
stored in the database. Version 2, soon to be released,
includes triggered events, the ability to update the database
and uses PL/SQL. Version 1, on the other hand, is perhaps the
one Oracle product tried and discarded by most sites. Despite
improvements, Version 2 looks to be getting the same reputation.

11. Oracle*CASE
A nifty set of data dictionary (once known as SDD) and design
tools that let you model your database and processes and then
generate reasonable first cut forms, etc from the definitions.
The design sides need a GUI for model display. This product is
good, like anything out of the Oracle UK group that used to be
an independent company that Oracle purchased.

Various reviewers have commented that while there are "me too"
modeling and design tools, (and of course, no others take
advantage of Oracle-specific enhancements), Oracle*CASE has the
best capability to reverse engineer existing Oracle applications
back into the modeling dictionary.

Rumor has it that Oracle UK are currently working on extending


this product to include CASE for languages like C et al.

11. SQL*Menu
A suite of tools that allows the developer to enter menu details
into a database and generate a menu from it. It integrates well
with the other Oracle tools and has the capacity to produce
quite useful end-user documentation.

One nice feature is that a number of different menu appearances


(full screen, pull down, lotus ring-like) can be generated from
the same input specifications.

Obsolete with SQL*Forms 4.

Nearly every DBA who has had to install SQL*Menu (on UNIX platforms at
least) that I have spoken to had a hard time. Once that is done,
however, it is easy to look after.

12. Oracle*Card
Helps develop HyperCard like applications in Windows and
Mac environments.

13. Oracle Glue


Helps develop applications under MS-Windows that use things like
Excel and Visual Basic, i.e. an API for DDE applications. It
thus competes against the forthcoming Microsoft OBDC API. Sun
and Mac versions of Glue are forthcoming.

14. SQL*Graph
Prepares graphs from Oracle data.
15. SQL*Loader
Loads data from flat files into Oracle. Data can be loaded into
more than one table at a time (e.g. if your incoming data is in
the format of a master record followed by a number of detail
records).

16. RPT/RPF
An ancient reporting tool with a syntax like runoff that because
of its ability to perform updates, is still used by some batch
processes where its procedural capabilities are useful, especially
where PL/SQL is not necessarily available and the
developer does not want to put SQL in a compiled language like
C. You need this for some aspects of Oracle*CASE. The RPT part
is the program which goes through the tables and feeds data to
the RPF (formatting part). If you are using this for reports
you need more than a fair share of disk for temporary files,
especially if the RPT part must finish before RPF can start the
formatting and there is a lot of data to process. It has advantages
over SQL*ReportWriter in that the code is ASCII and HUMAN
READABLE, and can thus be put under version control tools. Also, it is
a lot faster than SQL*ReportWriter and can be altered much quicker than
wading through a m[ae]ss of menus.

Actually, my earliest comments about RPT/RPF were perceived as


somewhat dismissive, and generated quite a lot of "fan-mail" for
this product.

17. Pro*C, Pro*COBOL, Pro*Fortran...


Precompilers that let you embed SQL statements into a standard
language without *too* much trouble. While there are other
means of accessing Oracle from languages such as C (the OCI for
example), these interfaces are fairly low level and should
probably only be used when you are being fairly sophisticated.

While I cannot comment about languages other than C, the C code


that comes out of the Pro*C precompiler is NOT really editable.
Anyway, some of the function calls generated are specific to
libraries that are part of the Pro*C product. Thus taking the
generated C code to a site without a Pro*C license is probably
not a good thing to do.

18. Data*Query
A fairly new product that permits you to generate reports fairly
easily. The nice thing about this (again from Oracle UK) is that
if you have put constraints into the dictionary, then this will
pick up those relationships, so you do not have to constantly
specify the linking field between the EMP and DEPT tables, for
example. It will also do break processing and allow you to
define calculated fields easily so you do not have to retype them
all the time.

A suite of tables are kept internally, permitting users to


have easy access to their own queries and with the ability
to share queries among users.

One nice feature for administrators is the ability to set a


timed break on user queries to prevent "run-away" queries
being generated.

There are still some limitations upon the number of tables


that can be joined together, but DBA management of some
appropriate views would solve this problem.

19. Data*Browser
Running under a window this gives graphical and analysis capabilities
according to one reviewer and is pretty good.

20. Book Viewer


Hypermedia application creating and viewing

21. co-author
A grammar checking Utility

22. Oracle*Mail and Calendar/Scheduler


E-mail using Oracle to glue systems together across architectures.
Betrays a VAX VMS heritage. Probably not a bad idea, using
Oracle to glue together a mess of different architectures for
mail, but why would you want to do that when there are other
common standards for mail messages that will still work without
needing Oracle up and running? For many common networks, such
as those made of DOS, OS/2, Mac, UNIX and VMS boxes, if all you
want is a common mail facility, there are probably better
alternatives. A similar application provides office calendar
information and is packages with Oracle*Mail as Oracle Office.

23. Oracle*Financials
A BIG product with modules for accounting, human resources, etc.
If you are a large company, worth considering if you have lots of
disk and cash to spare. Even Oracle admit that if you are not a
large company, it is not worth putting on your short list. It
is reported to cost about $20K per user.

24. Oracle*TextRetrieval
Lets you access text documents using queries. Next release (2)
will support storage of common PC and Mac formats (e.g.MesS-Word
and WordPerfect). Can do keyword searches.

25. Export and Import


These produce files that can be migrated across architectures
and can produce archives of a selection of tables, users and or
indices.

26. Oracle*Terminal
Terminal specification utility, that replaced the CRT suite used
by Forms 2.3. Lets you map logical key names, key help and display
attributes to custom escape sequences. Offers much more power
than CRT, but most of us DBA's could drive CRT. If ReportWriter
is the least used because of its limitations, Terminal is the
second least used, because the documentation is limited and it
is hard to see how it all hangs together. Please someone, send
in some hints.

27. Oracle*Alert
Lets you define certain conditions that when met trigger an
event, usually an Oracle*Mail message, to someone. For example,
if monthly sales go to low, fire off a message to the sales
manager.

28. SQL Modules


Currently in beta is the V1.0 support for Oracle in host languages not
including Embedded SQL but according to ANSI Standards.

V1.0 requires Oracle V7.1 and is scheduled for production with


7.1 production version.

Languages supported will be Ada, C, COBOL and FORTRAN and follows


the 1989 ANSI standards with some of the low-level 1992 standard.
Also lets you call stored procedures.

Limitations are one SQL statement per procedure, no DDL, no


dynamic SQL, no multiple concurrent connections. Full (ish) SQL92
expected with V2.0.

....
It should probably be noted that Oracle*Forms (4.0),
Oracle*ReportWriter (2.0), Oracle*Graphics (2.0), and
Oracle*Menu will be all integrated together into one large
Oracle*Tools package, the CDE (I think it stands for Common
Development Environment).

Oracle V7 needs a "procedural option" for database triggers, etc.

Oracle 7.1 has been announced and will include Parallel Query and
Multi-Media extensions. Alpha Now, Beta mid year, Production end
of year.

Oracle 8 is slowly being revealed and will include Object Oriented


extensions, and specialized servers for images, video, sound,
text, and SQL RDBMS. Looking at the SQL-93 spec will give you a
glimpse at the way this will move -- abstract data types are defined,
etc.

1.8. What Public Domain interfaces are there?


Not Public Domain but free include various tools that Oracle will
distribute *when* you ask for them. These are utility scripts
written by the Oracle Performance Group UK. I was given them
and told that they were copyright by Oracle but freely
distributable. They do things like take snapshots of internal
SYS.V$* tables (one set for V6, one for V7), analyze forms 2,
libraries of mathematical functions for forms 3. It includes a
version 6 database defragmenter in Pro*C; (V7 automatically
defrags). It is usually distributed as a UNIX tar file on a DOS
floppy names dostools.tar.

Third Party Freebie Tools available include...

1. Oraperl
The Oraperl patches to perl are available from comp.sources.misc
archives and were written by Kevin Stock. These patch perl from
Larry Wall (see GNU or comp.sources.unix archives and
Comp.lang.perl newsgroup) to give it access to Oracle at a
fairly basic level, permitting you to even have simultaneous
connections to one or more databases (e.g. under different
Oracle logins). The perl language is available (as far as I
know) for UNIX, VMS, DOS, OS/2 and Macintoshes and is a cross
between the UNIX shell and C, and gaining rapidly in popularity.
One major advantage is that it makes many C libraries available
for use in an interpretive script language, and is thus more
powerful than the shell.

One of the useful things that comes with Oraperl is a script


that takes an SQL statement from a command line and executes it.

Another useful script takes a table and turns it into a series of


INSERT statements.

The current version of Oraperl is 2.004 (version 2, patchlevel 4).


You can get it by FTP or a mailserver from any comp.sources.misc
archive site, for example:

USA: wuarchive.wustl.edu [128.252.135.4]


Australia: archie.au [139.130.4.6]

The directory should be something like:

usenet/comp.sources.misc/volume3[0-9]/oraperl-v2/*

There are five parts and four patches.

Note that you need to get perl (and check it compiles as is), from
any GNU archive site (e.g. archie.au in ~ftp/gnu). I am using
perl v4 patch 36 at the moment with oraperl v2 patch 3. I
will put in patch 4 soon. Version 5 of perl is currently in
alpha release on ftp@netlabs.com.

The availability of other patches to perl such as curses lets you


use screen-handling functions. There is also a GUI development
environment that sits on top of Tcl/perl that could use oraperl
instead and thus create an X-windows/Oracle development platform.
This is called WAFE.

[Also available are perl patches to Sybase, Ingress and RDB. You
could possibly link them all together, although the SQL
functions have different names and syntax depending on which
interface you are using.]

I have posted a separate FAQ for oraperl that I obtained from


Kevin.

2. DBperl
Soon to be available is DBperl, which unifies the syntax of the
Sybase and Oracle patches to perl. It will also permit access
to Ingress and Interbase, with consideration now being given to
xBase requirements.

There is a mailing list, <perldb-interest@vix.com. You can mail


<Perldb-interest-request@vix.com to receive it. This contains
stuff similar to the files that flow through this newsgroup, so
a fair bit of it is technical discussion on the innards of
DBperl which may not be to your interest. As soon as I find
about releases, I will announce it in this FAQ.

Nevertheless, now is your chance to put in your wish list


and comment on the design of the API.

You can get perl-related stuff (including individual perl


interfaces to Sybase, ingress, Informix, etc) from
Ftp.demon.co.uk

3. Unload
Another utility is unload (which a lot of people rename to
sqlunload). It takes a SQL statement and creates two files, a
data loader control file and the data file. I think this was in
comp.sources.misc. I'll post it up to comp.databases.oracle if
need be (I forget where it came from originally). If anyone
Knows where it comes from and where it is archived, let me know.
I have tried to contact the author, but mail bounces.

4. TCL extensions
TCL is a GUI oriented language. Tom Poindexter has extended it
(Pretty much like perl is extended) to permit access to Sybase
and Oracle. Tom can be reached by tpoindex@nyx.cs.du.edu and
the extensions should be available from the TCl archives at
harbor.ecn.purdue.edu. Further information would be available
via the comp.lang.tcl newsgroup. TCl/Tk is also available from
Sprite.berkely.edu

5. XSQL
Just written by Jeff Stander, this takes an SQL statement and
sends the results to an X-window. See credits for his address.

6. Other GUI interface application builders


Now, I do not know too much about the following, but they could
be useful for you:
XView from xview.ecdavis.edu
Xtpanel (used by XSQL) from lth.se

7. Documentation
While they are still in draft mode, SQL93 standards are
available via gatekeeper.dec.com:~ftp/pub/standards/sql

A description of ODBC is available on Windows archives cica and


Mirrored monu6.cc.monash.edu.au: ~ftp/pub/win3/programr/odbc.lzh.
These are WinWord documents and are written using strange
styles, fonts and with missing graphics. If your desperate for
doco, have a look and see if you feel like spending the time to
make them readable.

1.9. What third party interfaces are available?


Heaps. Oracle interfaces are usually the first RDBMS interface
a third party tool vendor will support. If you are on a PC,
look at Q+E that comes with Excel 4 for Windows, providing you
have SQL*Net. (Mind you, this is an old, cut down copy of Q+E).
Some interfaces written mainly for the UNIX world support a
number of databases. Two examples I have used and found OK were
JAM (from JYACC) - good for C programmers who wanted to write
forms quickly, and UNIFY - which also supports its own backend
if you do not have Oracle (or Ingress or ...)

Other front-end tools include Gupta SQLWindows, (which can also


be used for its own database).

MS-Access and ODBC is fairly new. One criticism is that you are
prevented from using the native SQL (which removes the ability
to use Oracle extensions) because the front-end product is too
"smart" and builds the SQL for you. However, if you ask
Microsoft *nicely* they will give you access to a routine that
you can send a straight SQL statement to that is passed to the
backed RDBMS without modification, thus bypassing this problem.
(Don't you hate mushroom treatment?)

Some more detailed product notes follow.

Q+E Range of Products


---------------------
Platforms: MS-Windows, OS/2
Requires: SQL*Net if connecting to Oracle
Product Range:
Broad range of products:
ODBC development kit
If you want to write your own ODBC driver
ODBC 12-pack
ODBC drivers for common databases
Database library
"Large" model for Microsoft C.
Many databases supported.
include xbase and ASCII files
SQL used is native to the host DBMS.
xBase includes many functions
ASCII files are R/O
either delimited or fixed
Most functions also supported in MS VisBasic.
(Those fiddling with pointers are not)
Royalties on run-time. DLLs required.

Database Editor
Version 2 comes bundled with Excel4 for Win.
Version 5 can be bought as an upgrade, and is
well worth looking at.
Permits easy generation of queries from various
sources and generation of summary information.
End users can build a parameterized query
and then save it.
Has forms and report painter.
Can edit SQL text directly.
Has script ability for talking via OLE and DDE
and permitting multiple commands.
(No IF, WHILE type constructs tho).
Comes with connect library for driving Q+E
from C, Visual basic, etc.
Comes with demo templates for WinWord, add-ins
for Excel, Ami-Pro, Actor, C and
VisBasic.
Less common ODBC drivers are also available.
Contact:
Pioneer Software (US) developed it.
In Australia, contact Azonic in Sydney. (02) 878-6600
Other Notes:
Most comments about these products are very favorable and
generally include the terms "rugged" and "well-designed".
Rumor has it there are quite a few ex-Oracle guys at Pioneer.
IDAPI will be supported, but ODBC is preferred.
Apparently someone in Finland markets an OO C++
extension to the database library.
Do not know if you can open two different types of DB at
once - that would be really useful.

Clear Access
------------
Platforms: Macintosh and MS-Windows
Requires: SQL*Net
Features:
1. Point and click SQL data retrieval to applications
such as MS-Excel or flat files.
2. Script manager
3. Can link applications directly to SQL servers, e.g.
An Excel macro button can populate a worksheet.
4. Supports DAL.
Pricing:
$450 (US?) lists per station, but there are volume discounts.
Contact:
Clear Access Corp, 200 West Lowe Fairfield, and Iowa 52556
(515) 472-7077 FAX (515) 472-7198
Other Notes:
Got this info from the vendor. Have heard no reviews.

JAM from JYACC


--------------
Platforms: MS-Windows, Motif, Open Look, and Character Based
DOS, UNIX
Requires: SQL*Net
Features:
1. Can use various other formats
2. More flexible validation than forms triggers
3. Can be real-time
4. Easy C interface
Pricing:
?
Contact:
US: 800-458-3313
International: 212.267.7722
Fax: 212-608-6753
Other Notes:
Once worked in an R&D shop we others in the team were using
this. They were very happy with it. Will appeal to C and
UNIX programmers particularly because it integrates so well
with C. It seemed to be designed with uncompromising
Code-cutters in mind. Not for cowboys and novices. One
of the cute things was the ability to use UNIX regular
expression matching on fields as part of standard
validation.

SQR
---
Platforms: Various OS and databases
Features:
1. Report generation language
2. Can update the database
3. Normal OS file interface capability
Contact:
US:
Australia: Sequel P/L, Melbourne
Other Notes:
Good if you have different database and OS platforms and
want to use similar code. I used it for a short time a
few years ago, but others I trust who used it more loved
it. Quite popular.

PowerBuilder
------------
Developer tool for management of databases and generation
of front-end forms and reports.
Platform:
MS-Windows
Features:
Some CASE and OO constructs for front-end
A few internal CASE tables for back-ends
Can generate ASCII files of DDL
(No triggers or procedures)
Looks useful as a working DBA tool as well.
Interfaces to most common RDBMSs.
Contact:
Powersoft, the developer.
Other Notes:
Smells of original design for Sybase.

SuperNOVA
---------
Platforms:
MS-Windows, Motif, OpenLook
UNIX, MS-DOS, VMS
Oracle, Sybase, Ingress, Informix, C-ISAM, Teradata
Contact:
Four Seasons Software, Bilthoven, Holland.
Fax: +44 81 446 9143?
Phone: +44 81 446 6481?

SQL*ETON
--------
Meant to be like "skeleton" for Oracle Forms development.
Features:
Application development skeletons and utilities
Uses standard Oracle tools
E.g. Straight forms; no user-exits
Can retrofit existing forms.
Contact:
Logical Technologies Pvt. Ltd.
2nd Floor, 535 Flinders Lane, Melbourne, Vic, 3000, Australia
Ph: +61 3 629 5200, Fax: 629 8383
Notes:
Logical also makes Forms 2.3 to 3.0 converters - more on
this soon. They also have "Definition", an alternative
to SQL*Case.

If anybody reading this is a user or vendor of a particular


third party interface that you think should be mentioned, mail me
direct rather than via the newsgroup together with a quick summary.This
section needs expanding and correction.

1.10. How portable is Oracle applications to other RDBMS?


While the core SQL is portable, each vendor has their own
extensions and ways in which you need to structure the data
model to take advantage of the way each RDBMS does things.
To get any real performance, you need to take advantage of the
extensions, or be stuck with a lowest common denominator.
Examples of extensions include functions available to SQL (such
as decode), query constructs (such as the hierarchical CONNECT
BY PRIOR and outer join constructs) and physical storage
parameters.

Not only this, but the languages used to implement non-SQL


operations and the various tools are not compatible across
different RDBMS systems (again, unless you use a third party
tool such as Unify).

1.11. What Query Optimizers are there?


Oracle <= 6 has rule based optimization that depends on two
things, the presence of indices and the way you construct your
where clause. Oracle 7 has the option of using a statistical
optimizer.

This requires you to run jobs that get a statistical picture


of the spread of data values in columns across your database.
This information is used to help decide how to perform the
query. The data collection can be very intensive and take
ages (unless you use the ESTIMATE option which helps a lot)
and run regularly as the population of your database changes
lest your queries suffer from being optimized using misleading
data. Note that the ESTIMATE function only scans the first part
of the table, which may not be representative of the whole table.

In The Future: I’ll be bringing in edited highlights of


Tina C. London's discussion on how to optimize queries using
the V6 rule-based optimizer and how to use EXPLAIN PLAN.

1.12. Is there an anonymous FTP site for Oracle stuff?


In Germany, one has been started up by Andreas Bartlett.
Ftp.Uni-Oldenburg.DE: /pub/Unix/oracle
It is mostly empty now, but he says to feel free to upload.
In the USA, Andy Finkenstadt, is starting one up soonish
Ftp.vistachrome.com
A more general site, best known for storing DBperl stuff is
ftp.demon.co.uk: /pub/perl/DBperl/oraperl
Which is growing a suite of oraperl programs.

1.13. What mail lists are there?


Apart from those that Oracle run if you have Oracle Support....

I heard rumors about an "orawiz" mailing list that had possibly


shut down, but here are notes on what I do know.

Name: ORACLE-L (ORACLE database mailing list.)


Mail Address:
ORACLE-L@SBCCVM.BITNET
List Server Address:
LISTSERV@SBCCVM.BITNET
LISTSERV@CCVM.SUNYSB.EDU
To Subscribe:
Send "Subscribe ORACLE-L Fred J. Nerk" command to list
Server address
To Unsubscribe:
Send "SIGNOFF ORACLE-L" commands to list server address
*NOT* to mail address
Archives:
Send "INDEX ORACLE-L" to list server address for info
Extra Notes
Send "INFO REFCARD" to list server address to get reference
Send "INFO DATABASE" to list server address to get search notes
Has just started activity again after a quiet period.

1.14. What bulletin boards are there?


I do not have the details, but I heard of a BBS called SQLware or
Something that only charges an annual fee. Does not specialize in
Oracle. Have no further details. Would love them and a list of the
sort of stuff they carry (hint). Unfortunately, it is not a local call
to the States from here!

Oracle themselves set up a bulletin board for customers with


Support.

Some local user groups are setting up there own bulletin boards.
One is the Victorian Oracle Users Group here in Australia. Are
there any others?

1.15. What news groups are there?


You probably already know of comp.databases.oracle (where you
Picked this up). Comp.databases is not bad for general questions
not related specifically to Oracle problems or techniques.
There are other comp.database sub-groups such as theory, ingress,
Sybase, Informix and xbase.

BTW: On all these information access media, *PLEASE* keep traffic


down by editing severely when you are quoting another mail.
Also, if you post an question, it is useful and polite to post
a summary of replies and solutions back. For these, prefix
the subject with "SUMMARY:". This enables quick selection of
Important information from the group or your mail and allows sites to
keep only summaries. I am not trying to dictate, only speak from the
point of view of someone snowed under who wants to be able to vgrep
mail and news easily.

1.16. How does Oracle compare to...?


OK, I'll admit this section is purely personal. My asbestos
Suit is on. Mail comments if you feel strongly.

Sybase:
I would be most likely to choose Sybase if
Mainly OS/2 site
Ingress:
Oracle has better SQL
Oracle has more robust backend
Oracle is more portable
Oracle has more flexible security.
Ingress front-end tools are niftier
I would be most likely to choose Ingress if
Most using X-terminals on UNIX host
Had DBA with good UNIX SysAdmin skills
Informix:
SQL interfaces can "pipe" output of SQL SELECTS through
a host UNIX command. Nifty!
Has SQL dialect like cross of Ingress and Oracle.
I would be most likely to choose Informix if
Hosted under UNIX on small systems
Dollars were scarce
DB2:
I would be most likely to choose DB2 if
What? Me? In an IBM shoppe?

2. SQL QUESTIONS
-----------------
2.1. How can I avoid a divide by zero error?
Use the DECODE function. This function is absolutely brilliant
and functions like a CASE statement, and can be used to return
different columns based on the values of others.

For example, assume we sell products at variable cost, depending


on the ability of the purchaser to pay (e.g. academic discount).

Our table includes the following columns,


PRODUCT, (the key)
NUM_SOLD,
TOTAL_REVENUE.

Average sell price should be TOTAL_REVENUE / NUM_SOLD, but if we


have not sold any, we are in trouble. We can avoid this by
returning NULL as the result if NUM_SOLD is zero as follows:

select PRODUCT,
Decode (NUM_SOLD,
0, NULL,
TOTAL_REVENUE/NUM_SOLD) AVG_SELL_PRICE
from my_table;

OK, so that is one problem solved, but DECODES is much more


Useful and it is worth giving a couple of more examples:
Select decode (SEX_CODE,
'M', 'man',
'm', 'boy',
'F', 'woman',
'f', 'girl',
'Unknown’)
...
In the above example, SEX_CODE would be a single character code,
and the statement would return a description based on that code
or "unknown" if there was no match.

Decode is especially useful if you even want to choose different


information from two tables:
Select decode (EXPR_1,
EXPR_2, TBL_1.COL_1,
EXPR_3, TBL_2.COL_1,
TBL_1.COL_2)
from ...

The DECODE function is always worth keeping in mind. Many


times, it will be your only way to do what you want in a tricky
bit of SQL.

2.2. Can I update tables from other tables?


Yes.

For example, if we had a table DEPT_SUMMARY, we could update


the number of employees field as follows

Update dept_summary s
Set num_emps = (select count (*) from emp e
Where e.deptno = s.deptno);

2.3. Can I remove duplicate rows?


Yes, using the ROWID field, which *will* be unique. There are
many variations on this statement, but the logic will work.

This assumes an EMP table keyed on EMP_ID, which is NOT NULL.

Delete from EMP e


Where not e. ROWID = (
Select min (f. ROWID) from EMP f
Where f. EMP_ID = e. EMP_ID);

I'll get the OFFICIAL statement according to Oracle sometime.

The other good thing about ROWID is that it is the quickest way to
reference a particular row in a table, providing that no table
reorganization happens in the meantime. A possible use is to
select information from a table including the row number into a
block in SQL*Forms, and pass the ROWID to a user-exit that goes
and picks up the LONG RAW in that table and displays it as a
picture.

2.4. Can I update using a view?


Only if the view is a simple horizontal slice through a single
table. Columns from the base table can be omitted from the view
if they are NOT NULL. Note that views can be created with a
check option that prevents you using the view to insert records
Contravening selection criteria for that view.

2.5. Are views automatically updated when I update base tables?


Yes, that is the whole idea of views. The only thing Oracle
stores for a view is the text of the definition. When you
select from a view, Oracle looks up the text used to define the
view and then executes that query.

2.6. Should we use complex views that cruel performance?


Because view queries that involve sorting, grouping, etc can
lead to a high performance overhead, it might be better to write
some reports with a procedural component that fills up a
temporary table and then does a number of queries from it.
While this is non-relational, it can be justified for some
cases. Nevertheless, it is useful to have the view definition
in the database. You can then test the output from the view
against the output from your procedural manipulations. The view
definition can also be used as the unambiguous gospel.

2.7. Can I implement tree-structured queries?


Yes! Those migrating from non-RDBMS commonly ask this
Apps. This is definitely non-relational (enough to kill Codd
and then make him roll in his grave) and is a feature I have not
seen in the competition.

The definitive example is in the example SCOTT/TIGER database,


when looking at the EMP table (EMPNO and MGR columns). The
MGR column contains the employee number of the "current"
Employee’s boss.

You have available an extra pseudo-column, LEVEL, that says how


deep in the tree you are. Oracle can handle queries with a
depth up to 255.

Select LEVEL, EMPNO, ENAME, MGR


from EMP
connect by prior EMPNO = MGR
start with MGR is NULL;

You can get an "indented" report by using the level number to


Substring or lpad a series of spaces and concatenate that to the
string.

Select lpad ('’, LEVEL * 2) || ENAME...

You use the start with clause to specify the start of the
Tree(s). More than one record can match the starting condition.
One disadvantage of a CONNECT BY PRIOR is that you cannot
Perform a join to other tables. Still, I have not managed to see
anything else like the CONNECT BY PRIOR in the other vendor
Offerings and I like trees. Even trying to doing this
Programmatically in embedded SQL/C is difficult as you have to
do the top level query, for each of them open a cursor to look
for child nodes, for each of these open a cursor .... Pretty
soon you blow the cursor limit for your installation.

The way around this is to use PL/SQL, open the driving cursor with
the CONNECT BY PRIOR statement, and "join" programmatically for
each row returned.

2.8. How can I get information on the row based on group information?
Imagine we have the EMP table and want details on the employee
Who has the highest salary. You need to use a subquery.

Select e.ename, e.empno, e.sal


from emp e
where e.sal in ( select max (e2.sal) from emp e2 );

You could get similar info on employees with the highest


salary in their departments as follows

Select e.ename, e.deptno, e.sal


From EMP e
where e.sal = (
Select max (e2.sal)
From EMP e2
Where e2.deptno = e.deptno
);

2.9. How can I get a name for a temporary table that will not clash?
Use a sequence, and use the number to help you build the
Temporary table name. Note that SQL-93 is developing specific
Constructs for using temporary tables.

2.10. How can I find out about what tables, columns and indices there are?
Oracle maintains a live set of views that you can query to tell
You what you have available. In V6, the first two to look at
are DICT and DICT_COLUMNS which act as a directory of the other
dictionary views. It is a good idea to be familiar with these.
Not all of these views are accessible by all users. If you are
a DBA you should also create private DBA synonyms by running
$ORACLE_HOME/rdbms/admin/dba_syn.sql in your account.

2.11. Is there a formatter for SQL statements?


There are a number of "beautifiers" for various programs
languages. The cb and indent programs for the C language spring
to mind (although they have slightly different conventions). As
far as I know there is no formatter for SQL available. Given that
a public domain SQL parser is available, maybe someone could base
a reformatted based on the grammar definitions therein.

Note that you CANNOT use cb and indent with Pro*C as both these
Programs will screw up the embedded SQL code.

2.12. What is the DUAL table?


The DUAL table is a table with a single row and a single column
used where a table is syntactically required, for example in
SQL*Forms 2.3 where you want to use a function available to
SQL.

E.g. If we have two fields, x and y and we want y to be set to


a substring of x

Select substr (x, 2, 4) into y from dual;

If DUAL has NO rows or more than one, many forms under 2.3
syntax (or 2.3 triggers in forms 3) will not work properly.
At worst, the logic of some of the triggers in your form will be
reversed, without any message to the user and data could be
destroyed.

When I was writing Forms 2.3 code, the *first* thing I did
was to check that there was one row (and only one row) in
the DUAL table, otherwise I displayed a message to contact the
DBA and then quit the form. This was done in KEY-STARTUP.

2.13. What is the difference between CHAR and VARCHAR?


Oracle have stated that CHAR will become fixed length character
type at storage level, and that VARCHAR will be variable length.
Currently they are synonymous. This will probably mean that CHAR
types will not be able to be NOT NULL, and will take up all the
storage required when the record is first inserted. Currently,
the only physical storage required is the actual data and a
length specifier. It may also mean that restrictions such as
where RESPONSE in ('YES', 'NO')
may have to be rewritten for CHAR types as
where RESPONSE in ('YES', 'NO ')

At the level of Pro*C, of course, they are markedly different.

BTW, the behavior of CHAR will be able to be altered by a PFILE


Setting affecting V6 compatibility. With V6 compatibility ON, the
CHAR will be the same as V6. With compatibility OFF, CHAR will
be padded and VARCHAR will be a true varchar.

There are some performance gains that MIGHT be possible with padded
Strings: if the initial strings or keys are padded, then the back-end
Engine can quickly skip to the field rather than scanning for field
delimiters.

2.14. What is ROWNUM good for?


ROWNUM is a pseudo-column returned as rows are selected and
gives you a number for the row. "Fine", say a lot of people, "I
will use it to peel off the first few rows by using (ROWNUM < n)
in a WHERE clause". The problem with this is that ROWNUM is
evaluated BEFORE the sorting (though after the WHERE). Try the
following to see my point.
select ROWNUM, DEPTNO from EMP
where ROWNUM < 10
Order by DEPTNO, ROWNUM

When you think about it for a minute or two, it cannot be any


other way!

However, ROWNUM is good when you want to get a UNIQUE reference


for each row returned, as long as you do not mind the order!

2.15. How do I get a top ten?


This question gets bandied around from time to time and the answer is
often given just to use ROWNUM (see above). However, what you have
to do is order them first, then get the first ten. Some answers
included creating a temporary table created by a select with an order
by and then select from the temp table where ROWNUM<10. This will not
always work.

I do not believe that straight SQL is the way to go for such problems
when you have PL/SQL available.

My approach would be to use a PL/SQL cursor to select the ordered


data and abort the loop after 10 records. If using Pro*C, you do
not even need a temporary table. If you are using a temporary table
then you will not need it to be as big as the original, which straight
SQL will do.

2.16. How can I control the rollback segment I use?


In SQL, you may need to control the rollback segment used as the
default rollback segment may be too small for the required
transaction, or you may want to ensure that your transaction
runs in a special rollback segment, unaffected by others. The
statement is as follows:

SET TRANSACTION USE ROLLBACK SEGMENT segment_name;

On a related note, if all you are doing are SELECTS, it is worth


telling the database of this using the following:
SET TRANSACTION READ ONLY;

Both these statements must be the first statement of the


transaction.

2.17. How can I order a union?


Use the column number.

Say we are getting a list of names and codes and want it ordered
by the name, using both EMP and DEPT tables:
select DEPTNO, DNAME from DEPT
union
select EMPNO, ENAME from EMP
order by 2;

2.18. How can I rename a column?


There is no way a column can be renamed using normal SQL. It
can be done carefully by the DBA playing around with internal
SYS dictionary tables and bouncing the database, but this is
not supported. (I have successfully done it in V4 thru V6. Have
not tried it with V7.)

2.19. Who are SCOTT/TIGER, SYSTEM and SYS?


These three users are common in many databases. SCOTT is the
standard demo user, with TIGER as the password. SYSTEM/MANAGER
is a DBA account that runs the internals as far as supported use
goes and SYS/CHANGE_ON_INSTALL actually owns the internals. It is
dangerous to fiddle with objects owned by SYS.

Another common user/password is PLSQL/SUPERSECRET used for PL/SQL


demo stuff.

Oh, and don't complain about the passwords being told here. These are
default passwords. For SYSTEM and SYS they ***MUST*** be altered for
security reasons. After all, everybody knows them.

2.20. Who do various access methods compare?


How you organize your SQL and indices controls what access
methods will be used. The following ranking is valid for
V6. I do not know about V7.

QUERY PATH RANKING (lowest rank is the best)


Rank Path
1 ROWID = constant
2 Unique indexes column = constant
3 Entire unique concatenated index = constant
4 Entire cluster key = corresponding key in another
table in same cluster
5 Entire cluster key = constant
6 Entire non-unique concatenated index = constant
7 Non-unique single column index merge
8 Most leading concatenated index = constant
9 Index column BETWEEN low AND hi or LIKE 'C%'
10 Sort/merge (joins only)
11 MAX/MIN of single indexed column
12 ORDER BY entire index
13 Full table scans
14 Unindexed column = constant or column IS NULL
or column LIKE '%C%'

2.21. What are clusters?


Clustering data is a technique where the storage of records of
related tables is intermixed, with the dependent records of one
table in the same block as those of the master record.

The logic behind this is that you probably most use the
dependent records after you have accessed the master table.

That’s all fine, but having a table in a cluster prevents


you from dropping one and not the other.

Also, the master and dependent records of other tables must fit
into an Oracle block, typically 2k (though adjustable at install
time by a brave DBA). Now, if you are thinking of cluster
transactions with an account master record, how long before you
have blown 2k ?

No Oracle DBA I ever knew, apart from Oracle staff, thought that
using clusters was worth the hassle.

2.22.How can I update a big table without blowing rollback segments?

Imagine you have a HUGE table and need to update it, possibly
updating the key. You cannot update it in one go because your
rollback segments are too small. You cannot open a cursor and
commit every n records, because the cursor will close. You
cannot have a number of updates of a few records each because
the keys may change - causing you to visit records more than
once.

The solution I have used was to have one process (with SET
TRANSACTION READ ONLY) select ROWID from the appropriate rows
and pump these (via standard I/O) to another process that
looped around reading ROWIDs from standard input, updating the
appropriate record and committing every 10 records or so. This
was very easy to program and also was quite fast in execution.
The number of locks and size of rollback segments required was
minimal.

2.23. Why don't I get records for the date I want?


You are trying to retrieve data based on something like:
SELECT fld1, fld2 FROM table WHERE date_field = '18-jun-60'

You *know* there are records for that day - but none of them are
coming back to you.

What has happened is that your records are not set to midnight?
(Which is the default value if time of day not specified).

You can either use to_char and to_date functions, which can be a
bad move regarding SQL performance, or you can say
WHERE date_field = '18-jun-60' AND date_field < '19-jun-60'

An alternative could be something like


WHERE date_field between '18-jun-1960' and
to_date('23:59:59 18-jun-60', 'HH24:......YY')

3. SQL*PLUS QUESTIONS
----------------------
3.1. How can I control the startup configuration of SQL*Plus?

SQL*Plus first looks at a login.sql (global login) in a


Directory underneath the main Oracle installation directory
($ORACLE_HOME/dbs/glogin.sql for UNIX) and then in login.sql
in your CURRENT directory. I think the VMS login file is
in SYS$ORACLE, but I am not sure about that.

Late item: someone reported glogin.sql in another directory:


$ORACLE_HOME/sqlplus/admin, but I am not sure of which version
and platform. I only REPRESENT the directory as a UNIX path,
I do not know whether it was UNIX or not. Actually, I think
$ORACLE_HOME/sqlplus/admin is a much better place for it.

It is a pity that Oracle does not use a file in your $HOME


Directory, but I have hacked glogin.sql to use a file in the
$HOME if it exists.

Another alternative is to set an environment variable SQLPATH


(I.e. $SQLPATH in UNIX, %SQLPATH% in MS-DOS, and probably a
logical in VMS) that points to the directory where the login.sql
file is to be read, rather than the current directory. This can
include more than one directory, separated by colons (in UNIX,
that is ... MS-DOS probably uses semi-colons as delimiters) with
the first login.sql found being the one that is used.

3.2. Can I get a column value into a substitution variable?

Use the OLD_VALUE spec with the COLUMN command.


Imagine we want the surname of an employee to go into a variable,
getting it via the employee id.

COLUMN x OLD_VALUE y
SELECT surname x
FROM employee
WHERE emp_id = 1234;
PROMPT I found employee with surname &&y

Of course, this was more often used as a kludge before PL/SQL


became available in SQL*Plus (or if you had v6 without TPO), but
it is still useful for a number of things.

Note that some people prefer to use the NEW_VALUE directive


rather than the OLD_VALUE directive. For this example where
only one row is returned, it does not make much difference.

3.3. How can I change the (hated default) editor to my favorite?

When you type "edit" to SQL*Plus, it invokes a default editor


for your system. On DOS this is often EDLIN, on UNIX ed and on
VMS, it is usually EDT. In your login.sql file (or preferably
the glogin.sql file set up by your DBA), you should set the
variable that changes this to your favorite editor.
A possibility for UNIX:
define _editor=" /usr/ucb/vi"
A possibility for VMS:
define _editor="EVE"

3.4. What is the difference between & and &&?

You can create a "permanent" definition of a substitution


variable using DEFINE, the OLD_VALUE or NEW_VALUE clauses of a
COLUMN statement (when the SQL statement uses them) or by
referencing the variable with &&.

Use of a & does not create a permanent version and will prompt
you for a value if the variable does not exist (as will &&).
However, next time you reference the variable with & or &&, it
will ask you for the value again.

Try the following to figure it out (do not enter the "SQL" and
remember to type something in when asked, make it different each
time).
SQL undefine try_1
SQL prompt &try_1
SQL prompt &try_1
SQL prompt &&try_1
SQL prompt &&try_1
SQL prompt &try_1
SQL prompt &&try_1

Note that use of positional parameters (&1, &2, &3....) are


slightly different, they are given a "permanent" definition.

P.S. When I say "permanent" I mean permanent for the current


process.

3.5. What is the difference between "host" and "!”?

The host and! (Sometimes another character) both create operating


system commands as child processes of SQL*Plus. The difference
is that the "host" will perform variable substitution of & or &&
symbols, whereas "!" will not.

Note also that the default shorthand character varies with


platform. Under VMS, you use the $ symbol.

3.6. Why can't I use a table name in a substitution variable?

Often, people try and put a table name in a substitution


variable and then use it as follows:

define WORK_TABLE="EMP"
select &&WORK_TABLE.DEPTNO
from &&WORK_TABLE;

Mind you, the substitution in the "from" clause is OK. What is


happening is that the "." between &&WORK_TABLE and DEPTNO is a
terminator for substitution. Thus

define XYZ="ABC"
prompt &&XYZ.abc

will give "ABCabc"

Thus, you should have used

Select &&WORK_TABLE.DEPTNO
from &&WORK_TABLE;

(You can change this meaning of "." if it bugs you use the SET
command with the CONCAT argument but I do not recommend changing
it without lots of thought).

3.7. How can I see all of a LONG?

First of all, the following might be useful


SET MAXDATA 32767
SET ARRAYSIZE 1
You should then
SET LONG 5000
SET WRAP
and maybe use COLUMN xxxx FORMAT A60 WORD_WRAP for it.
Oh yeah, if there is a hex display function in Oracle SQL, but
you can't use it on a LONG when you need it.
You should also know something of the SET parameters and ensure
you do not go outside system limits.

MAXDATA Maximum total buffer size


ARRAYSIZE Number of records buffered
LONG Characters of a long "seen"

RecordSize * Arraysize must be less than MAXDATA.

Note that ARRAYSIZE defaults to 10 or 20, and you will probably


blow the MAXDATA extracting large LONGS so check these out and
put appropriate SET statements in your script.

It is worth having a couple of library scripts in Oracle that


look after these parameters in a co-ordinates way so that other
scripts could simply
start $ORACLE_HOME/local/plus/set4long TRUE
or
start $ORACLE_HOME/local/plus/set4long FALSE

3.8. How can I force a column to begin on the left of the page?
Use the COLUMN FORMAT command with FOLD (BEFORE|AFTER).

3.9. Can I alias SQL commands?


There is no real alias mechanism in SQL*Plus, but you can do
something similar using && variables.

3.10. Can I escape significant punctuation marks?


Many UNIX-oriented users like to have a general "escape" character to
remove the significance of special characters. They want to be able
to refer to a real "&" using \&, for example.

Well, you cannot. [Hint to any of you at Oracle]. What you


have to do is check out the SET command parameter that is
specific to the character you were interested in and change it.

For example:
rem alter the character
set define "~"
select "This & that are normal" from dual;
accept your input prompt "Give me a string"
Select ~your input from dual;
Set define "&"
Now this is fairly painful if you want keep track of things and
there are some characters you cannot escape.

Do a "SHOW ALL" and you'll see all the various things you can
play with.

4. SQL*FORMS 3 QUESTIONS
-------------------------
4.1. How can I get a list of values from a hard coded list?

Assume the field is SEX_CODE, use the following in the


List-of-values SQL statement

SELECT 'M', 'Adult Male' INTO SEX_CODE FROM DUAL


UNION
SELECT 'F', 'Adult Female' FROM DUAL
UNION
SELECT 'm', 'Juvenile Male' FROM DUAL
UNION
SELECT 'f', 'Juvenile Female' FROM DUAL
UNION
SELECT 'U', 'Adult Unknown' FROM DUAL
UNION
SELECT 'u', 'Juvenile Unknown' FROM DUAL

It's for a zoo catalog of animals... :-)

4.2. How can I get find to look at description with list of values?
Imagine that you are have the following list of values text for
a key (e.g. for the DEPTNO field of the EMP block):
Select DEPTNO, DNAME, LOC into: EMP.DEPTNO from DEPT

The list-of-values find capability only works on the first field


however, which is next to useless. To get the searching on the
name, you need to put the name first in the SELECT clause.

Of course, it needs somewhere to go, so you need to have a


field (GLOBAL variables won't work) that you use as a bitbucket.
Select DNAME, DEPTNO, LOC
into :CONTROL.BITBUCKET, :EMP.DEPTNO
from DEPT

Of course, you had better make: CONTROL.BITBUCKET 255 characters


wide to avoid lots of annoying truncation messages.

4.2. Can I edit SQL*Forms code with my text editor?

Yes, but it is unsupported (since IAG became SQL*Forms).


Personally, I use the SQL*Forms Designer interface to cut the
basic code and screen layout and then do the rest inside my text
editor. I wonder how many others do it this way?

Forms 2.3 is difficult because the syntax is so obtuse and


takes a fair bit of mucking around if you want to learn how
to change the logic. Just changing an SQL statement, however
is easy enough. (I was able to do it because I grew up with
SQL*Forms before it even had a screen painter or field triggers
or key triggers, so I learnt gradually).

Forms 3 is a LOT easier, but be warned, DO NOT INCLUDE TABS.


Use leading spaces. TURN OFF AUTOINDENT FEATURES OF YOUR
EDITOR (or post-process with the expand utility of UNIX which
converts tabs to spaces).

Oracle proposed not having a human readable .inp file for


SQL*Forms 4, but enough protests were received to prevent
removal of this feature.

If you are using a text editor, you must remember to reload the
form back input the database using the iac program. You will
have to remove it using "iac -d" first.

One thing worth noting is the fact that the text file (and the
database definition) permits association of prompt text to be
associated with the field, and position above or to the left of
the field, moving automatically when you edit the position of
the field. You can also automatically have the prompt repeated
in multi-row blocks.

With the screen-based interface, the text is hard-coded into


display of the form and is NOT associated with the field. Thus
you must move TWO things, the field and the associated text.

Why doesn’t Oracle support the full .inp capabilities?

By the way, check out the advantages of using .inp files as


referenced source, particularly version control mentioned near
the end of this document.

4.3. Can I edit SQL*Forms code by updating the database?

Yes, but it is unsupported. In SQL*Forms 2.3, the tables being


with "IAP", in 3.0, with "FORM". Quite often, when I change the
name of a column or table, I use a form created with forms
tables as the base tables of the blocks to update the database
and then generate the new forms.

Using these tables for reports can also be handy to compare the
definition and consistency of columns and fields that use it as
well as for technical documentation (such as "where is
Such-and-such a table used?).

One very useful thing to do is run a query that brings up fields


based on the same column and use the "duplicate field" key to
copy the help message quickly.

This can be a *lot* faster than opening up all the forms under
SQL*Forms designer, navigating a million menus and then doing
heaps of typing.

Where I have had the luxury of specifying an entire application


where each column had a unique name, it was very easy to write
scripts that updated datatypes, lengths and help from the table
definitions and comments stored in the main data dictionary
(After I had run a report to see what my update was going to
do). This gave me a high degree of confidence in the integrity
of my application. Similar scripts made help consistent for
fields across the entire application (I had a supplementary
table that kept my help keyed on field name, this was used to
update the forms database).

Depending on how you set up forms, most users see tables like
SYSTEM.FORM_APP, SYSTEM.FORM_BLK, etc. These contain code for
forms owned by that user. If you are SYSTEM, then you can see
tables SYSTEM.FORM_APP_, SYSTEM.FORM_BLK_, etc that have code
for all users in them.

4.4. Why can't I see data in a control field?

If you have the Displayed attribute on for a field, that only


means that the field is displayed, not the data. You need to
turn on ECHO INPUT, even if the field is not to be entered by
the user.

4.5. Why is my terminal scrambled in a user exit?


When running Oracle Forms, the line settings are all changed.
Particularly whether the I/O is raw or cooked. If you are doing
terminal I/O in a user exit you will need to save the settings,
set them to what you want, do your stuff and then reset them.
You can save settings with the UNIX shell command
stty -g stty.save.file
Restore settings using
stty `cat stty.save.file`

4.6. What happens to LONGs?

LONGs are only partially supported in Forms 3. Anything after


the 255th character goes to the great bit bucket in the sky.

How to deal with LONGs using forms is to get the ROWID into a
field in your form. Your user exit picks this up and selects
from the base table using the ROWID, then breaks the LONG up
into a number of forms fields.

Rumor has it that Forms 4 will handle LONGs a lot better.

4.8. What are user-written form level functions?


These are a specialized version of procedures not properly
documented. They vary from procedures in that they keyword
"function" is used, they must be declared with a return type
and the keyword "return" is used within the code. A simple
example is as follows:

DEFINE PROCEDURE
NAME = TO_FAHRENHEIT
DEFINITION = <<<
function MY_FUNCTION (
VNAME in number
) return number is
Begin
Return ((VNAME * 9 / 5) + 32);
end;

ENDDEFINE PROCEDURE

Within other code, it is used as follows:


: f := TO_FAHRENHEIT (:c);

Choosing to use a function over a procedure is a stylistic


issue. I prefer to keep all arguments to functions read-only
(i.e. declared as "in") and use them where I want to use the
result in an expression a lot. I also use the word function
for those procedures that return a simple value and do not
really perform side effects.

4.9. How can I use regular expressions for field validation?

OK, you're probably a UNIX person asking this. For those of you
that are not, regular expressions are a much more expressive way
of specifying a "wildcard string", analogous to % and _ used
with the "LIKE" keyword of SQL.

For example [A-C]*T would match T, AT, CT, CAT, BAT, BBACACCACT.

You need to write a C user exit that uses the sedstr () function.
This permits both matching (and tells you the position of the
match) or substitution (hence the name - "sed" on C strings).
This is available from any comp.sources.unix archive. This also
uses other PD code, the "regexp" package out of EMACS. You can
get EMACS from any GNU archive. Of course, you could write the
whole thing from scratch using the regexp routines provided
straight from the C libraries, but sedstr() is *MUCH* easier to
use. Novice C programmers can use sedstr (), they cannot use the
standard regexp package.

Both these archives are on archie.au in Australia, in ~ftp/gnu


and ~ftp/usenet/comp.sources.unix. I think garbo in Europe and
Simtel in the US also have this stuff. Contact your local
archive server to find the site nearest you.

4.10. What is a user-exit?


A user-exit is a routine in some other language (typically C or
Pro*C) written locally and linked in to Oracle forms. When I
say relinked, I mean create a new executable that includes your
object (*.o) files. This *must* be managed by your DBA and
thought out carefully, as your forms executable size will
increase. Also, your code should be damn well behaved or you'll
core dump everyone and be most unpopular.

User exits are called from your PL/SQL and can be passed an
argument as a bit fat string up to 255 chars. They can read and
write forms fields using "get" and "put" functions.

It is thus a bad move to include application-specific code as


user exits except where absolutely necessary. General purpose
routines are another matter. Attributes of good candidates are
(1) Good at something forms cannot do easily
(2) Not suitable for V7 DBMS pipes.
(Actually DBMS pipes are sort-of "kernel user-exits")

Examples of good candidates include


a) Getting data from non-Oracle sources: text files, other RDBMS
b) Extra string routines such as regex type searches
c) Dealing properly with LONGS
d) Fancy mathematical functions
e) Standard I/O via files and pipes
f) Inter process communication: shmem, sockets, msgq, sems, etc.

[Warning: Ad On]
Actually I've written a few of these, along with the parsing of
the single command argument into argc, **argv for you C
Programmers. Cannot release it though as it is proprietary,
although good deals negotiable with my lords and masters.
[Ad Off]

Proprietary). User-exits are good for things that are (1) not
in sqlforms area of expertise and/or (2) to be done at the front
end, not via V7 DBMS pipes. Good examples would be routines to
perform regex searches, read data from non-Oracle sources, send
Inter-process communication messages routines to calculate Normal
distribution stuff, read stuff from text files into fields.

4.10. How can I call a popup window for field validation?

OK, so you are trying to go to a popup window in your


On-validate trigger and you cannot. Basically you cannot do
"go(blk|fld) (blk|fld)name)" type things in most "on-", "pre-"
and "post-" triggers. What you need to do is

a. Write a procedure or function that does the to-and-froing.

b. Call that function from all the appropriate "key-" triggers


in that field context. You will need to check whether the
field has changed, etc.

Yep, it is ugly. Anyone got a better way?

5. SQL*FORMS 4 QUESTIONS
-------------------------
5.1. What new features can be expected in forms 4 generator from CASE?

Forms will be generated with support for forms 4 widgets such as


push buttons, radio boxes, check boxes. GUI objects will follow
layout preferences defined in the CASE dictionary.
Client-server applications will be generated appropriately.
5.2. What new features can be expected in forms 4?
Full backward compatibility with SQL*Forms 3.0. If you have
forms 2.3 code, this should be updated first to SQL*Forms 3
using iac30/iag30. Backward compatibility with SQL*Menu 5.0
is also supported. (SQL*Menu functionality is included in
SQL*Forms 4).

GUI objects (buttons, check boxes, radio buttons, images,


dynamic boilerplate, etc) even in characters and block modes.

Bitmap editor.

Support for source in flat files.

Better integration with other Oracle products (such as graphs,


etc, embedded in a form).

Shared modules: Some modules can be put into shared memory


segments if you write a nice set of library functions and
triggers. This cuts down the total memory requirements.

6. PRO*C QUESTIONS
-------------------
6.1. Why are my C variables overwritten?

This question only gets phrased this way once you've got to the
stage of debugging your programs by putting printf() calls
everywhere because you cannot figure out what is going on. It
usually stems from the fact that you have been writing C for
some time and are new to the Pro*C precompiler.

The problem is that Pro*C does *not* understand the scoping of C


variables in a file. Basically, if you have declared a variable
to Pro*C in an EXEC SQL BEGIN DECLARE .... END DECLARE section,
it is global to the file rather than limited to the C scoping
you have declared it in.

You also cannot use Pro*C to refer to the same variable in


different files (i.e. the same part of memory, by declaring
the variable to be extern in one file).

Basically, except where necessary, it might be a good idea to


limit a Pro*C source file to a single function, thus avoiding
this sort of problem.

This can pose a problem if you want to deal with varchar data
from other files, as Pro*C does the declaration for you. You
can pass the varchar across to other functions by pointers.

6.2. Can I use C preprocessor definitions for VARCHAR size?

Using Pro*C, you cannot - Pro*C has finished before the C


preprocessor gets a look in and it won't accept a symbol.

One way around is to write a set of C functions that deal with


varchars and use these in functions that do not directly access
the database. I have a suite of functions that create a varchar
library that permits such declarations, mallocs for varchars, as
well as implementations of varchar versions of string.h type
functions and conversions. You can mail me, or if I become
overwhelmed, I will post it again to comp.databases.oracle.

Another way using Pro*C is to DECLARE your Pro*C variables as


pointers to varchar, and declaring the *real* storage in parts
of the file not seen by Pro*C and using C preprocessor symbols.
You can be quite evil to embedded SQL precompilers if you are
wanting to get Oracle to return a maximum of n characters and
not overwrite your n+1th null character and thus make C strings
easy. Simply declare your C variables at the appropriate length
to C rather than in a DECLARE section. To hold a 6 character
string, you need seven bytes.

Put the EXEC SQL DECLARE section inside C comments and make the
size of the char to be 6, easy if you know that the column is
char(6). Note that the EXEC keyword must NOT appear on the line
in which the comment opens, but further down.
E.g.
/* Begin C comment
This stuff not seen by C but still visible
to Pro*C
EXEC SQL BEGIN DECLARE SECTION;
myvar char(6);
EXEC SQL END DECLARE SECTION;
End of C comment */
char myvar[7] = { 0,0,0,0,0,0,0 } ;

Note that Pro*C then assumes it is binding a 6-byte char field,


C has got 7 bytes, which you set to all null (0x) characters
and you can get data in and out quickly as Oracle will only take
or put 6 characters, but C functions like strcmp() will not
runaway as the 7th byte has a null terminating character.
Unless you hide the SQL declarations from C, you will get duplicate
definition errors, which is why you DECLARE within C comments.
Definitely not supported but can make life much easier. It is
also the nicest perversion of a language facility that I ever
cooked up. This trick was first developed for the Ingress esqlc
precompiler. Have not tried it for a while - I use my varchar
handling library to deal with varchars and I do not risk getting
into trouble should the next release of Pro*C get the smarts to
know if it is commented out. Let me know if you find it to
work.

6.3. What can I do about "line too long" errors with version control?

Version control systems usually substitute a symbol in your


original code with a longer expansion. For example, in RCS, you
can have the keyword Id that expands to include the filename,
author, date, etc. As Pro*C is at least slightly brain-damaged
in not being able to handle long lines (partially fixed by a
Command-line option that ups the limit a bit), you should be
careful of this and use separate version control key words on
different lines, e.g. the filename, author and version number
keywords should be kept separate.

You can also make it safer by using a variable in your make


files (or equivalent), PROC, defined to include the appropriate
command line switches you commonly use, including the one to set
input and output line lengths to the maximum.

6.4. Why do my compiles crash or weird things happen?


Sometimes your C compiler does not obey the System V way of doing
things. This happens in BSD derived versions of Unix (like SunOS) and
VMS. Basically if there is an option available to use System V
compatibility on your gear, then those options should be used when
working with Pro*C. See similar question in UNIX QUESTIONS
section.
If you have a "dual universe" machine, like Pyramids and some
others, make sure you do your C compilation in the AT&T System V
environment.

6.5. Can I use C++?


Pro*C is not designed for C++. You can of course use the OCI (the
Oracle C Interface) in C++ and link in the appropriate libraries as you
do not have to pass your code through the Pro*C precompiler.
If you *do* want to use C++ with embedded SQL, then what you should do
is write a "wraparound" C function in Pro*C and call this from your C++
code where appropriate. Be careful, however, because not all the code
produced from Pro*C is suitable as re-entrant code.

I believe that a third party has an SQL*C++ product available,


but I have no details as yet.

6.6. How do I use OPS$login?


Use "/" for the username/password combination

7. CASE QUESTIONS
------------------
7.1. Can CASE generate forms with owner prepended to table names?
Set the TABOWN option.

7.2. Can CASE generate V7 databases?


CASE 5.1 is needed to take full advantage of V7 constructs from
within CASE.

8. UNIX QUESTIONS
------------------
8.1. Can I create a compressed export on the fly without needing to
have the space for both the export file and the compressed file?

Yes, use named pipes.

mknod p myexport.dmp # Make the pipe


compress < myexport.dmp myexport.dmp.Z & # Background compress
Export scott/tiger filename=myexport.dmp # Do export
The only space you need is that for the final compressed file
and about 4 disk blocks for the pipe. This is because if the
pipe is full (compress might be slower than export), the writing
process is blocked until the pipe empties a bit. The result is
very efficient with disk.

You can do a similar thing the other way to import the file.

8.2. How can I prevent trailing spaces in a spooled report?


You can't. Post-process with sed:

sed -e 's/ *$//' < infile outfile

This problem affects other OS versions as well. For VMS, you


would have to write a DCL script that fiddles with SYS$INPUT
and SYS$OUTPUT and uses LEXICALS to trim the lines. Don't ask
me for details - my VMS is rusty and I do not have a manual
handy. Could someone mail me (directly) the DCL and I'll
include it here and move the question to SQL*Plus.

8.3. How can I get an environmental variable into SQL*Plus variables?

a. Create a sequence accessed in glogin.sql (e.g. my_seq)


This permits you to have a "unique" number to build
a file that will not conflict with another process.

Column x old_value tmp_num noprint;


Set heading off
Set pause off
Select my_seq.newvalue x from dual;

b. Create a getenv.sql script like the following


host echo "define &1=\"$&1\"" $HOME/s&&tmp_num..sql
start $HOME/s&&tmp_num..sql
host rm $HOME/s&&tmp_num..sql

c. When you want to create a variable "LOGNAME" that reflects the


LOGNAME environment variable, do the following

start getenv.sql LOGNAME

OK, so it is a bit resource heavy, and may need to be altered


for your implementation, but you should get the basic idea. Of
course, SQL variables are NOT case sensitive....

Other operating systems can do a similar thing, I would expect,


but not necessarily so easily. Under VMS, for example, I had to
write a C program that did a getenv(3C) and then produced the
Sqlplus script file that had the define in it. However,
because of the process model of VMS, it was much too slow
apart from the most important variables. Maybe let the C
program take multiple arguments and produce a line for each.

8.4. Can I pipe stuff through SQL*Plus?


Yes. For example in vi, I often need to reference a table
structure. I simply type "desc EMP" into a new line in my
buffer, :.,.!Sqlplus -s / and wait for the employee table
description to appear, which then gets cut and pasted into the
SQL statement I want. Piping through grep is handy, as is
through sed or even awk for formatting. Seriously though, get
Oraperl.

8.5. Why does Pro*C compiles or programs crash on my Sun?


Some Background
---------------
SunOS 4.x (a.k.a. Solaris 1) is a BSD based OS. It comes with
two C compilers. One is in /usr/bin/cc (which should be linked
to /bin/cc) and it the BSD compiler, pointing to BSD header
files and libraries. The other is in /usr/5bin/cc (which should
be linked to /5bin/cc) and points to AT&T System V headers and
libraries. You may have GNU C installed on your system. Note
that Solaris 2 is System V-based.

SunOS 4.1 comes standard with TWO C Compilers.


/bin/cc The BSD based compiler
Gets default includes and libraries from
/usr/include and /usr/lib
/5bin/cc The AT&T compiler
Gets default includes and libraries from
/usr/5include and /usr/5lib

You may also have GNU C installed on your system. This too is
based upon BSD.

The BSD and AT&T compilers use libraries and include files from
different directories, reflecting the system libraries of the two
different dialects of UNIX. Sometimes the function is just called
under another name, sometimes the number of parameters (and their
ordering) is different.

Examples include
Get working directory getcwd vs. getwd
Copy Memory memcpy vs bcopy
Compare Memory memcmp vs bcmp

Oracle Pro*C libraries call System V library functions if one is


Commonly available for your architecture. Obviously, if the Oracle
libraries have references to the System V version, they will either be
unresolved in the BSD libraries, or worse, resolve to something
inappropriate.

What to Do
----------
Oracle recommends that when using Pro*C (or even installing and
linking Oracle) you have the /5bin directory ahead of /bin in your
PATH variable.

[This is good practice anyway, because you will get used to the
System V versions of commands (df and ps are good examples of this -
I usually create a soft link to /bin/ps and /bin/df as
/usr/local/bin/bps and /usr/local/bin/bdf - a similar practice to
HP when they supply both versions of a utility). ]

You might like to try the following if you *really* want to use
the GNU C (or other BSD) compiler.
(1) Using GNU C, but point at System V libraries
(2) Using GNU C and libraries but add in your own, written
in GNU C that mimic the system V calls. You'll know
which ones you need, as they will be the unresolved
references. Some of these may simply be stubs that call
the BSD function of a different name or reorder the
parameters.
(3) Extract the functions you need from the System V libraries
and add them to your list to be linked in via the make
file.

When working in the Oracle environment (or simply to help you


change to a System V frame of mind), you should put the System V
directories ahead of the BSD directories in your PATH. Also,
the CC variable (especially in your Makefiles) should point to
the System V compiler. Alternatively, you can try using the
-I /5include and -L /5lib flags ahead of other directories.
(These are probably linked from /usr/5include and /usr/5lib).

Look, I know it involves some hacking, but if you are that keen on Gnu
C and only using your products in-house, you should be OK. I am not
knocking Gnu C, mind you. Gnu C is a must for many shops developing
in-house code and compiling things from the net. One R&D shop I
worked in tried it out on our code, and it gave tighter executables
than the native HP compiler at the time!

One other thing to note if you are running Solaris 2 is that the
good C compiler has been unbundled. The compiler that comes
standard with Suns now is reported by some to be dain bramaged.
If you are serious about your compiler (and you should be if you
are running Oracle) then spend the money and get the *REAL*
developers kit. (At least this is not as bad as some UNIX
systems distributed without a compiler!)

8.5. How can I find a lost Oracle export file?

You need to add a description of the layout of an export file to


the /etc/magic file. See magic (4) and file (1) for details. Use
the fact that an Oracle export starts with a control-A and then
the word EXPORT and the version number of the export that
produced it. (Use the string (1) or od (1) command to check this
out). Your system administrator can then edit /etc/magic to not
Only recognize an export file but tell you the version number
when you use file(1). Say the key description was "Oracle
Export", you can look for Oracle export files from the current
directory and below as follows:

find . -type f -exec file {} \; | grep "Oracle Export" | \


sed -e 's/:.*//'
8.6. How can I tell make about SQL*Forms?
I use a make include file $ORACLE_HOME/local/include/oracle.mk.
Among other things it sets up the following:
OUP = / # Oracle user/password, defaults to OPS$login
IAG = iag30 # Generates .frm from .inp
IAC = iac30 # Converts b/w FORM_% tables and .inp
# I use .dbo to sign a form out of database, and .dbi as a sign-in
. SUFFIXES: .inp .frm .dbo .dbi

. Inp.frm:
- rm $*.frm $*.erf
- $(IAG) $* $(OUP) $*. inp.err 2&1
test $*.frm

. inp.dbi:
- rm $*.frm $*.erf
- $(IAG) $* $(OUP) $*. inp.err 2&1
test $*.frm
- $(IAC) -d $* $* $(OUP)
$(IAC) -i $* $* $(OUP)
touch $*.dbi

. dbo.inp:
- mv $*.inp $*.inp.bak
$(IAC) $* $* $(OUP)
- touch $*.dbo
touch $*.inp

9. MISC QUESTIONS
------------------
9.1. How can I alter table storage parameters from an export file?

Use the undocumented INDEXFILE=xxxxx parameter. This creates


an ASCII file "xxxxx" with the table creation statements REMmed
out and the index creation statements not. Edit this to change
the table storage parameters (such as initial size, tablespace,
etc).

Example:
imp scott/tiger filename=myexport.dmp indexfile=myexport.sql

BTW, it IS documented in V7.

9.2. What makes the best Oracle server for a network?


OK, I am biased and will say get a Sun. Even the low-end
SPARClassic might service around 32 concurrent users, but you
are limiting your upgradeability. A SPARC-10 is probably the best
Option for mid-range stuff for the long term. If you are
pushing departmental servers (users pushing the 100 mark and
above) consider the SPARCserver 1000 series.

There is some justification for this, Oracle do most of their


development on Suns, more Oracle licences go onto Suns than
anything else and so releases will be timely and well supported.
Also, as the most important source of revenue for Oracle is UNIX
based, going UNIX for the server is pretty sensible.

Actually, Oracle and Sun get to look at each other's source code
at early development levels and are HEAVILY allied against the
common enemy, a.k.a Bill Gates.

Talk is that Oracle and Sun is about to release benchmarks


using Oracle V7 and Sun's Solaris 2.1 that will show very good
bang for buck compared to anything else.

The other thing is that Sun's Solaris 2.2 is rumored to have


RAID and Journalled File Systems, making it virtually OK to kick
out the power supply without too much drama. This combined with
Oracle DBA tools makes a pretty good fault tolerant machine.

With Netware (Novell) and WABI (run Windows binaries) facilities


available or bundled, it is a pretty attractive machine.

In the mid-range, I do think I should at least mention HP and


Sequent. Certainly I have never had any problems with HP kit or
service.

For low end users, even though a Novell, or OS/2 server might
look cheaper, I do think that UNIX makes a better architecture
for something as complex as a multi-user database to live in.
Unless, of course, rumors of Novell bundling Oracle sometime in
the future are true and the price becomes impossible to resist.
The (apparent) lack of Virtual Memory in Novell means the Oracle
server could run out of memory and blow up.

Windows NT could be interesting. It promises heaps of features,


but on looking recently at the "system calls" for Windows I
balked at the loss of clean elegance at UNIX structures. Perhaps
Windows NT will be just as threatening. [What platform does NT
perform best on? A 35mm slide projector :-)] Its chief
designer, an ex-DEC SE, however, does deserve respect tho.

9.3. How can I implement version control?


The issue of version control for Oracle applications code is a
sticky one and is complicated by issues of different operating
systems, but most especially by Oracle's predilection for
Non-ASCII storage formats. Note the ruckus caused when Oracle
proposed no ASCII .inp format file for Forms4.

Version control is an important issue for MIS departments however


and MUST be successfully addressed, otherwise things start
falling apart.

1. Choice of Version Control Tool


----------------------------------
There are a number of version control tools available for
different platforms. These include CMS for VAX/VMS and SCCS for
AT&T UNIX. In the MS-DOS world, most formats are proprietary.
Our choice of tool was RCS however, because of the following
reasons

a. Reports and management are more user friendly than SCCS, the
default tool for UNIX, our main development platform (although
our network includes DOS and VMS nodes).

b. Source code is available in the public domain from most


sites archiving GNU code. This makes it possible to port it
fairly easily, especially if you are running VAX/VMS and have
either the POSIX C libraries or using GNU C. DOS source code
and binaries are also available. We can also modify the way
some of the programs (particularly the report programs) work to
perform extra things we like.

c. The binary files used to store initial code and deltas (from
which any version can be retrieved) are compatible across
architectures. For example, I can use the DOS RCS programs to
extract source files from the binary RCS files transferred from
the UNIX machine.

d. An add-on, CVS, also available in the public domain, permits


fairly easy management where TWO sites are carrying out
concurrent development. This is common where a vendor is
providing the source, but some local changes are being made.

e. Perusal of Oracle source code for scripts and the like shows
that they use RCS. If it's good enough for them to use PD
products .....

f. RCS is more efficient than the System V standard SCCS. SCCS


stored the original intact and then the deltas. RCS stores the
most recent intact and then the deltas. Getting more recent
files is thus easier with RCS.

g. RCS permits you to "remove" intermediate versions (e.g.


between 7.2 and 7.5 when you are on 9.1) when required.SCCS
cannot.

2. Outline of RCS operation


----------------------------
Essentially, you check in a file to RCS (with optional security
information, "aliases" for the version and state information).
Subsequent check ins are stored as deltas within the RCS storage
file, (unless you are checking in binary files, in which case
the entire new copy is stored).

For ASCII files, RCS looks for certain keywords, and on check
out, substitutes the version specific information. These
keywords are enclosed between dollar signs.

These keywords include


RCSfile filename without path
Header Combination of the keywords below
Author The user name of the file owner
Source Full path/filename of source
Date Date and time of check in
State A keyword you can assign
e.g. "Cut", "Tested", etc
Id A combination of all information
(Dangerous for many Oracle products)

You should be able to see expanded versions of these near the


top of this file. I have not used the dollar signs here as they
would get expanded and ruin the format.

You can also cause RCS to include in your source all comments
made specific to that version, for example, the reason why
changes had to be made using the Log keyword.

Note that with ASCII files, only storage for the changes between
successive versions are required. For binary files, the entire
file is stored - chewing up disk fairly quickly.

Various RCS utilities allow you to extract any version, merge


changes from different branches and see the differences between
any two versions.

Versions for multi-user operating systems allow better control


than the native operating system, as you can assign a list of
users authorized to manipulate the files. Authorized users can
be different for each file.

3. Basic Philosophy of Version Control with Oracle App Source


--------------------------------------------------------------
Wherever possible, use version control on ASCII representations
of the code.

Thus for forms, use the .inp file, for menus, the .sql file
produced by "exporting" the menu. For SQL*Reports, .rex files
rather than .rep files are put under version control.

The keywords are placed in the source, however you like, the
ASCII file produced checked in to RCS. When moving to a
testing or production environment, the source is checked out of
RCS (resulting in keyword substitution) and "compiled" in the
target environment to produce the runtime application.

4. General Caveat
------------------
Where source code for an Oracle application can be stored in the
database (such as forms or menu), keyword expansion of the Id
keyword can be dangerous, as it may expand to MORE than the
database allows to be stored. Thus, rather than use Id, I use
the more atomic keywords on different lines, these being
unlikely to expand above legal limits.

5. Specifics for some products


-------------------------------
A .SQL*Plus Scripts
RCS keywords are generally placed in Remark lines

B. SQL*Forms
RCS keywords are placed in the comments at forms level.
Selected keywords are placed as default values for
Non-enterable fields, so that the user can see version
information.

C. SQL*Menu
RCS keywords are placed either in the title section of
a menu or in the default value for a parameter,
depending on how we want to use the keyword. If you
do not want to do this, put a wraparound function to
create the Remark line(s) at the top of the .sql file
prior to checking it in. This will NOT affect
Compilation of the resulting .dmm.

D. SQL*ReportWriter
Major BUMMER, .rex files are not "sensible" ASCII that
will permit expansion of RCS keywords. The only way I
know how to solve this is to version an ASCII file
produced by selecting the data out of the report writer
internal tables and versioning that, then using
SQL*Loader to put them back into the SQL*ReportWriter
tables in the production environment. While this would
work, I have not tried it myself (as we do not use RW),
but apparently some group in the US has a tool that
performs this task. If anyone knows how I can contact
that group, let me know please.

Notes:
1. RCS and CVS, together with the GNU compiler you may need
are available from most GNU archive sites. If you are in
Australia, try archie.au in ~ftp/gnu. Less up-to-date
versions are also available in comp.sources.unix.

2. DOS RCS executables are available from SIMTEL. Again,


in Australia, try archie.au (somewhere under
~ftp/micros/pc/oak, I forget which subdirectory).

3. I think I have seen OS/2 versions of RCS floating around.


You could probably get the DOS patches and compile it for the
OS/2 environment with a few mods anyway.

9.3. What books are available about Oracle?


First of all, I must mention the range of books produced by
Oracle. You might not get the ones you need simply by ordering
the manuals for the products you buy. For example, there are quite a
few books written by the Oracle UK team that are excellent, especially
"Advanced SQL*Forms Techniques" and various CASE references (well
Oracle UK was originally an independent group that created CASE, then
known as SDD). Also look out for the Oracle Performance Tuning
Guide. Some of the "Oracle UK" books are published independently
by Addison-Wesley and written by Richard Barker and Cliff Longman.
Note that Oracle have a whole book that lists technical publications
available from them. This is worth getting.

Other books include:


1. Oracle Tuning beyond The Manual
Peter Corrigan and Mark Gurry
Covers Oracle performance from design, DBA and
application programmer perspectives. This book has been
recommended by a number of people, and having worked
with Mark briefly in 1988, I can tell you that he is no
idiot. The thing to remember about this book is that
there are about to be two versions of it. The first has
been published by the authors themselves for A$69.
(52 Rowena Parade, Richmond, Melbourne, Vic, Australia
or mag@scammell.ecos.tne.oz.au). The second version is
to be made available by O'Reilly and Associates in Sep 93
and is probably to be called "Oracle Performance
Tuning". According to Mark, there has been almost a
complete re-write together with the O'Reilly editors and
it is now at the final review stage. While there have
been a number of typos introduced by the rewrite which
are currently being addressed, Mark seems to think that
the result is a much more readable book than the
original version. O'Reilly are sending me a review copy
(thanks!) so expect more details in upcoming issues.

2. Mastering Oracle V6
Daniel Cronin and Joe Lee
Provides a good overview of V6 application development
in one handy book with an almost complete application
used as an example. This book came out very soon after
The release of V6 and thus only discusses Forms 2.3 and
has a V5 to V6 migration guide. Not really detailed
enough for power programming, does not go into Pro*XXX
languages, but great for somebody just moving into RDBMS
or Oracle. It would be nice to see a new edition for
V7.

3. ??????
George Koch
Have not seen this book, but has generally received
favorable reviews. Apparently the V7 stuff seems tacked
on to the end.

4. Dan's Oracle7 Guide


Daniel B. Bikle
I've put this here, because I think Dan will be
marketing this, though some drafts are available from
him gratis. He is building an ASCII file of tips and
example code that can be cut and pasted into your code.
I've seen early drafts and it looks useful. Dan is an
Ex-Oracle employee and can be contacted via
dbikle@alumni.caltech.edu and US phone 415/854-9542.

New Questions

10.1 What is Library Cache Locks


When a database object (such as a table, view, procedure, function,
package, package body, trigger, index, cluster, or synonym) is referenced
during parsing or compiling of a structured query language (SQL), (Data
Manipulation Language (DML) or Data Definition Language (DDL), PL/SQL, or
Java statement, the process parsing or compiling the statement acquires the
library cache lock in the correct mode. In Oracle9i, the lock is held only
until the parse or compilation completes (for the duration of the parse
call).

Oracle: Frequently Asked Questions


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

What built-in functions/operators are available for manipulating strings?


Can I print inside a PL/SQL program?
Is it possible to write a PL/SQL procedure that takes a table name as input and does something with
that table?
What is the correct syntax for ordering query results by row-type objects?
How do I kill long-running queries in sqlplus, Pro*C, and JDBC?
In Pro*C, why do I get a strange "break outside loop or switch" error message?

--------------------------------------------------------------------------------
What built-in functions/operators are available for manipulating strings?
The most useful ones are LENGTH, SUBSTR, INSTR, and ||:
LENGTH (str) returns the length of str in characters.
SUBSTR (str,m,n) returns a portion of str, beginning at character m, n characters long. If n is omitted,
all characters to the end of str will be returned.
INSTR (str1,str2,n,m) searches str1 beginning with its n-th character for the m-th occurrence of str2
and returns the position of the character in str1 that is the first character of this occurrence.
str1 || str2 returns the concatenation of str1 and str2.
The example below shows how to convert a string name of the format 'last, first' into the format 'first
last':
SUBSTR (name, INSTR (name,',',1,1)+2)
|| ' '
|| SUBSTR (name, 1, INSTR (name,',',1,1)-1)
For case-insensitive comparisons, first convert both strings to all upper case using Oracle's built-in
function upper() (or all lower case using lower()).

--------------------------------------------------------------------------------
Can I print inside a PL/SQL program?
Strictly speaking PL/SQL doesn't currently support I/O. But, there is a standard package DBMS_OUTPUT
that lets you do the trick. Here is an example:
-- create the procedure
CREATE PROCEDURE nothing AS
BEGIN
DBMS_OUTPUT.PUT_LINE('I did nothing');
-- use TO_CHAR to convert variables/columns
-- to printable strings
END;
.
RUN;
-- set output on; otherwise you won't see anything
SET SERVEROUTPUT ON;
-- invoke the procedure
BEGIN
nothing;
END;
.
RUN;
Then you should see "I did nothing" printed on your screen.
DBMS_OUTPUT is very useful for debugging PL/SQL programs. However, if you print too much, the
output buffer will overflow (the default buffer size is 2KB). In that case, you can set the buffer size to
a larger value, e.g.:

BEGIN
DBMS_OUTPUT.ENABLE(10000);
nothing;
END;
.
RUN;

--------------------------------------------------------------------------------
Is it possible to write a PL/SQL procedure that takes a table name as input and does something with
that table?
For pure PL/SQL, the answer is no, because Oracle has to know the schema of the table in order to
compile the PL/SQL procedure. However, Oracle provides a package called DBMS_SQL, which allows
PL/SQL to execute SQL DML as well as DDL dynamically at run time. For example, when called, the
following stored procedure drops a specified database table:
CREATE PROCEDURE drop_table (table_name IN VARCHAR2) AS
cid INTEGER;
BEGIN
-- open new cursor and return cursor ID
cid := DBMS_SQL.OPEN_CURSOR;
-- parse and immediately execute dynamic SQL statement
-- built by concatenating table name to DROP TABLE command
DBMS_SQL.PARSE(cid, 'DROP TABLE ' || table_name, dbms_sql.v7);
-- close cursor
DBMS_SQL.CLOSE_CURSOR(cid);
EXCEPTION
-- if an exception is raised, close cursor before exiting
WHEN OTHERS THEN
DBMS_SQL.CLOSE_CURSOR(cid);
-- reraise the exception
RAISE;
END drop_table;
.
RUN;

--------------------------------------------------------------------------------
What is the correct syntax for ordering query results by row-type objects?
As a concrete example, suppose we have defined an object type PersonType with an ORDER MEMBER
FUNCTION, and we have created a table Person of PersonType objects. Suppose you want to list all
PersonType objects in Person in order. You'd probably expect the following to work:
SELECT * FROM Person p ORDER BY p;
But it doesn't. Somehow, Oracle cannot figure out that you are ordering PersonType objects. Here is a
hack that works:
SELECT * FROM Person p ORDER BY DEREF(REF(p));
--------------------------------------------------------------------------------
How do I kill long-running queries in sqlplus, Pro*C, and JDBC?
Sometimes it is necessary to stop long-running queries, either because they take longer to run than
you'd like, or because you realize you've made a mistake. It is important kill off such queries properly
so that they don't take up extra computational resources and prevent others from using the system,
especially near project deadlines when resources are most strained.
As a general precautionary measure, please be sure to test your queries under sqlplus prompt before
running them through CGI or JDBC. It is much easier to kill a query in sqlplus than in CGI or JDBC. If
your test query takes a long time to run under sqlplus, you can simply hit Ctrl-C to terminate it.

Never close an ssh or telnet or xterm window without properly logging out. Always quit your programs
(including sqlplus), stop Java servlets, and type "exit" or "logout" to quit. If you force-close your
ssh/telnet/xterm window, there may still be processes running in the background, and you may be
taking up system resources without knowing it.

If, for some reason, you cannot logout normally (for example, the system is not responding), you should
open another window, login to the same machine where you have the problem, and kill the processes
that is causing trouble:

Type "ps -aef | grep [username]" to find the Process IDs of your processes (replace [username] with
your leland user name), and kill the processes you want to terminate using "kill [processID]". Always
use the "kill" command without the -9 flag first. Use -9 flag only if you cannot kill it otherwise.
If you closed the window by mistake and do not remember which sweet hall machine you were logged
into, open another window immediately and log into any sweet hall machine, then type "sweetfinger
[username]" (replace [username] with your actual leland user name). It will give you the machine
names you were on a few minutes ago. Then, log in to the appropriate machine and kill your processes
there.
If you issued a query through JDBC that is taking a long time to execute and you want to kill it, you
should stop your Java servlet. In most cases this will kill the query. You can also use the
setQueryTimeout([time in seconds]) method on a statement object to stop queries that run too long.

If you issued a query through CGI that is taking a long time to execute, normally the CGI service will
kill it for you within 10 seconds. However, the above occasionally fails to work, and we do not know of
any better way of killing runaway queries issued by JDBC or CGI (other than asking the administrator to
kill them for you). That's why we ask you to always test your queries under sqlplus first. It is much
easier to kill queries there.

--------------------------------------------------------------------------------
In Pro*C, why do I get a strange "break outside loop or switch" error message?
If you get an error message
"break" outside loop or switch

when compiling your Pro*C program, chances that you have the following statement somewhere before
a loop:

EXEC SQL WHENEVER NOT FOUND DO break;

After the loop, you should insert the following statement:

EXEC SQL WHENEVER NOT FOUND CONTINUE;

This would cancel the previous WHENEVER statement. If you do not do this, you may get the error
message at subsequent SQL calls.
Oracle Faq’s
"Oracle 8i is what type of database?
","A) hierarchical network
B) object network
C) hierarchical relational
D) object relational","D) object relational
"
"Which two (if any) of the following three WHERE clauses are equivilent. (Note - the numbers are for reference
only, they are not part of the WHERE clauses)
1 WHERE ename = 'SMITH'
2 WHERE UPPER(ename) = 'smith'
3 WHERE ename = UPPER('smith')","A) 1 and 2
B) 1 and 3
C) 2 and 3
D) each will yield different results","B) 1 and 3"
"Which keyword is used to suppress duplicate rows from being displayed?","A) SUPPRESS
B) DISTINCT
C) UNIQUE
D) NONDUPLICATE","B) DISTINCT"
"A primary key can be made up of","A) one column
B) two columns
C) three or more columns
D) A, B, or C
E) None of the above","D) A, B, or C"
"Which of the following Oracle versions meets ANSI standards?","A) SQL*Plus
B) PL/SQL
C) SQL
D) ISO","C) SQL"
"Which of the following is not a PL/SQL section?","A) LOOP
B) EXCEPTION
C) DECLARE
D) BEGIN","A) LOOP"
"Which of the following does have a semi-colon at the end?","A) A FROM clause which is followed by a WHERE
clause
B) The keyword END at the end of a PL/SQL block
C) The keyword DECLARE at the beginning of a PL/SQL block
D) A SELECT clause","B) The keyword END at the end of a PL/SQL block"
"Which was the first object-capable database developed by Oracle?","A) Oracle 5.2
B) Oracle 7
C) Oracle 8
D) Oracle 8i","C) Oracle 8"
"Which of the following is not a component of the relational model?","A) random file capability on DASD
B) collections of objects or relations that store data
C) a set of operators that act on the relations to produce other relations
D) data integrity for accuracy and consistency","A) random file capability on DASD"
"Which of the following is not a key component of the ER model?","A) entities
B) hierarchies
C) attributes
D) relationships","B) hierarchies"
"Which of the following is a DML statement?","A) SELECT
B) COMMIT
C) UPDATE
D) DROP","C) UPDATE"
"Which of the following is not a DML statement?","A) SELECT
B) INSERT
C) DELETE
D) UPDATE","A) SELECT"
"Which constraint is displayed via the DESCRIBE command?","A) UNIQUE KEY
B) CHECK
C) PRIMARY KEY
D) NOT NULL","D) NOT NULL"
"Which of the following is a DML statement?","A) CREATE
B) COMMIT
C) INSERT
D) DROP","C) INSERT"
"Which SQL*Plus command is equivalent to START?","A) @
B) $
C) !
D) (+)","A) @"
"Which of the following is a DML statement?","A) CREATE
B) TRUNCATE
C) ROLLBACK
D) DELETE","D) DELETE"
"A field is defined in Oracle as the intersection of what?","A) attribute and table
B) select and from
C) data type and PL/SQL
D) row and column","D) row and column"
"Which of the following is a DDL statement?","A) GRANT
B) COMMIT
C) DELETE
D) CREATE","D) CREATE"
"Which of the following is not a DDL statement?","A) ALTER
B) INSERT
C) RENAME
D) DROP","B) INSERT"
"How many keywords are there in the following?
SELECT ename, sal, hiredate
FROM emp
WHERE deptno = '10'
ORDER BY ename;","A) 1
B) 2
C) 3
D) 4
E) 5
F) 6","E) 5"
"How many clauses are there in the following?
SELECT ename, sal, hiredate
FROM emp
ORDER BY ename;","A) 1
B) 2
C) 3
D) 4
E) 5
F) 6","C) 3"
"How many statements are there in the following?
SELECT ename, sal, hiredate
FROM emp
WHERE deptno = 10
AND empno > 7900
ORDER BY ename;","A) 1
B) 2
C) 3
D) 4
E) 5
F) 6","A) 1"
"A relational database can contain at most one table.","True/False","False"
"A given table can many rows.","True/False","True"
"SQL keywords are case sensitive.","True/False","False"
"PL/SQL is the ANSI created language for SQL systems.","True/False","False"
"Commands within SQL*Plus can be abbreviated.","True/False","True"
"A column is made up of many rows, and rows are made up of many tables.","True/False","False"
"A column which serves as the primary key for a table can have duplicate values if the constraint UNIQUE VALUE
is set to NULL.","True/False","False"
"A primary key can not contain any null values.","True/False","True"
"Keywords within SQL can be abbreviated.","True/False","False"
"A column which has the UNIQUE KEY constraint will have an index created for it
automatically.","True/False","True"
"A column which has the UNIQUE KEY constraint can contain NULL values.
","True/False","True"
"What does 'ER' stand for, as in 'ER Modeling'?
","Short Answer","Entity Relationship"
"Two tables can be related via their common column. In one table this column would be the Primary Key. What
term describes the related column in the other table?","Short Answer","Foreign Key"
"What does SQL stand for?
","Short Answer","Structured Query Language"
"What does PL/SQL stand for?","Short Answer","Procedural Language/SQL"
"What does ANSI stand for?
","Short Answer","American National Standards Institute"
"What does ISO stand for?
","Short Answer","International Standards Organization"
"List the three (3) DML statements. Also, what does DML stand for?","Short Answer","INSERT
UPDATE
DELETE

Data Manipulation Language"


"List the five (5) DDL statements. Also, what does DDL stand for?","Short Answer","CREATE
ALTER
DROP
RENAME
TRUNCATE

Data Definition Language"


"List the three (3) Transaction control statements.","Short Answer","COMMIT
ROLLBACK
SAVEPOINT"
"List the two (2) DCL statements. Also, what does DCL stand for?","Short Answer","GRANT
REVOKE

Data Control Language"


"What is the term used to describe a primary key which is composed of two or more columns.","Short
Answer","Concatenated"
"The standard with which Oracle's version of SQL complies with.","A) ASCII
B) ANSI
C) NHTSA
D) ISO","B) ANSI"
"Write a statement to retrieve all columns from the emp table.","Short Answer","SELECT *
FROM emp;"
"Write a statement to retrieve employees who make more than 2000 in salary, listing their name and salary.","Short
Answer","SELECT ename, sal
FROM emp
WHERE sal > 2000;"
"Write a statement to retrieve employees who work in Dallas.","Short Answer","SELECT e.ename, e.deptno, d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno
AND d.loc = 'DALLAS';"
"Write a statement to retrieve the average salary for all employees.","Short Answer","SELECT avg(sal)
FROM emp;"
"Write a statement to retrieve the average salary for all employees who are NOT salesmen.","Short
Answer","SELECT avg(sal)
FROM emp
WHERE job != 'SALESMAN';

-also-

SELECT avg(sal)
FROM emp
WHERE job <> 'SALESMAN';"
"Write a statement to retrieve employees' name and salary for those who earn less than the average for all
employees.","Short Answer","SELECT ename, sal
FROM emp
WHERE sal < (SELECT avg(sal)
FROM emp);"
"Write a statement to retrieve the ename and loc for all employees, plus sort the data by loc ascending, then within
loc by ename descending.","Short Answer","SELECT ename, loc
FROM emp e, dept d
WHERE e.deptno = d.deptno
ORDER BY loc, ename DESC;"
"Write a statement to display the number of employees at each location (New York, Dallas, Chicago, and
Boston).","Short Answer","SELECT loc, count(*)
FROM emp e, dept d
WHERE e.deptno = d.deptno
GROUP BY loc;"
"The LINE_ITEM table contains these columns
LINE_ITEM_ID NUMBER(9) Primary Key
ORDER_ID NUMBER(9)
PRODUCT_ID VARCHAR2(9)
QUANTITY NUMBER(5)

Evaluate this SQL statement:


SELECT quantity, product_id
FROM line_item
ORDER BY quantity, product_id

Which statement is true concerning the results of executing this statement?","A) The results are sorted numerically
only.

B) The results are sorted alphabetically only.

C) The results are sorted numerically and then alphabetically.

D) The results are sorted alphabetically and then numerically.","C"


"Which syntax turns an existing constraint on?","A)
ALTER TABLE table_name
ENABLE contstraint_name;

B)
ALTER TABLE table_name
STATUS = ENABLE CONSTRAINT constraint_name;

C)
ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;

D)
ALTER TABLE table_name
STATUS ENABLE CONSTRAINT constraint_name;

E)
ALTER TABLE table_name
TURN ON CONSTRAINT constraint_name;","C"
"The EMPLOYEES table contains these columns:
LAST_NAME VARCHAR2 (25)
SALARY NUMBER (6,2)
COMMISSION_PCT NUMBER (6)

You need to write a query that will produce these results:


1. Display the salary multiplied by the commission_pct.
2. Exclude employees with a zero commission_pct.
3. Display a zero for employees with a null commission value.

Evaluate the SQL statement:

SELECT last_name, salary * commission_pct


FROM employees
WHERE commission_pct IS NOT NULL;

What does the statement provide?","A) All of the desired results

B) Two of the desired results

C) One of the desired results

D) An error statement","C"
"Which SELECT statement should you use to extract the year from the system date and display it in the format
'1998'?","A)
SELECT TO_CHAR(SYSDATE, 'yyyy')
FROM dual;

B)
SELECT TO_DATE(SYSDATE, 'yyyy')
FROM dual;

C)
SELECT DECODE(SUBSTR(SYSDATE, 8), 'YYYY')
FROM dual;

D)
SELECT DECODE(SUBSTR(SYSDATE, 8), 'year')
FROM dual;

E)
SELECT TO_CHAR(SUBSTR(SYSDATE, 8, 2), 'yyyy')
FROM dual;","A"
"Which of the following correctly describes the precedence of mathematical operators?","A) Multiplication,
Division, Addition, Subtraction
B) Subtraction, Division, Addition, Multiplication
C) Multiplication, Addition, Division, Subtraction
D) Subtraction, Division, Addition, Multiplication","A"
"Which of the following correctly describes the precedence of comparison and logical operators?","A) And, Not, All
comparison operators, Or
B) Not, And, Or, All comparison operators
C) All comparision operators, Not, And, Or
D) All comparison operators, Or, Not, And","C"
"For a hire date of December 10, 1999, what does the following function evaluate to?

TO_CHAR(hiredate, 'fmDD MONTH YYYY')","A) December 10, 1999


B) 10 December 1999
C) 12/10/1999
D) Tuesday, December 10, 1999
E) Ten DECEMBER 1999
F) 10 december 1999
G) Ten December 1999","B"
"For the clauses GROUP BY, HAVING, and WHERE, what is the correct order of evaluation? ","A) Where, Group
By, Having
B) Group By, Having, Where
C) Having, Where, Group By
D) Where, Having, Group By","A"
"Which of the following SQL*Plus commands reads in User Input and stores it in a variable?","A) Define
B) Variable
C) Column
D) Accept","D"
"Which of the following is NOT true of DML?","A) It is executed when you add new rows to a table.

B) It is executed when you modify existing rows in a table.

C) It is executed when you remove existing rows from a table.

D) It is executed when you select rows from a table.","D"


"Which of the following is the correct format for a SELECT statement which should select all columns in the emp
table and be immediately executed?","A)
SELECT *
FROM emp/

B)
SELECT *
FROM emp;

C)
SELECT all
FROM emp;

D)
SELECT */
FROM emp

E)
SELECT &&
FROM emp/","B"
"Which of the following is the correct format to clear a column?","A)
CLEAR COLUMN column_name

B)
COLUMN column_name CLEAR

C)
DELETE COLUMN column_name

D)
UNDEFINE COLUMN column_name","B"
"Which is the correct order of the mathematical operators?","A)
-+/*

B)
+/-*

C)
*/+-

D)
* + - /","C"
"The WHERE clause restricts which of the following?","A)
Rows

B)
Columns

C)
Groups

D)
Tables","A"
"Is PL/SQL a programming language or a way to gather data?","Short Answer","It is a programming lanugauge. It
uses SQL to gather data."
"How do you read specific data from a table (such as name, department, etc)?","Short Answer","With a SELECT
statement, such as:

SELECT ename, deptno


FROM emp;"
"How do you list all items in a table?","Short Answer","With an asterisk in a SELECT statement, such as:

SELECT * FROM emp;

If your intention is to see which columns are in a table, use the DESCRIBE command of SQL*Plus.

DESCRIBE emp"
"Does Oracle store all data in upper case, lower case, or mixed?","Short Answer","Data is stored in both upper and
lower case, such as an employee's name 'Jones'.

Column names and table names are stored in the Data Dictionary in upper case."
"Which statement would produce the following results:

EMPNO ENAME SAL MGR


--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788","A)
SELECT empno, ename, sal, mgr
FROM emp
WHERE mgr NOT IN (7902, 7566, 7788);

B)
SELECT empno, ename, sal, mgr
FROM emp
WHERE mgr IN (7902, 7566, 7788);

C)
SELECT empno, ename, mgr
FROM emp
WHERE empno NOT IN (7902, 7566, 7788);

D)
SELECT empno, ename, sal, mgr
FROM emp
WHERE empno IN (7902, 7566, 7788);","B"
"Why are Aliases better?","A)
They make the column/table name more meaningful

B)
They take up less memory

C)
They just look better

D)
They simplify things and make them more readable","D"
"If '&dept_name' is being inserted into the column department_name, what type of data is department_name?","A)
number
B) blob
C) varchar2
D) date","C

Note: Single quotes (apostrophes) are also used when inserting dates, however 'department_name' would be a very
bogus column name for a date column."
"How many rows can you insert into a table.","A)
As many as you want

B)
As many as the physical space of the database will allow

C)
Depends on which version of Oracle you are running

D)
Both B and C","Unknown, although I would guess D"
"Which of the following will always SELECT all columns and all rows from the emp table?","A)
SELECT ALL
FROM emp;

B)
SELECT *
FROM emp
WHERE sal IS NOT NULL;

C)
SELECT *
FROM emp;

D)
SELECT *
FROM emp
HAVING ALL ROWS;","C"
"For a given row which contains the value 'variable' in a column named 'type', what does the following function
return?

SUBSTR(type, -3)","A) 'riable'

B) 'iable'

C) 'able'

D) 'ble'

E) none of the above","D"


"For a given row which contains the value 'Johnson' in a column named 'cust_name', what does the following
function return?

SUBSTR(cust_name, 4, 3)","A) 'hnso'

B) 'nso'

C) 'nosn'

D) 'nos'","B"
"Which of the following is not a valid type of JOIN?","A) Non-Equijoin
B) Self-join
C) Limited-join
D) Outer-join
E) All the above are valid","C"
"How do PRIMARY KEY and UNIQUE KEY Constraints differ?","A) They do not differ, but are two different
ways to achieve the same result

B) The UNIQUE KEY Constraint allows Null values, PRIMARY KEY does not

C) The PRIMARY KEY Constraint allows Null values, UNIQUE does not

D) The PRIMARY KEY Constraint has an index, UNIQUE does not","B"


"How are PRIMARY KEY and UNIQUE KEY constraints alike?","Short Answer","They are alike in that both have
indexes created for their columns automatically.

They differ as follows:


[ ] A primary key column can NOT contain NULL values, and all its values must be unique.

[ ] A unique key column CAN contain NULL values, however, if values are present (non-NULL), then the values
must be unique."
"List the types of joins which are available.","Short Answer","Non-Equijoin
Equi-join
Self-join
Outer-join"
"Evaluate the following expression:

8 * 2 / 4","Short Answer","8 * 2 / 4

16 / 4

4"
"Evaluate the following expression:

3 + 100 / 2","Short Answer","3 + 100 / 2

3+ 50

53"
"Evaluate the following expression:

8 - 2 + 4","Short Answer","8 - 2 + 4

6 +4

10"
"Evaluate the following expression:

7 * (8 - 4) + (3 * 2)","Short Answer","7 * (8 - 4) + (3 * 2)

7 * (4) + (6)

7* 4 + 6

28 + 6

34"
"Evaluate the following expression:

100 / 50 * 2","Short Answer","100 / 50 * 2

2 *2

4
"
"Evaluate the following expression:

100 / (50 * 2)","Short Answer","100 / (50 * 2)

100 / (100)

100 / 100
1"
"Evaluate the following expression:

2 + 2 - 4","Short Answer","2 + 2 - 4

4 -4

0"
"A null in a character column is equivalent to blank, and in a numeric column is equivalent to
zero.","True/False","False"
"A column alias precedes the column name in the select clause.","True/False","False"
"The keyword AS is optional when using column aliases.","True/False","True"
"The following syntax is correct for using a column alias:

SELECT emp 'Employee Name', sal Salary


FROM emp;","True/False","False

The alias should be enclosed in DOUBLE quotes instead of SINGLE quotes (apostrophes)."
"Under which of the following circumstances should you use double quotes around a column alias?","A) It contains
spaces
B) It contains special characters
C) It is case sensitive
D) All of the above
E) None of the above, you should use single quotes instead","D) All of the above"
"Within a SQL statement, a column alias CAN be used with both the SELECT and the ORDER BY clauses, but can
NOT be used in the WHERE clause.","True/False","True"
"If a column alias is NOT enclosed in double quotes, it will be displayed in all capital letters.","True/False","True"
"What is the concatenation operator?","A) &&
B) ++
C) $$
D) ||","D) ||"
"Which of the following SQL statements will result in the following display for a table with only three rows?

CUSTOMERS
---------
Flo Jones
Moe King
Joe Brown

3 rows selected.","A)
SELECT first_name, ' ', last_name 'CUSTOMERS'
FROM cust;

B)
SELECT first_name ' ' || ' ' last_name 'Customers'
FROM cust;

C)
SELECT first_name || last_name CUSTOMERS
FROM cust;

D)
SELECT first_name || ' ' || last_name Customers
FROM cust;","D)"
"Date and character literals are enclosed within single quotes, whereas aliases are enclosed within double
quotes.","True/False","True"
"Date and character literals are enclosed within double quotes, whereas aliases are enclosed within single
quotes.","True/False","False"
"Compose a SQL statement to concatenate the employee name, the literal ' works in ', and the location with a
column heading in all caps of WORKSWHERE. A typical output would look like this:
WORKSWHERE
---------------------------------
KING works in NEW YORK
...
14 rows selected.","Short Answer","SELECT e.ename
|| ' works in '
|| d.loc workswhere
FROM emp e, dept d
WHERE e.deptno = d.deptno;"
"Which of the following uses the correct syntax for eliminating duplicate rows?","A)
SELECT ename, sal, deptno
FROM emp DISTINCT;

B)
SELECT DISTINCT ename, sal, deptno
FROM emp;

C)
SELECT UNIQUE ename, sal, deptno
FROM emp;

D)
SELECT ename, sal, deptno
FROM emp NONDUPLICATE;","B)
SELECT DISTINCT ename, sal, deptno
FROM emp;"
"Which of the following is based on ANSI standards?","A) SQL
B) SQL*Plus","A) SQL"
"Which of the following has keywords which CAN be abbreviated?","A) SQL
B) SQL*Plus","B) SQL*Plus"
"Which of the following has keywords which can NOT be abbreviated?","A) SQL
B) SQL*Plus","A) SQL"
"Which of the following does NOT have a continuation character?","A) SQL
B) SQL*Plus","A) SQL"
"Which of the following DOES have a continuation character?","A) SQL
B) SQL*Plus","B) SQL*Plus
Its continuation character is the dash (-)."
"Which of the following uses a termination character to execute the command immediately?","A) SQL
B) SQL*Plus","A) SQL - uses the semi-colon"
"What three pieces of information do you provide to SQL*Plus when logging in remotely?","Short Answer","User
Name
Password
Host String"
"What is the special character used to join the password and host string when using the CONNECT
command?","Short Answer","@

as in:

SQL> conn scott/tiger@dba"


"What SQL*Plus command is used to display the structure of a table?","Short Answer","DESCRIBE
or

DESC"
"List some common SQL datatypes.","Short Answer","NUMBER(p,s)
VARCHAR2(n)
CHAR(n)
DATE"
"What SQL*Plus command is used to empty out the SQL buffer?","Short Answer","CLEAR BUFFER

or

CL BUFF"
"What SQL*Plus command is used to display the contents of the SQL buffer?","Short Answer","LIST

or

L"
"What SQL*Plus command is used to execute the contents of the SQL buffer?","Short Answer","RUN

or

/"
"What SQL*Plus command is used to start recording of the screen display to an ASCII file?","Short
Answer","SPOOL filename
"
"What SQL*Plus command is used to stop spooling of the screen display?","Short Answer","SPOOL OFF"
"List the comparison operators (also known as relational operators).","Short Answer","=
>
<
>=
<=
<>
BETWEEN . . . AND . . .
LIKE
IN
IS NULL
IS NOT NULL

not equal to can also be written as:

!=
"
"Which of the following will result in one or more rows being retrieved?","A)
SELECT sal
FROM emp
WHERE sal BETWEEN 1500 AND 500;

B)
SELECT sal
FROM emp
WHERE BETWEEN 1500 AND 500;

C)
SELECT sal
FROM emp
WHERE sal BETWEEN 500 AND 1500;

D)
SELECT sal
FROM emp
WHERE BETWEEN 500 AND 1500;","C)
SELECT sal
FROM emp
WHERE sal BETWEEN 500 AND 1500;"
"Which of the following WHERE clauses uses the correct syntax?","A)
WHERE IN 7902, 7566, 7788;

B)
WHERE mgr IN 7902, 7566, 7788;

C)
WHERE IN(7902, 7566, 7788);

D)
WHERE mgr IN(7902, 7566, 7788);","D)
WHERE mgr IN(7902, 7566, 7788);"
"The comparison operator BETWEEN . . . AND . . . excludes the end points of the range.","True/False","False"
"The comparison operator BETWEEN . . . AND . . . includes the end points of the range.","True/False","True"
"Given: A table has fourteen (14) rows with the following salaries (sal):
500, 600, 799, 799, 800, 800, 801, 1000,
1100, 1499, 1499, 1500, 1500, and 1501.

How many rows will be retrieved with the following SQL statement?

SELECT sal
FROM emp
WHERE sal BETWEEN 800 AND 1500;","A) 5

B) 7

C) 9

D) 12","C) 9"
"The LIKE comparison operator uses which wildcard characters?","Short Answer","%
(percent sign)
for zero or many characters

_
(underscore)
denotes one character"
"For a column named 'tag' with a datatype of CHAR(6), what WHERE clause would you specify to look for all tags
that had unknown characters in the first two positions, followed by a 'C' in the third position, followed by an
unknown character in the fourth position, and '47' in the last two positions?","Short Answer","WHERE tag LIKE
'__C_47';"
"Which of the following WHERE clauses results in listing all employees whose name begins with the letter
'H'?","A)
WHERE ename LIKE 'H%';

B)
WHERE ename LIKE 'H+';
C)
WHERE ename LIKE 'H?';

D)
WHERE ename LIKE 'H_';","A)
WHERE ename LIKE 'H%';"
"List the three logical operators.","Short Answer","NOT
AND
OR"
"What is the correct order of evaluation for logical operators?","A) AND, NOT, OR
B) AND, OR, NOT
C) NOT, AND, OR
D) NOT, OR, AND
E) OR, AND, NOT
F) OR, NOT, AND","C) NOT, AND, OR"
"For the logical operator AND, fill in the following Truth Table (aka a Logic Table)?

AND TRUE FALSE NULL


TRUE ---- ----- ----
FALSE ---- ----- ----
NULL ---- ----- ----","Short Answer","AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL"
"For the logical operator OR, fill in the following Truth Table (aka a Logic Table)?

OR TRUE FALSE NULL


TRUE ---- ----- ----
FALSE ---- ----- ----
NULL ---- ----- ----","Short Answer"," OR TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL"
"For the logical operator OR, fill in the following Truth Table (aka a Logic Table)?

NOT Result
TRUE ------
FALSE ------
NULL ------","Short Answer","NOT Result
TRUE FALSE
FALSE TRUE
NULL NULL"
"Which of the following statements ALWAYS results in NO rows being retrieved?","A)
SELECT * FROM emp
WHERE sal < 1500
AND sal > 500;

B)
SELECT * FROM emp
WHERE sal > 1500
OR sal < 500;

C)
SELECT * FROM emp
WHERE sal > 1500
AND sal < 500;
D)
SELECT * FROM emp
WHERE sal < 1500
OR sal > 500;","C)
SELECT * FROM emp
WHERE sal > 1500
AND sal < 500;"
"Which of the following statements ALWAYS results in ALL rows being retrieved?","A)
SELECT * FROM emp
WHERE sal < 1500
AND sal > 500;

B)
SELECT * FROM emp
WHERE sal > 1500
OR sal < 500;

C)
SELECT * FROM emp
WHERE sal > 1500
AND sal < 500;

D)
SELECT * FROM emp
WHERE sal < 1500
OR sal > 500;","D)
SELECT * FROM emp
WHERE sal < 1500
OR sal > 500;"
"Which of the WHERE clauses below (multiple-choice) is equivalent to the following WHERE clause?

WHERE sal BETWEEN 800 AND 1500;","A)


WHERE sal >= 800 AND sal <= 1500;

B)
WHERE sal <= 800 AND sal >= 1500;

C)
WHERE sal <= 800 OR sal >= 1500;

D)
WHERE sal >= 800 OR sal <= 1500;","A)
WHERE sal >= 800 AND sal <= 1500;"
"Which clause is used to sort rows?","Short Answer","ORDER BY
"
"What is the default way in which rows are sorted when using the ORDER BY clause?","A) Ascending - ASC
B) Descending - DESC","A) Ascending - ASC"
"If neither ASC nor DESC is used in conjunction with ORDER BY, which is the default?","Short Answer","ASC"
"Column aliases CAN be used in an ORDER BY clause.","True/False","True"
"Which of the following ORDER BY clauses results in both columns being sorted in descending order?","A)
ORDER BY state, tag DESC;

B)
ORDER BY state DESC, tag DESC;
C)
ORDER BY DESC state, tag;

D)
ORDER BY DESC state, DESC tag;","B)
ORDER BY state DESC, tag DESC;"
"List nine (9) single row character functions.","Short Answer","LOWER
UPPER
INITCAP
CONCAT
SUBSTR
LENGTH
INSTR
LPAD
TRIM"
"What results from the following function?
CONCAT ('Adam', 'Ant')","Short Answer","'AdamAnt'"
"Given: A product code such as 'ABC123MI99' contains the state where the product was manufactured. Compose a
function to pick off the letters 'MI' from this string.","Short Answer","SUBSTR('ABC123MI99', 7, 2)"
"The column loc_code contains a two letter state abbreviation, a five digit zip code, and a one character plant code.
Which of the following extracts the zip code from that column? An example of a value contained in loc_code is:

'MI49017B'
","A)
SUBSTR(loc_code, 7, 3)

B)
SUBSTR(loc_code, 3, 7)

C)
SUBSTR(loc_code, 3, 5)

D)
SUBSTR(loc_code, 5, 3)","C)
SUBSTR(loc_code, 3, 5)"
"What value does the following function return?

LENGTH('ABC123')","Short Answer","6"
"What values do the following functions return? (You will have four answers)

1 - ROUND(10.849, 1)

2 - ROUND(13.35, 1)

3 - ROUND(88.4649, 2)

4 - ROUND(88.4650, 2)","Short Answer","1 - 10.8

2 - 13.4

3 - 88.46

4 - 88.47"
"What values do the following functions return? (You will have four answers)

1 - TRUNC(10.849, 1)
2 - TRUNC(13.35, 1)

3 - TRUNC(88.4649, 2)

4 - TRUNC(88.4650, 2)","Short Answer","1 - 10.8

2 - 13.3

3 - 88.46

4 - 88.46"
"What value is returned by the following function?

MOD(17, 3)","Short Answer","2"


"What is the function which returns the current operating system date?","Short Answer","SYSDATE"
"List six date functions.","Short Answer","MONTHS_BETWEEN
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
TRUNC"
"What values do the following functions return? (You will have six answers)

1 - MONTHS_BETWEEN('01-MAY-02', '01-MAY-03')
2 - MONTHS_BETWEEN('01-MAY-03', '01-MAY-02')
3 - ADD_MONTHS('31-JUL-99',3)
4 - NEXT_DAY('07-OCT-02', 'WEDNESDAY')
5 - LAST_DAY('15-OCT-02')
6 - NEXT_DAY(LAST_DAY('13-OCT-02'), 'SATURDAY')
","Short Answer","1 - minus 12 (-12)
2 - positive 12 (12)
3 - '31-OCT-99'
4 - '09-OCT-02'
5 - '31-OCT-02'
6 - '02-NOV-02'"
"List some common elements used when converting a number to a character value.","Short Answer","$
dollar sign

9
digit nine

,
comma

0
digit zero

.
decimal point"
"List some common elements used when converting a date to a character value.","Short Answer","YYYY
YEAR
MM
MONTH
DY
DAY
DDD
DD
D
fm"
"List the three conversion functions.","Short Answer","TO_CHAR
TO_DATE
TO_NUMBER
"
"When converting a date column to a character value, the TO_CHAR function is used. What does the fill mode 'fm'
at the beginning of the format do? (As below)

TO_CHAR(hiredate, 'fmDAY MONTH YYYY')","Short Answer","It suppresses leading zeroes and removes
padded blanks."
"How would you display 'No Commission' for those employees with either a zero commission or a null
commission?","Short Answer","SELECT
DECODE( NVL(comm, 0),
0, 'No Commission',
comm) commission
FROM emp;"
"What is wrong with the following function?

NVL(comm, 'No Commission')","Short Answer","The column comm is a numeric column, therefore the
replacement value must also be numeric.
"
"Which function is used to replace null values with a replacement value?","Short Answer","NVL
"
"What function and what format would you use to display the numerica value 1234567.99 as:

$1,234,567.99
","Short Answer","TO_CHAR(1234567.99, '$9,999,999.99')"
"Compose a function to associate an employee's job with a required level of experience. Use the following table:

CLERK none
SALESMAN some
ANALYST moderate
MANAGER high
PRESIDENT high
all others unknown","Short Answer","DECODE(job, 'CLERK', 'none',
'SALESMAN', 'some',
'ANALYST', 'moderate',
'MANAGER', 'high',
'PRESIDENT', 'high',
'unknown')"
"What term is used to describe the placing of one function inside another function?","Short Answer","nesting"
"If two tables are used to display data, but a WHERE clause is not used, what type of join results?","Short
Answer","Cartesian Join

aka

Cartesian Product"
"If one table has 10 rows and the second table has 15 rows, how many rows result from a Cartesian Join?","A) 10
B) 15
C) 25
D) 150","D) 150"
"How many aliases are in the following SQL statement?
SELECT ename employee,
sal salary,
loc location
FROM emp e, dept d;

Also, what type of join does the above illustrate?","Short Answer","Five aliases:
3 column aliases, and
2 table aliases

A Cartesian Join:
Because there is no WHERE condition"
"List seven (7) group functions.","Short Answer","AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE"
"Which of the following Equijoins is correctly written?","A)
SELECT ename, loc
FROM emp, dept
WHERE deptno = deptno;

B)
SELECT ename, loc
FROM emp e, dept d
WHERE deptno = deptno;

C)
SELECT ename, loc
FROM e.emp, d.dept
WHERE e.deptno = d.deptno;

D)
SELECT ename, loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;","D)
SELECT ename, loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;"
"Which of the following Non-equijoins is correctly written?","A)
SELECT e.ename, e.sal, s.grade FROM emp, salgrade
WHERE losal = sal;

B)
SELECT ename, sal, grade FROM emp e, salgrade s
WHERE e.sal >= s.losal AND e.sal <= s.hisal;

C)
SELECT ename, sal, grade FROM emp, salgrade
WHERE e.sal BETWEEN s.losal AND s.hisal;

D)
SELECT e.ename, e.sal, s.grade FROM emp e, salgrade s
WHERE sal >= losal OR sal <= hisal;","B)
SELECT ename, sal, grade FROM emp e, salgrade s
WHERE e.sal >= s.losal AND e.sal <= s.hisal;"
"What is the outer join operator?","Short Answer","(+)

Which is an open parenthesis, followed by a plus sign, followed by a closing parenthesis."


"The outer join operator ' (+) ' is placed on the side which is deficient in information.","True/False","True"
"The cars table has the columns make, model, and color. The makes table has a single column, make. Every make
from the makes table matches a make in the cars table, however, some makes in the cars table do not have matching
makes in the makes table.
Cars: FORD, CHEVY, DODGE, GEO, FORD, CHEVY
Makes: FORD, DODGE
Compose a query which shows the make and model for ALL cars, AND which displays the make from the makes
table (if there is a matching make).","Short Answer","SELECT c.make, c.model, m.make
FROM cars c, makes m
WHERE c.make = m.make (+);"

FREQUENTLY ASKED QUESTIONS:


1. Write a query to eliminate duplicate rows in a table?

DELETE FROM DEPT D WHERE D.ROWID! = (SELECT MAX (ROWID) FROM


DEPT D1 WHERE D.DEPTNO = D1.DEPTNO AND D.DNAME = D1.DNAME AND
D.LOC = D1.LOC)
2. Write a query to find max 5 salaries of employees?

Select sal from (select distinct (sal) from emp order by sal desc)
Where rownum < 6

Top – n- Analysis.
Select rownum as Rank, ename, Sal from (select ename, Sal from emp order by sal desc) where rownum
<=3

3. Given a Procedure in a Package and a Procedure standalone what is the diff between the two and which is
better to use?

Advantages of a package:

• Modularity -Group logically related PL/SQL types, items, and subprograms.


• Easier Application Design bcoz you can code and compile a specification without its body. You
need not define the package body fully until you are ready to complete the application.
• Information Hiding -You can decide which constructs are public (visible and accessible) or private
(hidden and inaccessible). The package hides the definition of the private constructs (i.e they are not
included in package specification) so that only the package is affected (not your application) if the
definition changes. Also, by hiding implementation details from users, you protect the integrity of
the package.
Note: When coding the package body, the definition of the private function has to be above the
definition of the public procedure.
• Persistence - Packaged public variables and cursors persist for the duration of a session. Thus they
can be shared by all subprograms that execute in the environment
• Overloading -Packages allow you to overload procedures and functions, which means you can
create multiple subprograms with the same name in the same package, each taking parameters of
different number,order or datatype. Necessity of overloading is - Sometimes the processing in
two subprograms is the same. In that case it is logical to give them the same name. PL/SQL
determines which subprogram is being called by checking its formal parameters. Only local or
packaged subprograms can be overloaded.
You cannot overload:
•Two subprograms if their formal parameters differ only in name or parameter mode. (datatype
and their total number is same).
•Two subprograms if their formal parameters differ only in datatype and the different datatypes
are in the same family (number and decimal belong to the same family)
•Two subprograms if their formal parameters differ only in subtype and the different subtypes are
based on types in the same family (VARCHAR and STRING are subtypes of VARCHAR2)
•Two functions that differ only in return type, even if the types are in different families.
Example of Overloading:

Package specification

CREATE OR REPLACE PACKAGE over_pack


IS
PROCEDURE add_dept
(v_deptno IN dept.deptno%TYPE,
v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown');

PROCEDURE add_dept
(v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown');
END over_pack;

Package Body

CREATE OR REPLACE PACKAGE BODY over_pack


IS
PROCEDURE add_dept
(v_deptno IN dept.deptno%TYPE,
v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown')
IS
BEGIN
INSERT INTO dept
VALUES (v_deptno,v_name,v_loc);
END add_dept;

PROCEDURE add_dept
(v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown')
IS
BEGIN
INSERT INTO dept
VALUES (dept_deptno.NEXTVAL,v_name,v_loc);
END add_dept;
END over_pack;

If you call ADD_DEPT with an explicitly provided department number, PL/SQL uses the first version of
the procedure. If you call ADD_DEPT with no department number, PL/SQL uses the second version.
EXECUTE OVER_PACK.ADD_DEPT (76,'MARKETING','ATLANTA')
EXECUTE OVER_PACK.ADD_DEPT ('SUPPORT','ORLANDO')
• Allow Oracle8 to read multiple objects into memory at once.
• When you call a packaged PL/SQL construct (subprogram) for the first time, the whole package is
loaded into memory. Thus, later calls to related constructs require no disk I/O.

Note : Packages cannot be called, parameterized, or nested.

A procedure in a package is better to use bcoz:


• In case of stand alone procedure, whenever it is called it has to be loaded into memory thus disk
I/O takes place everytime while if the procedure is in a package then first time when we call the
procedure from the package it gets loaded into memory and any later calls doesn’t require disk
I/O.
• Package procedure can be defined as public which can be called from other subprograms of the
package and from outside the package.Similarly we can define public function and public
variables.
Note: Package specification can exist without package body but package body cannot exist without
package specification.To drop a package first drop package specification then package body.

DROP PACKAGE package_name


DROP PACKAGE BODY package_name

4. What is FORWARD DECLARATION in Packages?

PL/SQL allows for a special subprogram declaration called a forward declaration. It consists of the
subprogram specification in the package body terminated by a semicolon. You can use forward declarations
to do the following:
• Define subprograms in logical or alphabetical order.
• Define mutually recursive subprograms. (Both calling each other).
• Group subprograms in a package

Example of forward Declaration:

CREATE OR REPLACE PACKAGE BODY forward_pack


IS

PROCEDURE calc_rating(. . .); -- forward declaration

PROCEDURE award_bonus(. . .)
IS -- subprograms defined
BEGIN -- in alphabetical order
calc_rating(. . .);
...
END;

PROCEDURE calc_rating(. . .)
IS
BEGIN
...
END;

END forward_pack;

5. PRAGMA RESTRICT_REFERENCES:
•Checks that the restrictions of using functions in SQL statements are not violated
•Allows packaged functions to be used in SQL statements
•Verifies the purity of a function at compilation. The purity level asserts the extent to which the function
permits database operations like insert,update or delete.

PRAGMA RESTRICT_REFERENCES is no longer required for Oracle8i.

PRAGMA RESTRICT_REFERENCES(function_name, WNDS --write no


database state
[,WNPS] --write no
package state
[,RNDS] --read no
database state
[,RNPS]);-- read no
package state
CREATE OR REPLACE PACKAGE taxes_pack
AS
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER;
PRAGMA RESTRICT_REFERENCES (tax, WNDS, RNPS, WNPS);
END taxes_pack;

Example
Encapsulate the function, TAX, in a package, TAXES_PACK. The function will be called from SQL
statements on remote databases. Therefore, you need to assert the RNPS, WNPS, and WNDS purity levels,
because remote functions can neither read nor write the package variables, nor modify database tables when
called from a SQL statement.
Note: we can declare the public (global) cursor in the package specification.

6. Name some Oracle Server supplied packages:


–DBMS_PIPE
–DBMS_DDL
–DBMS_JOB
–DBMS_OUTPUT
•Write dynamic SQL using DBMS_SQL and EXECUTE IMMEDIATE

DBMS_PIPE Package
The DBMS_PIPE package performs the following functions:
•It allows two or more sessions connected to the same instance (vis) to communicate through a pipe just
like pipes used in UNIX
•Each pipe works asynchronously
•Depending on your security requirements, you can use either a public pipe or a private pipe
•Once buffered information is read by one user, it is emptied from the buffer, and is not available for other
readers of the same pipe
•To send a message, first make one or more calls to PACK_MESSAGE to build your message. Then call
SEND_MESSAGE to send the message on the named pipe
•To receive a message from a pipe, first call RECEIVE_MESSAGE, and then call UNPACK_MESSAGE
to access the individual items in the message
Oracle pipes buffer information in the SGA, which means that information is lost if you shut down your
instance.

Example:

CREATE OR REPLACE PROCEDURE send_message


(v_message IN VARCHAR2)
IS s INTEGER;
BEGIN
DBMS_PIPE.PACK_MESSAGE(v_message);
s := DBMS_PIPE.SEND_MESSAGE('DEMO_PIPE');
IF s <> 0
THEN RAISE_APPLICATION_ERROR (-20200,
'Error '||TO_CHAR(s)||' sending on pipe.');
END IF;
END send_message;

CREATE OR REPLACE PROCEDURE receive_message


IS s INTEGER;
v_message VARCHAR2(50);
BEGIN
s := DBMS_PIPE.RECEIVE_MESSAGE('DEMO_PIPE');
IF s <> 0
THEN RAISE_APPLICATION_ERROR (-20201,
'Error '||TO_CHAR(s)||' reading pipe.');
END IF;
DBMS_PIPE.UNPACK_MESSAGE(v_message);
DBMS_OUTPUT.PUT_LINE(v_message);
END receive_message;

Dynamic SQL
Advantages:
• Dynamic SQL to create a procedure that operates on a table whose name is not known until runtime, or to
write and execute a data definition language (DDL) statement in PL/SQL.
In Oracle8, and earlier, you have to use DBMS_SQL to write dynamic SQL.
In Oracle 8i, you can use DBMS_SQL, EXECUTE IMMEDIATE. If the statement is a multirow
SELECT, you can use DBMS_SQL or OPEN-FOR, FETCH, and CLOSE statements.

Disadvantage of dbms_sql:
• Using this package to execute DDL statements can result in a deadlock. The most likely reason for this is if,
for example, the package is being used to drop a procedure, which is still in use by you.

Steps to Process SQL Statements:


All SQL statements have to go through various stages. Not all the stages are mandatory, and some stages
may be missed.
Parse
Every SQL statement must be parsed. Parsing the statement includes checking the statement's syntax and
validating the statement, ensuring that all references to objects are correct, and ensuring that the relevant
privileges to those objects exist.
Bind
After parsing, Oracle knows the meaning of the Oracle statement but still may not have enough information
to execute the statement. Oracle may need values for any bind variable in the statement. The process of
obtaining these values is called binding variables.
Execute
At this point, Oracle has all necessary information and resources, so the statement is executed.
Fetch
In the fetch stage, rows are selected and ordered (if requested by the query), and each successive fetch
retrieves another row of the result, until the last row has been fetched.
Some of the procedures and functions of the DBMS_SQL package:
•OPEN_CURSOR
•PARSE
•BIND_VARIABLE
•EXECUTE
•FETCH_ROWS
•CLOSE_CURSOR

SYNTAX of DBMS_SQL:

CREATE OR REPLACE PROCEDURE delete_all_rows


(tab_name IN VARCHAR2,
rows_del OUT NUMBER)
IS
cursor_name INTEGER;
BEGIN
cursor_name := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE ( cursor_name,'delete FROM '||tab_name,
DBMS_SQL.NATIVE );
rows_del := DBMS_SQL.EXECUTE (cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);

SQL> VARIABLE deleted NUMBER


SQL> EXECUTE delete_all_rows('emp',:deleted)
PL/SQL procedure successfully completed.
SQL> PRINT deleted
DELETED
---------
14

Dynamic SQL with Oracle8i using EXECUTE IMMEDIATE:

CREATE PROCEDURE del_rows


(v_table_name IN VARCHAR2,
rows_deld OUT NUMBER)
IS
BEGIN
EXECUTE IMMEDIATE 'delete from '||v_table_name;
rows_deld := SQL%ROWCOUNT;
END;

SQL> VARIABLE deleted NUMBER


SQL> EXECUTE del_rows('emp',:deleted)
PL/SQL procedure successfully completed.
SQL> PRINT deleted
DELETED
---------
14

DBMS_DDL Package

Uses:

•You can recompile your modified procedures, functions, and packages using
DBMS_DDL.ALTER_COMPILE.
ALTER_COMPILE (object_type, owner, object_name)

DBMS_DDL.ALTER_COMPILE('PROCEDURE','A_USER','QUERY_EMP')

•You can analyze a single object, using DBMS_DDL.ANALYZE_OBJECT. (There is a way of analyzing
more than one object at a time, using DBMS_UTILITY.)

ANALYZE_OBJECT (object_type, owner, name, method)


DBMS_DDL.ANALYZE_OBJECT('TABLE','A_USER','EMP','COMPUTE')

•This package gives developers access to ALTER and ANALYZE SQL statements through PL/SQL
environments.

DBMS_JOB Package

Allows tasks to be scheduled and altered once in the queue.


Some procedures in the package:
•SUBMIT (jobno, what, next_date).
–JOB is an out parameter, which will contain the number allocated for the job.
–WHAT is the statement you want to execute.
–NEXT_DATE is the date of execution. The default is SYSDATE.

•RUN (jobno): Force a submitted job to execute now

Note : USER_JOBS – Data dictionary view is used to see the jobs in the queue.

Example:

SQL> VARIABLE jobno NUMBER


SQL> EXECUTE DBMS_JOB.SUBMIT (:jobno, -
> 'OVER_PACK.ADD_DEPT(''EDUCATION'',''ZURICH'');', -
> SYSDATE)
SQL> COMMIT;
SQL> PRINT jobno

•You can force a job in the queue to run now, if you supply the job number
DBMS_JOB.RUN (jobno)

DBMS_OUTPUT Package

Allows you to output messages from PL/SQL blocks


Some of the procedures of the package:
•PUT
•NEW_LINE
•PUT_LINE
•GET_LINE
•GET_LINES
•ENABLE/DISABLE

Some other Oracle supplied packages:

•DBMS_ALERT
•DBMS_APPLICATION_INFO
•DBMS_DESCRIBE
•DBMS_LOCK
•DBMS_SESSION
•DBMS_SHARED_POOL
•DBMS_TRANSACTION
•DBMS_UTILITY
•UTL_FILE

7. What is the sequence of firing of database triggers?

Total 12 database triggers – insert/update/delete – before/after – row/statement.

Sequence of firing:

When single row is manipulated in trigger:


Before statement
Before row
After row
After statement

When multiple row is manipulated in trigger:


Before statement
Before row
After row
Before row
After row
------
After statement

Example of a statement trigger:

Create one trigger to restrict all data manipulation events on the EMP table to certain business hours,
Monday through Friday.

CREATE OR REPLACE TRIGGER secure_emp


BEFORE INSERT OR UPDATE OR DELETE ON emp
BEGIN
IF (TO_CHAR (sysdate,'DY') IN ('SAT','SUN')) OR
(TO_CHAR (sysdate, 'HH24') NOT BETWEEN '08' AND '18')
THEN
IF DELETING -keywords given by oracle in case of such triggers
THEN RAISE_APPLICATION_ERROR (-20502,
'You may only delete from EMP during normal hours.');
ELSIF INSERTING
THEN RAISE_APPLICATION_ERROR (-20500,
'You may only insert into EMP during normal hours.');
ELSIF UPDATING ('SAL')
THEN RAISE_APPLICATION_ERROR (-20503,
'You may only update SAL during normal hours.');
ELSE
RAISE_APPLICATION_ERROR (-20504,
'You may only update EMP during normal hours.');
END IF;
END IF;
END;

Example of a row trigger:

SQL> CREATE OR REPLACE TRIGGER DERIVE_COMMISSION_PCT


2 BEFORE INSERT OR UPDATE OF sal ON emp
3 FOR EACH ROW
4 BEGIN
5 IF NOT (:NEW.JOB IN ('MANAGER' , 'PRESIDENT'))
6 AND :NEW.SAL > 5000
7 THEN
8 RAISE_APPLICATION_ERROR
9 (-20202, 'EMPLOYEE CANNOT EARN THIS AMOUNT');
10 END IF;
11 END;

8. What are old and new qualifiers in triggers?

--After deleting or inserting or updating on emp –insert the data in audit_emp_table to track all the
changes done on emp table.

SQL>CREATE OR REPLACE TRIGGER audit_emp_values


2 AFTER DELETE OR INSERT OR UPDATE ON emp
3 FOR EACH ROW
4 BEGIN
5 INSERT INTO audit_emp_table (user_name,
6 timestamp, id, old_last_name, new_last_name,
7 old_title, new_title, old_salary, new_salary)
8 VALUES (USER, SYSDATE, :OLD.empno, :OLD.ename,
9 :NEW.ename, :OLD.job, :NEW.job,:OLD.sal, :NEW.sal );
11 END;
12 /
-- : old is used for the values before change and new for after change.

9. Difference between row and statement trigger?

Statement Triggers and Row Triggers


You can specify the number of times the trigger action is to be executed: once for every row affected by the
triggering statement (such as a multiple row UPDATE) , or once for the triggering statement no matter how
many rows it affects.
Statement Trigger
A statement trigger is fired once on behalf of the triggering event, even if no rows are affected at all.
Statement triggers are useful if the trigger action does not depend on data of rows that are affected or data
provided by the triggering event itself. For example, a trigger that performs a complex security check on
the current user.
Row Trigger
A row trigger fires each time the table is affected by the triggering event. If the triggering event affects no
rows, a row trigger is not executed at all.
Row triggers are useful if the trigger action depends on data of rows that are affected or data provided by
the triggering event itself.

10. How can you restrict a row trigger?

To restrict the trigger action to those rows that satisfy a certain condition, provide a WHEN clause.
Example:
Create a trigger on the EMP table to calculate an employee’s commission when a row is added to the EMP
table or an employee’s salary is modified.

SQL>CREATE OR REPLACE TRIGGER derive_commission_pct


2 BEFORE INSERT OR UPDATE OF sal ON emp
3 FOR EACH ROW
4 WHEN (NEW.job = 'SALESMAN')
5 BEGIN
6 IF INSERTING
7 THEN :NEW.comm := 0;
8 ELSIF :OLD.comm IS NULL
9 THEN :NEW.comm := 0;
10 ELSE :NEW.comm := :OLD.comm * (:NEW.sal/:OLD.sal);
11 END IF;
12 END;
13 /

The NEW qualifier does not need to be prefixed with a colon in the WHEN clause.
Note: If we use after insert or update then we will get a compilation error.
ORA-04084: cannot change NEW values for this trigger type
Bcoz new can only be used with before triggers.

11. What are instead of triggers?

Instead of trigger is a trigger created on a complex view (with more than 1 table) to modify them, as
complex views are inherently non-modifiable.
These triggers are called INSTEAD OF triggers, because, unlike other triggers,
Oracle server fires the trigger instead of executing the triggering statement
(insert/update/delete). . Ex- create trigger tst instead of insert on emp_view …do
something

Why Use INSTEAD OF Triggers?


If a view consists of more than one table, an insert to the view may entail an insert into one table and an
update to another. So, you write an INSTEAD OF trigger that fires, when you write an insert against the
view. Instead of the original insert, the trigger body executes, which results in an insert into one table and
an update to another table.ex- if we insert a row in emp table with emp salary. And there is another table
total which sums total sal for each department . In that case whenever an insert will be on emp table then
table – total will also get updated.

12. Difference between trigger and stored procedure?

Triggers Procedure
Use CREATE TRIGGER Use CREATE PROCEDURE
Data dictionary contains source and p-code Data dictionary contains source and p-code
Implicitly invoked Explicitly invoked
COMMIT, SAVEPOINT, ROLLBACK not allowed COMMIT, SAVEPOINT, ROLLBACK allowed

13. Restrictions on instead of triggers:


1. Available only on row level not on statement level.
2. Can be applied only to views not on tables.
3. Cannot use ‘WHEN’ clause to restrict instead of trigger.

Note: ALTER TRIGGER trigger_name DISABLE | ENABLE


ALTER TRIGGER trigger_name DISABLE | ENABLE ALL TRIGGERS
ALTER TRIGGER trigger_name COMPILE --to recompile the trigger

14. What are logon and log off trigger?

You can create this trigger to monitor how often you log on and off, or you may want to write a report on
how long you are logged on for.
Example:
SQL> CREATE OR REPLACE TRIGGER LOGON_TRIG
2 AFTER logon ON SCHEMA
3 BEGIN
4 INSERT INTO log_trig_table
5 (user_id, log_date, action)
6 VALUES (user, sysdate, 'Logging on');
7 END;

SQL> CREATE OR REPLACE TRIGGER LOGOFF_TRIG


2 BEFORE logoff ON SCHEMA
3 BEGIN
4 INSERT INTO log_trig_table
5 (user_id, log_date, action)
6 VALUES (user, sysdate, 'Logging off');
7 END;

15. How do we call a procedure in a trigger?

CALL statement is used to call a stored procedure, rather than coding the PL/SQL body in the trigger itself.

CREATE TRIGGER TEST3


2 BEFORE INSERT ON EMP
3 CALL proc1 – where proc1 is the name of stored procedure.

16. What is a mutating table?


Example:

This trigger, CHECK_SALARY, guarantees that whenever a new employee is added


to the EMP table or an existing employee’s salary or job title is changed, the
employee’s salary falls within the established salary range for the employee’s job.
SQL> CREATE OR REPLACE TRIGGER check_salary
2 BEFORE INSERT OR UPDATE OF sal, job ON emp
3 FOR EACH ROW
4 WHEN (new.job <> 'PRESIDENT')
5 DECLARE
6 v_minsalary emp.sal%TYPE;
7 v_maxsalary emp.sal%TYPE;
8 BEGIN
9 SELECT MIN(sal), MAX(sal)
10 INTO v_minsalary, v_maxsalary
11 FROM emp
12 WHERE job = :new.job;
13 IF :new.sal < v_minsalary OR
14 :new.sal > v_maxsalary THEN
15 RAISE_APPLICATION_ERROR(-20505,'Out of range');
16 END IF;
17 END;
18 /

SQL> UPDATE emp


2 SET sal = 1500
3 WHERE ename = 'SMITH';
*
ERROR at line 2:
ORA-04091: table EMP is mutating, trigger/function may not see it
ORA-06512: at "CHECK_SALARY", line 5
ORA-04088: error during execution of trigger
'CHECK_SALARY'

The EMP table is mutating, or in a state of change therefore the trigger cannot
read from it.
17. Some commands to do Auditing?

SQL> AUDIT INSERT, UPDATE, DELETE


2 ON emp
3 BY ACCESS
4 WHENEVER SUCCESSFUL;

AUDIT ROLE;
AUDIT ROLE WHENEVER SUCCESSFUL;
AUDIT ROLE WHENEVER NOT SUCCESSFUL;
AUDIT SELECT TABLE, UPDATE TABLE;
AUDIT SELECT TABLE, UPDATE TABLE BY scott, blake;
AUDIT DELETE ANY TABLE;

18. When is ‘RAISE_APPLICATION_ERROR’ used?

It is a procedure that lets you issue user-defined error messages from stored subprograms.
raise_application_error (error_number,
message[, {TRUE | FALSE}]);

Can be called from executable as well as exception section of a subprogram.

19. What is an exception and what are its types ? Name some pre-defined exceptions.

Exception is an error in PL/SQL. Types of exceptions are:


1. Pre-defined exceptions in Oracle Server - Implicitly raised
2. Non-PreDefined exceptions in Oracle Server - Implicitly raised
3. User Defined -- Explicitly raised

•Sample predefined exceptions:


–NO_DATA_FOUND ex- when no_data_found then rollback;
–TOO_MANY_ROWS
–INVALID_CURSOR
–ZERO_DIVIDE
–DUP_VAL_ON_INDEX

Non-PreDefined exceptions:
- first name the exception ----Declare
- Code the pragma EXCEPTION_INIT ----Associate
- Handle the raised exception or explicitly raise it by RAISE command. --Reference

Ex- Trap for Oracle7 Server error number -2292 an integrity constraint violation.

/* PRAGMA EXCEPTION_INIT (initialize) used to associate the exception with an error number */

DECLARE
e_products_remaining EXCEPTION;
PRAGMA EXCEPTION_INIT (e_products_remaining, -2292);
...
BEGIN
...
EXCEPTION
WHEN e_products_remaining THEN
TEXT_IO.PUT_LINE ('Referential integrity constraint violated.');
...
END;
User Defined exceptions:
- first name the exception ----Declare
- Explicitly raise it by RAISE command

[DECLARE]
e_amount_remaining EXCEPTION;
...
BEGIN
. . .if….then
RAISE e_amount_remaining;
...
EXCEPTION
WHEN e_amount_remaining THEN
:g_message := 'There is still an amount in stock.';
...
END;

20. Functions for trapping errors?

•WHEN OTHERS exception handler


–Traps all exceptions not yet handled.
–Is the last handler.
•SQLCODE
–Returns the numeric value for the error code.
•SQLERRM
–Returns the message associated with the error number.

DECLARE
v_error_code NUMBER;
v_error_message VARCHAR2(255);
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
INSERT INTO errors VALUES(v_error_code, v_error_message);
END;

21. In which scenario database triggers will be used.Name the database triggers. Diff between database triggers
and form transactional triggers ?

22. Types of loops :

While loop
WHILE v_counter <= 10 LOOP
INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;
END LOOP;

For loop
FOR index in [REVERSE]
lower_bound..upper_bound LOOP
Statement1;
Statement2;
...
END LOOP;

Basic Loop
LOOP
INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;

23. Name the sql cursor attributes?

SQL%ROWCOUNT Number of rows affected by the most recent SQL statement (an integer
value).
SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL
statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit cursors
immediately after they are executed.

24. Can we create a cursor without declaring it?

Yes – by using cursor for loop using subqueries.

BEGIN
FOR emp_record IN (SELECT empno, ename
FROM EMP) LOOP
-- Implicit open and implicit fetch occur
IF emp_record.empno = 7839 THEN
...
END LOOP; -- implicit close occurs
END;

25. Can we pass Parameters in cursor? If yes then how do we populate them?
What is cursor for loop? Why is WHERE CURRENT OF clause used in cursors?

Yes we can pass as shown below:


CURSOR emp_cursor
(v_dept NUMBER, v_job VARCHAR2) IS
SELECT last_name, salary, start_date
FROM s_emp
WHERE dept_id = v_dept
AND title = v_job;
Begin
Open emp_cursor (10,’FACULTY’) ---parameters are passed in open cursor statements
Fetch cursor into v1,v2
Close emp_cursor;

Cursor for loop (shortcut for explicit cursors, no need to open, fetch and close)
CURSOR emp_cursor
(v_dept NUMBER, v_job VARCHAR2) IS
SELECT last_name, salary, start_date
FROM s_emp
WHERE dept_id = v_dept
AND title = v_job;
Begin
For emp_data in emp_cursor loop –no need to declare variable emp_data.
--------Emp_data.last_name: = ‘Sharma’;

End loop;

WHERE CURRENT OF Clause


•Update or delete the current row using cursors.
•Lock the rows first by including the FOR UPDATE clause in the cursor query.

Syntax:

CURSOR emp_cursor IS
SELECT...
FOR UPDATE;
BEGIN
...
FOR emp_record IN emp_cursor LOOP
UPDATE...
WHERE CURRENT OF emp_cursor;
...
END LOOP;
COMMIT;
END;

Cursor with subqueries


Retrieve department number, dname and count of staff from dept and EMP table where Count >=5

DECLARE
CURSOR my_cursor IS
SELECT t1.deptno, dname,STAFF
FROM dept t1, (SELECT deptno, count (*) STAFF
FROM EMP
GROUP BY deptno) t2 –retrieves count of staff in each dept.This query is
used in place of a table
WHERE t1.deptno = t2.deptno
AND STAFF >= 5;

26. Types of variables in PL/SQL?

•PL/SQL variables
–Scalar
–Composite
–Reference
–LOB (large objects)
Internal LOBs:
- CLOB (Character LOB)
- BLOB (Binary LOB) - photos
- NLOB (national language character large object)
External LOBs:
- BFILE (binary file) – files in database or O/s system

•Non-PL/SQL variables
–Bind and host variables

Note: DBMS_LOB package is used to manipulate the LOB.

DBMS_LOB.READ
Call the READ procedure to read and return piecewise a specified AMOUNT of data from a given LOB,
starting from OFFSET.
DBMS_LOB.WRITE
Call the WRITE procedure to write piecewise a specified AMOUNT of data into a given LOB, from the
user-specified BUFFER, starting from an absolute OFFSET from the beginning of the LOB value.
DBMS_LOB.SUBSTR (substr from clob)
DBMS_LOB.INSTR (search information from clob)

27. What is the use of EMPTY_CLOB()/EMPTY_BLOB()?

The use of function EMPTY_CLOB() or EMPTY_BLOB() means that the LOB is initialized, but not
populated with data.Later can be populated by update statement. If you use NULL as the value for the LOB
column, the LOB is not initialized; therefore, it can not be populated using an update statement.

Initialize a LOB column using functions EMPTY_CLOB() / EMPTY_BLOB()

INSERT INTO employee


(emp_id, emp_name, resume, picture)
VALUES(7898, 'Marilyn Monroe', EMPTY_CLOB(),NULL);

28. What are temporary LOBs?

Temporary LOBs are new to Oracle8i.


Temporary LOBs can be BLOBs, CLOBs, or NCLOBs.

Temporary LOB features:


•Data is stored in your temporary tablespace.
•They are not stored permanently in the database.
•All temporary LOBs are deleted at the end of the session in which they were created.
•They are not associated with a table.
•Create a temporary LOB using DBMS_LOB.CREATETEMPORARY.
Temporary LOBs are useful when you want to perform some transformational operation on a LOB, for
example changing a LOB from one format to another, and then return it to the permanent LOB. A
temporary LOB will be empty when created and it does not support the EMPTY_B/C/NCLOB functions.
Use the DBMS_LOB package to use and manipulate temporary LOBs.

29. What is the diffrence between Long Raw and LOB datatype?

LONG, LONG RAW LOB


Single column per table Multiple columns per table
Up to 2 GB Up to 4 GB
SELECT returns data SELECT returns locator
Data stored in-line Data stored in-line or out-of-line
Sequential access to data Random access to data
30. What are composite datatypes like we have scalar (number,char,varchar etc.). Name them and write the
Syntax for them?

Composite Data types:


– PL/SQL TABLES
– PL/SQL RECORDS
- Nested TABLE
- VARRAY

Advantage:
–Contain internal components.
–Are reusable.

•PL/SQL TABLES
–Are composed of two components:
•Primary key of datatype BINARY_INTEGER
•Column of scalar datatype

Adv –Increase dynamically because they are unconstrained.

Syntax:

DECLARE
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
TYPE hiredate_table_type IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
hiredate_table hiredate_table_type;

BEGIN
ename_table(1) := 'CAMERON';
hiredate_table(8) := SYSDATE + 7;
IF ename_table.EXISTS(1) THEN
INSERT INTO ...
...
END;

The primary key (i.e index value) can be negative. Indexing need not start with 1.
Note: The table.EXISTS(i) statement returns TRUE if at least one row with index i is returned. Use the
EXISTS statement to prevent an error which is raised in reference to a non-existing table element.

Note: If TYPE ename_table_type IS TABLE OF emp%ROWTYPE


Then composite datatype is called – PL/SQL TABLE OF RECORDS.

PL/SQL RECORD
•Treat a collection of fields as a logical unit.
•Are convenient for fetching a row of data from a table for processing.emp_recordpe IS RECORD
(last emp_record_type;
Syntax:

TYPE emp_record_type IS RECORD


(last_name VARCHAR2(25),
first_name VARCHAR2(25),
gender CHAR(1));
employee_record emp_record_type;
TYPE emp_record_type TY
TYPE emp_record_type IS RECORD
emp_record.last_name := 'Maduro';
emp_record.first_name := 'Elena';
emp_record.gender := 'F';

How pl/sql record is used in a procedure:

PROCEDURE all_dept
(v_dept_id IN NUMBER)
IS
dept_record s_dept%ROWTYPE;
BEGIN
SELECT *
INTO dept_record --PL/SQL RECORD
FROM s_dept
WHERE id = v_dept_id;
...
END all_dept;
gender CHAR(1));
31. Uses of decode function with example?

32. What is accept, variable and print command in sql* plus?

•ACCEPT
–Accepts input from the user and stores the input into a variable.
Sql> ACCEPT p_sal PROMPT 'Enter the salary: '
/*salary entered by user is stored in p_sal */

•VARIABLE
–Declares a bind or host variable.
Sql> Variable abc Number (10)
Sql> Print abcINE DNAME = SALES
SQL>SELT NAME FROM S_DEPT WHERE
LO
•DEFINE
Sql> Define dname = ‘sales’
Sql> Select dname from dept where dname = ‘&dname’ --sales value is assigned to dname initially so
query gives result for sales dept.
UNDEFINE command is used to clear the variable.
NA SQL>DEFINE DNAME = SALES
SQL>
•PRINT
–Displays the current value of bind variables.

Example : Input the monthly salary. Output the calculated annual salary.

ACCEPT p_sal PROMPT 'Enter the salary: '


/*salary entered by user is stored in p_sal */
VARIABLE g_year_sal NUMBER

DECLARE
v_sal NUMBER := &p_sal;
BEGIN
:g_year_sal := v_sal * 12;
END;
/
PRINT g_year_sal

•EXECUTE
–Executes a particular sql statement.

33. Can we drop a column in oracle 8i ? If yes then what is the command
To do that ?

ALTER TABLE A
DROP COLUMN ENO;

34. A table contains a column – gender with values ‘Male’ and ‘Female’.Write a query to find the count of all
male and female emplyees in the company . Output should give 2 columns showing the count of male and
female employees ?

SELECT gender, COUNT (*) FROM emp GROUP BY gender;

35. In a select statement if count function is used and a group by clause is not used then will it give an error? If
yes then which error?

ORA-00937: not a single-group group function

36. What is the difference between ‘IN ‘ and ‘EXISTS’ operator in sql ?

37. What is the sequence of functions – group by,having,orderby in a select statements ?

Select…..
Group by…
Having…
Orderby..

38. Name some date functions?

•MONTHS_BETWEEN('01-SEP-95','11-JAN-94') 1.9774194
•ADD_MONTHS('11-JAN-94',6) '11-JUL-94'
•NEXT_DAY('01-SEP-95','FRIDAY') '08-SEP-95'
•LAST_DAY('01-SEP-95') '30-SEP-95'

39. Name some conversion functions?

•TO_CHAR converts a number or date string to a character string.


•TO_NUMBER converts a character string containing digits to a number.
•TO_DATE converts a character string of a date to a date value.

40. Use of an ‘Escape’ identifier?

ESCAPE identifier is used to search for "%" or "_".

41. What is RR date format

42. How can we see the code of a subprogram ?


Using view – USER_SOURCE
select text from user_source where name = ‘ABC’;

Other views are –


DICTIONARY, DICT_COLUMNS, USER_OBJECTS, USER_CONSTRAINTS,
USER_CONS_COLUMNS, USER_INDEXES , USER_IND_COLUMNS ,USER_ERRORS (to see error
details of a subprogram),USER_TRIGGERS,
USER_DEPENDENCIES (to check subprograms reference which database objects like tables,views etc.)

Column Description for USER_SOURCE


NAME Name of the object
TYPE Type of object (Procedure, function)
LINE Line number of the source code
TEXT Text of the source code line

43. Can 2 subprograms say one function and the other procedure can have same name.

No. 2 subprograms of different type cannot have same name.U will get error saying that –
ORA-00955: name is already used by an existing object.

44. What is an implicit and explicit rollback.

When an sql statement fails then only that statement is rolled back bcoz oracle creates an implicit savepoint
for each statement.
Explicit rollback is given by user.

45. How can we drop a table and its dependent integrity constraints?

DROP TABLE table [CASCADE CONSTRAINTS];

46. Command to execute a procedure and a function?

Execute abc (arguments) – where abc is procedure name.


Variable v_1 number
EXECUTE v_1 := function_name [(argument_list)]

47. Which table stores subprogram errors?


User_errors

48. How to change Oracle password?

Alter user <username> identified by <pwd>


WITH GRANT OPTION w3ith Grant command gives a user authority to pass along the privileges
GRANT select ON s_emp TO scott
WITH GRANT OPTION;

Grant privelege to all users.


GRANT select ON s_ord_id TO PUBLIC;

49. Types of privileges?

•System privileges (ex- create session, create table etc.)


–Gain access to the database
•Object privileges (grant select, update on a table)
–Manipulate the content of the database objects
50. How to see which user has logged in?

Sql>show user

51. What is the difference between PK and Unique key? What is a candidate and composite primary key and
foreign key?

PK can never be null and is always unique while unique key column can be null.
Candidate key is a key that can be used as a PK.
Composite primary key is formed with more than one PK column.
A foreign key (FK) is a column or combination of columns in one table that refers to a PK or unique key
(UK) in the same table or in another table.
Constraint that can only be defined at column level is: NOT NULL constraint.

Note: When u create a table by using a subquery then only the NOT NULL
Constraint is copied.
Add a NOT NULL constraint by using the MODIFY clause

52. What happens when u don’t give name to a constraint?

Server will generate a name by using the SYS_Cn format.

53. What is the use of ON DELETE CASCADE clause in a table?

–Allows deletion in the parent table and deletion of the dependent rows in the child table.

54. Suppose we create a sequence ,insert data in the table using that sequence and then drop that sequence ?
what will happen to the present state of data.

55. How to add comments on a table or column?

You can add comments to a table or column by using the COMMENT command.

SQL> COMMENT ON TABLE s_emp IS 'Employee Information';


Comment created

56. What are WITH CHECK OPTION CONSTRAINT and WITH READ ONLY in a view?

SQL> CREATE OR REPLACE VIEW empvu41


2 AS SELECT *
3 FROM s_emp
4 WHERE dept_id = 41
5 WITH CHECK OPTION CONSTRAINT empvu41_ck;
View created.
If you attempt to change the department number for any rows in the view, the statement will fail because it
violates the CHECK OPTION constraint.
Ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition in
case of simple views.
Note:–A view can be dropped without removing the underlying data.
(That means when we add or update or delete rows from simple view then
the underlying table also gets reflected)
57. What is normalization and what are the 3 normal forms?
Benefits of Normalization:
•Minimizes data redundancy
•Reduces integrity problems. (Entity, column, referential integrity are maintained.)
•Identifies missing entities, relationships, and tables

Rule Description
First normal form All attributes must be single-valued.(Intersection of a row and column must be a
single value).
Second normal form An attribute must depend upon its entity's entire UID (Unique identifier).
( Each table should have a PK column and Other columns of a table must
depend on PK column of the table)
Third normal form No non-UID attribute can be dependent upon another non-UID attribute.

58. Types of data integrity constraints?

•Entity
–No part of a primary key can be NULL and the value must be unique. A NULL is an absence of a value.
•Referential
–Foreign key values must match a primary key or be NULL.
•Column
–Values in the column must match the defined datatype.
•User-defined
–Values must comply with the business rules.

59. Write a query to select all even and odd number of rows from the table? (Hint :usemod function)

60. How the null values are displayed in case of order by clause by asc or desc.
For asc – 1---1000 null values are displayed at the end.
For desc – 1000---1 null values are displayed first.

61. Advantage & Disadvantage of using Truncate command over Delete command?

Truncate table <table_name>


–Removes all rows from a table.
–Releases the storage space used by that table.
Disadvantage is that it is a DDL command so cant be rolled back.

62. Difference between in,out and inout parameters?

IN OUT IN OUT
1. Default must be specified. Must be specified.
Value is
Passed into Returned to calling Passed into subprogram;
subprogram. Environment. Returned to calling env.

Formal parameter acts as


A constant. An uninitialized an initialized variable.
Variable

Actual parameter
Can be a literal, Must be a variable Must be a variable.
expression,
constant, or
initialized variable.
Ex- of IN OUT parameter.

SQL> CREATE OR REPLACE PROCEDURE format_phone


2 (v_phone_no IN OUT VARCHAR2)
3 IS
4 BEGIN
5 v_phone_no := '(' || SUBSTR(v_phone_no,1,3) ||
6 ')' || SUBSTR(v_phone_no,4,3) ||
7 '-' || SUBSTR(v_phone_no,7);
8 END format_phone;
9/
passing input as phone number and getting substr of the phone number.
Note: As functions should only return a single value, you should not declare OUT and IN OUT parameters
for a function.

63. What is p-code?

P-code is the compiled form of the source code of a subprogram.

64. Difference between function and procedure?

A procedure containing one OUT parameter can be rewritten as a function containing a RETURN
statement.
Ex- of a user defined function:

FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * .08);
END tax;

Procedure Function
1. Execute as a PL/SQL statement Invoke as part of an expression
2. No RETURN datatype Must contain a RETURN datatype
3. Can return none, one or many values Must return a single value

65. Coordination properties for master detail relation ?


Immediate
Deferred with Autoquery
Deferred without Autoquery

66. Relational Properties for master detail relation ?


Isolated,non-isolated,cascading.

67. Triggers for master detail relation? How they change with realtional properties.

68. Procedures for master detail relation ?


69. Signifance of ‘Prevent masterless operation’?

70. Types of form triggers with example?

71. Diff between Procedure and a function?

72. What is dynamic sql? Package used for that and syntax?
73. Diff between sql and sql* commands?

74. What are the different data sources of a block?

Data Source Query DML

Table YES YES

View YES YES

FROM Clause YES NO

Procedure-Reference Cursor YES NO

Procedure-Table of Records YES YES

Transactional. Trigger YES YES

Object Table YES YES

Object Column –here table selected is the object table YES YES
but column selected will have object datatype.

Reference Lookup – here table selected will have a YES NO


reference column whose attributes will be selected to
create a ref lookup block.

75. Creating an Object Table,Object column and reference column?

The syntax below creates an object table based on an object type:

CREATE TYPE aa_class_t AS OBJECT


(department VARCHAR2(20),
course_id NUMBER(4),
credit_hours NUMBER(1));

CREATE TABLE aa_classes OF aa_class_t;

CREATE TABLE aa_assignments


(student_id NUMBER(5),
class aa_class_t); -- this is an object column with attributes (department ,course_id
,credit_hours )

CREATE TABLE aa_schedules


(student_id NUMBER(5),
class REF aa_class_t);
In the data block wizard, the REF column name (CLASS) appears twice in the column selection list. It
appears once as a heading for the referenced object’s attributes. It then appears again as a pointer, and is a
selectable column.

76. Types of record groups?

• Query record Group –Design time & run time ----based on select stmt.
• Non-Query record group –Run time ----not based on select stmt.
• Static record group -- Design time ---- not based on select stmt.

77. New PL/SQL8 Scalar Datatypes:

• NCHAR stores fixed-length (blank-padded if necessary) NLS character data. How the data is represented
internally depends on the national character set, which might use a fixed-width encoding such as US7ASCII or
a variable-width encoding such as JA16SJIS.
• NVARCHAR2 stores variable-length NLS character data. How the data is represented internally depends on
the national character set, which might use a fixed-width encoding such as WE8EBCDIC37C or a variable-
width encoding such as JA16DBCS.
• SIGNTYPE lets you restrict an integer variable to the values -1, 0, and 1, which is useful in programming tri-
state logic.
• FLOAT is a subtype of NUMBER. However, you cannot specify a scale for FLOAT variables. You can only
specify a binary precision.
• NATURALN is like subtype NATURAL, but prevents the assignment of NULL.
• POSITIVEN is like subtype POSITIVE, but prevents the assignment of NULL.
• PLS_INTEGER stores signed integers. Its magnitude range is -2147483647 .. 2147483647. PLS_INTEGER
values require less storage than NUMBER values. Also, PLS_INTEGER operations use machine arithmetic, so
they are faster than NUMBER and BINARY_INTEGER operations, which use library arithmetic.

Besides the database character set, which is used for identifiers and source code, PL/SQL8
now supports a second character set called the national character set, which is used for NLS
data. The PL/SQL datatypes NCHAR and NVARCHAR2 allow you to store character strings
formed from the national character set.
78. Example of FORMS_DDL, FORM_SUCCESS, DBMS_ERROR_CODE & DBMS_ERROR_TEXT

FORMS_DDL (‘BEGIN ‘ || p_proc_name ||‘; END; ‘);


IF not FORM_SUCCESS THEN
handle_server_error(DBMS_ERROR_CODE,
DBMS_ERROR_TEXT);
END IF;

79. In Apps11i diff between a standalone form and a function ?

A form can show different output each time if it is stored as a function by giving different options in the
options field while registration.

80. Unix commands ?

Important Questions in Oracle, Developer /2000(Form 4.5 and Reports 2.5)

Oracle
1) What is the Back ground processes in Oracle and what are they.
1) This is one of the most frequently asked questions. There are basically 9 Processes but in a
General system we need to mention the first five background processes. They do the house
keeping
activities for the Oracle and are common in any system.
The various background processes in oracle are
a) Data Base Writer (DBWR) :: Data Base Writer Writes Modified blocks from Database buffer
cache to Data Files. This is required since the data is not written whenever a transaction is
commited.
b) LogWriter (LGWR) :: LogWriter writes the redo log entries to disk. Redo Log data is
generated in redo log buffer of SGA. As transaction commits and log buffer fills, LGWR writes
log entries into a online redo log file.
c) System Monitor (SMON) :: The System Monitor performs instance recovery at instance
startup. This is useful for recovery from system failure
d) Process Monitor (PMON) :: The Process Monitor performs process recovery when user
Process fails. Pmon Clears and Frees resources that process was using.
e) CheckPoint (CKPT) :: At Specified times, all modified database buffers in SGA are written to
data files by DBWR at Checkpoints and Updating all data files and control files of database to
indicate the
most recent checkpoint
f) Archieves (ARCH) :: The Archiver copies online redo log files to archival storal when they are
busy.
g) Recoveror(RECO) :: The Recoveror is used to resolve the distributed transaction in network
h) Dispatcher (Dnnn) :: The Dispatcher is useful in Multi Threaded Architecture
i) Lckn :: We can have upto 10 lock processes for inter instance locking in parallel sql.

2) How many types of Sql Statements are there in Oracle


2) There are basically 6 types of sql statements. They are
a) Data Definition Language (DDL): The DDL statements define and maintain objects and drop
objects.
b) Data Manipulation Language (DML): The DML statements manipulate database data.
c) Transaction Control Statements: Manage change by DML
d) Session Control: Used to control the properties of current session enabling and disabling roles
and changing .e.g: Alter Statements, Set Role
e) System Control Statements: Change Properties of Oracle Instance .e.g:: Alter System
f) Embedded Sql: Incorporate DDL, DML and T.C.S in Programming Language .e.g:: Using the
Sql Statements in languages such as 'C', Open, Fetch, execute and close

3) What is a Transaction in Oracle?


3) A transaction is a Logical unit of work that compromises one or more SQL Statements
executed by a single User. According to ANSI, a transaction begins with first executable
statement and ends when it is explicitly commited or rolled back.

4) Key Words Used in Oracle?


4) The Key words that are used in Oracle are ::
a) Committing: A transaction is said to be commited when the transaction makes permanent
changes resulting from the SQL statements.
b) Rollback: A transaction that retracts any of the changes resulting from SQL statements in
Transaction.
c) SavePoint: For long transactions that contain many SQL statements, intermediate markers or
savepoints are declared. Savepoints can be used to divide a transaction into smaller points.
d) Rolling Forward: Process of applying redo log during recovery is called rolling forward.
e) Cursor: A cursor is a handle (name or a pointer) for the memory associated with a specific
statement. A cursor is basically an area allocated by Oracle for executing the Sql Statement.
Oracle uses an implicit cursor statement for Single row query and Uses Explicit cursor for a
multi row query.
f) System Global Area (SGA): The SGA is a shared memory region allocated by the Oracle that
contains Data and control information for one Oracle Instance. It consists of Database Buffer
Cache and Redo log Buffer.
g) Program Global Area (PGA): The PGA is a memory buffer that contains data and control
information for server process.
g) Database Buffer Cache: Database Buffer of SGA stores the most recently used blocks of
database data. The set of database buffers in an instance is called Database Buffer Cache.
h) Redo log Buffer :: Redo log Buffer of SGA stores all the redo log entries.
i) Redo Log Files :: Redo log files are set of files that protect altered database data in memory
that has not been written to Data Files. They are basically used for backup when a database
crashes.
j) Process :: A Process is a 'thread of control' or mechanism in Operating System that
executes series of steps.

5) What are Procedure, functions and Packages?


5) Procedures and functions consist of set of PL/SQL statements that are grouped together as a
unit to solve a specific problem or perform set of related tasks.
Procedures do not return values while Functions return one Value
Packages :: Packages Provide a method of encapsulating and storing related procedures,
functions, variables and other Package Contents

6) What are Database Triggers and Stored Procedures?


6) Database Triggers :: Database Triggers are Procedures that are automatically executed as a
result of insert in, update to, or delete from table.
Database triggers have the values old and new to denote the old value in the table before it is
deleted and the new indicated the new value that will be used. DT is useful for implementing
complex business rules, which cannot be enforced using the integrity rules. We can have the
trigger as Before trigger or After Trigger and at Statement or Row level.
e.g:: operations insert, update ,delete 3
before ,after 3*2 A total of 6 combinations
At statement level (once for the trigger) or row level( for every execution ) 6*2 A
total of 12.
Thus a total of 12 combinations are there and the restriction of usage of 12 triggers has been
lifted from Oracle 7.3 Onwards.
Stored Procedures :: Stored Procedures are Procedures that are stored in Compiled form in the
database. The advantage of using the stored procedures is that many users can use the same
procedure in compiled and ready to use format.

7) How many Integrity Rules are there and what are they?
7) There are Three Integrity Rules. They are as follows ::
a) Entity Integrity Rule :: The Entity Integrity Rule enforces that the Primary key cannot be Null
b) Foreign Key Integrity Rule :: The FKIR denotes that the relationship between the foreign key
and the primary key has to be enforced. When there is data in Child Tables the Master tables
cannot be deleted.
c) Business Integrity Rules :: The Third Integrity rule is about the complex business processes
which cannot be implemented by the above 2 rules.

8) What are the Various Master and Detail Relation ships?


8) The various Master and Detail Relationship are
a) NonIsolated :: The Master cannot be deleted when a child is existing
b) Isolated :: The Master can be deleted when the child is existing
c) Cascading :: The child gets deleted when the Master is deleted.

9) What are the Various Block Coordination Properties?


9) The various Block Coordination Properties are
a) Immediate
Default Setting. The Detail records are shown when the Master Record are shown.
b) Differed with Auto Query
Oracle Forms defer fetching the detail records until the operator navigates to the detail block.
c) Differed with No Auto Query
The operator must navigate to the detail block and explicitly execute a query

10) What are the Different Optimization Techniques?


10) The Various Optimization techniques are
a) Execute Plan :: we can see the plan of the query and change it accordingly based on the
indexes
b) Optimizer_hint ::
set_item_property('DeptBlock',OPTIMIZER_HINT,'FIRST_ROWS');
Select /*+ First_Rows */ Deptno,Dname,Loc,Rowid from dept
where (Deptno > 25)
c) Optimize_Sql ::
By setting the Optimize_Sql = No, Oracle Forms assigns a single cursor for all SQL statements.
This slow downs the processing because for every time the SQL must be parsed whenever they
are executed.
f45run module = my_firstform userid = scott/tiger optimize_sql = No
d) Optimize_Tp ::
By setting the Optimize_Tp= No, Oracle Forms assigns separate cursor only for each query
SELECT statement. All other SQL statements reuse the cursor.
f45run module = my_firstform userid = scott/tiger optimize_Tp = No
11) How do u implement the If statement in the Select Statement?
11) We can implement the if statement in the select statement by using the Decode statement.
e.g select DECODE (EMP_CAT,'1','First','2','Second'Null);
Here the Null is the else statement where null is done .

12) How many types of Exceptions are there


12) There are 2 types of exceptions. They are
a) System Exceptions
e.g. When no_data_foiund, When too_many_roiws
b) User Defined Exceptions
e.g. My_exception exception
When My_exception then

13) What are the inline and the precompiler directives?


13) The inline and precompiler directives detect the values directly

14) How do you use the same lov for 2 columns


14) We can use the same lov for 2 columns by passing the return values in global values
and using the global values in the code

15) How many minimum groups are required for a matrix report
15) The minimum number of groups in matrix report are 4

16) What is the difference between static and dynamic lov


16) The static lov contains the predetermined values while the dynamic lov contains values
that come at run time

17) What are snap shots and views?


17) Snapshots are mirror or replicas of tables. Views are built using the columns from one
or more tables. The Single Table View can be updated but the view with multi table cannot
be updated

18) What are the OOPS concepts in Oracle.


18) Oracle does implement the OOPS concepts. The best example is the Property Classes.
We can categories the properties by setting the visual attributes and then attach the
property classes for the
objects. OOPS supports the concepts of objects and classes and we can consider the
property classes as classes and the items as objects

19) What is the difference between candidate key, unique key and primary key
19) Candidate keys are the columns in the table that could be the primary keys and the
primary key
is the key that has been selected to identify the rows. Unique key is also useful for
identifying the distinct rows in the table.

20)What is concurrency
20) Concurrency is allowing simultaneous access of same data by different users. Locks
useful for accessing the database are
a) Exclusive
The exclusive lock is useful for locking the row when an insert, update or delete is being
done. This lock should not be applied when we do only select from the row.
b) Share lock
We can do the table as Share_Lock as many share_locks can be put on the same resource.

21) Privileges and Grants


21) Privileges are the right to execute a particular type of SQL statements.
e.g :: Right to Connect, Right to create, Right to resource
Grants are given to the objects so that the object might be accessed accordingly. The grant
has to be
given by the owner of the object.

22)Table Space, Data Files, Parameter File, Control Files


22)Table Space :: The table space is useful for storing the data in the database. When a
database is created two table spaces are created.
a) System Table space :: This data file stores all the tables related to the system and dba
tables
b) User Table space :: This data file stores all the user related tables
We should have separate table spaces for storing the tables and indexes so that the access is
fast.
Data Files :: Every Oracle Data Base has one or more physical data files. They store the
data for the database. Every datafile is associated with only one database. Once the Data
file is created the size cannot change. To increase the size of the database to store more data
we have to add data file.
Parameter Files :: Parameter file is needed to start an instance. A parameter file contains
the list of instance configuration parameters e.g.::
db_block_buffeirs = 500
db_name = ORA7
db_domain = u.s.acme lang
Control Files :: Control files record the physical structure of the data files and redo log
files
They contain the Db name, name and location of dbs, data files ,redo log files and time
stamp.

23) Physical Storage of the Data


23) The finest level of granularity of the data base are the data blocks.
Data Block :: One Data Block correspond to specific number of physical database space
Extent :: Extent is the number of specific number of contiguous data blocks.
Segments :: Set of Extents allocated for Extents. There are three types of Segments
a) Data Segment :: Non Clustered Table has data segment data of every table is stored in
cluster data segment
b) Index Segment :: Each Index has index segment that stores data
c) Roll Back Segment :: Temporarily store 'undo' information
24) What are the Pct Free and Pct Used?
24) Pct Free is used to denote the percentage of the free space that is to be left when
creating a table. Similarly Pct Used is used to denote the percentage of the used space that
is to be used when creating a table
eg.:: Pctfree 20, Pictused 40

25) What is Row Chaining


25) The data of a row in a table may not be able to fit the same data block. Data for row is
stored in a chain of data blocks .

26) What is a 2 Phase Commit


26) Two Phase commit is used in distributed data base systems. This is useful to maintain
the integrity of the database so that all the users see the same values. It contains DML
statements or Remote Procedural calls that reference a remote object. There are basically 2
phases in a 2 phase commit.
a) Prepare Phase :: Global coordinator asks participants to prepare
b) Commit Phase :: Commit all participants to coordinator to Prepared, Read only or
abort Reply

27) What is the difference between deleting and truncating of tables


27) Deleting a table will not remove the rows from the table but entry is there in the
database dictionary and it can be retrieved But truncating a table deletes it completely and
it cannot be retrieved.

28) What are mutating tables


28) When a table is in state of transition it is said to be mutating. eg :: If a row has been
deleted then the table is said to be mutating and no operations can be done on the table
except select.

29) What are Codd Rules


29) Codd Rules describe the ideal nature of a RDBMS. No RDBMS satisfies all the 12 codd
rules and Oracle Satisfies 11 of the 12 rules and is the only Rdbms to satisfy the maximum
number of rules.

30) What is Normalization


30) Normalization is the process of organizing the tables to remove the redundancy. There
are mainly 5 Normalization rules.
a) 1 Normal Form :: A table is said to be in 1st Normal Form when the attributes are
atomic
b) 2 Normal Form :: A table is said to be in 2nd Normal Form when all the candidate keys
are dependant on the primary key
c) 3rd Normal Form :: A table is said to be third Normal form when it is not dependant
transitively

31) What is the Difference between a post query and a pre query
31) A post query will fire for every row that is fetched but the pre query will fire only once.

32) Deleting the Duplicate rows in the table


32) We can delete the duplicate rows in the table by using the Rowid
33) Can U disable database trigger? How?
33) Yes. With respect to table
ALTER TABLE TABLE
[ DISABLE all_trigger ]
34) What is pseudo columns ? Name them?

34) A pseudo column behaves like a table column, but is not actually
stored in the table. You can select from pseudo columns, but you
cannot insert, update, or delete their values. This section
describes these pseudo columns:
* CURRVAL
* NEXTVAL
* LEVEL
* ROWID
* ROWNUM

35) How many columns can table have?


The number of columns in a table can range from 1 to 254.

36) Is space acquired in blocks or extents ?

In extents .

37) what is clustered index?


In an indexed cluster, rows are stored together based on their cluster key values .
Can not applied for HASH.

38) what are the data types supported By oracle (INTERNAL)?


Varchar2, Number, Char , MLSLABEL.

39 ) What are attributes of cursor?


%FOUND , %NOTFOUND , %ISOPEN,%ROWCOUNT

40) Can you use select in FROM clause of SQL select ?


Yes.
Forms 4.5 Questions

1) Which trigger are created when master -detail relation?


1) master delete property

* NON-ISOLATED (default)

a) on check delete master


b) on clear details
c) on populate details

* ISOLATED

a) on clear details
b) on populate details

* CASCADE

a) per-delete
b) on clear details
c) on populate details

2) which system variables can be set by users?


2)
SYSTEM.MESSAGE_LEVEL
SYSTEM.DATE_THRESHOLD
SYSTEM.EFFECTIVE_DATE
SYSTEM.SUPPRESS_WORKING

3) What are object group?


3)
An object group is a container for a group of objects. You define an object group when you want
to package related objects so you can copy or reference them in another module.

4) What are referenced objects?


4)
Referencing allows you to create objects that inherit their functionality and appearance from
other objects.
Referencing an object is similar to copying an object, except that the resulting reference object
maintains a
link to its source object. A reference object automatically inherits any changes that have been
made to the
source object when you open or regenerate the module that contains the reference object.
5) Can you store objects in library?
5)
Referencing allows you to create objects that inherit their functionality and appearance from
other
objects. Referencing an object is similar to copying an object, except that the resulting reference
object maintains a link to its source object. A reference object automatically inherits any changes
that
have been made to the source object when you open or regenerate the module that contains the
reference object.

6) Is forms 4.5 object oriented tool ? why?


6)
yes , partially. 1) PROPERTY CLASS - inheritance property
2) OVERLOADING : procedures and functions.

7) Can you issue DDL in forms?


7)
yes, but you have to use FORMS_DDL.
Referencing allows you to create objects that inherit their functionality and appearance from
other
objects. Referencing an object is similar to copying an object, except that the resulting reference
object
maintains a link to its source object. A reference object automatically inherits any changes that
have
been made to the source object when you open or regenerate the module that contains the
reference object.
Any string expression up to 32K:
·a literal
· an expression or a variable representing the text of a block of dynamically created PL/SQL
code
· a DML statement or
· a DDL statement

Restrictions:
The statement you pass to FORMS_DDL may not contain bind variable references in the string,
but the
values of bind variables can be concatenated into the string before passing the result to
FORMS_DDL.

8) What is SECURE property?


8)- Hides characters that the operator types into the text item. This setting is typically used for
password protection.
9 ) What are the types of triggers and how the sequence of firing in text item
9)
Triggers can be classified as Key Triggers, Mouse Triggers ,Navigational Triggers.
Key Triggers :: Key Triggers are fired as a result of Key action. e.g :: Key-next-field, Key-up,
Key-Down
Mouse Triggers :: Mouse Triggers are fired as a result of the mouse navigation. e.g. When-mouse-
button-pressed, when-mouse-double clicked, etc
Navigational Triggers :: These Triggers are fired as a result of Navigation. E.g : Post-Text-item,
Pre-text-item.
We also have event triggers like when –new-form-instance and when-new-block-instance.
We cannot call restricted procedures like go_to(‘my_block.first_item’) in the Navigational triggers
But can use them in the Key-next-item.
The Difference between Key-next and Post-Text is an very important question. The key-next is
fired as a result of the key action while the post text is fired as a result of the mouse movement.
Key next will not fire unless there is a key event.
The sequence of firing in a text item are as follows ::
a) pre - text
b) when new item
c) key-next
d) when validate
e) post text

10 ) Can you store pictures in database? How?


10)Yes , in long Raw datatype.

11) What are property classes? Can property classes have trigger?
11) Property class inheritance is a powerful feature that allows you to quickly define objects that
conform to
your own interface and functionality standards. Property classes also allow you to make global
changes to
applications quickly. By simply changing the definition of a property class, you can change the
definition
of all objects that inherit properties from that class.
Yes . All type of triggers .

* 12 a) If you have property class attached to an item and you have same trigger written for the
item.
Which will fire first?
12)Item level trigger fires , If item level trigger fires, property level trigger won't fire.
Triggers at the lowest level are always given the first preference. The item level trigger fires
first and then the block and then the Form level trigger.

13) What are record groups ? * Can record groups created at run-time?
13)A record group is an internal Oracle Forms data structure that has a column/row framework
similar to a
database table. However, unlike database tables, record groups are separate objects that belong
to the
form module in which they are defined. A record group can have an unlimited number of
columns of type
CHAR, LONG, NUMBER, or DATE provided that the total number of columns does not exceed
64K.
Record group column names cannot exceed 30 characters.
Programmatically, record groups can be used whenever the functionality offered by a two-
dimensional
array of multiple data types is desirable.
TYPES OF RECORD GROUP:
Query Record Group A query record group is a record group that has an associated
SELECT statement.
The columns in a query record group derive their default names, data types, and lengths from
the database columns referenced in the SELECT statement. The records in a query record group
are the rows retrieved by the query associated with that record group.
Non-query Record Group A non-query record group is a group that does not have an associated
query, but whose structure and values can be modified programmatically at runtime.
Static Record Group A static record group is not associated with a query; rather, you define its
structure and row values at design time, and they remain fixed at runtime.

14) What are ALERT?


14)An ALERT is a modal window that displays a message notifiying operator of some application
condition.

15) Can a button have icon and label at the same time ?
15) -NO

16) What is mouse navigate property of button?


16)
When Mouse Navigate is True (the default), Oracle Forms performs standard navigation to move
the focus
to the item when the operator activates the item with the mouse.

When Mouse Navigate is set to False, Oracle Forms does not perform navigation (and the
resulting validation) to move to the item when an operator activates the item with the mouse.

17) What is FORMS_MDI_WINDOW?


17) forms run inside the MDI application window. This property is useful for calling a form from
another one.

18) What are timers ? when when-timer-expired does not fire?


18) The When-Timer-Expired trigger can not fire during trigger, navigation, or transaction
processing.
19 ) Can object group have a block?
19)Yes , object group can have block as well as program units.

20) How many types of canvases are there.


20)There are 2 types of canvases called as Content and Stack Canvas. Content canvas is the
default and the one that is used mostly for giving the base effect. Its like a plate on which we add
items and stacked canvas is used for giving 3 dimensional effect.

The following questions might not be asked in an Average Interview and could be asked
when the Interviewer wants to trouble u and go deeppppppppppppp……He cannot go
further…..

1) What are user-exits?


1) It invokes 3GL programs.

2) Can you pass values to-and-fro from foreign function ? how ?


2) Yes . You obtain a return value from a foreign function by assigning the return value to an
Oracle Forms
variable or item. Make sure that the Oracle Forms variable or item is the same data type as the
return value
from the foreign function.
After assigning an Oracle Forms variable or item value to a PL/SQL variable, pass the PL/SQL
variable as
a parameter value in the PL/SQL interface of the foreign function. The PL/SQL variable that is
passed as
a parameter must be a valid PL/SQL data type; it must also be the appropriate parameter type as
defined
in the PL/SQL interface.

3) What is IAPXTB structure ?


3) The entries of Pro * C and user exits and the form which simulate the proc or user_exit are
stored in IAPXTB table in d/b.

4) Can you call WIN-SDK thruo' user exits?


4) YES.

5) Does user exits supports DLL on MSWINDOWS ?


5) YES .

6) What is path setting for DLL?


6) Make sure you include the name of the DLL in the FORMS45_USEREXIT variable of the
ORACLE.INI file, or rename the DLL to F45XTB.DLL. If you rename the DLL to F45XTB.DLL,
replace the existing F45XTB.DLL in the \ORAWIN\BIN directory with the new F45XTB.DLL.
7) How is mapping of name of DLL and function done?
7) The dll can be created using the Visual C++ / Visual Basic Tools and then the dll is put in the
path that is defined the registry.

8) what is precompiler?
8) It is similar to C precompiler directives.

9) Can you connect to non - oracle data source ? How?


9) Yes .

10 ) what are key-mode and locking mode properties? level ?


10) Key Mode : Specifies how oracle forms uniquely identifies rows in the database. This is
property includes
for application that will run against NON-ORACLE data sources .
Key setting unique (default.)
dateable
n-updateable.

Locking mode :
Specifies when Oracle Forms should attempt to obtain database locks on rows that correspond to
queried records in the form.
a) immediate b) delayed

11) What are savepoint mode and cursor mode properties ? level?
11) Specifies whether Oracle Forms should issue savepoints during a session. This property is
included primarily for applications that will run against non-ORACLE data sources. For
applications that will run against ORACLE, use the default setting.
Cursor mode - define cursor state across transaction
Open/close.

12) Can you replace default form processing ? How ?

13) What is transactional trigger property?


13) Identifies a block as transactional control block. i.e. non - database block that oracle forms
should manage as transactional block.(NON-ORACLE data source) default - FALSE.

14) What is OLE automation ?


14) OLE automation allows an OLE server application to expose a set of commands and functions
that can be
invoked from an OLE container application. OLE automation provides a way for an OLE
container application to use the features of an OLE server application to manipulate an OLE
object from the OLE container environment. (FORMS_OLE)

15) What does invoke built-in do?


15) This procedure invokes a method.
Syntax:
PROCEDURE OLE2.INVOKE
(object obj_type,
method VARCHAR2,
list list_type := 0);
Parameters:
object Is an OLE2 Automation Object.
method Is a method (procedure) of the OLE2 object.
list Is the name of an argument list assigned to the OLE2.CREATE_ARGLIST function.

16) What are OPEN_FORM,CALL_FORM,NEW_FORM? diff?


16) CALL_FORM : It calls the other form. but parent remains active, when called form completes
the operation , it releases lock and control goes back to the calling form.
When you call a form, Oracle Forms issues a savepoint for the called form. If the CLEAR_FORM
function
causes a rollback when the called form is current, Oracle Forms rolls back uncommitted changes
to this
savepoint.
OPEN_FORM : When you call a form, Oracle Forms issues a savepoint for the called form. If the
CLEAR_FORM function causes a rollback when the called form is current, Oracle Forms rolls
back
uncommitted changes to this savepoint.
NEW_FORM : Exits the current form and enters the indicated form. The calling form is
terminated as
the parent form. If the calling form had been called by a higher form, Oracle Forms keeps the
higher call
active and treats it as a call to the new form. Oracle Forms releases memory (such as database
cursors)
that the terminated form was using.
Oracle Forms runs the new form with the same Runform options as the parent form. If the
parent form was
a called form, Oracle Forms runs the new form with the same options as the parent form.

17 ) What is call form stack?


17) When successive forms are loaded via the CALL_FORM procedure, the resulting module
hierarchy is known as the call form stack.

18) Can u port applications across the platforms? how?


18) Yes we can port applications across platforms. Consider the form developed in a windows
system. The form would be generated in unix system by using f45gen my_form.fmb scott/tiger

GUI

1) What is a visual attribute?


1) Visual attributes are the font, color, and pattern properties that you set for form and menu
objects that appear in your application's interface.

2) Diff. between VAT and Property Class? imp


2)Named visual attributes define only font, color, and pattern attributes; property classes can
contain these and any other properties.
You can change the appearance of objects at runtime by changing the named visual attribute
programmatically; property class assignment cannot be changed programmatically.
When an object is inheriting from both a property class and a named visual attribute, the named
visual
attribute settings take precedence, and any visual attribute properties in the class are ignored.

3 ) Which trigger related to mouse?


3) When-Mouse-Click
When-Mouse-DoubleClick
When-Mouse-Down
When-Mouse-Enter
When-Mouse-Leave
When-Mouse-Move
When-Mouse-Up

4) What is Current record attribute property?


4) Specifies the named visual attribute used when an item is part of the current record.
Current Record Attribute is frequently used at the block level to display the current row in a
multi-record
If you define an item-level Current Record Attribute, you can display a pre-determined item in a
special color
when it is part of the current record, but you cannot dynamically highlight the current item, as the
input focus changes.

5) Can u change VAT at run time?


5) Yes. You can programmatically change an object's named visual attribute setting to change the
font, color,
and pattern of the object at runtime.

6) Can u set default font in forms?


6) Yes. Change windows registry(regedit). Set form45_font to the desired font.

7) Can u have OLE objects in forms?


7) Yes.

8) Can u have VBX and OCX controls in forms ?


8) Yes.

9) What r the types of windows (Window style)?


9) Specifies whether the window is a Document window or a Dialog window.
10) What is OLE Activation style property?
10) Specifies the event that will activate the OLE containing item.

11) Can u change the mouse pointer ? How?


11) Yes. Specifies the mouse cursor style. Use this property to dynamically change the shape of
the cursor.

Reports 2.5

1) How many types of columns are there and what are they
1) Formula columns :: For doing mathematical calculations and returning one value
Summary Columns :: For doing summary calculations such as summations etc.
Place holder Columns :: These columns are useful for storing the value in a variable

2) Can u have more than one layout in report


2) It is possible to have more than one layout in a report by using the additional layout
option in the layout editor.

3) Can u run the report with out a parameter form


3) Yes it is possible to run the report without parameter form by setting the PARAM
value to Null

4) What is the lock option in reports layout


4) By using the lock option we cannot move the fields in the layout editor outside the
frame. This is useful for maintaining the fields .

5) What is Flex
5) Flex is the property of moving the related fields together by setting the flex property on

6) What are the minimum number of groups required for a matrix report
6) The minimum of groups required for a matrix report are 4

Most Frequently Asked Questions

 What are your strengths and weaknesses?


 Tell me about yourself.
 What are your team-player qualities? Give examples.
 Of the courses you have had at college which courses have you enjoyed the most?
 What is your GPA? How do you feel about it? Does it reflect your abilities?
 How have your educational and work experiences prepared you for this position?
 What work experiences have been most valuable to you and why?
 What have the experiences on your resume taught you about managing and working with people?
 Of the hobbies and interests listed on your resume what is your favorite and tell me why?
 Where do you see yourself in five years?
 What goals have you set for yourself? How are you planning to achieve them?
 To what do you owe your present success?
 Why should I hire you?
 What makes you think you can handle this position?
 What is your most significant accomplishment to date?
 Why do you want to work here?
 Describe a leadership role of yours and tell why you committed your time to it.
 In a particular leadership role you had, what was your greatest challenge?
 Give me an example of an idea that has come to you and what you did with it?
 Give me an example of a problem you solved and the process you used?
 Give me an example of the most creative project that you have worked on.
 Tell me about a project you initiated?
 Describe the project or situation that best demonstrates your analytical abilities?
 Since attending college, what is the toughest decision that you have had to make?
 Tell me about your most difficult decision and how did you go about making it?
 What types of situations put you under pressure, and how do you deal with pressure?
 Give me a situation in which you failed, and how you handled it?
 Why are you interested in our organization?
 What type of position are you seeking?
 Where do you think your interest in this career comes from?
 What industry besides this one are you looking into?
 Why have you chosen this particular profession?
 What interests you about this job?
 What challenges are you looking for in a position?
 What can you contribute to this company?
 What motivates you?
 What turns you off?
 If I asked the people who know you well to describe you, what three words would they use?
 If I asked the people who know you for one reason why I shouldn't hire you what would they say?
 When you take on a project do you like to attack the project in a group of individually?
 Describe the type of manager you prefer.
 Tell me about a team project of which you are particularly proud and your contribution?
 Describe a situation where you had to work with someone who was difficult, how did you handle it?
 What type of work environment appeals to you most?
 With which other companies are you interviewing?
 What charactersitics do you think are important for this position?
 Why do you feel that this company will be a career for you rather than a job?
 Name two management skills that you think you have?
 What characteristics are most important in a good manager? How have you displayed one of them?
 Why did you choose this college and how did you arrive at this decision?
 What factors did you consider in choosing your major?
 Describe how your favorite course has contributed your career interests?
 Since you have been at college, what is it that you are proudest of?
 How have you changed personally since starting college?
 What has been your greatest challenge?
 If you could change a decision you made while at college what would you change and why?
 Why did you choose the campus involvements you did? What did you gain? What did you
contribute?

Questions You Can Ask the Interviewer:

 Ask about the information you researched.


 Describe my job duties.
 Is this a newly created position?
 What are the companies short and long term goals?
 What do you like most about working for this company?
 What is a typical day like for you?
 To whom would I report?
 Whom will I supervise?
 Tell me about the training program I will experience.
 What is the company's promotional policy?
 With whom will I be working most closely?
 When can I expect to hear from you?

DataBase Assignment

Question 1.
Record Tracking

In any competitive event there are records that stand and records that are broken.The event categories
contains the world record and commonwealth record figures for all events as this meeting.As the events have their
heats and finals run some of the records get broken with new records being set.

Your task in this question is to write PL/SQL program to determine who ,if anyone,broke records during
the meeting .First you will need to create a table to store history into.Initially this new table will contain the current
world and commonwealth records for each event category.Then,as the races are completed ,each change to either the
commonwealth or the world record time should be recorded by adding a new row to the table. Once completed your
program will have recorded, in the table you create, the initial time for each record and all subsequent changes to the
records. Note that only the first person to finish a race can break a record since anyone finishing after them will have
a slower time than the record they just set.

The table you create to store the history of the records should have columns for the event description, the
gender of competitors, the name of the competitor who set the record, the record type (either W or C for the
commonwealth), the date the record was set, and the record time. For records which existed prior to the meeting
(which are stored in the Event Categories table) the name, and date of the record will be null.
You must report the record history in order of the event description, within event description sort by
gender, within gender sort by record type,within record type sort in the descending order of time.

Submit the following:


• The create table statement you used to create your table for storing the record history.
• The PL/SQL code you used to determine the records.
• The SQL code you used to output the table of resulting record history.
• The actual output from the execution of the SQL statement.

No table joins are permitted.Your procedure should have multiple cursors and pass
parameters.Examples of parameter passing are included in the study guide and will
also appear in lectures slides during the semester.
Question 2

Produce a PL/SQL stored procedure as follows:

The stored procedure should accept an input parameter of competitor ID.For the competitor selected,the following
information should be presented on the screen.

Competitor Name

For each race in which the competitor has completed,the following information:

Event Number Result Time Position

No table joing are permitted.Your procedure should have multiple cursors and pass
parameters.
Submit the following for both PL/SQL questions:
• The PL/SQL code printed out.
• The actual output from the execution of the program.

The Tables for the Database


Countries
The countries listed in the Countries table,described below,include all of the countries that participate in the
Commonwealth Games,however,not all of these countries have representatives at this competition.

Create table Countries


(CountryID varchar2(3) not null,
CountryName varchar2(40) not null,
CONSTRAINT Countries_pk primary key ( countryID));

The CountryID represents the three letter abbreviation used fo rthe country in the Commonwealth Games
competition.The country name is the name usually used when referring to the country.

Competitors
The competitors table contains a list of the competitors who may or may not compete in these games.Not all
competitors in the competitors table actually compete in the games.

Create table Competitors


(CompetitorNo number (4) not null,
Name varchar2(40) not null,
CountryID varchar2(3),
DateBirth date,
Gender char(1),
CONSTRAINT Competitors_pk primary key (competitorNO));

The countryID represents a countryID from the Countries table and acts as foreign key into that table.Gender is a
single character field that contains a code representing the gender of the competitor.This column will contain M for
male competitors or F for female competitors.

Event Categories
The EventCategories table contains the various categories of events that are contested at the games.For example,one
such event category is the Men’s 100m Backstroke.Notice that an event category consists of an event description
and a gender.Also recorded in this table are the world and commonwealth record time for the particular event as
they stood just prior to the competion.

create table EventCategories


(EventCatNo number(2) not null,
EventDescr varchar2(30) not null,
Gender char(1),
WorldRecord number(8,4),
CommonwealthRecord number(8,4),
CONSTRAINT EventCategories_pk primary key (EventCatNo));

Events
The Events table contains the particular events being contested at the games.In this table the events are actual
races, which are ither eheats or finals and have a scheduled start time.

create table Events


(EventNo number(4) not null,
EventCatNo number(2) not null,
EventType char(1),
StartTime date,
CONSTRAINT Events_pk primary key (EventNo),
CONSTRAINT Events_fk foreign key (EventCatNo) references EventCateogries (EventCatNo));

The EventNo column contains a unique integer used as the primary key for the event.The EventCatNo provides a
foreign key into the event categories table and enables an association between the event and its details including the
records.EventType is a single character coding which shows whether an event is a heat(H) or a final(f).

Entries
The Entries table associates a competitor with a particular event.It not only records the fact that the competitor has
entered the event but also the resulting time that they have achieved, the lane that they were assigned and a flag to
indicate whether or not they were disqualified.
Create table Entries
(EventNo number(4) not null,
CompetitorNo number(4) not null,
Lane number(1),
ResultTime number(8,4),
Disqualified char(1),
CONSTRAINT Entries_pk primary key (EventNo, competitorNo),
CONSTRAINT Entries_Evts_fk foreign key (EventNo) references Events(EventNo),
CONSTRAINT Entries_Comp_fk foreign key (competitotNo) references Competitors(CompetitorNo));

The EventNo column is a foreign key into the Events table.The competitorNo column provides a foreign key back to
the competitors table.Disqualified contain a Y if the competitor has been disqualified and an N otherwise.A
disqualified competitor is not eligible for any medals not are they able to break any records, regardless of the time
they swim.

INDEX

1. Query for retrieving N highest paid employees FROM each Department.


2. Query that will display the total no. of employees, and of that total the
number who were hired in 1980, 1981, 1982, and 1983.
3. Query for listing Deptno, ename, sal, SUM(sal in that dept).
4. Matrix query to display the job, the salary for that job based on department
number, and the total salary for that job for all departments.
5. Nth Top Salary of all the employees.
6. Retrieving the Nth row FROM a table.
7. Tree Query.
8. Eliminate duplicates rows in a table.
9. Displaying EVERY Nth row in a table.
10. Top N rows FROM a table.
11. COUNT/SUM RANGES of data values in a column.
12. For equal size ranges it might be easier to calculate it with
DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...).

13. Count different data values in a column.


14. Query to get the product of all the values of a column.
15. Query to display only the duplicate records in a table.
16. Query for getting the following output as many number of rows in the table.
17. Function for getting the Balance Value.
18. Function for getting the Element Value.
19. SELECT Query for counting No of words.
20. Function to check for a leap year.
21. Query for removing all non-numeric.
22. Query for translating a column values to INITCAP.
23. Function for displaying Rupees in Words.
24. Function for displaying Numbers in Words
25. Query for deleting alternate even rows FROM a table.
26. Query for deleting alternate odd rows FROM a table.
27. Procedure for sending Email.
28. Alternate Query for DECODE function.
29. Create table adding Constraint to a date field to SYSDATE or 3 months later.
30. Query to list all the suppliers who r supplying all the parts supplied by
supplier 'S2'.
31. Query to get the last Sunday of any month.
32. Query to get all those who have no children themselves.

33. Query to SELECT last N rows FROM a table.


34. SELECT with variables.
35. Query to get the DB Name.
36. Getting the current default schema.
37. Query to get all the column names of a particular table.
38. Spool only the query result to a file in SQLPLUS.
39. Query for getting the current SessionID.
40. Query to display rows FROM m to n.
41. Query to count no. Of columns in a table.
42. Procedure to increase the buffer length.
43. Inserting an & symbol in a Varchar2 column.
44. Removing Trailing blanks in a spooled file.
45. Samples for executing Dynamic SQL Statements.
46. Differences between SQL and MS-Access.
47. Query to display all the children, sub children of a parent.
48. Procedure to read/write data from/to a text file.
49. Query to display random number between any two given numbers.
50. Time difference between two date columns.
51. Using INSTR and SUBSTR
52. View procedure code
53. To convert signed number to number in oracle
54. Columns of a table
55. Delete rows conditionally
56.CLOB to Char
57.Change Settings
58.Double quoting a Single quoted String
59.Time Conversion
60.Table comparison
61.Running Jobs
62.Switching Columns
63.Replace and Round
64.First date of the year
65.Create Sequence
66.Cursors
67.Current Week
68. Create Query to restrict the user to a single row.
69. Query to get the first inserted record FROM a table.
70. Concatenate a column value with multiple rows.
71. Query to delete all the tables at once.
72. SQL Query for getting Orphan Records.

1. The following query retrieves "2" highest paid employees FROM each
Department :

SELECT deptno, empno, sal


FROM emp e
WHERE
2 > ( SELECT COUNT(e1.sal)
FROM emp e1
WHERE e.deptno = e1.deptno AND e.sal < e1.sal )
ORDER BY 1,3 DESC;
Index

2. Query that will display the total no. of employees, and of that total the number
who were hired in 1980, 1981, 1982, and 1983. Give appropriate column
headings.

I am looking at the following output. We need to stick to this format.

Total 1980 1981 1982 1983


----------- ------------ ------------ ------------- -----------
14 1 10 2 1

SELECT COUNT (*), COUNT(DECODE(TO_CHAR (hiredate, 'YYYY'),'1980', empno)) "1980",


COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1981', empno)) "1981",
COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1982', empno)) "1982",
COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1983', empno)) "1983"
FROM emp;

Index

3. Query for listing Deptno, ename, sal, SUM(sal in that dept) :

SELECT a.deptno, ename, sal, (SELECT SUM(sal) FROM emp b WHERE a.deptno = b.deptno)
FROM emp a
ORDER BY a.deptno;

OUTPUT :
=======
DEPTNO ENAME SAL SUM (SAL)
========= ======= ==== =========
10 KING 5000 11725
30 BLAKE 2850 10900
10 CLARK 2450 11725
10 JONES 2975 11725
30 MARTIN 1250 10900
30 ALLEN 1600 10900
30 TURNER 1500 10900
30 JAMES 950 10900
30 WARD 2750 10900
20 SMITH 8000 33000
20 SCOTT 3000 33000
20 MILLER 20000 33000

Index

4. Create a matrix query to display the job, the salary for that job based on
department number, and the total salary for that job for all departments, giving
each column an appropriate heading.

The output is as follows - we need to stick to this format :

Job Dept 10 Dept 20 Dept 30 Total


---------- --------------- ------------- ------------- ---------
ANALYST 6000 6000
CLERK 1300 1900 950 4150
MANAGER 2450 2975 2850 8275
PRESIDENT 5000 5000
SALESMAN 5600 5600

SELECT job "Job", SUM (DECODE (deptno, 10, sal)) "Dept 10",
SUM (DECODE (deptno, 20, sal)) "Dept 20",
SUM (DECODE (deptno, 30, sal)) "Dept 30",
SUM (sal) "Total"
FROM emp
GROUP BY job ;

Index

th
5. 4 Top Salary of all the employees :

SELECT DEPTNO, ENAME, SAL


FROM EMP A
WHERE
3 = (SELECT COUNT(B.SAL) FROM EMP B
WHERE A.SAL < B.SAL) ORDER BY SAL DESC;

Index

6. Retrieving the 5th row FROM a table :

SELECT DEPTNO, ENAME, SAL


FROM EMP
WHERE ROWID = (SELECT ROWID FROM EMP WHERE ROWNUM <= 5
MINUS
SELECT ROWID FROM EMP WHERE ROWNUM < 5)

Index

7. Tree Query :

Name Null? Type


-------------------------------------------------------------------
SUB NOT NULL VARCHAR2(4)
SUPER VARCHAR2(4)
PRICE NUMBER(6,2)

SELECT sub, super


FROM parts
CONNECT BY PRIOR sub = super
START WITH sub = 'p1';

Index

8. Eliminate duplicates rows in a table :


DELETE FROM table_name A
WHERE ROWID > ( SELECT min(ROWID) FROM table_name B WHERE A.col = B.col);

Index

9. Displaying EVERY 4th row in a table : (If a table has 14 rows, 4,8,12 rows will
be selected)

SELECT *
FROM emp
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
FROM emp);

Index

10. Top N rows FROM a table : (Displays top 9 salaried people)

SELECT ename, deptno, sal


FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM < 10;

Index

11. How does one count/sum RANGES of data values in a column? A value x will be
between values y and z if GREATEST(x, y) = LEAST(x, z).

SELECT
f2,
COUNT(DECODE(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100",
COUNT(DECODE(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59",
COUNT(DECODE(greatest(f1,29), least(f1, 0), 1, 0)) "Range 00-29"
FROM my_table
GROUP BY f2;

Index

12. For equal size ranges it migth be easier to calculate it with


DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...).

SELECT ename "Name", sal "Salary",


DECODE( TRUNC(sal/1000, 0), 0, 0.0,
1, 0.1,
2, 0.2,
3, 0.3) "Tax rate"
FROM emp;

13. How does one count different data values in a column?

COL NAME DATATYPE


----------------------------------------
DNO NUMBER
SEX CHAR

SELECT dno, SUM(DECODE(sex,'M',1,0)) MALE,


SUM(DECODE(sex,'F',1,0)) FEMALE,
COUNT(DECODE(sex,'M',1,'F',1)) TOTAL
FROM t1
GROUP BY dno;

Index

14. Query to get the product of all the values of a column :

SELECT EXP(SUM(LN(col1))) FROM srinu;

Index

15. Query to display only the duplicate records in a table:

SELECT num
FROM satyam
GROUP BY num
HAVING COUNT(*) > 1;

Index

16. Query for getting the following output as many number of rows in the table :

*
**
***
****
*****

SELECT RPAD(DECODE(temp,temp,'*'),ROWNUM,'*')
FROM srinu1;

Index

17. Function for getting the Balance Value :

FUNCTION F_BALANCE_VALUE
(p_business_group_id number, p_payroll_action_id number,
p_balance_name varchar2, p_dimension_name varchar2) RETURN NUMBER
IS
l_bal number;
l_defined_bal_id number;
l_assignment_action_id number;
BEGIN
SELECT assignment_action_id
INTO l_assignment_action_id
FROM
pay_assignment_actions
WHERE
assignment_id = :p_assignment_id
AND payroll_action_id = p_payroll_action_id;

SELECT
defined_balance_id
INTO
l_defined_bal_id
FROM
pay_balance_types pbt,
pay_defined_balances pdb,
pay_balance_dimensions pbd
WHERE
pbt.business_group_id = p_business_group_id
AND UPPER(pbt.balance_name) = UPPER(p_balance_name)
AND pbt.business_group_id = pdb.business_group_id
AND pbt.balance_type_id = pdb.balance_type_id
AND UPPER(pbd.dimension_name) = UPPER(p_dimension_name)
AND pdb.balance_dimension_id = pbd.balance_dimension_id;

l_bal := pay_balance_pkg.get_value(l_defined_bal_id,l_assignment_action_id);

RETURN (l_bal);

exception
WHEN no_data_found THEN
RETURN 0;
END;

Index

18. Function for getting the Element Value :

FUNCTION f_element_value(
p_classification_name in varchar2,
p_element_name in varchar2,
p_business_group_id in number,
p_input_value_name in varchar2,
p_payroll_action_id in number,
p_assignment_id in number
)
RETURN number
IS
l_element_value number(14,2) default 0;
l_input_value_id pay_input_values_f.input_value_id%type;
l_element_type_id pay_element_types_f.element_type_id%type;
BEGIN
SELECT DISTINCT element_type_id
INTO l_element_type_id
FROM pay_element_types_f pet,
pay_element_classifications pec
WHERE pet.classification_id = pec.classification_id
AND upper(classification_name) = upper(p_classification_name)
AND upper(element_name) = upper(p_element_name)
AND pet.business_group_id = p_business_group_id;

SELECT input_value_id
INTO l_input_value_id
FROM pay_input_values_f
WHERE upper(name) = upper(p_input_value_name)
AND element_type_id = l_element_type_id;
SELECT NVL(prrv.result_value,0)
INTO l_element_value
FROM pay_run_result_values prrv,
pay_run_results prr,
pay_assignment_actions paa
WHERE prrv.run_result_id = prr.run_result_id
AND prr.assignment_ACTION_ID = paa.assignment_action_id
AND paa.assignment_id = p_assignment_id
AND input_value_id = l_input_value_id
AND paa.payroll_action_id = p_payroll_action_id;

RETURN (l_element_value);

exception
WHEN no_data_found THEN
RETURN 0;
END;

Index

19. SELECT Query for counting No of words :

SELECT ename,
NVL(LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWX
YZ'' ',' @'),' ',''))+1,1) word_length
FROM emp;

Explanation :

TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','
@') -- This will translate all the characters FROM A-Z including a single quote to a space. It
will also translate a space to a @.

REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','
@'),' ','') -- This will replace every space with nothing in the above result.

LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ''
',' @'),' ',''))+1 -- This will give u the count of @ characters in the above
result.

Index

20. Function to check for a leap year :

CREATE OR REPLACE FUNCTION is_leap_year (p_date IN DATE) RETURN VARCHAR2


AS
v_test DATE;
BEGIN
v_test := TO_DATE ('29-Feb-' || TO_CHAR (p_date,'YYYY'),'DD-Mon-YYYY');
RETURN 'Y';
EXCEPTION
WHEN OTHERS THEN
RETURN 'N';
END is_leap_year;
SQL> SELECT hiredate, TO_CHAR (hiredate, 'Day') weekday
FROM emp
WHERE is_leap_year (hiredate) = 'Y';

Index

21. Query for removing all non-numeric :

SELECT
TRANSLATE(LOWER(ssn),'abcdefghijklmnopqrstuvwxyz- ','')
FROM DUAL;

Index

22. Query for translating a column values to INITCAP :

SELECT
TRANSLATE(INITCAP(temp),
SUBSTR(temp, INSTR(temp,'''')+1,1), LOWER(SUBSTR(temp, INSTR(temp,'''')+1)))
FROM srinu1;

Index

23. Function for displaying Rupees in Words :

CREATE OR REPLACE FUNCTION RUPEES_IN_WORDS(amt IN NUMBER) RETURN CHAR


IS
amount NUMBER(10,2);
v_length INTEGER := 0;
v_num2 VARCHAR2 (50) := NULL;
v_amount VARCHAR2 (50);
v_word VARCHAR2 (4000) := NULL;
v_word1 VARCHAR2 (4000) := NULL;
TYPE myarray IS TABLE OF VARCHAR2 (255);
v_str myarray := myarray (' thousand ',
' lakh ',
' crore ',
' arab ',
' kharab ',
' shankh ');
BEGIN
amount := amt;
IF ((amount = 0) OR (amount IS NULL)) THEN
v_word := 'zero';
ELSIF (TO_CHAR (amount) LIKE '%.%') THEN
IF (SUBSTR (amount, INSTR (amount, '.') + 1) > 0) THEN
v_num2 := SUBSTR (amount, INSTR (amount, '.') + 1);
IF (LENGTH (v_num2) < 2) THEN
v_num2 := v_num2 * 10;
END IF;
v_word1 := ' AND ' || (TO_CHAR (TO_DATE (SUBSTR (v_num2,
LENGTH (v_num2) - 1,2), 'J'),
'JSP' ))|| ' paise ';

v_amount := SUBSTR(amount,1,INSTR (amount, '.')-1);


v_word := TO_CHAR (TO_DATE (SUBSTR (v_amount, LENGTH (v_amount) -
2,3), 'J'), 'Jsp' ) || v_word;
v_amount := SUBSTR (v_amount, 1, LENGTH (v_amount) - 3);
FOR i in 1 .. v_str.COUNT
LOOP
EXIT WHEN (v_amount IS NULL);
v_word := TO_CHAR (TO_DATE (SUBSTR (v_amount, LENGTH
(v_amount) - 1,2), 'J'), 'Jsp' ) || v_str (i) || v_word;
v_amount := SUBSTR (v_amount, 1, LENGTH (v_amount) -
2);
END LOOP;
END IF;
ELSE
v_word := TO_CHAR (TO_DATE (SUBSTR (amount, LENGTH (amount) -
2,3), 'J'), 'Jsp' );
amount := SUBSTR (amount, 1, LENGTH (amount) - 3);
FOR i in 1 .. v_str.COUNT
LOOP
EXIT WHEN (amount IS NULL);
v_word := TO_CHAR (TO_DATE (SUBSTR (amount, LENGTH (amount)
- 1,2), 'J'), 'Jsp' ) || v_str (i) || v_word;
amount := SUBSTR (amount, 1, LENGTH (amount) - 2);
END LOOP;
END IF;

v_word := v_word || ' ' || v_word1 || ' only ';


v_word := REPLACE (RTRIM (v_word), ' ', ' ');
v_word := REPLACE (RTRIM (v_word), '-', ' ');

RETURN INITCAP (v_word);


END;

Index

24. Function for displaying Numbers in Words:


SELECT TO_CHAR( TO_DATE( SUBSTR( TO_CHAR(5373484),1),'j'),'Jsp') FROM DUAL;

Only up to integers from 1 to 5373484

Index

25. Query for deleting alternate even rows FROM a table :

DELETE
FROM srinu
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,2)
FROM srinu);

Index

26. Query for deleting alternate odd rows FROM a table :

DELETE
FROM srinu
WHERE (ROWID,1) IN (SELECT ROWID, MOD(ROWNUM,2)
FROM srinu);
Index

27. Procedure for sending Email :

CREATE OR REPLACE PROCEDURE Send_Mail


IS
sender VARCHAR2(50) := 'sender@something.com';
recipient VARCHAR2(50) := 'recipient@something.com';
subject VARCHAR2(100) := 'Test Message';
message VARCHAR2(1000) := 'This is a sample mail ....';
lv_mailhost VARCHAR2(30) := 'HOTNT002';
l_mail_conn utl_smtp.connection;
lv_crlf VARCHAR2(2):= CHR( 13 ) || CHR( 10 );
BEGIN
l_mail_conn := utl_smtp.open_connection (lv_mailhost, 80);
utl_smtp.helo ( l_mail_conn, lv_mailhost);
utl_smtp.mail ( l_mail_conn, sender);
utl_smtp.rcpt ( l_mail_conn, recipient);
utl_smtp.open_data (l_mail_conn);
utl_smtp.write_data ( l_mail_conn, 'FROM: ' || sender || lv_crlf);
utl_smtp.write_data ( l_mail_conn, 'To: ' || recipient || lv_crlf);
utl_smtp.write_data ( l_mail_conn, 'Subject:' || subject || lv_crlf);
utl_smtp.write_data ( l_mail_conn, lv_crlf || message);
utl_smtp.close_data(l_mail_conn);
utl_smtp.quit(l_mail_conn);

EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error');
END;
/

Index

28. Alternate Query for DECODE function :

SELECT case
WHEN sex = 'm' THEN 'male'
WHEN sex = 'f' THEN 'female'
ELSE 'unknown'
END
FROM mytable;

Index

29. Create table adding Constraint to a date field to SYSDATE or 3 months later:

CREATE TABLE srinu(dt1 date DEFAULT SYSDATE, dt2 date,


CONSTRAINT check_dt2 CHECK ((dt2 >= dt1) AND (dt2 <= ADD_MONTHS(SYSDATE,3)));

Index

30. Query to list all the suppliers who supply all the parts supplied by supplier
'S2' :
SELECT DISTINCT a.SUPP
FROM ORDERS a
WHERE a.supp != 'S2'
AND a.parts IN
(SELECT DISTINCT PARTS FROM ORDERS WHERE supp = 'S2')
GROUP BY a.SUPP
HAVING
COUNT(DISTINCT a.PARTS) >=
(SELECT COUNT(DISTINCT PARTS) FROM ORDERS WHERE supp = 'S2');

Table : orders

SUPP PARTS
-------------------- -------
S1 P1
S1 P2
S1 P3
S1 P4
S1 P5
S1 P6
S2 P1
S2 P2
S3 P2
S4 P2
S4 P4
S4 P5

Index

31. Query to get the last Sunday of any month :

SELECT NEXT_DAY(LAST_DAY(TO_DATE('26-10-2001','DD-MM-YYYY')) - 7,'sunday')


FROM DUAL;

Index

32. Query to get all those who have no children themselves :

table data :
id name parent_id
-------------------------------
1 a NULL - the top level entry
2 b 1 - a child of 1
3 c 1
4 d 2 - a child of 2
5 e 2
6 f 3
7 g 3
8 h 4
9 i 8
10 j 9

SELECT ID
FROM MY_TABlE
WHERE PARENT_ID IS NOT NULL
MINUS
SELECT PARENT_ID
FROM MY_TABlE;

Index

33. Query to SELECT last N rows FROM a table :

SELECT empno FROM emp WHERE ROWID in


(SELECT ROWID FROM emp
MINUS
SELECT ROWID FROM emp WHERE ROWNUM <= (SELECT COUNT(*)-5 FROM emp));

Index

34. SELECT with variables:

CREATE OR REPLACE PROCEDURE disp


AS
xTableName varchar2(25):='emp';
xFieldName varchar2(25):='ename';
xValue NUMBER;
xQuery varchar2(100);
name varchar2(10) := 'CLARK';
BEGIN
xQuery := 'SELECT SAL FROM ' || xTableName || ' WHERE ' || xFieldName ||
' = ''' || name || '''';

DBMS_OUTPUT.PUT_LINE(xQuery);

EXECUTE IMMEDIATE xQuery INTO xValue;


DBMS_OUTPUT.PUT_LINE(xValue);
END;

Index

35. Query to get the DB Name:

SELECT name FROM v$database;

Index

36. Getting the current default schema :

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

Index

37. Query to get all the column names of a particular table :

SELECT column_name
FROM all_tab_columns
WHERE TABLE_NAME = 'ORDERS';
Index

38. How do I spool only the query result to a file in SQLPLUS :

Place the following lines of code in a file and execute the file in SQLPLUS :

set heading off


set feedback off
set colsep ' '
set termout off
set verify off
spool c:\srini.txt
SELECT empno,ename FROM emp; /* Write your Query here */
spool off
/

Index

39. Query for getting the current SessionID :

SELECT SYS_CONTEXT('USERENV','SESSIONID') Session_ID FROM DUAL;

Index

40. Query to display rows FROM m to n :

To display rows 5 to 7 :

SELECT DEPTNO, ENAME, SAL


FROM EMP
WHERE ROWID IN
(SELECT ROWID FROM EMP
WHERE ROWNUM <= 7
MINUS
SELECT ROWID FROM EMP
WHERE ROWNUM < 5);

OR

SELECT ename
FROM emp
GROUP BY ROWNUM, ename
HAVING ROWNUM > 1 and ROWNUM < 3;

Index

41. Query to count no. Of columns in a table:

SELECT COUNT(column_name)
FROM user_tab_columns
WHERE table_name = 'MYTABLE';

Index

42. Procedure to increase the buffer length :


dbms_output.enable(4000); /*allows the output buffer to be increased to the specified
number of bytes */

DECLARE
BEGIN
dbms_output.enable(4000);
FOR i IN 1..400
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/

Index

43. Inserting an & symbol in a Varchar2 column :

Set the following to some other character. By default it is &.

set define '~'

Index

44. How do you remove Trailing blanks in a spooled file :


Change the Environment Options Like this :
set trimspool on
set trimout on

Index

45. Samples for executing Dynamic SQL Statements :

Sample :1
CREATE OR REPLACE PROCEDURE CNT(P_TABLE_NAME IN VARCHAR2)
AS
SqlString VARCHAR2(200);
tot number;
BEGIN
SqlString:='SELECT COUNT(*) FROM '|| P_TABLE_NAME;
EXECUTE IMMEDIATE SqlString INTO tot;
DBMS_OUTPUT.PUT_LINE('Total No.Of Records In ' || P_TABLE_NAME || ' ARE=' || tot);
END;

Sample :2
DECLARE
sql_stmt VARCHAR2(200);
plsql_block VARCHAR2(500);
emp_id NUMBER(4) := 7566;
salary NUMBER(7,2);
dept_id NUMBER(2) := 50;
dept_name VARCHAR2(14) := ’PERSONNEL’;
location VARCHAR2(13) := ’DALLAS’;
emp_rec emp%ROWTYPE;
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE bonus (id NUMBER, amt NUMBER)';

sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';


EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;

sql_stmt := 'SELECT * FROM emp WHERE empno = :id';


EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;

plsql_block := 'BEGIN emp_pkg.raise_salary(:id, :amt); END;';


EXECUTE IMMEDIATE plsql_block USING 7788, 500;

sql_stmt := 'UPDATE emp SET sal = 2000 WHERE empno = :1


RETURNING sal INTO :2';
EXECUTE IMMEDIATE sql_stmt USING emp_id RETURNING INTO salary;

EXECUTE IMMEDIATE 'DELETE FROM dept WHERE deptno = :num'


USING dept_id;

EXECUTE IMMEDIATE ’ALTER SESSION SET SQL_TRACE TRUE’;


END;

Sample 3
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x',
DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
LOOP
IF DBMS_SQL.FETCH_ROWS(v_cursor) = 0 THEN
EXIT;
END IF;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
END LOOP;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
WHEN OTHERS THEN
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||
sqlerrm);
END;

Index

46.Differences between SQL and MS-Access :


Difference 1:
Oracle : select name from table1 where name like 'k%';
Access: select name from table1 where name like 'k*';
Difference 2:
Access: SELECT TOP 2 name FROM Table1;
Oracle : will not work there is no such TOP key word.

Index

47. Query to display all the children, sub children of a parent :

SELECT organization_id,name
FROM hr_all_organization_units
WHERE organization_id in
(
SELECT ORGANIZATION_ID_CHILD FROM PER_ORG_STRUCTURE_ELEMENTS
CONNECT BY PRIOR
ORGANIZATION_ID_CHILD = ORGANIZATION_ID_PARENT
START WITH
ORGANIZATION_ID_CHILD = (SELECT organization_id
FROM hr_all_organization_units
WHERE name = 'EBG Corporate Group'));

Index

48. Procedure to read/write data from a text file :

CREATE OR REPLACE PROCEDURE read_data


AS
c_path varchar2(100) := '/usr/tmp';
c_file_name varchar2(20) := 'EKGSEP01.CSV';
v_file_id utl_file.file_type;
v_buffer varchar2(1022) := This is a sample text’;
BEGIN
v_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'w');
UTL_FILE.PUT_LINE(v_file_id, v_buffer);
UTL_FILE.FCLOSE(v_file_id);

v_file_id := UTL_FILE.FOPEN(c_path,c_file_name,'r');
UTL_FILE.GET_LINE(v_file_id, v_buffer);
DBMS_OUTPUT.PUT_LINE(v_buffer);
UTL_FILE.FCLOSE(v_file_id);
END;
/

Index

49. Query to display random number between any two given numbers :

SELECT DBMS_RANDOM.VALUE (1,2) FROM DUAL;

Index

50. How can I get the time difference between two date columns :
SELECT
FLOOR((date1-date2)*24*60*60)/3600)
|| ' HOURS ' ||
FLOOR((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)
|| ' MINUTES ' ||
ROUND((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600 -
(FLOOR((((date1-date2)*24*60*60) -
FLOOR(((date1-date2)*24*60*60)/3600)*3600)/60)*60)))
|| ' SECS ' time_difference
FROM my_table;

Index

51. Using INSTR and SUBSTR

I have this string in a column named location

LOT 8 CONC3 RR

Using instr and substr, I want to take whatever value follows LOT and put
it into a different column and whatever value follows CONC and put it into
a different column

select substr('LOT 8 CONC3 RR',4,instr('LOT 8 CONC3 RR','CONC')-4) from


dual;

select substr('LOT 8 CONC3 RR',-(length('LOT 8 CONC3 RR')-(instr('LOT 8


CONC3 RR','CONC')+3)))
from dual

Index

52. View procedure code

select text from all_source where name = 'X'


order by line;
select text from user_source where name = 'X'
select text from user_source where type = 'procedure' and
name='procedure_name';
select name,text from dba_source where name='ur_procedure'
and owner='scott';

Index

53. To convert signed number to number in oracle

select to_number('-999,999.99', 's999,999.99') from dual; -999,999.99


select to_number('+0,123.45', 's999,999,999.99') from dual; 123.45
select to_number('+999,999.99', 's999,999.99') from dual; 999,999.99

Index
54. Columns of a table

select column_name from user_tab_columns where TABLE_NAME = 'EMP'


select column_name from all_tab_columns where TABLE_NAME = 'EMP'
select column_name from dba_tab_columns where TABLE_NAME = 'EMP'
select column_name from cols where TABLE_NAME = 'EMP'

Index

55. Delete rows conditionally


I have a table have
a,b,c field,

a,b should be unique, and leave max(c) row in.


How can I delete other rows?

delete from 'table'


where (a,b,c) not in (select a,b,max(c) from 'table' group by a,b);

Index

56.CLOB to Char

1) This function helps if your clob column value not exceed 4000 bytes
(varchar2 limit).if clob column's data exceeds 4000 limit, you have to
follow different approach.

create or replace function lob_to_char(clob_col clob) return varchar2 IS


buffer varchar2(4000);
amt BINARY_INTEGER := 4000;
pos INTEGER := 1;
l clob;
bfils bfile;
l_var varchar2(4000):='';
begin
LOOP
if dbms_lob.getlength(clob_col)<=4000 THEN
dbms_lob.read (clob_col, amt, pos, buffer);
l_var := l_var||buffer;
pos:=pos+amt;
ELSE
l_var:= 'Cannot convert to varchar2..Exceeding varchar2 field
limit';
exit;
END IF;
END LOOP;
return l_var;
EXCEPTION
WHEN NO_DATA_FOUND THEN
return l_var;
END;

2) CREATE GLOBAL TEMPORARY TABLE temp_tab(id number,varchar_col


varchar2(4000));
SQL> var r refcursor
SQL> exec lobpkg.lob_to_char(:r);
SQL> print r

create or replace package lobpkg is


type ref1 is ref cursor;
n number:=0;
PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) ;
end;
/

create or replace package body lobpkg is

PROCEDURE lob_to_char(rvar IN OUT lobpkg.ref1) IS


buffer varchar2(4000);
amt BINARY_INTEGER := 4000;
pos INTEGER := 1;
l clob;
r lobpkg.ref1;
bfils bfile;
l_var varchar2(4000):='';
CURSOR C1 IS SELECT * FROM clob_tab;
-- change clob_tab to your_table_name
begin
n:=n+1;
FOR crec IN c1 LOOP
amt:=4000;
pos:=1;
BEGIN
LOOP

--change crec.clob_col to crec.your_column_name

dbms_lob.read (crec.clob_col, amt, pos, buffer);

--change next line if you create temporary table with different name

insert into temp_tab values (n,buffer);

pos:=pos+amt;

END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
END LOOP;
--change next line if you create temporary table with different name
open rvar for select vchar from temp_tab where id=n;

END;
END;
Index

57. Change Settings

Open file oracle_home\plus32\glogin.sql and


add this
set linesize 100
set pagewidth 20
and save the file
and exit from sql and reload then it will set it.

Index

58. Double quoting a Single quoted String

declare
-- we need one here to get a single quote into the variable
v_str varchar2 (20) := 'O''reilly''s';
begin
DBMS_OUTPUT.PUT_LINE ( 'original single quoted v_str= ' || v_str );
v_str := replace(v_str, '''', '''''');
DBMS_OUTPUT.PUT_LINE ( 'after double quoted v_str= ' || v_str );
end;
SQL> /
original single quoted v_str= O'reilly's
after double quoted v_str= O''reilly''s

Index

59. Time Conversion

CREATE OR REPLACE FUNCTION to_hms (i_days IN number)


RETURN varchar2
IS
BEGIN
RETURN TO_CHAR (TRUNC (i_days)) &#124&#124 ' days ' &#124&#124
TO_CHAR (TRUNC (SYSDATE) + MOD (i_days, 1), 'HH24:MI:SS');
END to_hms;

select to_hms(to_date('17-Jan-2002 13:20:20', 'dd-Mon-yyyy hh24:mi:ss') -


to_date('11-Jan-2002 11:05:05', 'dd-Mon-yyyy hh24:mi:ss')) from
dual;

Index

60. Table comparison


The table in both the schemas should have exactly the same structure. The data in
it could be same or different

a-b and b-a


select * from a.a minus select * from b.a and select * from b.a minus select * from a.a

Index

61.Running Jobs

select * from user_jobs;


exec dbms_job.remove(job_no);

Index

62.Switching Columns
Update tblname
Set column1 = column2,
Column2 = column1;

Index

63.Replace and Round


I have the number e.g. 63,9823874012983 and I want to round it to 63,98 and at the
same time change the , to a .

select round(replace('63,9823874012983',',','.'),2) from dual;

Index

64.First date of the year


select trunc(sysdate, 'y') from dual;

01-jan-2002

last year this month through a select statement


select add_months(sysdate, -12) from dual;
05-APR-01

Index

65.Create Sequence
create sequence sh increment by 1 start with 0;
Index

66.Cursors
cursor is someting like pointers in C language.
u fetch the data using cursor.( wiz...store it somewhere temporarily). u
can do any manipulation to the data that is fetched by the cursor. like
trim, padd, concat or validate. all this are done in temporary areas called
as context area or the cursor area. u can insert this data again in some
other table or do anything u want!!...like setting up some flags etc.
U can display the contents of cursor using the dbms_output only. U can
create an anonymous plsql block or a stored procedure. the major advantage
of cursors is that you can fetch more thatn one row and u can loop through
the resultset and do the manupulations in a secure manner.

set serveroutput on;


declare
cursor c1 is select * from emp;
begin
for var in c1 loop
exit when c1%notfound;
dbms_output.put_line('the employee' &#124&#124 var.ename &#124&#124'draws a
salary of '&#124&#124 var.sal);
end loop;
end;

Index

67.Current Week

select next_day(sysdate-7,'SUNDAY'), next_day(sysdate,'SATURDAY') from dual;

NEXT_DAY( NEXT_DAY(
--------- ---------
07-APR-02 13-APR-02

Index

Interview Questions for Oracle, DBA, Developer Candidates

PL/SQL Questions:

1. Describe the difference between a procedure, function and anonymous pl/sql block.
Level: Low
Expected answer : Candidate should mention use of DECLARE statement, a function must return a
value while a procedure doesn’t have to.

2. What is a mutating table error and how can you get around it?
Level: Intermediate
Expected answer: 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.

3. Describe the use of %ROWTYPE and %TYPE in PL/SQL


Level: Low
Expected answer: %ROWTYPE allows you to associate a variable with an entire table
row. The %TYPE associates a variable with a single column type.

4. What packages (if any) has Oracle provided for use by developers?
Level: Intermediate to high
Expected answer: 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_JOB,
DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they can mention a few of these and
describe how they used them, even better. If they include the SQL routines provided by
Oracle, great, but not really what was asked.

5. Describe the use of PL/SQL tables


Level: Intermediate
Expected answer: 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.

6. When is a declare statement needed?


Level: Low
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.

7. 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?
Level: Intermediate
Expected answer: 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.

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

9. How can you find within a PL/SQL block, if a cursor is open?


Level: Low
Expected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?


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

11. What are the types of triggers?


Level:Intermediate to high
Expected answer: 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.

DBA
1. Give one method for transferring a table from one schema to another:
Level:Intermediate
Expected answer:There are several possible methods, export-import, CREATE
TABLE... AS SELECT, or COPY.

2. What is the purpose of the IMPORT option IGNORE? What is it’s default setting?
Level: Low
Expected answer: 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.

3. You have a rollback segment in a version 7.2 database that has expanded beyond
optimal, how can it be restored to optimal?
Level: Low
Expected answer: Use the ALTER TABLESPACE ..... SHRINK command.

4. If the DEFAULT and TEMPORARY tablespace clauses are left out of a CREATE
USER command what happens? Is this bad or good? Why?
Level: Low
Expected answer: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).

5. What are some of the Oracle provided packages that DBAs should be aware of?
Level: Intermediate to High
Expected answer: 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, 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.

6. What happens if the constraint name is left out of a constraint clause?


Level: Low
Expected answer: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.

7. What happens if a tablespace clause is left off of a primary key constraint clause?
Level: Low
Expected answer: 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.

8. What is the proper method for disabling and re-enabling a primary key constraint?
Level: Intermediate
Expected answer: 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.

9. What happens if a primary key constraint is disabled and then enabled without fully
specifying the index clause?
Level: Intermediate
Expected answer: 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.

10. (On UNIX) When should more than one DB writer process be used? How many should
be used?
Level: High
Expected answer: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.

11. You are using hot backup without being in archivelog mode, can you recover in the
event of a failure? Why or why not?
Level: High
Expected answer:You can’t use hot backup without being in archivelog mode. So no,
you couldn’t recover.

12. What causes the "snapshot too old" error? How can this be prevented or mitigated?
Level: Intermediate
Expected answer: 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.

13. How can you tell if a database object is invalid?


Level: Low
Expected answer: By checking the status column of the DBA_, ALL_ or
USER_OBJECTS views, depending upon whether you own or only have permission on
the view or are using a DBA account.

14. A user is getting an ORA-00942 error yet you know you have granted them permission
on the table, what else should you check?
Level: Low
Expected answer: 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;)

15. 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?
Level: Intermediate
Expected answer: 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.

16. If you have an example table, what is the best way to get sizing data for the production
table implementation?
Level: Intermediate
Expected answer: 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.

17. How can you find out how many users are currently logged into the database? How can
you find their operating system id?
Level: high
Expected answer: 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.

18. A user selects from a sequence and gets back two values, his select is:
SELECT pk_seq.nextval FROM dual;
What is the problem?
Level: Intermediate
Expected answer: 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.

19. How can you determine if an index needs to be dropped and rebuilt?
Level: Intermediate
Expected answer: 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
BR_BLK_LEN/ LF_BLK_LEN+BR_BLK_LEN is nearing 0.3.

SQL/ SQLPlus

1. How can variables be passed to a SQL routine?


Level: Low
Expected answer: 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.

2. You want to include a carriage return/linefeed in your output from a SQL script, how
can you do this?
Level: Intermediate to high
Expected answer: 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.

3. How can you call a PL/SQL procedure from SQL?


Level: Intermediate
Expected answer: By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL?
Level: Low
Expected answer: By use of the exclamation point "!" (in UNIX and some other OS) or
the HOST (HO) command.

5. You want to use SQL to build SQL, what is this called and give an example
Level: Intermediate to high
Expected answer: 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.

6. What SQLPlus command is used to format output from a select?


Level: low
Expected answer: This is best done with the COLUMN command.

7. 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
Level: Intermediate
Expected answer:The only column that can be grouped on is the "item_no" column,
the rest have aggregate functions associated with them.

8. What special Oracle feature allows you to specify how the cost based system
treats a SQL statement?
Level: Intermediate to high
Expected answer: 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.

9. 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?
Level: High
Expected answer: 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.
10. What is a Cartesian product?
Level: Low
Expected answer: 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.
11. You are joining a local and a remote table, the network manager complains about the
traffic involved, how can you reduce the network traffic?
Level: High
Expected answer: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.
12. What is the default ordering of an ORDER BY clause in a SELECT statement?
Level: Low
Expected answer: Ascending

13. What is tkprof and how is it used?


Level: Intermediate to high
Expected answer: 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.

14. What is explain plan and how is it used?


Level: Intermediate to high
Expected answer: 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.

15. How do you set the number of lines on a page of output? The width?
Level: Low
Expected answer: 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.

16. How do you prevent output from coming to the screen?


Level: Low
Expected answer: The SET option TERMOUT controls output to the screen. Setting
TERMOUT OFF turns off screen output. This option can be shortened to TERM.

17. How do you prevent Oracle from giving you informational messages during and after a
SQL statement execution?
Level: Low
Expected answer: The SET options FEEDBACK and VERIFY can be set to OFF.
18. How do you generate file output from SQL?
Level: Low
Expected answer: By use of the SPOOL command

Tuning Questions:
1. A tablespace has a table with 30 extents in it. Is this bad? Why or why not.
Level: Intermediate
Expected answer: Multiple extents in and of themselves aren’t bad. However if you also
have chained rows this can hurt performance.

2. How do you set up tablespaces during an Oracle installation?


Level: Low
Expected answer: 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.

3. You see multiple fragments in the SYSTEM tablespace, what should you check first?
Level: Low
Expected answer: Ensure that users don’t have the SYSTEM tablespace as their
TEMPORARY or DEFAULT tablespace assignment by checking the DBA_USERS view.

4. What are some indications that you need to increase the SHARED_POOL_SIZE
parameter?
Level: Intermediate
Expected answer: 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.

5. What is the general guideline for sizing db_block_size and db_multi_block_read for an
application that does many full table scans?
Level: High
Expected answer: Oracle almost always reads in 64k chunks. The two should have a
product equal to 64 or a multiple of 64.

6. What is the fastest query method for a table?


Level: Intermediate
Expected answer: Fetch by rowid

7. Explain the use of TKPROF? What initialization parameter should be turned on to get
full TKPROF output?
Level: High
Expected answer: 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.

8. When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If bad
-How do you correct it?
Level: Intermediate
Expected answer: 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.

9. When should you increase copy latches? What parameters control copy latches?
Level: high
Expected answer: 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.

10. 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?
Level: Low
Expected answer: You can look in the init<sid>.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.

11. 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?
Level: Intermediate
Expected answer: 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.

12. Discuss row chaining, how does it happen? How can you reduce it? How do you correct
it?
Level: high
Expected answer: 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.
13. 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?
Level: high
Expected answer: 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.

14. If you see contention for library caches how can you fix it?
Level: Intermediate
Expected answer: Increase the size of the shared pool.

15. If you see statistics that deal with "undo" what are they really talking about?
Level: Intermediate
Expected answer: Rollback segments and associated structures.

16. If a tablespace has a default pctincrease of zero what will this cause (in relationship to
the smon process)?
Level: High
Expected answer: The SMON process won’t automatically coalesce its free space
fragments.

17. If a tablespace shows excessive fragmentation what are some methods to defragment
the tablespace? (7.1,7.2 and 7.3 only)
Level: High
Expected answer: 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 <name> 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.

18. How can you tell if a tablespace has excessive fragmentation?


Level: Intermediate
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.

19. 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?
Level: Intermediate
Expected answer: Since the wait time is zero, no. If the wait time was high it might
indicate a need for more or larger redo logs.
20. What can cause a high value for recursive calls? How can this be fixed?
Level: High
Expected answer: 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 proper space management techniques (proper storage and sizing) or
ensure repeat queries are placed in packages for proper reuse.

21. 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?
Level: Intermediate
Expected answer: This indicate that the shared pool may be too small. Increase the
shared pool size.

22. If you see the value for reloads is high in the estat library cache report is this a matter
for concern?
Level: Intermediate
Expected answer: Yes, you should strive for zero reloads if possible. If you see
excessive reloads then increase the size of the shared pool.

23. 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?
Level: High
Expected answer: 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.

24. You look at the dba_rollback_segs view and see that you have a large number of wraps
is this a problem?
Level: High
Expected answer: 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.

25. 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?
Level: Intermediate
Expected answer: 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.

26. You see multiple extents in the temporary tablespace. Is this a problem?
Level: Intermediate
Expected answer: 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.
Installation/Configuration
1. Define OFA.
Level: Low
Expected answer: 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.

2. How do you set up your tablespace on installation?


Level: Low
Expected answer: 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.

3. What should be done prior to installing Oracle (for the OS and the disks)?
Level: Low
Expected Answer: adjust kernel parameters or OS tuning parameters in accordance
with installation guide. Be sure enough contiguous disk space is available.

4. 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?
Level: Intermediate to high
Expected Answer: 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.

5. When configuring SQLNET on the server what files must be set up?
Level: Intermediate
Expected answer: INITIALIZATION file, TNSNAMES.ORA file, SQLNET.ORA file

6. When configuring SQLNET on the client what files need to be set up?
Level: Intermediate
Expected answer: SQLNET.ORA, TNSNAMES.ORA

7. What must be installed with ODBC on the client in order for it to work with Oracle?
Level: Intermediate
Expected answer: SQLNET and PROTOCOL (for example: TCPIP adapter) layers of
the transport programs.

8. You have just started a new instance with a large SGA on a busy existing server.
Performance is terrible, what should you check for?
Level: Intermediate
Expected answer: The first thing to check with a large SGA is that it isn’t being swapped
out.

9. What OS user should be used for the first part of an Oracle installation (on UNIX)?
Level: low
Expected answer: You must use root first.

10. When should the default values for Oracle initialization parameters be used as is?
Level: Low
Expected answer: Never

11. How many control files should you have? Where should they be located?
Level: Low
Expected answer: At least 2 on separate disk spindles. Be sure they say on separate
disks, not just file systems.

12. How many redo logs should you have and how should they be configured for maximum
recoverability?
Level: Intermediate
Expected answer: 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.

13. 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?
Expected answer: At least 7, see disk configuration answer above.

Data Modeler
1. Describe third normal form?
Level: Low
Expected answer: Something like: In third normal form all attributes in an entity are
related to the primary key and only to the primary key

2. Is the following statement true or false:


"All relational databases must be in third normal form"
Why or why not?
Level: Intermediate
Expected answer: 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.

3. What is an ERD?
Level: Low
Expected answer: An ERD is an Entity-Relationship-Diagram. It is used to show the
entities and relationships for a database logical model.

4. Why are recursive relationships bad? How do you resolve them?


Level: Intermediate
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 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.

5. What does a hard one-to-one relationship mean (one where the relationship on both ends
is "must")?
Level: Low to intermediate
Expected answer: This means the two entities should probably be made into one entity.

6. How should a many-to-many relationship be handled?


Level: Intermediate
Expected answer: By adding an intersection entity table

7. What is an artificial (derived) primary key? When should an artificial (or derived)
primary key be used?
Level: Intermediate
Expected answer: A derived key comes from a sequence. Usually it is used when a
concatenated key becomes too cumbersome to use as a foreign key.

8. When should you consider denormalization?


Level: Intermediate
Expected answer: Whenever performance analysis indicates it would be beneficial to do
so without compromising data integrity.
UNIX
1. How can you determine the space left in a file system?
Level: Low
Expected answer: There are several commands to do this: du, df, or bdf

2. How can you determine the number of SQLNET users logged in to the UNIX system?
Level: Intermediate
Expected answer: SQLNET users will show up with a process unique name that begins
with oracle<SID>, if you do a ps -ef|grep oracle<SID>|wc -l you can get a count of the
number of users.

3. What command is used to type files to the screen?


Level: Low
Expected answer: cat, more, pg

4. What command is used to remove a file?


Level: Low
Expected answer: rm

5. Can you remove an open file under UNIX?


Level: Low
Expected answer: yes

6. How do you create a decision tree in a shell script?


Level: intermediate
Expected answer: depending on shell, usually a case-esac or an if-endif or fi structure

7. What is the purpose of the grep command?


Level: Low
Expected answer: grep is a string search command that parses the specified string from
the specified file or files

8. The system has a program that always includes the word nocomp in its name, how can
you determine the number of processes that are using this program?
Level: intermediate
Expected answer: ps -ef|grep *nocomp*|wc -l

9. What is an inode?
Level: Intermediate
Expected answer: an inode is a file status indicator. It is stored in both disk and memory
and tracts file status. There is one inode for each file on the system.
10. The system administrator tells you that the system hasn’t been rebooted in 6 months,
should he be proud of this?
Level: High
Expected answer: Maybe. Some UNIX systems don’t clean up well after themselves.
Inode problems and dead user processes can accumulate causing possible
performance and corruption problems. Most UNIX systems should have a scheduled
periodic reboot so file systems can be checked and cleaned and dead or zombie
processes cleared out.

11. What is redirection and how is it used?


Level: Intermediate
Expected answer: redirection is the process by which input or output to or from a
process is redirected to another process. This can be done using the pipe symbol "|",
the greater than symbol ">" or the "tee" command. This is one of the strengths of UNIX
allowing the output from one command to be redirected directly into the input of another
command.

12. How can you find dead processes?


Level: Intermediate
Expected answer: ps -ef|grep zombie -- or -- who -d depending on the system.

13. How can you find all the processes on your system?
Level: Low
Expected answer: Use the ps command

14. How can you find your id on a system?


Level: Low
Expected answer: Use the "who am i" command.

15. What is the finger command?


Level: Low
Expected answer: The finger command uses data in the passwd file to give information
on system users.

16. What is the easiest method to create a file on UNIX?


Level: Low
Expected answer: Use the touch command

17. What does >> do?


Level: Intermediate
Expected answer: The ">>" redirection symbol appends the output from the command
specified into the file specified. The file must already have been created.

18. If you aren’t sure what command does a particular UNIX function what is the best way
to determine the command?
Expected answer: The UNIX man -k <value> command will search the man pages for
the value specified. Review the results from the command to find the command of
interest.
Oracle Troubleshooting

1. How can you determine if an Oracle instance is up from the operating system level?
Level: Low
Expected answer: 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.

2. Users from the PC clients are getting messages indicating :


Level: Low
ORA-06114: (Cnct err, can't get err txt. See Servr Msgs & Codes Manual)
What could the problem be?
Expected answer: The instance name is probably incorrect in their connection string.

3. Users from the PC clients are getting the following error stack:
Level: Low
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?
Expected answer: The Oracle instance is shutdown that they are trying to access,
restart the instance.

4. How can you determine if the SQLNET process is running for SQLNET V1? How about
V2?
Level: Low
Expected answer: 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".

5. What file will give you Oracle instance status information? Where is it located?
Level: Low
Expected answer: The alert<SID>.ora log. It is located in the directory specified by the
background_dump_dest parameter in the v$parameter table.

6. Users aren’t being allowed on the system. The following message is received:
Level: Intermediate
ORA-00257 archiver is stuck. Connect internal only, until freed
What is the problem?
Expected answer: The archive destination is probably full, backup the archive logs and
remove them and the archiver will re-start.

7. Where would you look to find out if a redo log was corrupted assuming you are using
Oracle mirrored redo logs?
Level: Intermediate
Expected answer: There is no message that comes to the SQLDBA or SRVMGR
programs during startup in this situation, you must check the alert<SID>.log file for this
information.

8. You attempt to add a datafile and get:


Level: Intermediate
ORA-01118: cannot add anymore datafiles: limit of 40 exceeded
What is the problem and how can you fix it?
Expected answer: 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.
9. 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?
Level: High
Expected answer: 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.

10. Your users get the following error:


Level: Intermediate
ORA-00055 maximum number of DML locks exceeded
What is the problem and how do you fix it?
Expected answer: 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.

11. 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?
Level: High
Expected answer: 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.

Oracle Concepts and Architecture Database Structures.

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

2.What are the components of Logical database structure of ORACLE database?

Table spaces and the Database's Schema Objects.

3. What is a Table space?

A database is divided into Logical Storage Unit called table spaces. A table space is used to
grouped related logical structures together.

4. What is SYSTEM table space and when is it Created?

Every ORACLE database contains a table space named SYSTEM, which is automatically
created when the database is created. The SYSTEM table
Space always contains the data dictionary tables for the entire database.

5. Explain the relationship among Database, Table space and Data file?

Each databases logically divided into one or more table


Spaces one or more data files are explicitly created for each table space.

6. What is schema?

A schema is collection of database objects of a User.

7. 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.
8. Can objects of the same Schema reside in different table spaces?
Yes.

9. Can a Table space hold objects from different Schemes?


Yes.

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

11. 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.)

12. Do View contain Data?

Views do not contain or store data.

13. Can a View based on another View?

Yes.

14. 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.
Store complex queries.
Present the data in a different perspective from that of the base table.

15. What is a Sequence?

A sequence generates a serial list of unique numbers for numerical columns of a database's
tables.

16. What is a Synonym?

A synonym is an alias for a table, view, sequence or program unit.

17. What are the types of Synonyms?

There are two types of Synonyms Private and Public.

18. What is a Private Synonyms?

A Private Synonyms can be accessed only by the owner.

19. What is a Public Synonyms?

Any user on the database can access a Public synonym.


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

21. 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 ones or more columns of a table.

22. How is Indexes Update?

Indexes are automatically maintained and used by ORACLE. Changes to table data are
automatically incorporated into all relevant indexes.

23. What are Clusters?

Clusters are groups of one or more tables physically stores together to share common
columns and are often used together.

24. What is cluster Key?

The related column of the tables in a cluster is called the Cluster Key.

25. What is Index Cluster?

A Cluster with an index on the Cluster Key.

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

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

28. What is Database Link?

A database link is a named object that describes a "path" from one database to another.

29. What are the types of Database Links?

Private Database Link, Public Database Link & Network Database Link.

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

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

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

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

34. 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 can’t be changed latter.

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

36. What is an Extent?

An Extent is a specific number of contiguous data blocks, obtained in a single allocation,


and used to store a specific type of information.

37. What is a Segment?

A segment is a set of extents allocated for a certain logical structure.

38. What are the different types of Segments?

Data Segment, Index Segment, Rollback Segment and Temporary Segment.

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

40. What is an Index Segment?


Each Index has an Index segment that stores all of its data.

41. What is Rollback Segment?

A Database contains one or more Rollback Segments to temporarily store "undo"


information.

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

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

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

45. 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 table space.

46. What is a Redo Log?

The set of Redo Log files for a database is collectively known as the database's redo log.

47. What is the function of Redo Log?

The Primary function of the redo log is to record all changes made to data.

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

49. 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.
50. 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.

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

52. What is an Integrity Constrains?

An integrity constraint is a declarative way to define a business rule for a column of a table.

53. Can an Integrity Constraint be enforced on a table if some existing table data does not
satisfy the constraint?
No.

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

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

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

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

DELETE Cascade - When a referenced row is deleted all associated dependent rows are
deleted.
58. What is self-referential integrity constraint?
If a foreign key reference a parent key of the same table is called self-referential integrity
constraint.

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

60. What is the maximum number of CHECK constraints that can be defined on a column?
No Limit.

SYSTEM ARCHITECTURE:

61. What constitute an ORACLE Instance?


SGA and ORACLE background processes constitute an ORACLE instance. (or) Combination of
memory structure and background process.

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

63. What are the components of SGA?


Database buffers, Redo Log Buffer the Shared Pool and Cursors.

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

65. What do Redo Log Buffers contain?


Redo Log Buffer stores redo entries a log of changes made to the database.

66. What is Shared Pool?


Shared Pool is a portion of the SGA that contains shared memory constructs such as shared
SQL areas.

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

68. What is Cursor?


A Cursor is a handle (a name or pointer) for the memory associated with a specific
statement.

69. What is PGA?


Program Global Area (PGA) is a memory buffer that contains data and control information
for a server process.

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

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

72. What are the two types of Server Configurations?


Dedicated Server Configuration and Multi-threaded Server Configuration.

73. What is Dedicated Server Configuration?


In a Dedicated Server Configuration a Server Process handles requests for a Single User
Process.

74. What is a Multi-threaded Server Configuration?


In a Multi-threaded Server Configuration many user processes share a group of server
process.

75. What is a Parallel Server option in ORACLE?


A configuration for loosely coupled systems where multiple instance share a single physical
database is called Parallel Server.

76. 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, and
LCKn - Lock
Snnn - Server.

77. What Does DBWR do?


Database writer writes modified blocks from the database buffer cache to the data files.

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

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

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

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

82. 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 table space or file is brought back on-line SMON
also coalesces free extents within the database to make free space contiguous and easier to
allocate.

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

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

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

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

87. How many Dispatcher Processes are created?


Atleast one Dispatcher process is created for every communication protocol in use.

88. What is the function of Lock (LCKn) Process?


Lock (LCKn) is used for inter-instance locking when the ORACLE Parallel Server option is
used.

89. What is the maximum number of Lock Processes used?


Though a single LCK process is sufficient for most Parallel Server systems
Up to Ten Locks (LCK0,....LCK9) are used for inter-instance locking.

DATA ACCESS

90. Define Transaction?


A Transaction is a logical unit of work that comprises one or more SQL statements executed
by a single user.

91. When does a Transaction end?


When it is committed or Roll backed.

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

93. What does ROLLBACK do?


ROLLBACK retracts any of the changes resulting from the SQL statements in the
transaction.

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

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

96. What is the function of Optimizer?

The goal of the optimizer is to choose the most efficient way to execute a SQL statement.

97. What is Execution Plan?


The combination of the steps the optimizer chooses to execute a statement is called an
execution plan.

98. What are the different approaches used by Optimizer in choosing an execution plan?
Rule-based and Cost-based.

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

100. What are the values that can be specified for OPTIMIZER MODE Parameter?
COST and RULE.

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

102. 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.
103. What are the values that can be specified for OPTIMIZER_GOAL parameter of the
ALTER SESSION Command?
CHOOSE, ALL_ROWS, FIRST_ROWS and RULE.

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

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

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

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

108. What is RULE-based approach to optimization?


Choosing an executing plan based on the access paths available and the ranks of these
access paths.

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

PROGRAMMATIC CONSTRUCTS

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

111. 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.
112. What is difference between Procedures and Functions?
A Function returns a value to the caller where as a Procedure does not.

113. 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.
114. 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)
115. 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.

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

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

DATABASE SECURITY

118. What are Roles?


Roles are named groups of related privileges that are granted to users or other roles.

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

120. How to prevent unauthorized use of privileges granted to a Role?


By creating a Role with a password.
121. What is default table space?
The Table space to contain schema objects created without specifying a table space name.

122. What is Table space Quota?


The collective amount of disk space available to the objects in a schema on a particular
table space.

123. What is a profile?


Each database user is assigned a Profile that specifies limitations on various system
resources available to the user.

124. 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 amount 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.

125. What is Auditing?


Monitoring of user access to aid in the investigation of database use.

126. What are the different Levels of Auditing?


Statement Auditing, Privilege Auditing and Object Auditing.

127. What is Statement Auditing?


Statement auditing is the auditing of the powerful system privileges without regard to
specifically named objects.

128. What is Privilege Auditing?


Privilege auditing is the auditing of the use of powerful system privileges without regard to
specifically named objects.

129. What is Object Auditing?


Object auditing is the auditing of accesses to specific schema objects without regard to user.

DISTRIBUTED PROCESSING AND DISTRIBUTED DATABASES

130. What is distributed database?


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.

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

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

133. What is the mechanism provided by ORACLE for table replication?


Snapshots and SNAPSHOT LOGs

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

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

136. What is a SQL * NET?


SQL *NET is Oracle’s mechanism for interfacing with the communication protocols used by
the networks that facilitate distributed processing and distributed databases. It is used in
Clint-Server and Server-Server communications.

DATABASE OPERATION, BACKUP AND RECOVERY

137. What are the steps involved in Database Startup?


Start an instance, Mount the Database and Open the Database.

138. What are the steps involved in Database Shutdown?


Close the Database, Dismount the Database and Shutdown the Instance.

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

140. What are the different modes of mounting a Database with the Parallel Server?

Exclusive Mode If the first instance that mounts a database does so in exclusive mode, only
that Instance can mount the database.

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.

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

142. Can Full Backup be performed when the database is open?


No.

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

144.WhatisOn-lineRedoLog?
The On-line Redo Log is a set of tow 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.

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

146. What is Archived Redo Log?


Archived Redo Log consists of Redo Log files that have archived before being reused.

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

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

149. What are the steps involved in Instance Recovery?


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

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.

Resolving any pending distributed transactions undergoing a two-phase commit at the time
of the instance failure.

Data Base Administration

Introduction to DBA

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

2. What is Parallel Server?

Multiple instances accessing the same database (Only In Multi-CPU environments)

3. What is a Schema?

The set of objects owned by user account is called the schema.

4. What is an Index? How it is implemented in Oracle Database?


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)

5. What are clusters?

Group of tables physically stored together because they share common columns and are
often used together is called Cluster.

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

7. What is the basic element 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 table spaces
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

8. 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 rowlock
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 this processes being killed externally.
MEMORY MANAGEMENT

9. What is SGA? How it is different from Ver 6.0 and Ver 7.0?

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.

The structure is Database buffers, Dictionary cache, Redo Log Buffer and Shared SQL pool
(ver 7.0 only) area.

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

11. What is mean by Program Global Area (PGA)?

It is area in memory that is used by a Single Oracle User Process.

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

13. 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 1 then increase the SHARED_POOL_SIZE.

LOGICAL & PHYSICAL ARCHITECTURE OF DATABASE.


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

15. What is dictionary cache?

Dictionary cache is information about the database objects stored in a data dictionary table.

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

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

18. How will you swap objects into a different table space for an existing database?

Export the user

Perform import using the command imp system/manager file=export.dmp


indexfile=newrite.sql. This will create all definitions into newfile.sql.

Drop necessary objects.

Run the script newfile.sql after altering the tablespaces.

Import from the backup for the necessary objects.

19. List the Optional Flexible Architecture (OFA) of Oracle database? Or how can we
organize the table spaces 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 table space
TEMP_USER - Temporary table space for users.
USERS - User table space.
20. How will you force database to use particular rollback segment?

SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

21. What is meant by free extent?

A free extent is a collection of continuous free blocks in table space. When a segment is
dropped its extents are reallocated and are marked as free.

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

23.Which parameter in Storage clause will reduce no. of rows per block?

PCTFREE parameter
Row size also reduces no of rows per block.

24. 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.,

25. How does Space allocation table 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)

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

27. What is the OPTIMAL parameter?

It is used to set the optimal length of a rollback segment.

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

29. How will you create multiple rollback segments in a database?

Create a database that implicitly creates a SYSTEM Rollback Segment in a SYSTEM table
space.

Create a Second Rollback Segment name R0 in the SYSTEM table space.

Make new rollback segment available (After shutdown, modify init.ora file and Start
database)

Create other tablespaces (RBS) for rollback segments.

Deactivate Rollback Segment R0 and activate the newly created rollback segments.

30. 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)

31. Why query fails sometimes?

Rollback segment dynamically extent to handle larger transactions entry loads.


A single transaction may wipeout all available free space in the Rollback Segment
Tablespace. This prevents other user using Rollback segments.

32. How will you monitor the space allocation?

By quering DBA_SEGMENT table/view.

33. 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 corrupted.
PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed
database.

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

Transaction Begins.

An entry is made in the RES header for new transactions entry

Transaction acquires blocks in an extent of RBS

The entry attempts to wrap into second extent. None is available, so that the RBS must
extent.

The RBS checks to see if it is part of its OPTIMAL size.


RBS chooses its oldest inactive segment.
Oldest inactive segment is eliminated.
RBS extents
The Data dictionary table for space management is updated.
Transaction Completes.

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

36. How will you estimate the space required by a non-clustered table?

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.
After arriving the calculation, add 10 % additional space to calculate the initial extent size
for a working table.

37. It is possible to use raw devices as data files and what are the advantages over file.
System files?

Yes.

The advantages over file system files.

I/O will be improved because Oracle is bye-passing the kernnel which writing into disk.
Disk Corruption will be very less.

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

39. How to implement the multiple control files for an existing database?

Shutdown the database


Copy one of the existing control files to new location
Edit Config ora file by adding new control file.name
Restart the database.

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

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

42. What is use of Rollback Segments In Database?

They allow the database to maintain read consistency between multiple transactions.

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

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

45. When will be a segment released?

When Segment is dropped.


When Shrink (RBS only)
When truncated (TRUNCATE used with drop storage option)

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

47. List the factors that can affect the accuracy of the estimations?

The space used transaction entries and deleted records do not become free immediately
after completion due to delayed cleanout.

Trailing nulls and length bytes are not stored.

Inserts of, updates to and deletes of rows as well as columns larger than a single data
block, can cause fragmentation a chained row pieces.

DATABASE SECURITY & ADMINISTRATION

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

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

50. What are the dictionary tables used to monitor a database spaces ?

DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.
51. What are the responsibilities of a Database Administrator ?

Installing and upgrading the Oracle Server and application tools.


Allocating system storage and planning future storage requirements for the database
system.
Managing primary database structures (tablespaces)
Managing primary objects (table,views,indexes)
Enrolling users and maintaining system security.
Ensuring compliance with Oralce license agreement
Controlling and monitoring user access to the database.
Monitoring and optimising the performance of the database.
Planning for backup and recovery of database information.
Maintain archived data on tape
Backing up and restoring the database.
Contacting Oracle Corporation for technical support.

52. 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.
54. What are the database administrators utilities avaliable ?

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.

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

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

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

58. 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 databse
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.

59. How can you enable automatic archiving ?

Shut the database


Backup the database
Modify/Include LOG_ARCHIVE_START_TRUE in init.ora file.
Start up the databse.

60. How can we specify the Archived log file name format and destination ?

By setting the following values in init.ora file.

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.

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

MANAGING DISTRIBUTED DATABASES.

62. How can we reduce the network traffic ?


- Replictaion of data in distributed environment.
- Using snapshots to replicate data.
- Using remote procedure calls.

63. What is snapshots ?

Snapshot is an object used to dynamically replicate data between distribute database at


specified time intervals. In ver 7.0 they are read only.

64. What are the various type of snapshots ?

Simple and Complex.

65. Differentiate simple and complex, snapshots ?


- A simple snapshot is based on a query that does not contains GROUP BY clauses,
CONNECT BY clauses, JOINs, sub-query or snashot of operations.
- A complex snapshots contain atleast any one of the above.

66. What dynamic data replication ?

Updating or Inserting records in remote database through database triggers. It may fail if
remote database is having any problem.

67. How can you Enforce Refrencial Integrity in snapshots ?

Time the references to occur when master tables are not in use.
Peform the reference the manually immdiately locking the master tables. We can join
tables in snopshots by creating a complex snapshots that will based on the master tables.

68. What are the options available to refresh snapshots ?

COMPLETE - Tables are completly regenerated using the snapshot's 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.

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

70. When will the data in the snapshot log be used ?

We must be able to create a after row trigger on table (i.e., it should be not be already
available )

After giving table privileges.

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.

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

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

MANAGING BACKUP & RECOVERY

73. What are the different methods of backing up oracle database ?

- Logical Backups
- Cold Backups
- Hot Backups (Archive log)

74. What is a logical backup ?

Logical backup involves reading a set of databse records and writing them into a file.
Export utility is used for taking backup and Import utility is used to recover from backup.

75. 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 file (Optional)

76. What are the different kind 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.
77. 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.

78. What is the use of FILE option in EXP command ?

To give the export file name.

79. What is the use of COMPRESS option in EXP command ?

Flag to indicate whether export should compress fragmented segments into single
extents.

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

81. What is the use of INDEXES option in EXP command ?

A flag to indicate whether indexes on tables will be exported.

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

83. What is the use of CONSTRAINTS option in EXP command ?

A flag to indicate whether constraints on table need to be exported.

84. What is the use of FULL option in EXP command ?

A flag to indicate whether full databse export should be performed.

85. What is the use of OWNER option in EXP command ?


List of table accounts should be exported.

86. What is the use of TABLES option in EXP command ?

List of tables should be exported.

87. What is the use of RECORD LENGTH option in EXP command ?

Record length in bytes.

88. What is the use of INCTYPE option in EXP command ?

Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL.

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

90. What is the use of PARFILE option in EXP command ?

Name of the parameter file to be passed for export.

91. What is the use of PARFILE option in EXP command ?

Name of the parameter file to be passed for export.

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

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

94. What is use of LOG (Ver 7) option in EXP command ?

The name of the file which log of the export will be written.

95.What is the use of FILE option in IMP command ?

The name of the file from which import should be performed.

96. What is the use of SHOW option in IMP command ?

A flag to indicate whether file content should be displayed or not.

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

98. What is the use of GRANT option in IMP command ?

A flag to indicate whether grants on database objects will be imported.

99. What is the use of INDEXES option in IMP command ?

A flag to indicate whether import should import index on tables or not.

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

SQL PLUS STATEMENTS


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

2. What is a transaction?

Transaction is logical unit between two commits and commit and rollback.

3. What is difference between TRUNCATE & DELETE?

TRUNCATE commits after deleting entire table i.e., can’t be rolled back. Database triggers
do not fire on TRUNCATE

DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.

4. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables.

Self Join - Joining the table with itself.


Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrive rows that do not
have corresponding join value in the other table.

5. What is the Subquery?

Subquery is a query whose return values are used in filtering conditions of the main query.

6. What is correlated sub-query?

Correlated sub_query is a sub_query, which has reference to the main query.

7. Explain Connect by Prior?

Retrives rows in hierarchical order.


e.g. select empno, ename from emp where.

8. Difference between SUBSTR and INSTR?

INSTR (String1, String 2(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.

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

10. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18character long, block no,
row number are the components of ROWID.

11. What is the fastest way of accessing a row in a table?

Using ROWID.

CONSTRAINTS
----------------------
12. What is an Integrity Constraint?

Integrity constraint is a rule that restricts values to a column in a table.


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

14. What are the usages 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.

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

16. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

17. 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 it is 255 and 2000 for VARCHAR2.

18. 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 columns is allowed. It is not possible to use LONG column in WHERE or
ORDER BY clause.

19. What are the pre requisites?


I. To modify data type of a column?
ii. To add a column with NOT NULL constraint?

To modify the datatype of a column the column must be empty.


To add a column with NOT NULL constrain, the table must be empty.

20. Where the integrity constrints are stored in Data Dictionary?

The integrity constraints are stored in USER_CONSTRAINTS.

21. How will you a activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE


constraint/DISABLE constraint.

22. If an 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.

23. What is a database link?

Database Link is a named path through which a remote database can be accessed.

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

25. What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continues to generate values after reaching either
maximum or minimum value. After pan 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.

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

27. Can a view be updated/inserted/deleted? If Yes under what conditions?


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.

28.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 which are base tables of a view will the changes be
reference on the view.

FORMS 3.0 BASIC

1.What is an SQL *FORMS?

SQL *forms is 4GL tool for developing and executing; Oracle based interactive application.

2. What is the maximum size of a form?

255 character width and 255 characters Length.


3. Name the two files that are created when you generate the form give the file extension?

INP (Source File)


FRM (Executable File)

4. How do you control the constraints in forms?

Select the use constraint property is ON Block definition screen.

BLOCK

5. Committed block sometimes refer to a BASE TABLE? True or False.

False.

6. Can we create two blocks with the same name in form 3.0?

No.

7. While specifying master/detail relationship between two blocks specifying the join
condition is a must? True or False.

True.

8. What is a Trigger?

A piece of logic that is executed at or triggered by a SQL *forms event.

9. What are the types of TRIGGERS?

1. Navigational Triggers.
2. Transaction Triggers.

10. What are the different types of key triggers?


Function Key
Key-function
Key-others
Key-startup

11. What is the difference between a Function Key Trigger and Key Function Trigger?

Function key triggers are associated with individual SQL*FORMS function keys
You can attach Key function triggers to 10 keys or key sequences that normally do not
perform any SQL * FORMS operations. These keys referred as key F0 through key F9.

12. What does an on-clear-block Trigger fire?

It fires just before SQL * forms the current block.

13. How do you trap the error in forms 3.0?

Using On-Message or On-Error triggers.

14. State the order in which these triggers are executed?

POST-FIELD, ON-VALIDATE-FIELD, POST-CHANGE and KEY-NEXTFLD.


KEY-NEXTFLD, POST-CHANGE, ON-VALIDATE-FIELD, POST-FIELD.

15. What is the usage of an ON-INSERT,ON-DELETE and ON-UPDATE TRIGGERS ?

These triggers are executes when inserting, deleting and updating operations are
performed and can be used to change the default function of insert, delete or update
respectively.

For E.g., instead of inserting a row in a table an existing row can be updated in the same
table.

16. When will ON-VALIDATE-FIELD trigger executed?

It fires when a value in a field has been changed and the field status is changed or new and
the key has been pressed. If the field status is valid then any further change to the value
in the field will not fire the on-validate-field trigger.

17. A query fetched 10 records how many times do a PRE-QUERY Trigger and POST-QUERY
Trigger will get executed?

PRE-QUERY fires once.


POST-QUERY fires 10 times.

18. What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGE


trigger?

When you changes the Existing value to null, the On-validate field trigger will fire post
change trigger will not fire. At the time of execute-query post-change trigger will fire, on-
validate field trigger will not fire.

19. What is the difference between an ON-VALIDATE-FIELD trigger and a trigger?


On-validate-field trigger fires, when the field Validation status New or changed.
Post-field-trigger whenever the control leaving form the field, it will fire.

20. What is the difference between a POST-FIELD trigger and a POST-CHANGE trigger?

Post-field trigger fires whenever the control leaving from the filed.
Post-change trigger fires at the time of execute-query procedure invoked or filed validation
status changed.

21. When is PRE-QUERY trigger executed?

When Execute-query or count-query Package procedures are invoked.


22. Give the sequence in which triggers fired during insert operations, when the following 3
triggers are defined at the same block level?
a. ON-INSERT b. POST-INSERT c. PRE-INSERT

PRE-INSERT, ON-INSERT & POST-INSERT.

23. Can we use GO-BLOCK package in a pre-field trigger ?

No.

24. Is a Key startup trigger fires as result of a operator pressing a key explicitly?

No.

25. How can you execute the user defined triggers in forms 3.0?

Execute_Trigger (trigger-name)

26. When does an on-lock trigger fire?

It will fires whenever SQL * Forms would normally attempt to lock a row.

26. What is Post-Block is a


. a. Navigational Trigger.
b. Key trigger
c. Transaction Trigger.

Navigational Trigger.

27. What is the difference between keystartup and pre-form ?

Key-startup trigger fires after successful navigation into a form.

Pre-form trigger fires before enter into the form.

28. What is the difference between keystartup and pre-form ?

Key-startup triigger fires after successful navigation into a form.


Pre-form trigger fires before enter into the form.
PACKAGE PROCEDURE & FUNCTION
-----------------------------------------
29. What is a Package Procedure ?

A Package proecdure is built in PL/SQL procedure.

30. What are the different types of Package Procedure ?

1. Restricted package procedure.


2. Unrestricted package proecdure.

31. What is the difference between restricted and unrestricted package procedure ?
Restricted package procedure that affects the basic basic functions of SQL * Forms. It
cannot used in all triggers execpt key triggers.

Unrestricted package procedure that does not interfere with the basic functions of SQL *
Forms it can be used in any triggers.

32. Classify the restricted and unrestricted procedure from the following.
a. Call
b. User-Exit
c. Call-Query
d. Up
e. Execute-Query
f. Message
g. Exit-From
h. Post
i. Break

a. Call - unrestricted
b. User Exit - Unrestricted
c. Call_query - Unrestricted
d. Up - Restricted
e. Execute Query - Restricted
f. Message - Restricted
g. Exit_form - Restricted
h. Post - Restricted
i. Break - Unrestricted.

33. Can we use a restricted package procedure in ON-VALIDATE-FIELD Trigger ?

No.

34. What SYNCHRONIZE procedure does ?

It synchoronizes the terminal screen with the internal state of the form.

35. What are the unrestricted procedures used to change the popup screen position
during run time ?

Anchor-view
Resize -View
Move-View.
36. What Enter package procedure does ?

Enter Validate-data in the current validation unit.

37. What ERASE package procedure does ?

Erase removes an indicated global variable.

38. What is the difference between NAME_IN and COPY ?

Copy is package procedure and writes values into a field.


Name in is a package function and returns the contents of the variable to which you apply.

38. Identify package function from the following ?


1. Error-Code
2. Break
3. Call
4. Error-text
5. Form-failure
6. Form-fatal
7. Execute-query
8. Anchor_View
9. Message_code

1. Error_Code
2. Error_Text
3. Form_Failure
4. Form_Fatal
5. Message_Code

40. How does the command POST differs from COMMIT ?

Post writes data in the form to the database but does not perform database commit
Commit permenently writes data in the form to the database.

41. What the PAUSE package procedure does ?

Pause suspends processing until the operator presses a function key

42. What package procedure is used for calling another form ?

Call (E.g. Call(formname)

43. What package procedure used for invoke sql *plus from sql *forms ?

Host (E.g. Host (sqlplus))

44. Error_Code is a package proecdure ?


a. True b. false

False.
45. EXIT_FORM is a restricted package procedure ?
a. True b. False

True.

46. When the form is running in DEBUG mode, If you want to examine the values of
global variables and other form variables, What package procedure command you would use
in your trigger text ?

Break.
SYSTEM VARIABLES

47. List the system variables related in Block and Field?

1. System.block_status
2. System.current_block
3. System.current_field
4. System.current_value
5. System.cursor_block
6. System.cursor_field
7. System.field_status.

48. What is the difference between system.current_field and


system.cursor_field ?

1. System.current_field gives name of the field.


2. System.cursor_field gives name of the field with block name.

49. The value recorded in system.last_record variable is of type


a. Number
b. Boolean
c. Character.
b. Boolean.

User Exits :

50. What is an User Exits ?

A user exit is a subroutine which are written in programming languages using pro*C pro
*Cobol , etc., that link into the SQL * forms executable.

51. What are the type of User Exits ?

ORACLE Precompliers user exits


OCI (ORACLE Call Interface)
Non-ORACEL user exits.

Page :

52. What do you mean by a page ?

Pages are collection of display information, such as constant text and graphics.
53. How many pages you can in a single form ?

Unlimited.

54. Two popup pages can appear on the screen at a time ?


a. True b. False

a. True.
55.What is the significance of PAGE 0 in forms 3.0 ?
Hide the fields for internal calculation.

56. Deleting a page removes information about all the fields in that page ?
a. True. b. False

a. True.

Popup Window :

57. What do you mean by a pop-up window ?

Pop-up windows are screen areas that overlay all or a portion of the
display screen when a form is running.

58. What are the types of Pop-up window ?

the pop-up field editor


pop-up list of values
pop-up pages.

Alert :

59. What is an Alert ?

An alert is window that appears in the middle of the screen overlaying a portion of the
current display.

FORMS 4.0

01. Give the Types of modules in a form?

Form
Menu
Library

02. Write the Abbreviation for the following File Extension


1. FMB 2. MMB 3. PLL

FMB ----- Form Module Binary.


MMB ----- Menu Module Binary.
PLL ------ PL/SQL Library Module Binary.
03. What are the design facilities available in forms 4.0?

Default Block facility.


Layout Editor.
Menu Editor.
Object Lists.
Property Sheets.
PL/SQL Editor.
Tables Columns Browser.
Built-ins Browser.

04. What is a Layout Editor?

The Layout Editor is a graphical design facility for creating and arranging items and
boilerplate text and graphics objects in your application's interface.

05. BLOCK

05. What do you mean by a block in forms4.0?

Block is a single mechanism for grouping related items into a functional unit for
storing,displaying and manipulating records.

06. Explain types of Block in forms4.0?

Base table Blocks.


Control Blocks.
1. A base table block is one that is associated with a specific database table
or view.
2. A control block is a block that is not associated with a database table.

ITEMS
07. List the Types of Items?

Text item.
Chart item.
Check box.
Display item.
Image item.
List item.
Radio Group.
User Area item.

08. What is a Navigable item?

A navigable item is one that operators can navigate to with the keyboard during default
navigation, or that Oracle forms can navigate to by executing a navigational
built-in procedure.

09. Can you change the color of the push button in design time?
No.

10. What is a Check Box?

A Check Box is a two state control that indicates whether a certain condition or value
is on or off, true or false. The display state of a check box is always either "checked"
or "unchecked".

11. What are the triggers associated with a check box?

Only When-checkbox-activated Trigger associated with a Check box.

PL/SQL

Basiscs of PL/SQL

1. What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural
programming language constructs such as iteration, conditional branching.

2. What is the basic structure of PL/SQL ?

PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks
can be used in PL/SQL.

3. What are the components of a PL/SQL block ?

A set of related declarations and procedural statements is called block.

4. What are the components of a PL/SQL Block ?

Declarative part, Executable part and Execption part.

Datatypes PL/SQL

5. What are the datatypes a available in PL/SQL ?

Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.

6. What are % TYPE and % ROWTYPE ? What are the advantages of using these over
datatypes?

% TYPE provides the data type of a variable or a database column to that variable.

% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.

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

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

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.

8. What is PL/SQL table ?

Objects of type TABLE are called "PL/SQL tables", which are modelled as (but not the
same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column
and a primary key.

Cursors
9. What is a cursor ? Why Cursor is required ?

Cursor is a named private SQL area from where information can be accessed. Cursors are
required to process rows individually for queries returning multiple rows.

10. Explain the two type of Cursors ?

There are two types of cursors, Implict Cursor and Explicit Cursor.
PL/SQL uses Implict Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.

11. What are the PL/SQL Statements used in cursor processing ?

DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or
Record types, CLOSE cursor name.

12. What are the cursor attributes used in PL/SQL ?

%ISOPEN - to check whether cursor is open or not


% ROWCOUNT - number of rows featched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are featched.
% NOT FOUND - to check whether cursor has featched any row. True if no rows are
featched.
These attributes are proceded with SQL for Implict Cursors and with Cursor name for
Explict Cursors.

13. What is a cursor for loop ?

Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of
values from active set into fields in the record and closes
when all the records have been processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;

14. What will happen after commit statement ?


Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;-----
commit;
end loop;
end;

The cursor having query as SELECT .... FOR UPDATE gets closed after
COMMIT/ROLLBACK.

The cursor having query as SELECT.... does not get closed even after
COMMIT/ROLLBACK.

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

Database Triggers

16. What is a database trigger ? Name some usages of database trigger ?

Database trigger is stored PL/SQL program unit associated with a specific database table.
Usages are Audit data modificateions, Log events transparently, Enforce complex
business rules Derive column values automatically, Implement complex security
authorizations. Maintain replicate tables.

17. How many types of database triggers can be specified on a table ? What are they ?

Insert Update Delete

Before Row o.k. o.k. o.k.

After Row o.k. o.k. o.k.

Before Statement o.k. o.k. o.k.

After Statement o.k. o.k. o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the
statement.
If WHEN clause is specified, the trigger fires according to the retruned boolean value.

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

19. What are two virtual tables 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.

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

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

Exception :

22. What is an Exception ? What are types of Exception ?

Exception is the error handling part of PL/SQL block. The types are Predefined and
user_defined. Some of Predefined execptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.

23. What is Pragma EXECPTION_INIT ? Explain the usage ?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle
error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

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

25. What are the return values of functions SQLCODE and SQLERRM ?

SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.

26. Where the Pre_defined_exceptions are stored ?

In the standard package.

Procedures, Functions & Packages ;

27. What is a stored procedure ?

A stored procedure is a sequence of statements that perform specific function.

28. What is difference between a PROCEDURE & FUNCTION ?

A FUNCTION is alway returns a value using the return statement.


A PROCEDURE may return one or more values through parameters or may not
return at all.

29. What are advantages fo Stored Procedures /

Extensibility,Modularity, Reusability, Maintainability and one time compilation.

30. What are the modes of parameters that can be passed to a procedure ?

IN,OUT,IN-OUT parameters.

31. What are the two parts of a procedure ?

Procedure Specification and Procedure Body.

32. Give the structure of the procedure ?

PROCEDURE name (parameter list.....)


is
local variable declarations

BEGIN
Executable statements.
Exception.
exception handlers

end;
33. Give the structure of the function ?

FUNCTION name (argument list .....) Return datatype is


local variable declarations
Begin
executable statements
Exception
execution handlers
End;

34. Explain how procedures and functions are called in a PL/SQL block ?

Function is called as part of an expression.


sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');

35. What is Overloading of procedures ?

The Same procedure name is repeated with parameters of different datatypes and
parameters in different positions, varying number of parameters is called overloading of
procedures.

e.g. DBMS_OUTPUT put_line

36. What is a package ? What are the advantages of packages ?

Package is a database object that groups logically related procedures.


The advantages of packages are Modularity, Easier Applicaton Design, Information.
Hiding,. reusability and Better Performance.

37.What are two parts of package ?

The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.

Package Specification contains declarations that are global to the packages and local to the
schema.
Package Body contains actual procedures and local declaration of the procedures and
cursor declarations.

38. What is difference between a Cursor declared in a procedure and Cursor declared in a
package specification ?

A cursor declared in a package specification is global and can be accessed by other


procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other
procedures.

39. How packaged procedures and functions are called from the following?
a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS

a. PACKAGE NAME.PROCEDURE NAME (parameters);


variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.
BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any
out/in-out parameters. A function can not be called.

40. Name the tables where characteristics of Package, procedure and functions are
stored ?

User_objects, User_Source and User_error.

FORMS4.0
12. what is a display item?

Display items are similar to text items but store only fetched or assigned values. Operators
cannot navigate to a display item or edit the value it contains.

13. What is a list item?

It is a list of text elements.

14. What are the display styles of list items?

Poplist, No text Item displayed in the list item.


Tlist, No element in the list is highlighted.

15. What is a radio Group?

Radio groups display a fixed no of options that are mutually Exclusive .


User can select one out of n number of options.

16. How many maximum number of radio buttons can you assign to a radio group?

Unlimited no of radio buttons can be assigned to a radio group

17. can you change the default value of the radio button group at run time?

No.

18.What triggers are associated with the radio group?

Only when-radio-changed trigger associated with radio group

Visual Attributes.
19. What is a visual attribute?

Visual Attributes are the font, color and pattern characteristics of objects that operators
see and intract with in our application.

20. What are the types of visual attribute settings?

Custom Visual attributes


Default visual attributes
Named Visual attributes.

Window

21. What is a window?

A window, byitself , can be thought of as an empty frame. The frame provides a way
to intract with the window, including the ability to scroll, move, and resize the window.
The content of the window ie. what is displayed inside the frame is determined by the
canvas View or canvas-views displayed in the window at run-time.

22. What are the differrent types of windows?

Root window, secondary window.

23. Can a root window be made modal?

No.

24. List the buil-in routine for controlling window during run-time?

Find_window,
get_window_property,
hide_window,
move_window,
resize_window,
set_window_property,
show_View

25. List the windows event triggers available in Forms 4.0?

When-window-activated, when-window-closed, when-window-deactivated,


when-window-resized

26. What built-in is used for changing the properties of the window dynamically?

Set_window_property

Canvas-View

27. What is a canvas-view?


A canvas-view is the background object on which you layout the interface items (text-
items, check boxes, radio groups, and so on.) and boilerplate objects that operators see
and interact with as they run your form. At run-time, operators can see only those items
that have been assiged to a specific canvas. Each canvas, in term, must be displayed in
a specfic window.

28. Give the equivalent term in forms 4.0 for the following.
Page, Page 0?

Page - Canvas-View
Page 0 - Canvas-view null.

29. What are the types of canvas-views?

Content View, Stacked View.

30. What is the content view and stacked view?

A content view is the "Base" view that occupies the entire content pane of the window in
which it is displayed.
A stacked view differs from a content canvas view in that it is not the base view for the
window to which it is assigned

31. List the built-in routines for the controlling canvas views during run-time?

Find_canvas
Get-Canvas_property
Get_view_property
Hide_View
Replace_content_view
Scroll_view
Set_canvas_property
Set_view_property
Show_view

Alert

32. What is an Alert?

An alert is a modal window that displays a message notifies the operator of some
application condition

33. What are the display styles of an alert?

Stop, Caution, note

34. Can you attach an alert to a field?

No

35. What built-in is used for showing the alert during run-time?

Show_alert.
36. Can you change the alert messages at run-time?
If yes, give the name of th built-in to chage the alert messages at run-time.

Yes. Set_alert_property.

37. What is the built-in function used for finding the alert?

Find_alert

Editors

38. List the editors availables in forms 4.0?

Default editor
User_defined editors
system editors.

39. What buil-in routines are used to display editor dynamicaly?

Edit_text item
show_editor

LOV

40. What is an Lov?

A list of values is a single or multi column selection list displayed in


a pop-up window

41. Can you attach an lov to a field at design time?

Yes.

42. Can you attach an lov to a field at run-time? if yes, give the build-in name.

Yes. Set_item_proprety

43. What is the built-in used for showing lov at runtime?

Show_lov

44. What is the built-in used to get and set lov properties during run-time?

Get_lov_property
Set_lov_property

Record Group

45. What is a record Group?

A record group is an internal oracle forms data structure that has a simillar column/row
frame work to a database table
46. What are the different type of a record group?

Query record group


Static record group
Non query record group

47. Give built-in routine related to a record groups?

Create_group (Function)
Create_group_from_query(Function)
Delete_group(Procedure)
Add_group_column(Function)
Add_group_row(Procedure)
Delete_group_row(Procedure)
Populate_group(Function)
Populate_group_with_query(Function)
Set_group_Char_cell(procedure)

48. What is the built_in routine used to count the no of rows in a group?

Get_group _row_count

System Variables

49. List system variables available in forms 4.0, and not available in forms 3.0?

System.cordination_operation
System Date_threshold
System.effective_Date
System.event_window
System.suppress_working

50. System.effective_date system variable is read only True/False

False

51. What is a library in Forms 4.0?

A library is a collection of Pl/SQL program units, including user named procedures,


functions & packages

52. Is it possible to attach same library to more than one form?

Yes

53. Explain the following file extention related to library?


.pll,.lib,.pld

The library pll files is a portable design file comparable to an fmb form file
The library lib file is a plat form specific, generated library file comparable to a fmx
form file
The pld file is Txt format file and can be used for source controlling your library
files

Parameter

54. How do you pass the parameters from one form to another form?

To pass one or more parameters to a called form, the calling form must perform the
following steps in a trigger or user named routine excute the create_parameter_list built_in
function to programatically.
Create a parameter list to execute the add parameter built_in procedure to add
one or more parameters list.
Execute the call_form, New_form or run_product built_in procedure and include the
name or id of the parameter list to be passed to the called form.

54. What are the built-in routines is available in forms 4.0 to create and manipulate a
parameter list?

Add_parameter
Create_Parameter_list
Delete_parameter
Destroy_parameter_list
Get_parameter_attr
Get_parameter_list
set_parameter_attr

55. What are the two ways to incorporate images into a oracle forms application?

Boilerplate Images
Image_items

56. How image_items can be populate to field in forms 4.0?

A fetch from a long raw database column PL/Sql assignment to executing the
read_image_file built_in procedure to get an image from the file system.

57. What are the triggers associated with the image item?

When-Image-activated(Fires when the operator double clicks on an image Items)


When-image-pressed(fires when the operator selects or deselects the image item)

58. List some built-in routines used to manipulate images in image_item?

Image_add
Image_and
Image_subtract
Image_xor
Image_zoom

59. What are the built_in used to trapping errors in forms 4?

Error_type return character


Error_code return number
Error_text return char
Dbms_error_code return no.
Dbms_error_text return char

60. What is a predefined exception available in forms 4.0?

Raise form_trigger_failure

61. What are the menu items that oracle forms 4.0 supports?

Plain, Check,Radio, Separator, Magic

FORMS4.5

object groups

01. what ia an object groups?

An object group is a container for a group of objects, you define an object group when you
want to package related objects. so that you copy or reference them in another
modules.

02. what are the different objects that you cannot copy or reference in object groups?

objects of differnt modules


another object groups
individual block dependent items
program units.

canvas views

03. what are different types of canvas views?

content canvas views


stacked canvas views
horizontal toolbar
vertical toolbar.

04. explain about content canvas views?

Most Canvas views are content canvas views a content canvas view is the "base" view
that occupies the entire content pane of the window in which it is displayed.

05. Explain about stacked canvas views?

Stacked canvas view is displayed in a window on top of, or "stacked" on the content canvas
view assigned to that same window. Stacked canvas views obscure some part of the
underlying content canvas view, and or often shown and hidden programmatically.

06. Explain about horizontal, Vertical tool bar canvas views?

Tool bar canvas views are used to create tool bars for individual windows Horizontal tool
bars are display at the top of a window, just under its menu bar.
Vertical Tool bars are displayed along the left side of a window

07. Name of the functions used to get/set canvas properties?

Get_view_property, Set_view_property

Windows

07. What is relation between the window and canvas views?

Canvas views are the back ground objects on which you place the interface items (Text
items), check boxes, radio groups etc.,) and boilerplate
objects (boxes, lines, images etc.,) that operators interact with us they run your form .
Each canvas views displayed in a window.

08. What are the different modals of windows?

Modalless windows
Modal windows

09. What are modalless windows?

More than one modelless window can be displayed at the same time, and operators can
navigate among them if your application allows them to do so . On most GUI platforms,
modelless windows can also be layered to appear either in front of or behind other windows.

10. What are modal windows?

Modal windows are usually used as dialogs, and have restricted functionality
compared to modelless windows. On some platforms for example operators cannot resize,
scroll or iconify a modal window.

11. How do you display console on a window ?

The console includes the status line and message line, and is displayed at the bottom of the
window to which it is assigned.
To specify that the console should be displayed, set the console window form property
to the name of any window in the form. To include the console, set console window to
Null.

12. What is the remove on exit property?

For a modelless window, it determines whether oracle forms hides the window automatically
when the operators navigates to an item in the another window.

13. How many windows in a form can have console?

Only one window in a form can display the console, and you cannot chage the console
assignment at runtime.

14. Can you have more than one content canvas view attached with a window?

Yes.
Each window you create must have atleast one content canvas view assigned to it.
You can also create a window that has manipulate contant canvas view. At run time only
one of the content canvas views assign to a window is displayed at a time.

15. What are the different window events activated at runtimes?

When_window_activated
When_window_closed
When_window_deactivated
When_window_resized
Within this triggers, you can examine the built in system variable
system.event_window to determine the name of the window for which the trigger fired.

Modules

27. What are different types of modules available in oracle form?

Form module - a collection of objects and code routines


Menu modules - a collection of menus and menu item commands that together make up
an application menu
library module - a collectio of user named procedures, functions and packages that can
be called from other modules in the application

18. What are the default extensions of the files careated by forms modules?

.fmb - form module binary


.fmx - form module executable

19. What are the default extentions of the files created by menu module?

.mmb, .mmx

20 What are the default extension of the files created by library module?

The default file extensions indicate the library module type and storage format
.pll - pl/sql library module binary

Master Detail

21. What is a master detail relationship?

A master detail relationship is an association between two base table blocks- a master
block and a detail block. The relationship between the blocks reflects a primary key to
foreign key relationship between the tables on which the blocks are based.

22. What is coordination Event?

Any event that makes a different record in the master block the current record is a
coordination causing event.

23. What are the two phases of block coordination?


There are two phases of block coordination: the clear phase and the population
phase. During, the clear phase, Oracle Forms navigates internally to the detail block
and flushes the obsolete detail records. During the population phase, Oracle Forms
issues a SELECT statement to repopulate the detail block with detail records associated
witjh the new master record. These operations are accomplished through the execution of
triggers.

24. What are Most Common types of Complex master-detail relationships?

There are three most common types of complex master-detail relationships:


master with dependent details
master with independent details
detail with two masters

25. What are the different types of Delete details we can establish in Master-Details?
Cascade
Isolate
Non-isolote

26. What are the different defaust triggers created when Master Deletes Property is set
to Non-isolated?
Master Delets Property Resulting Triggers
----------------------------------------------------
Non-Isolated(the default) On-Check-Delete-Master
On-Clear-Details
On-Populate-Details

26. Whar are the different default triggers created when Master Deletes Property is set to
Cascade?
Ans: Master Deletes Property Resulting Triggers
---------------------------------------------------
Cascading On-Clear-Details
On-Populate-Details
Pre-delete

28. What are the different default triggers created when Master Deletes Property is set to
isolated?

Master Deletes Property Resulting Triggers


---------------------------------------------------
Isolated On-Clear-Details
On-Populate-Details

29. What are the Coordination Properties in a Master-Detail relationship?


The coordination properties are
Deferred
Auto-Query
These Properties determine when the population phase of block
coordination should occur.

30. What are the different types of Coordinations of the Master with the Detail block?
42. What is the User-Named Editor?

A user named editor has the same text editing functionality as the default editor, but,
becaue it is a named object, you can specify editor attributes such as windows display size,
position, and title.

43. What are the Built-ins to display the user-named editor?

A user named editor can be displayed programmatically with the built in procedure
SHOW-EDITOR, EDIT_TETITEM independent of any particular text item.

44. What is the difference between SHOW_EDITOR and EDIT_TEXTITEM?

Show editor is the generic built_in which accepts any editor name and takes some input
string and returns modified output string. Whereas the edit_textitem built_in needs
the input focus to be in the text item before the built_in is excuted.

45. What is an LOV?


An LOV is a scrollable popup window that provides the operator with either a single or multi
column selection list.

46. What is the basic data structure that is required for creating an LOV?
Record Group.

47. What is the "LOV of Validation" Property of an item? What is the use of it?
When LOV for Validation is set to True, Oracle Forms compares the current value of the
text item to the values in the first column displayed in the LOV.
Whenever the validation event occurs.
If the value in the text item matches one of the values in the first column of the LOV,
validation succeeds, the LOV is not displayed, and processing continues normally.
If the value in the text item does not match one of the values in the first column of
the LOV, Oracle Forms displays the LOV and uses the text item value as the search criteria
to automatically reduce the list.

48. What are the built_ins used the display the LOV?

Show_lov
List_values

49. What are the built-ins that are used to Attach an LOV programmatically to an item?

set_item_property
get_item_property
(by setting the LOV_NAME property)

50. What are the built-ins that are used for setting the LOV properties at runtime?

get_lov_property
set_lov_property

51. What is a record group?


A record group is an internal Oracle Forms that structure that hs a column/row
framework similar to a database table. However, unlike database tables, record groups are
separate objects that belong to the form module which they are defined.

52. How many number of columns a record group can have?

A record group can have an unlimited number of columns of type CHAR, LONG, NUMBER,
or DATE provided that the total number of column does not exceed 64K.

53. What is the Maximum allowed length of Record group Column?

Record group column names cannot exceed 30 characters.

54. What are the different types of Record Groups?

Query Record Groups


NonQuery Record Groups
State Record Groups

55. What is a Query Record Group?

A query record group is a record group that has an associated SELECT statement. The
columns in a query record group derive their default names, data types, had lengths from
the database columns referenced in the SELECT statement. The records in query record
group are the rows retrieved by the query associated with that record group.

56. What is a Non Query Record Group?

A non-query record group is a group that does not have an associated query, but whose
structure and values can be modified programmatically at runtime.

57. What is a Static Record Group?

A static record group is not associated with a query, rather, you define its structure and
row values at design time, and they remain fixed at runtime.

58. What are the built-ins used for Creating and deleting groups?

CREATE-GROUP (function)
CREATE_GROUP_FROM_QUERY(function)
DELETE_GROUP(procedure)

59.What are the built -ins used for Modifying a group's structure?

ADD-GROUP_COLUMN (function)
ADD_GROUP_ROW (procedure)
DELETE_GROUP_ROW(procedure)

60. POPULATE_GROUP(function)
POPULATE_GROUP_WITH_QUERY(function)
SET_GROUP_CHAR_CELL(procedure)
SET_GROUP_DATE_CELL(procedure)
SET_GROUP_NUMBER_CELL(procedure)
61. What are the built-ins used for Getting cell values?

GET_GROUP_CHAR_CELL (function)
GET_GROUP_DATE_CELL(function)
GET_GROUP_NUMBET_CELL(function)

62. What are built-ins used for Processing rows?

GET_GROUP_ROW_COUNT(function)
GET_GROUP_SELECTION_COUNT(function)
GET_GROUP_SELECTION(function)
RESET_GROUP_SELECTION(procedure)
SET_GROUP_SELECTION(procedure)
UNSET_GROUP_SELECTION(procedure)

63. What are the built-ins used for finding Object ID function?

FIND_GROUP(function)
FIND_COLUMN(function)

64. Use the ADD_GROUP_COLUMN function to add a column to a record group that was
created at design time.
I) TRUE II)FALSE

II) FALSE

65. Use the ADD_GROUP_ROW procedure to add a row to a static record group

I) TRUE II)FALSE
I) FALSE

61. What are the built-in used for getting cell values?

Get_group_char_cell(function)
Get_group_date_cell(function)
Get_group_number_cell(function)

62. What are the built-ins used for processing rows?

Get_group_row_count(function)
Get_group_selection_count(function)
Get_group_selection(function)
Reset_group_selection(procedure)
Set_group_selection(procedure)
Unset_group_selection(procedure)

63. What are the built-ins used for finding object ID functions?

Find_group(function)
Find_column(function)
64. Use the add_group_column function to add a column to record group that was created
at a design time?

False.

65. Use the Add_group_row procedure to add a row to a static record group 1. true or
false?

False.

parameters

66. What are parameters?

Parameters provide a simple mechanism for defining and setting the values
of inputs that are required by a form at startup. Form parameters are variables of type
char,number,date that you define at design time.

67. What are the Built-ins used for sending Parameters to forms?

You can pass parameter values to a form when an application executes the call_form,
New_form, Open_form or Run_product.

68. What is the maximum no of chars the parameter can store?

The maximum no of chars the parameter can store is only valid for char parameters,
which can be upto 64K. No parameters default to 23Bytes and Date parameter default to
7Bytes.

69. How do you call other Oracle Products from Oracle Forms?

Run_product is a built-in, Used to invoke one of the supported oracle tools products and
specifies the name of the document or module to be run. If the called product is unavailable
at the time of the call, Oracle Forms returns a message to the opertor.

70. How do you reference a Parameter?

In Pl/Sql, You can reference and set the values of form parameters using bind variables
syntax. Ex. PARAMETER name = '' or :block.item = PARAMETER
Parameter name

71. How do you reference a parameter indirectly?

To indirectly reference a parameter use the NAME IN, COPY 'built-ins to indirectly set
and reference the parameters value' Example name_in ('capital parameter my param'),
Copy ('SURESH','Parameter my_param')

72. What are the different Parameter types?

Text Parameters
Data Parameters
73. When do you use data parameter type?

When the value of a data parameter being passed to a called product is always the
name of the record group defined in the current form. Data parameters are used to
pass data to produts invoked with the run_product built-in subprogram.

74. Can you pass data parametrs to forms?

No.

IMAGES

75. What are different types of images?

Boiler plate images


Image Items

76. What is the difference between boiler plat images and image items?

Boiler plate Images are static images (Either vector or bit map) that you import from the
file system or database to use a grapical elements in your form, such as company logos and
maps Image items are special types of interface controls that store and display
either vector or bitmap images. Llike other items that store values, image items can be
either base table items(items that relate directly to database columns) or control items.
The definition of an image item is stored as part of the form module FMB and FMX files,
but no image file is actualy associated with an image item until the item is populate at run
time.

77. What are the trigger associated with image items?

When-image-activated fires when the operators double clicks on an image item


when-image-pressed fires when an operator clicks or double clicks on an image item

78. What is the use of image_zoom built-in?

To manipulate images in image items.

WORKING WITH MULTIPLE FORMS

79. How do you create a new session while open a new form?

Using open_form built-in setting the session option Ex. Open_form('Stocks


',active,session). when invoke the mulitiple forms with open form and call_form in the
same application, state whether the following are true/False

80. Any attempt to navigate programatically to disabled form in a call_form stack is


allowed?

False
81. An open form can not be execute the call_form procedure if you chain of called forms
has been initiated by another open form?

True

82. When a form is invoked with call_form, Does oracle forms issues a save point?

True

Mouse Operations

83. What are the various sub events a mouse double click event involves?

Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse
down & mouse up events.

84, State any three mouse events system variables?

System.mouse_button_pressed
System.mouse_button_shift_state
system.mouse_item
system.mouse_canvas
system.mouse_record

OLE

85. What is an OLE?

Object Linking & Embadding provides you with the capability to integrate objects from
many Ms-Windows applications into a single compound document creating integrated
applications enables you to use the features form .

86. What is the difference between object embedding & linking in Oracle forms?

In Oracle forms, Embedded objects become part of the form module, and linked objects
are references from a form module to a linked source file.

87. What is the difference between OLE Server & Ole Container?

An Ole server application creates ole Objects that are embedded or linked in ole
Containers ex. Ole servers are ms_word & ms_excell. OLE containers provide a place to
store, display and manipulate objects that are created by ole server applications. Ex.
oracle forms is an example of an ole Container.

88. What are the different styles of actvation of ole Objects?

In place activation
External activation

ViSUAL Attributes & property clauses

89. What are visual attributes?


Visual attributes are the font, color, pattern proprities that you set for form and menu
objects that appear in your application interface.

90. What is a property clause?

A property clause is a named object that contains a list of properties and thier settings.
Once you create a property clause you can base other object on it. An object based on a
property can inherit the setting of any property in the clause that makes sense for that
object.

91. Can a property clause itself be based on a property clause?

Yes

92. What are the important difference between property clause and visual attributes?

Named visual attributes differed only font, color & pattern attributes, property clauses
can contain this and any other properties. You can change the appearance of objects at
run time by changing the named visual attributes programatically , property clause
assignments cannot be changed programatically. When an object is inheriting from both a
property clause and named visual attribute, the named visual attribute settings take
precedence, and any visual attribute properties in the class are ignored.

Form Build-ins

93. What is a Text_io Package?

It allows you to read and write information to a file in the file system.

94. What is an User_exit?

Calls the user exit named in the user_exit_string. Invokes a 3Gl programe by name
which has been properly linked into your current oracle forms executable.

95. What is synchronize?

It is a terminal screen with the internal state of the form. It updates the screen display to
reflect the information that oracle forms has in its internal representation of the screen.

96. What is forms_DDL?

Issues dynamic Sql statements at run time, including server side pl/SQl and DDL

Triggers

97. What is WHEN-Database-record trigger?

Fires when oracle forms first marks a record as an insert or an update. The trigger fires as
soon as oracle forms determines through validation that the record should be processed by
the next post or commit as an insert or update. c generally occurs only when the operators
modifies the first item in the record, and after the operator attempts to navigate out of the
item.
98. What are the master-detail triggers?

On-Check_delete_master
On_clear_details
On_populate_details

99. What is the difference between $$DATE$$ & $$DBDATE$$

$$DBDATE$$ retrieves the current database date


$$date$$ retrieves the current operating system date.

100. What is system.coordination_operation?

It represents the coordination causing event that occur on the master block in master-detail
relation.

101. What are the difference between lov & list item?

Lov is a property where as list item ias an item. A list item can have only one column, lov
can have one or more columns.

102. What are the different display styles of list items?

Pop_list
Text_list
Combo box

103. What is pop list?

The pop list style list item appears initially as a single field (similar to a text item field).
When the operator selects the list icon, a list of available choices appears.

104. What is a text list?

The text list style list item appears as a rectangular box which displays the fixed number of
values. When the text list contains values that can not be displayed, a vertical scroll bar
appears, allowing the operator to view and select undisplayed values.

105. What is a combo box?


A combo box style list item combines the features found in list and text item. Unlike the
pop list or the text list style list items, the combo box style list item will both display
fixed values and accept one operator entered value.

106. What are display items?

Display items are similar to text items with the exception that display items only store
and display fetched or assigned values.Display items are generaly used as boilerplate or
conditional text.

107. What is difference between open_form and call_form?


when one form invokes another form by executing open_form the first form remains
displayed,and operators can navigate between the forms as desired. when one form
invokes another form by executing call_form,the called form is modal with respect to the
calling form.That is, any windows that belong to the calling form are disabled, and
operators cannot navigate to them until they first exit the called form.

108. What is new_form built-in?

When one form invokes another form by executing new_form oracle form exits the first
form and releases its memory before loading the new form calling new form completely
replace the first with the second. If there are changes pending in the first form,the operator
will be prompted to save them before the new form is loaded.

109. What is a library?

A library is a collection of subprograms including user named procedures, functions and


packages.

110. What is the advantage of the library?

Library's provide a convenient means of storing client-side program units and sharing
them among multipule applications. Once you create a library, you can attach it to any
other form,menu,or library modules. When you can call library program units from triggers
menu items commands and user named routine, you write in the modules to which you
have attach the library.
when a library attaches another library ,program units in the first library can reference
program units in the attached library. Library support dynamic loading-that is library
program units are loaded into an application only when needed. This can significantly
reduce the run-time memory requirements of an applications.

111. What is strip sources generate options?

Removes the source code from the library file and generates a library files that contains
only pcode.The resulting file can be used for final deployment, but can not be
subsequently edited in the designer.

ex. f45gen module=old_lib.pll userid=scott/tiger


strip_source YES output_file

112.What are the vbx controls?

Vbx control provide a simple mehtod of buildig and enhancing user interfaces.The
controls can use to obtain user inputs and display program outputs.vbx control where
originally develop as extensions for the ms visual basic environments and include such
items as sliders,grides and knobs.

113. What is a timer?

Timer is a "internal time clock" that you can programmatically create to perform an action
each time the timer expires.

114. What are built-ins associated with timers?


find_timer
create_timer
delete_timer

115. what are difference between post database commit and post-form commit?

Post-form commit fires once during the post and commit transactions process, after
the database commit occures. The post-form-commit trigger fires after inserts,updates
and deletes have been posted to the database but before the transactions have been
finalished in the issuing the command.The post-database-commit trigger fires after
oracle forms issues the commit to finalished transactions.

116. What is a difference between pre-select and pre-query?

Fires during the execute query and count query processing after oracle forms constructs
the select statement to be issued, but before the statement is actually issued.

The pre-query trigger fires just before oracle forms issues the select statement to the
database after the operator as define the example records by entering the query criteria in
enter query mode.

Pre-query trigger fires before pre-select trigger.

117. What is trigger associated with the timer?

When-timer-expired.

118 What is the use of transactional triggers?

Using transactional triggers we can control or modify the default functionality of the
oracle forms.

REPORTS

1. What are the different file extensions that are created by oracle reports?

Rep file and Rdf file.

2. From which designation is it preferred to send the output to the printed?

Previewer.

3. Is it possible to disable the parameter from while running the report?


Yes

4. What is lexical reference?How can it be created?

Lexical reference is place_holder for text that can be embedded in a sql


statements.A lexical reference can be created using & before the column or
parameter name.
5. What is bind reference and how can it carate?

Bind reference are used to replace the single value in sql,pl/sql


statements a bind reference can be careated using a (:) before a column or
a parameter name.

6.What use of command line parameter cmd file?

It is a command line argument that allows you to specify a file that contain a set of
arguments for r20run.

7.Where is a procedure return in an external pl/sql library executed at the client or at the
server?

At the client.

8. Where is the external query executed at the client or the server?

At the server.

9. What are the default parameter that appear at run time in the parameter screen?

Destype and Desname.

10. Which parameter can be used to set read level consistency across multiple queries?

Read only.

11. What is term?

The term is terminal definition file that describes the terminal form which you are using
r20run.

12. What is use of term?

The term file which key is correspond to which oracle report functions.

13. Is it possible to insert comments into sql statements return in the data model editor?

Yes.

14. If the maximum record retrieved property of the query is set to 10 then a summary
value will be calculated?

Only for 10 records.

15. What are the sql clauses supported in the link property sheet?

Where startwith having.

16. To execute row from being displayed that still use column in the row which property
can be used?
Format trigger.

17. Is it possible to set a filter condition in a cross product group in matrix reports?

No.

18. If a break order is set on a column would it effect columns which are under the
column? No.

19. With which function of summary item is the compute at options required?

percentage of total functions.

20. What is the purpose of the product order option in the column property sheet?

To specify the order of individual group evaluation in a cross products.

21.Can a formula column be obtained through a select statement?

Yes.

22.Can a formula column refered to columns in higher group?

Yes.

23. How can a break order be created on a column in an existing group?

By dragging the column outside the group.

24. What are the types of calculated columns available?

Summary, Formula, Placeholder column.

25. What is the use of place holder column?

A placeholder column is used to hold a calculated values at a specified place rather than
allowing is to appear in the actual row where it has to appeared.

26. What is the use of hidden column?

A hidden column is used to when a column has to embedded into boilerplate text.

27. What is the use of break group?

A break group is used to display one record for one group ones.While multiple related
records in other group can be displayed.

28. If two groups are not linked in the data model editor, What is the hierarchy between
them?
Two group that is above are the left most rank higher than the group that is to right or
below it.

29.The join defined by the default data link is an outer join yes or no?

Yes.

30. How can a text file be attached to a report while creating in the report writer?

By using the link file property in the layout boiler plate property sheet.

31. Can a repeating frame be careated without a data group as a base?

No.

32. Can a field be used in a report wihtout it appearing in any data group?

Yes.

33. For a field in a repeating frame, can the source come from the column which does not
exist in the data group which forms the base for the frame?

Yes.

34. Is it possible to center an object horizontally in a repeating frame that has a variable
horizontal size?

Yes.

35. If yes,how?

By the use anchors.

36. What are the two repeating frame always associated with matrix object?

One down repeating frame below one across repeating frame.

37. Is it possible to split the printpreviewer into more than one region?

Yes.

38. Does a grouping done for objects in the layout editor affect the grouping done in
the datamodel editor?

No.

39. How can a square be drawn in the layout editor of the report writer?

By using the rectangle tool while pressing the (Constraint) key.

40. To display the page no. for each page on a report what would be the source & logical
page no. or & of physical page no.?
& physical page no.

41. What does the term panel refer to with regard to pages?

A panel is the no. of physical pages needed to print one logical page.

42. What is an anchoring object & what is its use?

An anchoring object is a print condition object which used to explicitly or implicitly anchor
other objects to itself.

43. What is a physical page ? & What is a logical page ?

A physical page is a size of a page. That is output by the printer. The


logical page is the size of one page of the actual report as seen in the
Previewer.

44. What is the frame & repeating frame?

A frame is a holder for a group of fields. A repeating frame is used to display a set of
records when the no. of records that are to displayed is not known before.

REPORT TRIGGERS.

45. What are the triggers available in the reports?

Before report, Before form, After form , Between page, After report.

46. Does a Before form trigger fire when the parameter form is suppressed.

Yes.

47. At what point of report execution is the before Report trigger fired?

After the query is executed but before the report is executed and the
records are displayed.

48. Is the After report trigger fired if the report execution fails?

Yes.

49. Give the sequence of execution of the various report triggers?

Before form , After form , Before report, Between page, After report.

50. Is it possible to modify an external query in a report which contains


it?

No.

51. What are the ways to monitor the performance of the report?

Use reports profile executable statement.


Use SQL trace facility.

52. Why is it preferable to create a fewer no. of queries in the data


model.

Because for each query, report has to open a separate cursor and has to
rebind, execute and fetch data.

53. What are the various methods of performing a calculation in a report ?

1. Perform the calculation in the SQL statements itself.


2. Use a calculated / summary column in the data model.

54. Which of the above methods is the faster method?

performing the calculation in the query is faster.

55. Why is a Where clause faster than a group filter or a format trigger?

Because, in a where clause the condition is applied during data retrieval


than after retrieving the data.

56. What is the main diff. bet. Reports 2.0 & Reports 2.5?

Report 2.5 is object oriented.

57. What is the diff. bet. setting up of parameters in reports 2.0 reports
2.5?

LOVs can be attached to parameters in the reports 2.5 parameter form.

58. How is link tool operation different bet. reports 2 & 2.5?

In Reports 2.0 the link tool has to be selected and then two fields to be
linked are selected and the link is automatically created. In 2.5 the first
field is selected and the link tool is then used to link the first field to
the second field.

REPORT 2.5 SPECIFIC ISSUES.

59.What are the two types views available in the object navigator(specific
to report 2.5)?

View by structure and view by type .

60. Which of the two views should objects according to possession?

view by structure.

61.How is possible to restrict the user to a list of values while entering


values for parameters?

By setting the Restrict To List property to true in the parameter property


sheet.

62. How is it possible to select generate a select ste. for the query in
the query property sheet?

By using the tables/columns button and then specifying the table and the
column names.

63. If a parameter is used in a query without being previously defined,


what diff. exist betw. report 2.0 and 2.5 when the query is applied?

While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a
message that a bind parameter has been created.

64. Do user parameters appear in the data modal editor in 2.5?

No.

65.What is the diff. when confine mode is on and when it is off?

When confine mode is on, an object cannot be moved outside its parent in
the layout.

66. What is the diff. when Flex mode is mode on and when it is off?

When flex mode is on, reports automatically resizes the parent when the
child is resized.

67. How can a button be used in a report to give a drill down facility?

By setting the action asscoiated with button to Execute pl/sql option and
using the SRW.Run_report function.

68. What are the two ways by which data can be generated for a parameter's
list of values?
1. Using static values.
2. Writing select statement.

69. What are the two panes that Appear in the design time pl/sql
interpreter?

1.Source pane. 2. Interpreter pane

70. What are three panes that appear in the run time pl/sql interpreter?

1.Source pane. 2. interpreter pane. 3. Navigator pane.

CROSS PRODUCTS AND MATRIX REPORTS

71. How can a cross product be created?

By selecting the cross products tool and drawing a new group surrounding
the base group of the cross products.

72. How can a group in a cross products be visually distinguished from a


group that does not form a cross product?

A group that forms part of a cross product will have a thicker border.

73. Atleast how many set of data must a data model have before a data model
can be base on it?

Four.

74. Is it possible to have a link from a group that is inside a cross


product to a group outside ? (Y/N)

No.

75. Is it possible to link two groups inside a cross products after the
cross products group has been created?

No.
76. What is an user exit used for?

A way in which to pass control (and possibly arguments ) form Oracle report
to another Oracle products of 3 GL and then return control ( and ) back
to Oracle reprots.

77. What are the three types of user exits available ?

Oracle Precompiler exits, Oracle call interface,NonOracle user exits.

78. How can values be passed bet. precompiler exits & Oracle call
interface?

By using the statement EXECIAFGET & EXECIAFPUT.

79. How can I message to passed to the user from reports?

By using SRW.MESSAGE function.

Oracle DBA
1. SNAPSHOT is used for
[DBA] a] Synonym, b] Table space, c] System server, d] Dynamic data
replication

Ans : D

2. We can create SNAPSHOTLOG for


[DBA] a] Simple snapshots, b] Complex snapshots, c] Both A & B, d]
Neither A nor B
Ans : A
3. Transactions per rollback segment is derived from
[DBA] a] Db_Block_Buffers, b] Processes, c] Shared_Pool_Size, d] None
of the above

Ans : B

4. ENQUEUE resources parameter information is derived from


[DBA] a] Processes or DDL_LOCKS and DML_LOCKS, b] LOG_BUFFER,
c] DB__BLOCK_SIZE..
Ans : A

5. LGWR process writes information into


a] Database files, b] Control files, c] Redolog files, d] All the
above.
Ans : C

6. SET TRANSACTION USE ROLLBACK SEGMENT is used to create user


objects
in a particular Tablespace
a] True, b] False
Ans : False

7. Databases overall structure is maintained in a file called


a] Redolog file, b] Data file, c] Control file, d] All of the
above.
Ans : C

8. These following parameters are optional in init.ora parameter file


DB_BLOCK_SIZE,
PROCESSES
a] True, b] False
Ans : False

9. Constraints cannot be exported through EXPORT command


a] True, b] False
Ans : False

10. It is very difficult to grant and manage common privileges needed by


different groups of
database users using the roles
a] True, b] False
Ans : False

11. What is difference between a DIALOG WINDOW and a DOCUMENT WINDOW


regarding
moving the window with respect to the application window
a] Both windows behave the same way as far as moving the window is
concerned.
b] A document window can be moved outside the application window while
a dialog
window cannot be moved
c] A dialog window can be moved outside the application window while a
document
window cannot be moved
Ans : C

12. What is the difference between a MESSAGEBOX and an ALERT


a] A messagebox can be used only by the system and cannot be used in
user application
while an alert can be used in user application also.
b] A alert can be used only by the system and cannot be use din user
application
while an messagebox can be used in user application also.
c] An alert requires an response from the userwhile a messagebox just
flashes a message
and only requires an acknowledment from the user
d] An message box requires an response from the userwhile a alert just
flashes a
message an only requires an acknowledment from the user
Ans : C

13. Which of the following is not an reason for the fact that most of the
processing is done at the
server ?
a] To reduce network traffic. b] For application sharing, c] To
implement business rules
centrally, d] None of the above
Ans : D

14. Can a DIALOG WINDOW have scroll bar attached to it ?


a] Yes, b] No
Ans : B

15. Which of the following is not an advantage of GUI systems ?


a] Intuitive and easy to use., b] GUI's can display multiple
applications in multiple windows
c] GUI's provide more user interface objects for a developer
d] None of the above
Ans :D

16. What is the difference between a LIST BOX and a COMBO BOX ?
a] In the list box, the user is restricted to selecting a value from a
list but in a combo box
the user can type in a value which is not in the list
b] A list box is a data entry area while a combo box can be used only
for control purposes
c] In a combo box, the user is restricted to selecting a value from a
list but in a list box the
user can type in a value which is not in the list
d] None of the above
Ans : A

17. 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
Ans : D

18. 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
Ans : A

19. 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.
Ans : C

20. What does DLL stands for ?


a] Dynamic Language Library
b] Dynamic Link Library
c] Dynamic Load Library
d] None of the above
Ans : B

21. POST-BLOCK trigger is a


a] Navigational trigger
b] Key trigger
c] Transactional trigger
d] None of the above
Ans : A

22. The system variable that records the select statement that SQL * FORMS
most recently used
to populate a block is
a] SYSTEM.LAST_RECORD
b] SYSTEM.CURSOR_RECORD
c] SYSTEM.CURSOR_FIELD
d] SYSTEM.LAST_QUERY
Ans: D

23. Which of the following is TRUE for the ENFORCE KEY field
a] ENFORCE KEY field characterstic indicates the source of the value
that SQL*FORMS
uses to populate the field
b] A field with the ENFORCE KEY characterstic should have the INPUT
ALLOWED
charaterstic turned off
a] Only 1 is TRUE
b] Only 2 is TRUE
c] Both 1 and 2 are TRUE
d] Both 1 and 2 are FALSE
Ans : A

24. What is the maximum size of the page ?


a] Characters wide & 265 characters length
b] Characters wide & 265 characters length
c] Characters wide & 80 characters length
d] None of the above
Ans : B

25. A FORM is madeup of which of the following objects


a] block, fields only,
b] blocks, fields, pages only,
c] blocks, fields, pages, triggers and form level procedures,
d] Only blocks.
Ans : C

26. For the following statements which is true


1] Page is an object owned by a form
2] Pages are a collection of display information such as constant text
and graphics.
a] Only 1 is TRUE
b] Only 2 is TRUE
c] Both 1 & 2 are TRUE
d] Both are FALSE
Ans : B

27. The packaged procedure that makes data in form permanent in the
Database is
a] Post
b] Post form
c] Commit form
d] None of the above
Ans : C

28. Which of the following is TRUE for the SYSTEM VARIABLE $$date$$
a] Can be assigned to a global variable
b] Can be assigned to any field only during design time
c] Can be assigned to any variable or field during run time
d] None of the above
Ans : B

29. Which of the following packaged procedure is UNRESTRICTED ?


a] CALL_INPUT, b] CLEAR_BLOCK, c] EXECUTE_QUERY, d] USER_EXIT
Ans : D
30. Identify the RESTRICTED packaged procedure from the following
a] USER_EXIT, b] MESSAGE, c] BREAK, d] EXIT_FORM
Ans : D

31. What is SQL*FORMS


a] SQL*FORMS is a 4GL tool for developing & executing Oracle based
interactive
applications.
b] SQL*FORMS is a 3GL tool for connecting to the Database.
c] SQL*FORMS is a reporting tool
d] None of the above.
Ans : A

32. Name the two files that are created when you generate a form using
Forms 3.0
a] FMB & FMX, b] FMR & FDX, c] INP & FRM, d] None of the above
Ans : C

33. 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
Ans : C

34. Which of the folowing is TRUE for a ERASE packaged procedure


1] ERASE removes an indicated Global variable & releases the memory
associated with it
2] ERASE is used to remove a field from a page
1] Only 1 is TRUE
2] Only 2 is TRUE
3] Both 1 & 2 are TRUE
4] Both 1 & 2 are FALSE
Ans : 1

35. All datafiles related to a Tablespace are removed when the Tablespace
is dropped
a] TRUE
b] FALSE
Ans : B

36. 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
Ans : B

37. Multiple Tablespaces can share a single datafile


a] TRUE
b] FALSE
Ans : B

38. 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
Ans : A

39. Datadictionary can span across multiple Tablespaces


a] TRUE
b] FALSE
Ans : B

40. What is a DATABLOCK


a] Set of Extents
b] Set of Segments
c] Smallest Database storage unit
d] None of the above
Ans : C

41. Can an Integrity Constraint be enforced on a table if some existing


table data does not satisfy
the constraint
a] Yes
b] No
Ans : B

42. A column defined as PRIMARY KEY can have NULL's


a] TRUE
b] FALSE
Ans : B

43. 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
Ans : C

44. A Database Procedure is stored in the Database


a] In compiled form
b] As source code
c] Both A & B
d] Not stored
Ans : C

45. A database trigger doesnot apply to data loaded before the definition
of the trigger
a] TRUE
b] FALSE
Ans : A

46. Dedicated server configuration is


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
Ans : C

47. Which of the following does not affect the size of the SGA
a] Database buffer
b] Redolog buffer
c] Stored procedure
d] Shared pool
Ans : C

48. What does a COMMIT statement do to a CURSOR


a] Open the Cursor
b] Fetch the Cursor
c] Close the Cursor
d] None of the above
Ans : D

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

50. 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
Ans : B

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

Ans : A

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

Ans : C

53. Which of the following is not correct about User_Defined Exceptions ?


a] Must be declared
b] Must be raised explicitly
c] Raised automatically in response to an Oracle error
d] None of the above

Ans : C

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

Ans : D

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

Ans : C

56. Is it possible to open a cursor which is in a Package in another


procedure ?
a] Yes
b] No

Ans : A
57. Is it possible to use Transactional control statements in Database
Triggers ?
a] Yes
b] No

Ans : B

58. Is it possible to Enable or Disable a Database trigger ?


a] Yes
b] No

Ans : A

59. PL/SQL supports datatype(s)


a] Scalar datatype
b] Composite datatype
c] All of the above
d] None of the above

Ans C

60. Find the ODD datatype out


a] VARCHAR2
b] RECORD
c] BOOLEAN
d] RAW

Ans : B

61. 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
c] Column datatype of any Scalar type
d] None of the above

Ans : A

62. Find the ODD one out of the following


a] OPEN
b] CLOSE
c] INSERT
d] FETCH

Ans C

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

Ans : B

64. Which of the following is NOT VALID in PL/SQL ?


a] Select ... into
b] Update
c] Create
d] Delete

Ans : C

65. What is the Result of the following 'VIK'||NULL||'RAM' ?


a] Error
b] VIK RAM
c] VIKRAM
d] NULL

Ans : C

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

Ans : C
67. Does the Database trigger will fire when the table is TRUNCATED ?
a] Yes
b] No

Ans : B

68. SUBSTR(SQUARE ANS ALWAYS WORK HARD,14,6) will return


a] ALWAY
b} S ALWA
c] ALWAYS
Ans : C

69. REPLACE('JACK AND JUE','J','BL') will return


a] JACK AND BLUE
b] BLACK AND JACK
c] BLACK AND BLUE
d] None of the above
Ans : C

70. TRANSLATE('333SQD234','0123456789ABCDPQRST','0123456789') will return


a] 333234
b] 333333
c] 234333
d] None of the above

Ans : A

71. EMPNO ENAME SAL


A822 RAMASWAMY 3500
A812 NARAYAN 5000
A973 UMESH 2850
A500 BALAJI 5750

Use these data for the following Questions

Select SAL from EMP E1 where 3 > ( Select count(*) from Emp E2
where E1.SAL > E2.SAL ) will retrieve
a] 3500,5000,2500
b] 5000,2850
c] 2850,5750
d] 5000,5750

Ans : A

72. Is it possible to modify a Datatype of a column when column contains


data ?
a] Yes
b] No

Ans B

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

Ans : B

74. Which is not part of the Data Definiton Language ?


a] CREATE
b] ALTER
c] ALTER SESSION

Ans : C
75. The Data Manipulation Language statements are
a] INSERT
b] UPDATE
c] SELECT
d] All of the above

Ans : D

76. EMPNO ENAME SAL


A822 RAMASWAMY 3500
A812 NARAYAN 5000
A973 UMESH
A500 BALAJI 5750

Using the above data


Select count(sal) from Emp will retrieve
a] 1
b] 0
c] 3
d] None of the above

Ans : C

77. If an UNIQUE KEY constraint on DATE column is created, will it accept


the rows that are
inserted with SYSDATE ?
a] Will
b] Won't

Ans : B

78. What are the different events in Triggers ?


a] Define, Create
b] Drop, Comment
c] Insert, Update, Delete
d] All of the above

Ans : C
79. What built-in subprogram is used to manipulate images in image items ?
a] Zoom_out
b] Zoom_in'
c] Image_zoom
d] Zoom_image

Ans : C

80. Can we pass RECORD GROUP between FORMS ?


a] Yes
b] No

Ans : A
81. SHOW_ALERT function returns
a] Boolean
b] Number
c] Character
d] None of the above

Ans : B

82. What SYSTEM VARIABLE is used to refer DATABASE TIME ?


a] $$dbtime$$
b] $$time$$
c] $$datetime$$
d] None of the above

Ans : A

83. :SYSTEM.EFFECTIVE.DATE varaible is


a] Read only
b] Read & Write
c] Write only
d] None of the above

Ans : C

84. How can you CALL Reports from Forms4.0 ?


a] Run_Report built_in
b] Call_Report built_in
c] Run_Product built_in
d] Call_Product built_in

Ans : C

85. When do you get a .PLL extension ?


a] Save Library file
b] Generate Library file
c] Run Library file
d] None of the above

Ans : A

86. What is built_in Subprogram ?


a] Stored procedure & Function
b] Collection of Subprogram
c] Collection of Packages
d] None of the above

Ans : D

87. GET_BLOCK property is a


a] Restricted procedure
b] Unrestricted procedure
c] Library function
d] None of the above
Ans : D

88. A CONTROL BLOCK can sometimes refer to a BASETABLE ?


a] TRUE
b] FALSE

Ans : B

89. What do you mean by CHECK BOX ?


a] Two state control
b] One state control
c] Three state control
d] none of the above

Ans : C - Please check the Correcness of this Answer ( The correct answer
is 2 )

90. List of Values (LOV) supports


a] Single column
b] Multi column
c] Single or Multi column
d] None of the above

Ans : C

91. What is Library in Forms 4.0 ?


a] Collection of External field
b] Collection of built_in packages
c] Collection of PL/SQl functions, procedures and packages
d] Collection of PL/SQL procedures & triggers

Ans : C

92. Can we use a RESTRICTED packaged procedure in WHEN_TEXT_ITEM trigger ?


a] Yes
b] No

Ans : B

93. Can we use GO_BLOCK package in a PRE_TEXT_ITEM trigger ?


a] Yes
b] No

Ans : B

94. What type of file is used for porting Forms 4.5 applications to various
platforms ?
a] .FMB file
b] .FMX file
c] .FMT file
d] .EXE file

Ans : C

95. What built_in procedure is used to get IMAGES in Forms 4.5 ?


a] READ_IMAGE_FILE
b] GET_IMAGE_FILE
c] READ_FILE
d] GET_FILE

Ans A

96. When a form is invoked with CALL_FORM does Oracle forms issues
SAVEPOINT ?
a] Yes
b] No

Ans : A

97. Can we attach the same LOV to different fields in Design time ?
a] Yes
b] No

Ans : A

98. How do you pass values from one form to another form ?
a] LOV
b] Parameters
c] Local variables
d] None of the above

Ans : B

99. Can you copy the PROGRAM UNIT into an Object group ?
a] Yes
b] No

Ans : B

100. Can MULTIPLE DOCUMENT INTERFACE (MDI) be used in Forms 4.5 ?


a] Yes
b] No

Ans : A

101. When is a .FMB file extension is created in Forms 4.5 ?


a] Generating form
b] Executing form
c] Save form
d] Run form

Ans : C
102. What is a Built_in subprogram ?
a] Library
b] Stored procedure & Function
c] Collection of Subprograms
d] None of the above

Ans : D

103. What is a RADIO GROUP ?


a] Mutually exclusive
b] Select more than one column
c] Above all TRUE
d] Above all FALSE

Ans : A

104. Identify the Odd one of the following statements ?


a] Poplist
b] Tlist
c] List of values
d] Combo box

Ans : C

105. What is an ALERT ?


a] Modeless window
b] Modal window
c] Both are TRUE
d] None of the above

Ans : B

106. Can an Alert message be changed at runtime ?


a] Yes
b] No

Ans : A

107. Can we create an LOV without an RECORD GROUP ?


a} Yes
b] No

Ans : B

108. How many no of columns can a RECORD GROUP have ?


a] 10
b] 20
c] 50
d] None of the above

Ans D
109. Oracle precompiler translates the EMBEDDED SQL statemens into
a] Oracle FORMS
b] Oracle REPORTS
c] Oracle LIBRARY
d] None of the above

Ans : D

110. Kind of COMMENT statements placed within SQL statements ?


a] Asterisk(*) in column ?
b] ANSI SQL style statements(...)
c] C-Style comments (/*......*/)
d] All the above

Ans : D

111. What is the appropriate destination type to send the output to a


printer ?
a] Screen
b] Previewer
c] Either of the above
d] None of the above

Ans : D

112. What is TERM ?


a] TERM is the terminal definition file that describes the terminal
from which you are
using R20RUN ( Reports run time )
b] TERM is the terminal definition file that describes the terminal
from which you are
using R20DES ( Reports designer )
c] There is no Parameter called TERM in Reports 2.0
d] None of the above

Ans : A

113. If the maximum records retrieved property of a query is set to 10,


then a summary value will
be calculated
a] Only for 10 records
b] For all the records retrieved
c] For all therecords in the referenced table
d] None of the above

Ans : A

114. With which function of a summary item in the COMPUTE AT option


required ?
a] Sum
b] Standard deviation
c] Variance
d] % of Total function

Ans : D

115. For a field in a repeating frame, can the source come from a column
which does not exist in
the datagroup which forms the base of the frame ?
a] Yes
b] No

Ans : A

116. What are the different file extensions that are created by Oracle
Reports ?
a] .RDF file & .RPX file
b] .RDX file & .RDF file
c] .REP file & .RDF file
d] None of the above

Ans : C

117. Is it possible to Disable the Parameter form while running the report
?
a] Yes
b] No

Ans : A
118.What are the SQL clauses supported in the link property sheet ?
a] WHERE & START WITH
b] WHERE & HAVING
c} START WITH & HAVING
d] WHERE, START WITH & HAVING

Ans : D
119. What are the types of Calculated columns available ?
a] Summary, Place holder & Procedure column
b] Summary, Procedure & Formula columns
c] Procedure, Formula & Place holder columns
d] Summary, Formula & Place holder columns

Ans.: D
120. If two groups are not linked in the data model editor, what is the
hierarchy between them?
a] There is no hierarchy between unlinked groups
b] The group that is right ranks higher than the group that is to the
left
c] The group that is above or leftmost ranks higher than the group
that is to right or below
it
d] None of the above

Ans : C
121. 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

Ans : B
122. SYSTEM TABLESPACE can be made off-line
a] Yes
b] No

Ans : B
123. 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

Ans : A
124. SMON process is used to write into LOG files
a] TRUE
b] FALSE

Ans : B
125. 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

Ans : A
126. SNAPSHOTS cannot be refreshed automatically
a] TRUE
b] FALSE
Ans : B
127. The User can set Archive file name formats
a] TRUE
b] FALSE

Ans : A

128. The following parameters are optional in init.ora parameter file


DB_BLOCK_SIZE,
PROCESS
a} TRUE
b] FALSE
Ans : B
129. NOARCHIEVELOG parameter is used to enable the database in Archieve
mode
a] TRUE
b] FALSE
Ans : B
130. Constraints cannot be exported through Export command?
a] TRUE
b] FALSE

Ans: B
131. It is very difficult to grant and manage common priveleges needed by
Different groups of
Database users using roles
a] TRUE
b] FALSE

Ans: B
132. The status of the Rollback segment can be viewed through
a] DBA_SEGMENTS
b] DBA_ROLES
c] DBA_FREE_SPACES
d] DBA_ROLLBACK_SEG

Ans: D

133. Explicitly we can assign transaction to a rollback segment


a] TRUE
B] FALSE

Ans: A

134. What file is read by ODBC to load drivers ?


a] ODBC.INI
b] ODBC.DLL
c] ODBCDRV.INI
d] None of the above

Ans: A

Quiz – 1
1)Display the names of all the employees and their experience in years.
SELECT ENAME,ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) AS EXPERINCE FROM EMP

2)Display the employee name and his manager's name.


ANS. select a.ename as employee,b.ename as manager
from emp a,emp b
where b.empno=a.mgr

3)Display the employee's name, department's name ,grade and manager's name.
SQL> SELECT a.ENAME,DNAME,s.grade,B.ENAME
2 FROM emp a,EMP B,DEPT D,salgrade s
3 WHERE a.mgr=b.empno
4 AND A.DEPTNO=D.DEPTNO
5 And a.sal between s.losal and s.hisal
5 /
4)Display the emp name and salary those earn more than the average salary of
the company.
select ename,sal from emp where sal>(select avg(sal) from emp);

5)Display all the employees who earn more than their manager's salary.
SELECT A.EMPNO FROM EMP A,EMP B
WHERE B.EMPNO=A.MGR
AND A.SAL>B.SAL

6)Display all the employees whose grade is the same as that of JONES.

Select empno,ename from


Emp A,SALGRADE S,(select grade
from salgrade,emp
Where sal
between LOsal and HIsal
And ename='JONES') B
WHERE A.SAL BETWEEN S.LOSAL AND S.HISAL
AND S.GRADE=B.GRADE
AND A.ENAME <>'JONES'
OR

Select empno,ename from


Emp A,SALGRADE S
WHERE A.SAL BETWEEN S.LOSAL AND S.HISAL
AND S.GRADE=(select grade
from salgrade,emp
Where sal
between LOsal and HIsal
And ename='JONES')
AND A.ENAME <>'JONES'

7)Display all employee names and their salaries whose salary is not in the
range on 1500 and 2850
The Column Heading to be displayed as
Emp Monthly
Name Salary
---- ------
SQL> column ename heading 'Emp|Name'
SQL> column sal heading 'Monthly|Salary'
SQL> select ename,sal
2 from emp
3 where sal not between 1500 and 2850;

8)Display the name of the employee who don't have any manager.
select ename from emp where mgr is null;

9)Display the name ,salary and commission for all employees whose commission
amount is greater than their salary increased by 10%
select ename,sal,comm from emp where comm >(1.1*sal);
10)Display the Ename,salary and salary increased by 15% expressed as a whole
number.Label the column New Salary.In addition to this display the Increase
of salary over the previous one.For Example.

ENAME SAL NEWSAL INCREASE


----- --- ------ -------
KING 5000 5500 500
SELECT ENAME,SAL,ROUND(SAL*1.15) AS NEWSAL,ROUND(SAL*1.15)-sal AS INCREASE
FROM EMP

11)Display the Employee name ,hiredate, salary review date which is the first
Monday after 6 months of the service.

Ename Hiredate Review


----- -------- ------
KING 17-NOV-81 Monday, the Twenty-Forth of May,1982

select ename as Ename,


hiredate as Hiredate,
to_char(next_day(add_months(hiredate,6),'monday'),'Day",the" ddsp "of"
month rrrr')
as Review
from emp
/

12)Create a query that will display the employee name ,dept number and all
the employees name that work in tha same dept as a given employee.

select a.ename,a.deptno,b.ename
from emp a,emp b
where b.deptno=a.deptno
and a.ename !=b.ename
order by a.deptno,a.ename

13) Display the Job and the no. of persons working in each job type.
select job,count(job) from emp group by job;

14) Display dept name,location,number of employees and the average salary for
all employees in that dept.

select dname,loc,count(empno),avg(sal)
from emp,dept
where emp.deptno(+)=dept.deptno
group by dname,loc

15) Display the empname,salary of all employees who report to KING.


select a.ename,a.sal
from emp a,emp b
where b.empno=a.mgr
and b.ename ='KING'
/
select ename,sal+nvl(comm,0),job,loc
from emp,dept
where emp.deptno=dept.deptno
and sal+nvl(comm,0)>
(select sal+nvl(comm,0)
from emp where ename=’JONES’);

EXERCISE 1
Quiz - 2

1.Display current date and 78 days after.


SELECT SYSDATE, SYSDATE+78 FROM DUAL;

2. Display the current date in the following fashion.


Today's date is : Jan 4 1998.
SELECT TO_CHAR(SYSDATE,' "Today''s date is :" MON D YYYY') FROM DUAL

3. Display Employee name and Job information from employee in the following
fashion.
SMITH Works as CLERK.
select ename||' Works as '||job from emp

4. Display all the information from department table where second character
of city name is 'A'.
SELECT * FROM DEPT WHERE LOC LIKE '_A%'

5. Display rowid, employee number from employee table.


SQL> SELECT ROWID,EMPNO FROM EMP;

6. Display rowid, row number, deptno from department table.


SQL> SELECT ROWID,ROWNUM,DEPTNO FROM DEPT
2 /

7. Display the last date in Feb-97


select LAST_DAY(to_date('FEB-97','MON-YY')) FROM DUAL

8. Display logged on user name in the following fashion.


Current User Name is : SCOTT
select 'Current User Name is: ' || user from dual;

9. Display 'YOU ARE GOOD IN SQL' text as 'You Are Good In Sql' in a Select
statement.
SELECT INITCAP('U ARE GOOD IN SQL')FROM DUAL;

10. Display current date and 78 days before.


SQL> SELECT SYSDATE,SYSDATE-78 FROM DUAL;

Group Functions
===============

1. Select maximum, minimum salary in employee table.


select max(sal),min(sal) from emp;

2. Select minimum salary,commission in employee table for deptno 20.


select sal,comm from emp where deptno=20 and sal=(select min(sal) from emp
where deptno=20)

3. Select employee number, employee name, department number whose sum of


salary and commission greater than 2500.

select empno, ename, deptno from emp


where empno in (select empno from emp a having sum(sal+comm) > 2500 group by
empno)

4.Select employee number, employee name, employee experience in years from


employee table.
select empno,ename,round(months_between(sysdate,hiredate)/12) from emp;

5. Select employee number , employee name hired in the month of july.


select empno,ename from emp where to_char(hiredate,'MON')='JUL'

6.Select employee name ,Hiredate in the format of "2nd of july 1997" for
deptno 10 and 20.
SELECT ENAME,TO_CHAR(HIREDATE,'ddth "of" month rrrr')
from emp
where deptno in(10,20)

7.Display employee names in lower case whose salary is greater than 2000 and
less than 2800.
select lower(ename) from emp where sal between 2000 and 2800;

8.Select the number of employees who has no commission .


select count(empno) from emp where comm is null;

9.Select employee name whose job is Manager or Clerk and Salary greater than
1000 and commission greater than 100 and deptno is either 10 or 20.

select ename from emp


where job in('MANAGER','CLERK')
AND SAL >1000
AND COMM>100
AND DEPTNO IN(10,20);
10.Select employee names in an alphabetical order.
select ename from emp order by ename;

SQL Exercise (Simple Joins)

1. Display employee number, employee name, department name, location from


employee and department tables.
Select empno,ename,dname,loc from emp,dept
where emp.deptno(+)=dept.deptno

2. Display employee number, employee name, salary + comm as TOTAL, location


from employee and department tables.
Select empno,ename,dname,loc,sum(sal+comm) as total from emp,dept
where emp.deptno(+)=dept.deptno
group by empno,ename,dname,loc
/

3. Display employee name, location from employee and department tables.


select ename,loc from emp,dept
where emp.deptno=dept.deptno

4. Diplay employee name, department name, job from employee and department tables
who job is CLERK.
select ename,dname,job from emp,dept
where emp.deptno=dept.deptno
and job='CLERK'

5. Display employee name, deptno, dname from employee and department table where
location is DALLAS.
select ename,A.dEPTNO,DNAME from emp A,dept
where A.deptno=dept.deptno
and LOC='DALLAS'
6. Display employee number, name, address and city from employee, employee
address tables.
Select a.empno,a.ename,b.address,b.city from emp a,address b
Where a.empno=b.empno;

7. Display employee nmae, address from employee and employee address tables
who lives in zip code 75039

Select a.empno,a.ename,b.address,b.city from emp a,address b


Where a.empno=b.empno
And b.zip_code=75039;

8. Display employee name, department name, location who were getting comm as
null.
Select ename,dname,loc from emp,dept
Where emp.deptno=dept.deptno
And comm is null;

9. Display first 3 characters of employee name, job, sal, comm, location from
employee and department tables who works in department 20 or 30, salary
should be more than 1000 comm as not null.

Select substr(ename,1,3),job,sal,comm,loc
From emp,dept
Where emp.deptno=dept.deptno
And emp.deptno in(20,30)
And sal >1000
And comm is not null;

10. Display location, department name, length of location, length of


department name for employee numbers 1001, 1008, 1009.

Select loc,dname,length(loc),length(dname)
From emp,dept where emp.deptno=dept.deptno
And empno in (1001,1008,1009);

Exercise (Group By Clause)

1. Display deptno, number of employee works in each department.

select dept.deptno,count(empno) from emp,dept


where emp.deptno(+)=dept.deptno
group by dept.deptno

2. Display job, number of employees works in each category.


select job,count(empno) from emp
group by job
/

3. Display job and averge salary paid for each jobs in the company.
select job,avg(sal) from emp
group by job
/

4. Display location and sum of the salary spending for employees on that
location respectively.
select loc,sum(sal) from emp,dept
where emp.deptno(+)=dept.deptno
group by loc

5. Select minimum salary, maximum salary in each department.


Select min(sal),max(sal) from emp group by deptno;
6. Select department number, dname, average salary for each department.
Select dept.deptno,dname,avg(sal) from emp,dept
Where dept.deptno=emp.deptno(+)
Group by dept.deptno
7. Select job, number of employees working in that job, maximum and minimum salary
for each job.

Select job,count(empno),max(sal),min(sal)
From emp group by job

8.Select department number, name where atleast 3 employees works.

Select deptno,dname from dept


Where deptno in(select deptno from emp having count(empno) >=3
Group by deptno)
/
9. Select department name, location where the average salary in each
department more than 1600.

select dname,loc from dept


where dept.deptno in (select deptno from emp having avg(sal)>1600 group by
deptno)

10. Select department name, job and sum of salary by each job with in the department.
Select dname,job,sum(sal) from emp,dept
Where emp.deptno=dept.deptno
Group by dname,job

Exercise ( Use SQL Functions )

1. Display the following text in lowercase ‘DISPLAY EXAMPLE IN LOWERCASE'


SELECT LOWER('DISPLAY EXAMPLE IN LOWERCASE') FROM DUAL;

2. Display the following text in uppercase ‘you are great’.


SELECT UPPER('you are great') FROM DUAL;

3. Write a select statement to add 123 and 786.


SELECT SUM(123+786) FROM DUAL;

4. What is the length of ‘CURRENT’ string.


SELECT LENGTH('CURRENT') FROM DUAL;

5. Display the current username.


SELECT USER FROM DUAL;

6. Display ‘DOCTOR’ from ‘JOHN IS A DOCTOR’ string.


SELECT SUBSTR('JOHN IS A DOCTOR',11,6) FROM DUAL;

7. Display Day of 'July-10-1998'


SELECT TO_CHAR(TO_DATE('July-10-1998','Month-dd-rrrr'),'DAY') FROM DUAL

8. Display number of days till today from your date of birth.


select sysdate-TO_DATE('04-SEP-1977','DD-MON-YYYY') FROM DUAL

9. Display the date after 18 months from today.


SELECT ADD_MONTHS(SYSDATE,18) FROM DUAL;
10.Display employee information if employee id is an even number
select * from emp where mod(empno,2)=0;

Exercise ( Date functions from Dual Table)

1.Display Current date


SELECT SYSDATE FROM DUAL

2.Display Current Time.


SELECT TO_CHAR(SYSDATE,'HH:MI:SS') FROM DUAL;

3.Display current user name.


SELECT USER FROM DUAL;

4.Display Current date in July 3 1997 format


SELECT TO_CHAR(SYSDATE,'Month dd RRRR') FROM DUAL;

5.Display Current date and the date after 78 days.


SELECT SYSDATE,SYSDATE+78 FROM DUAL;

6.Display Current date, day, 70 days after current date and its day also.
SELECT SYSDATE,TO_CHAR(SYSDATE,'DAY'),SYSDATE+70,TO_CHAR(SYSDATE+70,'DAY')
FROM DUAL;

7.Display the months between ‘JAN-10-65’ and ‘JUN-23-98’ take the input in
specified format.
select (months_between(to_date('JAN-10-65','MON-DD-RR' ),to_date('JUN-23-
98','MON-DD-RR') ))
from dual
/
8.Display the current date as Today’s date is : current date from system.
SELECT 'Today''s date is : '||sysdate from dual;

9.Display Current date, time and user name.


select sysdate,to_char(sysdate,'hh:mi:ss'),user from dual;

10.Display the day like Sunday or what for this date ‘July 4 1998’
select to_char(to_date('July 4 1998' ,'fmMonthfmdd yyyy'),'Day') from dual

ROWNUMBERING WITH AN ORDER BY CLAUSE

One of the most often uses of the pseudo column rownum is to provide serial numbers to the
records in a query. This feature is widely used in reports to represent systematic display of
information.
For instance

Listing A
Select rownum, ename, empno
from emp10;

Table A

ROWNUM ENAME EMPNO


--------- ---------- ---------
1 KING 7839
2 BLAKE 7698
3 CLARK 7782
4 JONES 7566
5 MARTIN 7654

However, when we order this statement the rownum gets disturbed as shown below ( Listing B
and Table B).

Listing B
select rownum, ename, empno from emp10
order by ename;

Table B
ROWNUM ENAME EMPNO
--------- ---------- ---------
2 BLAKE 7698
3 CLARK 7782
4 JONES 7566
1 KING 7839
5 MARTIN 7654

As we can see from above the employee names did get ordered but the rownum also got the
wrong order. The desired result was BLAKE having rownum 1 , CLARK having a rownum of 2
and so on. To achieve this we have to outer join this table with dual that process forces a implicit
order on the rownum as shown below ( Listing C, Table C).

Listing C
select rownum, ename, empno from emp10 a , dual d
where a.ename = d.dummy (+)
order by ename;

Table C
ROWNUM ENAME EMPNO
------- ---------- ---------
1 BLAKE 7698
2 CLARK 7782
3 JONES 7566
4 KING 7839
5 MARTIN 7654
The trick is to do an outer join with the column that you want to order and this process
does not disturb the rownum order. In addition to that if the column is of number
datatype then one should make sure to use TO_CHAR datatype conversion function.

What are the difference between DDL, DML and DCL commands?
DDL is Data Definition Language statements. Some examples:
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
• COMMENT - add comments to the data dictionary
• GRANT - gives user's access privileges to database
• REVOKE - withdraw access privileges given with the GRANT command
DML is Data Manipulation Language statements. Some examples:
• SELECT - retrieve data from the a database

• INSERT - insert data into a table

• UPDATE - updates existing data within a table

• DELETE - deletes all records from a table, the space for the records remain

• CALL - call a PL/SQL or Java subprogram

• EXPLAIN PLAN - explain access path to data

• LOCK TABLE - control concurrency

DCL is Data Control Language statements. Some examples:


• COMMIT - save work done

• SAVEPOINT - identify a point in a transaction to which you can later roll back

• ROLLBACK - restore database to original since the last COMMIT

• SET TRANSACTION - Change transaction options like what rollback segment to use

How does one escape special characters when building SQL queries?

The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one character, '%'
is used to match zero or more occurrences of any characters. These characters can be escaped in SQL. Example:
SELECT name FROM emp WHERE id LIKE '%\_%' ESCAPE '\';
Use two quotes for every one displayed. Example:
SELECT 'Franks''s Oracle site' FROM DUAL;
SELECT 'A ''quoted'' word.' FROM DUAL;
SELECT 'A ''''double quoted'''' word.' FROM DUAL;

How does one eliminate duplicates rows from a table?


Choose one of the following queries to identify or remove duplicate rows from a table leaving only unique records
in the table:
Method 1:
SQL> DELETE FROM table_name A WHERE ROWID > (
2 SELECT min(rowid) FROM table_name B
3 WHERE A.key_values = B.key_values);
Method 2:
SQL> create table table_name2 as select distinct * from
table_name1;
SQL> drop table_name1;
SQL> rename table_name2 to table_name1;
SQL> -- Remember to recreate all indexes, constraints,
triggers, etc on table...
Method 3: (thanks to Dennis Gurnick)
SQL> delete from my_table t1
SQL> where exists (select 'x' from my_table t2
SQL> where t2.key_value1 = t1.key_value1
SQL> and t2.key_value2 = t1.key_value2
SQL> and t2.rowid > t1.rowid);
Note: One can eliminate N^2 unnecessary operations by creating an index on the joined fields in the inner loop (no
need to loop through the entire table on each pass by a record). These will speed-up the deletion process.
Note 2: If you are comparing NOT-NULL columns, use the NVL function. Remember that
NULL is not equal to NULL. This should not be a problem as all key columns should be NOT
NULL by definition.
How does one generate primary key values for a table?

Create your table with a NOT NULL column (say SEQNO). This column can now be populated with unique values:
SQL> UPDATE table_name SET seqno = ROWNUM;
or use a sequences generator:
SQL> CREATE SEQUENCE sequence_name START WITH 1
INCREMENT BY 1;
SQL> UPDATE table_name SET seqno = sequence_name.NEXTVAL;
Finally, create a unique index on this column.

How does one get the time difference between two date columns?

Look at this example query:


select floor(((date1-date2)*24*60*60)/3600)
|| ' HOURS ' ||
floor((((date1-date2)*24*60*60) -
floor(((date1-date2)*24*60*60)/3600)*3600)/60)
|| ' MINUTES ' ||
round((((date1-date2)*24*60*60) -
floor(((date1-date2)*24*60*60)/3600)*3600 -
(floor((((date1-date2)*24*60*60) -
floor(((date1-
date2)*24*60*60)/3600)*3600)/60)*60)))
|| ' SECS ' time_difference
from ...
If you don't want to go through the floor and ceiling math, try this method (contributed by Erik
Wile):
select to_char(to_date('00:00:00','HH24:MI:SS') +
(date1 - date2), 'HH24:MI:SS')
time_difference
from ...
Note that this query only uses the time portion of the date and ignores the date itself. It will thus
never return a value bigger than 23:59:59.

How does one add a day/hour/minute/second to a date value?

The SYSDATE pseudo-column shows the current system date and time. Adding 1 to SYSDATE will advance the
date by 1 day. Use fractions to add hours, minutes or seconds to the date. Look at these examples:
SQL> select sysdate, sysdate+1/24, sysdate +1/1440,
sysdate + 1/86400 from dual;

SYSDATE SYSDATE+1/24 SYSDATE+1/1440


SYSDATE+1/86400
-------------------- --------------------
-------------------- --------------------
03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002
08:33:12 03-Jul-2002 08:32:13
The following format is frequently used with Oracle Replication:
select sysdate NOW, sysdate+30/(24*60*60)
NOW_PLUS_30_SECS from dual;

NOW NOW_PLUS_30_SECS
-------------------- --------------------
03-JUL-2002 16:47:23 03-JUL-2002 16:47:53

How does one count different data values in a column?

Use this simple query to count the number of data values in a column:
select my_table_column, count(*)
from my_table
group by my_table_column;
A more sophisticated example...
select dept, sum( decode(sex,'M',1,0)) MALE,
sum( decode(sex,'F',1,0)) FEMALE,
count(decode(sex,'M',1,'F',1)) TOTAL
from my_emp_table
group by dept;

How does one count/sum RANGES of data values in a column?

A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at this example:
select f2,
sum(decode(greatest(f1,59), least(f1,100), 1, 0))
"Range 60-100",
sum(decode(greatest(f1,30), least(f1, 59), 1, 0))
"Range 30-59",
sum(decode(greatest(f1, 0), least(f1, 29), 1, 0))
"Range 00-29"
from my_table
group by f2;
For equal size ranges it might be easier to calculate it with DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...).
Eg.
select ename "Name", sal "Salary",
decode( trunc(f2/1000, 0), 0, 0.0,
1, 0.1,
2, 0.2,
3, 0.31) "Tax rate"
from my_table;

Can one retrieve only the Nth row from a table?

provided this solution to select the Nth row from a table:


SELECT * FROM (
SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 )
WHERE RN = 100;
Note: Note: In this first it select only one more than the required row, then it selects the required one. Its far better
than using MINUS operation.
provided this solution:
SELECT f1 FROM t1
WHERE rowid = (
SELECT rowid FROM t1
WHERE rownum <= 10
MINUS
SELECT rowid FROM t1
WHERE rownum < 10);
Alternatively...
SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN
(SELECT rowid FROM emp WHERE rownum < 10);
Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even
help in the odd situation.

Can one retrieve only rows X to Y from a table?

provided this solution to the problem:


SELECT * FROM (
SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101
) WHERE RN between 91 and 100 ;
Note: the 101 is just one greater than the maximum row of the required rows (means x= 90, y=100, so the inner
values is y+1).
Another solution is to use the MINUS operation. For example, to display rows 5 to 7, construct a
query like this:
SELECT *
FROM tableX
WHERE rowid in (
SELECT rowid FROM tableX
WHERE rownum <= 7
MINUS
SELECT rowid FROM tableX
WHERE rownum < 5);
Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even
help in the odd situation.

How does one select EVERY Nth row from a table?

One can easily select all even, odd, or Nth rows from a table using SQL queries like this:
Method 1: Using a subquery
SELECT *
FROM emp
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4)
FROM emp);
Method 2: Use dynamic views (available from Oracle7.2):
SELECT *
FROM ( SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.ROWNUM,4) = 0;
Please note, there is no explicit row order in a relational database. However, these queries are quite fun and may
even help in the odd situation.

How does one select the TOP N rows from a table?

Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example:
SELECT *
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC)
WHERE ROWNUM < 10;
Use this workaround with prior releases:
SELECT *
FROM my_table a
WHERE 10 >= (SELECT COUNT(DISTINCT maxcol)
FROM my_table b
WHERE b.maxcol >= a.maxcol)
ORDER BY maxcol DESC;

How does one code a tree-structured query?

Tree-structured queries are definitely non-relational (enough to kill Codd and make him roll in his grave). Also, this
feature is not often found in other database offerings.
The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation
(EMPNO and MGR columns). This table is perfect for tesing and demonstrating tree-structured
queries as the MGR column contains the employee number of the "current" employee's boss.
The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can handle
queries with a depth of up to 255 levels. Look at this example:
select LEVEL, EMPNO, ENAME, MGR
from EMP
connect by prior EMPNO = MGR
start with MGR is NULL;
One can produce an indented report by using the level number to substring or lpad() a series of spaces, and
concatenate that to the string. Look at this example:
select lpad(' ', LEVEL * 2) || ENAME ........
One uses the "start with" clause to specify the start of the tree. More than one record can match the starting
condition. One disadvantage of having a "connect by prior" clause is that you cannot perform a join to other tables.
The "connect by prior" clause is rarely implemented in the other database offerings. Trying to do this
programmatically is difficult as one has to do the top level query first, then, for each of the records open a cursor to
look for child nodes.
One way of working around this is to use PL/SQL, open the driving cursor with the "connect by
prior" statement, and the select matching records from other tables on a row-by-row basis,
inserting the results into a temporary table for later retrieval.

How does one code a matrix report in SQL?


Look at this example query with sample output:
SELECT *
FROM (SELECT job,
sum(decode(deptno,10,sal)) DEPT10,
sum(decode(deptno,20,sal)) DEPT20,
sum(decode(deptno,30,sal)) DEPT30,
sum(decode(deptno,40,sal)) DEPT40
FROM scott.emp
GROUP BY job)
ORDER BY 1;

JOB DEPT10 DEPT20 DEPT30 DEPT40


--------- ---------- ---------- ---------- ----------
ANALYST 6000
CLERK 1300 1900 950
MANAGER 2450 2975 2850
PRESIDENT 5000
SALESMAN 5600

How does one implement IF-THEN-ELSE in a select statement?

The Oracle decode function acts like a procedural statement inside an SQL statement to return different values or
columns based on the values of other columns in the select statement.
Some examples:
select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown')
from employees;

select a, b, decode( abs(a-b), a-b, 'a > b',


0, 'a = b',
'a < b') from
tableX;

select decode( GREATEST(A,B), A, 'A is greater OR EQUAL


than B', 'B is greater than A')...

select decode( GREATEST(A,B),


A, decode(A, B, 'A NOT GREATER THAN B', 'A
GREATER THAN B'),
'A NOT GREATER THAN B')...
Note: The decode function is not ANSI SQL and is rarely implemented in other RDBMS offerings. It is one of the
good things about Oracle, but use it sparingly if portability is required.
From Oracle 8i one can also use CASE statements in SQL. Look at this example:
SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE
'Under paid' END
FROM emp;
How can one dump/ examine the exact content of a
database column?
SELECT DUMP(col1)
FROM tab1
WHERE cond1 = val1;

DUMP(COL1)
Typ=96 Len=4: 65,66,67,32

Can one drop a column from a table?

From Oracle8i one can DROP a column from a table. Look at this sample script, demonstrating the ALTER TABLE
table_name DROP COLUMN column_name; command.
Other workarounds:
1. SQL> update t1 set column_to_drop = NULL;
SQL> rename t1 to t1_base;
SQL> create view t1 as select <specific columns> from t1_base;

2. SQL> create table t2 as select <specific columns> from t1;


SQL> drop table t1;
SQL> rename t2 to t1;

Can one rename a column in a table?


No, this is listed as Enhancement Request 163519. Some workarounds:
1. -- Use a view with correct column names...
rename t1 to t1_base;
create view t1 <column list with new name> as select * from
t1_base;

2. -- Recreate the table with correct column names...


create table t2 <column list with new name> as select * from
t1;
drop table t1;
rename t2 to t1;

3. -- Add a column with a new name and drop an old column...


alter table t1 add ( newcolame datatype );
update t1 set newcolname=oldcolname;
alter table t1 drop column oldcolname;
How can I change my Oracle password?

Issue the following SQL command: ALTER USER <username> IDENTIFIED BY


<new_password>

From Oracle8 you can just type "password" from SQL*Plus, or if you need to change another
user's password, type "password user_name".
How does one find the next value of a sequence?

Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequence numbers from the Oracle
library cache. This way, no cached numbers will be lost. If you then select from the USER_SEQUENCES dictionary
view, you will see the correct high water mark value that would be returned for the next NEXTVALL call.
Afterwards, perform an "ALTER SEQUENCE ... CACHE" to restore caching.
You can use the above technique to prevent sequence number loss before a SHUTDOWN
ABORT, or any other operation that would cause gaps in sequence values.
Workaround for snapshots on tables with LONG columns

You can use the SQL*Plus COPY command instead of snapshots if you need to copy LONG and LONG RAW
variables from one location to another. Eg:
COPY TO SCOTT/TIGER@REMOTE -
CREATE IMAGE_TABLE USING -
SELECT IMAGE_NO, IMAGE -
FROM IMAGES;
Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated.

You might also like