Вы находитесь на странице: 1из 247

SQL Function Reference

This appendix outlines various functions you will encounter in the Oracle database, the syntax used to
call the function, and an example or two for each to help provide context to the explanation.

Many of the examples use a table called DUAL to query against, so we'll explain that first, and then go
on to look at:

0 NUMBER Functions

0 DATETIME Functions

0 CHARACTER Functions

0 CONVERSION Functions

0 AGGREGATION Functions

DUAL
There is a table defined in the Oracle data dictionary named DUAL. This table is provided so a
developer performing a query or writing a function can guarantee a known result. The table has one
column named DUMMY of type VARCHAR ( 1) , and there is one row in the table with the value X.

SQL> select * from dual;

DUMMY

You might be asking yourself how one column, one row, and one table equate to guaranteeing a known
result. Well, if you select a constant value {such as a string literal) or an expression from any table, the
result will be returned once for each row of the result set. In the case of DUAL, this means that we
always return one result:
Appendix A

SQL> select 'BLAH'


2 from dual;

'BLA

BLAH

1 row selec t ed .

As you can see, when we select a string literal value from the table, the literal value is returned once.

You can use the DUAL table to do math, using SQL queries to return one value. We'll see many
examples of how this is done in this appendix.

DUAL is used extensively by Oracle, so care should be taken to never insert, update, or
delete from DUAL. Violating this rule is very dangerous for your database, as there are
many internal operations that Oracle performs which are dependent on DUAL. User-
written PLISQL and stored queries may also be dependent upon DUAL, and errors or
wrong answers may be uncovered if the DUAL table is modified.

NUMBER Functions
Oracle has a variety of functions to process and manipulate number values in the database. The
following table lists some of the more common number functions available in the Oracle database:

ABS() MOD() SIGN()

CEIL() POWER() TRUNC()

FLOOR() ROUND()

ABS()
The ABS ( ) function is used to get the absolute value of the parameter passed to the function.

SQL> select abs(13.4)


2 from dual
3 I

ABS(l3 . 4)

13 . 4

856
SQL Function Reference

SQL> select abs(-4.5)


2 from dual
3 I

ABS(-4.5)

4.5

SQL> select abs(-70 * 415) •using an expression•


2 from dual
3 I

Using an expression

29050

CEIL()
This function returns the next smallest integer value greater than or equal to the parameter passed in.

number_value := CEIL( number_value

SQL> select ceil( 10.00000000001 )


2 from dual;

CEIL(l0.00000000001)

11

SQL> select ceil( -1.99


2 from dual
3 I

CEIL(-1.99)

-1

FLOOR()
The opposite of CEIL ( ) , FLOOR ( ) returns the largest integer value less than or equal to the parameter
passed in.

number_value := FLOOR( number_value )

SQL> select floor( 10 . 00000000001


2 from dual
3 I

857
Appendix A

FLOOR(10.00000000001)

10

SQL>
SQL> select floor( -1 . 99 )
2 from dual
3 I

FLOOR ( -1 . 9 9 )

-2

MOD()
MOD ( ) returns the remainder of a division operation.

number_value := MOD( numerator, denominator

SQL> select mod( 11,2


2 from dual 1
3 I

MOD(l1,2)

SQL> select mod( 150.12, 2.6 )


2 from dual
3 I

MOD(150 . 12,2.6)

1. 92

POWER(}
POWER ( ) returns the first number, raised to the power of the second number.

number_value := POWER( base_number, to_the_power_of )

SQL> select power( 10, 5 )


2 from dual
3 I

POWER(l0,5)

100000

858
SQL Function Reference

SQL> select power( -5, 3 ) •using Negatives•


2 from dual
3 I

Using Negatives

-125

SQL> select power( 5.2, 2.7 ) "With Reals"


2 from dual
3 I

With Reals

85.7450441

ROUND()
The ROUND ( ) function rounds a number up either to the left or right of a decimal point, depending on
the sign of the second parameter. The second parameter must be an integer. If the second parameter is
negative, the first number is rounded up to that many digits to the left of the decimal point. A positive
second value means the first number is rounded up to that many digits to the right of the decimal.

number_value := ROUND(bas e_number [ , integer_indicating_number_of_digits ])

SQL> select round( 12345.67890 )


2 from dual
3 I

ROUND(12345.67890)

12346

SQL> select round( 12345.67890, 2 )


2 from dual
3 I

R00ND(12345.67890,2)

12345 . 68

SQL> select round( 12345.67890, -2 )


2 from dual
3 I

ROUND(12345.67890,-2)

12300

859
Appendix A

SIGN()
SIGN () takes one parameter, and returns either a -1, 0, or 1 depending on whether the parameter is
less than zero (-1), zero (0), or greater than zero (1).

nurnber_value := SIGN( nurnber_value

SQL> select sign( 123 )


2 from dual
3 I

SIGN(123)

SQL> select sign( 100 - ( 50 * 2 ) ) •using expressions•


2 from dual
3 I

Using expressions

SQL> select sign( 123 * -1 + 122) ·using expressions•


2 from dual
3 I

Using expressions

-1

TRUNC()
The TRUNC ( ) function drops all digits a number up either to the left or right of a decimal point,
depending on the sign of the second parameter. The second parameter must be an integer. If the second
parameter is negative, the first number is truncated to that many digits left of the decimal point. A
positive second value means the first number is truncated to that many digits right of the decimal.

nurnber_value := TRUNC(base_nurnber [, integer_indicating_nurnber_of_digits ])

SQL> select trunc( 12345.67890 )


2 from dual
3 I

TRUNC(12345.67890)

12345

SQL> select trunc( 12345.67890, 2 )

860
SQL Function Reference

2 from dual
3 I

TRUNC(l2345.67890,2)

12345.67

SQL> select trunc( 12345.67890, -2 )


2 from dual
3 I

TRUNC(l2345.67890,-2)

12300

DATETIME Functions
In order to process and manipulate dates, Oracle provides a number of functions that operate on the
various date-related data types in Oracle.

ADD_MONTHS ( ) LAST_DAY() NUMTOYMINTERVAL()

CURRENT_DATE () LOCALTIMESTAMP() ROUND()

CURRENT_TIMESTAMP() MONTHS_BETWEEN() SYSTIMESTAMP ( )

DBTIMEZONE ( ) NEXT_DAY() SYSDATE()

EXTRACT() NUMTODSINTERVAL() TRUNC()

ADD_MONTHS()
This function is used to add or subtract a number of months to/from a date value.

date_value := ADD_MONTHS( date_value, number_of_months

If today is 3ro November 2001 then:

SQL> select add_months( sysdate, 12 ) "Next Year•


2 from dual
3 I

Next Year

03-NOV-02

SQL> select ad~onths( sysdate, -12 ) "Last Year•


2 from dual

861
Appendix A

3 I

Last Year

03-NOV-00

CURRENT_DATE{)
The CURRENT_DATE () function returns the current date in the current session's time zone (which can
be altered}.

date_value .- CURRENT_DATE

SQL> column sessiontimezone for al5


SQL> select sessiontimezone, current_date
2 from dual
3 I

SESSIONTIMEZONE CURRENT_DATE

-05:00 03-nov-2001 09:03:56

SQL> alter session set time_zone = '-08:00'


2 I

Session altered.

SQL> select sessiontimezone, current_date


2 from dual
3 I

SESSIONTIMEZONE CURRENT_DATE

-08:00 03-nov-2001 06:05:16

CURRENT_TIMESTAMP{)
The CURRENT_TIMESTAMP () function returns the current date in a TIMESTAMP WITH TIME ZONE
data type in the current session's time zone (which can be altered}. The precision of the TIMESTAMP
value returned can optionally be specified as a parameter to the CURRENT_TIMESTAMP () function.

timestarnp_with_time_zone_value := CURRENT_TIMESTAMP([timestarnp_precision])

SQL> column sessiontirnezone for al5


SQL> col current_timestarnp format a36
SQL> select sessiontimezone, current_timestamp
2 from dual
3 I

862
SQL Function Reference

SESSIONTIMEZONE CURRENT_TIMESTAMP

-08:00 03-NOV-01 06.10.45.000000 AM -08:00

SQL> alter session set time_zone = '-11:00'


2 I

Session altered.

SQL> select sessiontimezone, current_timestamp(3) current_timestamp


2 from dual
3 I

SESSIONTIMEZONE CURRENT_TIMESTAMP

-11:00 03-NOV-01 03.11 . 53.000 AM -11:00

DBTIMEZONE{)
This function returns the time zone that was specified in the CREATE DATABASE statement, or the most
recent ALTER SYSTEM SET TIME ZONE statement.

varchar_value .- DBTIMEZONE

SQL> select DBTIMEZONE


2 from dual
3 I

DBTIME

-05:00

EXTRACT(}
The EXTRACT ( ) function is used to find out the value of a field of a datetime or interval value. There
are a variety of date fields available to the EXTRACT ( ) function, including:

SECOND YEAR
MINUTE TIMEZONE_MINUTE
HOUR TIMEZONE_HOUR
DAY TIMEZONE_REGION
MONTH TIMEZONE_ABBR

date_value := EXTRACT( date_field FROM [ datetime_value interval_value ])

863
Appendix A

SQL> select extract( month from sysdate ) "This Month'


2 from dual
3 I

This Month

11

SQL> select extract( year from ad~onths(sysdate,36) ) "3 Years Out'


2 from dual
3 I

3 Years Out

2004

LAST_DAY()
The LAST_DAY () function returns the date of the last day of the month containing the date parameter.

date_value := LAST_DAY{ date_value )

SQL> select last_day{ date'2000-02-01' ) "Leap Yr?"


2 from dual
3 I

Leap Yr?

29-FEB-00

SQL> select last_day{ sysdate ) 'Last day of this month'


2 from dual
3 I

Last day

30-NOV-01

LOCALTIMESTAMP()
This function returns the date and time in the current session's time zone in a TIMESTAMP value.

timestamp_value := LOCALTIMESTAMP

SQL> column localtimestamp format a28


SQL> select localtimestamp
2 from dual
3 I

864
SQL Function Reference

LOCALTIMESTAMP

03-NOV-01 10.40.20.000001 AM

SQL> select localtimestamp, current_timestamp


2 from dual
3 I

LOCALTIMESTAMP CURRENT_TIMESTAMP

03-NOV-01 10.42.30 . 000000 AM 03-NOV-01 10 . 42.30.000000 AM -05 : 00

SQL> alter session set time_zone = '-08:00'


2 I .

Session altered.

SQL> select localtimestamp,


2 to_char(sysdate, 'DD-MON-YY HH:MI:SS AM') "SYSDATE"
3 from dual
4 I

LOCALTIMESTAMP SYSDATE

03-NOV-01 08.02.10.000000 AM 03-NOV-01 11:02:10 AM.

MONTHS_BETWEEN()
The MONTHS_BETWEEN ( ) function determines the number of months between two dates. The value
returned is a real number indicating the whole months and a fraction of the month between the two
dates. If the first date is earlier in time than the second date, the value returned is a negative number.

number_value := MONTHS_BETWEEN( date_value, date_value }

SQL> select months_between( sysdate, date'1971-05-18' )


2 from dual
3 I

MONTHS_BETWEEN(SYSDATE,DATE'1971-05-18')

365 . 534266

SQL> select months_between( sysdate, date'2001-01-01'


2 from dual
3 I

MONTHS_BETWEEN(SYSDATE,DATE'2001-01-01')

10.0826695

865
Appendix A

NEXT_DAY()
Given a datetime value, the NEXT_DAY () function returns a date value of the first occurrence of the day
indicated in the second parameter (a character string of the name of the day that should be returned).

date_value := NEXT_DAY( date_value, day_of_the_week

SQL> select next_day( date'2001-09-ll', 'SUNDAY' )


2 from dual
3 I

NEXT_DAY(

16-SEP-01

SQL> select next_day( date'2002-01-01', 'FRI' )


2 from dual
3 I

NEXT_DAY(

04-JAN-02

NUMTODSINTERVAL()
NUMTODSINTERVAL () accepts a number and a character value representing which part of the
INTERVAL DAY TO SECOND should be populated by the function. Valid character values are SECOND,
MINUTE, HOUR, and DAY.

interval_day_to_second_value := NUMTODSINTERVAL( number, type_of_interval )

SQL> column current_timestamp format a38


SQL> select current_timestamp
2 from dual
3 I

CURRENT_TIMESTAMP

03-NOV-01 01 .05.57.000001 PM -08:00

SQL> select current_timestamp + numtodsinterval( 2, 'hour' ) current_timestamp


2 from dual
3 I

CURRENT_TIMESTAMP

03-NOV-01 03 .06.25 . 000001000 PM -08:00

866
SQL Function Reference

NUMTOYMINTERVAL()
NUMTOYMINTERVAL ( ) accepts a number and a character value representing which part of the
INTERVAL YEAR TO MONTH should be populated by the function. Valid character values are YEAR
and MONTH.

interval_year_to_month_value .- NUMTODSINTERVAL( number, type_of_interval )

SQL> select current_timestamp


2 from dual
3 I

CURRENT_TIMESTAMP

03-NOV-01 01.10.48.000001 PM -08:00

SQL> select current_timestamp + numtoyminterval( 3, 'month' ) current_timestamp


2 from dual
3 I

CURRENT_TIMESTAMP

03-FEB-02 01.11.22.000000000 PM -08:00

ROUND()
ROUND returns a datetime value formatted to the next highest part of a date, optionally indicated by a
character-based format parameter. (Valid formats can be found at the end of this section.)

date_value .- ROUND( date_value [, format_mask ] )

SQL> select round( sysdate )


2 from dual
3 I

ROUND(SYS
---------
04-NOV-01

SQL> select round( sysdate, 'year~ )


2 from dual
3 I

ROUND(SYS
---------
01-JAN-02

SQL> select round( sysdate, 'month' )


2 from dual

867
Appendix A

3 I

ROUND(SYS

01-NOV-01

SQL> select round( sysdate, 'q' ) "Quarter•


2 from dual
3 I

Quarter

01-0CT-01

SYSDATE()
This function returns the current date and time in a DATE value, based on the database's time zone.

date_value := SYSDATE

SQL> select sysdate


2 from dual
3 I

SYSDATE

03-NOV-01

SQL> select to_char(sysdate, 'DD-MON-YY HH24:MI:SS' ) "Right Now•


2 from dual
3 I

Right Now

03-NOV-01 16:44:50

SYSTIMESTAMP(}
This function returns the current time and date in a TIMESTAMP WITH TIME ZONE value, based on the
time zone of the database.

timestamp_with_time_zone_value := SYSTIMESTAMP

SQL> select systimestamp


2 from dual
3 I

SYSTIMESTAMP

03-NOV-01 04.46.24.000000 PM -05:00

868
SQL Function Reference

TRUNC(}
The TRUNC () function retums a DATE value truncated to the value optionally specified in the format
mask parameter. For more information about format masks, see the section below entitled 'Date Format
Models for ROUND () and TRUNC () '.

date_value := TRUNC( date_value [, format_mask ] }

SQL> select trunc( sysdate }


2 from dual
3 I

TRUNC(SYS

03-NOV-01

SQL> select to_char( trunc( sysdate, 'HH' ),


2 '00-MON-YY HH24:MI:SS' ) 'The Current Hour•
3 from dual
4 I

The Current Hour

03-NOV-01 16:00:00

Date Format Models for ROUND(} and TRUNC(}


The following format masks are available for use in the date-related ROUND ( ) and TRUNC ( ) functions:

0 Year:YYYY,YYY,YY,Y,YEAR
0 Quarter: Q

0 Month: MONTH, MON, MM, RM


0 Day: DDD,DD,J
0 Starting day of the week: DAY, DY, D
0 Hour:HH,HH12,HH24
0 Minute: MI

Some rules regarding the various dimensions of the date field when used with ROUND ( ) :

0 Years round up onJuly 1.


0 Quarters round up on the 16th day of the second month in the quarter.

869
Appendix A

CHARACTER Functions
Oracle provides plenty of functions for working with string values in SQL and PLISQL. The following
table lists all those functions that are described below:

CHR() LPAD() TRANSLATE ( )

INITCAP () REPLACE () TRIM()

INSTR() RPAD() UPPER()

LENGTH() SOUNDEX()

LOWER() SUBSTR()

CHR()
The CHR ( ) function is used for retrieving a character in the database character set, or the national
character set identified by the binary number parameter. This is especially useful for characters that
cannot be identified using a keyboard. In order to use the national character set, you may optionally use
the USING NCHAR_CS clause.

character_value := CHR( nurnber_value [ USING NCHAR_CS ] }

SQL> select chr(71) llchr(ll4) llchr(111) llchr(l11) lichr(l18) llchr(l2ll •cool! •


2 from dual
3 I

Cool!

Groovy

INITCAP()
The INITCAP () function is for making the first word in each word of the character string passed to the
function upper case, and the rest of the letters lower case.

character_value := INITCAP( character_value

SQL> select initcap('THESE WORDS will be INITcapped')


2 from dual
3 I

INITCAP('THESEWORDSWILLBEINITC

These Words Will Be Initcapped

SQL> select initcap( table_name

870
SQL Function Reference

2 from user_tables
3 I

INITCAP(TABLE_NAME)

Bonus
Casepartyaddress
Courses
Dept
Emp
Employees
Salgrade
Subjects

8 rows selected.

INSTR(}
INSTR ( ) is useful when you are trying to determine the numeric position of a particular search string
within a character string, or iterating through a document looking for multiple instances of a character
string. In the syntax below, you will see you can tell Oracle to look for the nth instance of a particular
search string, instead of simply the first iteration. You can also give Oracle a position from which to
begin its search.

numeric_value .- INSTR( character_value, search_string


[, start_position [, occurrence ] ] )

SQL> select instr( 'Where is the fourth letter E in this sentence?', 'e', 1, 4)
2 from dual
3 I

INSTR('WHEREISTHEFOURTHLETTEREINTHISSENTENCE?', 'E',l,4 )

22

LENGTH()
Passing a character string to the LENGTH ( ) function returns the number of characters in the string.

number_value := LENGTH( character_value

SQL> select ename, length( ename )


2 from emp
3 I

ENAME LENGTH ( ENAME)

SMITH 5

871
Appendix A

ALLEN 5
WARD 4
JONES 5
MARTIN 6
BLAKE 5
CLARK 5
SCOTT 5
KING 4
TURNER 6
ADAMS 5
JAMES 5
FORD 4
MILLER 6

14 rows selected.

LOWER()
Passing a character string to the LOWER ( ) function causes every character in the string to be converted
to lower case.

character_value := LOWER( character_value

SQL> select lower( table_name


2 from user_tables
3 I

LOWER(TABLE_NAME)

bonus
casepartyaddress
courses
dept
emp
employees
salgrade
subjects

8 rows selected.

LPAD()
The LPAD () function takes the first character-based argument, and pads out the left-hand side for n
number of characters (the second parameter} with either spaces or characters in the optional character-
based third parameter.

character_value := LPAD( character_value, number_of_characters_to_pad


[, characters_to_pad_with ) )

872
SQL Function Reference

SQL> select lpad( '.' 5, I. I )

2 from dual
3 I

LPAD(

*****

SQL> column empname format al5


SQL> select lpad( '. ', 2*level, ' ' ) I I e.ename empname,
2 d.dname, e . job
3 from emp e, dept d
4 where e . deptno = d.deptno
5 start with e.mgr is null
6 connect by prior e.empno = e.mgr
7 I

EMPNAME DNAME JOB

. . KING ACCOUNTING PRESIDENT


.. . . JONES RESEARCH MANAGER
..... . SCOTT RESEARCH ANALYST
.. .... .. ADAMS RESEARCH CLERK
.. . .. . FORD RESEARCH ANALYST
........ SMITH RESEARCH CLERK
. . .. CLARK ACCOUNTING MANAGER
. . .... MILLER ACCOUNTING CLERK
•.•• BLAKE SALES MANAGER
...... ALLEN SALES SALESMAN
•.•.•• WARD SALES SALESMAN
. ..... JAMES SALES CLERK
...... TURNER SALES SALESMAN
...... MARTIN SALES SALESMAN

14 rows selected.

LTRIM()
The LTRIM ( ) function trims leading spaces, or a designated character, off the front of a character string.

character_value .- LTRIM( character_value [, character_to_trim ] )

SQL> select '"' II ltrim( ' Some String' ) I I '"' "A String•
2 from dual
3 I

A String

"Some String•

873
Appendix A

REPLACE(}
The REPLACE ( ) function allows you to replace a sequence of characters with a different sequence of
characters. The third parameter, the replacement value, is optional. Not passing a replacement value
will simply strip the search string from the original string.

character_value := REPLACE( character_value,


search_string [, replacement_value ] )

SQL> select replace( 'Oracle is great!', 'great', 'awesome' )


2 from dual
3 I

REPLACE('ORACLEISG

Oracle is awesome!

RPAD(}
The RPAD () function takes the first character-based argument, and pads out the right-hand side for n
number of characters (the second parameter) with either spaces or characters defined in the optional
(character-based) third parameter.

character_value .- RPAD( character_value, number_of_characters_to_pad


[, characters_to_pad_with ] )

SQL> select rpad( '*' 5, ' .. ' )


2 from dual
3 I

RPAD(

*****
SQL> select rpad( ename, 10, ' ' ) II ' (' II job II ')' "Responsibilities•
2 from emp
3 order by ename
4 I

Responsibilities

ADAMS (CLERK)
ALLEN (SALESMAN)
BLAKE (MANAGER)
CLARK (MANAGER)
FORD (ANALYST)
JAMES (CLERK)
JONES (MANAGER)
KING (PRESIDENT)

874
SQL Function Reference

MARTIN (SALESMAN)
MILLER (CLERK)
SCOTT (ANALYST)
SMITH (CLERK)
TURNER (SALESMAN)
WARD (SALESMAN)

14 rows selected.

RTRIM()
The RTRIM ( ) function trims trailing spaces, or a designated character, off the end of a character string.

character_value .- RTRIM( character_value [, character_to_trim ] )

SQL> select'"' II rtrim( 'Some String ' ) II '"' "A String•


2 from dual
3 I

A String

"Some String•

SOUNDEX()
This function returns a character string that represents the way a word or character string 'sounds'. This
function can then be applied to two character strings that are not spelt the same, but 'sound the same'.

character_phonetic_representation := SOUNDEX( character_value

SQL> select e.employee_id, e.last_name, e2.employee_id, e2.last_name


2 from employees e, employees e2
3 where e.employee_id != e2.employee_id
4 and soundex( e.last_name ) = soundex( e2.last_name
5 I

EMPLOYEE_ID LAST_NAME EMPLOYEE_ID LAST~AME

156 King 100 King


153 Olsen 132 Olson
154 Ca.mbrault 148 Ca.mbrault
132 Olson 153 Olsen
148 Ca.mbrault 154 Ca.mbrault
100 King 156 King
161 Sewall 157 Sully
194 McCain 158 McEwen
171 Smith 159 Smith
157 Sully 161 Sewall

875
Appendix A

159 Smith 171 Smith


180 Taylor 176 Taylor
199 Grant 178 Grant
176 Taylor 180 Taylor
192 Bell 185 Bull
206 Gietz 190 Gates
185 Bull 192 Bell
158 McEwen 194 McCain
178 Grant 199 Grant
190 Gates 206 Gietz

20 rows selected.

SUBSTR(}
SUBSTR ( ) is used to extract a piece of a character string. Parameters include the source string to extract
from, the position where Oracle should begin extracting, and an optional length parameter. The
position parameter can be positive or negative. A negative position parameter indicates to count back
from the end of the string for that many characters, rather than counting forward from the beginning of
the string.

character_value := SUBSTR( character_string, position [, length J )

SQL> select substr( '1234567890', 5 )


2 from dual
3 I

SUBSTR

567890

TRANSLATE(}
The TRANSLATE () function modifies a character string by converting all those characters in the search
string with the corresponding characters in the translation string. If the search string has no
corresponding value in the translation string parameter, NULL is used to replace that character in the
result. If NULL is passed as the search string, the return value is NULL.

character_value .- TRANSLATE( character_value, search_string,


translation_string

SQL> select translate('l910 Oracle Way',


2
'1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklrnnopqrstuvwxyz',
3 '1234567890') 'Number Portion Only"
4 from dual
5 I

876
SQL Function Reference

Number

1910

SQL> select length(


2 translate('how many consonants are there?',
3 'bcdfghjklmnpqrstvwxzaeiouy? '
4 'bcdfghj klmnpqrs tvwxz' )
5 ) 'i of consonants'
6 from dual
7 I

# of consonants

15

TRIM(}
The TRIM () function trims leading and/or trailing characters from the beginning and/or end of a
character string.

character_value := TRIM( [ { { LEADING I TRAILING BOTH }


[character_to_trim ] I
character_to_trim } FROM character_value

SQL> select''' II trim( ' ' from' This is a string ' ) II ' ' ' 'Result'
2 from dual
3 I

Result

'This is a string•

SQL> select trim( trailing ' ' from 'This is a string ' ) "Result •
2 from dual
3 I

Result

This is a string

UPPER(}
The UPPER ( ) function is used to convert all the characters in a string to upper case.

character_value .- UPPER( character_value

877
Appendix A

SQL> connect hr/hr


SQL> select department_name, upper( department_narne )
2 from departments
3 where rownum < 11
4 order by department_name
5 I

DEPARTMENT_ftAME UPPER (DEPARTMENT_ftAME)

Administration ADMINISTRATION
Executive EXECUTIVE
Finance FINANCE
Human Resources HUMAN RESOURCES
IT IT
Marketing MARKETING
Public Relations PUBLIC RELATIONS
Purchasing PURCHASING
Sales SALES
Shipping SHIPPING

10 rows selected.

CONVERSION Functions
Oracle provides plenty of functions for working with string values in SQL and PLISQL.

CAST() TO_NCLOB () TO_TIMESTAMP ( )

CHARTOROWID ( ) TO_DATE () TO_TIMESTAMP_TZ()

TO_CHAR() TO_DSINTERVAL () TO_YMINTERVAL()

TO_NCHAR() TO_LOB () TRANSLATE ... USING ( )

TO_CLOB () TO_NUMBER ( )

CAST()
The CAST ( ) function converts a value of one data type into a value of another data type. Oracle is very
good about performing this functionality for you for standard scalar types, but this is especially useful
for collection types. Used with the MULTI SET () function, collection objects can be constructed from
queries.

return_value := CAST( [ expression I subquery I MULTISET ( subquery } ] AS type }

SQL> create type vc2tab as table of varchar2(4000)


2 I
Type created .

878
SQL Function Reference

SQL> declare
2 l_enames vc2tab;
3 begin
4 select cast( multiset ( select ename from emp ) as vc2tab )
5 into l_enames
6 from dual;
7
8 for i in 1 .. l_enames.count loop
9 dbms_output.put_line(l_enames(i));
10 end loop;
11 end;
12 I
SMITH
ALLEN
WARD
JONES

JAMES
FORD
MILLER

PL/SQL procedure successfully completed.

CHARTOROWID()
This function is for creating a ROWID value from a character-based representation of a ROWID.

rowid_value := CHARTOROWID( character_value

SQL> select empno, ename, job, hiredate


2 from emp
3 where rowid = chartorowid('AAAHqXAABAAAR74AAI ' )
4 I

EMPNO ENAME JOB HIREDATE

7839 KING PRESIDENT 17-NOV-81

TO_CHAR()
There are three types of TO_CHAR ( ) functions.

TO_CHAR( character)
The character-based TO_CHAR ( ) function is for transforming a CLOB, NCLOB, or NCHAR value into the
database character set.

character_value .- TO_CHAR( clob_value nclob_value nchar_value

879
Appendix A

SQL> create table xmldata(


2 xmldoc clob l
3 I

Table created.

SQL> insert into xmldata


2 select dbms_xmlquery.getxml('select *from emp')
3 from dual
4 I

1 row created.

SQL> select to_char( xmldoc )


2 from xmldata
3 I

TO_CHAR(XMLDOC)

<?xml version = '1.0'?>


<ROWSET>
<ROW num='1">
<EMPN0>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>l2/17/1980 0:0:0</HIREDATE>
<SAL>BOO</SAL>
<DEPTN0>20</DEPTNO>
</ROW>
<ROW num="2">
<EMPN0>7499</EMPNO>
<ENAME>ALLEN</ENAME>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>2/20/1981 0:0:0</HIREDATE>
<SAL>l600</SAL>
<COMM>300</COMM>
<DEPTN0>30</DEPTNO>
</ROW>

<ROW num="14">
<EMPN0>7934</EMPNO>
<ENAME>MILLER</ENAME>
<JOB>CLERK</JOB>
<MGR>7782</MGR>
<HIREDATE>l/23/1982 0:0:0</HIREDATE>
<SAL>l300</SAL>
<DEPTNO>lO</DEPTNO>
</ROW>
</ROWSET> ________________~~---------------------------------------------------~d

880
SQL Function Reference

TO_CHAR( datetime)
The datetime-based TO_CHAR () function is for transforming a DATETIME value into a VARCHAR2
value, optionally using a specified date format. (Date formatting options can be found at the end of the
Conversion Functions section.)

character_value := TO_CHAR( datetime_value [, date_format ] )

SQL> select to_char( sysdate, 'DD/MM/YY HH24:MI:SS' ) "Right Now"


2 from dual
3 I

Right Now

04/11/01 19:28:31

SQL> select to_char( hiredate, 'Day Mon, YYYY' )


2 from emp
3 where empno = 7839
4 I

TO_CHAR(HIREDATE, 'D

Tuesday Nov, 1981

TO_CHAR( number)
The number-based TO_CHAR ( ) function is for transforming a numeric value into a VARCHAR2 value.
(Number formatting options can be found at the end of the Conversion Functions section.)

character_value .- TO_CHAR( number_value [, number_format ] )

SQL> select ename, to_ char ( sal, '$9, 999.99' ) • Salary•


2 from emp
3 I

ENAME Salary
----------
SMITH
----------
$800.00
ALLEN $1,600.00
WARD $1,250.00
JONES $2,975.00
MARTIN $1.250.00
BLAKE $2,850.00
CLARK $2,450.00
SCOTT $3,000.00
KING $5,000.00
TURNER $1,500.00
ADAMS $1,100.00
JAMES $950.00
FORD $3,000.00
MILLER $1,300.00

14 rows selected.

881
Appendix A

TO_NCHAR()
TO_NCHAR ( ) provides the same functionality as the TO_CHAR function. There are three flavors,
TO_NCHAR ( character ) , TO_NCHAR ( datetime), and TO_NCHAR ( number ) . The only difference
is that the return values are in the database's national character set. See the TO_CHAR ( ) function above
for syntax and examples.

TO_CLOB()
The TO_CLOB ( ) function transforms either an NCLOB value or other character-based data types
(VARCHAR2, VARCHAR2, CHAR, NCHAR) to CLOB values.

clob_value := TO_CLOB( character_value

SQL> create table xmldata(


2 xmldoc clob )
3 I

Table created.

SQL> insert into xmldata values


2 ( to_clob( '<?xml version='1.0'?>
3 <ROWSET>
4 <ROW num="1'>
5 <EMPN0>7369</EMPNO>
6 <ENAME>SMITH</ENAME>
7 <JOB>CLERK</JOB>
8 <MGR>7902</MGR>
9 <HIREDATE>12/17/1980 0:0:0</HIREDATE>
10 <SAL>800</SAL>
11 <DEPTN0>20</DEPTNO>
12 </ROW>
13 </ROWSET>' ) )
14 I

1 row created.

TO_NCLOB()
TO_NCLOB () provides the same functionality as the TO_CLOB () function. The only difference is that
the return values are in the database's national character set. See the TO_CLOB ( ) function above for
syntax and examples.

TO_DATE()
The TO_DATE () function is for converting a character string to its date equivalent. A date format string
can be provided to tell Oracle how to interpret the character string. (Date formatting options can be
found at the end of the Conversion Functions section.)

882
SQL Function Reference

date_value .- TO_DATE( character_value [, format_string ] )

SQL> create table author_log(


2 activity clob,
3 completed date
4 )
5 I

Table created.

SQL> insert into author_log values (


2 'Began SQL Functions appendix',
3 to_date( '04-NOV-2001 08:00', 'DD-MON-YYYY HH24:MI' )
4 )
5 I

1 row created .

TO_DSINTERVAL()
This function creates an INTERVAL DAY TO SECOND value.

interval_day_to_second_value := TO_DSINTERVAL( character_value

SQL> alter session set nls_date_format 'DD-MON-YYYY HH24:MI : SS';

Session altered.

SQL> select sysdate


2 from dual
3 I

SYSDATE

11-NOV-2001 10:58 : 13

SQL> select sysdate- to_dsinterval( '1 00:00:00' ) "US Marines


Birthday"
2 from dual
3 I

US Marines Birthday

10-NOV-2001 10:58:13

TO_LOB{)
The TO_LOB ( ) function is used for converting LONG and LONG RAW values to CLOBs and BLOBs,
respectively. The function can only be used in a subquery of an INSERT statement.

883
Appendix A

INSERT INTO table ( clob_or_blob_column


SELECT TO_LOB( long_or_long_raw_column )
FROM table

SQL> create table old_log(


2 activity long,
3 completed date
4 )
5 I

Table created .

SQL> insert into old_log values (


2 'Completed chapter 1', sysdate- 60 )
3 I

1 row created.

SQL> insert into old_log values (


2 'Completed chapter 2', sysdate- 30)
3 I

1 row created.

SQL> create table author_log(


2 activity clob,
3 completed date
4 )
5 I

Table created.

SQL> insert into author_log


2 select to_lob( activity), completed
3 from old_log
4 I

2 rows created.

TO_NUMBER{)
The TO_NUMBER ( ) function is used to convert a character value to a number value.

number_value := TO_NUMBER( character_value

SQL> select to_number( '15' )


2 from dual
3 I

TO_NUMBER(' 15')

884
SQL Function Reference

15

TO_TIMESTAMP()
This function creates a TIMESTAMP value.

timestamp_value := TO_TIMESTAMP( character_value

SQL> select to_timestamp ( '2001-NOV-11 08:00:00', 'YYYY-MON-DD


HH:MI:SS' )
2 from dual
3 I

TO_TIMESTAMP('2001-NOV-1108:00:00', 'YYYY-MON-DDHH:MI:SS')

11-NOV-01 08.00.00.000000000 AM

TO_TIMESTAMP_TZ()
This function creates a TIMESTAMP WITH TIME ZONE value.

timestamp_with_time_zone_value := TO_TIMESTAMP_TZ( character_value )

SQL> select to_timestamp_tz('2001-NOV-11 08:00:00 -05:00',


2 'YYYY-MON-DD HH:MI:SS TZH:TZM') "TS wl TZ"
3 from dual
4 I

TS wl TZ

11-NOV-01 08.00.00.000000000 AM -05:00

TO_YMINTERVAL()
This function creates an INTERVAL YEAR TO MONTH value.

interval_year_to_month_value := TO_YMINTERVAL( character_value

SQL> declare
2 l_hiredate timestamp:= to_timestamp('1996-11-04 07:00:00',
3 'YYYY-MM-DD HH24:MI:SS');
4 l_oneyr interval year to month:= to_yminterval('Ol-00');

885
Appendix A

5 1_18mos interval year to month := to_yminterval('01-06');


6 l_threeyrs interval year to month := to_yminterval('03-00');
7 l_fiveyrs interval year to month .- to_yminterval('05-00');
8 begin
9 dbms_output . put_line('One Year: 'I I (l_hiredate + l_oneyr)};
10 dbms_output.put_line('One + 112 Year: 'I I (l_hiredate +
1_18mos));
11 dbms_output.put_line('Three Years: 'I I (l_hiredate +
l_threeyrs));
12 dbms_output . put_line('Five Years : 'I I (l_hiredate + l_fiveyrs));
13 end;
14 I
One Year : 04-NOV-97 07 . 00 . 00.000000000 AM
One+ 112 Year: 04-NOV-97 07 . 00.00.000000000 AM
Three Years: 04-NOV-99 07.00.00.000000000 AM
Five Years : 04-NOV-01 07.00 . 00.000000000 AM

~L/S QL procedure successfully completed .

TRANSLATE USING(}
This function is for converting character values from the database character set to the database's
national character set and vice versa.

character_value := TRANSLATE(character_value USING { CHAR_CS NCHAR_CS } )

SQL> create table nchar_samples(


2 char_data char(100),
3 nchar_data nchar(100}
4 )
5 I

Table created .

SQL> insert into nchar_samples( nchar_data


2 values ( N'Some text' )
3 I

1 row created.

SQL> update nchar_samples


2 set char_data = translate( nchar_data using char_cs
3 I

886
SQL Function Reference

Date and Number Format Strings


When converting character values to dates and numbers, or vice versa, Oracle offers some flexibility.
Instead of having a fixed format that must be followed to convert a character value representing a date
into a date format, you can provide a format string that tells Oracle howio interpret your data.

The same flexibility is offered when converting date and number values to strings, so you can do things
like only show the name of the month, or the abbreviation of the month, or the numeric value of the
month; or for a number, you might want to use a dollar sign ($) in front of the number to indicate a
monetary value, or you may want to convert your number into Roman numerals. In this section, we will
outline some of the formatting options available for date formats and number formats.

Date Formatting
The following list describes those formatting options for the TO_DATE ( ) and the
TO_CHAR (datetime) functions:

0 AD, A. D . - AD indicator
0 AM, PM, A.M. , P . M. - The meridian indicator

0 BC, B . C • - BC indicator
0 RM - Roman numerals of month
0 cc, sec- The century indicator (1999 resolves to 20, 2001 resolves to 21, etc.)
0 Y, YY, YYY, YYYY- Numeric value of the year (1, 2, 3, and 4 digits, respectively)
0 YEAR - Character representation of year ("Two thousand one")
0 YY- Numeric value of the month (1-12)
0 RR - Given a two-digit year, this date format returns a year based on the second two digits of
the current year. If the two digits are < 50, the first two digits become the current year's two
digits. If they are >= 50, the first two digits are the current year minus one. (RR ( ' 9 9 ' )
1999, RR( I 00 I) = 2000)
0 MON- Abbreviated character value of month (JAN, FEB, etc.)
0 MONTH- Character value of month (JANUARY, FEBRUARY, etc.)
0 MM- Numeric value of the month (1-12)
0 WW- Numeric value of week of the year (1-53)
0 W- Numeric value of week of the month (1-5)
0 D - Numeric value of day of the week ( 1-7)
0 DD- Numeric value of day of the month (1-31)
0 DDD- Numeric value of day of the year (1-365)
0 Day -Text value of day of the week

887
Appendix A

0 HH, HH12- Hour of the day (1-12)


0 HH2 4 - Hour of the day (0-23)
0 MI - Minute of the hour (0-59)
0 SS- Seconds of the minute (0-59)

0 SSSSS -Seconds of the day (0-86399)

Number Formatting
0 9- Returns a digit from the numeric value, by position (TO_CHAR ( 111 1 999) = 111)

0 9 9 9 9 -Places a comma in the designated position (TO_CHAR ( 12 3 4


1 1
1 9 999
1
1 ) = 1 2 3 4)
1

0 9 9 9 . 9 9 - Places a decimal point in the designated position (TO_CHAR ( 12 3 1


1 999 . 99 1 ) =
123. 00)
0 $ 9 9 9 9 - Returns the numeric value preceded by a dollar sign
0 FM9 9 - Strips all leading and trailing blanks from the returned character value
0 RN, rn - Returns the roman numeral representation for the number given (in upper and lower
case, respectively)
0 X- Returns the hexadecimal value for the number given. (TO_CHAR ( 2 0 I I XX I ) = 14)

AGGREGATION Functions
Oracle provides plenty of functions for working with values in SQL and PL/SQL.

AVG() MIN()

COUNT() SUM()

MAX()

AVG(}
The AVG () function returns the average of all the non-NULL values provided. If NULL values are
included in the set of records passed to AVG ( ) , those values are ignored completely.

SELECT AVG( number_column


FROM table

SQL> select avg( sal )


2 from emp
3 I

AVG(SAL)

2073 . 21429

888
SQL Function Reference

COUNT()
COUNT () returns the total number of non-NULL values in a set of records. NULL values are not counted,
unless COUNT(*) is used.

SELECT COUNT(column
FROM table

SQL> select count( * )


2 from emp
3 I

COUNT(*)
----------
14

SQL> select empno, ename


2 from emp
3 where mgr is null
4 I

EMPNO ENAME
---------- ----------
7839 KING

SQL> select count( mgr )


2 from emp
3 I

COUNT(MGR)

13

MAX()
MAX ( ) is used to determine the maximum value in a set of records.

SELECT MAX(column
FROM table

SQL> select max( sal )


2 from emp
3 I

MAX(SAL)

5000

889
Appendix A

MIN(}
MIN ( ) is used to determine the minimum value in a set of records.

SELECT MIN(column
FROM table

SQL> select min( sal )


2 from emp
3 I

MIN (SAL)

800

SUM(}
The SUM ( ) function is responsible for determining the sum of all the values in a set of records.

SELECT SUM(column
FROM table

SQL> select sum( sal )


2 from emp
3 I

SUM(SAL)

29025

MISCELLANEOUS Functions
Oracle provides plenty of functions for working with string values in SQL and PL/SQL.

COALESCE () LEAST() SYS_CONNECT_BY_PATH()


DECODE () NULL IF () UID()

DUMP() NVL() USER()


GREATEST() NVL2() VSIZE()

COALESCE(}
The COALESCE ( ) function is for returning the first value in a list of values that is non-NULL. If all the
values passed to the COALESCE ( ) function are NULL, the return value is NULL. COALESCE ( ) works for
any data type, but all the data types passed in a single call must be either NULL or the same data type.

890
SQL Function Reference

value:= COALESCE( value{, value} ... )

SQL> select coalesce( null, 'A' )


2 from dual
3 I

c
A

SQL> select coalesce( null, sysdate )


2 from dual
3 I

COALESCE(

04-NOV-01

DECODE()
DECODE ( ) is a comparison function, used for comparing a base value against up to 255 evaluation
values in a single function call. Optionally, a default value can be passed at the end of the function to be
returned in the case where the base value does not equal any of the evaluation values.

value := DECODE( base_value, evaluation_valuel, return_valuel


{, evaluation_value2, return_value2 } ...
{, default_value } )

SQL> select dname, decode( loc, 'BOSTON', 'Red Sox fans',


2 'CHICAGO', 'White Sox fans',
3 'DALLAS', 'Astros fans',
4 'NEW YORK', 'Mets fans' ) "Baseball Team"
5 from dept
6 I

DNAME Baseball Team

ACCOUNTING Mets fans


RESEARCH Astros fans
SAL.ES White Sox fans
OPERATIONS Red Sox fans

SQL> select decode( ename, 'KING', 'KING OF THE HILL', ename) 'ENAME"
2 from emp
3 I

ENAME

SMITH

891
Appendix A

AL.LEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING OF THE HILL
TURNER
ADAMS
JAMES
FORD
MILLER

14 rows selected.

DUMP{)
The DUMP () function provides meta data about the first parameter (expression) passed to the function,
including data type code, length in bytes, and an internal representation of the expression. The data
type codes are as follows:

0 1 - VARCHAR2, NVARCHAR2
0 2- NUMBER
0 8- LONG
0 12- DATE
0 23- RAW
0 24- LONG RAW
0 69- ROWID
0 96 - CHAR, NCHAR
0 112 - CLOB, NCLOB
0 113- BLOB
0 114- BFILE
0 208- UROWID
0 180- TIMESTAMP
0 181 -TIMESTAMP WITH TIME ZONE
0 182- INTERVAL YEAR TO MONTH
0 183- INTERVAL DAY TO SECOND
0 231 -TIMESTAMP WITH LOCAL TIME ZONE

892
SQL Function Reference

Optional parameters to the DUMP ( ) function are as follows:

0 Return format. Allows you to specify the format of the return value. Valid return formats are
as follows:
0 8- Octal
0 10- Decimal
0 16- Hexadecimal
0 17 - Single-digit characters
0 Start position. Specifies the position to start evaluating the expression.
0 Length. Specifies the amount of data to evaluate.

value :=DUMP( expression {, return_format {, start_position {, length } } } )

SQL> select dump( ename, 8 )


2 from emp
3 I

DUMP(ENAME,S)
--------------------------------------
Typ=1 Len=5: 123,115,111,124,110
Typ=1 Len=5: 101,114,114,105,116
Typ=1 Len=4: 127,101,122,104
Typ=1 Len=5: 112,117,116,105,123
Typ=1 Len=6: 115,101,122,124,111,116
Typ=1 Len=5: 102,114,101,113,105
Typ=1 Len=5: 103,114,101,122,113
Typ=1 Len=5 : 123,103,117,124,124
Typ=1 Len=4: 113. 111,116. 107
Typ=1 Len=6 : 124,125,122,116,105,122
Typ=1 Len=5: 101,104,101,115,123
Typ=1 Len=5: 112,101,115,105,123
Typ=1 Len=4 : 106,117,122,104
Typ=1 Len=6: 115,111,114,114,105,122

14 rows selected.

SQL> select dump( ename, 16 l


2 from emp
3 I

DUMP ( ENAME, 16)

Typ=1 Len=5 : 53,4d,49,54,48


Typ=1 Len=5: 41,4c,4c,45,4e
Typ=1 Len=4: 57,41,52,44
Typ=1 Len=5: 4a,4f,4e,45,53
Typ=1 Len=6: 4d,41,52,54,49,4e
Typ=1 Len=5: 42,4c,41,4b,45
'l'>Ln:.l • n=.§. ill 4r 41 'i2 4.b

893
Appendix A

Typ=l Len=5: 53' 43' 4f. 54' 54


Typ=l Len=4: 4b,49,4e,47
Typ=l Len=6: 54,55,52,4e,45,52
Typ=l Len=5: 41.44,41,4d,53
Typ=l Len=5: 4a,41,4d,45,53
Typ=l Len=4: 46,4f.52,44
Typ=l Len=6: 4d,49,4c,4c,45,52

GREATEST(}
The GREATEST (} function is for returning the greatest value in a list of values, based on the database
character set. A character is greater than another if it has a higher value in the database character set.

value := GREATEST( value {, value } ...

SQL> select greatest( lA!, •a• }


2 from dual
3 I

SQL> select greatest( 'ONE', 1 )


2 from dual
3 I

GRE

ONE

SQL> select greatest( 1, 5' 10 )


2 from dual
3 I

GREATEST(1,5,10)
----------------
10

LEAST()
The LEAST ( } function is for returning the smallest value in a list of values, based on the database
character set. A character is less than another if it has a lower value in the database character set.

value:= LEAST( value{, value} ... )

SQL> select least( 'X', 'x' }


2 from dual
3 I

894
SQL Function Reference

SQL> select least( 'A', 'B', 'C' )


2 from dual
3 I

NULLIF{)
This function evaluates two expressions and determines if they equal each other or not. If they equal
each other, NULL is returned. If they do not equal each other, the first expression is returned. The first
expression cannot be a NULL value, or an error is raised.

value := NULLIF( expressionl, expression2

SQL> select nullif( 1, 1 l


2 from dual
3 I

NULLIF(1,1)

SQL> select nullif( 1, null )


2 from dual
3 I

NULLIF(l,NULL)

NVL{)
NVL ( ) is used for evaluating an expression, and returning a given value if the expression evaluates to
NULL.

value := NVL( expression, alternative_return_value

SQL> select nvl( 'Yes ' ' ' ' is null' ) "Evaluate•
2 from dual
3 I

895
Appendix A

Evaluate

Yes 1 1 is null

SQL> select e.ename, nvl( e2.ename, 'NO BOSS! PARTY TIME!' ) "MGR"
2 from emp e, emp e2
3 where e.mgr = e2.empno(+)
4 I

ENAME MGR
---------- --------------------
SMITH FORD
ALLEN BLAKE
WARD BLAKE
JONES KING
MARTIN BLAKE
BLAKE KING
CLARK KING
SCOTT JONES
KING NO BOSS! PARTY TIME!
TURNER BLAKE
ADAMS SCOTT
JAMES BLAKE
FORD JONES
MILLER CLARK

14 rows selected.

NVL2()
NVL2 ( ) takes the NVL ( ) function one step further. If the first expression in NVL2 ( ) is not NULL, the
second parameter is returned. If the value is NULL, the third parameter is returned.

value := NVL2( expression, not_null_return_value, null_return_value,)

SQL> select e.ename, nvl2( e2.ename, 'BACK TO WORK!', 'NO BOSS!' ) "MGR"
2 from emp e, emp e2
3 where e.mgr = e2.empno(+)
4 I

ENAME MGR
---------- -------------
SMITH BACK TO WORK!
ALLEN BACK TO WORK!
WARD BACK TO WORK!
JONES BACK TO WORK!
MARTIN BACK TO WORK!
BLAKE BACK TO WORK!
CLARK BACK TO WORK!

896
SQL Function Reference

SCOTT BACK TO WORK!


KING NO BOSS!
TURNER BACK TO WORK!
ADAMS BACK TO WORK!
JAMES BACK TO WORK!
FORD BACK TO WORK!
MILLER BACK TO WORK!

14 rows selected.

SYS_CONNECT_BY_PATH()
This function works with the CONNECT BY condition in a hierarchical query to show the entire path in a
single return value. Until Oracle 9i, this functionality was only accomplished programmatically. The
first parameter is the column that should populate each level of the 'hierarchy' in the return value, the
second parameter is the value delimiter.

SQL> select lpad('*', 2*level, '*' l II ename empName,


2 dname, job , sys_connect_by_path( empno, ' ) cbp
3 from scott.emp emp, scott . dept dept
4 where emp.deptno = dept.deptno
5 start with mgr is null
6 connect by prior empno = mgr
7 order siblings by ename
8 I

EMPNAME DNAME JOB CBP


-------------- PRESIDENT
--------- ------------------------
.7839
**KING ACCOUNTING
****BLAKE SALES MANAGER .7839 . 7698
******ALLEN SALES SALESMAN .7839 . 7698.7499
******JAMES SALES CLERK . 7839.7698 . 7900
******MARTIN SALES SALESMAN .7839.7698 . 7654
******TURNER SALES SALESMAN .7839.7698 . 7844
******WARD SALES SALESMAN . 7839 . 7698 . 7521
****CLARK ACCOUNTING MANAGER . 7839 . 7782
******MILLER ACCOUNTING CLERK .7839.7782.7934
****JONES RESEARCH MANAGER .7839 . 7566
******FORD RESEARCH ANALYST .7839.7566.7902
********SMITH RESEARCH CLERK .7839 . 7566.7902.7369
******SCOTT RESEARCH ANALYST . 7839.7566.7788
********ADAMS RESEARCH CLERK .7839 . 7566 . 7788.7876

14 rows selected.

UID()
UID () returns a number that uniquely identifies the connected user.

number_value .- UID

897
Appendix A

SQL> select uid •current urn•


2 from dual
3 I

CUrrent UID

54

USER()
The USER ( ) function returns the name of the currently connected user.

character_value .- USER

SQL> select user •current User•


2 from dual
3 I

Current User

SCOTT

SQL> select object_name, object_ type


2 from all_objects
3 where owner "' user
4 I

OBJECT_NAME OBJECT_TYPE

ADDRESS_TYP TYPE
AUTHOR_LOG TABLE
BONUS TABLE
CASEPARTYADDRESS TABLE
COURSES TABLE
DEPT TABLE
EMP TABLE
EMPLOYEES TABLE
GETCASEXML FUNCTION
GET_TRANSPOSED FUNCTION
NCHAR_SAMPLES TABLE
OLD_LOG TABLE
PK_COURSES INDEX
PK_DEPT INDEX
PK_EMP INDEX
PK_SUBJECTS INDEX
SALGRADE TABLE
SUBJECTS TABLE
SYS_LOB0000031587C00001$$ LOB
T TABLE
TRANSPOSE FUNCTION

21 rows selected.

898
SQL Function Reference

VSIZE()
This function returns the number of bytes the internal representation of the expression parameter
consumes.

number_value .- VSIZE( expression

SQL> create table nchar_test (


2 ename varchar2(20),
3 n_ename nvarchar2(20)
4 )
5 I

Table created.

SQL> insert into nchar_test


2 select ename, ename
3 from emp
4 I

14 rows created.

SQL> select ename,


2 vsize( ename ) "Char Size•, vsize( n_ename ) "NChar Size•
3 from nchar_test
4 I

ENAME Char Size NChar Size


-------------------- ---------- ----------
SMITH 5 10
ALLEN 5 10
WARD 4 8
JONES 5 10
MARTIN 6 12
BLAKE 5 10
CLARK 5 10
SCOTT 5 10
KING 4 8
TURNER 6 12
ADAMS 5 10
JAMES 5 10
FORD 4 8
MILLER 6 12

14 rows selected.

899
Supplied Packages

In this appendix, we will look at some of the more common supplied packages. These PLISQL packages
are usually installed in the database when it is created and are available to all schemas users (though
they are owned by the SYS user). Their names are prefixed with either DBMS_ or UTL_. We will discuss
the following seven supplied packages.

0 DBMS_ OUTPUT

0 DBMS_RANDOM

0 UTL_FILE

0 DBMS_JOB

0 UTL_RAW

0 DBMS_LOB

0 DBMS_SQL

This is in no way a complete list though. You can get a full listing of each package in the Oracle
documentation Supplied PUSQL Packages Reference.

For any given package you can use the DESCRIBE command to return a list of all the procedures and
functions it contains, as well as the parameters available to it and its data types. Further information can
be found in the specification (spec). The specs are stored in clear text and are usually quite well
documented with comments. We could either query a spec out of the database, or just go look for it on
the file system. They are located in $0RACLE_HOME/rdbms/admin. You will see many files in that
directory. The ones you will be most interested in are those prefixed with dbms or utl and ending with
the . sql extension. For example, the DBMS_RANDOM spec is located in the file dbmsrand. sql. The
• plb files are the wrapped package bodies. Viewing the dbmsrand. sql file, you will see that it is
nicely documented and that there are even examples on how to use it.
Appendix B

DBMS_OUTPUT
DBMS_ OUTPUT allows the developer to return text messages from their PL/SQL routines to any client
that is DBMS_OUTPUT aware. You can view the file containing the specification located at
$0RACLE_HOME/rdbms/admin/dbmsotpt.sql.

The spec of DBMS_OUTPUT is fairly simple. There are only a few procedures defined:

DISABLE NEW_LINE

ENABLE PUT

GET_LINE PUT_LINE

GET_LINES

DBMS_OUTPUT is only useful for relatively small debugging tasks, since the buffer (where the messages
are cached) is only 1,000,000 characters long, and each line only 255 characters. The package works by
buffering your text messages into an array of VARCHAR2 ( 2 55) . Then a DBMS_OUTPUT aware client will
spool that information when the procedure is successfully completed. We have all seen
DBMS_OUTPUT. PUT_LINE ()in action in SQL*Plus, but remember we needed to enable SQL*Plus to
spool the messages back to us upon successful completion of the PL/SQL routines. With SQL*Plus, that
was accomplished with the SET SERVEROUTPUT ON command. Without that command, you will not see
any of your output.

ENABLE()/ DISABLE()
SQL*Plus is a DBMS_OUTPUT aware client. But what if you wanted to display these messages from your
Cor java program? You will need to enable the DBMS_OUTPUT package and then fetch and display the
cached row programmatically. The syntax is as follows:

Usage
procedure enable (buffer_size in integer default 20000);
procedure disable;

The first thing your client will need to do is issue a call to DBMS_OUTPUT. ENABLE ( ) . You supply it
with a buffer size between 2,000 and 1,000,000 bytes (the default is 20000). This allows Oracle to
allocate that much room for your messages. Attempting to store more information than space provided
will cause an exception to be raised. Once enabled, the application can then make calls to PUT ( ) and
PUT_LINE ()to cache the messages for later retrieval.

If at any time you want to turn off DBMS_OUTPUT message caching and clear the cache, a call to
DBMS_ OUTPUT. DISABLE () will accomplish that.

SQL> set aerveroutput on


SQL> begin
2 dbms_output.put_line( 'One' );
3 dbms_output.disable;
4 end;

902
5 I

PLISQL procedure successfully completed.

Here we enabled the SQL*Plus client to spool back any DBMS_OUTPUT messages with the call to SET
SERVEROUT ON. This makes the call to DBMS_OUTPUT. ENABLE (), setting up the buffer, and
prepares the client to spool the messages back. In the block itself, we cached one message but then
invoked the DISABLE () procedure which cleared any previous messages in the cache. When the
block completed, no messages were displayed. Until we enable DBMS_OUTPUT, either
programmatically, DBMS_OUTPUT. ENABLE ( ) , or manually with another call to SET SERVEROUT ON,
we will not see any messages:

SQL> begin
2 dbms_output.put_line( 'One' );
3 dbms_output.put_line( 'Two' );
4 dbms_output . put_line( ' Three• );
5 end;
6 I

PLISQL procedure successfully completed.

SQL> begin
2 dbms_output.put_line( 'One' ) ;
3 dbms_output . put_line( 'Two' ) ;
4 dbma_output.enablel
5 dbms_output.put_line( 'Three' );
6 end;
7 I

Three

Alternatively, we could disable the SQL*Plus client from spooling back the messages by issuing the
command SET SERVEROUTPUT OFF. We can still cache the messages if we enable DBMS_OUTPUT
programmatically, but they will never be displayed because SQL*Plus is not currently displaying the
cached messages. This is bad since you are sure to fill up the buffer as nothing is cleaning it up after
every successful procedure completion. Unless you have a real reason to do so, do not enable
DBMS_OUTPUT in your PL!SQL. Let the client running your procedure manage that.

PUT() I PUT_LINE() I NEW_LINE()


The procedures PUT ()and PUT_LINE ()allow you to put messages into the DBMS_OUTPUT cache.
PUT ()places your message just as it was sent. PUT_LINE ()will add a new-line character to the end of
your text string. The procedure NEW_LINE ()adds a new line to the buffer. Calling PUT_LINE () is
equivalent to calling PUT ( ) and then NEW_LINE ( ) . Any line cannot be longer than 255 characters.

Usage
procedure put(a varchar2);
procedure put(a number);

903
Appendix 8

procedure put_line(a varchar2);


procedure put_line(a number);

procedure new_line;

Example
SQL> set serverout on
SQL> begin
2 dbms_output.put( 'One' );
3 dbms_output.put( 'Two' );
4 dbms_output.new_line;
5 dbms_output.put_line( ' Three' );
6 dbms_output . put( 'Four' );
7 end;
8 I

OneTwo
Three

PL/SQL procedure successfully completed.

You can see that the calls to PUT ( ) on lines 2 and 3 caused the messages to be displayed on the same
line after the call to NEW_LINE ( ) on line 4. Also notice that the message ' Four' was not displayed.
Any message that does not end with a new line will not be returned or displayed.

GET_LINE()/ GET_LINES()
The procedures GET_LINE () and GET_LINES ( l are used for clients that want to retrieve the
DBMS_OUTPUT messages that have be queued up. SQL*Plus handles that for us when we initialize it to
do so with the SET SERVEROUTPUT ON command. (Other clients would need to fetch the rows cached
and display them using whatever means available.) The client can fetch one line at a time with
GET_LINE () or fetch multiple lines with one call using GET_LINES ().

Usage
procedure get_line(line out varchar2, status out integer);
procedure get_lines(lines out chararr, numlines in out integer);

Summary
Do not rely exclusively on DBMS_OUTPUT for generating debug messages. The line-size restriction and
the relatively small buffer size do not make it a great solution for large scale application debugging. For
simple small procedures and quick message retrieval from the SQL*Plus client, it works just great.

DBMS_RANDOM
DBMS_RANDOM is a package that generates random numbers or strings. It will generate a sequence of
38-digit Oracle numbers. You can view the specification in the file
$0RACLE_HOME/rdbms/admin/dbmsrand.sql.

904
Supplied Packages

Here are the available procedures and functions:

Procedures Functions
INITIALIZE() VALUE () -returns NUMBER
SEED() NORMAL ( ) - returns NUMBER
TERMINATE ( ) RANDOM () -returns BINARY_INTEGER

STRING ( ) - returns VARCHAR2

VALUE()
The overloaded function VALUE ( ) is used to request a random number from the DBMS_RANDOM
package. The function VALUE () with no parameters will return a number with 38 digits of precision. It
will be in the range of 0.0 up to but not including 1.0.

Usage
FUNCTION value RETURN NUMBER;
FUNCTION value (low IN NUMBER, high IN NUMBER) RETURN NUMBER;

Example
To generate 10 integers between 1 and 100, you could do the following:

SQL> begin
2 for~ ~n 1 .. 10 loop
3 dbrns_output.put_line( round( dbms_random.value*100) );
4 end loop;
5 end;
6 I
13
19
64
99
48
7
7
5
83
32

PL/SQL procedure successfully com eted .

Notice how 7 came up twice in a row. There is no guarantee that the same number will not come up
twice, just that the numbers will be in a random order.

The second version of VALUE ( ) takes in two parameters, an upper and lower bound. The possible
values returned by using this call will be in the range of these bounds. Passing in LOW => 10 and HIGH
=>50 will generate numbers between 10 and 49. To generate 10 integers again between 1 and 100 we
could do this instead:

905
Appendix B

SQL> begin
2 fori in 1 .. 10 loop
3 dbms_output.put_line( trunc( dbms_random.value( 1, 101 ) ) );
4 end loop;
5 end;
6 I
10
40
74
77
67
10
91
58
34
29

PL/SQL procedure successfully completed.

STRING()
The STRING ( ) function will generate a random string. STRING ( ) takes two required parameters.
The first parameter is a key to tell STRING ( ) the characteristics of the value you want returned. The
keys include:

0 U or u - The string can only contain uppercased alpha characters.

0 L or 1 - The string can only contain lowercased alpha characters.


0 A or a - The string can only contain upper and lowercased alpha characters.
0 X or x - The string can only contain upper alpha-numeric characters.
0 P or p - The string can contain any printable character.

The second parameter, LEN, dictates how long the string will be.

Usage
FUNCTION string (opt char, len NUMBER};

Examples
SQL> exec ~_output.put_line( ~_randaa.•tring( 'A', 20 ) )1
qGkAKXPXswvrzwznvDDJ

PL/SQL procedure successfully completed.

SQL> exec ~_output.put_line( ~_randOIIl.•tring( •x•, 20 l l 1


SJALDSAJKTCV5JBKIY45

PL/SQL procedure successfully completed.

906
Supplied Packages

SQL> exec dbms_output .put_ U .ne ( dl:laut_r&Ddom. strinlif ( 'P •, 20 ) ) 1


]*20B'.~nf9b)Zt1v-Sh

PL/SQL procedure successfully completed.

SQL> exec dbm&_output.put_ line( dbmB_ randam.strinliJ( '1', 20 ) l1


hriamgknxcxoehreplge

PL/SQL procedure successfully completed.

SQL> exec dbms_output.put_ line( dbm&_ randam.string( •u•, 20 ) ) 1


NOGRKGBCNWIUQLEDIPAG

PL/ SQL procedu.r e successfully completed .

This is useful when you are populating a table with a bunch of dummy data to test how your application
will run against a table with many rows of data.

SEED()
The procedure SEED () is an overloaded procedure that takes in either a BINARY_INTEGER or a
VARCHAR2. This is the starting point for the random values to be returned. You should always attempt
to seed with some unique value so your random values will truly be random. If the DBMS_RANDOM
package is seeded with the same value, it will produce the same results in the same order.

Usage
PROCEDURE seed(val IN BINARY_INTEGER);
PROCEDURE seed(val IN VARCHAR2);

Examples
SQL> connect scott/tiger
Connected.

SQL> set serverout on


SQL> exec dl:laut_output.put_ line( dbm&_r&Ddom.va1ue ll
.6733207147036675153870418717622262172

PL/SQL procedure successfully completed .

SQL> connect scott/tiger


Connected.

SQL> set serverout on


SQL> exec dbm&_output.put_ line( dbm&_r&ndam.value ) 1
. 64740754965940299586220325260648615694

Notice that we connected twice and, without seeding the DBMS_RANDOM package, received different
results. That is because the package was seeded with the time and session id, which were different for
each connection.

907
Appendix B

SQL> connect scott/tiger


Connected.

SQL> set serverout on


SQL> exec &:aa_random.8ee4( to_cbar( •y•d&te, 'YYYYIIIIDD' ) ) 1

PL/SQL procedure successfully completed .

SQL> exec &:as_ output. put_ line ( &:aa_random. value ) 1


. 14397125844208444263515445820862550754

PL/SQL procedure successfully completed.

SQL> exec dbma_output.put_ line( dbma_random.value )I


.03283354076303502023328442695142548424

PL/SQL procedure successfully completed .

SQL> connect scott/tiger


Connected .

SQL> set serverout on


SQL> exec dbma_random.8ee4( to_char( 8y8d&te, 'Y"xxz~D' ) )1

PL/SQL procedure successfully completed .

SQL> exec &:aa_output. put_ line ( &:aa_ random. value ) ;


.14397125844208444263515445820862550754

PL/SQL procedure successfully completed.

SQL> exec &:aa_output.put_ line( dbma_ random.value ) 1


.03283354076303502023328442695142548424

PL/SQL procedure successfully completed.

This time we chose to seed the DBMS_RANDOM package ourselves, but we chose a poor value to seed
with. The value of the function TO_CHAR ( sysda te, 'YYYYMMDD' ) is going to be the same for
everyone and we can see we get the same random numbers each time.

It is normally best practice to accept the default seeding of the package, which is the current username,
the current time down to the second and the current session id. Those three values combined make for a
pretty unique key to seed by.

NORMAL()
The NORMAL ( ) function simply returns a random number from a normal distribution. The same rules
apply to this function as to VALUE ( ) and STRING ( ) with regards to how the package was seeded.

Usage
FUNCTION normal RETURN NUMBER;

908
Supplied Packages

Examples
SQL> begin
2 fori in 1 .. 10 loop
3 dbaa_output.put_line ( dbaul_randolll . normal ) ;
4 end 1 oopJ
5 end;
6 I
-1 . 19503152622542500144888406874463873571
. 7375783751870584132414152563297172815803
-.7937646128338100216415226706722760298202
.5765210921386172650218917205476532877619
-.7110720402941713980469270294743260344575
.4456902772420322425209890755347992887892
-.0918263969133436048840681355219765633005
-1.08462420404879076083328769627598888086
1 . 33394747019616122501366949844410068467
.1621663118391535938482533243194089135786

PL/SQL procedure successfully completed.

INITIALIZE() I RANDOM() I TERMINATE()


These three routines are obsolete as of Oracle 9i. They have been left in for backward compatibility.
They are mapped to the new procedure and functions we have already talked about.

Usage
PROCEDURE initialize(val IN BINARY_INTEGER);
FUNCTION random RETURN BINARY_INTEGER;
PROCEDURE terminate;

Old Function/Procedure Call New Function/Procedure Call


INITIALIZE ( seed_value ) SEED ( seed_value )
RANDOM() VALUE( -power(2,32), power(2,32)
TERMINATE () N/A

Summary
DBMS_RANDOM is a great little utility for generating random numbers and strings. Make sure you seed
the package uniquely or DBMS_RANDOM. VALUE ( ) will not be as random as you think.

UTL_FILE
The UTL_FILE package gives the PLISQL developer the ability to read an ASCII file from, or write it
to, the server's file system. The spec is in the file $ORACLE_HOME/rdbms I admin/utlfile. sql.

909
Appendix B

UTL_FILE's procedures and functions are:

Procedures Functions
FCLOSE () FOPEN ( ) - returns RECORD
FCLOSE_ALL ( ) FOPEN_NCHAR ( ) - returns RECORD
FFLUSH () IS_OPEN () -returns BOOLEAN
TERMINATE ( )
GET_LINE()

GET_LINE_NCHAR()

NEW_LINE ()
PUTF()

PUTF_NCHAR ( )

Setup
In the init. ora file, you set the parameter UTL_FILE_DIR equal to the directory where PLISQL can
write files. You may have multiple entries for this parameter, each set to a directory that is writable by
the instance owner. On UNIX they might look like this:

UTL_FILE_DIR = /tmp
UTL_FILE_DIR = /dO/users/clbeck/sql/stage
On Windows-based machines, entries may look like:

UTL_FILE_DIR = C:\Temp
UTL_FILE_DIR = E:\SQL\stage

Even though directorie are not case-sensitive on Windows, the directories listed for
UTL_ FILB_ DIR are. Take note as to how they are defined on your Windows machine
and u e the exact case. UNIX is always case-sensitive.

Files can only be opened if they are in the specified directories. UTL_FILE will not open files in any sub
directories.

UTL_FILE_DIR can also be set to"*" giving PL/SQL access to write to any directory that the Oracle
instance owner can write to. This overrides the safeguards that this parameter was designed for. Be
careful if you choose to set this value to * for the reasons described above.

910
Supplied Packages

Process
The process for using UTL_FILE is quite simple:

D Open a file with mode of Read, Write or Append.


D Read or write the file with the procedures supplied.
D Close the file when you are done.

A sample of that code may look like this:

declare
l_file utl_file.file_type;
begin
l_file : = utl_file.fopen( ' / tmp', 'debug.txt', 'w' );
utl_file.put_line( l _file, 'One. ' ) ;
utl_file . put( l _file, 'Two' ) ;
utl_file.fflush( l_file );
utl_file.close( l_file );
exception
when others then
if utl_file.is_open( !_file ) then
utl_file.fclose( !_file);
end if;
. . raise;
end;

This sample code opens a file I tmp I debug. txt with the mode of write. It then writes two lines to
the file and closes it. The exception handler catches any exception that can be thrown and closes the file
handle if it is open.

Exceptions
The UTL_FILE package can throw many different exceptions. They include:

Exception Description
INVALID_PATH Attempted to open a file in a path not defined in the ini t. ora
parameter file.
INVALID_MODE Attempted to open a file with a mode other than r, w, or a.

INVALID_MAXLINESIZE Raised when a supplied MAXLINESIZE is out of range.


INVALID_FILEHANDLE The file handle supplied to the package was invalid.
INVALID_OPERATION The attempted request to open the file failed.
READ_ERROR OS error occurred during the reading of the file.
Table continued on following page

911
Appendix B

Exception Description

WRITE_ERROR OS error occurred during the writing of the file.


INTERNAL_ERROR Unspecified PLISQL error.
CHARSETMISMATCH A file is open using the FOPEN_NCHAR ( ) function but then non-
NCHAR operations are attempted on the file.

Types
UTL_FILE defines a package-level record type, FILE_ TYPE. This record type is used as the handle to
your file once it is opened. Although it is defined in the spec and is public, you should not attempt to
read or modify any values in the type.

The record type is defined as:

TYPE file_type IS RECORD (id BINARY_INTEGER, datatype BINARY_INTEGER);

FOPEN() / FOPEN_NCHAR()
The overloaded functions FOP EN () (pronounced F-Open, not fop-en) and FOPEN_NCHAR () are usually
the first call to UTL_FILE. You cannot operate on a file in PL/SQL unless you use one of these
functions to first open the file.

Usage
FUNCTION fopen(location IN VARCHAR2,
filename IN VARCHAR2,
open_mode IN VARCHAR2) RETURN file_type;

FUNCTION fopen_nchar( location IN VARCHAR2,


filename IN VARCHAR2,
open_mode IN VARCHAR2) RETURN file_type;

FUNCTION fopen(location IN VARCHAR2,


filename IN VARCHAR2,
open_mode IN VARCHAR2,
max_linesize IN BINARY_INTEGER) RETURN file_type;

FUNCTION fopen_nchar(location IN VARCHAR2,


filename IN VARCHAR2 ,
open_mode IN VARCHAR2 ,
max_linesize IN BINARY_INTEGER) RETURN file_type;

ID and DATA TYPE are the elements or the record type returned. Each version of FOPEN () is
overloaded. The difference is that the one version takes in an additional parameter, MAX_LINESIZE.
That is the maximum length any line of the file can be. By default the length is 1023 and the OS dictates
that. To specify a different max line size, call the version which accepts the MAX_LINESIZE parameter.

FOPEN ( ) 's sister function is FOPEN_NCHAR ( ) allows you to open the file and read or write Unicode,
and not the database's default character set.

912
Supplied Packages

Example
declare
l_file_handle utl_file.file_type;
begin
l_file_handle := utl_file.fopen( '/tmp', 'tom.data', 'w' );
end;

Mode
Along with a location and a filename, you need to supply the mode you would like to open the file in:

r Read-Only
w Write I Overwrite If the file exists it will be overwritten
a Append. If the file exists, all writes will be appended. If the file does not exist, it will be
opened in the w mode

Exceptions
INVALID_PATH, INVALID_MODE, INVALID_OPERATION,andiNVALID_MAXLINESIZE.

IS_OPEN()
The function IS_OPEN () is used to determine if a file handle is valid and pointing to an open file. It is
useful in exception handling to determine if you should close the file . It takes in a
UTL_FILE. FILE_TYPE and returns a Boolean. No exceptions are raised from this function.

Usage
FUNCTION is_open(file IN file_type) RETURN BOOLEAN;

Example

if utl_file.is_open( l_file_handle ) then


Do some work with the file
end if;

GET_LINE()/ GET_LINE_NCHAR()
When a file is opened with the mode of r, (read mode), you can use the GET_LINE () and
GET_LINE_NCHAR ( ) functions to fetch one line of data at a time from the file. Each procedure takes in
the file handle and populates an OUT parameter with the next line of the file. The GET_LINE_NCHAR ()
procedure is used when a file is opened with the FOPEN_NCHAR () function. A NO_DATA_FOUND error
is raised when the end-of-file is hit. A VALUE_ERROR is raised if the buffer is too small.

913
Appendix B

Usage
PROCEDURE get_line(file IN file_type,
buffer OUT VARCHAR2);

PROCEDURE get_line_nchar(file IN file_type,


buffer OUT NVARCHAR2);

Example
Read every line of a file and store it in a database table:

declare
l_file_handle utl_file.file_type
l_buffer varchar2(4000);
begin
utl_file.fopen( '/tmp', 'chris.data', 'r' );
Loop
get_line( l_file_handle, l_buffer );
insert into file_table( seq, data )
values ( file_sequence.nextval, l_buffer );
end loop;
exception
when NO_DATA_FOUND then
utl_file.fclose( l_file_handle );
end;

Exceptions
INVALID_FILEHANDLE, INVALID_OPERATION,READ_ERROR,NO_DATA_FOUND,and
VALUE_ERROR.

PUT()/ PUT_NCHAR()
These procedures are used to write data to the current line of the file. A new-line character is not added
to the end of the line. Two subsequent called to PUT ( ) will write the data on the same line of the file.

Usage
PROCEDURE put(file IN file_type,
buffer IN VARCHAR2);

PROCEDURE put_nchar(file IN file_type,


buffer IN NVARCHAR2) ;

Example
Writes Hello World to one line of the file:

utl_file.put( l_file_handle, 'Hello' );


utl_file.put( l_file_handle, • ' );
utl_file.put( l_file_handle, 'World' );

914
Supplied Packages

Exceptions
INVALID_OPERATION,INVALID_FILEHANDLE,andWRITE_E RROR

NEW_LINE()
The procedure NEW_LINE ( ) is used in conjunction with PUT ( ) and PUT_NCHAR ( ) . Calling
NEW_LINE () will write a new-line character into the file ensuring that the next call to PUT () or
PUT_NCHAR ( ) will start in the next line.

Usage
PROCEDURE new_line(file IN file_type,
lines IN NATURAL:= 1);

Example
This writes Hello on the first line of the file and World on the next line:

utl_file . put( l_file_handle, 'Hello' ) ;


utl_file . new_line( l_file_handle );
utl_file . put( l_file_handle, 'World' );

Exceptions
INVALID_OPERATION, INVALID_FILEHANDLE, and WRITE_ERROR.

PUT_LINE()/ PUT_LINE_NCHAR()
The procedures PUT_LINE () and PUT_LINE_NCHAR () are exactly the same as their PUT counterparts
except that a new-line character will be automatically appended to each buffer put.

Usage
PROCEDURE put_line(file IN file_type,
buffer IN VARCHAR2);

PROCEDURE put_line_nchar(file IN file_type,


buffer IN NVARCHAR2);

Example
Write three lines to a file:

utl_file.put_line( l_file_handle, 'One• );


utl_file.put_line( l_file_handle, 'Two' );
utl_file.put_line( l_file_handle, 'Three' );

915
Appendix B

Exceptions
INVALID_OPERATION, INVALID_FILEHANDLE,andWRITE_ERROR

PUTF() / PUTF_NCHAR()
The procedures PUTF ( ) and PUTF _NCHAR ( ) are similar to the PUT procedures except that they take
optional formatting. It works like PRINTF ( ) in C, but only in a limited fashion.

The buffer to be written can contain special sequences of characters that will be substituted prior to
being written to the file, called tokens. Those tokens are:

0 %s - The token will get substituted with the next value in the argument list.
0 \n- This token will be replaced with a new line character.

If the formatted buffer contains more %s than arguments supplied, all additional %swill be replaced
with NULL.

Usage
procedure putf(file IN file_type,
format IN VARCHAR2,
argl IN VARCHAR2 DEFAULT NULL,
arg2 IN VARCHAR2 DEFAULT NULL,
arg3 IN VARCHAR2 DEFAULT NULL,
arg4 IN VARCHAR2 DEFAULT NULL,
arg5 IN VARCHAR2 DEFAULT NULL);

procedure putf_nchar(file IN file_type,


format IN NVARCHAR2,
argl IN NVARCHAR2 DEFAULT NULL,
arg2 IN NVARCHAR2 DEFAULT NULL,
arg3 IN NVARCHAR2 DEFAULT NULL,
arg4 IN NVARCHAR2 DEFAULT NULL,
arg5 IN NVARCHAR2 DEFAULT NULL);

Example
Write two lines to a file, Chris was here as the first line and and so was Sean as the second:

utl_file.putf( l_file_handle, •'%s was here\nand so was %s',


'Chris',
'Sean' ) ;
----------------------------------------------~

Exceptions
INVALID_OPERATION,INVALID_FILEHANDLE, and WRITE_ERROR

FFLUSH()
The procedure FFLUSH ( ) physically writes pending data to the file. For performance reasons, the data
is usually buffered and written in large chunks. FFLUSH ( ) forces the physical write to happen
immediately. The data must be terminated with a new-line character.

916
Supplied Packages

Usage
PROCEDURE fflush(file IN file_type);

Exceptions
INVALID_OPERATION, INVALID_FILEHANDLE, and WRITE_ERROR

FCLOSE() / FCLOSE_ALL()
The FCLOSE ( ) procedure is called to physically close the file handle itself. If there is pending buffered
data to be written, you could receive a WRITE_ERROR exception. It is good practice to call FFLUSH ( )
prior to calling FCLOSE ( ) .

The FCLOSE_ALL ( ) procedure should only be called in an emergency. It closes every file handle open
in a session but it does not change the state of the handles currently held. Calls to I S_OPEN ( ) will still
return TRUE but you will receive a WRITE ERROR if you attempt to write to the file. You would only use
this procedure when exiting a program from an exception.

Usage
PROCEDURE fclose(file IN OUT file_type);

PROCEDURE fclose_all;

Example
Close the current file:

Exceptions
INVALID_FILEHANDLE and WRITE_ERROR

Summary
UTL_FILE gives you the ability to read and write ASCII and Unicode files from within PLISQL. You
just need to be mindful of the file's mode and state when passing around its handle and make sure you
properly handle the possible exceptions that can be raised.

DBMS_JOB
The DBMS_JOB package allows the developer to schedule PL/SQL routines to run unattended at some
time in the future. Those familiar with the at or cron UNIX commands, or task scheduling with
Windows, will see that DBMS_JOB is basically the same thing.

Configuration
You need to configure your database to support jobs. You need to set up the following database
initialization parameters:

917
Appendix B

0 JOB_QUEUE_PROCESSES - this tells Oracle how many processes should be started to handle
the jobs in the queue.
0 JOB_QUEUE_INTERVAL - this tells Oracle, in seconds, how often it should scan the queue for
jobs that need to be executed (Note that this parameter is obsolete in Oracle 9t).

Example
JOB_QUEUE_PROCESSES = 2
JOB_QUEUE_INTERVAL = 300

This tells Oracle to start to process and scan the queue every 5 minutes for jobs ready to run.

Procedures Functions
BROKEN() BACKGROUND_PROCESS ( ) - returns BOOLEAN

CHANGE() IS_JOBQ () -returns BOOLEAN


INSTANCE ()

INTERVAL ()

ISUBMIT()

NEXT_DATE ()

REMOVE()

RUN()

SUBMIT ()

USER_EXPORT ()

WHAT()

Listing Your Jobs


Job definitions, like everything else in the database, are stored in the data dictionary. You can view your
jobs and the status of each using the dictionary view USER_JOBS:

SQL> deac uaer_j oba


Name Null? Type

JOB NOT NULL


NUMBER
LOG_USER NOT NULL
VARCHAR2(30)
PRIV_USER NOT NULL
VARCHAR2(30)
SCHEMA_USER NOT NULL
VARCHAR2(30)
LAST_DATE DATE
LAST_SEC VARCHAR2(8)
THIS_DATE DATE
THIS_SEC VARCHAR2(8)
NEXT_DATE NOT NULL DATE
NEXT_SEC VARCHAR2(8)

918
Supplied Packages

TOTAL_TIME NUMBER
BROKEN VARCHAR2(1)
INTERVAL NOT NULL VARCHAR2(200)
FAILURES NUMBER
WHAT VARCHAR2(4000)
NLS_ENV VARCHAR2(4000)
MISC_ENV RAW(32)
INSTANCE NUMBER

You can get all the information about each job. You can see what jobs you have, what they will run {the
WHAT column), when they are scheduled to run next (the NEXT_DATE column), how long it took them to
run (the TOTAL_TIME column), and even find out if they were successfully run on their last attempt (the
BROKEN column will tell you if the job failed).

Never attempt to change the values in the USER_JOBS view manually via SQL. Always use the
DBMS_JOBS supplied package to manage your jobs.

It is important, if you have recurring database jobs, to regularly monitor them to make sure that they are
all running successfully. Using the following query:

select job, what


from user_jobs
where broken= 'Y';

will tell you if you have any jobs that need your attention. Oracle will attempt to run a job 16 times.
If it is not successfully after 16 attempts, it will no longer attempt its execution. You will then need
to manually run the job. Once it has been executed successfully, Oracle will then manage its
execution again.

SUBMIT()/ #SUBMIT()
These procedures are how you get a job into the queue. SUBMIT () returns the job ID via an OUT
parameter. Using I SUBMIT (),you would supply your own ID number.

Usage
PROCEDURE submit job OUT BINARY_INTEGER,
what IN VARCHAR2,
next_date IN DATE DEFAULT sysdate,
interval IN VARCHAR2 DEFAULT 'null',
no_parse IN BOOLEAN DEFAULT FALSE,
instance IN BINARY_INTEGER DEFAULT 0,
force IN BOOLEAN DEFAULT FALSE);

PROCEDURE isubmit job IN BINARY_INTEGER,


what IN VARCHAR2,
next_date IN DATE,
interval IN VARCHAR2 DEFAULT 'null',
no _parse IN BOOLEAN DEFAULT FALSE);

919
Appendix B

Parameters
0 JOB - This is the ID of the job in the queue. You can use this ID to modify and remove
the job.
0 WHAT- This is the block of PLISQL that will be executed by the job.
0 NEXT_DATE- This is the next time Oracle will attempt to run the job. Leave it NULL to only
have the job run once then remove itself.
0 INTERVAL - This is the formula to determine when is the next time the job will schedule itself.
0 NO_PARSE- A Boolean flag to tell Oracle to either parse the block of code when the job is
submitted (FALSE, the default) or when the job is first run (TRUE).
0 INSTANCE - In a multi-instance environment, this tells Oracle which instance should handle
the job execution. The default is 0.
0 FORCE - A Boolean flag that when set to TRUE, tells Oracle to accept the instance ID
regardless of whether or not the instance is currently running. FALSE is the default.

Example
Create a job to insert the date and time into a table every 5 minutes:

declare
l_job number;
begin
dbms_job.submit(
l_job,
'insert into T values ( to_char( sysdate, '00-MON-YYYY HH24:MI:SS' ) ); ',
sysdate,
'sysdate+(S/1440) • );
end;

There are a few things to note in this example. Firstly, we only supplied 4 parameters to the SUBMIT ( )
procedure, but it takes 7. The last three parameters are defaulted so we do not need to supply values for
them. Secondly, this job is scheduled to run the next time the job queue is processed. We know that
because it was submitted with a NEXT_DATE of sysdate, which says, run it right now. Lastly, the
interval was set to the string sysdate+ ( 5 I 1440) and not the value ofthat expression. Understand
that the interval is a formula to determine the next run-time, not the actual next run-time value.

Slipping Interval Problem


Over time, intervals can seem to slip. That means that the jobs will continually take more time in
between runs than the interval allows. This is not a bug in Oracle. It is a function of how often the job
queue is scanned, the number of jobs that need executing, and how your interval is defined.

In our example above, we tell the job to run every 5 minutes. But what if the database parameter
JOB_QUEUE_INTERVAL is set to 600, or every 10 minutes. It is impossible for Oracle to execute that
job every five minutes if it only scans the queue every 10 minutes. It will be run, in this example, but
only every 10 minutes or so.

920
Supplied Packages

Even if the queue was scanned every five minutes, there is no guarantee that this job will run every five
minutes on the nose. Consider, the job queue wakes up at 12:00:00 exactly and finds our job to run. It
first calculates the next run-time, which in our case would be 12:05:00. Next, it runs our job, which
takes some amount of time. There may also be other jobs that need executing. The database then runs
each of them in turn, first calculating their next run date and then running them. This too takes some
amount of time.

Let's say 2 minutes have passed since the job queue process awoke. It is now 12:02:00. The database
now rests for 5 minutes before again scanning the queue for jobs to run. It wakes up again at 12:07:00.
Our job was scheduled to run at 12:05:00. Herein lies the slipping interval problem. The NEXT_TIME
attribute of a job is not when exactly the job will run, but rather the earlie sf date which the database will
consider running the job.

To minimize the "slipping" you can lower the sleep time between job queue scans. If you have a lot of
jobs in the queue that run frequently, you might consider adding more processes to handle the
workload. And writing a more exact INTERVAL formula will help minimize the slipping. If you want a
job to run at 3AM every day, don't schedule the job like this:

dbms_job.submit(
l_job,
'my_proc•,
trunc(sysdate+l) + (3/60),
'sysdate+l' ) ;

The next date will slip. Instead code your interval like this

dbms_job . submit(
l_job,
'my_proc',
trunc(sysdate+l) + (3/60),
'trunc(sysdate+l) + (3/60)' );

This ensures that no matter what time your job runs, it will schedule itself to run tomorrow at 3AM. If it
does not run until 03:04AM, no big deal, it will still be scheduled to run at 03:00 tomorrow.

RUN()
The procedure RUN () will cause the database to execute the job immediately. The NEXT_DATE is
recomputed. Even if a job is broken, its execution will be attempted. If, upon your frequent checks of
the job queue, you find a broken job that the database is no longer attempting to run, you can fix it, and
then using DBMS_JOB. RUN ( ) , run the job and get the database to manage its execution again.

If you are running multiple instances, then you need to need to either set FORCE to TRUE, which will
allow the job to run in the foreground process or set to FALSE if you are connected to the appropriate
instance for running that particular job. An exception will be raised if you attempt to execute the job
from the wrong instance and FORCE was set to FALSE.

Usage
PROCEDURE run job IN BINARY_INTEGER,
force IN BOOLEAN DEFAULT FALSE);

921
Appendix B

Example
dbms_job.run( 12345 l;

REMOVE()
Use this procedure to remove a job from the queue. Any job in the queue not currently running can be
removed using this procedure.

Usage
PROCEDURE remove ( job IN BINARY_INTEGER );

Example
dbms_job . remove( 12345 ); __________________________________________________~

CHANGE()
The CHANGE procedure allows you to modify the user-set table attributes for a given job. The downside
to using CHANGE () is that you must supply the WHAT, NEXT_DATE, and INTERVAL whether or not you
wish to change their values.

Usage
PROCEDURE change job IN BINARY_INTEGER,
what IN VARCHAR2,
next_date IN DATE,
interval IN VARCHAR2,
instance IN BINARY_INTEGER DEFAULT NULL,
force IN BOOLEAN DEFAULT FALSE);

Example
dbms_job . change ( 12345,
'insert into t values ( sysdate ); ',
sysdate,
'sysdate+1' ~
~ ~;--------------------------------------------~

WHAT()
The procedure WHAT () allow you to just change the WHAT of the given job.

Usage
PROCEDURE what job IN BINARY_INTEGER,
what IN VARCHAR2 ) ;

Example
dbms_job.what( 12345, 'update t set cnt cnt + 1;' l; ------------~---------'

922
Supplied Packages

NEXT_DATE()
The procedure NEXT_DATE () allows you to just change the NEXT_DATE attribute of the given job.

Usage
PROCEDURE next_date (job IN BINARY_INTEGER, next_date IN DATE );

Example
Change the NEXT_DATE to 5 hours from right now:

INSTANCE()
The INSTANCE () procedure allow you to change the INSTANCE attribute of the given job. If FORCE is
TRUE, then the instance ID that you are setting need not be up, but if it is FALSE (the default) then the
instance ID must currently be up and running.

Usage
PROCEDURE instance ( job IN BINARY_INTEGER,
instance IN BINARY_INTEGER,
force IN BOOLEAN DEFAULT FALSE);

Example
Change the instance ID to 3 even though instance 3 is not currently up.

INTERVAL()
The INTERVAL ( ) procedure allows you to change the INTERVAL attribute of the given job.

Usage
PROCEDURE interval job IN BINARY_INTEGER,
interval IN VARCHAR2 );

Example
Change the interval to be every hour, on the hour.

BROKEN()
The BROKEN ( ) procedure allows you to set the BROKEN status of the given job. BROKEN jobs are never
run. You can use this procedure to disable a job but keep it in the queue. Setting the BROKEN parameter
to TRUE sets the job's BROKEN status to Y. If you are re-enabling a job, then you can use the
NEXT_DATE parameter to set its next scheduled run-time.

923
Appendix B

Usage
PROCEDURE broken job IN BINARY_INTEGER,
broken IN BOOLEAN,
next_date IN DATE DEFAULT SYSDATE );

Example
Enable a broken job to run 15 minutes from now.

dbms_job.broken( 12345,
FALSE,
sysdate + (15/1440) );

UTL_RAW
The supplied package UTL_RAW is for work with the database type RAW. It is, as the name suggests, a
utilities package for manipulating RAWs. Since PLISQL does not allow the overloading of RAW and
VARCHAR2, this package is required. This package contains all the standard procedures and functions that
you would expect. Using the RAW data type is useful when working with binary data. Also the RAW data
type is not affected by characterset conversions if it is transferred between databases with alternative
charactersets. The specification can be found in $0RACLE_HOME/rdbms/ admin/utlraw. sql.

Here are the functions in this package (there are no procedures):

Functions
BIT_AND () -returns RAW COMPARE - returns NUMBER
BIT_COMPLEMENT () -returns RAW CONCAT () -returns RAW
BIT_OR () -returns RAW CONVERT ( ) - returns RAW
BIT_XOR () -returns RAW COPIES ( ) - returns RAW
CAST_FROM_BINARY_INTEGER () -returns RAW LENGTH ( ) - returns NUMBER

CAST_FROM_NUMBER ( ) - returns RAW OVERLAY ( ) - returns RAW

CAST_TO_BINARY_INTEGER () -returns BINARY_INTEGER REVERSE () -returns RAW

CAST_TO_NUMBER () -returns NUMBER SUBSTR ( ) - returns RAW

CAST_TO_NVARCHAR2 () -returns NVARCHAR2 TRANSLATE ( ) - returns RAW

CAST_TO_RAW () -returns RAW TRANSLITERATE () -returns


RAW
CAST_TO_VARCHAR2 () -returns VARCHAR2
XRANGE ( ) - returns RAW

CONCAT()
The CONCAT () function concatenates up to 12 RAWs into a single RAW. If the resulting RAW is over 32K,
a VALUE_ERROR is raised.

924
Supplied Packages

Usage
FUNCTION concat(rl IN RAW DEFAULT NULL,
r2 IN RAW DEFAULT NULL,
r3 IN RAW DEFAULT NULL,
r4 IN RAW DEFAULT NULL,
r5 IN RAW DEFAULT NULL,
r6 IN RAW DEFAULT NULL,
r7 IN RAW DEFAULT NULL,
r8 IN RAW DEFAULT NULL,
r9 IN RAW DEFAULT NULL,
rlO IN RAW DEFAULT NULL,
rll IN RAW DEFAULT NULL,
r12 IN RAW DEFAULT NULL) RETURN RAW;

Example
SQL> select utl_raw.concat( '9', '0102', •ff•, '0a2b' l from dual;

UTL_RAW.CONCAT('9', '0102', 'FF', '0A2B')

090102FFOA2B

CAST_TO_RAW()
The CAST_TO_RAW () function converts a VARCHAR2 of N data bytes into a RAW with the same number
of data bytes.

Usage
FUNCTION cast_to_raw(c IN VARCHAR2 CHARACTER SET ANY_CS) RETURN RAW;

Example
SQL> select utl_raw.cast_to_raw( 'Cameron' ) from dual;

UTL_RAW.CAST_TO_RAW('CAMERON')

43616D65726F6E

CAST_TO_VARCHAR2() / CAST_TO_NVARCHAR2()
The CAST_TO_VARCHAR2 () function is the opposite of the CAST_TO_RAW (). It will convert a RAW of N
data bytes into a VARCHAR2 with N data bytes. If the characterset of the database is different then the
result will probably be garbage. The CAST_TO_NVARCHAR2 () function works just like the
CAST_TO_RAW ( ) function except that it returns a NVARCHAR2 data type value.

Usage
FUNCTION cast_to_varchar2(r IN RAW) RETURN VARCHAR2;
FUNCTION cast_to_nvarchar2(r IN RAW) RETURN NVARCHAR2;

925
Appendix B

Example
SQL> select utl_raw.cast_to_varchar2( '43616D65726F6E') from dual;

UTL_RAW . CAST_TO_VARCHAR2('43616D65726F6E')

Cameron

LENGTH()
The function LENGTH ( ) returns the length of the imputed RAW value.

Usage
FUNCTION length(r IN RAW) RETURN NUMBER;

Example
It we take our raw value from the above example, we should get 7 since 'cameron' has a length of 7.

SQL> select utl_raw . length( '43616D65726F6E') from dual;

UTL_RAW . LENGTH('43616D65726F6E')

SUBSTR()
The SUBSTR ( ) function returns a RAW starting from position POS of the length LEN. If LEN is omitted
or NULL, the RAW starting at POS to the end of the RAW will be returned. If POS = 0, or LEN < 1 then a
VALUE ERROR exception is raised.

Usage
FUNCTION substr(r IN RAW,
pos IN BINARY_INTEGER,
len IN BINARY_INTEGER DEFAULT NULL) RETURN RAW;

Example

SQL> select utl_raw . substr( '0102030405', 3, 2) from dual;

UTL_RAW.SUBSTR('0102030405',3,2)

0304

926
Supplied Packages

TRANSLATE()
The TRANSLATE ( ) function, given a RAW R, will replace every occurrence of each byte in FROM_SET
with the corresponding positional byte in TO_SET. If a byte in FROM_SET is not present in R, it is
skipped. Any byte in FROM_SET without a matching positional byte in TO_SET will be removed from R.

Usage
FUNCTION translate{r IN RAW,
from_set IN RAW,
to_set IN RAW) RETURN RAW;

Example
In the following example, we want to replace every Ox02 byte with OxO 6. Since Ox03 does not have a
positional match in TO_SET, it is removed.

SQL> select utl_raw.translate( '0102030405', '0203', '06' ) from dual;

UTL_RAW.TRANSLATE{'010203040502', '0203', '06')

0106040506

TRANSLITERATE()
This works similar to TRANSLATE ( ) except that the result will always be the same length as the input
R. If TO_SET is shorter than FROM_SET then those values in TO_SET without a positional match in
FROM_SET will be replaced by either the first byte in PAD, if PAD is not NULL, or OxOO if PAD is omitted
or NULL;

Usage
FUNCTION transliterate{r IN RAW,
to_set IN RAW DEFAULT NULL,
from_set IN RAW DEFAULT NULL,
pad IN RAW DEFAULT NULL) RETURN RAW;

Example
SQL> select utl_raw. transliterate ( '010203040502' , '0809', '01020304' , 'Oa' )
from dual;

UTL_RAW.TRANSLITERATE{'010203040502', '0809', '01020304', '0A')

08090AOA0509

OVERLAY()
The function OVERLAY ()returns a raw with the specified portion of TARGET replaced with
ORVERLAY_STR. It will start at POS and replace LEN bytes of TARGET with LEN bytes of
OVERLAY_STR.

927
Appendix B

If this occurs ... ••. this is the result


Length of OVERLAY_STR <LEN OVERLAY_STR padded out to LEN bytes with the first PAD
byte
Length of OVERLAY_STR > LEN Extra bytes in OVERLAY_STR are ignored
POS + LEN > length of TARGET TARGET is extended to contain the entire length of
OVERLAY_STR

POS >length of TARGET TARGET is extended to length POS with PAD and then
extended LEN bytes of OVERLAY

Usage
FUNCTION overlay(overlay_str IN RAW,
target IN RAW,
pos IN BINARY_INTEGER DEFAULT 1,
len IN BINARY_INTEGER DEFAULT NULL,
pad IN RAW DEFAULT NULL) RETURN RAW;

Example
Replace the first two bytes of 0 x ' 0 10 2 0 3' with Ox ' AABB ' :

SQL> select utl_raw.overlay( 'aabb', '010203' ) from dual;

UTL_RAW.OVERLAY('AABB', '010203')

AABB03

Replace two bytes of Ox'0102 03' with Ox' AABB', starting at the second byte:

SQL> select utl_raw.overlay( •aabb', '010203', 2) from dual;

UTL_RAW.OVERLAY('AABB', '010203' ,2)

01AABB

Replace two bytes of Ox' 010 2 0 3 ' with Ox' AABB • , starting at the fifth byte. Since there is no fifth byte
in that string and no PAD was supplied, OxOO is used as the PAD.

SQL> select utl_raw.overlay( 'aabb', '010203', 5) from dual;

UTL_RAW.OVERLAY('AABB', '010203',5)

---
01020300AABB

Replace the second byte of 0 x ' 0 1 0 2 0 3 1 with the first byte of Ox ' AABB 1 •

928
Supplied Packages

SQL> select utl_raw.overlay( 'aabb', '010203', 2, 1 ) from dual;

UTL_RAW.OVERLAY('AABB', '010203',2,1)

01AA03

Replace the fifth byte of Ox' 010 2 0 3' with the first byte of Ox' AABB'. Since there are only three bytes
in Ox' 010203', it will be padded out with PAD.

SQL> select utl_raw.overlay( 'aabb', '010203', 5, 1, 'FF' ) from dual;

UTL_RAW. OVERLAY ( 'AABB' , '010203' , 5, 1, 'FF')

010203FFM

Exceptions
A VALUE_ERROR exception raised when:

0 OVERLAY is NULL

0 Length of result is longer than max length of a RAW


0 LEN<O

0 POS < 1

COPIES()
The COPIES () function returns N copies of R concatenated together.

Usage
FUNCTION copies(r IN RAW,
n IN NUMBER) RETURN RAW;

Example
SQL> select utl_raw.copies( '010203', 4) from dual;

UTL_RAW.COPIES('Ol0203',4)

010203010203010203010203

Exceptions
A VALUE ERROR exception is raised when:

0 R is NULL

0 R is 0 length
0 N< 1

0 Resulting RAW value is longer than the max length of a RAW

929
Appendix 8

XRANGE()
The XRANGE () function returns a RAW starting at the START_BYTE and including every byte in
succession to END_BYTE. If END_BYTE is less than START_BYTE, the range will wrap from Ox' FF' to
Ox' 01 ' and continue on to END_BYTE.

Usage
FUNCTION xrange(start_byte IN RAW DEFAULT NULL,
end_byte IN RAW DEFAULT NULL} RETURN RAW;

Example
SQL> select utl_raw.xrange( '01', '11' J from dual;

UTL_RAW.XRANGE('01', '11')

0102030405060708090AOBOCODOEOF1011

SQL> select utl_raw.xrange( 'fa', '06' } from dual;

UTL_RAW.XRANGE( 'FA', '06')

FAFBFCFDFEFF00010203040506

REVERSE()
The REVERSE () function will reverse the RAW from end to end; the first byte becomes the last, the
second byte becomes the second to last, and so on.

Usage
FUNCTION reverse(r IN RAW} RETURN RAW;

Example
SQL> select utl_raw . reverse( '0102030405' ) from dual;

UTL_RAW.REVERSE('0102030405 ' )

0504030201

Exception
A VALUE_ERROR is raised when the input R is Null.

COMPARE()
The COMPARE { ) function compares Rl and R2. If they differ in size, the shorter parameter will be
padded out with PAD. It will return 0 is they are the same, otherwise it will return the index of the first
mismatched byte.

930
Supplied Packages

Usage
FUNCTION compare(rl IN RAW,
r2 IN RAW,
pad IN RAW DEFAULT NULL) RETURN NUMBER;

Example

SQL> select utl_raw . compare( '010203', '01020304', '04' ) from dual;

UTL_RAW . COMPARE('010203', '01020304', '04')

SQL> select utl_raw . compare( '01050304', '01020304' ) from dual;

UTL_RAW.COMPARE('01050304', '01020304')

CONVERT()
The CONVERT () function will convert the raw R from the character set FROM_CHARSET to
TO_CHARSET.

Usage
FUNCTION convert(r IN RAW,
to_charset IN VARCHAR2,
from_charset IN VARCHAR2) RETURN RAW;

Exceptions
A VALUE_ERROR exception is raised when:

0 R is NULL or 0 length
0 TO_CHARSET or FROM_CHARSET NULL or 0 length
0 TO_CHARSET or FROM_CHARSET is not supported by the Oracle server

BIT_AND()
The BIT_AND () function returns the bitwise logical AND of the supplied raws Rl and R2. If Rl and R2
are not of the same length, then bit for bit they are ANDed and the remaining bits of the longer are
appended. If either parameter is NULL, NULL is returned.

Usage
FUNCTION bit_and(rl IN RAW,
r2 IN RAW) RETURN RAW;

931
Appendix B

Example
Bitwise AND OxOl and AND Ox0302. Remember 01 is 1 in binary and 03 is 11 in binary. Using AND
should get you 01.

SQL> select utl_raw.bit_and( '01', '0302' ) from dual;

UTL_RAW.BIT_AND('01', '0302')

0102

BIT_OR()
The BIT_OR () function returns the bitwise logical OR of the supplied parameters Rl and R2. If Rl and
R2 are of different lengths, the OR'ing is terminated at the last byte of the shorter and the extra bytes are
appended to the result. If either parameter is NULL, NULL is returned.

Usage
FUNCTION bit_or(rl IN RAW,
r2 IN RAW) RETURN RAW;

Example
SQL> select utl_raw.bit_or( '01', '0302' ) from dual;

UTL_RAW.BIT_OR('01', '0302')

0302

BIT_XOR()
The BIT_XOR () function returns the bitwise exclusive OR of two RAW values, Rl and R2. If either
parameter is longer than the other, the exclusive OR is terminated after the last byte of the shorter
parameter and the remaining bytes are appended to the result. If either parameter is NULL, NULL is
returned.

Usage
FUNCTION bit_xor(rl IN RAW,
r2 IN RAW) RETURN RAW;

Example
SQL> select utl_raw.bit_xor( '01', '0302 ' ) from dual;

UTL_RAW.BIT-XOR('Ol', '0302')

0202

932
Supplied Packages

BIT_COMPLEMENT()
The BIT_COMPLEMENT () function returns the bitwise complement of the parameter R. It will return
NULL if R was NULL.

Usage
FUNCTION bit_complement(r IN RAW) RETURN RAW;

Example
SQL> select utl_raw.bit_complement( '010203' ) from dual;

UTL_RAW.BIT_COMPLEMENT('010203')

FEFDFC

CAST_FROM_NUMBER()
The CAST_FROM_NUMBER () function returns the binary representation of a number as a RAW.

Usage
FUNCTION cast_from_number(n IN NUMBER) RETURN RAW;

Example
SQL> select utl_raw.cast_from_number( 123 . 45 ) from dual;

UTL_RAW.CAST_FROMLNUMBER(123.45)

C202182E

CAST_TO_NUMBER()
The CAST_TO_NUMBER ( ) function casts the binary representation of a number in a raw to a number.

Usage
FUNCTION cast_to_number(r IN RAW) RETURN NUMBER;

Example
SQL> select utl_raw.cast_to_number( 'c202182e' ) from dual;

UTL_RAW.CAST_TO~ER('C202182E')

123.45

CAST_FROM_BINARY_INTEGER()
The CAST_FROM_BINARY_INTEGER () function returns the binary representation of a binary integer as
a RAW.

933
Appendix B

Usage
FUNCTION cast_from_binary_integer(n IN BINARY_INTEGER,
endianess IN PLS_INTEGER DEFAULT 1)
RETURN RAW;

Example
SQL> select utl_raw.cast_frornLbinary_integer( 12345 ) from dual;

UTL_RAW.CAST_FROM_BINARY_INTEGER(12345)

00003039

CAST_TO_BINARY_INTEGER()
The CAST_TO_BINARY_INTEGER () function casts the binary representation of a binary integer in a
raw to a binary integer.

Usage
FUNCTION cast_to_binary_integer(r IN RAW,
endianess IN PLS_INTEGER DEFAULT 1)
RETURN BINARY_INTEGER;

Example
SQL> select utl_raw.cast_to_binary_integer( '00003039' ) from dual;

UTL_RAW.CAST_TO_BINARY_INTEGER('00003039')

12345

DBMS_LOB
Since Oracle 8, Oracle has supported Large Objects, LOBS. Initially, there was no native support for
these objects. The DBMS_LOB package was created to allow developers to manipulate LOBs. In Oracle 9,
native support exists for some of the features in this package but the package still exists to provide both
the additional functionality for BFILES and backwards compatibility. The spec for DBMS_LOB can be
found in $0RACLE_HOME/rdbms/admin/dbmslob. sql.

934
Supplied Packages

Here are its functions and procedures:

Procedures Functions
APPEND () COMPARE () - returns NUMBER ( 3 8)
CLOSE () FILEEXISTS () - returns NUMBER ( 3 8)
COPY() FILEISOPEN () -returns NUMBER ( 3 8)
CREATETEMPORARY()
GETCHUNKSIZE () -returns NUMBER ( 3 8)
ERASE ()
GET LENGTH ( ) - returns NUMBER ( 3 8)
FILECLOSE ()
INSTR () - returns NUMBER ( 3 8)
FILECLOSEALL ()
ISO PEN () - returns NUMBER ( 3 8)
FILEGETNAME ()
IS TEMPORARY () - returns NUMBER ( 3 8)
FILEOPEN()
FREETEMPORARY ( ) SUBSTR ( ) - returns RAW

LOADFROMFILE ( ) SUBSTR ( ) - returns VARCHAR2

OPEN()
READ()
TRIM()
WRITE ()
WRITEAPPEND ( )

We saw LOBs introduced in Chapter 3, and more information can be found in the Oracle
documentation Application Developers Guide - Large Objects. LOBs are good for storing unstructured data
like images, video, music, and when you want to store your data outside the database on the file system.

The DBMS_LOB package acts upon the LOB locator. This locator can point to either:

0 Internal LOB - These are LOBs that are defined in SQL and are columns of database tables.
0 External LOB -These are locators to physical external files located in a DIRECTORY object.
These LOBs are knows as BFILES.
0 Temporary LOB - These LOBs are defined in some programming interface like PLISQL or OCI
(Oracle Call Interface for C). These are mainly for performing transformations on LOB data.

LOBs can be up to 4Gb in size but PLISQL VARCHAR2s and RAWs can only be 32767K. This can be an
issue if you are attempting to convert a LOB into a VARCHAR2 or a RAW.

Dealing with LOBs can be a bit tricky. An empty LOB and NULL is not the same thing. You will get an
error if you attempt to perform LOB operations on a NULL. There is a built-in function
EMPTY_CLOB ()that will allow you to create an empty LOB to avoid this error:

935
Appendix 8

SQL> create table my_lob(


2 id number,
3 c clob )
4 I

Table created.

SQL> insert into my_lob values ( 1, empty_clob() );

1 row created.

Most of the CLOB manipulations are now, as of 9i, supported directly in SQL. SUBSTR (), INSTR ()
and TRIM (),now work on LOBs as well as VARCHAR2s. BFILES still need to be accessed and
manipulated through the DBMS_LOB package. If you want to store your .pdf files on the filesystem but
modify and maintain them in the database you can do the following.

First create a DIRECTORY.

SQL> connect system/manager as sysdba


Connected.

SQL> create or replace directory wrox_dir as 'C:\Temp';

Di rectory created.

SQL> grant read, write on direc tory wrox_dir to public;

Grant succeeded.

Now, create a table to store the BFILE locator and insert a row.

SQL> connect chris/chris


Connected.

SQL> create table bfile_table(


2 name varchar2(255),
3 the_file bfile ) ;

Table created.

SQL> insert into bfile_table values ( 'doc 1', bfilename( 'WROx_DIR', •my_doc.pdf'
) ) ;

1 row created.

SQL> commit;

Commit complete.

936
Supplied Packages

There is no guarantee that the file my_doc. pdf exists. Oracle cannot manage files not in the database.
To see if it is a valid file we could run the following:

SQL> declare
2 l_bfile bfile;
3 l_dir_alias varchar2(2000);
4 !_filename varchar2(2000);
5 begin
6 select the_file
7 into l_bfile
8 from bfile_table
9 where name= 'doc 1'·
10 dbms_lob.fileopen( l_bfile, dbms_lob.file_readonly );
11 if dbms_lob.fileexists( ljbfile l = 1 then
12 dbms_output.put_line( 'Valid file' );
13 else
14 dbms_output.put_line( 'Not a valid file' );
15 end if;
16 if dbms_lob.fileisopen( l_bfile ) = 1 then
17 dbms_lob.fileclose( l_bfile ) ;
18 end if;
19 end;
20 I

Valid file

PL/SQL procedure successfully completed.

That ensures that the file is on the file system.

Exceptions
The following is a list of the DBMS_LOB exceptions that the package can raise:

Exception Error Description


Code
INVALID_ARGVAL 21560 An argument passed in was NULL, invalid or out of
range.
ACCESS_ERROR 22925 You are attempting to write more that 4 Gb to the
LOB.

NOEXIST_DIRECTORY 22285 The directory does not exist.


NOPRIV_DIRECTORY 22286 Oracle does not have permission to write to the
directory or the file.
INVALID_DIRECTORY 22287 The DIRECTORY object being accessed is not valid.
OPERATION_FAILED 22288 The operation attempted failed.
Table continued on following page

937
Appendix B

Exception Error Description


Code
UNOPENED_FILE 22289 The file is not opened.
OPEN_TOOMANY 22290 The maximum number of files has been opened.
NO_DATA_FOUND Attempt was made to read a NULL LOB or read past
the end of the LOB.
VALUE_ERROR 6502 Invalid argument type passed into a procedure.

Just like in UTL_FILE, it is important to close all of your LOB locators. By default, they will be all closed
at the end of a session, but you should make an effort to manually close them in your program.

Most of the procedures and functions in this package are overloaded to support both CLOBs and BLOBs.

Let's take a look at the APis.

APPEND()
The APPEND () procedure appends the SRC_LOB to the end of the DEST_LOB. It is overloaded for both
BLOBs and CLOBs.

Usage
PROCEDURE append(dest_lob IN OUT NOCOPY BLOB,
src_lob IN BLOB);

PROCEDURE append(dest_lob IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


src_lob IN CLOB CHARACTER SET dest_lob%CHARSET);

CLOSE()
The procedure CLOSE ( ) will close any previously opened internal or external LOBs. It is overloaded
for BLOBs, CLOBs, and BFILEs.

Usage
PROCEDURE close(lob_loc IN OUT NOCOPY BLOB);

PROCEDURE close(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS);

PROCEDURE close(file_loc IN OUT NOCOPY BFILE);

COMPARE()
The COMPARE () function will compare two similar LOBs, or part of them as defined by the input
ranges. If equal, zero is returned. Otherwise a non-zero value is returned. If you are comparing BFILEs,
they must already have been opened. It is overloaded for as, CLOBs, and BFILEs.

938
Supplied Packages

Usage
FUNCTION compare(lob_1 IN CLOB CHARACTER SET ANY_CS,
lob_2 IN CLOB CHARACTER SET lob_1%CHARSET,
amount IN INTEGER .- 4294967295,
offset- 1 IN INTEGER .- 1,
offset_2 IN INTEGER .- 1)
RETURN INTEGER;

FUNCTION compare(lob_1 IN BLOB,


lob_2 IN BLOB,
amount IN INTEGER := 4294967295,
offset- 1 IN INTEGER .- 1,
offset_2 IN INTEGER .- 1)
RETURN INTEGER;

FUNCTION compare(file_1 IN BFILE,


file_2 IN BFILE,
amount IN INTEGER,
offset- 1 IN INTEGER .- 1,
offset_2 IN INTEGER .- 1)
RETURN INTEGER;

Example
SQL> declare
2 c1 clob :='chris';
3 c2 clob := •sean';
4 begin
5 dbms_output . put_line(
6 dbms_lob.compare( c1, c2) );
7 dbms_output.put_line(
8 dbms_lob.compare( c1, c2, 1, 5, 1) );
9 end;
10 I
-1
0

PL/SQL procedure successfully completed.

COPY()
The COPY () procedure will copy the AMOUNT of the SRC_LOB starting at SRC_OFFSET to the DEST_LOB
starting at the DEST_OFFSET. If the DEST_OFFSET is beyond its end, non-Null padding will be
appended before the copy takes place. The procedure is overloaded to copy both BLOBs and CLOBs.

Usage
PROCEDURE copy(dest_lob IN OUT NOCOPY BLOB,
src_lob IN BLOB,
amount IN INTEGER,
dest_offset IN INTEGER .- 1,
src_offset IN INTEGER .- 1);

939
Appendix B

PROCEDURE copy(dest_lob IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


src_lob IN CLOB CHARACTER SET dest_lob%CHARSET,
amount IN INTEGER,
dest_offset IN INTEGER : = 1 ,
src_offset IN INTEGER := 1);

CREATETEMPORARYO
The CREATETEMPORARY () procedure creates a temporary BLOB or CLOB in your default temporary
tablespace. The CACHE parameter tells whether or not the LOB should be saved into the buffer cache.
The DUR parameter tells Oracle when the LOB should be cleaned up at the end of the session or call.
Use the global constants DBMS_LOB. SESSION and a for DUR's value.

Usage
PROCEDURE createtemporary(lob_loc IN OUT NOCOPY BLOB,
cache IN BOOLEAN,
dur IN PLS_INTEGER := 10);

PROCEDURE createtemporary(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


cache IN BOOLEAN,
dur IN PLS_INTEGER .- 10);

ERAS EO
The erase procedure erases some or all of a BLOB or CLOB. It starts at OFFSET and erases AMOUNT
bytes/characters. If a+ OFFSET is greater than the length of the LOB, then everything from OFFSET is
erased and the exact number of bytes/ characters erased are returned in the IN OUT parameter
AMOUNT. The length of the LOB remains the same. The erased bytes/ characters are zeroed out with
Null-bytes or spaces.

Usage
PROCEDURE erase(lob_loc IN OUT NOCOPY BLOB,
amount IN OUT NOCOPY INTEGER,
offset IN INTEGER := 1);

PROCEDURE erase(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


amount IN OUT NOCOPY INTEGER,
offset IN INTEGER := 1);

Example
SQL> declare
2 l_c clob := 'Hello World!';
3 l_a number := 9;
4 begin
5 dbms_lob.erase( l_c, l_a, 6 );
6 dbms_output.put_line( 'The clob now=*' I I l_c I I '*' );
7 dbms_output.put_line( 'The amount that was erased was: ' II l_a );
8 end;
9 I

940
Supplied Packages

The clob now = *Hello *


The amount that was erased was: 7

PL/SQL procedure successfully completed.

Notice that L_C is still as long as it was; just the string 'World!' was erased. And we asked to erase 9
characters, but given the offset we supplied, only 7 were actually erased.

FILECLOSE()
The FILECLOSE () procedure will close a previously open BFILE.

Usage
PROCEDURE fileclose{file_loc IN OUT NOCOPY BFILE};

FILECLOSEALL()
The FILECLOSEALL () procedure will close all BFILES opened in a session.

Usage
PROCEDURE filecloseall;

FILEEXISTS()
The FILEEXISTS () function is used to determine if the FILE_LOC points to a valid file on the file
system. It returns 0 if the file does not exist, 1 if it does.

Usage
FUNCTION fileexists{file_loc IN BFILE}
RETURN INTEGER;

FILEGETNAME()
The FILEGETNAME () procedure returns via OUT parameters, DIR_ALIAS and FILENAME, the
directory alias and the filename of the FILE_LOC. Not the physical directory and filename but rather
that of the FILE_LOC.

Usage
PROCEDURE filegetname{file_loc IN BFILE,
dir_alias OUT VARCHAR2,
filename OUT VARCHAR2};

Example
SQL> declare
2 l_bfile bfile;
3 l_dir_alias varchar2(2000);

941
Appendix B

4 l_filename varchar2(2000);
5 begin
6 select the_file
7 into l_bfile
8 from bfile_table
9 where name= 'doc 1';
10 dbms_lob.fileopen( l_bfile, dbms_lob.file_readonly );
11 if dbms_lob.fileexists( l_bfile ) = 1 then
12 dbms_lob.filegetname( l_bfile, l_dir_alias, !_filename);
13 dbms_output.put_line( 'Directory alias: ' I I l_dir_alias );
14 dbms_output.put_line( 'Filename: ' I I l_filename );
15 end if;
16 if dbms_lob.fileisopen( l_bfile ) = 1 then
17 dbms_lob.fileclose( l_bfile );
18 end if;
19* end;
SQL> I
Directory alias: WROX_DIR
Filename: my_doc.pdf

PL/SQL procedure successfully completed.

FILEISOPEN()
The FILEISOPEN () function determines if the supplied BFILE was previously opened. It returns 0 if
the file is not open, 1 if it is open.

Usage
FUNCTION fileisopen(file_loc IN BFILE)
RETURN INTEGER;

FILEOPEN()
The FILEOPEN () procedure is used to open an external BFILE.

Usage
PROCEDURE fileopen(file_loc IN OUT NOCOPY BFILE,
open_mode IN BINARY_INTEGER := file_readonly);

FREETEMPORARY()
The FREETEMPORARY ( ) procedure will free a previously allocated temporary LOB.

Usage
PROCEDURE freetemporary{lob_loc IN OUT NOCOPY BLOB);

PROCEDURE freetemporary{lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS);

942
Supplied Packages

GETCHUNKSIZE()
The GETCHUNKSIZE () function returns the amount of space used in the LOB chunk to store the LOB
value. It helps performance if you read and write LOBs by this amount. Writes are versioned by the
chunk so if you write a chunk at a time there is no extra or duplicated versioning done. The function is
overloaded for both CLOB and BLOB.

Usage
FUNCTION getchunksize(lob_loc IN BLOB)
RETURN INTEGER;

FUNCTION getchunksize(lob_loc IN CLOB CHARACTER SET ANY_CS)


RETURN INTEGER;

Example
SQL> select dbms_lob.getchunksize( c ) from my_lob;

DBMS_LOB.GETCHUNKSIZE(C)

4036

Notice, it is a little less than 4K, the database block size. That is because there is little system-related
information stored with the LOB.

GETLENGTH()
The GETLENGTH ( ) function returns the length of the LOB locater. It is overloaded for all three LOB
types, CLOB, BLOB, and BFILE. In 9i, the built-in function LENGTH () will also work.

Usage
FUNCTION getlength(lob_loc IN BLOB)
RETURN INTEGER;

FUNCTION getlength(lob_loc IN CLOB CHARACTER SET ANY_CS)


RETURN INTEGER;

FUNCTION getlength(file_loc IN BFILE)


RETURN INTEGER;

INSTR()
The INSTR () function returns the position of NTH occurrence of PATTERN in the LOB starting at the
position OFFSET. It is overloaded for CLOBs, BLOBs, and BFILEs. In 9i, the built-in function INSTR ()
will work on LOBS as well as VARCHAR2.

943
Appendix 8

Usage
FUNCTION instr(lob_loc IN BLOB,
pattern IN RAW,
offset IN INTEGER := 1,
nth IN INTEGER := 1)
RETURN INTEGER;

FUNCTION instr(lob_loc IN CLOB CHARACTER SET ANY_CS,


pattern IN VARCHAR2 CHARACTER SET lob_loc%CHARSET,
offset IN INTEGER .- l,
nth IN INTEGER := 1)
RETURN INTEGER;

FUNCTION instr(file_loc IN BFILE,


pattern IN RAW,
offset IN INTEGER .- 1,
nth IN INTEGER .- 1)
RETURN INTEGER;

IS OPEN()
The I SOP EN ( ) function is used to determine if a LOB was previously opened. It returns 1 if the LOB is
open, 0 otherwise. The function is overloaded to support BLOB, CLOB, and BFILE.

Usage
function isopen(lob_loc in blob)
RETURN INTEGER;

function isopen(lob_loc in clob character set any_cs)


RETURN INTEGER;

function isopen(file_loc in bfile)


RETURN INTEGER;

ISTEMPORARY()
The ISTEMPORARY () function is used to determine if a locator was created with the
CREATETEMPORARY () procedure. It will return 1 if it is True, otherwise 0. The function is overloaded
to support CLOB and BLOB.

Usage
FUNCTION istemporary(lob_loc IN BLOB)
RETURN INTEGER;

FUNCTION istemporary(lob_loc IN CLOB CHARACTER SET ANY_CS)


RETURN INTEGER;

944
Supplied Packages

LOADFROM FILE()
The LOADFROMFILE () procedure allows the developer to copy the data from a BFILE into a BLOB or
CLOB. The AMOUNT and OFFSETs can be specified for both the LOB and the BFILE.

Usage
PROCEDURE loadfromfile(dest_lob IN OUT NOCOPY BLOB,
src_lob IN BFILE,
amount IN INTEGER,
dest_offset IN INTEGER .- 1,
src_offset IN INTEGER := 1);

PROCEDURE loadfromfile(dest_lob IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


src_lob IN BFILE,
amount IN INTEGER,
dest_offset IN INTEGER := 1,
src_offset IN INTEGER := 1);

OPEN()
The OPEN ( ) procedure allows the developer to open both internal and external locators with the mode
supplied. The modes are LOB_READONLY and LOB_READWRITE. External LOBs, BFILEs, can only be
opened in LOB_READONLY mode.

Usage
PROCEDURE open(lob_loc IN OUT NOCOPY BLOB,
open_mode IN BINARY_INTEGER);

PROCEDURE open(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


open_mode IN BINARY_INTEGER);

PROCEDURE open(file_loc IN OUT NOCOPY BFILE,


open_mode IN BINARY_INTEGER := file_readonly) ;

READ()
The READ ( ) procedure reads AMOUNT of characters/bytes into the OUT parameter BUFFER, starting at
the position OFFSET. The procedure is overloaded to support all three LOB types.

Usage
PROCEDURE read(lob_loc IN BLOB,
amount IN OUT NOCOPY BINARY_INTEGER,
offset IN INTEGER,
buffer OUT RAW);

PROCEDURE read(lob_loc IN CLOB CHARACTER SET ANY_CS,


amount IN OUT NOCOPY BINARY_INTEGER,
offset IN INTEGER,
buffer OUT VARCHAR2 CHARACTER SET lob_loc%CHARSET) ;

PROCEDURE read(file_loc IN BFILE,

945
Appendix B

amount IN OUT NOCOPY BINARY_INTEGER,


offset IN INTEGER,
buffer OUT RAW);

SUBSTR()
The SUBSTR () function will return the AMOUNT of characters/bytes starting at the OFFSET. This
function is overloaded to support all three LOB types. In 9i, the built-in function SUBSTR () also works
on LOBs.

Usage
FUNCTION substr(lob_loc IN BLOB,
amount IN INTEGER .- 32767,
offset IN INTEGER := 1)
RETURN RAW;

FUNCTION substr(lob_loc IN CLOB CHARACTER SET ANY_CS,


amount IN INTEGER := 32767,
offset IN INTEGER := 1)
RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;

FUNCTION substr(file_loc IN BFILE,


amount IN INTEGER := 32767,
offset IN INTEGER . - 1)
RETURN RAW;

TRIM()
The TRIM ( ) procedure will shorten the supplied LOB to the length NEWLEN. It is overloaded to support
CLOBs and BLOBs. The built-in function TRIM () now works with LOBs directly in 9i.

Usage
PROCEDURE trim(lob_loc IN OUT NOCOPY BLOB,
newlen IN INTEGER);

PROCEDURE trim(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


newlen IN INTEGER);

WRITE()
The WRITE ( ) procedure writes the AMOUNT of characters/bytes in the BUFFER into the LOB starting at
the position OFFSET. It is overloaded to support both CLOBs and BLOBs. If there is less data in BUFFER
than AMOUNT specified, an error is raised. If there is more data in BUFFER, then only AMOUNT is written.
If the OFFSET is greater than the LOB's length, the LOB is padded out and then the BUFFER is written.
The procedure is overloaded to support CLOB and BLOB.

Usage
PROCEDURE write(lob_loc IN OUT NOCOPY BLOB,
amount IN BINARY_INTEGER,
offset IN INTEGER,
buffer IN RAW);

946
Supplied Packages

PROCEDURE write(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


amount IN BINARY_INTEGER,
offset IN INTEGER,
buffer IN VARCHAR2 CHARACTER SET lob_loc%CHARSET);

Example
SQL> declare
2 l_clob clob := '12345';
3 begin
4 dbms_lob.write( l_clob, 2, 3, 'AB' );
5 dbms_output.put_line( l_clob );
6 dbms_lob.write( l_clob, 2, 9, 'CD' );
7 dbms_output.put_line( l_clob );
8 end;
9 I
12AB5
12AB5 CD

PLISQL procedure successfully completed.

Notice the CLOB was padded out with spaces to accommodate the larger OFFSET.

WRITEAPPEND()
The WRITEAPPEND ( ) procedure writes the AMOUNT of the BUFFER to the end of the LOB_LOC
supplied. If the BUFFER is smaller than the AMOUNT supplied, an error occurs. If the BUFFER is greater,
then only the AMOUNT is written.

Usage
PROCEDURE writeappend(lob_loc IN OUT NOCOPY BLOB,
amount IN BINARY_INTEGER,
buffer IN RAW);

PROCEDURE writeappend(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,


amount IN BINARY_INTEGER,
buffer IN VARCHAR2 CHARACTER SET lob_loc%CHARSET);

Example
SQL> declare
2 l_clob clob := '12345';
3 begin
4 dbms_lob.writeappend( l_clob, 5, 'ABCDEFGHIJK' );
5 dbms_output.put_line( l_clob );
6 end;
7 I
12345ABCDE

PLISQL procedure successfully completed.

947
Appendix B

DBMS_SQL
The DBMS_SQL package allows the developer to execute DML and DDL SQL dynamically. This might
not sound like that much of a deal, but consider writing a search procedure which selects values based
on the users inputs. Using DBMS_SQL you can, at run-time, b.uild the WHERE clause and execute the
query. You can write a generic routine that prints the result to any query. That would be impossible
using straight PLISQL. SQL defined in a PLISQL routine is parsed and verified at compile time. SQL
executed with DBMS_SQL is not parsed until run-time.

Procedures Functions
BIND_ARRAY () EXECUTE ( ) - returns NUMBER ( 3 8 )

BIND_VARIABLE () EXECUTE_AND_FETCH ( ) - returns NUMBER ( 3 8)

CLOSE_ CURSOR () FETCH_ROWS ( ) - returns NUMBER ( 3 8)

COLUMN_VALUE () IS_OPEN () -returns BOOLEAN

COLUMN_VALUE_CHAR() LAST_ERROR_POSITION () -returns NUMBER ( 3 8)

COLUMN_VALUE_LONG() LAST_ROW_COUNT ( ) - returns NUMBER ( 3 8)

COLUMN_VALUE_RAW() LAST_ROW_ID ( ) - returns ROWID

COLUMN_VALUE_ROWID() LAST_SQL_FUNCTION_CODE() -returnsNUMBER(38)

COLUMN_VALUE_ROWID() OPEN_ CURSOR () -returns NUMBER ( 3 8)

DEFINE_ARRAY ()

DEFINE_ COLUMN ()

DEFINE_COLUMN_CHAR()

DEFINE_COLUMN_LONG()

DEFINE_COLUMN_RAW()

DEFINE_COLUMN_ROWID()

DESCRIBE_COLUMNS()

DESCRIBE_COLUMNS2()

PARSE ()

VARIABLE_VALUE ()

VARIABLE_VALUE_CHAR()

VARIABLE_VALUE_RAW()

VARIABLE_VALUE_ROWID()

948
Supplied Packages

Before Oracle8~ DBMS_SQL was the only way to perform dynamic SQL. With the introduction of the
EXECUTE IMMEDIATE PLISQL command, issuing some dynamic SQL became much easier. But
DBMS_SQL is still required when you do not know the number of items in the select list, their types or
the number of bind variables. You need to programmatically inspect and react to the query being
executed. DBMS_SQL gives you the API to do just that. Any valid SQL can be executed using
DBMS_SQL.

The flow is as follows:

1. Open a cursor. Every DBMS_SQL statement executed must first be associated with a
DBMS_SQL cursor.

2. Parse the statement. This is the point in which Oracle verifies that the statement about to be
executed is valid SQL.

3. If the statement requires values to be supplied via bind variables, then bind those values.

4. If it is not a query, execute the statement.

5. If the statement returns a value then associate those values with local variables.

or

4. If the statement was a query, specify the variables in your procedure that will accept the select
list values.

5. Execute the query.

6. Fetch the row.

7. Read the resulting values into local storage.

Finish with

8. Close the cursor in either case.

DBMS_SQL allows for both single value and array binding, as well as single row and array fetching.
Array processing is important because it allows you to process multiple rows/values at a time, making
just a single network round trip to the server, so saving time and network bandwidth. Let's look at a
few examples.

The PRINT_TABLE () procedure is an excellent example of using DBMS_SQL. This procedure will print
the results of any SQL statement that is valid for the user executing it. It runs with AUTHID
CURRENT_USER, which means that the SQL is parsed as executing the procedure and not the procedure
owner himself.

949
Appendix B

SQL> create or replace


2 procedure print_table( p_query in varchar2 l
3 AUTHID CURRENT_USER is
4 l_theCursor integer default dbms_sql.open_cursor;
5 l_columnValue varchar2 {4000);
6 !_status integer;
7 l_descTbl dbms_sql.desc_tab;
8 l_colCnt number;
9 begin
10 dbms_sql.parse( l_theCursor, p_query, dbms_sql . native );
11 dbms_sql.describe_colwnns
12 { l_theCursor, l_colCnt, l_descTbl );
13
14 fori in 1 .. l_colCnt loop
15 dbms_sql.define_column
16 {l_theCursor, i, l_columnValue, 4000);
17 end loop;
18
19 !_status:= dbms_sql.execute(l_theCursor);
20
21 while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
22 fori in 1 .. l_colCnt loop
23 dbms_sql.column_value
24 ( l_theCursor, i, l_columnValue );
25 dbms_output.put_line
26 ( rpad( l_descTbl(i) .col_name, 30 )
21 II ·: · II
28 substr( l_columnValue, 1, 200) );
29 end loop;
30 dbms_output.put_line( ·-----------------' );
31 end loop;
32
33 end print_table;
34 I

Procedure created.

And executing the procedure yields the following result:

SQL> exec print_table( •select *from emp where empno like' '778%' • • );
EMPNO 7782
ENAME CLARK
JOB MANAGER
MGR 7839
HIREDATE 09-JUN-81
SAL 2450
COMM
DEPTNO 10

EMPNO 7788
ENAME SCOTT
JOB ANALYS~T~--------------------------------------~

950
Supplied Packages

MGR 7566
HIREDATE 19-APR-87
SAL 3000
COMM
DEPTNO 20

PL/SQL procedure successfully completed.

The PRINT_TABLE () procedure, at run-time, dynamically executed a query, determined the columns
selected, and printed the results. Don't worry too much about the implementation yet, just realize that
using this package you can run any query or perform any valid SQL not known until run-time.

OPEN_CURSOR()
The OPEN_CURSOR () function returns a DBMS_SQL cursor. This cursor, or handle, is the reference
to the SQL being executed. It will be passed into every other procedure and function in the
DBMS_SQL API.

Usage
function open_cursor return integer;

PARSE()
The PARSE ( ) procedure is called to verify that the SQL about to be executed is valid. Since SQL
executed by DBMS_SQL is not validated when the procedure is compiled (it can't because the SQL is
usually not known at that time), the PARSE () procedure checks the syntax of the SQL. If the SQL is
invalid, an exception is raised.

Usage
procedure parse(c in integer,
statement in varchar2,
language_flag in integer);

procedure parse(c in integer,


statement in varchar2s,
lb in integer,
ub in integer,
lfflg in boolean,
language_flag in integer);

There are two versions of parse. One that takes in a VARCHAR2 and on that takes in
DBMS_SQL.VARCHAR2s. The VARCHAR2s is defined as:

type varchar2s is table of varchar2(256) index by binary_integer;

951
Appendix 8

If your statement is larger than 32K you need to break it up into 256 character pieces and populate a
VARCHAR2 s type and use the alternative parse procedure. The LB and UB parameters tell Oracle the
lower and upper bound of the VARCHAR2 S entries. You need not start at index 1 but all the entries must
be contiguous. LFFLG, line feed flag, tells Oracle whether or not to insert a new line at the end of each
entry in the VARCHAR2 S type. LANGUAGE_FLAG is a constant that defines how Oracle should handle
the SQL statement. The values are:

0 DBMS_SQL.V6- Specifies version 6 behavior.


0 DBMS_SQL.V7- Specifies version 7 behavior.
0 DBMS_SQL.NATIVE- Specifies current version behavior.

Example
Create a table FOO using the VARCHAR2 S style of PARSE ( ) .

SQL> declare
2 !_cursor number := dbms_sql.open_cursor;
3 l_stmt dbms_sql.varchar2s;
4 begin
5 l_stmt(3) .- 'junk';
6 l_stmt (4) : = 'create table foo';
7 l_stmt(5) := ' ( n numb';
8 l_stmt ( 6) . - 'er, v varchar2 ( 100) ' ;
9 l_stmt(7) := ') ';
10 l_stmt(8) := 'more junk';
11 dbms_sql.parse( !_cursor,
12 l_stmt,
13 4,
14 7,
15 FALSE,
16 dbms_sql.native );
17 dbms_sql.close_cursor( !_cursor);
18 end;
19 I

PL/SQL procedure successfully completed.

SQL> desc foo


Name Null? Type

N NUMBER
v VARCHAR2 (100)

Notice that the statement is broken up into pieces and stored in the VARCHAR2S type. Lines 7 and 8
break the word NUMBER up and lines 5 and 10 put junk into our variable yet the statement still
processed. That is because we parsed only entries 4 through 7 {lines 13 and 14) and did not insert a line
feed after each entry (line 15). Since the entire statement is not longer than 32K we could have passed it
as a single VARCAHR2, but we chose to use the alternative to demonstrate how it works.

Also notice that we did not execute the statement, we only parsed it. DDL is automatically executed
when the statement is parsed.

952
Supplied Packages

BIND_VARIABLE()
The BIND_VARIABLE ( ) procedure allows the developer to programmatically populate placeholders, or
bind variables, in the statement about to be executed. Bind variables are extremely important for
performance. Bind variables allow you to parse a query once and reuse it, changing just the bind
variable's value.

Usage
procedure bind_variable(c in integer, name in varchar2,
value in number) ;

procedure bind_variable(c in integer, name in varchar2,


value in varchar2 character set any_cs);

procedure bind_variable(c in integer, name in varchar2,


value in varchar2 character set a
out_value_size in integer) ;

procedure bind_variable(c in integer, name in varchar2, value in date);

procedure bind_variable(c in integer, name in varchar2, value in blob);

procedure bind_variable(c in integer, name in varchar2,


value in clob character set any_cs);

procedure bind_variable(c in integer, name in varchar2, value in bfile);

procedure bind_variable(c in integer, name in varchar2,


value in urowid);

procedure bind_variable(c in integer, name in varchar2,


value in time_unconstrained);

procedure bind_variable(c in integer, name in varchar2,


value in timestamp_unconstrained);

procedure bind_variable(c in integer, name in varchar2,


value in TIME_TZ_UNCONSTRAINED);

procedure bind_variable(c in integer, name in varchar2,


value in TIMESTAMP_TZ_UNCONSTRAINED) ;

procedure bind_variable(c in integer, name in varchar2,


value in TIMESTAMP_LTZ_UNCONSTRAINED);

procedure bind_variable(c in integer, name in varchar2,


value in YMINTERVAL_UNCONSTRAINED);

procedure bind_variable(c in integer, name in varchar2,


value in DSINTERVAL_UNCONSTRAINED);

procedure bind_variable_char(c in integer, name in varchar2,

953
Appendix B

value in char character set any_cs);

procedure bind_variable_char(c in integer, name in varchar2,


value in char character set any_cs,
out_value_size in integer);

procedure bind_variable_raw(c in integer, name in varchar2,


value in raw) ;

procedure bind_variable_rowid(c in integer, name in varchar2,


value in rowid);

Notice that the bind variable procedure is heavily overloaded. That is because we need to be able to
bind in any SQL database into our statement. Notice too that the last 4 BIND_VARIABLE () procedures
end with _TYPE. That is because Oracle will autocast RAW and ROWID to VARCHAR2 so we need to
explicitly call a correct procedure so the casting will not occur.

Example

SQL> select * from foo;

no rows selected

SQL> declare
2 l_cursor number := dbms_sql.open_cursor;
3 l_ignore number;
4 begin
5 dbms_sql.parse( l_cursor,
6 'insert into foe values ( :n, :c)',
7 dbms_sql.native );
8 dbms_sql. bind_variable ( l_cursor, ' : N' , 1 ) ;
9 dbms_sq1.bind_variable( l_cursor, ':C', 'Chris' );
10 l_ignore := dbms_sql.execute( l_cursor );
11 dbms_sql.bind_variable( l_cursor, ':N', 2 );
12 dbms_sql.bind_variable( l_cursor, ':C', 'Sean' );
13 l_ignore := dbms_sql.execute( l_cursor );
14 dbms_sql.close_cursor( l_cursor );
15 end;
16 I

PL/SQL procedure successfully completed.

SQL> select * from foe;

NV

1 Chris
2 Sean

954
Supplied Packages

Here we parsed the statement only once, but executed it twice with different values. Parsing a statement
is usually an expensive procedure so we use bind variables to cut down on the number of times we need
to do it. Not only can we benefit from this, but the next user who executes this code can too. The query
is stored in the shared SQL area of the database. When Oracle first attempts to parse this statement, it
looks to see if the statement has already been parsed. If so, then it can use that parsed statement instead
of re-parsing it thus saving processing time.

BIND_ARRAY()
The BIND_ARRAY () procedure allows the developer to bulk bind many values at a time. When
executed the statement will be executed multiple times for each set of bind variables. Again, this
procedure is heavily overloaded to support all SQL types.

Usage
procedure bind_array{c in integer,
name in varchar2,
<VARAIBLE_NAME> in <VARIABLE_TYPE>);

procedure bind_array{c in integer,


name in varchar2,
<VARIABLE_NAME> in <VARIABLE_TYPE>,
indexl in integer,
index2 in integer);

where the VARIABLE_TYPE is of one of the following types defined in the DBMS_SQL spec:

type Number_Table is table of number


index by binary_integer;
type Varchar2_Table is table of varchar2{2000)
index by binary_integer;
type Date_Table is table of date
index by binary_integer;
type Blob_Table is table of Blob
index by binary_integer;
type Clob_Table is table of Clob
index by binary_integer;
type Bfile_Table is table of Bfile
index by binary_integer;
type Urowid_Table is table of urowid
index by binary_integer;
type time_table is table of time_unconstrained
index by binary_integer;
type timestamp_table is table of timestamp_unconstrained
index by binary_integer;
type time_with_time_zone_table is table of time_tz_unconstrained
index by binary_integer;
type timestamp_with_time_zone_table is table of
timestamp_tz_unconstrained index by binary_integer;
type timestamp_with_ltz_table.is table of
timestamp_ltz_unconstrained index by binary_integer;

955
Appendix B

type interval_year_to_month_table is table of


yminterval_unconstrained index by binary_integer;
type interval_day_to_second_table is table of
dsinterval_unconstrained index by binary_integer;

The alternative version of BIND_ARRAY () allows you to define the start and stop indexes of the
appropriate table types. It works the same way as the lower and upper bound parameters in the
PARSE () procedure.

Example
Rewrite the BIND_VARIABLE ( ) example above to use bulk binds.

SQL> declare
2 l_cursor number := dbms_sql.open_cursor;
3 l_ignore number;
4 l_num dbms_sql.number_table;
5 l_var dbms_sql.varchar2_table;
6 begin
7 dbms_sql.parse( l_cursor,
8 'insert into foo values ( :n, :c ) ',
9 dbms_sql.native );
10 l_num(1) := 3;
11 l_num(2) : = 4;
12 l_var(1) := 'Tom';
13 l_var(2) := 'Joel';
14 dbms_sql.bind_array( l_cursor, ':N', l_num );
15 dbms_sql . bind_array ( l_cursor, ' : C' , 1_var ) ;
16 l_ignore := dbms_sql.execute( l_cursor );
17 dbms_sql.close_cursor( l_cursor );
18 end;
19 I

PL/SQL procedure successfully completed.

SQL> select * from foo;

NV

1 Chris
2 Sean
3 Tom
4 Joel

DEFINE_COLUMN()
The DEFINE_COLUMN ( ) procedure allows the developer to define a column being selected from a
query. It is only used for SELECT statements. Columns in the select list are referenced by their position.
This allows us to set up local variables to handle the values from a select statement.

956
Supplied Packages

Usage
procedure define_column(c in integer,
position in integer,
column in <DATATYPE>);

where <DATATYPE> is one of the following:

DATE TIMESTAMP_UNCONSTRAINED

BLOB TIME_TZ_UNCONSTRAINED

CLOB TIMESTAMP_TZ_UNCONSTRAINED

BFILE TIMESTAMP_LTZ_UNCONSTRAINED

UROWID YMINTERVAL_UNCONSTRAINED

TIME_UNCONSTRAINED DSINTERVAL_UNCONSTRAINED

For VARCHAR2, RAW, ROWID, and LONG data types, use the following:

procedure define_column(c in integer, position in integer,


column in varchar2 character set any_cs,
column_size in integer) ;

procedure define_column_char(c in integer, position in integer,


column in char character set any_cs,
column_size in integer);

procedure define_column_raw(c in integer, position in integer,


column in raw,
column_size in integer);

procedure define_column_rowid(c in integer, position in integer,


collirnn in rowid);

procedure define_column_long(c in integer, position in integer);

DEFINE_ARRAY()
The DEFINE_ARRAY () procedure allows the developer to set up bulk fetching of values from a
SELECT statement. It tells Oracle where it will store the values returned from a SELECT statement once
COLUMN_VALUE () is called. This will allow you to fetch·multiple rows with a single call to
FETCH_ROWS ( ) . It saves on network round trips since many rows can be returned from the server with
a single call. It is overloaded to support all base SQL types. The CNT parameter tells Oracle how many
rows to return with a single fetch and the LOWER_BOUND parameter defines the starting index The
values will be saved in the supplied type.

957
Appendix B

Usage
procedure define_array(c in integer,
position in integer,
<VARIABLE_NAME> in <VARIABLE_TYPE>,
cnt in integer,
lower_bound in integer);

where <VARIABLE_TYPE> is written as:

Type <table type> is table of <data type>

Table Type Data Type


NUMBER_ TABLE NUMBER

VARCHAR2_TAble VARCHAR2(2000)

DATE_ TABLE DATE

BLOB_TABLE BLOB

CLOB_TABLE CLOB

BFILE_TABLE BFILE

UROWID_TABLE UROWID

TIME_ TABLE TIME_UNCONSTRAINED


TIMESTAMP_TABLE TIMESTAMP_UNCONSTRAINED
TIME_WITH_TIME_ZONE_TABLE TIME_TZ_UNCONSTRAINED
TIMESTAMP_WITH_TIME_ZONE_TABLE TIMESTAMP_TZ_UNCONSTRAINED

TIMESTAMP_WITH_LTZ_TABLE TIMESTAMP_LTZ_UNCONSTRAINED
INTERVAL_YEAR_TO_MONTH_TABLE YMINTERVAL_UNCONSTRAINED

INTERVAL_DAY_TO_SECOND_TABLE DSINTERVAL_UNCONSTRAINED

EXECUTE()
The function EXECUTE ( ) , as the name suggests, executes the given cursor. It returns the number of
rows affected by either an INSERT, UPDATE, or DELETE. For any other statement, the return value is
undefined and should be ignored.

Usage
function execute(c in integer) return integer;

958
Supplied Packages

EXECUTE_AND_FETCH()
The function EXECUTE_AND_FETCH ( } allows the developer, in one call, to execute a SELECT
statement and fetch the rows. It is the same as calling EXECUTE ( } and then FETCH_ROWS ( } but it
could reduce the number of network round trips. The return value is the actual number of rows fetched.
The EXACT parameter, when set to TRUE, will cause an exception to occur ifthe number of rows
fetched is not 1.

Usage
function execute_and_fetch(c in integer,
exact in boolean default false)
return integer;

FETCH_ROWS()
The FETCH_ROWS ( } function does just that, it fetches rows for a parsed and executed SELECT
statement. It returns the rows into a buffer that can only be accessed by calls to the procedure
COLUMN_VALUE ( } . The function returns the actual number of rows fetched.

Usage
function fetch_rows(c in integer) return integer;

COLUMN_VALUE()
The COLUMN_VALUE (} procedure retrieves the fetched values into the local variables defined in the
DEFINE_COLUMN (} and DEFINE_ARRAY (} procedures. The value references are determined by the
POSITION in the select list of the query previously parsed and executed. An error is raised if the data type
does not match the data type set up in the DEFINE_COLUMN ( } and DEFINE_ARRAY ( } procedures.

Usage
procedure column_value(c in integer,
position in integer,
value out <DATATYPE>);

where <DATA TYPE> data type is one of the following:

NUMBER TIME_UNCONSTRAINED

VARCHAR2 CHARACTER SET ANY_CS TIMESTAMP_UNCONSTRAINED

DATE TIME_TZ_UNCONSTRAINED

BLOB TIMESTAMP_TZ_UNCONSTRAINED

CLOB CHARACTER SET ANY_CS TIMESTAMP_LTZ_UNCONSTRAINED

BFILE YMINTERVAL_UNCONSTRAINED

UROWID DSINTERVAL_UNCONSTRAINED

959
Appendix B

You can also do bulk COLUMN_VALUE () operations.

procedure column_value{c in integer,


position in integer,
<VARIABLE_NAME> in <VARIABLE_TYPE>);

Where the VARIABLE_TYPE can be one of the following types defined in the DBMS_SQL specification.

NUMBER_TABLE TIME_ TABLE

VARCHAR2_TABLE TIMESTAMP_TABLE

DATE_ TABLE TIME_WITH_TIME_ZONE_TABLE

CLOB_TABLE TIMESTAMP_WITH_TIME_ZONE_TABLE

BFILE_TABLE TIMESTAMP_WITH_LTZ_TABLE

BLOB_TABLE INTERVAL_YEAR_TO_MONTH_TABLE

UROWID_TABLE INTERVAL_DAY_TO_SECOND_TABLE

For those types that might be autocast, the following COLUMN_VALUE () procedures have been
provided:

procedure column_value_char{c in integer,


position in integer,
value out char character set any_cs);
procedure column_value_char{c in integer,
position in integer,
value out char character set any_cs,
column_error out number,
actual_length out integer) ;

procedure column_value_raw{c in integer,


position in integer,
value out raw);
procedure column_value_raw{c in integer,
position in integer,
value out raw,
column_error out number,
actual_length out integer);

procedure column_value_rowid{c in integer,


position in integer,
value out rowid) ;
procedure column_value_rowid{c in integer,
position in integer,
value out rowid,
column_error out number,
actual_length out integer);

960
Supplied Packages

procedure column_value_long{c in integer,


position in integer,
length in integer,
offset in integer,
value out varchar2,
value_length out integer);

Example
Here is an example of using array binding and fetching:

SQL> declare
2 l_cursor number := dbms_sql.open_cursor;
3 l_num dbms_sql.number_table;
4 l_var dbms_sql.varchar2_table;
5 l_ignore number;
6 l_cnt number;
7 begin
8 dbms_sql.parse( l_cursor,
9 •select n, v from foo•,
10 dbms_sql.native );
11 dbms_sql.define_array( l_cursor, 1, l_num, 100, 1 );
12 dbms_sql.define_array( l_cursor, 2, l_var, 100, 1 );
13
14 !_ignore:= dbms_sql . execute( l_cursor );
15 loop
16 dbms_output.put_line( 'About to attempt a fetch of 100 rows.• );
17 l_cnt : = dbms_sql.fetch_rows( l_cursor );
18 dbms_output.put_line( 'Fetched • I I l_cnt I I • rows.• );
19
20 exit when l_cnt =
0;
21
22 dbms_sql.column_value( l_cursor, 1, l_num );
23 dbms_sql.column_value( l_cursor, 2, l_var );
24
25 fori in 1 . . l_num.count loop
26 dbms_output.put_line( 'N = ' II l_num(i) II ' V • II l_var{i) );
27 end loop;
28
29 exit when l_cnt < 100;
30
31 end loop;
32 dbms_sql.close_cursor( l_cursor );
33 end;
34 I

About to attempt a fetch of 100 rows.


Fetched 4 rows.
N 1 v Chris
N 2 v Sean
N 3 v Tom
N 4 v Joel

PL/SQL procedure successfully completed.

961
Appendix B

We only made one call to FETCH ( ) , but got back all 4 rows. This will save network round trips when
making calls to remote databases.

VARIABLE_ VALUE()
The procedure VARIABLE_VALUE ( ) allows the developer to retrieve the value or values returned by
the RETURNING clause by passing in the name of the bind variable.

Usage
procedure variable_value(c in integer,
name in varchar2,
value out <DATATYPE>);

where the VALUE parameter can have one of the following types:

NUMBER TIME_UNCONSTRAINED

VARCHAR2 CHARACTER SET ANY_CS TIMESTAMP_UNCONSTRAINED


DATE TIME_TZ_UNCONSTRAINED
BLOB TIMESTAMP_TZ_UNCONSTRAINED

CLOB CHARACTER SET ANY_CS TIMESTAMP_LTZ_UNCONSTRAINED

BFILE YMINTERVAL_UNCONSTRAINED
UROWID DSINTERVAL_UNCONSTRAINED

Or you can bulk retrieve the values using the following:

procedure variable_value(c in integer,


name in varchar2,
value in <DATATYPE>);

where VALUE can be one of the following DBMS_SQL defined types:

NUMBER_ TABLE TIME_ TABLE

VARCHAR2_TABLE TIMESTAMP_TABLE

DATE_ TABLE TIME_WITH_TIME_ZONE_TABLE

CLOB_TABLE TIMESTAMP_WITH_TIME_ZONE_TABLE

BFILE_TABLE TIMESTAMP_WITH_LTZ_TABLE

BLOB_TABLE INTERVAL_YEAR_TO_MONTH_TABLE

UROWID_TABLE INTERVAL_DAY_TO_SECOND_TABLE

962
Supplied Packages

If you are retrieving a VARCHAR2, RAW, or ROWID type, use the following:

procedure variable_value_char(c in integer,


name in varchar2,
value out char character set any_cs);

procedure variable_value_raw(c in integer,


name in varchar2,
value out raw) ;

procedure variable_value_rowid(c in integer,


name in varchar2,
value out rowid) ;

Example
SQL> create sequence my_seq;

Sequence created.

SQL> declare
2 l_cursor number := dbms_sql.open_cursor;
3 l_n number;
4 l_ignore number;
5 l_cnt number;
6 begin
7 dbms_sql.parse( l_cursor,
8 'insert into foo values ( my_seq.nextval, ''MARK'' ) ' II
9 • returning n into : n • ,
10 dbms_sql.native );
11
12 dbms_sql.bind_variable( l_cursor, ':N', l_n );
13
14 l_ignore := dbms_sql.execute( l_cursor );
15
16 dbms_sql.variable_value( l_cursor, ':N', l_n );
17
18 dbms_output.put_line( 'Inserted the value •• II Ln II
19 •• for the column N' );
20
21 dbms_sql.close_cursor( l_cursor );
22 end;

Inserted the value "1" for the column N

PL/SQL procedure successfully completed.

SQL> select * from foo;

NV

1 MARK

963
Appendix B

1 Chris
2 Sean
3 Tom
4 Joel

IS_OPEN()
The IS_OPEN () function is used to test whether or not a DBMS_SQL cursor was previously opened. It
returns TRUE if the cursor is open, FALSE otherwise. It is useful to use in the exception handler to
determine if you should close the cursor or not.

Usage
function is_open(c in integer) return boolean;

Example
begin
l_cursor .- dbms_sql.ope~cursor;

exception
when others then
if dbms_sql.is_open( l_cursor ) then
dbms_sql.close_cursor( l_cursor );
end if;
raise;
end;

DESCRIBE_COLUMNS()/ DESCRIBE_COLUMNS2()
The DESCRIBE_COLUMNS ( ) procedure allows the developer to determine information about the select
list of the query that was just parsed. It returns via OUT parameters, the number of columns, COL_CNT,
and a table of records containing information for each column of the query, DESC_T. The DESC_T type
is of DBMS_SQL. DESC_TAB, which is defined as:

type desc_tab is table of desc_rec index by binary_integer;

and the record is defined as:

type desc_rec is record


col_ type binary_integer := 0,
col_max_len binary_integer := 0,
col_name varchar2(32) := ''
col_name_len binary_integer := 0,
col_schema_name varchar2(32) := ''
col_schema_name_len binary_integer := 0,
col_precision binary_integer := 0,
col_scale binary_integer := 0,
col_charsetid binary_integer := 0,
col_charsetform binary_integer .- 0,
col_null_ok boolean .- TRUE) ;

964
Supplied Packages

Element Description
COL_TYPE The data type of the column.

COL_MAX_LEN The maximum length of the column.

COL_NAME The name of the column.

COL_NAME_LEN The length of the column's name.

COL_SCHEMA_NAME The schema owner of the column if the column is a user-defined


object type.
COL_SCHEMA_NAME_LEN The length of the COL_SCHEMA_NAME value.

COL_PERCISION The column's precision if the return type of the column is a


number.

COL_SCALE The column's scale of the return type of the column is a number.

COL_CHARSETID The character set of the column value.

COL_CHARSERFORM The character set form of the column.

COL_NULL_OK A Boolean value indication if NULLs are allow as a value of the


column.

The DESCRIBE_COLUMNS2 () procedure is identical to DESCRIBE_COLUMNS () with one exception. It


returns a DBMS_SQL. DESC_TAB2. That is a table of records of DESC_REC2. The structure of the
records differs slightly from its counterpart. The COL_NAME attribute is defined as a
VARCHAR2 ( 3 2 7 67), instead of a VARCHAR2 ( 3 2). That gives you the ability to select a non-aliased
expression that is longer than 32 characters.

Both DESCRIBE_COLUMNS ()and DESCRIBE_COLUMNS2 ()can describe the following query:

select to_char( sysdate )


from dual

whereas only DESCRIBE_COLUMNS2 ( ) can describe the query:

select to_char( sysdate, 'DD-MON-YYYY' ) II


to_char( sysdate, 'HH24:MI:SS' )
from dual

CLOSE_CURSOR()
Usage
procedure describe_columns(c in integer,
col_cnt out integer,
desc_t out desc_tab);

965
Appendix B

procedure describe_columns2(c in integer,


col_cnt out integer,
desc_t out desc_tab2);

Example

SQL> declare
2 l_cursor number := dbms_sql.open_cursor;
3 l_ignore number;
4 l_desc dbms_sql.desc_tab2;
5 l_cnt number;
6 begin
7 dbms_sql.parse( l_cursor,
8 •select to_char( sysdate, • 'DD-MON-YYYY' • II · II
9 •to_char( sysdate, • 'HH24:MI:SS' • • II
10 'from dual',
11 dbms_sql.native );
12
13 dbms_sql.describe_columns2( !_cursor, l_cnt, l_desc );
14
15 fori in 1 .. l_cnt loop
16 dbms_output.put_line( 'Column • I I i II ' is •• I I 1_desc(i) .col_name I I
) ;
17 end loop;
18
19 dbms_sql.close_cursor( !_cursor);
20 end;
21 I

Column 1 is "TO_CHAR(SYSDATE, 'DD-MON-YYYY') I ITO_CHAR(SYSDATE, ' HH24:MI : SS')"

PL/SQL procedure successfully completed.

Using DESCRIBE_COLUMNS () in this script would produce the following error message:

declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: dbms_sql.describe_columns overflow,
col_name_len=61. Use describe_columns2
ORA-06512: at "SYS.DBMS_SYS_SQL", line 1522
ORA-06512: at "SYS.DBMS_SQL', line 614
ORA-06512: at line 13

LAST_ERROR_POSITION()
The LAST_ERROR_POSITION () function will return the index into the statement where an error
occurred after having parsed the statement. This is useful for giving feedback to the caller as to why his
or her SQL statement failed the parse.

966
Supplied Packages

Usage
function 1ast_error_position return integer;

LAST_ROW_COUNT()
The LAST_ROW_COUNT ( ) function returns the total number of rows returned for a given statement.

Usage
function 1ast_row_count return integer;

LAST_ROW_ID()
The LAST_ROW_ID ( ) function returns the ROWID of the last row that was processed.

Usage
function 1ast_row_id return rowid;

LAST_SQL_FUNCTION_CODE()
LAST_SQL_FUNCTION_CODE() returns the function code of the last OCI function that called it. The
codes map as follows:

Function Function Function

Qj Qj Qj
'C 'C 'C
0 0 0
u u u
1 OCIINITIALIZE () 33 OCITRANSSTART () 65 OCIDEFINEBYPOS()

2 OCIHANDLEALLOC() 34 OCITRANSDETACH{) 66 OCIBINDBYPOS ()

3 OCIHANDLEFREE ( ) 35 OCITRANS 67 OCIBINDBYNAME ()


COMMIT ()
4 OCIDESCRIPTOR 36 68 OCILOBASSIGN ()
ALLOC ()
5 OCIDESCRIPTOR 37 OCIERRORGET ( ) 69 OCILOBISEQUAL ()
FREE()
6 OCIENVINIT ( ) 38 OCILOBFILEOPEN() 70 OCILOBLOCATORIS
!NIT()
7 OCISERVERATTACH() 39 OCILOBFILECLOSE 71 OCILOBENABLE
() BUFFERING ( )

8 OCISERVERDETACH() 40 72 OCILOBCHARSETID()
9 41 73 OCILOBCHARSET
FORM()
Table continued on following page

967
Appendix B

Function Function Function

~ ~ ~
"CS "CS "CS
Q Q Q
u u u
10 OCISESSIONBEGIN() 42 OCILOBCOPY () 74 OCILOBFILESET
NAME()

11 OCISESSIONEND () 43 OCILOBAPPEND () 75 OCILOBFILEGET


NAME()

12 OCIPASSWORD 44 OCILOBERASE () 76 OCILOGON ()


CHANGE()

13 OCISTMTPREPARE() 45 OCILOBGET 77 OCILOGOFF ()


LENGTH ()

14 46 OCILOBTRIM () 78 OCILOBDISABLE
BUFFERING ( )

15 47 OCILOBREAD () 79 OCILOBFLUSH
BUFFER()

16 48 OCILOBWRITE () 80 OCILOBLOAD
FROMFILE ()

17 OCIBINDDYNAMIC() 49 81 OCILOBOPEN ()

18 OCIBINDOBJECT () 50 OCIBREAK () 82 OCILOBCLOSE ()

19 51 OCISERVER 83 OCILOBISOPEN ()
VERSION()

20 OCIBINDARRAYOF 52 84 OCILOBFILEIS
STRUCT() OPEN()

21 OCISTMTEXECUTE () 53 85 OCILOBFILE
EXISTS ()

22 54 OCIATTRGET () 86 OCILOBFILE
CLOSEALL ()

23 55 OCIATTRSET () 87 OCILOBCREATE
TEMPORARY ( )

24 56 OCIPARAMSET () 88 OCILOBFREE
TEMPORARY ( )

25 OCIDEFINEOBJECT() 57 OCIPARAMGET () 89 OCILOBIS


TEMPORARY ( )

26 OCIDEFINE 58 OCISTMTGET 90 OCIAQENQ ()


DYNAMIC() PIECE
INFO()

27 OCIDEFINEARRAY 59 OCILDATOSVC 91 OCIAQDEQ ()


OFSTRUCT() CTX()

968
Supplied Packages

Function Function Function

-=0 -=0
~ ~

u u
28 OCISTMTFETCH () 60 92 OCIRESET ()
29 OCISTMTGET 61 OCISTMTSET 93 OCISVCCTXTOLDA()
BINDINFO () PIEC
INFO()
30 62 OCITRANSFORGET 94 OCILOBLOCATOR
() ASSIGN()
31 63 OCITRANS 95
PREPARE ()
32 OCIDESCRIBEANY () 64 OCITRANS 96 OCIAQLISTEN()
ROLLBACK ()

Usage
function 1ast_sq1_function_code return integer;

969
Data Dictionary

The Data Dictionary is a collection of tables and views where Oracle stores all the information about
the instance. The Oracle process maintains these tables and views in the SYS schema and users are
granted read-only privilege on them. just about all user access to the data dictionary is through user-
accessible views, since the underlying base tables are very cryptic and complex. Each view is prefixed
with either DBA, indicating that all objects will be shown regardless of execution privileges, ALL,
indicating that all objects that you have privilege on will be shown, or USER, indicating that all objects
owned by the user will be shown.

The following table lists each of the dictionary views that we'lllook at. You need to understand that
there are hundreds of data dictionary views in the Oracle database, and these are simply some of the
more commonly used. For information about other views not covered here, refer to the Oracle 9i
Database Reference documentation.

Topic Data Dictionary Views


Dictionary meta DICTIONARY,DICT_COLUMNS,DBA_OBJECTS
data
Tables DBA_TABLES,DBA_TAB_COLUMNS,DBA_TAB_PRIVS,DBA_COL_PRIVS,
DBA_TAB_COMMENTS,DBA_COL_COMMENTS,DBA_CONSTRAINTS,
DBA_CONS_COLUMNS,DBA_EXTERNAL_TABLES,
DBA_EXTERNAL_LOCATIONS,DBA_OBJECT_TABLES,
DBA_COLL_TYPES

Jobs DBA_JOBS

Objects DBA_TYPES,DBA_TYPE_ATTRIBUTES,DBA_TYPE_METHODS,
DBA_METHOD_PARAMS,DBA_METHOD_RESULTS

Large Objects DBA_LOBS

Views DBA_VIEWS,DBA_UPDATEABLE_COLUMNS
Table continued on following page
Appendix C

Topic Data Dictionary Views


Triggers DBA_TRIGGERS,DBA_TRIGGER_COLS

PL!SQL DBA_SOURCE,DBA_PROCEDURES,ALL_ARGUMENTS,
DBA_DEPENDENCIES,DBA_ERRORS

Indexes DBA_INDEXES,DBA_IND_COLUMNS

Security /Privileges DBA_ROLES,DBA_ROLE_PRIVS,DBA_SYS_PRIVS

Miscellaneous DBA_DIRECTORIES,DBA_USERS,GLOBAL_NAME

Short Names CAT,CLU,COLS,IND,OBJ,DICT,SEQ,SYN,TABS

DICTIONARY
This view has a complete listing of all the views in the Data Dictionary along with a brief description.

Column Definitions and Usage


0 TABLE_NAME [VARCHAR2 ( 3 0)] -Name of the object
0 COMMENTS [VARCHAR2 ( 4 0 0 0) ] -Text comment on the object

You can use this view to get a count of classes of dictionary views like DBA_, USER_, ALL_, and the
performance views.

SQL> column prefix format a6

SQL> select substr( table_name, 1,


2 case
3 when instr(table_name, '$') <> 0
4 then length( substr( table_name, 1, instr( table_name, '$' )
)
5 when substr( table_name,1,3) in ('DBA', 'ALL'
6 then 3
7 else
8 4
9 end prefix,
10 count(*)
11 from dictionary
12 where table_name like 'DBA%'
13 or table_name like 'USER%'
14 or table_name like 'ALL%'
15 or instr( table_name, '$' <> 0
16 group by substr( table_name, 1'
17 case
18 when instr( table_name, '$' J <> 0
19 then length( substr( table_name, 1, instr( table_name, '$' )
) )
20 when substr( table_name,l,3) in ('DBA', 'ALL'

972
Data Dictionary

21 then 3
22 else
23 4
24 end )
25 I

PREFIX COUNT(*)

ALL 172
DBA 244
GV$ 226
SM$ 1
USER 190
V$ 230
X$ 5

7 rows selected.

Or you can use it to get the description of any view in the dictionary.

set echo off


set verify off
set linesize 72
set pagesize 9999
set feedback off

Prompt Dictionary View Name &1

column table_name format a30


column co.m ments format a200

select *
from dictionary
where table_name upper('&1')
I

Save this to a file called dl is t. sql. You execute it using the following:

SQL> @dlist dba_objects


Dictionary View Name dba_objects

TABLE...NAME

COMMENTS

DBA_OBJECTS
All objects in the database

973
Appendix C

DICT_COLUMNS
Use this view to get a description of the columns in any dictionary table.

Column Definitions and Usage


Same as DICTIONARY with the addition of:

0 COLUMN_NAME [VARCHAR2 ( 3 0) ] -Name of the column

This is a handy script to get a quick listing of the columns in any dictionary view and a brief description.
Save the following into a file named de list. sql:

set echo off


set verify off
set linesize 132
set pagesize 9999
set feedback off

Prompt Dictionary View Name &1

column columns format a30


column comments format alOO

select dc.column_name,
dc.comments
from dba_tab_columns tc,
dict_columns de
where tc.table_name = dc.table_name
and tc.column_name = dc.column_name
and dc.table_name = upper('&l'l
order by column_id
I

and execute it like this:

SQL> @dclist dba_users


Dictionary View Name dba_users

COLUMN_NAME COMMENTS

USERNAME Name of the user


USER_ID ID number of the user
PASSWORD Encrypted password
ACCOUNT_STATUS
LOCK_DATE
EXPIRY_DATE
DEFAULT_TABLESPACE Default tablespace for data
TEMPORARY_TABLESPACE Default tablespace for temporary tables
CREATED user creation date
PROFILE User resource profile name
INITIAL_RSRC_CONSUMER_GROUP User ' s initial consumer group
EXTERNAL_NAME User external name

974
Data Dictionary

DBA_OBJECTS
This view contains a listing of all the objects in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Username of the owner of the object
0 OBJECT_NAME [VARCHAR2 ( 12 8) ] -Name of the object
0 SUBOBJECT_NAME [VARCHAR2 ( 3 0) ] -Name of the sub-object (for example, partition}
0 OBJECT_ID [NUMBER] -Object number of the object
0 DATA_OBJECT_ID [NUMBER] - Object number of the segment which contains the object
0 OBJECT_TYPE [VARCHAR2 ( 18) ] -Type of the object
0 CREATED [DATE] -Timestamp for the creation of the object
0 LAST_DDL_TIME [DATE] -Timestamp for the last DDL change (including GRANT and
REVOKE) to the object

0 TIMESTAMP [VARCHAR2 ( 19) ] -Timestamp for the specification of the object


0 STATUS [VARCHAR2 ( 7) ] -Status of the object
0 TEMPORARY [VARCHAR2 ( 1) ] - Can the current session only see data that it places in this
object itself?
0 GENERATED [VARCHAR2 ( 1) ] -Was the name of this object system generated?
0 SECONDARY [VARCHAR2 ( 1) ] -Is this a secondary object created for domain indexes?

You can use it to get a quick account of the objects in your database. This query lists every object type
and the number of objects of that type for the entire database.

SQL> select object_type, count(*)


2 from dba_objects
3 group by object_type
4 I

OBJECT_TYPE COUNT(*)
------------------ ----------
CLUSTER 10
CONSUMER GROUP 4
CONTEXT 2
DIMENSION 5
DIRECTORY 4
FUNCTION 60
INDEX 850
INDEX PARTITION 101
INDEXTYPE 6
JAVA CLASS 11835
JAVA DATA 290
JAVA RESOURCE 190

975
Appendix C

LIBRARY 66
LOB 66
MATERIALIZED VIEW 3
OPERATOR 22
PACKAGE 444
PACKAGE BODY 403
PROCEDURE 51
QUEUE 38
RESOURCE PLAN 3
SEQUENCE 104
SYNONYM 13515
TABLE 720
TABLE PARTITION 43
TRIGGER 25
TYPE 427
TYPE BODY 46
VIEW 2038

Or you can join it to another dictionary view and create a listing for an individual schema. Save the
following script in a file called dbls. sql.

set echo off


set verify off
set pagesize 9999

column object_name format a30


column tablespace_name format a30
column object_type format a12
column status format al

break on object_type skip 1

select object_type, object_name,


decode( status, 'INVALID', '* ' ' ' ) status,
decode( object_type,
'TABLE', (select tablespace_name
from dba_tables
where table_name = object_name
and owner= upper('&l')),
'TABLE PARTITION', (select tablespace_name
from dba_tab_partitions
where partition_name = subobject_name
and owner= upper('&l')),
'INDEX', (select tablespace_name
from dba_indexes
where index_name = object_name
and owner= upper('&l')),
'INDEX PARTITION', (select tablespace_name
from dba_ind_partitions
where partition_name = subobject_name
and owner= upper('&l')),
'LOB', (select tablespace name

976
Data Dictionary

from dba_segments
where segment~arne ~ object_name
and owner= upper('&l')),
null ) tablespace_name
from dba_objects a
where owner= upper('&l')
order by object_type, object_name
I
column status format alO

And run it supplying the schema you would like the listing for. For example:

SQL> @dbls scott

OBJECT_TYPE OBJECT_NAME S TABLESPACE~AME

FUNCTION ITE
MY_UPPER
NO_RETURN_TYPE *

INDEX PK_DEPT SYSTEM


PK_EMP SYSTEM
SYS_C002499 SYSTEM
SYS_C002528 SYSTEM

PACKAGE EMPLOYEE_PKG
VARIABLES

PACKAGE BODY EMPLOYEE_PKG *


VARIABLES

PROCEDURE EMP_LOOKUP
PRINT_TABLE

SEQUENCE MY_SEQ

TABLE ADDRESS_TABLE
BONUS SYSTEM
DEPT SYSTEM
EMP SYSTEM
SALGRADE SYSTEM

TYPE CONSULTANT
EMPLOYEE
SALES_REP
SHAPE
SUB_TYPE *
SUPER._TYPE

TYPE BODY CONSULTANT


EMPLOYEE
SALES_REP

977
Appendix C

DBA_TABLES
This view shows all the relational tables in the database.

Column Definitions and Usage


D OWNER [VARCHAR2 ( 3 0) ] - Owner of the table.
0 TABLE_NAME [VARCHAR2 (30)] -Name of the table.
0 TABLESPACE_NAME [VARCHAR2 ( 3 0) ] - Tablespace the table is stored in.
D CLUSTER_NAME [VARCHAR2 ( 3 0) J -If the table is in a cluster, the cluster's name.
0 IOT_NAME [VARCHAR2 ( 3 0) ] -If this row in DBA_ TABLES is an index-organized table
(lOT), IOT_OVERFLOW or IOT_MAPPING, this column is the name of the base lOT.
D PCT_FREE [NUMBER] -Percentage of the block that is available for updates only. Oracle
will stop inserting rows into the block once the block reaches this percentage of free space
in the block.
D PCT_USED [NUMBER] -Once PCT_FREE is reached, records will not be inserted into a block
until the block falls below the PCT_USED percentage.
D INI_TRANS [NUMBER] -The initial number of transaction entries in a block set aside by
Oracle in order to allow multiple transactions to simultaneously change rows within the same
block for this table.
D MAX_ TRANS [NUMBER] -The maximum number of transactions that can simultaneously
change rows within the same block for this table.
D INITIAL_EXTENT [NUMBER] -The number of bytes of the first extent created for this
table.
D NEXT_EXTENT [NUMBER] -The number of bytes of the next extent to be allocated for this table.
D MIN_EXTENTS [NUMBER] -The initial number of extents that are allocated for this table at
creation time.
D MAX_EXTENTS [NUMBER] -The maximum number of extents that may be allocated for this
table.
D PCT_INCREASE [NUMBER] -For each extent that is allocated for a table after the initial
extent, the size of the next extent to be allocated grows by this percentage.
D FREELISTS [NUMBER] -The number of freelists for this table. Freelists track a list of data
blocks that have room for new inserts into the table.
D FREELIST_GROUPS [NUMBER] -This is number of groups of freelists for the table. This is
used with Oracle's Real Application Clusters.
D LOGGING [VARCHAR2 ( 3) J -Specifies whether creation of this table, direct path load, and
direct path inserts against this table are logged in the redo log (LOGGING vs. NOLOGGING).
D BACKED_UP [VARCHAR2 ( 1) ] -Whether this table has been backed up or not since the
LAST_CHANGED column.

978
Data Dictionary

0 NUM_ROWS [NUMBER] -The number of rows.

0 BLOCKS [NUMBER] -The number of blocks used.

0 EMPTY_BLOCKS [NUMBER] -The number of empty blocks.

0 AVG_SPACE [NUMBER] -This attribute is the average amount offree space per data block.

0 CHAIN_CNT [NUMBER] -The number of rows in the table that have been chained or
migrated.
0 AVG_ROW_LEN [NUMBER] -This is the average amount of space consumed by an individual
row.
0 AVG_SPACE_FREELIST_BLOCKS [NUMBER] -The average amount offree space in blocks
per freelist.
0 NUM_FREELIST_BLOCKS [NUMBER] -The number of blocks on a freelist.

0 DEGREE [VARCHAR2 ( 10) ] -The number of threads used by the database to scan this table,
per instance.
0 INSTANCES [VARCHAR2 ( 10) ] -The number of instances that the table can be scanned in.

0 CACHE [VARCHAR2 ( 5) ] -This attribute tells Oracle whether to try to keep this table's
blocks in the buffer cache or not. (CACHE vs. NOCACHE).
0 TABLE_LOCK [VARCHAR2 ( 8) ] -Whether table locking is enabled or disabled.

0 SAMPLE_SIZE [NUMBER] -When this table is analyzed, Oracle can estimate statistics based
on a percentage of the table instead of computing statistics based on the entire table. This
saves time and processing, but is only as accurate as the amount of space used to estimate the
statistics. SAMPLE_SIZE tells you what size was used to estimate the statistics.
0 LAST_ANALYZED [DATE] -Identifies the date for the last time this table was analyzed.

0 PARTITIONED [VARCHAR2 ( 3) ] -Indicates whether this is a partitioned table or not


(YES/NO).
0 IOT_TYPE [VARCHAR2 ( 12) ] -If this is an index-organized table (IOT), this will be either
IOT, IOT_OVERFLOW or IOT_MAPPING. NULL if it is not an IOT.

0 TEMPORARY [VARCHAR2 ( 1) ] -Indicates whether this is a temporary table or not (YIN).


0 SECONDARY [VARCHAR2 ( 1) ] -Whether the table was created by the Oracle 9i Data
Cartridge.
0 NESTED [VARCHAR2 (3)] -Indicates whether this is a nested table or not (YES/NO).

0 BUFFER_POOL [VARCHAR2 ( 7) ] -The default buffer pool for this table.

0 ROW_MOVEMENT [VARCHAR2 ( 8) ] -Whether partitioned row movement is enabled for this


table or not.
0 GLOBAL_STATS [VARCHAR2 ( 3) ] -Indicates whether statistics were gathered on an entire
partitioned table, or on partitions or sub partitions only.
0 USER_STATS [VARCHAR2 ( 3) ] -Indicates whether the statistics for the table were specified
instead of computed. Users can "create" statistics using the DBMS_STATS supplied package. If
a user does this, this column will be YES. NO if not.

979
Appendix C

0 DURATION [VARCHAR2 ( 15) ] -For temporary tables, this indicates the type of table
(SYS$SESSION/SYS$TRANSACTION).

0 SKIP_CORRUPT [VARCHAR2 ( 8) ] -Blocks of the database may be marked corrupt. Using


the supplied package DBMS_REPAIR, you can tell Oracle to skip these blocks during table
scans. This column will indicate whether the table will skip corrupt blocks or not.
0 MONITORING [VARCHAR2 ( 3) ] -Whether MONITORING is enabled for this table or not.

0 CLUSTER_ OWNER [VARCHAR2 ( 3 0) ] -For clustered tables, the schema that owns the cluster
that this table belongs to.
0 DEPENDENCIES [VARCHAR2 ( 8) ].

This query results in a list of those tables belonging to the username passed into the script, along with
various properties of these tables. The tables are ordered by table name, and grouped by their
tablespace. The script below is named tableinfo. sql.

set verify off


set linesize 76
set pagesize 9999

break on tablespace_name skip 1


column tablespace_name format al5
column table_name format a30
column table_properties format a30 word_wrapped

select tablespace_name, table_name,


decode( partitioned, 'YES', 'Partitioned',
decode( logging, 'NOLOGGING', 'Non-logging table ' ) ) I I
decode( temporary, 'Y', 'Temporary(' I I
decode( duration, 'SYS$SESSION', 'Session-based',
'Transaction-based' ) II
')It
" l II
decode( iot_type, null, '', 'Index-organized' ) II
decode( nested, 'YES', 'Nested ', '' )
table_properties
from dba_tables
where owner upper( '&1'
order by 1, 2
I

In the following example, the HR schema from the Oracle 9 i Sample Schemas is used:

SQL> @tableinfo.sql HR

TABLESPACE_NAME TABLE_NAME TABLE_PROPERTIES


--------------- ------------------------- -----------------------------EXAMPLE
AUDIT_TBL
CUSTOMER_TAB
DEPARTMENTS
EMPLOYEES

980
Data Dictionary

JOBS
JOB_HISTORY
LOCATIONS
REGIONS
SALES_PEOPLE
COUNTRIES Index-organized
LOCATIONS_INC Index-organized
LOCATIONS_IOT Index-organized
LOCATIONS_IOT_C Index-organized
SESSION_TAB Temporary (Session-based)
TRANSACTION_TAB Temporary (Transaction-based)

DBA_TAB_COLUMNS
DBA_TAB_COLUMNS contains information about all the columns of tables, views, and clusters.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -Owner of the table this column belongs to.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] -Name of the table this column belongs to.
0 COLUMN_NAME [VARCHAR2 ( 3 0) ] -Name of the column.
0 DATA_TYPE [VARCHAR2 ( 106)] -Data type for the column.
0 DATA_TYPE_MOD [VARCHAR2 ( 3) ] -Data type modifier for the column.
0 DATA_TYPE_OWNER [VARCHAR2 ( 3 0) ] - Owner of the data type for the column.
0 DATA_LENGTH [NUMBER] -Length specified for this column's data type.
0 DATA_PRECISION [NUMBER] -Precision specified for this column's data type (NUMBERs and
FLOATs).
0 DATA_SCALE [NUMBER] -The scale of the column's data type. This indicates the digits to the
right of the decimal place in a NUMBER.
0 NULLABLE [VARCHAR2 ( 1) ] -Indicates whether this column can contain NULL values or
not.
0 COLUMN_ID [NUMBER] -Each column gets a sequence number when it is created.
0 DEFAULT_LENGTH [NUMBER] -Length of the default value of the column.
0 DATA_DEFAULT [LONG] -The default value assigned to the column in a new record if no
value is given.
0 NUM_DISTINCT [NUMBER] -The number of distinct values for this column. This data is kept
for backward compatibility, and can now be found in the TAB_COL_STATISTICS view.
0 LOW_VALUE [RAW ( 3 2) ] -The lowest value for this column. This data is kept for backward
compatibility. This data can now be found in the TAB_COL_STATISTICS view.
0 HIGH_VALUE [RAW ( 3 2) ] -The highest value for this column. This data is kept for backward
compatibility. This data can now be found in the TAB_COL_STATISTICS view.

981
Appendix C

0 DENSITY [NUMBER] -The density of the column. This data is kept for backward
compatibility. This data can now be found in the TAB_COL_STATISTICS view.
0 NUM_NULLS [NUMBER]- The number of NULL values for this column.
0 NUM_BUCKETS [NUMBER]- The number of buckets for this column's histogram (if one exists).
0 LAST_ANALYZED [DATE]- Identifies the date for the last time this column was analyzed.
0 SAMPLE_SIZE [NUMBER]- When this column is analyzed, Oracle can estimate statistics
based on a percentage of the table instead of computing statistics based on the entire table.
This saves time and processing, but is only as accurate as the amount of space used to estimate
the statistics. SAMPLE_SIZE tells you what size was used to estimate the statistics.
0 CHARACTER_SET_NAME [VARCHAR2 { 44) ] -The name of the character set for this column
(CHAR_CS/NCHAR_CS).

0 CHAR_COL_DECL_LENGTH [NUMBER].

0 GLOBAL_STATS [VARCHAR2 { 3) ] -Indicates whether column statistics were gathered on an


entire partitioned table, or on partitions or sub partitions only.
0 USER_STATS [VARCHAR2 { 3) ] - Indicates whether the statistics for the column were
specified instead of computed. Users can "create" statistics using the DBMS_STATS supplied
package. If a user does this, this column will be YES - NO if not.
0 AVG_COL_LEN [NUMBER] -Average length of the column in bytes.
0 CHAR_LENGTH [NUMBER] -The length of the column in characters (only for CHAR, NCHAR,
VARCHAR2, NVARCHAR2).

0 CHAR_USED [VARCHAR2 ( 1) ] - Indicates whether the column's length was specified in bytes
or characters.
0 V8 O_FMT_IMAGE [VARCHAR2 ( 3) ] .

0 DATA_UPGRADED [VARCHAR2 {3)].

In the following script, we write a query that emulates the SQJ.*Plus DESCRIBE command.

set verify off


set linesize 72
set pagesize 9999
set feedback off

Prompt Datatypes for Table &1

column data_type format a20


column col~name heading "Column Name"
column data_type heading "Datal Type"
column data_length heading 'Datal Length'
column nullable heading 'Nullable'

select column_name,
data_ type,
substr(

982
Data Dictionary

decode( data_type, 'NUMBER',


decode( data_precision, NULL, NULL,
'('I ldata_precisionl I',' I ldata_scalel I')' ),
data_lengthl ,
1,11) data_length,
decode( nullable, 'Y', 'null', 'not null' ) nullable
from all_tab_columns
where owner = USER
and table_name = upper('&1 ' )
order by column_id
I

In the example below, we use the desc. sql script on the DEPARTMENTS table:

SQL> @desc.sql DEPARTMENTS


Datatypes for Table DEPARTMENTS

Data Data
Column Name Type Length Null able

DEPARTMENT_ID NUMBER (4, 0) not null


DEPARTMENT_NAME VARCHAR2 30 not null
MANAGER_ID NUMBER (6, 0) null
LOCATION_ID NUMBER (4, 0) null

DBA_TAB_PRIVS
DBA_TAB_PRIVS displays all the privileges that have been granted on objects in the database.

Column Definitions and Usage


0 GRANTEE [VARCHAR2 ( 3 0) ] -The user that the privilege was granted to.
0 OWNER [VARCHAR2 ( 3 0) ] -The user that owns the object for which the privilege was
granted.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] -The table the privilege was granted upon.
0 GRANTOR [VARCHAR2 ( 3 0) ] -The user that granted the privilege to the grantee.
0 PRIVILEGE [VARCHAR2 ( 4 0) ] - The privilege that was granted.
0 GRANTABLE [VARCHAR2 ( 3) ] -Whether the GRANTOR can grant this privilege to other users
or not (YES/NO).

0 HIERARCHY [VARCHAR2 ( 3) ] .

The following query is used to select all those object privileges for a particular user. The filename for
this query is tabpri vs. sql.

983
Appendix C

set verify off


set linesize 78
set pagesize 9999
set feedback off

Prompt &1. 's Object Privileges

column tab format a24 heading "Schema.Object•


column privilege format a24 heading "Privilege•
column grantor format a20 heading "Granted By"
column grantable format a6 heading "Admin?"

select owner I I '.' II table_name tab,


privilege,
grantor,
grantable
from dba_tab_privs
where grantee= upper( '&1'
order by owner, table_name, privilege
I

In the following example, we connect to the database as a user account with SELECT privileges on the
DBA_TAB_PRIVS view, and run the tabprivs . sql script on the PM schema:

SQL> Qtabprivs . sql PM


PM's Object Privileges

Schema.Object Privilege Granted By Admin?

OE.CUSTOMERS SELECT OE NO
OE.INVENTORIES SELECT OE NO
OE.ORDERS SELECT OE NO
OE. ORDER_ITEMS SELECT OE NO
OE.PRODUCT_DESCRIPTIONS SELECT OE NO
OE.PRODUCT_INFORMATION REFERENCES OE NO
OE.PRODUCT_INFORMATION SELECT OE NO
OE.WAREHOUSES SELECT OE NO
SYS . DBMS_STATS EXECUTE SYS NO

DBA- COL_PRIVS
This view is used to display all privileges granted on particular columns in the database.

Column Definitions and Usage


0 GRANTEE [VARCHAR2 ( 3 0) ] -The user who granted the privilege.
0 OWNER [VARCHAR2 ( 3 0) ] -The user that owns the object for which the privilege was
granted.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] - The table that contains the column the privilege was
granted upon.

984
Data Dictionary

0 COLUMN_NAME [VARCHAR2 ( 3 0) J -The column the privilege was granted upon.


0 GRANTOR [VARCHAR2 ( 3 0) J -The user that the privilege was granted to.
0 PRIVILEGE [VARCHAR2 ( 40)) -The privilege that was granted.
0 GRANTABLE [VARCHAR2 ( 3) J -Whether the GRANTOR can grant this privilege to other users
or not (YES/NO).

In the following code sample, connect to the database as the Oracle 9i Sample Schema HR, and run the
following grants:

SQL> grant references ( employee_id ),


2 update( first_name,last_name,job_id,manager_id,department_id
3 on hr.employees to scott;

SQL> grant references ( department_id ),


2 update( department~ame, location_id
3 on hr.departments to scott;

SQL> grant references ( job_id ),


2 update( job_title l
3 on hr.jobs to scott;

SQL> grant references ( location_id ),


2 update( city, state_province
3 on hr.locations to scott;

Once the SCOTT user has a number of column privileges on HR's tables, use the colpri vs. sql script
to view the column privileges (and associated information) granted:

SQL> connect sdillon/sdillon


Connected.
SQL> @colprivs scott
Column Privileges For scott

Table Column Privilege Granted By Admin?

HR. DEPARTMENTS DEPARTMENT_ID REFERENCES


-------------- NO
---------------- HR
DEPARTMENT_NAME UPDATE HR NO
LOCATION_ID UPDATE HR NO

HR.EMPLOYEES EMPLOYEE_ID REFERENCES HR NO


FIRST_NAME UPDATE HR NO
LAST_NAME UPDATE HR NO
JOB_ID UPDATE HR NO
DEPARTMENT_ID UPDATE HR NO
MANAGE~ID UPDATE HR NO

HR.JOBS JOB_ID REFERENCES HR NO


JOB_TITLE UPDATE HR NO

HR.LOCATIONS LOCATION_ID REFERENCES HR NO


CITY UPDATE HR NO
STATE PROVINCE UPDATE HR NO

985
Appendix C

DBA_TAB_COMMENTS/ DBA_COL_COMMENTS
Comments created on tables and views are displayed in these views.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ) -The owner of the object.
0 TABLE_NAME [VARCHAR2 ( 3 0) J -The object name the comment is for.
0 COMMENTS [VARCHAR2 ( 4 0 0 0) ) - Comment text for the object.
0 TABLE_TYPE [VARCHAR2 ( 11) ) -The type of object the comment is for
(DBA_TAB_COMMENTS).

0 COLUMN_NAME [VARCHAR2 ( 3 0) J -The column of the object that the comment is for
(DBA_COL_COMMENTS).

Copy the following script into a file named comments. sq1:

set linesize 10078


set verify off

variable tname varchar2(200)


begin
:tname := upper('&l');
end;
I

column comments format a7S heading •comments• word_wrapped

prompt Table comments for table &1

select comments
from dba_tab_comments
where table_name = :tname
I

column column_name format a20 heading "Column Name" word_wrapped


column comments format aSS heading "Comments" word_wrapped

prompt
prompt Column comments for table &l

select column_name, comments


from dba_col_comrnents
where table_name = : tname
order by column_pame
I

Comments are created for many of the tables and columns created during the installation of the Oracle
9i Sample Schemas. Using the comments. sql script, the table and column comments can be queried
from the data dictionary:

986
Data Dictionary

SQL> connect hr/hr


Connected.
SQL> @comments EMPLOYEES

PL/SQL procedure successfully completed .

Table comments for table EMPLOYEES

Comments

employees table. Contains 107 rows. References with departments,


jobs, job_history tables. Contains a self reference.

Column comments for table EMPLOYEES

Column Name Comments

COMMISSION_PCT Commission percentage of the employee; Only employees


in sales department eligible for commission percentage

DEPARTMENT_ID Department id where employee works; foreign key to


department_id column of the departments table

EMAIL Email id of the employee


EMPLOYEE_ID Primary key of employees table.
FIRST_NAME First name of the employee. A not null column.
HIRE_DATE Date when the employee started on this job. A not null
column.

JOB_ID CUrrent job of the employee; foreign key to job_id


column of the jobs table. A not null column.

LAST....NAME Last name of the employee. A not null column.


MANAGER_ID Manager id of the employee; has same domain as
manager_id in departments table. Foreign key to employee_id
column of employees table. (useful for reflexive joins and
CONNECT BY query)

PHONE_NUMBER Phone number of the employee; includes country code and


area code

SALARY Monthly salary of the employee. Must be greater


than zero (enforced by constraint emp_salary~in)

11 rows selected.

987
Appendix C

DBA_CONSTRAINTS
DBA_CONSTRAINTS shows information about constraints defined on tables in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -The owner of the constraint.

D CONSTRAINT_NAME [VARCHAR2 ( 3 0) ] -The name of the constraint.

D CONSTRAINT_TYPE [VARCHAR2 ( 1) ] -A single character indicating the type of the


constraint.
D P - Primary Key
D R- Foreign Key
D U- Unique
D c- Check
D v- Check (on a view)
D 0 -Read only (on a view)
D TABLE_NAME [VARCHAR2 ( 3 0) ] -The table or view the constraint is defined upon.

D SEARCH_CONDITION [LONG] -Text for a check condition.

D R_OWNER [VARCHAR2 ( 3 0) ] -For foreign keys, this is the table owner the foreign key refers to.

D R_CONSTRAINT_NAME [VARCHAR2 ( 3 0) J -For foreign keys, this is the primary key


constraint name the foreign key refers to.
0 DELETE_RULE [VARCHAR2 ( 9) ] -For foreign keys, this is either CASCADE or NO ACTION.

D STATUS [VARCHAR2 ( 8) ] -Whether the constraint is enforced or not (ENABLED/


DISABLED).

D DEFERRABLE [VARCHAR2 ( 14) J -Whether the constraint can be deferred or not


(DEFERRABLE/NOT DEFERRABLE).

D DEFERRED [VARCHAR2 ( 9 ) J - Whether the constraint is deferred or not.

D VALIDATED [VARCHAR2 ( 13) J -If all the rows in the table/view adhere to the constraint or
not (VALIDATED/NOT VALIDATED).
0 GENERATED [VARCHAR2 ( 14) J -Indicates whether the constraint name is system-generated
or user-specified.
D BAD [VARCHAR2 ( 3 ) ] - If you use the TO_DATE function with a two-digit year date format,
this column will be YES. Otherwise, it will be NO. Constraints are said to be BAD if two-digit
years are ambiguous.
D RELY [VARCHAR2 ( 4)] -Indicates whether a constraint is enabled and enforced or not.

D LAST_CHANGE [DATE] -The last time the constraint was enabled or disabled.

0 INDEX_OWNER [VARCHAR2 ( 3 0) ] -The user that owns the index.

988
Data Dictionary

0 INDEX_NAME [VARCHAR2 ( 3 0) ] -The name of the index.


0 INVALID [VARCHAR2 ( 7) ] .

0 VIEW_RELATED [VARCHAR2 ( 14) ].

See DBA_CONS_COLUMNS for usage information.

DBA_CONS_COLUMNS
DBA_CONS_ COLUMNS shows detailed information about the columns that are a part of constraints
defined on tables in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -The owner of the constraint the column is a part of.
0 CONSTRAINT_NAME [VARCHAR2 ( 3 0) ] -The name of the constraint the column is a part of.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] -The name of the table the constraint is defined upon.
0 COLUMN_NAME [VARCHAR2 ( 3 0) ] - The name of the column.
0 POSITION [NUMBER] -The position of the column relative to other columns that are a part
of this constraint.

Pass a table name as the first argument to the following script to query constraint information from the
data dictionary. This script only queries the first sixteen columns of any given constraint, so if there is a
constraint with more columns than this then another query would be necessary:

set verify off


set linesize 78
set pagesize 9999
set feedback off

Prompt Column Constraints for Table &1

column constraint_name heading "Name• format a20


column constraint_type heading "Type" format alS
column columns format a25 word_wrapped
column invalid format al heading 'V"
column deferred format al heading "D"
column status format al heading "S'

select substr(c . constraint_name,l,30) constraint_name,


decode(c.constraint_type,
'P', 'Primary Key',
'R', 'Foreign Key',
'U', 'Unique Key',
'C' , 'Check' ,
'V', 'Check (on view)',
'0', 'Read only (view)',
'Unknown') constraint_type,

989
Appendix C

max(decode{ co.position, 1,
substr(co.column_name,1,30), NULL )) II
max{decode( co.position, 2, ' 'II
substr(co.column_name,1,30), NULL )) II
max(decode( co.position, 3' ' 'II
substr(co.col~ame,1,30), NULL )) II
max(decode( co.position, 4, ' 'II
substr(co.column_name,1,30), NULL ) ) II
max(decode( co.position, 5, 'II
substr(co.column_name,l,30), NULL )) II
' 'II
max(decode( co.position, 6,
substr(co.column_name,1,30), NULL )) II
max(decode( co.position, 7' . 'II
substr(co.column_name,1,30), NULL ) ) II
' 'II
max(decode( co.position, 8,
substr(co.column_name,1,30), NULL )) II
' 'II
max(decode( co.position, 9,

.
substr(co.column_name,1,30), NULL )) II
max(decode( co.position, 10, ' 'II
substr(co.col~ame,1,30), NULL )) II
max(decode( co.position, 11, '. 'II
substr(co.co1umn_name,1,30), NULL)) I I
max(decode( co.position, 12, ', 'I I
substr(co.co1umn_name,1,30), NULL)) I I
max(decode( co.position, 13, ', 'I I
substr(co.column_name,1,30l, NULL ll I I
max(decode( co.position, 14, ', 'I I
substr(co.col~ame,1,30), NULL)) II
max(decode( co.position, 15, ', 'I I
substr (co. co1umn_name, l, 30) , NULL ) J II
max(decode( co.position, 16, ', 'I I
substr(co.co1umn_name,l,30), NULL)) columns,
decode( invalid, 'YES', '*', ' ' ) invalid,
decode( deferred, 'YES', ' *', ' ' ) deferred,
decode( status, 'INVALID', '*', •' ) status
from dba_constraints c, dba_cons_columns co
where c . owner = USER
and c.table_name = upper('&l')
and co.table_name = c.table_name
and co.owner = c.owner
and c.constraint_name = co.constraint_name
group by substr(c.constraint_name,l,30), c.constraint_type,
c.invalid, c.deferred, c.status
order by c.constraint_type
I

prompt
prompt 'V' - * indicates constraint is INVALID
prompt 'D' - * indicates constraint is DEFERRED
prompt 'S' -
* indicates constraint is DISABLED

990
Data Dictionary

At the bottom of the query, a legend is included to help the person performing the query to understand
the output. The three final columns are abbreviated to a single character for each column, and an
asterisk is output only in the case where the constraint is invalid, deferred, or disabled. Running the
script on the HR schema's EMPLOYEES table produces the following results:

SQL> @cons EMPLOYEES


Column Constraints for Table EMPLOYEES

Name Type COLUMNS V DS

EMP_EMAIL_NN Check
EMP_HIRE_DATE~ Check
EMP_JOB_NN Check
EMP_LAST_NAME_NN Check
EMP_SALARY_MIN Check
EMP_EMP_ID_PK Primary Key EMPLOYEE_ID
EMP_DEPT_FK Foreign Key DEPARTMENT_ID
EMP_JOB_FK Foreign Key JOB_ID
EMP_MANAGER_FK Foreign Key MANAGER_ID
EMP_EMAIL_UK Unique Key EMAIL

'V' - * indicates constraint is INVALID


'D' - * indicates constraint is DEFERRED
'S' - * indicates constraint is DISABLED

DBA_EXTERNAL_TABLES
This view provides information about the external tables created in the database.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0) ] - The owner of the external table.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] -The name of the external table.

0 TYPE_ OWNER [CHAR ( 3 ) ] - The owner of the type of access driver used for the external
table.
0 TYPE_NAME [VARCHAR2 ( 3 0) ] -The type of access driver used for the external table.

0 DEFAULT_DIRECTORY_OWNER [CHAR ( 3) ] -The owner of the directory object where the


external table exists.
0 DEFAULT_DIRECTORY_NAME [VARCHAR2 ( 3 0) ] -The name of the directory object where
the external table exists.
0 REJECT_LIMIT [VARCHAR2 ( 4 0) ] -The number of conversion errors Oracle will allow
before a query against this external table fails.
0 ACCESS_ TYPE [VARCHAR2 ( 7) ] -The type of access parameters for the external table.

0 ACCESS_PARAMETERS [VARCHAR2 ( 4 0 0 0) ] -The values of the access parameters for the


external table.

See DBA_EXTERNAL_LOCATIONS for usage information.

991
Appendix C

DBA_EXTERNAL_LOCATIONS
This view provides information about the location of data for external tables in the database.

Column Definitions and Usage


D OWNER [VARCHAR2 ( 3 0) ] -The owner of the external table.

D TABLE_NAME [VARCHAR2 ( 3 0) ] -The name of the external table.

D LOCATION [VARCHAR2 ( 4 0 0 0) J -The name of the file that makes up the external table's
data.
D DIRECTORY_OWNER [VARCHAR2 ( 3) J -The type of access driver used for the external table.

D DIRECTORY_NAME [VARCHAR2 ( 3 0) J -The name of the directory object where the external
table exists.

Copy the following script to a file named ext tabs. sql:

set verify off


set linesize 81
set pagesize 9999
set feedback off

Prompt External Table

column table_name format a22 heading "ExternaliTable Name• wordlwrapped


column src format a54 heading •source File'
column parms format a54 heading "Access Parameters•

select t . table_name, d . directory_path I I !.location src


from dba_external_tables t, dba~external_locations 1, dba_directories d
where t.default_directory_name = d . directory_name
and t.owner = l.owner
and t.table_name l.table_name
I

select table_name, access_parameters parms


from dba_external_tables
order by table_name
I

This script will first select the table name and the location of the source data for the external table. The
next query in this script will query all the access parameters from the data dictionary view
DBA_EXTERNAL_TABLES. The SH (shipping) schema, for example, has an external table named:

SQL> @exttabs
External Table

External
Table Name

992
Data Dictionary

SALES_TRANSACTIONS_EXT C:\Oracle\ora90\demo\schema\sales_history\sh_sales.dat

External
Table Name Access Parameters

SALES_TRANSACTIONS_EXT RECORDS DELIMITED BY NEWLINE CHARACTERSET US7ASCII


BADFILE log_file_dir: 'sh_sales_ext.bad'
LOGFILE log_file_dir: 'sh_sales_ext.log'
FIELDS TERMINATED BY 'I' LDRTRIM

DBA_OBJECT_TABLES
DBA_OBJECT_TABLES contains information about all the object tables created in the database.

Column Definitions and Usage


This is the DBA_TABLES view with three additional columns as follows:

0 OBJECT_ID_TYPE [VARCHAR2 ( 16) J -This indicates whether the object ID this table is
based on is user-defined or system-generated.
0 TABLE_TYPE_OWNER [VARCHAR2 ( 3 0) ] -If this table is a typed table, this is the owner of
the type.
0 TABLE_TYPE [VARCHAR2 ( 3 0) J -If this table is a typed table, this is the name of the type.

To see the object tables owned by the current user, copy the following script to a file named
obj tabs. sql. This is a query on the DBA_OBJECT_TABLES view that selects the tablespace name,
table name, and some of the type information that was used in creating the table itself.

set verify off


set linesize 82
set pagesize 9999
set feedback off

Prompt Object Tables

column tablespace_name format a16 heading "Tablespace Name•


column table_name format a25 heading "Table Name•
column type_name format a30 heading "Type Name•

select tablespace_name, table_name,


table_type_owner I I ' ' I I table_type type_name
from dba_object_tables
where owner = USER
order by tablespace_name, table_name
I

993
Appendix C

Using the PM schema, run the obj tab. sql script to produce the following results:

SQL> @objtab
Object Tables

Tablespace Name Table Name Type Name

EXAMPLE TEXTDOCS~STEDTAB PM.TEXTDOC_TYP

DBA_COLL_TYPES
DBA_COLL_TYPES displays information about all the collection types in the database.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 l ] - Owner of the table containing the nested table.
0 TABLE_NAME [VARCHAR2 ( 3 0) ] -Name of the nested table.
0 TABLE_TYPE_OWNER [VARCHAR2 ( 3 0) ] -Owner of the type used to create the nested table.
0 TABLE_TYPE_NAME [VARCHAR2 ( 3 0) ] -Name of the type used to create the nested table.
0 PARENT_TABLE_NAME [VARCHAR2 ( 3 0) ] -Name of the table this nested table is a part of.
0 PARENT_TABLE_COLUMN [VARCHAR2 (4000)] -Name of the column in the parent table
this nested table makes up.
0 STORAGE_SPEC [VARCHAR2 ( 3 0) ] -The storage for the nested table can be user defined or
left as the default. This column indicates which type of storage is used.
0 RETURN_TYPE [VARCHAR2 ( 2 0) ] - Return type of the column.

In order to find out all those collections that a user owns, use the following script (named
coll types. sql):

prompt
prompt Collections

column type_name format a35 heading •collection Name•


column coll_type format aS heading "Type"
column element_type format a35 heading "Element Type"

select type_name,
decode(coll_type, 'TABLE', 'Table', 'Varray') coll_type,
decode(elemLtype_owner,null, '',
elemLtype_ownerl I'.') I I elemLtype_name element_type
from dba_coll_types
order by 1, 2
I

994
Data Dictionary

The OE user receives the following data when executing this script:

SQL> connect oe/oe


Connected
SQL> @colltypes

Collections

Collection Name Type Element Type

INVENTORY_LIST_TYP Table OE.INVENTORY_TYP


ORDER_ITEMLLIST_TYP Table OE.ORDER_ITEMLTYP
ORDER_LIST_TYP Table OE. ORDER_TYP
PHONE_LIST_TYP Varray VARCHAR2
PRODUCT_REF_LIST_TYP Table NUMBER
SUBCATEGORY_REF_LIST_TYP Table OE.CATEGORY_TYP

6 rows selected.

DBA_JOBS
This view contains all the information about scheduled jobs in the database.

Column Definitions and Usage


0 JOB [NUMBER] -Identifier of job.
0 LOG_USER [VARCHAR2 ( 3 0) ] -USER who was logged in when the job was submitted.
0 PRIV_USER [VARCHAR2 ( 3 0) ] -USER whose default privileges apply to this job.
0 SCHEMA_USER [VARCHAR2 ( 3 0) ) -Default schema used to parse the jobs.
0 LAST_DATE [DATE] -Date that this job last successfully executed.
0 LAST_SEC [VARCHAR2 ( 8) ] -Same as LAST_DATE. This is when the last successful
execution started.
0 THIS_DATE [DATE] -Date that this job started executing (usually NULL if not executing).
0 THIS_SEC [VARCHAR2 ( 8) ] -Same as THIS_DATE. This is when the last successful
execution started.
0 NEXT_DATE [DATE] -Date that this job will next be executed.
0 NEXT_SEC [VARCHAR2 ( 8) ] -Same as NEXT_DATE. The job becomes due for execution at
this time.
0 TOTAL_TIME [NUMBER] -Total wallclock time spent by the system on this job, in seconds.
0 BROKEN [VARCHAR2 ( 1) ] -If Y, no attempt is being made to run this job. See
DBMS_JOBQ.BROKEN(JOB).

995
Appendix C

D INTERVAL [VARCHAR2 ( 2 0 0) l -A date function, evaluated at the start of execution,


becomes next NEXT_DATE.
D FAILURES [NUMBER] -How many times has this job started and failed since its last success?

D WHAT [VARCHAR2 (4000)]- Body of the anonymous PLISQL block that this job executes.

D NLS_ENV [VARCHAR2 ( 400 0) ] -Alter session parameters describing the NLS environment
of the job.
D MI SC_ENV [RAW ( 3 2) ] - A versioned raw maintained by the kernel, for other session
parameters.
D INSTANCE [NUMBER] -Instance number restricted to run the job.

SQL> column priv_user format al5


SQL> column scherna_user format al5

SQL> select priv_user,


2 schema_user,
3 this_date,
4 next_date,
5 decode( failures, null, 0, failures ) failures
6 from dba_jobs
7 I

PRIV_USER SCHEMA_USER THIS_DATE NEXT_DATE FAILURES

SCO'M' SCO'M' 13-MAR-02 0

DBA_TYPES
This view contains information about all the object types in the database.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 ) ] - Owner of the type

0 TYPE_NAME [VARCHAR2 ( 3 0) ] -Name of the type

0 TYPE_OID [RAW(l6)] -Object identifier (OlD) of the type

0 TYPECODE [VARCHAR2 ( 3 0) ] - Typecode of the type

0 ATTRIBUTES [NUMBER] -Number of attributes in the type

0 METHODS [NUMBER] -Number of methods in the type

0 PREDEFINED [VARCHAR2 (3)] -Is the type a predefined type? (YES/NO)

0 INCOMPLETE [VARCHAR2 ( 3)] -Is the type an incomplete type? (YES/NO)

D FINAL [VARCHAR2 ( 3) ] -Is the type a final type? (YES/NO)

996
Data Dictionary

0 INSTANTIABLE [VARCHAR2 (3)] -Is the type an instantiable type?

0 SUPER TYPE_ OWNER [VARCHAR2 ( 3 0) ] -Owner of the supertype (NULL if type is not a
supertype)
0 SUPERTYPE_NAME [VARCHAR2 ( 3 0) ] -Name of the supertype (NULL if type is not a
supertype)
0 LOCAL_ATTRIBUTES [NUMBER l - Number of local (not inherited) attributes (if any) in the
subtype
0 LOCAL_METHODS [NUMBER] -Number of local (not inherited) methods (if any) in the
subtype
0 TYPEID [RAW ( 16) ] - Type id value of the type

SQL> column name format a25


SQL> column extends format a29
SQL> column •fl ATTRS" format a?
SQL> column "II METHS" format a?

SQL> select type_name name,


2 decode( supertype_owner, null, null,
3 supertype_owner I I ' ' I I supertype_name ) 'EXTENDS',
4 final,
5 attributes 'II ATTRIBUTES",
6 methods •fl METHODS"
7 from dba_types
8 where owner = upper( 'OE'
9 I

NAME EXTENDS FINAL # ATTRS # METHS


---------------------- ----------------------------- ------- -------
CUST~DRESS_TYP YES 5 0
PHONE_LIST_TYP YES 0 0
WAREHOUSE_TYP YES 3 0
INVENTORY_TYP YES 3 0
INVENTORY_LIST_TYP YES 0 0
PRODUCT_INFORMATION_TYP YES 12 0
ORDER_ITEM_TYP YES 5 0
ORDER_ITEMLLIST_TYP YES 0 0
CUSTOMER_TYP NO 10 0
ORDER_TYP YES 7 0
ORDER_LIST_TYP YES 0 0
CATEGORY_TYP NO 3 1
SUBCATEGORY~F_LIST_TYP YES 0 0
PRODUCT_REF_LIST_TYP YES 0 0
CORPORATE_CUSTOMER_TYP OE. CUSTOMER_TYP YES 11 0
LEAF_CATEGORY_TYP OE.CATEGORY_TYP YES 4 2
COMPOSITE_CATEGORY_TYP OE.CATEGORY_TYP NO 4 2
CATALOG_TYP OE.COMPOSITE_CATEGORY_TYP YES 4 4

997
Appendix C

DBA_TYPE_ATTRS
Use the DBA_TYPE_ATTRS view to get information about the attributes of an object type.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 ) ] - Owner of the type
0 TYPE_NAME [VARCHAR2 ( 3 0) ] - Name of the type
0 ATTR_NAME [VARCHAR2 ( 3 0) ] -Name of the attribute
0 ATTR_TYPE_MOD [VARCHAR2 ( 7) ] -Type modifier of the attribute
0 ATTR_TYPE_OWNER [VARCHAR2 (30)] -Owner of the type of the attribute
0 ATTR_ TYPE_NAME [ VARCHAR2 ( 3 0 ) ] - N arne of the type of the attribute
0 LENGTH [NUMBER] -Length of the CHAR attribute or maximum length of the VARCHAR or
VARCHAR2 attribute
0 PRECISION [NUMBER] -Decimal precision of the NUMBER or DECIMAL attribute, or binary
precision of the FLOAT attribute
0 SCALE [NUMBER] -Scale of the NUMBER or DECIMAL attribute
0 CHARACTER_SET_NAME [VARCHAR2 ( 44) ] -Character set name of the attribute
0 ATTR_NO [NUMBER] - Syntactical order number or position of the attribute as specified in the
type specification or CREATE TYPE statement (not to be used as ID number)
0 INHERITED [VARCHAR2 ( 3) ] -Is the attribute inherited from the supertype ?

SQL> column type format a30

SQL> select attr_name,


2 decode( attr_type_owner, null, null, attr_type_owner II > II
3 attr_type_name I I
4 decode( attr_type_name,
5 'VARCHAR2', '('I llengthl I')',
6 'CHAR', ' (' II length II') ',
7 'NUMBER', ' (' llprecisionll ','II scale! I')',
8 null ) type
9 from dba_type_attrs
10 where owner = 'OE'
11 and type_name = 'COMPOSITE_CATEGORY_TYP'
12 order by attr_no
14 I

ATTR_NAME TYPE

CATEGORY_NAME VARCHAR2 ( 50 )
CATEGORY_DESCRIPTION VARCHAR2(1000)
CATEGORY_ID NUMBER(2, 0)
SUBCATEGORY_REF_LIST OE.SUBCATEGORY_REF_LIST_TYP

998
Data Dictionary

DBA_TYPE_METHODS
This view contains information about the methods in object types.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 ) ] - Owner of the type
0 TYPE_NAME [VARCHAR2 ( 3 0)] -Name of the type
0 METHOD_NAME [VARCHAR2 ( 3 0) ] -Name of the method
0 METHOD_NO [NUMBER] -Method number for distinguishing overloaded method (not to be
used as ID number)
0 METHOD_TYPE [VARCHAR2 ( 6) ] -Type of the method
0 PARAMETERS [NUMBER] -Number of parameters to the method
0 RESULTS [NUMBER] -Number of results returned by the method
0 FINAL [ VARCHAR2 ( 3 ) ] - Is the method final ?
0 INSTANTIABLE [VARCHAR2 ( 3) ] -Is the method instantiable ?
0 OVERRIDING [VARCHAR2 ( 3) J -Is the method overriding a supertype method ?
0 INHERITED [VARCHAR2 ( 3) ] -Is the method inherited from the supertype ?

SQL> clea~ breaks


SQL> break on num skip 1
SQL>
SQL> column method_name format a20
SQL> column param_name format a20
SQL> column num format 999
SQL> column "IN/OUT' format a6
SQL>
SQL> select tm.metho~o num,
2 tm.method_name,
3 tm.method_type,
4 tm.final,
5 tm.instantiable,
6 tm.overriding,
7 tm.inherited,
8 mp.param_name,
9 mp.param_mode 'IN/OUT"
10 from dba_type_methods tm,
11 dba~etho~arams mp
12 where tm.owner = mp.owner
13 and tm. type_name = mp. type_name
14 and tm.method_name = mp.metho~ame
15 and tm.method_no = mp.method_no
16 and tm.owner = 'OE'
17 and tm. type_name • COMPOSITE_CATEGORY_TYP'
18 order by 1, 2. 3

999
Appendix C

19 I

NUM METHOD_NAME METHOD FINAL INS OVE INH PARAM_NAME IN/OUT

1 CATEGORY_DESCRIBE PUBLIC NO NO NO YES SELF IN


2 CATEGORY_DESCRIBE PUBLIC NO YES YES NO SELF IN

DBA_METHOD_PARAMS
The view contains information about the parameters of methods of object types.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Owner of the type
0 TYPE_NAME [VARCHAR2 ( 3 0) ] -Name of the type
0 METHOD_NAME [VARCHAR2 ( 3 0) ] -Name of the method
0 METHOD_NO [NUMBER] -Method number for distinguishing overloaded method (not to be
used as ID number)
0 PARAM_NAME [VARCHAR2 ( 3 0)] -Name of the parameter
0 PARAM_NO [NUMBER] -Parameter number or position
0 PARAM_MODE [VARCHAR2 ( 6) ] -Mode of the parameter
0 PARAM_TYPE_MOD [VARCHAR2 ( 7) ] -Type modifier of the parameter
0 PARAM_TYPE_OWNER [VARCHAR2 (30)] -Owner of the type of the parameter
0 PARAM_TYPE_NAME [VARCHAR2 (30)] -Name of the type of the parameter
0 CHARACTER_SET_NAME [VARCHAR2 ( 44) ] -Character set name of the parameter

See DBA_TYPE_METHODS for usage information.

DBA_METHOD_RESULTS
The DBA_METHOD_RESULTS view contains information about the return type from methods accessible
to the caller.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -Owner of the type
0 TYPE_NAME [VARCHAR2 ( 3 0) ] -Name of the type
0 METHOD_NAME [VARCHAR2 ( 3 0) ] - N arne of the method
0 METHOD_NO [NUMBER] -Method number for distinguishing overloaded method (not to be
used as ID number)

1000
Data Dictionary

0 RESULT_TYPE_MOD [VARCHAR2 ( 7) 1 -Type modifier of the result


0 RESULT_TYPE_OWNER [VARCHAR2 ( 3 0) ] -Owner of the type of the result
0 RESULT_TYPE_NAME [VARCHAR2 ( 3 0) 1 -Name of the type of the result
0 CHARACTER_SET_NAME [VARCHAR2 ( 44) 1 -Character set name of the result

SQL> clear breaks


SQL> break on num skip 1
SQL>
SQL> column method_name format a20
SQL> column param_name format a20
SQL> column result_type_name a25
SQL> column num format 999
SQL>
SQL> select tm.methodLno num,
2 tm.method_name,
3 tm.method_type,
4 tm . final,
5 tm.instantiable,
6 tm . overriding,
7 tm.inherited,
8 mr.result_type_name
9 from dba_type~ethods tm,
10 dba~ethod_results mr

11 where tm.owner = mr.owner


12 and tm. type_name = mr. type_name
13 and tm.method_name =
mr.method_name
14 and tm . method_no = mr.method_no
15 and tm.owner = 'OE'
16 and tm . type_name = 'COMPOSITE_CATEGORY_TYP'
17 order by 1, 2, 3
18 I

NUM METHOD_NAME METHOD FINAL INS OVE !NH RESULT_TYPE_NAME

1 CATEGORY_DESCRIBE PUBLIC NO NO NO YES VARCHAR2


2 CATEGORY_DESCRIBE PUBLIC NO YES YES NO VARCHAR2

DBA_LOBS
This view shows all the large objects, or LOBs, in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) 1 - Owner of the table containing the LOB.
0 TABLE_NAME [VARCHAR2 ( 3 0) 1 -Name of the table containing the LOB.
0 COLUMN_NAME [VARCHAR2 ( 4 0 0 0) 1 - The column of the table that is the LOB.

1001
Appendix C

0 SEGMENT_NAME [VARCHAR2 ( 3 0) ] -The segment that is storing the LOB.

0 INDEX_NAME [VARCHAR2 ( 3 0) ] -The index of the LOB.

0 CHUNK [NUMBER] - The size of the LOB chunk.

D PCTVERSION [NUMBER] -The maximum amount of space in a LOB block used for
versioning.
D CACHE [ VARCHAR2 ( 1 0 ) ] - The CACHE setting is how the cluster is cached in the database
buffer cache.
0 LOGGING [VARCHAR2 ( 7) ] -Whether changes to the LOB are logged.

D IN_ROW [VARCHAR2 ( 3) ] -Whether the LOB is eligible for in-line storage with the base row
of the table.

In the following query, we will query DBA_LOBS to find out all the LOBS a particular owner owns, what
tables and columns they are in, and the size of the LOB chunk.

set verify off


set linesize 80

prompt &l. ' s LOBS


&1. 's LOBS

column table_column format a45 heading "Table and Column of LOB"


column lob_name format a25 heading "LOB Name•
column in_row format a6 heading "In?"

select table_name I I ' . ' I I column_name table_column,


segment_name lob_name, in_row
from dba_lobs
where owner= upper( ' &1' )
order by 1, 2
I

If we invoke this query using the OE schema, we get the following results:

SQL> @lobs OE
OE' s LOBS

Table and Column of LOB LOB Name In?

CUSTOMERS."CUST_GEO_LOCATION"."SDO_ELEM_INFO" SYS_LOB0000030851C00022$$ Yes


CUSTOMERS."CUST_GEO_LOCATION"."SDO_ORDINATES" SYS_LOB0000030851C00023$$ Yes
WAREHOUSES."WH_GEO_LOCATION"."SDO_ELEM_INFO' SYS_LOB0000030857C00012$$ Yes
WAREHOUSES . "WH_GEO_LOCATION"."SDO_ORDINATES" SYS_LOB0000030857C00013$$ Yes
WAREHOUSES.SYS~C00003$ SYS_LOB0000030857C00003$$ Yes

1002
Data Dictionary

DBA_VIEWS
DBA_VIEWS contains information about all the views in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -Owner of the view

0 VIEW_NAME [VARCHAR2 ( 3 0) ] -Name of the view

0 TEXT_LENGTH [NUMBER] -Length of the view text

0 TEXT [LONG] - View text

0 TYPE_TEXT_LENGTH [NUMBER] -Length of the type clause of the object view

0 TYPE_TEXT [ VARCHAR2 ( 4 0 0 0 ) ] - Type clause of the object view

0 OID_TEXT_LENGTH [NUMBER] -Length of the WITH OBJECT OID clause of the object view

0 OID_TEXT [VARCHAR2 (4000)] -WITH OBJECT OID clause of the object view

0 VIEW_ TYPE_OWNER [VARCHAR2 ( 3 0) J - Owner of the type of the view if the view is an
object view
0 VIEW_TYPE [VARCHAR2 ( 3 0) ] -Type of the view if the view is an object view

0 SUPERVIEW_NAME [VARCHAR2 ( 3 0) J -Name of the superview, if view is a superview

We can use the following script to generate the CREATE VIEW command used to initially create the
view. (Save it in a file called getaview. sql.}

set heading off


set long 99999999
set feedback off
set linesize 1000
set trimspool on
set verify off
set termout off
set embedded on

column column_name format alOOO


column text format alOOO

spool &2 .. sql


prompt create or replace view &2 (
select decode(column_id,l,' ', •, ') I I column_name column_name
from dba_tab_columns
where table_name = upper('&2')
and owner= upper('&l')
order by column_id
I
prompt ) as
select text

1003
Appendix C

from dba_views
where view_name; upper('&2')
and owner= upper('&l')
I
prompt I
spool off

set termout on
set heading on
set feedback on
set verify on

You can execute it using @getaview <user> <view_name>. It will generate a file named
<view_name>.sql.

DBA_UPDATABLE_COLUMNS
This view lists all columns of a join view and whether or not data can be modified through them.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -Table/View owner

0 TABLE_NAME [VARCHAR2 ( 3 0) ] -Table/View name

0 COLUMN_NAME [VARCHAR2 ( 3 0) ] - Column name

0 UPDATABLE [VARCHAR2 (3)] -Is the column updatable? (YES/NO)

0 INSERTABLE [VARCHAR2 ( 3)] -Is the column insertable? (YES/NO)

0 DELETABLE [VARCHAR2 ( 3) ] -Is the column deletable? (YES/NO)

Use this script to get information about a join view. (Save it in a file called viewrep. sql. ):

set echo off


set verify off
set linesi~e 72
set pagesi~e 9999
set feedback off

column view_name format a30


column column_name format a30
column i format al
column u format al
column d format al

clear breaks
break on view_name

select tableJlame view_name,


colurnn_name,

1004
Data Dictionary

decode( insertable, 'YES', null, '*' ) i,


decode( updatable, 'YES', null, '*' u,
decode( deletable, 'YES', null, ·•· ) d
from dba_updatable_columns
where owner= upper('&l')
and table_name = upper('&2')
I

prompt
prompt
prompt '*' indicated action not permitted.
prompt

You can run it for any <user> <view_name> combination.

SQL> @viewrep hr emp_details_view

VIEW_NAME COLUMN_NAME I U D

EMP_DETAILS_VIEW EMPLOYEE_ID • • •
JOB_ID • • *
MANAGER_ID * * *
* * •
DEPARTMENT_ID
LOCATION_ID . * *
COUNTRY_ID • • *
FIRST_NAME • • •
LAST_NAME * * *
SALARY * * *
COMMISSION_PCT • * •
DEPARTMENT_NAME * * *
JOB_TITLE * * •
CITY * * *
STATE_PROVINCE * * *
COUNTRY_NAME • * •
REGION_NAME • • •

Note that'*' indicates that the action is not permitted.

DBA_TRIGGERS
This view is a listing of all trigger-related information in the database.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] -Owner of the trigger
0 TRIGGER_NAME [VARCHAR2 (30)] -Name of the trigger
0 TRIGGER_TYPE [VARCHAR2 ( 16)] -When the trigger fires. BEFORE/AFTER and
STATEMENT/ROW

1005
Appendix C

0 TRIGGERING_EVENT [VARCHAR2 (227)] -Statement that will fire the trigger. INSERT,
UPDATE and/or DELETE

0 TABLE_OWNER [VARCHAR2 ( 3 0) ] -Owner of the table that this trigger is associated with

0 BASE_OBJECT_TYPE [VARCHAR2 ( 16) ] -Object type (TABLE, VIEW, SCHEMA, or


DATABASE) that the trigger is attached to

0 TABLE_NAME [VARCHAR2 ( 3 0) ] -Name of the table that this trigger is associated with

0 COLUMN_NAME [VARCHAR2 ( 4 0 0 0) ] -The name of the column on which the trigger is defined

0 REFERENCING_NAMES [VARCHAR2 ( 12 8) ] -Names used for referencing to OLD and NEW


values within the trigger
0 WHEN_ CLAUSE [VARCHAR2 ( 4000)] -WHEN clause must evaluate to TRUE in order for
triggering body to execute
0 STATUS [VARCHAR2 ( 8) ] - ENABLED/DISABLED. If DISABLED then trigger will not fire

0 DESCRIPTION [VARCHAR2 ( 400 0) ] -Trigger description, useful for recreating trigger


creation statement
0 ACTION_ TYPE [VARCHAR2 ( 11) ] -Action type of trigger's body (PUSQL or CALL)

0 TRIGGER_BODY [LONG] - Action taken by this trigger when it fires

You can use the following to produce a quick report on the trigger for the HR schema:

SQL> set 1inesize 77


SQL> column triggering_event format a30
SQL> column trigger_name format a20
SQL>
SQL> select trigger_name,
2 triggering_event,
3 trigger_type,
4 status
5 from dba_triggers
6 where owner = 'HR'
7 I

TRIGGER_NAME TRIGGERING_EVENT TRIGGER_TYPE STATUS

SECURE_EMPLOYEES INSERT OR UPDATE OR DELETE BEFORE STATEMENT DISABLED


UPDATE_JOB_HISTORY UPDATE AFTER EACH ROW ENABLED

DBA_TRIGGER_COLS
Describes the use of all columns in triggers.

Column Definitions and Usage


0 TRIGGER_ OWNER [VARCHAR2 ( 3 0) ] - Owner of the trigger

0 TRIGGER_NAME [VARCHAR2 ( 3 0) ] -Name of the trigger

1006
Data Dictionary

0 TABLE_OWNER [VARCHAR2 ( 3 0) ) - Owner of the table


0 TABLE_NAME [VARCHAR2 ( 3 0) J -Name of the table on which the trigger is defined
0 COLUMN_NAME [VARCHAR2 (4000) J -Name of the column or the attribute of the column
used in trigger definition
0 COLUMN_LIST [VARCHAR2 ( 3) ) -Is column specified in UPDATE OF clause?
0 COLUMN_USAGE [VARCHAR2 ( 17) ) -Usage of column within trigger body

Here we show you a list of columns referenced in the trigger UPDATE_JOB_HISTORY in the HR schema.

SQL> clear breaks


SQL> break on table_name
SQL>
SQL> column table_name format a20
SQL> column column_name format a20
SQL>
SQL>
SQL> select table_name,
2 column_name,
3 col~list,
4 col~usage
5 from dba_trigger_cols
6 where trigger_name = 'UPDATE_JOB_HISTORY'
7 and trigger_owner = 'HR'
8 I

TABLE_NAME COLUMN_NAME COL COLUMN_USAGE

EMPLOYEES DEPARTMENT_ID YES OLD IN


EMPLOYEE_ID NO OLD IN
HIRE_DATE NO OLD IN
JOB_ID YES OLD IN

We can see how these columns are referenced, by querying the DBA_TRIGGERS view:

SQL> set long 9999

SQL> select trigger_body


2 from dba_triggers
3 where owner = 'HR'
4 and trigger_name 'UPDATE_JOB_HISTORY'
5 I

TRIGGER_BODY

BEGIN
add_job_history(:old.employee_id, :old.hire_date, sysdate,
:old.job_id, :old.department_id);
END;

1007
Appendix C

DBA_SOURCE
This view contains the actual PLISQL source code for the given object.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Owner of the object
0 NAME [VARCHAR2 ( 3 0) ] -Name of the object
0 TYPE [VARCHAR2 ( 12) ] -Type of the object
0 LINE [NUMBER] -Line number of this line of the source
0 TEXT [ VARCHAR2 ( 4 0 0 0 ) ] - Source text

We can use the following script to retrieve PLISQL from the database:

set feedback off


set heading off
set terrnout off
set linesize 1000
set trimspool on
set verify off

spool &2 .. sql

prompt set define off

select decode( typel I'-' I lto_char(line, 'fm99999'),


'PACKAGE BODY- 1', '/'I lchr(10),
null) II
decode(line,l, 'create or replace', '' ) I I
text text
from dba_source
where name= upper('&&2')
and order= upper( '&&1')
order by type, line;
prompt I

prompt set define on

spool off

set feedback on
set heading on
set terrnout on
set linesize 100

Save this script to a file called get code. sql. To execute the script issue the following. @getcode
<owner> <obj ect_name>. It will produce a file named <obj ect_name>. sql containing the source
code of the object.

1008
Data Dictionary

DBA_PROCEDURES
Use the DBA_PROCEDURES view to determine more information about procedures and functions.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Owner of the object.

0 OBJECT_NAME [VARCHAR2 ( 3 0) ] -Name of the object: top-level


function/procedure/package name
0 PROCEDURE_NAME [VARCHAR2 ( 3 0) ] -Name of the procedure

0 AGGREGATE [VARCHAR2 ( 3) ] -Is it an aggregate function? (YES/NO)

0 PIPELINED [VARCHAR2 ( 3) ] -Is it a pipelined table function? (YES/NO)

0 IMPLTYPEOWNER [VARCHAR2 ( 3 0) ] -Name of the owner of the implementation type (if


any)
0 IMPLTYPENAME [VARCHAR2 ( 3 0) ] -Name of the implementation type (if any)

0 PARALLEL [VARCHAR2 ( 3) ] -Is the procedure parallel enabled? (YES/NO)

0 INTERFACE [VARCHAR2 (3)]

0 DETERMINISTIC [VARCHAR2 ( 3) ] -Is the procedure deterministic? (YES/NO)

0 AUTHID [VARCHAR2 ( 12) ] -The AUTHID of the procedure (INVOKER/DEFINER)

SQL> select procedure~e.


2 aggregate,
3 pipelined,
4 parallel,
5 dete~nistic,
6 authid
7 from dba_procedures
8 where owner = 'HR'
9 I

PROCEDURE_NAME AGG PIP PAR DET AUTHID

ADD_JOB_HISTORY NO NO NO NO DEFINER
SECURE_DML NO NO NO NO DEFINER

ALL_ARGUMENTS
This view contains information about the parameters and return types of procedures and functions.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Username of the owner of the object

0 OBJECT_NAME [VARCHAR2 ( 3 0) ] - Procedure or function name

1009
Appendix C

0 PACKAGE_NAME [VARCHAR2 ( 3 0) ] -Package name


0 OBJECT_ID [NUMBER] -Object number of the object
0 OVERLOAD [ VARCHAR2 ( 4 0 ) ] - Overload unique identifier
0 ARGUMENT_NAME [VARCHAR2 ( 3 0) ] -Argument name
0 POSITION [NUMBER] -Position in argument list, or null for function return value
0 SEQUENCE [NUMBER] -Argument sequence, including all nesting levels
0 DATA_LEVEL [NUMBER] -Nesting depth of argument for composite types
0 DATA_ TYPE [VARCHAR2 ( 3 0) ] -Data type of the argument
0 DEFAULT_VALUE [LONG] -Default value for the argument
0 DEFAULT_LENGTH [NUMBER] -Length of default value for the argument
0 IN_OUT [VARCHAR2 ( 9)] -Argument direction (IN, OUT, or IN/OUT)
0 DATA_LENGTH [NUMBER] -Length of the column in bytes
0 DATA_PRECISION [NUMBER] -Length: decimal digits (NUMBER) or binary digits (FLOAT)
0 DATA_SCALE [NUMBER] -Digits to right of decimal point in a number
0 RADIX [NUMBER] -Argument radix for a number
0 CHARACTER_SET_NAME [VARCHAR2 ( 44) ] -Character set name for the argilment
0 TYPE_ OWNER [VARCHAR2 ( 3 0) ] - Owner name for argument type in case of object types
0 TYPE_NAME [VARCHAR2 ( 3 0) l -Object name for argument type in case of object types
0 TYPE_SUBNAME [VARCHAR2 ( 3 0) ] -Subordinate object name for argument type in case of
object types
0 TYPE_LINK [VARCHAR2 ( 12 8) ] -Database link name for argument type in case of object
types
0 PLS_TYPE [VARCHAR2 ( 3 0) ] - PLISQL type name for numeric arguments
0 CHAR_LENGTH [NUMBER] -Character limit for string data types
0 CHAR_USED [VARCHAR2 ( 1) ] -Is the byte limit (B) or char limit (C) official for this string?

SQL> column object_name format a20


SQL> column data_type format al5
SQL>
SQL> clear breaks
SQL> break on object_name
SQL>
SQL> select object_name,
2 argument_name,
3 data_type
4 from all_arguments
5 where owner = 'HR'
6 order by position

1010
Data Dictionary

7 I

OBJECT_NAME ARGUMENT....NAME DATA,_TYPE

ADD_JOB_HISTORY P_EMP_ID NUMBER


P_START_DATE DATE
P_END_DATE DATE
P_JOB_ID VARCHAR2
P_DEPARTMENT_ID NUMBER

DBA_DEPENDENCIES
The DBA_DEPENDENCIES view contains information about which objects are dependent on which
other objects.

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) ] - Owner of the object
0 NAME [VARCHAR2 ( 3 0) ] -Name of the object
0 TYPE [VARCHAR2 ( 12) ] -Type of the object
0 REFERENCED_OWNER [ VARCHAR2 ( 3 0) l - Owner of referenced object (remote owner if
remote object)
0 REFERENCED_NAME [VARCHAR2 (64)] -Name of referenced object
0 REFERENCED_TYPE [VARCHAR2 ( 12) ] -Type of referenced object
0 REFERENCED_LINK_NAME [VARCHAR2 ( 12 8) ] -Name of DBLINK if this is a remote object
0 DEPENDENCY_TYPE [VARCHAR2 ( 4)] -Defines the dependency type (REF/HARD)

You can determine which objects your schema is dependent on with the following query:

SQL> set linesize 132


SQL> column referenced_object format a35
SQL> clear breaks
SQL> break on name on type
SQL>
SQL> select name,
2 type,
3 referenced_owner I I'.' I I referenced_name referenced_object
4 from dba_dependencies
5 where owner = 'HR'
6 I

NAME TYPE REFERENCED_OBJECT

SECURE_DML PROCEDURE SYS. STANDARD


UPDATE_JOB_HISTORY TRIGGER SYS.STANDARD
SECURE_DML PROCEDURE SYS.DBMS_STANDARD

1011
Appendix C

SYS.SYS_STUB_FOR_PURITY_ANALYSIS
ADD_JOB_HISTORY PROCEDURE SYS.SYS_STUB_FOR_PURITY_ANALYSIS
EMP_DETAILS_VIEW VIEW HR . REGIONS
HR.COUNTRIES
HR.LOCATIONS
HR.DEPARTMENTS
HR.JOBS
EMP_DETAILS_VIEW VIEW HR.EMPLOYEES
SECURE_EMPLOYEES TRIGGER HR.EMPLOYEES
UPDATE_JOB_HISTORY TRIGGER HR . EMPLOYEES
ADD_JOB_HISTORY PROCEDURE HR.JOB_HISTORY
SECURE_EMPLOYEES TRIGGER HR.SECURE_DML
UPDATE_JOB_HISTORY TRIGGER HR.ADD_JOB_HISTORY

Or you can see which objects in the database are dependent on a particular object in your schema.

SQL> select owner I I ' . ' II name name,


2 type,
3 dependency_type
4 from dba_dependencies
5 where referenced_owner = 'HR'
6 and referenced_name = ' EMPLOYEES'
7 I

NAME TYPE DEPE

HR . MY_REPORTS
------------
VIEW HARD
HR.COMPANY_PHONE_BOOK VIEW HARD
HR . EMP_DETAILS_VIEW VIEW HARD
HR.SECURE_EMPLOYEES TRIGGER HARD
HR.UPDATE_JOB_HISTORY TRIGGER HARD

DBA_ERRORS
This is the view that SQL*Plus uses to return the current results from the SHOW ERRORS command on
every object in the database.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 ) ] - Owner of the object

0 NAME [VARCHAR2 (30)] -Name of the object

0 TYPE [VARCHAR2 ( 12) ] -Type

0 SEQUENCE [NUMBER] -Sequence number used for ordering purposes

0 LINE [NUMBER] -Line number at which this error occurs

0 POSITION [NUMBER] -Position in the line at which this error occurs

0 TEXT [VARCHAR2 (4000)] -Text of the error

1012
Data Dictionary

If we compile a procedure and get an error we can query the DBA_ERRORS view to return the error, and
allow other clients to mimic the SQL*Plus functionality.

SQL> connect system/manager


Connected.

SQL> set long 9999

SQL> select line I I '/' I I position "LINE/COL",


2 text error
3 from dba_errors
4 where owner = 'SCOTT'
5 and name =
'FOO'
6 I

LINE/COL ERROR

4/1 PLS-00103: Encountered the symbol "END" when eXPeCting one of the
following:

The symbol";" was substituted for "END" to continue.

DBA_INDEXES

Column Definitions and Usage


0 OWNER [VARCHAR2 ( 3 0) J -The user who created the index
0 INDEX_NAME [VARCHAR2 ( 3 0) ] -The name of the index
0 INDEX_TYPE [VARCHAR2 ( 2 7) ] -The type of index
0 TABLE_OWNER [VARCHAR2 ( 3 0) J - The owner of the table this index is built on
0 TABLE_NAME [VARCHAR2 ( 3 0) J -The name of the table this index is built on
0 TABLE_TYPE [ VARCHAR2 ( 11) ] - The type of the table this index is built on
0 UNIQUENESS [VARCHAR2 ( 9) ] -Whether the index is unique or not
0 COMPRESSION [VARCHAR2 ( 8) J -Whether this index uses compression or not
0 PREFIX_LENGTH [NUMBER] -Number of columns in the prefix of a compressed index
0 TABLESPACE_NAME [VARCHAR2 ( 3 0) ] - Tablespace this index is stored in
0 INI_TRANS [NUMBER] -The number of transaction entries in a block to allow multiple
transactions to simultaneously change rows within the same block for this index
0 MAX_TRANS [NUMBER] -The maximum number of transactions that can simultaneously
change rows within the same block for this index

1013
Appendix C

0 INITIAL_EXTENT [NUMBER] -Number of bytes in the first extent created for this index
0 NEXT_EXTENT [NUMBER] -Number of bytes in the next extent to be allocated for this index
0 MIN_EXTENTS [NUMBER] -The minimum number of extents created for this index
0 MAX_EXTENTS [NUMBER] - The maximum number of extents that can be created for this
index
0 PCT_INCREASE [NUMBER] -The percentage of the extent size that the next extent will grow
by
0 PCT_THRESHOLD [NUMBER] -Indicates the percentage of the block size that all non-key
columns in the index must fit in, in order to not be broken out to the row overflow area
0 INCLUDE_COLUMN [NUMBER] -The column number in the index that indicates the first
column in the index (and all remaining columns) that will be stored in the row overflow area
0 FREELISTS [NUMBER] -The number of freelists for this index. Freelists track a list of data
blocks that have room for new inserts into the index
0 FREELIST_GROUPS [NUMBER] -This is the number of groups of freelists for the index. This
is used with Oracle's Real Application Clusters
0 PCT_FREE [NUMBER] -Percentage of the block that is available for updates only. Oracle will
stop inserting rows into the block once the block reaches this percentage of free space in the
block
0 LOGGING [VARCHAR2 ( 3)] -Specifies whether creation of this index, direct path load, and
direct path inserts against the table this index is built on are logged in the redo log (LOGGING
vs. NOLOGGING)
0 BLEVEL [NUMBER] -This is the depth of the index. A BLEVEL of zero indicates that the root
blocks are the leaf blocks
0 LEAF _BLOCKS [NUMBER] -The number of leaf blocks in the index
0 DISTINCT_KEYS [NUMBER] -The number of distinct keys in the index
0 AVG_LEAF _BLOCKS_PER_KEY [NUMBER] - This is the average number of blocks in which
each distinct value in the index appears. For unique indexes, this number is always 1
0 AVG_DATA_BLOCKS_PER_KEY [NUMBER] -This is the average number of data blocks
pointed to by a distinct value in the index
0 CLUSTERING_FACTOR [NUMBER] -This indicates how well the rows in the table are
ordered, according to the index. If the value is near the number of blocks of the index, the
table is well-ordered. Higher numbers indicate the table is randomly ordered
0 STATUS [VARCHAR2 ( 8) ] -Whether the index is VALID or UNUSABLE
0 NUM_ROWS [NUMBER] -The number of rows in this index
0 SAMPLE_SIZE [NUMBER] -When this index is analyzed, Oracle can estimate statistics based
on a percentage of the table instead of computing statistics based on the entire index.
SAMPLE_SIZE tells you what size was used to estimate the statistics

0 LAST_ANALYZED [DATE] -Identifies the date for the last time this index was analyzed

1014
Data Dictionary

D DEGREE [VARCHAR2 ( 4 0) ) - The number of threads per instance for scanning the index

D INSTANCES [VARCHAR2 ( 4 0) J -The number of instances that can scan an index


simultaneously
D PARTITIONED [VARCHAR2 ( 3) ) -Whether the index is on a temporary table

D TEMPORARY [VARCHAR2 ( 1) J -Whether the table this index is built upon or not

D GENERATED [VARCHAR2 ( 1) ) -The name of an index can be user-defined or system-


generated. This column indicates how this index was named
D SECONDARY [VARCHAR2 (1) J -Was the index was created by the Oracle 9iData Cartridge?

D BUFFER_POOL [VARCHAR2 ( 7) ) -The default buffer pool for this index

D USER_STATS [VARCHAR2 ( 3) J -Indicates whether the statistics for the index were "created"
using the DBMS_STATS supplied package. If a user does, this column will be YES
D DURATION [VARCHAR2 ( 15) J -For indexes built on temporary tables, this indicates the type
of temporary table (SYS$SESSION/SYS$TRANSAC TION)
D PCT_DIRECT_ACCESS [NUMBER) -If the index is on an IOT, this is the percentage of rows
with valid guess
D ITYP_OWNER [VARCHAR2 ( 3 0) J -For a domain index, the owner of the index type

D ITYP_NAME [VARCHAR2 ( 3 0) J - For a domain index, the name of the index type

D PARAMETERS [VARCHAR2 ( 1000) J -For a domain index, the parameter string

D GLOBAL_STATS [VARCHAR2 ( 3)) -For partitioned indexes, indicates whether statistics were
gathered on the entire index (YES) or on the index partitions (NO)
0 DOMIDX_STATUS [VARCHAR2 ( 12) ) -Reflects the status of a domain index (NULL, VALID,
IDXTYP_INVLD)

D DOMIDX_OPSTATUS [VARCHAR2 ( 6)] -Reflects the status of an operation that was


performed on a domain index (NULL, VALID, FAILED)
D FUNCIDX_STATUS [VARCHAR2 ( 8) ) -Indicates the status of a function-based index (NULL,
ENABLED, DISABLED)

D JOIN_INDEX [VARCHAR2 ( 3) J -Whether this is a join index or not


See DBA_IND_COLUMNS for usage information.

DBA_IND_COLUMNS

Column Definitions and Usage


D INDEX_OWNER [VARCHAR2 ( 3 0) J -The user who created the index this column is a part of.

D INDEX_NAME [VARCHAR2 ( 3 0) ) -The name of the index this column is a part of.

D TABLE_OWNER [VARCHAR2 ( 3 0) J -The owner of the table this column's index is defined on.

1015
Appendix C

0 TABLE_NAME [VARCHAR2 ( 3 0) ] -The name of the table this column's index is defined on.
0 COLUMN_NAME [VARCHAR2 ( 4 0 0 0) ] - The name of the column in the index.
0 COLUMN_POSITION [NUMBER] -The position of the column in the index amongst the other
columns.
0 COLUMN_LENGTH [NUMBER] -The indexed length of the column.
0 CHAR_LENGTH [NUMBER] - Maximum length of the column.
0 DESCEND [VARCHAR2 ( 4) ] -Whether the column is sorted in descending order (Y) or not
(N).

To get index information for a particular table, copy the following SQL*Plus script to a file named
indexes. sql:

set verify off


set linesize 72
set pagesize 9999
set feedback off

variable tname varchar2(30)


begin
:tname := upper( '&1');
end;
I

prompt
Prompt Indexes on &1
column index~ame heading "IndexiName•
column Uniqueness heading 'IsiUnique• format a6
column columns format a32 wordLwrapped

select substr(a.ind~ame,l,30) index_name,


decode(a.uniqueness, 'UNIQUE', 'Yes', 'No') uniqueness,
max(decode( b.column_position, 1, substr(b.column_name,1,30),
NULL)) II
max(decode( b.column_position, 2, •, •II
substr(b.column~ame,l,30), NULL )) II
max(decode( b.column_position, 3, ', 'I I
substr(b.column_name,l,30), NULL)) II
max(decode( b.column_position, 4, ', 'I I
substr(b.column_name,1,30), NULL)) II
max(decode( b.column_position, 5, ', 'II
substr(b.column_name,l,30), NULL)) II
max(decode( b . column_position, 6, ', 'I I
substr(b.column_name,1,30), NULL)) II
max(decode( b.column_position, 7, ', 'I I
substr(b.column_name,l,30), NULL)) II
max(decode( b.column_position, 8, ', 'I I
substr(b.column_name,1,30), NULL)) II
max(decode{ b.column_position, 9, ', 'I I
substr(b . column_name,l,30), NULL)) II
max(decode{

1016
Data Dictionary

substr(b.column_name,l,30), NULL)) II
max(decode( b.column_position, 11, ', • I I
substr(b.column_narne,l,30), NULL)) II
max(decode( b.column_position, 12, ', 'I I
substr(b.column~ame,1,30), NULL)) II
max(decode( b.column_position, 13, ', 'I I
substr(b.column_name,1,30), NULL)) II
max(decode( b.column_position, 14, ', 'I I
substr(b . col~name,1,30), NULL)) II
max(decode( b.column_position, 15, ', 'I I
substr(b.column_name,1,30), NULL )) II
max(decode( b . column_position, 16, ', 'I I
substr(b.column_name,1,30), NULL)) columns
from db~indexes a, dba_ind_columns b
where a.owner = USER
and a. table_name = : tname
and b. table_name = a . table_name
and b.table_owner = a . owner
and a. inde~name = b. ind~name
group by substr(a.index~ame,1,30), a.uniqueness
I

Running this script will generate a list of each index on the table along with related information:

SQL> connect hr/hr


Connected.
SQL> @indexes employees

Indexes on employees

Index Is
Name Unique COLUMNS

EMP_DEPARTMENT_IX No DEPARTMENT_ID
EMP_EMAIL_UK Yes EMAIL
EMP_EMP_ID_PK Yes EMPLOYEE_ID
EMP_JOB_IX No JOB_ID
EMP_MANAGER_IX No MANAGER_ID
EMP_NAME_IX No LAST_NAME, FIRST_NAME

DBA_ROLES
DBA_ROLES displays all roles in the database, and whether a password is required to enable them.

Column Definitions and Usage


0 ROLE [VARCHAR2 (30)] -Name of the role

0 PASSWORD_REQUIRED [VARCHAR2 ( 8) ] -Whether a password is required to enable them

1017
Appendix C

SQL> select role, password_required


2 from dba_roles
3 order by role
4 I

ROLE

CONNECT
RESOURCE
DBA
SELECT_CATALOG_ROLE
EXECUTE_CATALOG_ROLE
DELETE_CATALOG_ROLE
EXP_FULL_DATABASE
IMP_FULL_DATABASE
RECOVERY_CATALOG_OWNER
AQ_ADMINISTRATOR_ROLE
AQ_USER_ROLE
GLOBAL~Q_USER_ROLE
OEM_MONITOR
PLUSTRACE
JAVAUSERPRIV
JAVAIDPRIV
JAVASYSPRIV
JAVADEBUGPRIV
JAVA_ADMIN
JAVA_DEPLOY

20 rows selected.

DBA_ROLE_PRIVS
This view displays what roles are granted to which users or roles in the database.

Column Definitions and Usage


0 GRANTEE [VARCHAR2 ( 3 0) ] -Name of the user or role receiving the grant

0 GRANTED_ROLE [VARCHAR2 ( 3 0) ] -Name of the role granted to the grantee

0 ADMIN_OPTION [VARCHAR2 ( 3) ] -Whether the grantee has the ability to grant this role to
other users or roles
0 DEFAULT_ ROLE [VARCHAR2 ( 3)] -Whether the role is a default role for the user or not

In order to find out what roles have been granted to a particular user, use the following query:

set verify off

column grole format a20 heading "Role Granted"


column wadmin format a6 heading "Admin?"

1018
Data Dictionary

prompt &l.'s granted roles

select granted_role grole, initcap(admin_option) wadmin


from dba_role_privs
where grantee= upper( '&1' )
order by 1
I

If we were to pass the DBA role to this query, we would find all those object privileges granted to the
DBA role:

SQL> @roleprivs DBA


DBA's granted roles

Role Granted Admin?

DELETE_CATALOG_ROLE Yes
EXECUTE_CATALOG_ROLE Yes
EXP_FULL_DATABASE No
IMP_FULL_DATABASE No
JAVA_ADMIN No
JAV~DEPLOY No
SELECT_CATALOG_ROLE Yes
WM_ADMIN_ROLE No

8 rows selected.

DBA_SYS_PRIVS
This view shows all those system privileges that are granted to users or roles in your database.

Column Definitions and Usage


0 GRANTEE [VARCHAR2 ( 3 0) ] -Name of the user or role receiving the grant.
0 PRIVILEGE [VARCHAR2 ( 4 0) ] -Name of the privilege granted to the grantee.
0 ADMIN_OPTION [VARCHAR2 ( 3) ] -Whether the grantee has the ability to grant this role to
other users or roles.

In order to see all those privileges that have been granted directly to a user, use the following query:

set verify off

column priv format a30 heading "Privilege"


column wadmin format a6 heading "Admin?"

prompt &l.'s Granted Privileges

select privilege priv, initcap(admin_option) wadmin

1019
Appendix C

from dba_sys_privs
where grantee =upper( '&1' )
order by 1
I

Calling this query using the HR user yields the following results:

SQL> @sysprivs HR
HR's Granted Privileges

Privilege Admin?

ALTER SESSION No
CREATE PROCEDURE No
CREATE SEQUENCE No
CREATE SESSION No
CREATE SYNONYM No
CREATE TABLE No
CREATE TRIGGER No
CREATE VIEW No

8 rows selected.

DBA_DIRECTORIES
This view is used to display information about directory objects created in the database.

Column Definitions and Usage


0 OWNER [ VARCHAR2 ( 3 0 ) ] - The user that created the directory.
0 DIRECTORY_NAME [VARCHAR2 ( 3 0) ] -The name of the directory.
0 DIRECTORY_PATH [VARCHAR2 (4000)] -The path on the operating system this directory
object refers to.

For a practical usage of DBA_DIRECTORIES see DBA_EXTERNAL_LOCATIONS.

DBA_USERS
This view provides information about all the users in the database.

Column Definitions and Usage


0 USERNAME [VARCHAR2 ( 3 0) ] -Name of the user.
0 USER_ID [NUMBER] - ID number assigned to the user.
0 PASSWORD [ VARCHAR2 ( 3 0) ] -The user's encrypted password.

1020
Data Dictionary

0 ACCOUNT_STATUS [VARCHAR2 ( 3 2) ] -Indicates whether the user's account is locked,


unlocked, or expired.
0 LOCK_DATE [DATE] -The date the account was locked (if ACCOUNT_STATUS is locked).
0 EXPIRY_DATE [DATE] -The date the account expires.
0 DEFAULT_TABLESPACE [VARCHAR2 ( 3 0) ] -Default tablespace for data.
0 TEMPORARY_TABLESPACE [VARCHAR2 ( 3 0) ] -Default tablespace (temporary tables).
0 CREATED [DATE] -User creation date.
0 PROFILE [VARCHAR2 ( 3 0) ] -User resource profile name.
0 INITIAL_RSRC_CONSUMER_GROUP [VARCHAR2 ( 3 0) ] -User's initial consumer group.
0 EXTERNAL_NAME [ VARCHAR2 ( 4 0 0 0 ) ] - User external name.

In order to get an overview of user accounts in the database, save the following to a file named
users . sql:

set define off


set echo off
set linesize 78

prompt User Information

column username format a20 heading ·username•


column default_tablespace format al4 heading 'Default Tblspc•
column temporary_tablespace format alO heading "Temp Tblspc•
column locked format al heading 'L"

break on tblspc skip 1

select username, default_tablespace, temporary_tablespace,


decode( account_status, 'EXPIRED & LOCKED', '*'
'OPEN', '' l locked
from dba_users
order by username
I
set define on

Executing this file in SQL*Plus against a database should return information about the users in the
database. The fourth column in the query results, L, is whether the account is locked ( * or not.
11 11 )

SQL> @users
User Information

Username Default Tblspc Temp Tblsp L

AURORA$JIS$UTILITY$ SYSTEM TEMP


AURORA$0RB$UNAUTHENT SYSTEM TEMP
ICATED

1021
Appendix C

CTXSYS DRSYS TEMP *


CLBECK USERS TEMP
DBSNMP SYSTEM TEMP
HR EXAMPLE TEMP
HR._AUDIT USERS TEMP
LBACSYS SYSTEM TEMP *
MDSYS SYSTEM TEMP *
OE EXAMPLE TEMP
ORACLE_DBA USERS TEMP
ORDPLUGINS SYSTEM TEMP •
ORDSYS SYSTEM TEMP •
OSE$HTTP$ADMIN SYSTEM TEMP
OUTLN SYSTEM TEMP •
PM EXAMPLE TEMP
PPL USERS TEMP
QS EXAMPLE TEMP
QS_ADM EXAMPLE TEMP
QS_CB EXAMPLE TEMP
QS_CBADM EXAMPLE TEMP
QS_CS EXAMPLE TEMP
QS_ES EXAMPLE TEMP
QS_OS EXAMPLE TEMP
QS_WS EXAMPLE TEMP
SCO'M' USERS TEMP
SDILLON USERS TEMP
SH EXAMPLE TEMP
SYS SYSTEM TEMP
SYSTEM SYSTEM TEMP
TKYTE USERS TEMP
WKSYS DRSYS TEMP •

GLOBAL_NAME
This view is a one-row, one-column view that displays the global name of the current database.

Column Definitions
0 GLOBAL_NAME [VARCHAR2 ( 4 0 0 0) ] - The global name of the database.

GLOBAL_NAME can be used to find out the name of the database you are currently connected to. This is
useful information for tools that connect to multiple databases. Place the following SQL*Plus command
in a file named prompt. sql:

set termout off


column global_name new_value gname
select lower(user) I I '@' I I global_name global_name
from global_name;
set termout on
set sqlpro~t '&~arne> '

1022
Data Dictionary

Executing it from a standard SQL*Plus prompt is as follows:

SQL> @prompt.sql

GLOBAL_NAME

sdillon@SLAPDB.US.ORACLE.COM

sdillon@SLAPDB.US.ORACLE.COM> -- new sqlprompt!

Short Names
Some of the data dictionary views have synonyms as summarized here:

Synonym Data Dictionary View


CAT USER_CATALOG
CLU USER_CLUSTERS
COLS USER_TAB_COLUMNS
IND USER_INDEXES
OBJ USER_ OBJECTS
DICT DICTIONARY
SEQ USER_SEQUENCES
SYN USER_SYNONYMS
TABS USER_TABLES

SQL> select table_name


2 from user_tables
3 I

is the same as ...

SQL> select table_name


2 from tabs
3 I

1023
Installing Sample Schemas

In this appendix, we see how to install Oracle's sample schemas. We look at the familiar SCOTT schema
as well as the new Oracle 9i sample schemas.

Installing the SCOTT Schema


The file used to install the SCOTT schema is utlsampl. sql, and can be found in the
following directory:

Unix:
0 7 or earlier. $ORACLE_HOME/rdbms/admin/utlsampl. sql
0 8.0.0- 8.0.6. $ORACLE_HOME/rdbms80 / admin/utlsampl. sql
0 8.1.3- 8. 1.7. $ORACLE_HOME/rdbms / admin/utlsampl. sql

Windows:
0 7 or earlier. %ORACLE_ HOME%/rdbms/admin/utlsampl. sql
0 8.0.0- 8.0.6. %0RACLE_HOME%/rdbms80 / admin/utlsampl. sql
0 8.1.3- 8.1.7. %0RACLE_HOME%/rdbms/admin/utlsampl. sql

This script performs a number of operations:

0 The users SCOTT, ADAMS, JONES, CLARK, and BLAKE are dropped.
0 The user SCOTT is created with the password TIGER. SCOTT and is granted RESOURCE and
UNLIMITED TABLESPACE privileges.

0 The public synonym PARTS is dropped.


0 The user SCOTT is connected, and this user is used to create the EMP, DEPT, BONUS, and
SALGRADE tables.

0 The tables are populated with sample data.


Appendix D

One noticeable difference between this script in Oracle 9i and previous versions is that the users
ADAMS, JONES, CLARK, and BLAKE are not created. These users were created in previous versions to
simulate employees from the EMP table having database accounts. In version 9.0.1, these users are
removed for security reasons.

In Oracle 9i, a number of changes have been made to default user accounts created during installation to
avoid security risks with default users and passwords. Now, many of the users that are created by default
have their accounts locked.
Some Oracle users would prefer to have these two tables created in a schema with their own usemame,
rather than in the SCOTT schema. Instead of modifying the utlsarnpl. sql script, there is another script
available named dernobld. sql that helps do this. This script can be found in the following directory:

Unix:
0 8.0.0- 8.0.6: $0RACLE_HOME/dbs/dernobld. sql
0 8.1.3- 9.0.1: $0RACLE_HOME/sqlplus/derno/dernobld. sql

Windows:
0 8.0.0- 8.0.6: %0RACLE_HOME%\dbs\dernobld. sql
0 8.1.3- 9.0.1: %ORACLE_HOME%\sqlplus\derno\dernobld. sql

In order to use the dernobld. sql script, connect to the database as a user with CREATE TABLE
privileges and run the script. This creates the same tables and data as the utlsarnpl. sql script, but
does so in the current user's schema. To remove the tables run the dernodrop. sql script located in the
same directory.

The SCOTT schema is not terribly complex. It was created many years ago and there haven't been many
changes to this script throughout the years. To truly show off the capabilities of Oracle, our samples
need to be stepped up considerably! With that in mind, let's move on to discuss the new sample
schemas introduced in Oracle 9i.

Installing the Oracle 9i Schemas


There are two ways to install the sample schemas in Oracle 9i. The first and easiest way is to use the
Database Configuration Assistant (DBCA}. The other way is to run the installation scripts manually.

Using the DBCA


The sample schemas can be installed in a new or existing database. If you are using the DBCA to create
a new database then you can simply allow the DBCA tool to install the sample schemas along with the
new database, (see below for details}. If you already have a database you want to install the sample
schemas into, you can use the DBCA to generate the scripts you will use to perform the installation. Use
the following steps to install the sample schemas with the DBCA tool:

1. Start up the DBCA from the command line (by typing dbca} or through the Windows Start
menu. The file will be located in $0RACLE_HOME/bin/dbca on UNIX, and
%0RACLE_HOME% \bin \dbca. bat on Windows.

1026
Installing Sample Schemas

2. Click the Next button to show the available tasks you can perform with the DBCA.

3. Select the Create a database radio button and click the Next button to continue.

4. Select the New database radio button and click the Next button to continue.

5. Choose a Global Database Name and SID, and click the Next button.

6. Click on the Example Schemas checkbox, and select the sample schemas you would like
installed. You may want to review the guidelines below in the Schema Dependencies section
when doing so.

7. Click on the Additional database configurations ... button if you want to install the Oracle
JVM and/or Oracle lntermedia (these are required for the Product Media schema).

8. Once you have selected the schemas and database configuration options to install, click on the
Next button.

9. If you are only using the DBCA to install the sample schemas, you can simply click the Next
button for the next three steps.

10. Select the server mode you want your database to operate in. If you are not sure, select
Dedicated Server Mode, and click Next.

11. Configure the initialization parameters for your database instance. If you're not sure, select
the Typical radio button, and select the Multipurpose option in Database Type. Click Next
to continue.

12. Configure your database storage. If you wish to change the location of the data files from the
default location, click on the Files Location Variables ... button. Click Next to continue.

13. On the final page, what you do will depend on whether or not you are performing an
installation or not. If you are really creating a database, select the Create Database checkbox
and click Finish. The schema creation will be performed as a part of the database creation,
and your work is done. If you are only using this wizard for the sample schema installation,
click on the Generate Database Creation Scripts checkbox, select a destination directory for
the files to be generated, and click on Finish.

14. Once you click Finish, you will be presented with an overview of all the options you selected
for the database you wish to create. Simply click on OK to continue.

15. A dialog box will appear, which indicates your scripts are being created. Once the scripts are
complete, you will be notified with a pop-up window telling you that the script generation was
successful, and asking if you would like to perform another operation. Click No to close the DBCA.

16. Once the DBCA is closed, you can run the demoSchemas. sql file in the directory location
specified in step 13 above.

1027
Appendix D

You will notice there are quite a few other file in that directory. Th.i is becau e the
DBCA bas created all the scripts nece ary for you to create an entire database, not
just the sample scbemas. Reviewing these files would be a good way to learn the teps
involved in creating an Oracle database.

Manual Installation
Instead of using the DBCA, you can choose to perform a manual installation of the sample schemas, in
one of two ways. The first and easiest way is by executing the following SQL*Plus script:

0 UNIX: $0RACLE_HOME/demo/schema/mksample.sql

0 Windows: %ORACLE_HOME% \demo\ schema \mksample. sql

This file will create all of the sample schemas in the correct order, and will prompt you for all the
information it needs for the installation (in other words, SYS, SYSTEM, and schema passwords, and so
on). Since there are inter-schema dependencies there are grants that must be performed during the
course of the installation between schemas. These grants are all handled in this single script. The default
tablespace and temporary table space for each of the sample schemas is specified for you as EXAMPLE
and TEMP respectively.

The other way to perform manual installations is to run each of the sample schemas' installation scripts
individually. This takes longer, and is more work, but in the end you will have a better understanding of the
schema objects, the inter-schema dependencies, and how to recreate data once you've been playing with it.

You do not have to install all the sample schemas if you don't want to. The problem then is that
dependencies that exist between the schemas will prevent the successful installation of a schema if it is
dependent on another schema that is not installed yet. An easy way to manage this is to install the
schemas in the following order, until you have installed the schema(s) you want to install:

0 Human Resources
0 Order Entry
0 Product Media
0 Queued Shipping
0 Sales History

In other words, if you wanted to install the Order Entry schema, you must first install Human Resources
and then Order Entry. If you wanted to install Sales History, you need to install them all. We will talk
more about inter-schema dependencies in a later section.

Human Resources Schema Installation


You will find that a manual installation of the schemas is relatively simple. The installation scripts are
constructed so that one script can be run which will in turn run all the other scripts. The master script
name is called <schema_name> _main. sql, and can be found in the schema's directory along with all
the supporting installation scripts. The sample schema installation directories can be found in the
following location:

1028
Installing Sample Schemas

0 UNIX: $0RACLE_HOME/demo/schema/
0 Windows: %0RACLE_HOME%\demo\schema\

For example, if we were to look for the Human Resources (HR) scripts we would find them in the
following directory:

Unix:
$ ls $0RACLE_HOME/demo/schema/human_resources
./ hr_code.sql hr_dn_c.sql hr_idx.sql
.. / hr_comnt.sql hr_dn_d.sql hr_main.sql,
hr_analz.sql hr_cre.sql hr_drop.sql hr_popul.sql

Windows:
C:\>dir/w/a/o %0RACLE_HOME%\demo\schema\human_resources
Volume in drive C has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\demo\schema\human_resources

[ .) [ .. ) hr_analz.sql hr_code . sql hr_comnt.sql


hr_cre.sql hr_dn_c.sql hr_dn_d.sql hr_drop.sql hr_idx.sql
hr_main.sql hr_popul . sql
10 File(s) 89,628 bytes
2 Dir(s) 561,352,704 bytes free

As mentioned above, the hr_main. sql file is the master installation script for the Human Resources
schema. This script performs the following steps:

1. Drops the HR schema and all its objects, if it already exists.

2. Creates the HR schema, and grants the appropriate privileges for the schema to create tables,
procedures, sequences, triggers, views, and synonyms.

3. Grants the user the ability to execute the SYS. DBMS_STATS package.

4. Runs hr_cre. sql to create the HR tables, sequences, and constraints

5. Runs hr_popul. sql to insert all the data into the HR tables.

6. Runs hr_idx. sql to create indexes on the tables.

7. Runs hr_code. sql to create the procedural code owned by HR.

8. Runs hr_comnt. sql to add meta data comments to tables and comments.

9. Runs hr_analz. sql which uses the DBMS_STATS package to gather statistics for each table.

1029
Appendix D

Be sure to check the spool file which was generated in the script above for any errors you may have
encountered but didn't see while you were running the scripts in SQL*Plus. The name of the spool file
in the scripts above is hr_mail. log.

One thing to note about the HR schema (but not the other chemas) is it is currently not
Oracle 9i-dependent. There is nothing in the Human Resources installation scripts that
prevents you from running the scripts on an Oracle 8i database (version 8.1.6 for
example).

Order Entry Schema Installation


You will find the installation scripts for the Order Entry (OE) schema in the order_entry directory of
the sample schemas directories. The files in this directory are as follows:

UNIX:
$ ls $0RACLE_HOME/demo/schema/order_entry
./ oe_p_ar.sql oe_p_itm.sql oe_p_ru. sql
.. I oe_p_cs.sql oe_p_iw.sql oe_p_s.sql
oc_comnt.sql oe_p_cus.sql oe_p_ja. sql oe_p_s f . sql
oc_cre.sql oe_p_d.sql oe_p_ko. sql oe_p_sk.sql
oc_drop. sql oe_p_dk. sql oe_p_n.sql oe_p_th. sql
oc_main. sql oe_p_e.sql oe_p_nl. sql oe_p_tr.sql
oc_popul.sql oe_p_el.sql oe_p_ord.sql oe_p_us.sql
oe_analz.sql oe_p_esa. sql oe_p__pd. sql oe_p_whs.sql
oe_comnt.sql oe_p_f.sql oe_p_pi . sql oe_p_zhs . sql
oe_cre.sql oe_p_frc.sql oe_p_pl . sql oe_p_zht. sql
oe_d.rop.sql oe_p_hu. sql oe_p_pt . sql oe_views.sql
oe_idx.sql oe_p_i.sql oe_p_ptb. sql
oe_main. sql oe_p_inv.sql oe_p_ro.sql

Windows:
C:\>dir/w/a/o %0RACLE_HOME%\demo\schema\order_entry
Volume in drive c has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\demo\schema\order_entry

[.] [ .. ] oc_comnt. sql oc_cre.sql oc_drop.sql


oc_main. sql oc_popul. sql oe_analz.sql oe_comnt. sql oe_cre.sql
oe_drop.sql oe_idx.sql oe_main. sql oe_p_ar.sql oe_p_ca. sql
oe_p_cs.sql oe_p_cus.sql oe_p_d.sql oe_p_dk. sql oe_p_e.sql
oe_p_el.sql oe_p_esa.sql oe_p_f .sql oe_p_frc.sql oe_p_hu. sql
oe_p_i.sql oe_p_inv.sql oe_p_i tm. sql oe_p_iw.sql oe_p_j a . sql
oe_p_ko.sql oe_p_n.sql oe_p_nl . sql oe_p_ord.sql oe_p_pd. sql
oe_p_pi . sql oe_p_pl . sql oe_p_pt. sql oe_p_ptb. sql oe_p_ro.sql
oe_p_ru. sql oe_p_s.sql oe_p_sf.sql oe_p_sk. sql oe_p_th.sql
oe_p_tr.sql oe_p_us.sql oe_p_whs.sql oe_p_zhs . sql oe_p_zht.sql
oe_views.sql
49 File(s) 3,286,640 bytes
2 Dir(s) 561,377,280 bytes free

1030
Installing Sample Schemas

As you can see, there are quite a few more files involved for the installation of the Order Entry schema
than there were for the Human Resources schema. You will notice, when we discuss using these scripts
to install the sample schemas, that not all the files in this directory are used during the installation. This
is because in this release of the database the default NLS_LANGUAGE and NLS_TERRITORY are
"American". The unused files in this directory represent product descriptions and product information
in other languages supported by the Oracle database.

As we saw in the Human Resources schema installation, you need only call the oe_main. sql file,
which in turn calls all other necessary SQL*Plus installation files.

The oe_main. sql file is responsible for performing the following steps:

1. Dropping the OE schema and all its objects, if OE already exists.

2. Creating the OE schema, and granting the appropriate privileges for the schema to create
tables, views, synonyms, materialized views, triggers, sequences, and perform query rewrite.

3. Granting the user the ability to execute the SYS. DBMS_STATS package.

4. Connecting as the HR schema, and granting object privileges on many of the HR tables.

5. Running oe_cre. sql in order to create the OE types, tables, sequences, synonyms, and constraints.

6. Running oe_p_pi. sql to populate the PRODUCT_INFORMATION table.

7. Running oe_p_pd. sql to populate PRODUCT_DESCRIPTION with a number of other


language translations.

8. Running oe_p_whs . sql to populate the WAREHOUSES table, as well as the XMLType column
warehouse_spec with XML data.

9. Running oe_p_cus. sql to populate the CUSTOMERS table.

10. Running oe_p_ord. sql to populate the ORDERS table.


11. Running oe_p_i tm. sql to populate the ORDER_ITEMS table.
12. Running oe_p_inv. sql to populate the INVENTORIES table.

13. Running oe_views. sql to create various inventory, product, and product pricing views.
14. Running oe_comnt. sql to create meta data comments on tables and columns.
15. Running oe_idx. sql to create indexes.
16. Running oe_analz. sql which uses the DBMS_STATS package to gather statistics for each table.
17. Running oc_main. sql to create the OC subschema, which is basically a number of object
types, object views, and inserts into those views.

1031
Appendix D

The spool file is named oe_oc_main. log. This spool file contains the results of the entire installation.
Be sure to review the file for any errors that may have occurred. Once this script is done and you have
reviewed the spool file, the Order Entry schema is installed.

Product Media Schema Installation


You will find the installation scripts for the Product Media (PM) schema in the product_media
directory of the sample schemas home directory. You will find many files in this directory that are not
SQL files, but which are still necessary for the installation of the Product Media schema installation. The
necessary files in this directory are as follows:

UNIX:
$ ls $0RACLE_HOME/demo/schema/product_media/pm_*
pm_analz.sql pffiLdrOp.sql pm_p_lob.ctl pm_p_ord . sql
pm_cre.sql pm_main.sql pm_p_lob . sql

Windows:
C: \>dir/w/a/o %ORACLE_HOME%\demo\schema\product_media\pm_•
Volume in drive C has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\demo\schema\product_media

pm_analz. sql PffiLCre.sql pffiLdrop. sql pm_main . sql pm_p_lob . ctl


pm_p_lob.dat pm_p_lob.sql pm_p_ord.sql
8 File(s) 33,477 bytes
0 Dir(s) 559,833,088 bytes free

Other files that are not mentioned are a variety of image, audio, and video files in the same directory
that will be loaded into the database during the installation process. To install the entire Product Media
schema, run the pm_main. sql file. This file will run all the necessary files for installing the Product
Media schema.

The pm_main. sql file is responsible for performing the following steps:

1. Dropping the PM schema and its objects, if PM already exists.

2. Creating the PM schema, and granting the appropriate privileges for the schema to create
tables, types, indexes, and procedures.

3. Connecting as the OE schema, and granting object privileges on many of the OE tables.

4. Granting the PM schema the ability to execute the SYS . DBMS_STATS package.

5. Running pm_cre. sql to create the OE types, tables, sequences, synonyms, and constraints.

6. Running pm__p_ord. sql to populate the PRODUCT_INFORMATION table.

7. Running pm__p_lob. sql to load the PRINT_MEDIA and TEXTDOCS_NESTEDTAB tables with
documents in the product_media directory.

1032
Installing Sample Schemas

8. Running pm_analz. sql which uses the DBMS_STATS package to gather statistics for each table.

The spool file is named pm_main .log. This spool file contains the results of the entire installation. Be
sure to review the file for any errors that may have occurred. Once this script is done and you have
reviewed the spool file, the Product Media schema is installed.

Queued Shipping Schema Installation


The Queued Shipping {QS) schema installation is slightly more complex, due to the fact that we are
creating eight schemas, not just one. Not only that but we are also configuring Oracle Advanced
Queues. Getting your advanced queues installed, designed, configured, and working properly is an
intermediate-to-advanced-level task. By installing the shipping schema{s) and analyzing the entire
installation, you have a good baseline to work from when you want to start using Advanced Queues for
your own projects.

All the files necessary for the installation are located in the shipping directory of the sample schemas'
directories.

UNIX:
$ ls $0RACLE_HOME/demo/schema/shipping
./ qs_cre.sql qs_main.sql qs_ws.sql
.. / qs_cs.sql qs_os.sql
qs_adm.sql qs_drop.sql qs_popul.sql
qs_cbadm.sql qs_es.sql qs_run.sql

Windows:
C:\>dir /w/a/o 'ORACLE_HOME,\demo\schema\shipping
Volume in drive C has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\demo\schema\shipping

[.) [ .. ) qs_adm.sql qs_cbadm. sql qs_cre.sql


qs_cs.sql qs_drop. sql qs_es.sql qs_main.sql qs_os.sql
qs_run.sql qs_ws.sql
10 File(s) 50,567 bytes
2 Dir(s) 557,395,968 bytes free

To install all the shipping schemas, run the file qs_main. sql. This file performs the following steps:

1. Drops the QS_ADM, QS, QS_WS, QS_ES, QS_OS, QS_CBADM, QS_CB, and QS_CS schemas and
their objects, if they already exist.

2. Alters the database instance to start up job queue processes if they aren't already running.
These queue processes are responsible for managing queuing of messages.

3. Creates the QS_ADM schema, and grants all the appropriate privileges to this user. This user, as
the schema name indicates, is the Queued Shipping Administration schema. This schema is
granted the role aq_administrator_role as well as the queuing system privileges
ENQUEUE_ANY and DEQUEUE_ANY. This indicates that this schema can enqueue and dequeue
messages from any queue in the database.

1033
Appendix D

4. Creates the rest of the shipping schemas to represent various sections within the shipping
department, as follows:

0 QS - Queued Shipping schema.


0 QS_WS- Western region shipping.
0 QS_ES - Eastern region shipping.
0 QS_OS - Overseas shipping.
0 QS_CBADM- Customer billing administration. For security reasons, this schema is
created to hold the customer billing queues and application tables.
0 QS_CB - Customer billing.
0 QS_CS -Customer service.

5. Once those schemas are created, they are granted appropriate privileges to perform the
queuing tasks for which they will be responsible and create a variety of database objects,
which are as follows:

0 Clusters
0 Database links
0 Sequences
0 Create sessions
0 Synonyms
0 Tables
0 Views
0 Index types
0 Operators
0 Procedures
0 Sequences
0 Triggers
0 Types

They also have responsibility for executing the DBMS_AQ and DBMS_AQADM packages.

6. Connects as the
OE schema and grants object privileges on the CUSTOMERS and
PRODUCT_INFORMATION tables to QS_ADM.

7. Runs qs_adm. sql to create a few object types that will be used in the queues to pass data
between the shipping subschemas. The appropriate privileges are granted to the other
shipping subschemas to use these types.

1034
Installing Sample Schemas

8. Runs qs_cre. sql to create queues and queue tables for orders. A non-persistent queue is
created to track the number of connections to the shipping application.

Qjleue tables are used to store queued messages and/or objects. These tables are created, managed,
and removed through the Oracle Advanced Q,ueues AP/s.

9. Runs qs_es . sql to create queues and queue tables for the Eastern Shipping schema.

10. Runs qs_ws . sql to create queues, queue tables, and queue subscribers for the Western
Shipping schema.

11. Runs qs_os . sql to create queues and queue tables for the Overseas Shipping schema.
12. Runs qs_cbadm. sql to create customer billing queues, queue tables, and queue subscribers.
13. Runs qs_cs. sql to create a customer status queue and queue table that is responsible for
tracking the status of customer orders.

14. Runs qs_run. sql to create the QS_APPLICATIONS package. This package is for submitting
orders to the collection of shipping subschemas for processing. Effectively, it is a front-end
tool for the queues that have been created.

The spool file is named qs_main. log. This spool file contains the results of the entire installation. Be
sure to review the file for any errors that may have occurred. Once this script is done and you have
reviewed the spool file, the Queued Shipping schema and all the shipping subschemas are installed.

Sales History Schema Installation


The Sales History (SH) schema installation is fairly straightforward. It has a different installation process
from the rest of the schemas, because it relies heavily on SQL*Loader to populate the vast relational
tables that it consists of.

The files you will need for the sales history schema installation are located in two places. The
sales_history directory under the sample schemas directories is where you will find the majority of
the files needed:

UNIX:
$ ls $ORACLE_HOMEidemolschemalsales_history
.I sh_cremv.sql sh_main. sql sh__prod.ctl
.. I sh_cust.ctl sh,_olp_c.sql sh__prod.dat
sh,_analz . sql sh,_cust.dat sh,_olp_d.sql sh__promo.ctl
sh_comnt. sql sh_drop . sql sh__popl.sql sh__promo.dat
sh_cons. sql sh_hiera. sql sh__pop2.sql sh_sales.ctl
sh_cre.sql sh,_idx. sql sh__pop3.sql sh_sales.dat

1035
Appendix D

Windows:
C:\>dir /w/a/o %0RACLE_HOME%\demo\schema\sales_history
Volume in drive C has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\demo\schema\sales_history

[.] ..
[ ] sn_analz. sql sh_comnt. sql sh_cons . sql
sh_cre.sql sQ_cremv. sql sh_cust.ctl sh_cust . dat sh_drop.sql
sh_hiera.sql sQ_idx.sql s}Unain.sql sh_olp_c . sql sh_olp_d. sql
sQ_popl . sql sh_pop2 . sql sQ_pop3.sql sh_prod.ctl sh_prod . dat
sQ_promo.ctl sQ_promo.dat sh_sales.ctl sh_sales.dat
22 File(s) 66,095,457 bytes
2 Dir(s) 556,748,800 bytes free

In addition to the sales history installation files, there are five files referenced from the
$0RACLE_HOME/rdbms/admin directory (%0RACLE_HOME%\rdbms\admin on Windows). They are
as follows:

UNIX:
$ ls $0RACLE_HOME/rdbms/admin/utlx*.sql
/export/home/Oracle 9i/rdbrns/admin/utlxmv.sql
/export/home/Oracle 9i/rdbrns/admin/utlxplan.sql
/export/home/Oracle 9i/rdbms/admin/utlxplp.sql
/export/home/Oracle 9i/rdbms/admin/utlxpls.sql
/export/home/Oracle 9i/rdbms/admin/utlxrw.sql

Windows:
C:\>dir /w/a/o %ORACLE_HOME%\rdbms\admin\utlx*.sql
Volume in drive C has no label.
Volume Serial Number is 787E-5450

Directory of C:\Oracle\ora90\rdbms\admin

utlxmv.sql utlxplan . sql utlxplp.sql utlxpls.sql utlxrw.sql


5 File(s) 18,619 bytes
0 Dir(s) 556,285,952 bytes free

To install the Sales History schema, run the file sh_main. sql. This file performs the following steps:

1. Drops the SH schema and its objects, if SH already exists.

2. Creates the SH schema, and grants all the appropriate privileges to this user. Privileges
granted are as follows:

D Create session (connect to database)


D Alter session
D Create table

1036
Installing Sample Schemas

0 Create dimension
0 Create materialized view
0 Query rewrite
0 Create any directory
0 Drop any directory

3. Grants execute on SYS. DBMS_STATS package to SH.

4. Runs sh_cre. sql to create the tables for the sales history schema.

5. Runs sh_popl. sql to populate the COUNTRIES and CHANNELS tables.

6. Runs sh_pop2 . sql to populate the TIMES table.

7. Runs sh_pop3 . sql to populate the PROMOTIONS, CUSTOMERS, PRODUCTS, and SALES
tables using SQL*Loader. The SALES_TRANSACTIONS_EXT external table is also created,
and the data file is associated accordingly. The COSTS table is then populated with a INSERT
INTO SELECT statement from the SALES_TRANSACTIONS_EXT table.

8. Runs sh_idx. sql to create all the Sales History schema's indexes.

9. Runs sh_cons. sql to enable the constraints on the SALES table.

10. Runs sh_hiera. sql to create all the Sales History schema's dimensions and hierarchies.
11. Runs sh_cremv. sql to create all the Sales History schema's materialized views.
12. Runs sh_analz. sql which uses the DBMS_STATS. GATHER_SCHEMA_STATS routine to
analyze the entire Sales History schema.

13.Runs sh_comnt. sql to create meta data comments on tables and columns.
14. Runs utlxplan. sql to create the PLAN_ TABLE table, which is used by the EXPLAIN_PLAN
statement.

15. Runs u tlxrw. sql to create the REWRITE_TABLE table that is populated by the
DBMS_MVIEW. EXPLAIN_REWRITE procedure.

16. Runs utlxmv. sql to create the MV_CAPABILITIES_TABLE table that is used by the
DBMS_MVIEW. EXPLAIN_MVIEW procedure.

The spool file is named sh_main .log. This spool file contains the results of the entire installation. Be
sure to review the file for any errors that may have occurred. Once this script is done and you have
reviewed the spool file, the Sales History schema is installed.

1037
Appendix D

Schema Dependencies
In order to use the Oracle 9i sample schemas, there are inter-schema dependencies you need to
understand:

0 The Order Entry schema depends on the Human Resources schema


0 The Product Media schema depends on the Human Resources and Order Entry schemas
0 The Queued Shipping schema depends on the Order Entry schema
0 The Sales History schema depends on the Order Entry schema

As indicated earlier in the chapter, if you are installing all the schemas you should do them in the
following order: HR, OE, PM, QS, and SH. Creating the schemas in this order satisfies the schema
dependencies.

In addition to inter-schema dependencies, there are technology dependencies to be aware of. Because
the database can be configured with various options, you may or may not decide to include the Oracle
lntermedia in your database installation. If you don't install this, you will not be able to use the Product
Media schema, as it requires lntermedia to store and process image, audio, and video data. Use the
following guidelines when choosing what database options to install:

0 The Order Entry schema needs Oracle Spatial


0 The Product Media schema requires Oracle lntermedia and the Oracle Java Virtual Machine

Installation Wrap Up
This completes the installation instructions for the Oracle 9i sample schemas. It is certainly more time-
consuming and will take a greater number of keystrokes to complete the installation manually. On the
other hand, once you perform a manual installation you have a much more intimate understanding of
the sample schema architecture.

1038
Installing Sample Schemas

1039
Options and Features

Not all of Oracle's options and features are available in every edition and release of the database. In this
appendix, we will review the options and features available in the most recent releases of Oracle.

If you review the tables below, you may notice a trend in the way Oracle introduces features and
options into the classes of the database. Typically, a new feature is introduced and made available only
on the Enterprise Edition. It will stay this way for a number of releases until the functionality that the
feature offers becomes mainstream in other vendors' products, at which time Oracle will make it
available on the Standard Edition as well. For instance, in Oracle 8.0.4 object functionality was bundled
in the "Objects Option". It was made available only to the Oracle Enterprise Edition database. In
Oracle 8.1.5, "objects and extensibility" became a feature and was made available on both platforms,
Standard and Enterprise. It stayed this way through 8.1.6 and 8.1.7, until Oracle 9i9.0.1 was released.
In 9.0.1, "objects and extensibility" isn't even mentioned; it's just a core feature of the database.

For the past few years, Oracle has published a document entitled "Getting To Know ... " that provided a
central resource of useful information about the new version. In this document you would find
information such as:

0 A summary of new features that were added


0 Which features were no longer supported or were deprecated
0 The titles of all the documentation
0 Feature and option availability

The first one was published with Oracle 8 8.0.4, and the last one with Oracle 8i 8.1.7. In Oracle 9i9.0.1,
this information can be found in the RDBMS README documentation. For versions prior to Oracle 8
8.0.4, you can visit Oracle's Technology Network for new features by release and documentation at
http://technet.oracle.com.

In the tables overleaf, we break down the option and feature availability by release.
Appendix E

Oracle 9i 9.0.1
Option Availability
Option Personal Standard Enterprise
Advanced Replication y N y

Oracle Advanced Security N N y

Oracle Change Management Pack y N y


Oracle Data Mining y N y

Oracle Diagnostics Pack y N y

Oracle Label Security y N y

Oracle Management Pack for Oracle Applications N N y


Oracle Management Pack for SAP R/3 N N y

Oracle OLAP y N y

Oracle Partitioning y N y

Oracle Programmer y y y

Real Application Clusters y N y

Oracle Spatial y N y
Oracle Tuning Pack y N y

Feature Availability
Features Personal Standard Enterprise
Application Development
AppWizard for Visual Studio (NT only) y y y

Autonomous Transactions y y y

COM cartridge (NT only) y y y

iSQL*Plus y y y

Java N y y

JDBC drivers y y y

Microsoft Transaction Server Integration (NT y y y


only)

1042
Options and Features

Features Personal Standard Enterprise


Application Development (Cont'd}
Objects and extensibility y y y

PLISQL native compilation y y y

PL!SQL stored procedures and triggers y y y

PLISQL Server Pages y y y

User-defined aggregates y y y

XML y y y

Content Management
Dynamic Services y y y

Oracle Database Workspace Manager y y y

Parallel Text Index Creation y N y

Ultra Search y y y

Database Features
Advanced Queuing y y y

Database event triggers y y y

DBMS_REPAIR package y y y

Drop column y y y

Flashback Query y y y

Globalization Support y y y

Index coalesce y N y

Index-organized tables y y y

Instead-of triggers y y y

LOB support y y y

Locally-managed tablespaces y y y

LogMiner y y y

Online index build y N y

Online table reorganization y N y

Plan stability y y y
Table continued on following page

1043
Appendix E

Features Personal Standard Enterprise


Database Features (Cont'd)
Quiesce database y N y

Reverse key indexes y y y

Temporary tables y y y

Trial Recovery y N y

Distributed Database Features


Advanced Replication y N y

Basic Replication y y y

Distributed queries y y y

Distributed transactions y y y

Heterogeneous services y y y

Integration
Messaging Gateway to IBM MQ Series y N y

Manageability
Basic readable standby database y y y

Block-level media recovery y N y

Database Resource Manager y N y

Oracle Data Guard y N y

Duplexed backup sets y N y

Fast-start selectable recovery time y N y

Global index maintenance during DDL operations y y y

Incremental backup and recovery y N y

Legato Storage Manager y y y

Multiple block size y y y

Online backup and recovery y y y

Oracle Change Management Pack y N y

Oracle Enterprise Manager y y y

Oracle Fail Safe for Oracle 9i on NT y y y

Oracle Managed Files y y y

1044
Options and Features

Features Personal Standard Enterprise


Integration (Cont'd)
Parallel backup and recovery y N y

Point-in-time tablespace recovery y N y

Recovery Manager y y y

Resumable space allocation y y y

Standby Database GUI y N y

Transparent application failover y N y

Unused index identification y y y

Networking
Connection pooling y y y

Oracle Connection Manager y N y

Oracle Names y y y

Oracle Net Services y y y

Security
Encryption toolkit y y y

Virtual Private Database y N y

Fine-grained auditing y N y

Password management y y y

Proxy authentication y y y

Warehousing/VLDB
Analytic functions y y y

Automated parallel query degree y N y

Bitmapped indexes and bitmapped joined indexes y N y

Descending indexes y y y

Direct Path Load API y y y

Export transportable tablespaces y N y

Import transportable tablespaces y y y

External tables y y y
Table continued on following page

1045
Appendix E

Features Personal Standard Enterprise


Warehousing/VLDB (Cont'd)
Function-based indexes y y y
Long operations monitor y y y
Materialized views y N y
MERGE (incremental refresh of tables) y y y
Optimizer statistics management y y y
Parallel analyze y N y
Parallel bitmap star query optimization y N y
Parallel DML y N y

Parallel index build y N y

Parallel index scans y N y


Parallel load y y y
Parallel query y N y
Pipelined table functions
Sample scan y y y
Star query optimization y y y
Synchronous Change Data Capture y N y

Oracle 81 8.1.6, 8.1. 7


Option Availability
Option Workstation Standard Enterprise
Oracle Advanced Security y N y

Oracle Change Management Pack y N y

Oracle Diagnostics Pack y N y

Oracle interMedia y y y

Oracle ]Server N y N
Oracle ]Server Enterprise Edition y N y
Oracle Parallel Server y N y
Oracle Partitioning y N y

1046
Options and Features

Option Workstation Standard Enterprise


Oracle Programmer y y y

Oracle Spatial y N y

Oracle Standard Management Pack N y N


Oracle Time Series y N y

Oracle Tuning Pack y N y

Oracle Visual Information Retrieval y N y

Oracle W ebDB y y y

Feature Availability
Features Workstation Standard Enterprise
Application Development
AppWizard for Visual Studio (NT only) y y y

Autonomous Transactions y y y

COM Automation Feature (NT only) y y y

JDBC drivers y y y

Microsoft Transaction Server integration (NT y y y


only)
Objects for OLE y y y
ODBC Driver y y y
Oracle Call Interface (OCI) y y y
Pro*C y y y

SQLJ y y y

Database Features
Advanced queuing y N y

Database event triggers y y y

DBMS_REPAIR package y y y

Drop column y y y

Fine-grained access control y N y


Table continued on following page

1047
Appendix E

Features Workstation Standard Enterprise


Application Development (Cont'd)
Index coalesce y N y
Index-organized tables y y y
Indexes on NLS collating sequences y N y

Instead-of triggers y y y

LOB support y y y

Locally-managed tablespaces y y y

LogMiner y y y

National language support (NLS) y y y

Objects and extensibility y y y


Online index build y N y

Password management y y y
PLISQL stored procedures, triggers y y y

PLISQL Server Pages y y y

Plan stability y N y
Reverse key indexes y y y
Temporary tables y y y

Distributed Database Features


Advanced replication y N y

Basic replication y y y

Distributed queries y y y

Distributed transactions y y y

Heterogeneous services y y y

Manageability
Automated standby database y N y

Readable standby database y N y

Database resource management y N y

Duplexed backup sets y N y

Oracle DBA Management Pack y y y

1048
Options and Features

Features Workstation Standard Enterprise


Manageability (Cont'd)
Fast-start fault recovery y N y

Incremental backup and recovery y N y

Legato Storage Manager y y y

Online backup and recovery y y y

Oracle Enterprise Manager y y y

Oracle Fail Safe for Oracle 8 i on NT y y y

Parallel backup and recovery y N y

Point-in-time tablespace recovery y N y

Recovery Manager y y y
Server managed backup and recovery y y y

Transparent Application Failover y N y


Networking
N-tier authentication/authorization y N y
Network access control y N y

Connection pooling y y y
Multi-protocol connectivity y N y
Multiplexing y N y

Oracle Connection Manager y N y


Oracle Names y y y

NetS y y y
W arehousing/VLDB
Analytic functions y y y

Automated parallel query degree y N y


Bitmap indexes y N y
CUBE and ROLLUP y y y
Descending indexes y y y
Direct Path Load API y y y
Table continued on following page

1049
Appendix E

Features Workstation Standard Enterprise


Warehousing/VLDB (Cont'd)
Export transportable tablespaces y N y

Import transportable tablespaces y y y

Function-based indexes y N y

Long operations monitor y y y

Materialized views y N y

Optimizer statistics management y y y

Parallel analyze y N y

Parallel bitmap star query optimization y N y

Parallel DML y N y

Parallel index build y N y

Parallel index scans y N y

Parallel load y y y

Parallel query y N y

Sample scan y N y
Star query optimization y y y

Oracle Si 8.1.5
Option Availability
Option Workstation Standard Enterprise
Oracle Advanced Security y N y

Oracle Change Management Pack y N y

Oracle Diagnostics Pack y N y

Oracle interMedia y y y

Oracle ]Server N y N
Oracle ]Server Enterprise Edition y N y

Oracle ]Server Enterprise Edition Accelerator y N y


{8.1.5 only)
Oracle Parallel Server y N y

1050
Options and Features

Option Workstation Standard Enterprise


Oracle Partitioning y N y
Oracle Programmer y y y
Oracle Spatial y N y
Oracle Standard Management Pack N y N
Oracle Time Series y N y
Oracle Tuning Pack y N y
Oracle Visual Information Retrieval y N y
Oracle W ebDB y y y

Feature Availability
Features Workstation Standard Enterprise
Application Development
AppWizard for Visual Studio (NT only) y y y
Autonomous Transactions y y y
COM cartridge (NT only) y y y
JDBC drivers y y y
Microsoft Transaction Server Integration (NT y y y
only)
Objects for OLE y y y
ODBC Driver y y y
Oracle Call Interface (OCI) y y y
Pro*C y y y

SQLJ y y y
Database Features
Advanced Queuing y N y
Database event triggers y y y
DBMS_REPAIR package y y y
Drop column y y y
Table continued on following page

1051
Appendix E

Features Workstation Standard Enterprise


Database Features (Cont'd)
Fine-grained access control y N y

Index coalesce y N y

Index-organized tables y y y

Indexes on NLS collating sequences y N y

Instead-of triggers y N y

LOB support y y y

Locally managed tablespaces y y y

LogMiner y y y

National language support (NLS) y y y

Objects and extensibility y y y

Online index build y N y

Password management y y y

PL!SQL stored procedures, triggers y y y

Plan stability y N y
Reverse key indexes y y y

Temporary tables y y y

Distributed Database Features


Advanced replication y N y

Basic replication y y y

Distributed queries y y y

Distributed transactions y y y

Heterogeneous services y y y

Manageability
Automated standby database y N y

Readable standby database y N y

Database Resource manager y N y

Duplexed backup sets y N y

Oracle DBA Management Pack y y y

1052
Options and Features

Features Workstation Standard Enterprise


Manageability (Cont'd)
Fast-start fault recovery y N y
Incremental backup and recovery y N y
Legato Storage Manager y y y
Online backup and recovery y y y

Oracle Enterprise Manager N y y

Oracle Fail Safe for Oracle 8i on NT y y y


Parallel Backup and Recovery y N y
Point-in-time tablespace recovery y N y
Recovery Manager y y y
Server-managed backup and recovery y y y
Transparent Application Failover y N y

Networking
N -tier authentication/ authorization y N y
Network access control y N y
Connection pooling y y y
Multi-protocol connectivity y N y
Multiplexing y N y

Oracle Connection Manager y N y


Oracle Names y y y

NetS y y y
Warehousing/VLDB
Analytic functions y y y
Automated parallel query degree y N y
Bitmapped indexes y N y
CUBE and ROLLUP y y y
Descending indexes y y y
Direct Path Load API y y y
Table continued on following page

1053
Appendix E

Features Workstation Standard Enterprise


Warehousing/VLDB (Cont'd)
Export transportable tablespaces y N y
Import transportable tablespaces y y y

Function-based indexes y N y

Long operations monitor y y y


Materialized views y N y
Optimizer statistics management y y y
Parallel analyze y N y
Parallel bitmap star query optimization y N y
Parallel DML y N y

Parallel index build y N y


Parallel index scans y N y
Parallel load y y y

Parallel query y N y
Sample scan y N y
Star query optimization y y y

Oracle 8 8.0.4
Option Availability
Option Standard Enterprise
Objects Option N y

Partitioning Option N y

Advanced Networking Option N y


Enterprise Manager Performance Pack N y

Parallel Server Option N y

1054
Options and Features

Feature Availability
Option Standard Enterprise

Application Development
Oracle Call Interface (OCI) y y
Objects for OLE y y
ODBC driver y y
Pro*C/C++ y y

Database Features
Advanced Queuing N y
Reverse key indexes y y
Password management y y
Index-organized tables y y
PLISQL stored procedures, triggers y y
Instead-of triggers y y
External procedures y y
National language support (NLS) y y
LOB support y y
Data Cartridges
Context Cartridge y y
Video Cartridge y y
Image Cartridge N y
Visual Information Retrieval Cartridge N y
Time Series Cartridge N y
Spatial Data Cartridge N y
Distributed
Distributed queries y y
Distributed transactions (2-phase commit, XA) y y
Heterogeneous Services y y
Basic Replication y y
Advanced Replication N y
Table continued on following page

1055
Appendix E

Option Standard Enterprise


Networking
Oracle Names y y
Oracle Connection Manager N y
Connection Pooling y y
Connection Multiplexing y y

Multiprotocol Connectivity N y
Oracle Security Server y y
Object Features
Object references (REFs) y y
Object collections (Nested tables, VARRAYS) y y
Object views y y

Manageability
Enterprise Manager y y

Enterprise Manager Performance Pack N y

Server Managed Backup and Recovery y y


Recovery catalog for online backup y y
Online recovery y y
Incremental backup and recovery N y
Parallel backup and recovery N y

Legato Storage Manager y y


Point-in-time tablespace recovery N y

Fail Safe for Oracle 8 on NT y y

Warehousing/VLDB
Bitmapped indexes N y

Star Query optimization y y

Parallel Execution N y

Parallel Load N y
Parallel Query N y

1056
Options and Features

Option Standard Enterprise


Warehousing/VLDB {Cont'd)
Parallel DML N y

Parallel index scans N y

Parallel bitmap star joins N y

Parallel index build N y

Parallel analyze N y

V$ OPTION
The product installation media Oracle distributes includes all options available for that particular class
of database. You must be licensed in order to use the options.

If you are interested in knowing what options have been installed in your database, you can query the
dynamic view, V$0PTION, and you will find out the names of all the options available for your
database, and a Boolean value indicating whether it is installed or not:

SQL> •elect parameter, value


2 from v$option
3 order by param.ter
4 I
PARAMETER VALUE

Advanced replication TRUE


Application Role TRUE
Bit-mapped indexes TRUE

Spatial FALSE
Transparent Application Failover TRUE
Visual Information Retrieval TRUE

37 rows selected.

1057
Index

A Guide to the Index


The index covers the numbered Chapters, the Case Studies and the Appendices. It is arranged
alphabetically, word-by-word {that is, New York would be listed before Newark) with symbols
preceding the letter A. Hyphens have been ignored in the sorting {so block terminator comes before
block-based development) and acronyms have been preferred to their expansions as main entries.

Symbols A
- Introducing comments, 349 ABORT option, 179
commenting out lines of code, 403 ABS() function, 856
% (percent) character abstraction
%s token, PUTF() and PUTF_NCHAR() procedures, 916 advantages of procedures and functions, 412
substituting for, using the PARSE_IT() function, 802 ACCEPT command, SQL*Pius, 324, 382
wildcard access drivers
Finding People Case Study, 829 external tables, 217
& (ampersimd) character access parameters, 216
denotes a SQL *Plus variable, 316 ACID transaction properties, 475
SQL *Plus replacement character, 400 Ada language
(+)outer join convention, 85 PL/SQL based loosely on, 19, 345
1 (forward slash) character source of pragmas, 399
ending a stored procedure, 413 ADD_MONTHS() function, 881
SQL *Plus execution command, 339, 348 ADD_POLICY() procedure
:=assignment operator, PL/SQL, 351 DBMS_RLS package, 526, 527
?: operator UPDATE_CHECK argument, 529
Boolean test in C and Java, 437 adding records
0 command INSERT statements, 70
SQL *Plus START command and, 314 ADDRESS object type
starting scripts, 340 creating an object table from, 654
00 command administrative user accounts see SYS; SYSTEM.
calling scripts in relative directories, 341 Advanced Queuing
SQL *Plus START command and, 314 ORDER_STATUS_TABLE created by, 136
\ (backslash) character QS sample schema uses, 127
substituting for, using the PARSE_IT() function, 802 sample schema as tutorial on, 137
\n (new line characters) SYSTEM user account owns, 14
substituting, in PARSE_IT() function, 803 AFTER triggers, 591
token, PUTF() and PUTF_NCHAR() procedures, 916 AFTER STARTUP triggers
\t (tab characters) system event triggers, 605
substituting, in PARSE_IT() function, 803 AIUD_EMPLOYEES_COPY trigger, 596
_ (underscore) character aggregate data
sorts last in index, 268 aggregation functions
wildcard character, 48 listed with syntax and examples, 888
II (pipe characters) ODCIAggregate*() functions, 675
concatenation operator, 348 user-defined aggregate functions, 672
=> (arrow Indicator) using GROUP BY clauses, 54
linking parameters and expressions, 420 using HAVING clauses, 56
AIUD_EMPLOYEES_COPY trigger, 596
AL16UTF16 datatype

AL16UTF16 datatype, 93 analytic functions, 686


aliasing alternative to inline views, 564, 565
columns first and last values, 697
table joins and, 60 joining tables is allowed, 688
using SELECT or COLUMN, 320 partitioning on the results of a function, 697
directory objects and, 214 queries can contain any number, 689
in line views, 563 ranking and top N values, 694
joins SQL Reference documentation lists, 698
self joins, 66 web application example, 692
tables and, 59 ANALYZE INDEX statement
tables validate structure clause, 264, 265, 270
accessing object type attributes, 626, 652 ANALYZE TABLE statement, 198
example of managing subtypes, 644
COMPUTE STATISTICS clause, 261, 281
joins and, 59
REF() function and, 656 indexed testing examples, 257
ALL PRIVILEGES shortcut
investigating optimizer query methods, 221
AND binary operator, 49
granting object privileges, 510
ALL_ prefix anonymous blocks
data dictionary views, 122 DEBUG called from, determining the owner, 800
ALL_ARGUMENTS view ANSI (American National Standards Institute)
column definitions and usage, 1009 data types, 104
ALL_IND_COLUMNS view, 144 standards body for SQL, 42
table joins in Oracle 9i, 61
ALL_INDEXES view, 144
transaction isolation levels defined, 482
ALL_JOBS view, 183
Apache web server
ALL_OBJECTS view, 37
MOD_PLSQL application, 19
ALL_ROWS setting
APPEND command
OPTIMIZER_MODE, 196
SQL *Plus built-in editor, 338
ALL_TAB_PRIVS view, 509
APPEND option
ALL_TABLES view, 121, 122
SAVE command, SQL *Plus, 337
alphabetization see ORDER BY clause. APPEND() procedure
ALTER object privilege, 507 DBMS_LOB package, 938
ALTER SESSION statement, 163 application contexts, 530
bigdate.sql script, 7 45 CAN_VIEW context, 532
enabling SQL-TRACE, 727 FGAC and, 535
function-based indexes, 295 investigating with SYS_CONTEXT() function, 531
local timezones settings, 102 setting values, 532
overriding OPTIMIZER_MODE parameters, 196 Application Developer's Guide - Large Objects, 935
query rewrites, 575 applications
SET EVENTS option, 727
storing within the database, 463
TIMED_STATISTICS parameter, 726
architecture, 153
ALTER SYSTEM CHECKPOINT statement, 182
importance of understanding, 17, 154
ALTER SYSTEM statement, 163 overview and diagram, 184
server parameter files and, 164 Archlver (ARCn), 182
TIMED_STATISTICS parameter, 726
ARGV type
ALTER TABLE statement, 237
DEBUG package, 794
adding constraints, 109
arrays
check constraints, 116
unique constraints, 115 emulation by PL/SQL tables, 361
attributes, 231 arrow Indicator ( =>)
defining a foreign key, 114 linking parameters and expressions, 420
setting a primary key, 112, 212 AS keyword
UPGRADE INCLUDING DATA option, 630 column aliases, 60
ALTER TABLESPACE statement AS SELECT clause
coalescing extents using, 179 CREATE TABLE statement, 117, 226, 235
ALTER TRIGGER statement, 607 ASSEMBLY_LINE example role, 513, 515, 517
ALTER TYPE command password protection, 518
INVALIDATE and CASCADE options, 628 assigning values
ALTER USER statement PL/SQL assignment operator, 351
changing multiple settings, 88 PL/SQL tables, 362
locking and unlocking user accounts, 86 PL/SQL variables and constants, 351
modifying tablespace settings, 87 DEFAULT keyword, 351
resetting passwords, 86 AT command
ampersand(&) character job scheduling on Windows, 844
atomicity, 475
denotes a SQL *Plus variable, 316
SQL *Plus replacement character, 400 achieving using savepoints, 469
essential nature of transactions, 466

1060
block-based development, PL/SQL

attributes best practice


CREATE TABLE and ALTER TABLE statements, 231 performance optimization, 708
displaying for PM sample schema, 134 scripting, 339
object types, 623 BETWEEN operator, WHERE clause, 48
accessing, 626, 627 BFILE (Binary Flies), 95
adding invalidates the constructor, 628 BIFER_All_UPPER_DATA trigger, 608
defaulting with the constructor, 636 BIFER_FOO_ID_PK trigger, 594
migration sets to NULL in dependent objects, 632
blgdate.sql script, 745
AUID_EMPLOYEES_COPY trigger, 599
binary data types
logging the statements which caused firing, 613
RAW data type, 94, 924
authentication
binary operators
see also passwords.
WHERE clause, 49
not a prerequisite for FGAC, 525
binary values
user name and password, 500
hexadecimal conversion, 537, 538
AUTHID clause
BINARY_INTEGER data type, 357
SHOW_OBJECTS example procedure, 525
generating in table function example, 678
AUTHID directive
bind variables, 329
stored procedures, 430
CURRENT_USER,432 capturing with SET EVENTS level 4, 727
auto population detecting scope for, 713
materialized views, 573 effect on query perfomance, 711
autolncrementlng primary keys
execute counts from TKPROF tool, 733
importance of using throughout, 712
monotonically increasing sequence numbers, 291
optimistic locking example, 491
automatic undo manangement, 167
perfomance optimization and, 710
autonomous transactions making queries generic and reusable, 710
AUTONOMOUS_TRANSACTION directive PRAGMA EXCEPTION_INIT, 400
logging with, 433 BIND_ARRAY() procedure
debug messages and, 788
DBMS_SQL package, 955
triggers and, 609
BIND_VARIABLE() procedure
AUTOTRACE tool, 718
DBMS_SQL package, 953
comparing optimizers, 197
BIT_AND() function
index testing examples, 257, 259
UTL_RAW package, 931
interpretation of statistics, 721
BIT_COMPLEMENT() function
investigating optimizer query methods, 221
materialized view example, 570 UTL_RAW package, 933
BIT_NOR() function
ways of enabling in SQL *Plus, 724
AVG() function, 888 UTL_RAW package, 932
BIT_OR() function
UTL_RAW package, 932

B bitmap Indexes, 300


bimap join indexes, 304
can't use RBO optimization with, 196
background processes, 178 BIU_FER_DEBUGTAB trigger, 790, 807
Archiver, 182 BIUD_EMPLOYEES_COPY trigger, 585
Checkpoint, 182 modifying to initialize a variable, 595
Database Writer, 180 BIUD_FOO trigger, 584 ·
Job Queue Coordinator, 183 BIUDFER_EMPLOYEES_COPY trigger, 596
Log Writer, 181 BIUFER_EMPLOYEES_DEPARTMENT_ID trigger, 580
Process Monitor, 178
BLOB (Binary large Objects), 95
Recoverer, 183
ORDSOURCE data types, 134
System Monitor, 179
block buffer cache, SGA, 175
backslash (\) character
role in DML statement execution, 204
substituting for, using the PARSE_IT() function, 802
block headers, data blocks, 169
backup and restore operations
block reads
stored in large pool, 177
access to an indexed table, 256
BADFILE clause
current and consistent mode
CREATE TABLE statement, 217
AUTOTRACE tool statistic, 721
BEFORE SHUTDOWN triggers
block size
system event triggers, 605
multi-block reads and, 258
BEFORE statement triggers, 595
block splits
HR (Human Resources) sample schema, 611
cannot occur with monotonically increasing sequence
BEGIN keyword, Pl/SQL, 26
numbers, 292
stored procedure declarations precede, 413 introduced, 263
benchmarking, 709
block terminator, SQL*Pius, 348
in isolation and to scale, 709
block-based development, Pl/SQL, 346
optimization best practice, 708
nested blocks, 349

1061
blocking

blocking, 487 carriage returns


capturing wait information, 738 formatting SQL statements, 47
distinct from deadlocks, 486 Cartesian products, 58
body see package body; type body. CASCADE CONSTRAINTS parameter
Boolean AND operations DROP TABLE statement, 247
bitmap indexes, 302 cascade deletes for referential Integrity
BOOLEAN data type, PL/SQL, 358 SQL-92 Intermediate level compliance and, 43
ITE example, 438 CASCADE option
Boolean OR peratlons ALTER TYPE command, 630
bitmap indexes, 303 FORCE option, 632
BOTH option DROP USER statement, 88-89, 827
ALTER SYSTEM statement, 165 cascading triggers, 587
branch nodes case sensitivity
block splits, 263 circumventing with UPPER() function, 294
B-Tree indexes, 256 column aliases, 60
role in skip scanning, 280 directories listed for UTL_FILE_DIR parameter, 910
BREAK ON * SKIP1 statement, 689 PL/SQL is case insensitive, 346
BROKEN() procedure case structures
DBMS_JOB package, 923 alternative to IF ... THEN ... ELSE, 388
B-Tree indexes, 256 Oracle 9i feature, 446
bitmap indexes and, 301 SQL-92 Intermediate level compliance and, 43
concatenated indexes, 275 Case Studies
index-organized tables example, 220 see Debugging PL/SQL; Finding people.
key compression, 277 case.sql file, 389
buffer busy waits CASE_NOT_FOUND
contention, reverse key indexes and, 293 ELSE clause, CASE statement, 389
buffer cache, 175 CAST() function, 878
Database Writer operation and, 180 see a/so TREAT() function.
scanned data blocks aged out quickly, 237 SQL-92 Intermediate level compliance and, 43
build Immediate option CAST_FROM_BINARY_INTEGER() function
CREATE MATERIALIZED VIEW statement, 573 UTL_RAW package, 933
BUILD_IT() function CAST_FROM_NUMBER() function
DEBUG package, 800 UTL_RAW package, 933
bulk fetches, 733 CAST_TO_BINARY_INTEGER() function
business logic UTL_RAW package, 934
encrypting with the wrap utililty, 463 CA5T_TO_NUMBER() function
business rules UTL_RAW package, 933
enforcing with triggers, 583 CAST_TO_NVARCHAR2() functions
HR sample schema, 128 UTL_RAWpackage, 925
byte keyword CAST_TO_RAW() function
CREATE TABLE statement, 93 UTL_RAW package, 925
bytes sent and received CAST_TO_VARCHAR2() function, 538
AUTOTRACE tool statistic, 722 UTL_RAW package, 925
BYTES value casting
CBO query plans, 199 parameter values, people_detail.sql script, 850
CBO (Cost Based Optimizer), 195
choices in million_row_table example, 203
c factors leading to the use of, 196
query plan listing when using, 717
use recommended, 196
C language
CEIL() function, 857
?: Boolean test operator in, 437
centralized net services management, 158
triggers can be written in, 579
CHANGE command
CACHE clause
SQL *Plus built-in editor, 338
ALTER TABLE statement, 246
CHANGE() procedure
CREATE TABLE statement, 237
DBMS_JOB package, 922
caching data
CHAR data type, 91
using object views, 568
char keyword
call stacks
use by DEBUG package, 797 CREATE TABLE statement, 93
character data types, 91
CAN_VIEW application context, 532, 534
ANSI equivalents tabulated, 105
CARD value
character-based TO_CHAR() function, 879
CBO query plans, 199
multibyte character sets, 93
cardinality
NVARCHAR2,93
columns, index test example, 284
PL/SQL, with SQL equivalents, 357
low cardinality columns
VARCHAR2, 92
favor bitmap indexes, 301, 303
favor index compression, 287

1062
company_phone_book view

character functions column headings


listed with syntax and examples, 870 changing with column aliases, 61, 320
character strings repeating, in query output from SQL *Plus, 34
converting to dates and numbers, 887 repeating, in SQL *Plus query output, 33
script to remove, 713 COLUMN NAME option
variable length CREATE TABLE statement, 106
SQL-92 Intermediate level compliance and, 43 column widths
characters LONG column setting governs display, 41
permitted in valid Oracle dentifiers, 83 moditying to accommodate headings, 321
CHARTOROWID() function, 879 specifYing for SQL *Plus output, 35
CHECK clause COLUMN_VALUE
sub-queries in default column name of DBMS_OUTPUT, 679
SQL-92 Full compliance and, 43 COLUMN_VALUE() procedure
check constraints, 116 DBMS_SQL package, 959
Checkpoint (CKPT) process, 182 columns
checkpoints altering, in existing tables, 238
Database Writer operation and, 180 built-in, 494
log switches and, 181 cardinality, index test example, 284
child tables characteristics of, 44
foreign key constraints, 113 column order in compressed indexes, 283
indexing and performance issues, 290 column order in concatenated indexes, 280, 286
index compression recommended, 290 reversing, 282
CHOOSE setting dropping and marking as unused, 240
OPTIMIZER_MODE, 194, 196 formatting numeric columns, 321
CHR() function, 870 LEVEL pseudo-column, 667
CJQ (Job Queue Coordinator), 183 low cardinality key columns favor compression, 287
see also jobs. low cardinality, bitmap indexes and, 301
CKPT (Checkpoint) process, 182 naming with dot notation for table joins, 59
clauses, SELECT statements, 46 object types as, 624
CLEAR option trigger to log column changes, 595
SQL *Plus COLUMN command, 322 updatable columns in views, 558
CLEAR() procedure columns objects, 624
DEBUG package, 793, 808, 814 comma delimited lists see CSV flies_
client tools command line operations
configuring, 157 see also SQL*Pius.
client triggers see user event triggers- Finding People Case Study
client-side caches calling the people_detail.sql script, 852
using object views, 568 user interface, 846
CLOB (Character Large Objects), 95 TKPROF tool, 728
comments
invalidating views example, 556
CLOSE() procedure documenting the table structure
Finding People Case Study, 832
DBMS_LOB package, 938
effects on query reusability and performance, 710
CLOSE_CURSOR() procedure
introduced with --, 349
DBMS_SQL package, 965 commenting out lines of code, 403
clustered tables, 230 comments.sql script, 148, 149
COALESCE() function, 890 DBA_COL_COMMENTS view, 986
collection methods, PL/SQL, 366 commit operations, 467
COUNT collection method, 364, 372 distinct from write operations, 180
EXTEND collection method, 372 fast and grouped commits, 181
collections, PL/SQL, 358 flat response times of, 467
choosing between, 372 Log Writer and, 181
distinguished from object types, 621 two-phase commit, 184
nested tables, 370 COMMIT statements
object collections, 368 introduced, 75
table functions return, 677 issued before and after DOL execution, 82, 207, 230
tables, PL/SQL, 361 communication processes
colltypes.sql script architecture diagram, 184
DBA_COLL_TYPES view, 994 company employees example
colprlvs-sql script subtypes of NOT INSTANTIABLE types, 648
DBA_COL_PRIVS view, 985 company_phone_book view
column aliases, 60 creating a trigger on, 600
COLUMN command, SQL*Pius, 34 object views derived from, 567
column headings, 319 relational view example, 545
column widths, 36 updatable columns, 558
further options, 322 virtual columns, 546
column constraints
may be rejected where existing data violates, 240
NOT NULL constraints, 239

1063
COMPARE() function

COMPARE() function connecting to a database instance, 154


DBMS_LOB package, 938 centralized net services management, 158
UTL_RAW package, 930 dedicated server and shared server modes, 161
comparison operators, 48 localized net services management, 158
compbody.sql script, 752 using the SQL *Plus tool, 27
compilation errors across a network, 28
PL/SQL and database objects with SQL *Plus, 327 remote database services, 29
complle_schema.sql script, 758 connection descriptors
composite foreign keys, 114 tnsnames.ora file, 157
composite unique keys, 115 connection management
composition SQL-92 Full compliance and, 43
simulates object inheritance, 627 consistency, 477
compound queries, 88 see also locking.
compproc.sql, 754 advantage of using NOT INSTANTIABLE types, 647
compression points to remember, 482
statement level consistency, 477
B-Tree indexes, 277, 286
favored by low cardinality key columns, 287 transaction level consistency, 478
COMPRESS attribute consistent gets
CREATE TABLE statement, 223 AUTOTRACE tool statistic, 721
compressed index example, 282 execution plan statistics, 571, 573
index storage and, 223 consistent reads
recommended on child table indexes, 290 CBO and RBO execution plans compared, 724
comptrlg.sql script, 755 TKPROF tool execution report, 732
COMPUTE STATISTICS clause constants
ANALYZE TABLE statement, 257, 261, 281 defined in PL/SQL declaration section, 346, 349
compvlew.sql script, 755 initializing using the CONSTANT keyword, 350
CONCAT() function testing against the DUAL table, 855
UTL_RAW package, 924 constraints
concatenated Indexes, 275 adding with the ALTER TABLE statement, 109
importance of field order, 276 automatic index creation, 287
index-only scans, 300 check constraints, 116
leading columns should match usual query DEBUGTAB table, 790
declarative integrity, 108
predicates, 280, 285, 286
Oracle 8i example, 281 defining with the CREATE TABLE statement, 107, 109
reversing column order, 282, 286 foreign key, 113
skip scanning increases usability, 280 HR sample schema. 128
concatenating fields primary key, 109
self-referential constraints, 115
Finding People Case Study, 829
unique constraints, 115
concatenation operator
using in views, 550
concatenating personal names, 382
security example, 551
creating virtual columns in views, 546
construc;tor methods
double pipe character as, 348
object types, adding attributes invalidates, 628
concurrency control, 484
object types, are system defined, 624
factor distinguishing DBMSs from file systems, 465 object types, attribute defaults, 636
multi-versioning and read consistency, 492
one of three method types, 633
conditional expressions, 385 CONSULTANT object type
see also WHERE clause. company employees example, 650
IF... THEN ... ELSE statements, 386 consumer groups
NULL values and, 51
resource manager assignments, 167
precedence, 50
contention
conditional predicates, triggers, 588
indexes on monotonically increasing sequence
BIUD_EMPLOYEES_COPY trigger, 598
numbers, 292
PL/SQL can't reference, 588
control flies
trigger to log table modifications
createctl.sql script, 767, 769
capturing the statement type, 589, 590
Oracle Managed Files covers, 172
conference call example
role in database startup, 165
timestamps with local timezones, 102
control statements, 385
timestamps with timezones, 100
looping structures, PL/SQL, 375, 390
CONNECT BY clause
when to use each type, 393
see also hierarchical queries.
conversion functions
SELECT statements, 665
LEVEL best specificed in, 668 listed with syntax and examples, 878
CONNECT role, 505, 518 CONVERT() function
connect.sql script, 745 UTL_RAW package, 931
cookies
application contexts and, 530, 535

1064
CURSOR ALREADY_OPEN exception

COPIES() function complex syntax, 106


UTL_RAW package, 929 compression, 223
COPY command, SQL*Pius CREATE GLOBAL TEMPORARY TABLE statement, 227
Finding People Case Study, 833, 845 CREATE INDEX clause, 290
COPY() procedure creating an object table, 654
DBMS_LOB package, 939 creating constraints, 109
correlation names external tables, 216
see also aliasing, tables. Finding People Case Study, 830
inline views, 563 granting system privileges, 504
INSTEAD OF trigger example, 604 new user example, 505
row triggers, 592 storage clause parameters, 168
cost of rollbacks, 468 TABLESPACE clause, 214
cost of using Indexes, 261, 275 CREATE TABLESPACE statement
compressed indexes, 286 REUSE option, 172
COST values CREATE TRIGGER statement
CBO query plans, 199 INSTEAD OF trigger example, 600
COUNT collection method, 364, 365-366, 372 syntax errors, 584
COUNT() function, 889 CREATE TYPE statement
CPU time object views example, 566
disparity with elapsed time, TKPROF tool, 733, 738 user privileges
crash recovery
INSTEAD OF trigger example, 601
CREATE USER statement, 84, 501
role of SMON, 179
CREATE ANY DIRECTORY privilege, 214 access to procedures example, 415
options, 85
CREATE BITMAP INDEX statement, 301
CREATE VIEW statement
bimap join indexes, 304
complex views
CREATE COMMENT statement, 148
INSTEAD OF trigger example, 602
CREATE INDEX clause
FORCE option, 557
CREATE TABLE statement, 290 WITH CHECK OPTION constraint, 560
CREATE INDEX statement WITH OBJECT OlD clause, 567
concatenated indexes, 275 create_tab_syns.sql file, 684
CREATE BITMAP INDEX, 301 createctl.sql script, 767
examples, 257 example, 769
function-based indexes, 294 possible use with flat.sql script, 767
introduced, 255
CREATETEMPORARY() procedure
key compression, 277
DBMS_LOB package, 940
PCTFREE attribute, 263
credentials see authentication.
reverse key indexes, 293
CSV (Comma-separated Value) flies
CREATE MATERIALIZED VIEW statement, 572
using as an external table, 214
build immediate option, 573
using the flat.sql script, 746
enable query rewrite option, 575
currency values
refresh on commit option, 573
CREATE option
formatting, 34
current reads
SAVE command, SQL *Plus, 337
TKPROF tool execution report, 732
CREATE OR REPLACE FUNCTION statement, 296, 436
CURRENT_DATE() function, 862
CREATE OR REPLACE PACKAGE BODY statement, 444
LOG_MESSAGE private procedure, 446
CREATE OR REPLACE PROCEDURE statement, 413
Jogging with autonomous transactions, 435
CREATE OR REPLACE TRIGGER statement, 587
CURRENT_SCHEMA
CREATE OR REPLACE TYPE statement, 622
distinguished from SESSION_USER for stored
creating subtypes, 639
procedures, 430
including a member method, 633
CURRENT_TIMESTAMP column, 494
user-defined aggregate functions example, 67 4
CURRENT_TIMESTAMP() function, 862
CREATE OR REPLACE VIEW statement, 544
CURRENT_USER AUTHID
preserves access privileges, 549
compile_schema.sql script, 757
CREATE PROCEDURE statement, 522
stored procedures, 432
application contexts and, 530
CURSOR FOR LOOP
CREATE ROLE statement, 512
creating a PL/SQL table, 367
CREATE SESSION statement
DEBUG package, 805
granting system privileges, 84, 503
implicit cursor, 376
CREATE SYNONYM statement, 684
nested tables example, 371
CREATE TABLE AS SELECT statement, 117, 226 cursor variables, 380
can use NOLOGGING clause, 235 CURSOR_ALREADY_OPEN exception, 396
CREATE TABLE statement
attributes, 231

1065
cursors
cursors, 3 73 characteristics of column data types, 44
cursor attributes, 376 date and time information
dynamic or REF cursors, 380 datetimes, 95
implicit and explicit cursors compared, 373 intervals, 103
example, 377 SQL-92 Intermediate level compliance and, 43
implicit preferred, 379 large object data types, 94, 95
implicit cursors, 375 length semantics, 93
input to pipelined functions, 681 numeric data types, 90
loading data from an external table, 684 PL/SQL, with SQL equivalents, 357
opening doesn't copy data, 493 PLS_INTEGER, BINARY_INTEGER and NUMBER, 357
passing parameters to, 373 PL/SQL specific and package types
CUST_ADDRESS_TYP object type, 132 not allowed for object type attributes, 623
custom error handling see user-defined exceptions. PL/SQL, BOOLEAN, 358
customer data PL/SQL, with SQL equivalents, 356
OE sample schema stores, 130 PLS_INTEGER, 357
REF data types, 655
returned by pipelined function, 680

D type conversion errors with external tables, 217


user-defined, object types as, 621
views, displaying for, 145
dangling REFs, 657 VIRTUAL_TABLE_TYPE, 678
data blocks, 169 data warehousing
data dictionary, 118, 971 bimap join indexes, 305
see also views. bitmap indexes ideal for, 303
DUAL table, 855 new sample schemas to illustrate, 126
introduced, 15 SH sample schema illustrates, 137
managed space allocation before Oracle 8i, 235 using materialized views with, 569
modification using recursive SQL, 207 database buffer cache, 175
naming conventions for views, 122 database connections
PL/SQL access as invoking user preferred, 524 see also connecting to a database Instance.
procedures may be queried using, 459 not needed with PL/SQL, 345
retrieving view definitions, 54 7 database Instances see connecting to a database
scope of views, 120 Instance.
stored in shared pool cache, 177 database object decrlptlons see object desrlptlons.
SYS user account owns, 14 database objects
triggers information from, 610 assessing impact of changes with compbody.sql, 754
using queries to write SQL with SQL, 685 assessing impact of changes with invalid.sql
data flies script, 766
logical and physical storage, 165 compilation errors when writing with SQL *Plus, 327
data integrity Finding People Case Study, 829
see also locking; reliability. listing with dbls.sql, 769
enforcing using row triggers, 595 naming conventions, 82
read only views and, 555 reporting on with dblsl.sql script, 771
restricting access to stored procedures and, 432 segments as stored representations of, 166
data security, 535 Database Performance Guide and Reference,
data segments, 166 Oracle 91, 197
overflow segments, 225 database roles see roles.
SMON will clean up temporary segments, 179 database servers
Data Structure Diagrams trace files generated on, 730
HR sample schema, 128 database terminology, 12
OE sample schema, 130 Database Writer (DBWn), 180
SCOTT sample schema, 125 role in system crash example, 204
SH sample schema, 137 using multiple writers, 181
data types, 90 databases
%TYPE and %ROWTYPE, 355 Oracle database Editions, 19, 1041
allowed for object type attributes, 623 startup and shutdown as triggering statements, 581
ANSI data types, 104 dataflle
tabulated with Oracle equivalents, 104
problem when creating a temporary tables pace
binary data types
with, 171
RAW data type, 94
DATATYPE option
BINARY_INTEGER, 357
BIT string CREATE TABLE statement, 106
SQL-92 Full compliance and, 43 data types see data types.
character data types, 91 date and time Information
NCHAR, 92 datetimes and intervals, 95
NVARCHAR2,93 DATE data type, 96
PL/SQL, with SQL equivalents, 357
VARCHAR2, 92

1066
DBMS_JOB package

datetlme data types DBA_OBJECTS view


DATE data type, 96 column definitions and usage, 975
date formatting options, 887 compile_schema.sql script, 759
datetime-based TO_CHAR() function, 881 dbls.sql script, 976
date formatting options, 887 indexed testing examples, 257
default date formats, 97 DBA_PROCEDURES view
TIMESTAMP data type, 98 column definitions and usage, 1009
TIMESTAMP WITH LOCAL TIMEZONE data type, 101 DBA_ROLE_PRIVS view
TIMESTAMP WITH TIMEZONE data type, 99 column definitions and usage, 1018
using Julian day to spell out numbers, 702 DBA_ROLES view
DATETIME functions column definitions and usage, 1017
listed with syntax and examples, 861 DBA_SOURCE view
db block gets column definitions and usage, 1008
AUTOTRACE tool statistic, 721 getcode.sql script, 1008
CBO and RBO execution plans compared, 724 DBA_SYS_PRIVS view, 502
db_block_slze parameter, 176 column definitions and usage, 1019
db_cache_slze parameter, 176 DBA_TAB_COLUMNS view
DB_CREATE_FILE_DEST parameter, 172 column definitions and usage, 981
DB_CREATE_ONLINE_LOG_DEST parameter, 173 desc.sql script, 983
DBA (Database Administrator) role DBA_TAB_COMMENTS view
create synonym technique, 685 column definitions and usage, 986
SYS and SYSTEM accounts, 14 comments.sql script, 986
system privileges, 84 DBA_TAB_PRIVS view, 509
DBA_ prefix column definitions and usage, 983
data dictionary views, 122 tabprivs.sql script, 983
DBA_COL_COMMENTS view DBA_TABLES view
column definitions and usage, 986 column definitions and usage, 978
comments.sql script, 986 hidden columns, 294
DBA_COL_PRIVS view tableinfo.sql script, 980
colprivs.sql script, 985 DBA_TABLESPACES view, 87
column definitions and usage, 984 print_table.sql script, 750
DBA_COLL_TYPES view DBA_TEMP_FILES view, 774
colltypes.sql script, 994 DBA_TRIGGER_COLS view
column definitions and usage, 994 column definitions and usage, 1006
DBA_CONS_COLUMNS view DBA_TRIGGERS view
column definitions and usage, 989 column definitions and usage, 1005
DBA_CONSTRAINTS view DBA_TYPE_ATTRS view
column definitions and usage, 988 column definitions and usage, 998
DBA_DATA_FILES view, 774 DBA_TYPE_METHODS view
DBA_DEPENDENCIES view column definitions and usage, 999
column definitions and usage, 1011 DBA_TYPES view
DBA_DIRECTORIES view column definitions and usage, 996
column definitions and usage, 1020 DBA_UPDATABLE_COLUMNS view
DBA_ERRORS view column definitions and usage, 1004
column definitions and usage, 1012 viewrep.sql script, 1004
DBA_EXTERNAL_LOCATIONS view DBA_USERS view
column definitions and usage, 992 column definitions and usage, 1020
exttabs.sql script, 992 Needed for SQL*Pius PROMPT example, 324
DBA_EXTERNAL_TABLES view users.sql script, 1021
column definitions and usage, 991 DBA_VIEWS view
DBA_IND_COLUMNS view column definitions and usage, 1003
column definitions and usage, 1015 getaview.sql script, 1003
indexes.sql script, 1016 DBCA (Database Configuration Assistant)
DBA_INDEXES view installing the Oracle 9i sample schemas, 1026
column definitions and usage, 1013 dbls.sql script, 139, 769
DBA_JOBS view, 183 DBA_OBJECTS view, 976
column definitions and usage, 995 dblsl.sql script, 771
DBA_LOBS view DBMS (Database Management Systems)
column definitions and usage, 1001 factors distinguishing from file systems, 465
DBA_METHOD_PARAMS view Oracle differences from other, 16
column definitions and usage, 1000 DBMS_APPLICATION package
DBA_METHOD_RESULTS view SET_CLIENT_INFO and debugging, 788
column definitions and usage, 1000 DBMS_APPLICATION_INFO package, 778
DBA_OBJECT_TABLES view DBMS_AQ and DBMS_AQADM packages
column definitions and usage, 993 QS sample schema installation, 1034
objtab.sql script, 994 DBMS_JOB package, 17
managing external table refreshes, 220
procedures and functions, 917

1067
DBMS_LOB package

DBMS_LOB package, 95 DEBUG package


procedures and functions, 934 four main procedures, 791
DBMS_LOCK.SLEEP private debug procedures, 793
showsql.sql script, 780 setting up using INIT{), 811
DBMS_METADATA package situations where it might be useful, 817
alternatives for non-Oracle 9/ users, 761 troubleshooting, 817
extracting DDL to the file system, 759 use in a production environment, 818, 820
DBMS_MVIEW package DEBUG tool, requirements
SH sample schema installation, 1037 debugging PL/SQL case study, 788
DBMS_OBFUSCATION_TOOLKIT package, 535 DEBUG_IT() procedure
message digests, 539 DEBUG package, 795
DBMS_OUTPUT package debugging
calling a stored procedure, 414 see also tracing.
debugging tool, limitations of, 787 case study: debugging PL/SQL, 787
default column name is COLUMN_VALUE, 679 generating messages, 812
illustrating use of SQL *Plus DESCRIBE limitations of DBMS_ OUTPUT, 787
command, 323 options for real-time debugging, 788
list of procedures, 902 use of the SQL *Plus tool, 15
private stored procedure example, 44 7 value of instrumented code, 709
PUT_LINE{) procedure, 903 Debugging PL/SQL Case Study, 787
PUT_LINE in DEBUG package case study, 809, 810 creation of the UTILITY user, 789
PUT_LINE in Finding People Case Study, 847 finishing touches, 810
PUT_LINE in overloaded swap routine, 454 selective debugging, 815
PUT_LINE in PL/SQL examples, 347, 348 DEBUGTAB table
PUT_LINE in strongly-typed REF CURSOR debugging PL/SQL case study, 790
examples, 381 decision support systems
PUl'_LINE in table function example, 679 SH sample schema demonstrates, 137
spooling PL/SQL table output, 367 declaration section
DBMS_RANDOM package, 451 exceptions raised in, 406
procedures and functions of, 904 PL/SQL blocks, 346, 348, 349
DBMS_RLS package order of variable declaration, 353
see also FGAC. declarative Integrity
adding security policies, 526, 527, 529 referential integrity and, 108
DBMS_SPACE package, 780 DECLARE keyword, PL/SQL, 34 7
DBMS_SQL package absent from stored procedure syntax, 413
procedures and functions of, 948 DECODE() function, 891
DBMS_STATS package decryption see encryption.
comparing optimizers using, 199 dedicated server mode, 161
DBMS_SYSTEM package UGA stored on PGA, 178
enabling SQL-TRACE, 727 default date formats, 97
third-party applications, 728 changing with the bigdate.sqi script, 7 45
DBMS_TRACE package DEFAULT keyword
real-time debugging options, 788 PL/SQL variable/constant value assignment, 351
DBMS_UTILITY package default object attributes, 636
error logging using CASCADE/FORCE, 632 default passwords
FORMAT_CALL_STACK{) function, 797, 798 SYS and SYSTEM user accounts, 14
timing with the GET_TIME utility, 711 default roles
DBTIMEZONE() function, 101, 863 avoid password protection, 518
DBWn see database writer. default tablespaces, 166
dcllst.sql script changing with create synonym technique, 685
DICT_COLUMNS view, 974 modifying tablespace settings, 87
DDL (Data Deflnltlon Language), 81 option in CREATE USER statement, 85
COMMIT issued before and after execution, 82, 230 default values
COMMIT issued before execution, 207 defining with the CREATE TABLE statement, 106
CREATE TABLE statement for external tables, 216 parameters of stored procedures, 422
execution compared with DML, 190 parameter order and, 429
extracting to the file system, 759 supporting with triggers, 583
processing of DDL statements, 207 DEFAULT_DIRECTORY attribute
SQL category, 43, 189 CREATE TABLE statement, 216, 217
statements may include a query, 190 defensive programming, 709
system privileges constrain operation of DDL deferrable constraints
statements, 506 best to name explicitly when deferring, 4 74
triggering statements can be in, 581 enforced with non-unique indexes, 288
triggers may not contain DDL statements, 609 setting enforcement mode, 4 73
TRUNCATE TABLE statement, 249 SQL-92 Full compliance and, 43
dead entries see deleted entries. transaction level consistency and, 479
deadlocks, 485

1068
dlist.sql script

deferred operations script alternative to, 144


Database Writer and, 180 SET DESCRIBE DEPTH ALL command, 624
DEFINE _EDITOR command, SQL*Pius, 336 USER_TABLES view, 118
incorporating in the login.sql script, 7 44 DESCRIBE_COLUMNS() and DESCRIBE_COLUMNS2()
DEFINE_ARRAY() procedure procedures
DBMS_SQL package, 957 DBMS_SQL package, 964
DEFINE_COLUMN() procedure descvlew.sql file, 144
DBMS_SQL package, 956 design phase
definer's rights tuning should be done at design time, 707
PL/SQL procedures executed under, 521 ANSI-compliant SQL design tools, 104
stored procedures, 430 desktop version see Oracle Personal Edition.
DELETE command deterministic functions, 439
SQL *Plus built-in editor, 338 function-based indexes, 295
DELETE method, PL/SQL tables, 365 deterministic hint, 440
DELETE object privilege, 506 DICT_COLUMNS view
delete operations column definitions and usage, 97 4
PL/SQL tables, 364 dclist.sql script, 974
DELETE statements, 73 dictionary cache
DROP TABLE compared to, 247 SGA shared pool, 176
indexed tables, result in unused space in leaf dictionary managed temporary tablespaces, 171
nodes, 269 SMON clean up and poor performance, 179
deleted entries SMON extent coalescing, 179
removing from indexes, 269 dictionary managed tablespace, 235
removing from indexes on insert operations, 27 4 DICTIONARY view
deleted leaf rows column definitions and usage, 972
updating and deleting effects, 273 dlist.sql script, 973
DELETING conditional predicate dimension tables, 137
BIUD_EMPLOYEES_COPY trigger, 598 dlr command, operating system
statement triggers, 588 SQL *Plus HOST command example, 341
demobld.sql script directories
scon
installing the schema, 1026 erors calling scripts in other directories, 340
denormallzatlon directory objects
Finding People Case Study, 829, 830 aliasing a file system directory, 214
DENSE_RANK() function, 695 directory servers see OlD.
dependencies Directory Usage
invalid PL/SQL modules Net Configuration Assistant and, 29
manually recompiling with comp* scripts, 751 Dirty Lists, buffer cache, 175
object types, 628 dirty reads
dependent objects must be dropped first, 632 ANSI transaction isolation levels and, 482
INVALIDATE option and, 629 Oracle doesn't suffer from, 16
using CASCADE to validate, 630 DISABLE() procedures
Oracle 9i sample schemas, 1028, 1038
DBMS_OUTPUT package, 902
technological dependencies, 1038
disabling roles, 515
stored procedures, 455
disabling triggers, 607
deptemps.sql script, 330
de-referencing disk counts
DEREF(} function, 657 TKPROF tool, 733
LOC_REF values, 657 disk crashes
DES (Data Encryption Standard), 536 Archiver and, 182
disk storage
DES3ENCRYPT() and DES3DECRYPT()
procedures, 536
clustered tables, 230
inefficient use by indexed tables with many
desc.sql script, 141
inserts, 263
DBA_TAB_COLUMNS view, 983
dispatcher
DESCRIBE command, SQL*Pius, 315, 322
component of shared server mode, 161
bug affecting altered objects, 629, 631
display length
employee history table, 107
controlling in DEBUG package, 801
investigating database tables, 44
investigating object types, 623 distributed transactions
investigating packages, 461 use of Recoverer, 183
investigating stored procedures, 14 7 dllst.sql script
investigating system privileges, 502 DICTIONARY view, 973
investigating views, 546

1069
DML (Data Manipulation Language)

DML (Data Manipulation Language), 46 DUAL table, 855


activity on indexed tables causes problems, 275 bind variables example, 711
DELETE statements, 73 deadlock example, 485
DML locks not acquired on temporary tables, 227 finding local timezone, 100
execution compared with DDL, 190 query hash value comparison, 193-194
implicit cursors assigned, 375 row triggers, 593
INSERT statements, 70 SYS_CONTEXT{) function, 531-534
limiting with SET TRANSACTION READ ONLY, 470 use with MERGE statement, 703
most statements include a query, 189 using MY_ENCRYPT{), 537
non-query statements, 70 whitespace effects example, 710
object privileges constrain operation of DML DUMP() function, 892
statements, 506 DUP_VAL_ON_INDEX exception
performance with monotonically increasing sequence PL/SQL predefined exception, 396
numbers, 292 predefined exception, 396
processing of DML statements, 203 duplicate rows
security policies and DML operations, 526 INTERSECT statements and, 69
SELECT statements, 46 MINUS statement and, 69
SQL category, 43, 189 UNION ALL statements and, 68
statements not limited by serializable isolation UNION statements and, 67
level, 472 duplicating tables
statements performed in transactions, 466 CREATE TABLE AS SELECT statement, 117
statements, invalid object conversion on access, 630 durability, 483
triggering statements can be in, 581 dynamic cursors see REF cursors.
UPDATE statements, 71 dynamic Index creation, 275
using indexes slows DML operations, 261 dynamic Initialization parameters, 163
DN (Distinguished Names)
OPEN_CURSORS, 164
HR sample schema, LDAP use, 129
dynamic performance tables, 192
documentation
dynamic registration, 155
advantage of using scripts, 309
Dynamic SQL
Application Developer's Guide- Large Objects, 935
bind variable example, 710
creating a view, 544
DBMS_SQL package, 949
'Getting To Know' guides, 1041
EXECUTE IMMEDIATE statement, 400
Oracle 9i Data Cartridge Developer's Guide, 677
SQL-92 Intermediate level compliance and, 43
PL/SQL User's Guide and Reference, 396, 442
dynamic views
RDBMS README introduced in Oracle 9i, 1041
V$0PTION, 1057
self documenting schemas, 148
SQL Reference, 698
SQL *Plus commands, 319
Supplied PL/SQL Packages and Types E
Reference, 759, 901
domains EDIT command, SQL*Pius
SQL-92 Intermediate level compliance and, 43 SQL *Plus buffer and, 337
dot notation editors
accessing attributes of included objects, 627 defining with the login.sql script, 7 44
multi-column PL/SQL tables, 364 modifying commands from the SQL *Plus buffer, 336
naming columns for table joins, 59 EJB (Enterprise JavaBean) containers
double quotes shared server mode mandatory, 161
column aliases, 60 ELSE clause, CASE statement
naming database objects using, 83 PL/SQL default is CASE_NOT_FOUND, 389
print_table.sql script requires, 751 EMP_DETAILS_VIEW, 553
resetting NUMFORMAT to its default value, 41 Employee Handbook
DROP COLUMN clause Finding People Case Study, 823
ALTER TABLE statement, 240 employee history table
DROP STORAGE clause CREATE TABLE statements, 107
TRUNCATE TABLE statement, 249 EMPLOYEES table
DROP TABLE statement, 246 Finding People Case Study, 830
DROP TRIGGER statement, 588 HR sample schema, investigating, 143
DROP TYPE statement, 632 enable query rewrite option
DROP UNUSED COLUMNS clause CREATE MATERIALIZED VIEW statement, 575
ALTER TABLE statement, 243 ENABLE() procedures
DROP USER statement, 88 DBMS_OUTPUT package, 902
CASCADE option, 827 enabling roles, 515
DROP VIEW statement, 548, 549 encapsulation, 620
DS_SUM() function using REF cursors, 846
user-defined aggregate functions, 676

1070
exception codes

encryption ORA-04067: not executed, package body* does not


DBMS_OBFUSCATION_TOOLKIT package, 535 exist, 443
padding data for, 536 ORA-04068: existing state of packages has been
PL/SQL, using the wrap utility, 461 discarded, 443
END keyword, PL/SQL, 26, 347 ORA-04081: trigger * already exists, 587
enqueues ORA-04088: error during execution of trigger *, 610
TKPROF tool, 738 ORA-06502: PL/SQL: numeric or value error .. . , 352,
environment settings, SQL*Pius, 326 406,424
environment variables ORA-06503: PL/SQL: function returned without
value, 441
SQLPATH, 313, 742
ERASE() procedure ORA-06508: PL/SQL: could not find program unit
being called, 443
DBMS_LOB package, 940
ORA-06510: PL/SQL: unhandled user-defined
error handling, PL/SQL, 394
exception, 403
exception block, 34 7
ORA-06592: CASE not found while executing CASE
error messages
statement, 390
don 't distinguish syntax and semantic checking
ORA-24372 : invalid object for describe, 629
failures, 191
ORA-25954: missing primary key or unique constraint
ORA-00001: unique constraint * violated, 112, 116, on dimension, 305
396,478 ORA-28000: the account is locked, 86
ORA-00054: resource busy, 489, 490 ORA-28115: policy with check option violation, 530
ORA-00060: deadlock detected while waiting for ORA-30544: function based index name is
resource, 486 disabled, 295
ORA-00904: invalid column name, 400, 627, 644 PLS-00103: encountered the symbol "AS" when
ORA-00918: column ambiguously defined, 60
expecting one of the following ... , 442
ORA-00932: inconsistent data types, 673
PLS-00103: encountered the symbol "END" when
ORA-00936: missing expression, 191
expecting one of the following ... , 355, 585
ORA-00942: table or view does not exist, PLS-00201: identifier * must be declared,
191, 507, 558 416, 520, 534
AUTHID local declarations, 431, 433 visibility and scope issues, 353, 404
database role examples, 517, 518, 521
PLS-00221 : * is not a procedure or is undefined, 440
ORA-00955: name is already used by an existing
PLS-00302: component * must be declared, 450
object, 414, 548
PLS-00306: wrong number or types of argument in
ORA-00959 : tablespace * does not exist, 232
call to *, 424, 624
ORA-01031: insufficient privileges, 515, 533
PLS-00320: the declaration of the type of this
object privileges, 507, 508, 512
system privileges, 501, 504 expression is incomplete or malformed, 354
ORA-01039: insufficient privileges on underlying PLS-00322: declaration of a constant * must contain
objects of the view, 736 an initialization assignment, 351
ORA-01045: user * lacks CREATE SESSION PLS-00363 : expression * cannot be used as an
privileges ... , 503 assignment target, 351, 427, 428
ORA-01400: cannot insert NULL into *, 112 PLS-00382 : expression is of wrong type, 360
ORA-01402: view WITH CHECK OPTION where-clause PLS-00526: a MAP or ORDER function is
violation, 561 required ... , 637
ORA-01422: exact fetch returns more than requested PLS-00590: attempting to create a subtype UNDER a
number of rows, 408 FINAL type, 646
ORA-01437 : cannot have join with CONNECT BY, 671 PLS-00637 : FINAL method cannot be overridden or
ORA-01456: may not perform * operation inside a hidden, 646
read only transaction, 4 70 PLS-00713: attempting to instantiate a type that is
ORA-01555: snapshot-too-old, 166 NOT INSTANTIABLE, 648
ORA-01733: virtual column not allowed here, 559 SP2-0685: The date * is invalid or format, 326
ORA-01922: CASCADE must be specified to mismatched
drop *, 89 SP2-0738: restricted command "*" not
ORA-01927: cannot REVOKE privileges you did not available, 319
grant, 510 SQL *Plus, using SHOW ERRORS, 327
ORA-01950: no privileges on tables pace *, SQLCODE and SQLERRM variables, 407
88,232,504 escaping
ORA-02091: transaction rolled back, 474, 475, 480 percent characters, 803
ORA-02290: check constraint * violated , event attribute functions, 611
117,473,475 evolution
ORA-02291: integrity constraint* violated .. . , 114, type evolution, 628
480,481 Excel spreadsheets
ORA-02292: integrity constraint * violated ... , 480 exporting to, using the flat.sql script, 7 46
ORA-02303: cannot drop or replace a type with type using as an external table, 214
or table dependents, 632 exception block
ORA-02449: unique/primary keys ... referenced by PL/SQL blocks, 347
foreign keys, 248 exception codes
ORA-04043: object * does not exist, 507, 549 see a/so error messages.
ORA-04063: view* has errors, 557 associating user-defined exceptions with , 401
SQLCODE variable, 407

1071
exception handlers

exception handlers EXTEND() collection method, 372


FILE_IT() function, 806 extensibility
in functions, must return values, 441 advantages of procedures and functions, 411
PL/SQL error handling, 394 extents, 167
PL/SQL exception expressions, 395 extent coalescing, 179
propagation of exceptions, 401 locally managed tablespaces and, 168, 236
SQLCODE and SQLERRM variables, 407 external tables, 214
user-defined exceptions, 397 read-only in Oracle 9i, 219
exception section EXTRACT() function, 863
PL/SQL blocks, 394 exttabs.sql script
exceptions DBA_EXTERNAL_LOCATIONS view, 992
DBMS_LOB package, 937
UTL_FILE package, 911
exclusive locks, 487
excprop.sql file, 402 F
executable section
F() procedure
PL/SQL blocks, 34 7
DEBUG package, 792, 793, 812
EXECUTE command, SQL*Pius
FA() procedure
calling a stored procedure, 414
DEBUG package, 792, 795, 813
example procedure for hierarchical data, 662
fast commits, 181
execute character, 339, 348
FASTEMP table
execute counts
Finding People Case Study, 830, 832
TKPROF tool, 733
FCLOSE() and FCLOSE_ALL() procedures
EXECUTE IMMEDIATE statement, 400, 686
UTL_FILE package, 917
bind variables example, 711
features
USING to_char() caluse, 711
available with recent releases of Oracle, 1041
EXECUTE object privilege, 506
distinguished from options, in Oracle, 20
stored procedure, 415
fetch counts
EXECUTE() function
TKPROF tool, 733
DBMS_SQL package, 958
FETCH_ROWS() function
EXECUTE_AND_FETCH() function
DBMS_SQL package, 959
DBMS_SQL package, 959
FFLUSH() procedure
execution
UTL_FILE package, 916
SQL statements, 190
FGAC (Fine Grained Access Control), 525
execution engine, 201
DEBUG package use with RLS, 817
execution plans
enhancement using application contexts, 530, 535
see a/so query plans.
field declarations, PL/SQL, 359
before and after index compression, 286
field order
CBO and RBO versions compared, 724
significance in concatenated indexes, 276
effects of indexing tables, 257
effects of skip scanning, 285 field values
EXPLAIN PLAN statement, 720 datetime and interval data types, 96
materialized view example, 571, 573 file management
execution report problems before Oracle 9i, 172
TKPROF tool, 732 file systems, 162
execution speed control files, 165
control statements, 393 data files, 165
directory objects and, 214
EXIT command, PL/SQL, 390
extracting DDL from the database into, 759
EXIT WHEN command, PL/SQL, 390
factors distinguishing DBMSs from, 465
alternative to IF... THEN ... ELSE statements, 391
parameter files, 162
WHILE loop alternative, 392
pre-allocated file sizes, 169
EXP_FULL_DATABASE role, 505
requirements of an Oracle installation 154
experimentation temporary files, 170 '
performance optimization requires, 708
FILE_IT() function
explain option
calling from INIT(), 808
AUTOTRACE tool, 724 DEBUG package, 804
EXPLAIN PLAN statement, 716 FILECLOSE() and FIRECLOSEALL() procedures
example using rule based optimizer, 723
DBMS_LOB package, 941
EXPLAIN= syntax FILEEXISTS() function
TKPROF tool, 736 DBMS_LOB package, 941
explicit cursors, 373
FILEGETNAME() procedure
example, 377 DBMS_LOB package, 941
implicit cursors compared to, 377, 379
FILEISOPEN() function
exporting data
DBMS_LOB package, 942
using the flat.sql script, 746
FILEOPEN() procedure
expressions
DBMS_LOB package, 942
testing against the DUAL table, 855

1072
functions, PL/SQL
filtering LEVEL pseudo-column, 668
duplicate rows in UNION statements, 67 numeric values, 40, 321
GROUP BY clause results, using HAVING, 56 PARSE_IT() function, 803
records in table joins, 58 preserving leading spaces
FINAL see NOT FINAL option. SET SERVEROUT ON FORMAT WRAPPED
find tool statement, 662
extracting worst-performing queries, TKPROF, 737 print_table.sql script, 7 48
Finding People Case Study, 823 formatting SQL statements, 4 7
see also People application. effects on reusability and performance, 710
adding data to the application, 843 forward slash (/) character
creating database objects, 829 ending a stored procedure, 413
creating the schema, 826 SQL *Plus execution command, 339, 348
employee search example, 846 %FOUND cursor attribute, 376
finding a person's details, 852 free space, data blocks, 169
finding individual employee details, 850 free.sql script, 772
HR sample schema and, 129 example, 774
PL/ SQL APis, 835 FREETEMPORARY() procedure
populating the staging tables, 834 DBMS_LOB package, 942
user interface, 846 FROM clause, 46
Fine Grained Access Control see FGAC. derived tables in
Fine Grained Auditing with rules SQL-92 Full compliance and, 43
can 't use RBO optimization with, 197 may contain inline views, 562
FIRST() collection method, PL/SQL, 366 specifying a selfjoin, 66
FIRST_ROWS setting table functions can return, 677
OPTIMIZER_MODE, 194, 196 frozen views, 471
FIRST_VALUE() function, 697 full outer joins, 65
fixed-length data types full table scans
CHAR,91 alternative to using indexes, 254
NCHAR, 92 case sensisitivity and, 294
flat.sql script, 7 46 cost compared to use of indexes, 221
possible use with createctl.sql script, 767 database tables, comparing optimizers, 198
FLOOR() function, 857 Finding People Case Study, 830
flow diagram LOB locators help speed, 95
QS (Queued Shipping) sample schema, 136 Oracle optimized for, 258
FOPEN() and FOPEN_NCHAR() functions treatment in buffer cache, 237, 246
fully qualified column names
UTL_FILE package, 912
FOR EACH ROW clause table joins and, 59
fully qualified table references
row triggers, 591, 592
FOR loops, 391
granting object privileges, 508
functionality
FORCE option
core and extended, of Oracle, 18
CASCADE option, ALTER TYPE command, 632
enhancing with triggers, 579
CREATE VIEW statement, 557
features and options, 20
foreign key constraints, 113
function-based Indexes, 294
guidelines, 114
can't use RBO optimization with, 197
locking of child tables, 290
example, 298-299
no automatic index generation, 290
must use deterministic functions, 440
REFERENCES object privileges and, 511
functions, PL/SQL
foreign keys
advantages over anonymous PL/SQL, 411
REF data types compared to, 655, 657
accessible with SQL *Plus DESCRIBE command, 323
self referencing foreign keys, 65
aggregation functions
table joins and, 58
listed with syntax and examples, 888
format masks, 321, 702
analytic functions, 686
for ROUND() and TRUNC() datetime functions, 869
associated with object types are methods, 633
input to DEBUGTAB table, 791
capturing the return value, 436
format strings
character functions
converting between characters , dates and listed with syntax and examples, 870
numbers, 887 classified list with syntax and examples, 855
FORMAT_CALL_STACK() function miscellaneous functions, 890
DBMS_UTILITY package, 797, 798 common errors, 440
formatting Input data conversion functions
data from external tables, 684 listed with syntax and examples, 878
row t riggers, 591 DATETIME functions
formatting output data, 34 listed with syntax and examples, 861
DEBUG package, 813 DBMS_JOB package, 917
default date formats, 97 DBMS_LOB package, 934
Finding People Case Study, 8 4 7 DBMS_RANDOM package, 904
format masks, 35

1073
functions, PL/SQL (Cont'd)

functions, PL/SQL (Cont'd) granting permissions


DBMS_SQL package, 948 access to external tables, 217
deterministic functions, 439 applying security policies, 526
event attribute functions, 611 database roles, 514
FIRST_VALUE() and LAST_VALUE(), 697 object privileges, 507, 508
function mimicking?: Boolean test operator, 438 EXECUTE privileges for packages, 448
IN parameters to stored procedures, 437 EXECUTE privileges for procedures, 416, 417
ITE, for passing alternative values, 439 primary key example, 110, 112
LAG() and LEAD() functions, 690, 691 system privileges, 502
miscellaneous functions, 890 create view privileges, 545
NUMBER functions granularity
listed with syntax and examples, 856 see a/so FGAC.
overloading, 452 Fine Grained Auditing with rules, 197
RANK() and DENSE_RANK(), 695 lock escalation and, 487
SYS_CONNECT_BY _PATH() function, 670 GREATEST() function, 894
table and pipelined functions, 677 grep tool
unlike stored procedures, must return values, 436 extracting worst-performing queries, TKPROF, 737
updating columns based on functions GROUP BY clauses, 54
INSTEAO OF triggers and, 600, 601 temporary files and, 170
use in function-based indexes, 295 grouped commits, 181
use promotes query reusability and performance, 710 GUI (Graphical User Interface) tools
user-defined aggregate functions, 672 starting up SQL *Plus, 30, 318
user-defined, in function-based indexes, 295
UTL_FILE package, 909
UTL_RAW package, 924
H
hard parses, 191
G avoiding with bind variables, 710
hash clustered tables, 230, 708
geographical information locating with hash function, 230
Oracle Spatial technology supports, 132 hash joins
GET_EMPLOYEE() function require MAP MEMBER() method, 639
PEOPLE package, 841, 842, 850 hashing
GET_EMPLOYEES() function not a unique mapping, 193
PEOPLE package, 842, 847 password security through, 535
GET_LAST_NAME(} function, 640 SQL statements before checking the shared
GET_LINE() and GET_LINE_NCHAR() function pool, 192
UTL_FILE package, 913 HAVING clauses, 56
GET_LINE(S)() procedures distinguished from WHERE clauses, 57
DBMS_OUTPUT package, 904 heap tables, 212
GET_PHONE_NUMBER(} function, 640 temporary tables compared to, 226
getallcode.sql script, 762 heights of Indexes, 263
getallvlews.sql script, 766 help system, SQL*Pius, 332
getavlew.sql script entering a new Help topic, 334
DBA_VIEWS view, 1003 HELP command, 332
GETCHUNKSIZE() function hexadecimal strings
DBMS_LOB package, 943 binary values conversion, 537-538
getcode.sql script, 761 HEXTORAW() function, 538
DBA_SOURCE view, 1008 hidden columns
GETLENGTH() function DBA_TABLES view and, 294
DBMS_LOB package, 943 HIDE option
getobject.sql script, 759 SQL *Plus ACCEPT, 324
getvlew.sql script, 764 hierarchical queries, 661
global variables example, 663
accessible from a trigger, 595 LEVEL pseudo-column, 667
incrementing, 598 may include join conditions, 670
example using, 598 ORDER SIBLINGS BY clause, 668
public and private, 448 SYS_CONNECT_BY_PATH() function, 670
use in BUILD_IT() package, 801 using NULL values to find the root, 665
GLOBAL_NAME view high water mark
column definitions and usage, 1022 database tables, 254
prompt.sql script, 1022 hints see optimizer hints.
glogln.sql flies, 34 histograms
creating a site profile, 312 influencing the query optimizer, 261, 281
login.sql script compared to, 7 44 hlpbld.sql file
SQL *Plus help installation, 334

1074
inheritance

HOST commands, SQL*Pius, 341 Implicit begin statements


host name modifying data begins a transaction, 466
Oracle listener defaults, 155 Implicit cursors, 375
HR (Human Resources) sample schema alternative to singleton SELECTs, 385
atypically simple, 835 explicit cursors compared to, 377, 379
compared to SCOTT, 128 PPL_UTI LITY package
createctl.sql script example, 769 Finding People Case Study, 836
EMP_DETAILS_VIEW, 553 In doubt distributed transactions, 184
EMPLOYEES table, investigating, 143 IN OUT parameters
example using INSTEAD OF triggers, 601 stored procedures, 418, 427
explicit cursor example, 377 IN parameters, stored procedures, 417, 418
Finding People Case Study, 833 default values, 422
index.sql script example, 776 functions may be used as, 437
installation, 1028 passed by reference, 428
introduced, 127 INCLUDING clause
JOBS table, 149 CREATE TABLE statement, 225
illustrating INSERT statements, 70 INDEX and REFERENCES object privilege, 506
listing object decriptions, 139 Index only scans, 296
PL/SQL tables example, 361 example, 298, 299
predefined exceptions example, 395 index organized tables see lOT.
relational view example, 545 INDEX UNIQUE SCAN, 201
SECURE_EMPLOYEES trigger, 610
lndex.sql script, 775
self documenting example, 148
example, 776
trigger example, 580
INDEX_STATS view, 264
HR_AUDIT accountjschema
change on inserting records, 267
creating the account, 86
effect of PCTFREE attribute changes, 266
foreign key constraints, 114
index-by tables see tables, PL/SQL.
modifying tablespace settings, 87
Indexes, 253
primary key constraints, 110
access using, may be slower than a full scan, 199
hr_comnt.sql script, 148
automatic rebalancing by Oracle, 263
hr_maln.sql script
bitmap indexes, 300
hr_ *.sql scripts and, 1029
can use on temporary tables, 227
HTML (Hypertext Markup Language)
cannot use with LIKE operator, 830
output from SQL *Plus, 310
compressed and concatenated, example, 280
Human Resources see HR schema. compression, 223, 277, 286
should be considered for non-unique indexes, 278
concatenation, 275
constraints can cause automatic index creation, 287
cost of using indexes, 261, 275
IBM DB/2 data types, 104 compressed indexes, 286
IDENTIFIED BY clause DEBUGTAB table, 790
ALTER ROLE statement degradation over time, 263
password protecting roles, 518 displaying using desc.sql script, 143
CREATE USER statement, 84, 501 DML activity causes problems, 275
Identifiers see valid Oracle Identifiers. dynamically creating within applications, 275
Identifiers, PL/SQL effects of record insertion, 264
scope and visibility, 352 effects of updating and deleting rows, 268
IF... THEN ... ELSE statements, 386 formatting input data and using indexes, 592
function-based indexes, 294
case statements as alternative to, 388
inserting rows and its effect, 262
EXIT WHEN alternative, 391
listing indexes defined for a user, 775
people_detail.sql script, 851
not available on external tables, 219
trigger to log table modifications
capturing the statement type, 590 rebuilding, 275
lf_then_else.sql Hie, 386 reverse key indexes, 291
skip scanning of indexes, 278
modified to use case statements, 389
If-Then-Else (ITE) function updating and deleting effects, 270
view performance and, 561
alternative to case structures, 446
when to use, 258
mimicking?: Boolean test operator, 438
lndexes.sql script
IIOP (Internet Inter-ORB Protocol)
DBA_IND_COLUMNS view, 1016
shared server mode mandatory, 161
Index-only scans, 296
Image data
example, 298, 299
ORDSOURCE data types, 134
Index-organized tables see lOT.
IMMEDIATE keyword
Infinite loops, 390
deferrable constraints, 288
Inheritance, 639
SET CONSTRAINTS statement, 474, 481
Immediate population simulated by composition, 627
single and multiple, introduced, 620
materialized views, 573

1075
INIT() procedure

INIT() procedure Instantiation of packages, 448


DEBUG package, 792, 806 instantiation block, 451
lnit.ora flies, 162 INSTEAD OF triggers, 599
_trace_files_public parameter, 730 example, 600, 602
enabling TIMED_STATISTICS parameter, 726 updating views using, 559, 568
MAX_DUMP_FILE_SIZE parameter, 726 INSTR() function, 871
NLS DATE FORMAT setting, 745 DBMS_LOB package, 943
QUERY _RE-WRITE_ENABLED parameter, 295 DEBUG package, 796
setting checkpoint frequency, 183 FILE_IT package, 805
SHOW PARAMETERS command and, 328 Instrumenting code, 709
UNDO_MORE parameter, 167 lntermedla see Oracle lntermedla.
UNDO RETENTION parameter, 167 lnteroperablllty
UTL_FlLE_DIR parameter, 791, 910 advantage of using NOT INSTANTIABLE types, 647
troubleshooting the DEBUG package, 817 INTERSECT statements, 69
INITCAP() function, 870 interval data types, 103
INITIAL parameter example to sum, 674
CREATE TABLE statement, storage clause, 168, 236 SUM() function doesn't support, 673
Initialization flies, 162 INTERVAL DAY TO SECOND data type, 103
static and dynamic initialization parameters, 163 user-defined aggregate functions example, 672
used in database instance startup, 162 INTERVAL YEAR TO MONTH data type, 103
INITIALIZE() procedure INTERVAL() procedure
DBMS_RANDOM package, 909 DBMS_JOB package, 923
lnllne object constructors, 369 slipping interval problem, 920
inllne views, 562 intlallzlng constants, PL/SQL, 350
analytical function alternative, 564 lntlallzlng variables, PL/SQL, 350
length of service example, 694 INTO clause
web application example, 693
singleton SELECTs, 384
inner joins, 62 Invalid database objects
INPUT command
dependent objects marked as, 628
SQL *Plus built-in editor, 338 reported by dbls.sql script, 770, 771
INPUT STRING argument Invalid PL/SQL code
DES3ENCRYPT() and DES3DECRYPT() manually recompiling with comp* scripts, 751
procedures, 536 Invalid stored procedures
INSERT and UPDATE statements manual recompiling with compproc.sql, 754
UPDATE_CHECK argument, 529 Oracle tries to recompile when invoked, 458
INSERT INTO SELECT statement, 230 referenced object changes cause, 456, 457
INSERT INTO statement Invalid triggers
adding object types to tables, 625, 652 manual recompiling with comptrig.sql, 755
example of managing subtypes, 642 Invalid views
RETURNING INTO clause, 807 FORCE option, 557
VALUES clause, 840 manually recompiling with compview.sql, 755
INSERT object privileges, 506, 511 revalidated automatically when queried, 557
Insert operations lnvalld.sql script, 766
deleted entries cleared from indexes, 269, 274 INVALID_NUMBER
effects on indexes, 262 predefined exception, 396
INSTEAD OF trigger inserting into a view, 601 INVALIDATE option
issuing against views ALTER TYPE command, 628
INSTEAD OF triggers and, 600
Invalidation
loading data from external tables, 684
package specification changes don't cause, 458
PL/SQL tables, 369
invoker's rights
sample stored procedure executing, 418
triggers can change values without warning, 582 designating PL/SQL procedures to operate with, 523
print_table.sql script, 7 48
update or, MERGE statement, 698
stored procedures, 432
INSERT statements, 70
compile_schema.sql script, 759
explicit column listing recommended, 70
IO_BIFER_DEPT_EMP_VIEW trigger, 604
illustrating an INNER JOIN, 62
lOT (Index-Organized Tables), 220
INSERTING conditional predicate
compression, 223
BIUD_EMPLOYEES_COPY trigger, 598
require the use of CBO, 196
statement triggers, 588
using overflow segments, 225
INSTANCE() procedure
when to use, 223
DBMS_JOB package, 923
IS DANGLING predicate
Instances see connecting to a database Instance.
SELECT statements, 658
Instantiation of object types, 624
IS NOT NULL operator, 52
inline instantiation, 625
IS NULL operator, 52
objects within objects, 627
IS OF predicate
order not predetermined, 636
SELECT statements, 644
use with TREAT() function, 645

1076
LOB column types
IS_OPEN() function large object data types see LOB data types.
DBMS_SQL package, 964 large pool, SGA, 177
UTL_FILE package, 913 LAST collection method, PL/SQL, 366
IS·A relationships, 639 LAST_DAY() function, 864
Isolation see transaction Isolation. LAST_ERROR_POSITION() function
%1SOPEN cursor attribute, 376 DBMS_SQL package, 966
ISOPEN() function LAST_ROW_COUNT() function
DBMS_LOB package, 944 DBMS_SQL package, 967
ISTEMPORARY() function LAST_ROW_ID() function
DBMS_LOB package, 944 DBMS_SQL package, 967
ISUBMIT() procedure LAST_SQL_FUNCTION_CODE() function
DBMS_JOB package, 919 DBMS_SQL package, 967
ITE (lf·Then·Eise) function LAST_VALUE() function, 697
alternative to case structures, 446 LDAP (Lighwelght Directory Access Protocol)
mimicking?: Boolean test operator, 438 HR sample schema, 129
OlD and, 129
LEAD() function, 690
J leading key
concatenated indexes, 286
Java leaf nodes
?: Boolean test operator in, 437 B-Tree indexes, 256
bulk fetches, 733 updates and deletes result in unused space in, 269
Finding People Case Study and, 853 leaf rows
NOT INSTANTIABLE types resemble Abstract updating and deleting effects on deleted rows, 273
Classes, 64 7 learning
Oracle management tools moving to, 157 gradual approach facilitated by sample schemas, 138
triggers can be written in, 579 LEAST() function, 894
Job Queue Coordinator (CJQ), 183 left outer joins, 63
job scheduling systems length of service example
Finding People Case Study, 844 ranking with analytic functions, 694
job tracking systems, 16 length semantics, 93
JOB_QUEUE_INTERVAL parameters LENGTH() function, 871
slipping interval problem, 920 UTL_RAW package, 926
JOB_QUEUE_PROCESSES and JOB_QUEUE_INTERVAL LEVEL pseudo column, 667
parameters best located in CONNECT BY clause, 668
DBMS_JOB package, 917 formatting results, 668
jobs LGWR see Log Writer.
configuring a database to support jobs, 917 library cache
JOBS table misses in, TKPROF tool report, 734
HR sample schema, viewing comments on, 149 SGA shared pool, 176
join views, 553 LIKE operator, WHERE clause, 48, 830
updating with INSTEAD OF triggers, 560 line lengths
joining tables see table joins. limits on DBMS_OUTPUT package, 788
JVM (Java VIrtual Machine) line-mode applications
Oracle 8 new features, 19 lsnrctl utility, 156
PM sample schema needs, 1038 LINESIZE setting, SQL*Pius, 38
GUI version, 318
Linux servers
K example of a listener.ora file for, 156
example of an init.ora file for, 162
LIST command
key compression see compression.
key data SQL *Plus built-in editor, 337
Listener see Oracle Listener.
indexes relate to rowids, 256
KEY STRING argument llstener.ora flies, 156
DES3ENCRYPT() and DES3DECRYPT() LOAD_EMPLOYEE() procedure
procedures, 536 PPL_UTILITY package, 836
LOAD_FASTEMP() procedure
PPL_UTILITY package, 840

L LOADFROMFILE() procedure
DBMS_LOB package, 945
LOB column types
LAG() function, 691 PM sample schema relies on, 133
languages other than English
NCHAR data types, 92
OE sample schema installation, 1031

1077
LOB data types

LOB data types logical storage


Application Developer's Guide- Large Objects, 935 data blocks, 169
BLOBs and ORDSOURCE data types, 134 extents, 167
GLOBs, invalidating views example, 556 segments, 166
LOB locators, 95 tablespaces, 165
NCLOBs not allowed for object type attributes, 623 logical units of work
Oracle 8 new feature, 94 transactions viewed as, 466
prohibited in compound queries, 67 logln.sql script, 34, 744
LOC_REF values creating a user profile, 313
REF() function, 656 defining editors within, 336
local declarations LogMiner
stored procedures, 429 SYSTEM user account owns, 14
localized net services management, 158 LONG and LONG RAW data types, 94
locally managed extents, 168 not allowed for object type attributes, 623
Oracle 9i default, 168 LONG setting, SQL*Pius, 41
locally managed tablespace, 236 lookup tables, 137
locally managed temporary tablespaces, 171 CACHE clause recommended for, 237
LOCALTIMESTAMP() function, 864 loop counters
LOCATION attribute FOR loops, 392
CREATE TABLE statement, 216 looping structures, 385, 390
locators, LOBs, 95 cursor input to pipelined functions, 682
lock conversion, 487 FORioops,391
lock promotion, 487 company employees example, 652
Oracle uses instead of escalation, 487 PL/SQLioops, 375
locking, 484 unconstrained loops, 390
bitmap indexes and OLTP, 303 WHILE loops, 392
child tables subject to foreign key constraints, 290 lost updates, 487
conversion to more restrictive levels, 487 LOWER() function, 872
enqueues, 738 LPAD() function, 872
optimistic and pessimistic compared, 492 formatting results, 668
optimistic locking, 490 Finding People Case Study, 84 7
pessimistic locking, 488 LRU (Least Recently Used) list
reading around locked data, 495 buffer caches
release of locks in commit operations, 467 touch counts have replaced, 175
shared pool, by users with unique queries, 712 effect of CACHE clause, 237
user accounts, and unlocking, 86 scanned data blocks aged out quickly, 237
log switches used by SGA shared pool, 177
cause checkpoints, 183 lsnrctl utility, 156
redo log files, 181 LTRIM() function, 873
Log Writer (LGWR), 181
flushing the redo log buffer, 468
role in commit operations, 467
role in system crash example, 204
M
LOG_BUFFER Initialization parameter, 176 maintainability
LOG_CHECKPOINT_* parameters, 183 advantages of procedures and functions, 412
LOG_MESSAGE() procedure maintaining data
private procedure example, 445 Finding People Case Study, 844
LOGFILE clause manageability
CREATE TABLE statement, 219 Oracle core competency, 153
logging manual Installation of sample schemas, 1028
see also redo log flies. manual recompiling of Invalid modules
dropped objects comp* scripts, 751
user event triggers example, 606 MAP MEMBER method, 636
logging with PRAGMA AUTONOMOUS_TRANSACTION superior for sorting and required by hash joins, 639
directive, 433 mapping
messages
strings to numbers, by hashing, 193
private procedure example, 445
master Installation script
Oracle listener, 157
Finding People Case Study, 845
statements, causing triggers to fire, 613
materialized views, 568
trigger to log table modifications, 585
capturing the statement type, 589 adding to existing applications, 575, 576
row counts and logging column changes, 595 auto population, 573
LOGGING parameter immediate population, 573
ALTER TABLE statement, 246 maintained as data is added, 571, 573
CREATE TABLE statement, 234 potential conflict with function-based indexes, 295
query rewrite, 575
suitabililty to different systems, 57 4
SYSTEM user account owns, 14

1078
Naming Methods

MAX() function, 889 mixed notation


MAX_DUMP_FILE_SIZE parameter passing parameters into stored procedures, 422
init.ora files, 726 default values, 423
MAXEXTENTS parameter mksample.sql script, 1028
CREATE TABLE statement, storage clause, 168, 236 MOD() function, 116, 858
MD5 (Message Digest) security, 535, 539 MOD_PLSQL application, 19
media failures, 182 modifying commands
member method functions stored in SQL *Plus buffer, 336
GET_LAST_NAME() function, 640 modifying data
GET_PHONE_NUMBER() function, 640 example trigger to log, 585
overriding, 645 implicitly begins a transaction, 466
member method procedures, 644 UPDATE statements, 71
member methods updating and deleting effects on an index, 268
called through object instances, 636 modifying object types, 628
calling from SQL, 634 modifying profiles
defining as NOT INSTANTIABLE, 647 DEBUG package, 812
example, 635 modifying tablespace settings, 87
FINAL and NOT FINAL options, 646 quotas, 87
one of three method types, 633 modifying triggers, 587
static methods compared to, 633, 635 modifying user accounts, 85
memory modularity
limiting user allocation, 178 advantages of procedures and functions, 411
memory parameters for a database instance, 163 monotonically Increasing sequence numbers, 291
problems when SGA won't fit, 175 MONTHS_BETWEEN() function, 865
requirements of an Oracle installation, 154 MOVE statement
memory areas, 174 ALTER TABLE statement, 244
PGA, 178 MTS (Multi-Threaded Server) see shared server
shared server mode, 161 mode.
MEMORY option multi block reads
ALTER SYSTEM statement, 164 full table scans and, 258
MERGE INTO clause, 700 multlbyte character sets, 93
MERGE statement, 698 multidimensional arrays
five clauses in syntax, 700 modeling with nested tables, 370
PL/SQL alternative, 699, 702 multimedia data
without selecting the record first, 701
see also Oracle lntermedla.
merging tables
PM sample schema and, 132, 1032
CBO optimization, 200
multiple Inheritance, 620
message digests
multl-verslonlng, 492
DBMS_OBFUSCATION_ TOOLKIT package, 539
my_order_mv materialized view, 572
password security through, 535
my_reports view, 551.
mesaaglng systems
QS sample schema flow diagram, 136
QS sample schema illustrates, 135
meta data N
data dictionary as a source of, 16
USER_TABLES view, 120 named notation
external tables stored as, 217 passing parameters into stored procedures, 420
provided by cursor attributes, 376 naming conventions
provided by the DUMP() function, 892 see also dot notation.
methods, 633 constraints, automatic index creation and, 287
see also member methods. data dictionary, 122
displaying for PM sample schema, 134 data dictionary views, 971
implemented in type body, 634 short names, 1023
object-orientation and, 620 database roles, 512
metonyms every object in a schema must be uniquely
created by OE sample schema, 132 named, 414
metrlcs Oracle fundamental terminology, 11
benchmarking and, 709 owner.object use with procedures, 416
migration PL/SQL variables and constants, 346
dependent objects, 632 reserved words, SQL, 82, 347
automated by type evolution, 632 short names, data dictionary views, 1023
MIN() function, 890 table joins and column naming, 59
MINEXTENTS parameter triggers, 580
CREATE TABLE statement, storage clause, 168, 236 valid Oracle identifiers, 82, 107
MINUS statement, 69 Naming Methods
misses In library cache Net Configuration Assistant and, 29
TKPROF tool report, 734

1079
national character sets

national character sets NOLOGGING parameter


NCHAR data types, 92 ALTER TABLE statement, 246
NCLOB data types, 95 CREATE TABLE statement, 234
NVARCHAR2 data types, 93 non-blocking queries, 492
NATURAL and NATURALN data types non-repeatable reads
BINARY_INTEGER sub-types, 358 ANSI transaction isolation levels and, 483
natural joins, 61 non-unique Indexes
NCHAR data type, 92 compression suitability, 278
not allowed for object type attributes, 623 deferrable constraints enforced with, 288
NCLOB (National Character Large Objects), 95 NO-OPs
not allowed for object type attributes, 623 use of NULL values, 354
nested blocks, PL/SQL, 349 NORMAL() function
exceptions raised in declaration section, 406 DBMS_RANDOM package, 908
propagation of exceptions, 401 NOT FINAL option
nested queries CREATE OR REPLACE TYPE statement, 639
Finding People Case Study, 842 MEMBER methods, 646
free_sql script and, 77 4 %NOT FOUND cursor attribute, 376
nested tables, PL/SQL, 370 NOT INCLUDING TABLE DATA option
distinguished from object types, 622 CASCADE option, ALTER TYPE command, 630
modifying using INSTEAD OF triggers, 601 NOT INSTANTIABLE
PL/SQL collections, 358 defining object types and member methods as, 647
PM sample schema, 134 NOT NULL constraints, 239
table functions can return, 677 employee history table, 108
nesting stored procedures EMPLOYEES table, HR sample schema, 128
with local declarations, 429 using on child table columns, 114
nesting transactions, 433 NOT NULL operator
Net Configuration Assistant, 28 PL/SQL variables, 352
networks NOT operator, WHERE clause, 48
database connections using SQL *Plus, 28 Notepad
new line character modifying commands from the SQL *Plus buffer, 336
substituting, in PARSE_IT() function, 803 NULL values, 51, 354
NEW_LINE() procedure acceptable to unique constraints, 115
DBMS_OUTPUT package, 903 assigned to uninitialized PL/SQL variables, 352
UTL_FILE package, 915 assignment, deleting PL/SQL table records, 366
next and previous values attempting to de-reference dangling REFs, 658
analytic functions, 690 DESCRIBE statement and, 45
NEXT collection method, PL/SQL, 367 excluded from indexes, 297
NEXT parameter migrated object attributes set to, 632
CREATE TABLE statement, storage clause, 168, 236 object types, 627
NEXT_DATE() procedure use as a placeholder, 354
DBMS_JOB package, 923 use in hierarchical query example, 665
NEXT_DAY() function, 866 NULLIF() function, 895
NLS_DATE_FORMAT setting, 98, 625 NUMBER data types, 90
changing with the bigdate.sql script, 7 45 ANSI equivalents tabulated, 105
NLS_LANG setting formatting options, 888
NLS_DATE_FORMAT and, 98 PLS_INTEGER and BINARY_INTEGER
NLS_LENGTH_SEMANTICS parameter, 94 compared to, 357
NO_DATA_FOUND NUMBER functions
exception propagation example, 403 listed with syntax and examples, 856
predefined exception, 396 numeric data types
compile_schema.sql script, 759 number-based TO_CHAR() function, 881
NOBADFILE clause PL/SQL, with SQL equivalents, 357
CREATE TABLE statement, 219 numeric values
NOCACHE clause formatting with NUMFORMAT, 40
default for CREATE TABLE statement, 237 formatting with the COLUMN command, 321
NOCOMPRESS attribute NUMFORMAT setting, SQL*Pius, 40
CREATE TABLE statement, 223 NUMTODSINTERVAL() function, 673, 866
NOCOPY hint NUMTOYMINTERVAL() function, 867
passing stored procedure parameters, 428 NVARCHAR2 data type, 93
WHEN OTHERS THEN exception handler, 428 not allowed for object type attributes, 623
NOLOGFILE clause NVL() function, 634, 895
CREATE TABLE statement, 219 NVL2() function, 896

1080
options

0 OE (Order Entry) sample schema, 130


installation, 1030
introduced, 127
object collections locked user account example, 86
Oracle 8 new features, 368 nested tables example, 370
VARRAYs, 368 OC_ORDERS view, 145
object constructors Oracle Spatial and, 1038
inline object constructors, 369 oe_maln.sql script
object decrlptlons oe_ * .sql scripts and, 1031
extracting definitions from the database, 139 OlD (Oracle Internet Directory)
investigating tables, 141 alternative to Oracle Names Server, 158
object names and object IDs industry-standard LDAP server, 129
TKPROF tool report, 735 maintaining user credentials, 501
object orientation see object·orlentatlon. OIS (Oracle Internet Server), 824
object privileges, 13, 506 OLTP (Online Transaction Processing)
ALL PRIVILEGES shortcut, 510 bitmap indexes unsuitable for, 303
granted through roles, can cause PL/SQL materialized views, refresh on demand option, 574
problems, 519 ON clause
table privileges, 509 MERGE statement, 700
object tables, 653 ON COMMIT DELETE ROWS clause
object types, 621 CREATE GLOBAL TEMPORARY TABLE
accessing attributes, 626 statement, 230
attribute names and data types, 623 ON COMMIT PRESERVE ROWS clause
can use LOBs in, 94 compile_schema.sql script, 758
columns in database tables, 624 CREATE GLOBAL TEMPORARY TABLE statement, 229
comparing and sorting, 636, 637 ON DELETE triggers
constructor methods, 624 TRUNCATE TABLE doesn't fire, 249
creating an object table from, 654 ONE_MILLION_ROW_TABLE example, 202
defining as NOT INSTANTIABLE, 647 one-way functions
distinguished from collections, 621
password encryption, 535
dropping, 632
ONLINE CATALOGUE subschema
implementing user-defined aggregate functions, 673
OE sample schema, 132
inline instantiation, 625
online ordering
object views and, 566
objects within, 627 QS sample schema illustrates, 135
OE sample schema, 132 online rebuild of Indexes, 275
order of instantiation not predetermined, 636 online resources
PM sample schema, 134 creating a view, 544
reported by dbls.sql script, 769 Oracle 9i Database Performance Guide and
sorting, MAP methods better than ORDER, 639 reference, 197
specification and body, 622 Oracle 9i Database Reference, 162
object views, 565 PL/SQL User's Guide and Reference, 396, 442
benefits, 568 online transaction processing
modifying using INSTEAD OF triggers, 601 new sample schemas to illustrate, 126
pivot function alternative, 683 OPEN() procedure
OBJECT_NAME column DBMS_LOB package, 945
ALL_OBJECTS view, 37 OPEN_CURSOR server parameter, 163
object-orientation, 619 OPEN_CURSOR() function
concepts introduced, 620 DBMS_SQL package, 951
example of the way new features are operating system
introduced, 1041 data blocks are distinct from Oracle's, 169
non-00 applications can still use Oracle executing a command within, from SQL *Plus, 341
features, 621 influence on database installations, 154
object hierarchies, 620 OS authentication, 311
OE sample schema, 132 operator precedence, 50
polymorphism, 620 OPS (Oracle Parallel Server), 12
object-relational model, 566, 619 optimistic locking, 490
objtab.sql script optimization see performance optimization; query
DBA_OBJECT_TABLES view, 994 optimization.
obsolete commands, 334 optimizer hints
OC_ORDERS view deterministic hint, 440
OE sample schema, 145 NOCOPY hint, 428
OCI (Oracle Call Interface), 568, 935, 967 use of CBO optimization and, 196
ODCI (Oracle Data Cartridge Interface) OPTIMIZER_MODE setting, 194, 196
ODCIAggregate*() functions, 67 4 options
ODCIAggregate*() functions, 675 available with recent releases of Oracle, 1041
user-defined aggregate functions, 673 checking availability with V$0PTION, 1057
distinguished from features, of Oracle, 20

1081
OR binary operator

OR binary operator, 49 object-orientation improved


ORA·* see error messages. inheritance, polymorphism and type evolution, 619
ora_*() event attribute functions, 611 Oracle Managed Files, 172
ora_sql_txt() function ORDER SIBLINGS BY clause, 668
logging the statements which fired triggers, 613 pipelined table functions, 679
Oracle 8 new features RDBMS README documentation, 1041
Java Virtual Machine, 19 server parameter files, 164
skip scanning of indexes, 278
LOB data types, 94
locally managed tablespaces, 168 SYS_CONNECT_BY_PATH() function, 670
object oriented technology, 368, 372, 565, 619 timezone translation, 103
type evolution, 628
Oracle 8 release 8.0.4
Unicode National character data types, 92, 93
feature availability, 1055
variable data block sizes, 169
option availability, 1054
Oracle 91 release 9.0.1
Oracle 81 compared with 91
feature availability, 1042
index concatenation, compression example, 280
option availability, 1041
Oracle 81 Designing and Tuning for Performance, 725
Oracle 91 SQL Reference manual, 506
Oracle 8/ new features
Oracle Advanced Queues
application contexts, 530
configured with QS sample schema installation, 1033
data security with triple DES, 535
Oracle Data Dictionary
deferrable constraints, 288
extracting definitions from the database, 139
drop column statement, 240
dynamic configuration of listeners, 155 Oracle Enterprise Edition, 20
fine grained access control, 525 bitmap indexes, 303
function-based indexes, 294 options and feature available with, 1041
key compression of B-Tree indexes, 277 Oracle Forms tool
locally managed tablespace, 236 DEBUG package use with, 817
MD5 (Message Digest) security, 539 protects against lost updates, 488
nesting transactions, 433 SQL_TRACE and, 728
OlD directory server, 158 Oracle lntermedla
option over PL/SQL procedure rights, 521 interMediaText, 708
ORDER BY clause in views, 551 object types, 135
reverse key indexes, 292 ORDSOURCE data types, 134
touch counts, 175 ORDSYS.ORD_ columns, 134
Oracle 81 release 8.1.5 PM sample schema and, 127, 132, 1038
feature availability, 1051 Oracle Listener
option availability, 1050 connecting to databases, 155
Oracle 81 release 8.1.6 and 8.1. 7 creating multiple listeners, 156
feature availability, 104 7 database services registered by PMON, 179
optiah availability, 1046 default protocol, hostname and port, 155
Oracle 91 Data Cartridge Developer's Guide, 677 manual configuration, 156
Oracle 91 Database Performance Guide and Net Configuration Assistant and, 29
Reference, 197, 725 Oracle Managed Flies, 172
Oracle 91 Database Reference, 162 file size needn't be specified, 170
Oracle Names Server
Oracle 91 new features
only service repository before Oracle 8i, 158
affecting function-based indexes, 297
Oracle Net Configuration Assistant, 28
ANSI table joins, 61
automatic undo manangement, 167 Oracle Net Services
bimap join indexes, 304 see a/so SQL*Net.
byte or char column size definitions, 93 centralized net services management, 158
Case structures, 388, 446 combining centralized servers with tnsnames.ora
creating indexes along with tables, 290 files, 160
CURRENT_DATE() function, 435 connecting to databases, 155
date and time data types expanded, 95 database connections using SQL *Plus, 28
INTERVAL DAY TO SECOND data type, 672 localized management, 158
DBMS_RANDOM package, 451 Oracle Net client, 157
event attribute functions People search command file and, 849
public synonyms, 611 risk of sending passwords over, 501
EXAMPLE tablespace, 83 Oracle NetS
external tables, 214 now Oracle Net Services, 28
hierarchical queries including joins, 670 Oracle Personal Edition, 20
inheritance, 639 options and feature available with, 1041
Job Queue Coordinator, 183 Oracle Server Concepts Manual, 483, 487
locally managed tablespaces as default, 236 Oracle Spatial technology
MERGE statement, 698 OE sample schema illustration, 132
nested tables, 370 OE sample schema needs, 1038
new sample schemas, 126, 1025 Oracle Standard Edition, 20
options and feature availalble with, 1041

1082
parent-child relationships

ORACLE_ADMIN user
creating user accounts, 84, 415, 551
p
dropping user accounts, 89
Finding People Case Study, 826 package body, 442, 444
unlocking user accounts, 86 global variables defined in, are private, 448
using SHOW PARAMETERS, 97 invalidated by changed dependencies, 459
viewing tables and tablespaces, 87, 120 recompiling with compbody.sql, 752
ORACLE_LOADER access driver, 217 PEOPLE package, 842
ORDER BY clause, 52 PPL_UTILITY package, 836
analytic functions, 686 package level variables see global variables.
ORDER SIBLINGS BY for hierarchies, 668 package specification, 442, 443
prohibited in compound queries, 67 global variables accessible by triggers, 595
ROWNUM assigned before, 565 global variables defined in, are public, 448
sorting by columns not selected, 54 PEOPLE package, 841
sorting by multiple columns, 53 PPL_UTILITY package, 835
sorting using numeric column positions, 54 varying doesn't invalidate referencing objects, 458
using with a view, 546, 551 packages, PL/SQL,442, 901
Order Entry see OE schema. accessible with SQL *Plus DESCRIBE command, 323
ORDER() method advantages of, 458
object types, 638 DBMS_JOB package, 917
ORDER SIBLINGS BY clause DBMS_LOB package, 934
SELECT statements, 668 DBMS_SQL package, 948
ORDER_STATUS_TABLE Finding People Case Study, 835
QS_CS schema, 136 instantiation, 448
ordered groups
instantiation block, 451
investigating using SQL *Plus DESCRIBE, 461
LAG() and LEAD() functions, 690
private procedures and functions, 445
ORDSOURCE data types, 134
supplied packages prefixed with DBMS_ or UTL_, 901
ORDSYS.ORD_ columns
Supplied PL/SQL Packages and Types
PM sample schema, 134
Reference, 901
ORDSYS.ORDIMAGE object type
UTL_FILE package, 909
methods, 134 UTL_RAW package, 924
ORGANIZATION EXTERNAL clause
padding
CREATE TABLE statement, 216 CHAR data type columns, 92
ORGANIZATION INDEX clause data for encryption, 536, 538
CREATE TABLE statement, 220 PAGESIZE setting, SQL*Pius, 37
OS authentication, 311
paging of output, 33, 34
OUT parameters PAGESIZE settings and, 37
passed by value, 428 PAUSE command and, 36
stored procedures, 418, 424, 426 parallel execution message buffers
compile_schema.sql script, 759 stored in large pool, 177
WHO_CALLED_ME() procedure, 797
parallel query operations
outer joins, 63
can't use RBO optimization with, 197
(+) convention, 65
parameter flies
out-of-line storage
configuring a database instance on startup, 162
large object data types, 94
enabling Oracle Managed Files, 172
OVER keyword
persisting parameters with, 164
indicates an analytic function, 686
server parameter files, 164
overflow segments
uses, 163
index organized tables, 225 parameters
OVERLAY() function
parameter order, 428
UTL_RAW package, 927 passing by reference and by value, 428
overloading
passing into stored procedures, 420
functions and stored procedures, 452 add new parameters as last, 423
methods, 633 common errors, 423
overriding using mixed notation, 422
FINAL methods cannot be overridden, 646 using named notation, 420
member functions and subtypes, 645 using positional notation, 421
NOT INSTANTIABLE objects must be overridden, 647 passing to cursors, 373
OVERRIDING keyword REF() function, 656
subtypes, 641 stored procedure IN OUT parameters, 427
use in overriding example, 645 stored procedure OUT parameters
OWA (Oracle Web Agent), 824 common errors, 426
owner.object naming convention stored procedures, 417
use with procedures, 416 parent-child relationships
foreign key constraints, 113
using the CONNECT BY clause, 665

1083
parse counts

parse counts indexes on monotonically increasing sequence


compared to execute counts, TKPROF tool, 733 numbers, 292
PARSE() procedure overhead defined, 599
DBMS_SQL package, 951 overhead of encryption and decryption, 538
PARSE_IT() function queries, enhanced by index-organized
DEBUG package, 802 tables, 220, 223
substituting for% and \, 802 quer~es, enhanced by using overflow segments, 226
parsing, 191 requirements, People web application, 825
hard and soft parses, 191 views and, 561
stage in SQL statement execution, 190 performance optimization, 707
PARTITION BY clause AUTOTRACE tool, 718
LAG() and LEAD() functions, 691 benchmarking, 709
partition clause best practice, 708
analytic functions, 686, 688 bind variables and, 710
partitioned tables, 230, 708 bulk fetches, 733
query plan columns, 717 design time activity, 707
require the use of CBO, 196 execution speed of control statements, 393
passing parameters see parameters. EXPLAIN PLAN statement, 716
PASSWORD EXPIRE clause manual recompiling of invalid modules, 751
CREATE USER statement, 85 maximizing number of soft parses, 191
passwords pipelined functions, 681
tuning tools, 707
encryption, 535
using materialized views, 568
HIDE option, 324
using metrics, 709
message digests, 540
using object views, 568
password protecting roles, 517
using the showsql.sql script, 778
resetting, 85
performance problems
specifying in CREATE USER statement, 84, 501
SYS and SYSTEM user accounts, 14 dictionary managed temporary tablespaces, 179
user name and, ATM/PIN analogy, 500 finding bottlenecks using DEBUG timestamps, 817
function-based indexes using user-defined
pattern matching see LIKE operator.
functions, 295
PAUSE command, SQL*Pius, 36
indexes on child table foreign keys, 290
PCTFREE attribute
memory available too small for SGA, 175
ALTER INDEX statement, 266
reliance on default SYSTEM tablespace, 233
CREATE INDEX statement, 263
perslstance
monotonically increasing sequence numbers, 292
object instances into a database, 621, 652
PCTINCREASE parameter, 179
personal names
CREATE TABLE statement, storage clause, 236
concatenating, 382
PCTTHRESHOLD clause
personalizing an Installation
CREATE TABLE statement, 226
Finding People Case Study, 826
PCTUSED attribute
pessimistic locking, 488
can't set at index creation, 270
pflles see parameter flies .
. pdf files, 936
PGA (Program Global Area), 178
People application
one of three major memory areas, 17 4
finding individual employee details, 850
shared server mode and, 161
HR sample schema and, 129
sorting data that won't fit, 170
requirements specification, 825
phantom reads
search command file, 849
ANSI transaction isolation levels and, 483
PEOPLE package
Phone shell script
Finding People Case Study, 835, 841
precursor to People application, 824
people.sql script, 846
web-enabling, 824
people_detall.sql script
PHONE_LIST_TYP object type, 132
Finding People Case Study, 850
physical reads
percent (%) character
AUTOTRACE tool statistic, 722
%s token, PUTF() and PUTF_NCHAR() procedures, 916
pipe characters <Ill
substituting for, using the PARSE_IT() function, 802
concatenation operator, 348
wildcard, 48
PIPE ROW() command, 680
Finding People Case Study, 829
cursor input to pipelined functions, 683
performance
plpellned function, 679
bimap join index effects on, 305
constraints enforcing with pre-existing indexes, 289 loading data from an external table, 684
effects of using triggers, 599 pivot function
favors packages over stand-alone procedures, 459 cursor input to pipelined functions, 681
index height and, 263 example, 682
object views alternative, 683

1084
PRINT TABLE() procedure

PL/SQL, 345 port number


alternative to MERGE statement, 699, 702 Oracle listener defaults, 155
APis positional notation
Finding People Case Study, 835 passing parameters into stored procedures, 421
based loosely on Ada language, 19 POSITIVE and POSITIVEN data types
block-based development, 346 BINARY_INTEGER sub-types, 358
bulk fetches, 733 POWER() function, 858
calling a stored procedure, 414 ppl_apl.sql script
can't reference conditional predicates from, 588 Finding People Case Study, 841
case study: debugging PL/SQL, 787 ppl_comnt.sql script
compilation errors when writing with SQL *Plus, 327 Finding People Case Study, 832
data types, with SQL equivalents, 356 ppl_cre.sql script
DBMS_JOB package, 17
Finding People Case Study, 830
DBMS_STATS package, 199
ppl_load.sql script
distinguished from SQL and SQL *Plus, 24
Finding People Case Study, 843
encrypting with the wrap utility, 461
ppl_maln.sql script, 827
error handling, 394
Finding People Case Study, 826
investigating code with the SQL *Plus DESCRIBE
master installation script, 845
command, 323
ppl_popul.sql script
language of original Oracle 7 stored procedures, 19
Finding People Case Study, 834, 845
screenshot example, 26
triggers can be written in, 579 ppl_reload.sql script
web applications based on, 824 Finding People Case Study, 845
web-based application anecdote, 17 ppl_reload.cmd command file, 844
PL/SQL functions see functions. ppl_utll-sql script
PL/SQL objects Finding People Case Study, 835
collections, 358 PPL_UTILITY package
compile_schema.sql script, 756 Finding People Case Study, 835
converting into stored procedures and functions 411 PRAGMA AUTONOMOUS_TRANSACTION directive
enabling invoker's rights, 523 ' CLEAR() procedure, 808
forcing users to access databases through, 521 INIT() procedure, 808
order of compilation not significant, 756 LOG_MESSAGE() private procedure, 446
privileges derive from defining user, 518 stored procedures, 433
PL/SQL packages see packages. PRAGMA EXCEPTION_INIT, 399
PL/SQL procedures see stored procedures. pragmas, 399
PL/SQL tables see tables, PL/SQL. precedence, 50
PL/SQL User's Guide and Reference, 442 precision
lists predefined exceptions, 396 NUMBER data types, 90
PL/SQL Web Toolkit predefined exceptions, 396
Finding People Case Study and, 853 PL/SQL exception expressions, 395
placeholders use PRAGMA EXCEPTION_INIT, 401
use of NULL values as, 354 VALUE_ERROR exception, 399
PLAN_TABLE table pre-existing Indexes
EXPLAIN PLAN demonstration, 716 performance effects, constraints enforced with, 289
.plb file extension previous values
wrap utility output files, 461 analytic functions, 690
PLS_INTEGER data type, 357 primary key constraints, 109
plus sign with parentheses can cause automatic index creation, 287
historic use with outer joins, 65 employee history table, 108
PLUSTRACE role, 570, 719 enforcing with non-unique indexes, 289
plustrace.sql script
example, 112
AUTOTRACE tool and, 719 exception handling example, 396
primary keys
PM (Product Media) sample schema, 132
populating with sequence values using a row
installation, 1032
trigger, 593
introduced, 127
setting with ALTER TABLE, 212
Oracle lntermedia and, 1038
shouldn't update, 4 79
Oracle JVM and, 1038
table joins and, 58
reference to PRODUCT_INFORMATION table, 133
PRINT command, SQL*Pius, 425
pm_maln.sql script, 1032
PRINT_DATA() procedure, 447
PMON (Process Monitor), 178
PRINT_ENAME() procedure
dynamic registration and, 155
policy function package example, 444
PRINT_SAL() procedure
security policies, 527
polymorphism, 620
package example, 444
PRINT_TABLE() procedure
example of managing subtypes, 643
porridge temperature example using the DBMS_SQL package, 949
user-defined exceptions, 397

1085
print_table.sql script

prlnt_table.sql script
example, 750 Q
version for Oracle 8.0.4 through 8.1.4, 7 49
version for Oracle 8.1.5 and above, 7 48 QS (Queued Shipping) sample schema, 135
PRIOR keyword installation, 1033
other QS_ * shipping schemas, 1034
CONNECT BY clause, 665
QS group introduced, 127
private debug procedures
qs_ * .sql scripts, 1034
DEBUG package, 793
QS_ADM schema
private procedures and functions, 445
investigating stored procedures, 147
PRIVATE_SGA parameter, 178
QS_APPLICATIONS package
Pro*C programs
investigating stored procedures, 14 7
bulk fetches, 733
QS_CS schema, 136
default is to roll back transactions, 467
qs_maln.sql script, 1033
procedural code
queries
see also stored procedures.
PL/SQL as procedural SQL extension, 345 see a/so SELECT statement.
procedural logic advanced queries, 661
basic queries using SQL *Plus, 23, 31
executing inside the database, 19
bind variables and reusability, 710
procedures, PL/SQL see stored procedures.
can contain any number of analytic functions, 689
process control statements see control statements.
combining using set operators, 66
processing statements, 189
concatenated indexes and query predicates,
product Information 280,286
OE sample schema stores, 130 consistent data formats simplify, 591
Product Media see PM schema. converting to uppercase
profiles, 34 Finding People Case Study, 829
checking with the STATUS() procedure, 811 data dictionary views queried, 119
modifying with I NIT(), 812 DML and, 46
removing with CLEAR(), 814 hierarchical queries, 661
profiles, SQL*Pius, 312 object attributes, require table aliasing, 626
PROMPT command, SQL*Pius, 324, 382 read-consistent views, 166
prompt, SQL reuse of parsed, 192
changing with the connect.sql script, 7 45 revalidate invalid views automatically, 557
prompt.sql script saving copies as scripts, 339
GLOBAL_NAME view, 1022 SQL statement category, 189
propagation of exceptions, 394, 401 subset of most DML statements, 189
properties using bind variables to make generic and
database tables, 231, 245 reusable, 710
pseudo-columns, 564, 667, 694 views as stored queries, 144, 543
LEVEL, 667-668 inline views as embedded queries, 562
ROWNUM,37,564,694 writing SQL with SQL, 684
USER, 795 query optimization, 195
Pstart and Pstop columns comparing optimizers with AUTOTRACE, 197
query plans, 717 comparing optimizers with DBMS_STATS, 199
public package variables, 449 factors affecting whether to use an index, 259, 261
concatenated indexes, 286
PUBLIC role, 122
influencing with histogram calculations, 261, 281
execute privileges with procedures, 417
full table scans and multi-block reads, 258
granting select privileges on views, 551
mode affects use of index on heap tables, 221
making the DEBUG package available, 814
mode, TKPROF tool report, 734
PUT() procedure
optimizer hints, 196, 228, 240
UTL_FILE package, 914 OPTIMIZER_MODE setting, 194, 196
DBMS_OUTPUT package, 903 skip scanning of indexes in Oracle 9i, 279
PUT_LINE() procedure stage in SQL statement execution, 190
see also DBMS_OUTPUT package. USER_TAB_MODIFICATIONS view, 120
UTL_FILE package, 915 query performance
PUT_LINE_NCHAR() procedures enhanced by index-organized tables, 220, 223
UTL_FILE package, 915 enhanced by using overflow segments, 226
PUT_NCHAR() procedure query plans
UTL_FILE package, 914 see a/so execution plans.
PUTF() and PUTF_NCHAR() procedures appearance of results and, 202
UTL_FILE package, 916 columns, 717
EXPLAIN PLAN statement, 716
produced using CBO optimization, 199
TKPROF tool report, 734
QUERY REWRITE privileges
function-based indexes need, 295

1086
REMOVE CONSTANTS() function

query rewrites records, 358


ALTER SESSION statement, 575 PL/SQL collections, 358
materialized views, 575 Recoverer (RECO), 183
Queued Shipping see QS sample schema. recovery
quotas after system crashes, a two-stage process, 206
modifying tablespace settings, 87 Archiver and, 182
option in CREATE USER statement, 85 Checkpoint and, 182
quotation marks recursive calls
see also double quotes. AUTOTRACE tool statistic, 721
not permitted in valid Oracle identifiers, 83 recursive SQL
print_table.sql script requires double, 751 hierarchical queries as an alternative to, 662
processing of DDL statements, 207
report.txt, 730
R SYS_CONNECT_BY_PATH() function
alternative to, 670
redo log buffer, 176
RAC (Real Application Clusters), 12
capacity and LogWriter, 181
RAISE statement
durability of transactions and, 484
exception handling, 405
flushing during commit operations, 468, 484
random numbers
flushing in system crash example, 205
setting variables as, 451
writing to disk in commit operations, 467
RANDOM() function
redo log flies, 170
DBMS_RANDOM package, 909
archiving, 182
RANGE BETWEEN UNBOUNDED AND CURRENT ROW
crash recovery and, 179, 207
clause, 687, 689
durability and, 483
range scans
Log Writer and, 181
concatenation, compression example, 285 LOGGING and NOLOGGING parameters, 234
function-based indexes, 299 must be at least two online, 181
reverse key indexes and, 293 not created for temporary tables, 227
ranges Oracle Managed Files covers online, 172
PL/SQL and SQL data types, 357 processing of DML statements, 204
RANK() function, 695 redo size
ranking AUTOTRACE tool statistic, 722
see also ORDER BY clause. REF cursors, 380
analytic functions, 694 Finding People Case Study
RAW data type, 94 user interface, 846
UTL_RAW package, 924 GET_EMPLOYEES() function, 842
RAWTOHEX() function, 537 ppl_api.sql script, 841, 842
RBO (Rule Based Optimizer), 195 REF data types, 655
EXPLAIN PLAN example using, 723 dangling REFs, 657
Oracle 9i Database Performance Guide and de-referencing, 657
Reference, 197 object view example, 567
query plan listing when using, 718 REF() function, 656
use of CBO recommended, 196 REFERENCES object privileges, 511
RDBMS (Relational Database Management Systems) REFERENCING clause
factors distinguishing from file systems, 465 row triggers, 591, 592
Oracle differences from other, 16 referential Integrity
READ COMMITTED Isolation level declarative integrity and, 109
default setting in Oracle, 4 73 foreign key constraints and, 113
read only transactions refex.sql file, 382
compared with read-write, 471 refresh on commit option
non-ANSI isolation level in Oracle, 483 CREATE MATERIALIZED VIEW statement, 573
SET TRANSACTION statement, 470 refresh on demand option
READ() procedure materialized views on OLTP systems, 574
DBMS_LOB package, 945 REJECT LIMIT clause
read-consistent queries, 492 CREATE TABLE statement, 216
example, 494 relational views, 544
read-consistent views relative locations
provided using rollback segments, 166 calling scripts in, with the @@ command, 341
README documentation, Oracle 91, 1041 reliability
read-write Oracle core competency, 153, 619
default setting for transactions, 4 72 Oracle redo log and, 234
RECO (Recoverer), 183 REMOVE() procedure
record variables DBMS_JOB package, 922
assignment of one to another, 359 REMOVE_CONSTANTS() function, 713
use of %ROWTYPE, 355 removing data see delete operations.

1087
renaming tables

renaming tables rollback segments, 166


ALTER TABLE statement, 244 automatic undo manangement removes need
REPLACE option, SQL*Pius to size, 167
COPY command, 833 processing of DML statements, 204
SAVE command, 337 ROLLBACK statements
REPLACE syntax, SQL example illustrating, 78
must use CREATE OR REPLACE, 414 introduced, 75
REPLACE() function, 874 TRUNCATE TABLE can't be rolled back, 249
FILE_IT() package, 805 ROLLBACK TO SAVEPOINT statement, 469
replacement character, SQL*Pius, 400 root nodes
reporting singleton branch nodes as, 263
balance totals, illustrating read consistency, 494 ROUND() datetlme function, 867
read only transactions and consistent data, 471 format masks, 869
reserved words, 82 ROUND() number function, 859
listing in SQL and PL/SQL, 347 row counts
Resource Manager poor man's row counter, 843
assigning an UNDO Quota, 167 trigger to log table modifications, 595
resource profiles row data, data blocks, 169
timing out idle sessions, 490 row directories, data blocks, 169
RESOURCE role, 505, 516 ROW EXCLUSIVE TABLE locks, 487
RESTRICT option, SQL*Pius, 310 row level security see FGAC.
GUI version, 319 ROW SHARE TABLE locks, 487
result sets row source generation, 201
multiple copies from using START WITH stage in SQL statement execution, 190
predicates, 665 row triggers, 591
use of cursors with, 373 BIUDFER_EMPLOYEES_COPY trigger, 596
RETURN data type clause defining a FOR EACH ROW trigger, 592
PL/SQL functions, 436 enforcing data integrity using, 595
RETURN statements example using, 598
neutralizing the debug code, 818 formatting input data, 591
effect on timings, 819, 820 populating primary keys with sequence values, 593
required at every function exit point, 441 %ROWCOUNT cursor attribute, 376
return types detecting zero output
explicit cursors, 373 Finding People Case Study, 848
pipelined functions, 680 ROWID and UROWID data types
RETURNING INTO clause not allowed for object type attributes, 623
INSERT INTO statement, 807 rowlds
reusability associated with keys in indexes, 255
advantages of procedures and functions, 412 sart and stop, bitmap indexes, 302
REUSE option selecting by
CREATE TABLESPACE statement, 172 Finding People Case Study, 842
REUSE STORAGE clause ROWNUM pseudo-column
TRUNCATE TABLE statement, 250 ALL_ OBJECTS view, 37
reverse engineering scripts, 759 inadequacy for top * queries, 564
reverse key Indexes, 292 length of service exam pie, 694
REVERSE keyword rows
FOR loops, 392 accessing two at the same time, 666
REVERSE() function assigning to a variable with singleton SELECTs, 384
UTL_RAW package, 930 database table contents held in, 44
revoking object privileges, 507, 510 rows processed
revoking system privileges, 503 AUTOTRACE statistics, 723
right outer joins, 64 %ROWTYPE data type, 355
derived from database table, 363
RLS see FGAC.
ROWTYPE object
roles, 512
pipelined function example, 682, 683
DBA role, 84
RPAD() function, 874
default roles avoid password protection, 518
formatting results
enabling and disabling, 515
Finding People Case Study, 84 7
password protecting, 517
RTRIM() function, 875
PLUSTRACE role, 570
pre-defined roles, 505 RULE setting
properties, 514 OPTIMIZER_MODE, 196
PUBLIC role, 122 RUN() procedure
granting select privileges on views, 551 DBMS_JOB package, 921
security administration uses, 13 running totals
rollback processing calculating using an analytic function, 687
component tasks and cost, 468
DDL execution cannot be rolled back, 82

1088
scripts

s colprivs.sql script, 985


comments.sql script, 148·149, 986
compbody.sql script, 752
salary calculation example compile_schema.sql script, 756·757, 759
implicit and explicit cursors, 377 compproc.sql, 754
Sales History see SH sample schema. comptrig.sql script, 755
sales organization compview.sql script, 755
new sample schemas based on, 126 connect.sql script, 7 45
SALES table controlling user input with ACCEPT, 325
central role in SH sample schema, 137 createctl.sql script, 767, 769
SALES_REP object type create_tab_sync.sql script, 684
company employees example, 650 creating comments on sample schema
sample schemas, 125 installation, 148
comments created on installation, 148 dbls.sql script, 139, 769, 976
dependencies amongst the schemas, 1028, 1038 dblsl.sql script, 771
technological dependencies, 1038 dclist.sql script, 97 4
gradual approach to learning, 138 demobld.sql script, 1026
installing the schemas, 1025 deptemps.sql script, 330
manual installation, 1028 desc.sql script, 141, 983
order of installing, 1028, 1038 dlist.sql script, 973
using the DBCA, 1026 example to list database objects, 139
introduced, 13 example to list table details, 141
obtaining information about, 139 excprop.sql script, 402
stored procedures, 14 7 exttabs.sql script, 992
using for simple queries, 31 flat.sql script, 7 46, 767
SAVE command, SQL*Pius, 337 free.sql script, 772, 77 4
SAVEPOINT statement, 469 get* .sql scripts, 759
savepolnts getallcode.sql script, 762
use recommended in modular code, 469 getallviews.sql script, 766
scalability getaview.sql script, 1003
benchmarking to scale, 708 getcode.sql script, 761, 1008
Oracle core competency, 153 getobject.sql script, 759
scalar attributes getview.sql script, 764
stored in PL/SQL records, 358 glogin.sql script, 34, 312, 744
scalar data types hlpbld.sql script, 334
storing with objects and collections, 134 hrcomment.sql script, 148
scale hr_main.sql script, 1029
NUMBER data types, 90 if_then_else.sql script, 386, 389
Scheduled Tasks Interface, 844 index.sql script, 775
SCHEMA option indexes.sql script, 1016
CREATE TABLE statement, 106 invalid.sql script, 766
schemas login.sql script, 34, 313, 336, 744
distinguished from users, 12, 500 mksample.sql script, 1028
scon and the new 9i sample schemas, 125 objtab.sql script, 994
oe_main.sql script, 1031
SCN (System Chance Numbers), 467
scope people.sql script, 846
ALTER SYSTEM statements, 164 people_detail.sql script, 850
data dictionary views, 120 plustrace.sql script, 719
PL/SQL variables and constants, 352 pm_main.sql script, 1032
REF data types, 655 potential problems in using temporary files, 7 43
user-defined exceptions, 404 ppl_api.sql script, 841
SCOTT sample schema ppl_comnt.sql script, 832
ppl_cre.sql script, 830
dbls.sql script example, 770
ppl_load.sql script, 843
installing the schema, 1025
ppl_main.sql script, 826, 845
relationship to 9i HR schema, 127, 128
ppl_popul.sql script, 834, 845
structure and relation to 9i samples, 125
ppl_reload.sql script, 844
SCOTT user accounts, 27
ppl_util.sql script, 835
Scott, Bruce
print_table.sql script, 748, 751
scan sample schema and, 126
prompt.sql script, 1022
scripts, 339
qs_main.sql script, 1033
automating benchmarking with, 708 refex.sql script, 382
availability as downloads, 139 reverse engineering scripts, 759
bigdate.sql script, 7 45 running from a URI, 314
calling from a web server, 315 saving in files, 141
case.sql script, 389 scope for documenting, 309
character string removal, 713 sh_main.sql script, 1036
colltypes.sql script, 994
showspace.sql script, 780

1089
scripts (Cont'd)

scripts (Cont'd) SYS_CONNECT_BY _PATH() function, 670


showsql.sql script, 777 TREAT() function, 644
tableinfo.sql script, 980 using for simple queries, 32
tabprivs.sql script, 983 view definitions, 146
users.sql script, 1021 WHERE clause, 48
utlsample.sql script, 1025 selectivity
utlxplan.sql script, 716, 1037 column choice in concatenated indexes, 280
utlxpls.sql script, 717 self documenting schemas, 148
value of maintaining a repository of, 7 41 self joins, 65
versions.sql script, 317 EMPLOYEES table, HR sample schema, 129
viewrep.sql script, 1004 SELF parameter
scrolling through result sets, 36 member functions, 634
scrubbing data, 835 self-referencing foreign keys, 65
SECURE_DML trigger self-referencing tables
EMPLOYEES table, HR sample schema, 128 hierarchical queries, 661
SECURE_EMPLOYEES trigger, 610 self-referential constraints, 115
security, 499 semantic analysis
advantages of procedures and functions, 412 function of the statement parsing process, 191
data security, 535 sequence values
database security overview, 500 populating primary keys with, using a row
fine grained access control, 525 triggers, 593
granting no direct user privileges, 521 server parameters
involves components other than the database, 500 server parameter files, 164
People search command file and, 849 UTL_FILE_DIR and OPEN_CURSORS, 163
PL/SQL functions, 518 server processes
privilege model used by Oracle, 13 architecture diagram, 184
use of roles in administering, 13 communicating with user processes, 160
restricting access with views, 547 each has one PGA, 178
risks, SYS and SYSTEM account passwords, 14 monitored by PMON, 178
roles, 512 shared server mode uses fewer, 161
stored procedure, 415 use of buffer caches, 175
system and object privileges, 501 server round trips
using constraints in views, 551 AUTOTRACE tool statistics, 722
web users, setting within the database, 535
SERVERERROR triggers
security policies
system event triggers, 605
effects compared to views, 528 service registration, 155
FGAC implemented through, 526
client connection to databases, 155
SEED() procedure
session control statements
DBMS_RANDOM package, 907
SQL category, 43
segments, 166
session state
overflow segments, 225
storage in the UGA, 178
SMON will clean up temporary segments, 179
session tlmeouts
SELECT* FROM EXTERNAL TABLE cursor, 684
resource profiles, 490
SELECT COUNT(*) statement
SESSION_ROLES view, 515
temporary table example, 22 7
SESSION_USER
SELECT object privilege, 506
distinguished from CURRENT_SCHEMA for stored
select operations procedures, 430
TKPROF tool execution report, 732 sessions
SELECT statements reporting on with showsql.sql script, 777
causing migration of instances to dependent temporary tables lasting for, 227
objects, 632 SET AUTOTRACE statement, 257, 719
clauses of, 46 variations tabulated, 724
conditions attached to in compound queries, 66
SET CONSTRAINTS statement, 4 73
CONNECT BY clause, 665
SET DESCRIBE DEPTH ALL command, 624
formatting, 4 7
SET EVENTS option
FROM clause, 46
GROUP BY and HAVING clauses, 54 ALTER SESSION statement
IS DANGLING predicate, 658 enabling SQL_TRACE, 727
TKPROF tool, 738
IS OF predicate, 644
set operators, 66
multi-table selects, 50
INTERSECT statements, 69
nested, free.sql script and, 77 4
MINUS statement, 69
ORDER SIBLINGS BY clause, 668
UNION ALL statement, 68
OVER keyword, 686, 687
UNION statement, 67
PRIOR keyword, 666
SET ROLE and SET ROLE ALL statements, S15
singleton SELECTs and, 384
sorting results with ORDER BY, 52 SET ROLE NONE statement, 520
START WITH predicate, 663

1090
SQL Reference documentation

SET SERVEROUTPUT ON statement, 478 single Inheritance, 620


calling a stored procedure, 414, 426 single slcn-on, 311
DBMS_OUTPUT package and, 903 singleton branch nodes, 263
SET SERVEROUT ON FORMAT WRAPPED singleton SELECTs, 384
statement, 662 implicit cursors as alternative to, 385
SET TRANSACTION ISOLATION SERIALIZABLE site profiles, SQL*Pius, 312
statements, 472 SIZE clause
SET TRANSACTION statement, 469 ALTER TABLESPACE statement, 169
SET UNUSED COLUMN clause CREATE TABLESPACE statement, 169
ALTER TABLE statement, 241 skip scanning of Indexes, 278
SET_APPLICATION_INFO package, 777 concatenated indexes, 285
SGA (System Global Area), 174 slipping Interval problem, 920
architecture diagram, 184 SMON (System Monitor), 179
block buffer cache, 175 extent coalescing, 179
large pool, 177 snapshots see materialized views.
one of three major memory areas, 17 4 soft parse, 191
shared pool, 176 view performance and, 561
SH (Sales History) sample schema, 137 SORT BY clauses
installation, 1035 temporary files and, 170
introduced, 127 SORT_AREA_SIZE setting, 194
sh_maln.sql script temporary storage of results and, 203
sh_ * .sql scripts and, 1036 sort= option, TKPROF, 737
shadowing see overriding. sorting
shapes subtyplng example, 639 see a/so ORDER BY clause.
Shared Global Area see SGA. AUTOTRACE tool statistics, 722
shared pool, SGA, 176 object types using MAP methods, 639
checking, function of statement parsing, 191 SELECT statement results with ORDER BY, 52
locking by users with unique queries, 712 by multiple columns, 53
maximizing use with functions and procedures, 710 SOUNDEX() function, 875
PL/SQL statements stored in, 346 source code
reuse of parsed queries, 192 retrieving procedure code from the dictionary, 461
shared server mode space
compared to dedicated server, 161 see also tablespaces; white space.
processes store session data in large pool, 177 physical space information from showspace.sql
UGA stored in large pool, 178 script, 780
using SQL_TRACE in, not recommended, 726 specifications see package specification; type
short names specification.
data dictionary views, 1023 SPFILE option
SHOW command, SQL*Pius, 326 ALTER SYSTEM statement, 164
environment settings and, 326 spoofing
SHOW ERRORS, 327, 328 application contexts and, 530
SHOW ERRORS PROCEDURE SHOW_EMP syntax, 328 preventing with views, 553
SHOW PARAMETERS command, 328 stored procedures and, 431
SHOW ERROR command, SQL*Pius SPOOL command, SQL*Pius, 326
subtype creation errors, 646 spooling
SHOW ERRORS command, SQL*Pius
installation events
comp* scripts query after a recompile, 752 Finding People Case Study, 827
trigger creation syntax errors, 584 limits on DBMS_OUTPUT package, 788
SHOW PARAMETERS statement, 97 output settings
SHOW_OBJECTS example procedure, 521, 524 Finding People Case Study, 846
showspace.sql script, 780 tables to a control file
example, 782 createctl.sql script, 768
showsql.sql script, 777 SQL (Strucured Query Language), 42
example, 779 calling member functions, 634
SID (Systems Identifier) distinguished from SQL *Plus and PL/SQL, 24
SID_LIST_LISTENER setting, 156 history and status, 42
SIGN() function, 860 Oracle extensions to standard SQL, 661
SIGNTYPE data type reserved words, 82
BINARY_INTEGER sub-type, 358 screenshot example, 25
SILENT option, SQL*Pius, 311, 747 writing SQL with SQL, 684
Finding People Case Study, 844 SQL Implicit cursor, 375
versions.sql example script, 318 SQL Reference documentation, 698

1091
SQL statements

SQL statements SQL_TRACE, 725


hashing, 192 enabling at system or session level, 726
importance of isolating code, 712 third-party applications, 728
logging the statements which fired triggers, 613 using TKPROF tool with, 729
processing and execution by Oracle, 189 capturing wait events, 738
recursive SQL, 207 SQL-92
stages in execution, 190 compliance, 43
execution summary flowchart, 201 transaction isolation levels defined, 482
three types of statement, 189 SQLCODE variable, 407
user event triggers and, 605 SQLERRM variable, 407
value of storing in a script repository, 741 SQLPATH environment variable
view definitions, 146 searched for login.sql files, 313
SQL *Loader utility storing scripts in, 7 42
createctl.sql script, 767, 769 sqlplus command, 26, 27, 310
direct path load can use NOLOGGING clause, 235 sqlplusw command, 319
external tables replace, 214 staging tables
SH sample schema installation, 1035 Finding People Case Study, 833
SQL*Net stand-alone procedures
see a/so Oracle Net Services. definition with CREATE OR REPLACE, 413
execution plans, 571 STANDARD package
AUTOTRACE tool statistics, 722 predefined exceptions, 401
SQL*Pius buffer, 336 standards
EDIT command compared to, 337 see a/so ANSI.
SQL*Pius Interface, 23, 309 ANSISQL,42
ACCEPT command, 324 OIP as industry-standard LDAP server, 129
behavior in locating executable files, 7 42 password encryption, 536
built-in editor, 337 star schema table design, 137
example using, 338
START command, SQL*Pius, 314
built-in help, 332
starting scripts, 340
installing, 334
START WITH predicate
carriage returns and prompts, 4 7
command line tool SELECT statements, 663
scope for personalizing, 309 startup and shutdown
commands for which HELP is available, 334 triggering statements, 581
connecting to a database, 27 startup options, SQL*Pius, 310, 318
remote database services, 29 state storage
COPY command, 833 between trigger executions, 595
day to day use, 319 bind variables and, 330
default is to commit transactions, 467 global package variables, 448
default user accounts, 27 package state is unique to a session, 450
DESCRIBE command, 322 statement level consistency, 477
distinguished from SQL and PL/SQL, 25 verfiying user privileges, 584
EDIT command, 337 statement triggers, 583
environment settings, 326 BEFORE and AFTER triggers, 591
executing scripts in, 141 example using, 598
execution command character, 339, 348 cascading triggers, 587
HOST commands, 341 conditional predicates, 588
introduced, 14 example to log table modifications, 585
manual installation of sample schemas, 1028 capturing the statement type, 589
PROMPT command, 324 logging statements which caused firing, 613
SAVE command, 337 modifying, 587
screenshot example, 25 static Initialization flies
SHOW command, 326 server parameter files as alternative to, 164
simple queries, 31 static Initialization parameters, 163
START command, 314 UTL_FILE_DIR, 164
starting up from the command line, 26 static methods
starting up using a GUI, 30, 318 compared to member methods, 633, 635
startup options, 310 one of three method types, 633
user interface statistics, AUTOTRACE tool, 721
Finding People Case Study, 846 statistics option, 724
using AUTOTRACE to compare optimizers, 197 STATUS() procedure
value of, 15 DEBUG package, 793, 809, 811
VARIABLE command, 329 STORAGE clauses
SQL*Pius User Guide and Reference see a/so CREATE TABLE statements.
obsolete commands, 334 CREATE * statements, 235
SQL/DS data types, 104

1092
SYSTEM schema

storage space subtypes


see a/so quotas. example of creating, 640
out-of-line storage, 94 example of managing, 642
table spaces introduced, 639
investigating with free.sql script, 772 subtyping FINAL object types causes an error, 646
stored memory area see SQL *Plus buffer. SUM() function, 890
stored procedures, 412 deficiencies with running totals, 687
accessible with SQL *Plus DESCRIBE command, 323 doesn't support INTERVAL data types, 673
advantages over anonymous PL/SQL, 411 summary Information
API to database, 412 using GROUP BY clauses, 54
associated with object types are methods, 633 supertypes
AUTHID directive, 430 example of managing, 642
compared with functions, 436 introduced, 639
compilation errors after testing with SQL *Plus, 519 supplied packages
DBMS_JOB package, 917 DBMS_STATS package, 199
DBMS_LOB package, 934 Supplied PL/SQL Packages and Types
DBMS_OUTPUT package, 902 Reference, 759, 901
DBMS_RANDOM package, 904 supporting objects
DBMS_SQL package, 948 CREATE TABLE AS SELECT doesn't duplicate, 118
dependencies, 455 swap routine
displaying for a sample schema, 147 overloading, 453
executing, 414 using IN OUT parameters, 427
calling from anonymous PL/SQL, 426 Sybase
introduced with Oracle 7, 19
Oracle differences from, 16
listing using the data dictionary, 460
synonyms
local declarations, 429
event attribute functions, 611
overloading, 452
package specification with two procedures, 443 short names, data dictionary views, 1023
packaged procedures preferred, 459 writing SQL with SQL, 684
syntax check
parameters, 417
add new parameters as last, 423 function of the statement parsing process, 191
common errors in passing, 423 syntax errors
default values, 422 trigger creation, 584
OUT parameters, 424 SYS schema
recursive, hierarchical query alternative, 662 data dictionary views maintained in, 971
referenced object changes invalidate, 456, 457 default tablespace properties shouldn't be
retrieving code from the database, 460 changed, 234
stand-alone and packaged, 443, 459 SYS user accounts, 27
subject to locking, 484 introduced, 14
treated as atomic, 477 owns supplied packages, 901
use promotes query reusability and performance, 710 SYS_CONNECT_BY_PATH() function, 897
UTL_FILE package, 909 SELECT statements, 670
string comparisons SYS_CONTEXT() function
DEBUG package application contexts and, 531
searching for matches in strings, 796 SYSDATE() function, 96, 868
string manipulation functions CURRENT_TIMESTAMP column alternative in Oracle
listed with syntax and examples, 878 9i, 494
WHO_CALLED_ME() procedure, 797, 800 statement trigger example, 586
STRING() function timestamp datatype example, 99
DBMS_RANDOM package, 906 system control statements
strings see character strings. SQL category, 43
striping see FGAC. system crashes
strongly-typed REF CURSORs, 381 effects of during DML activity, 204
stubs startup after, 206
use of NULL values as, 354 system errors
SUBMIT() procedure triggering statements, 581
DBMS_JOB package, 919 system event triggers, 604
sub-queries system privileges, 13, 501
START WITH predicate, 663 CREATE SESSION statement, 84
sub-query restriction clauses, 555 DBA database roles, 84
subschemas predefined database roles, 506
ONLINE CATALOGUE subschema, 132 QUERY REWRITE
SUBSTR() function, 876 function-based indexes need, 295
DBMS_LOB package, 946 SYSTEM schema
FILE_IT package, 805 default tablespace properties shouldn't be
UTL_RAW package, 926 changed, 234
WHO_CALLED_ME() procedure, 799 SQL *Plus help owned by, 334

1093
SYSTEM tablespace

SYSTEM tablespace, 165 types of table, 212


identifying and eliminating invaders, 233 external tables, 214
problems with use as default, 233, 504 heap tables, 212
SYSTEM user accounts, 27 index-organized tables, 220
introduced, 14 other table types, 230
SYSTIMESTAMP() function, 868 temporary tables, 226
tables, PL/SQL, 361
choice of collection type, 372
declarations and value assignment, 362
T deleting records, 364
graphical representations, 363
tab character insert operations, 369
substituting, in PARSE_IT() function, 803 multi-column, must use dot notation, 364
table aliases see aliasing. nested tables, 370
table directories, data blocks, 169 PL/SQL collections, 358
table functions, 677 referencing values in, 364
advantages, 684 TABLESPACE clause
pipelining, 679 ALTER TABLE statement, 231
table joins, 57 CREATE TABLE statement, 214, 231
analytic functions, 688 tablespaces, 165
eliminating by denormalization allocating when creating users, 500
Finding People Case Study, 830 differing block sizes in Oracle 9i, 176
hierarchical queries may now include, 670 introduced, 16
inadequate information can lead to Cartesian investigating with free.sql script, 772
products, 58 listing for database objects, 141
inner joins, 62 modifying tablespace settings, 87
join conditions, 59 quotas, 88
natural joins, 61 nested tables stored in, 370
outer joins, 63 Oracle Managed Files covers, 172
self joins, 65 standard, used as temporary, 171
using the WHERE clause, 50 storage attributes inherited from, 235
TABLE NAME option storage units for user accounts, 83
CREATE TABLE statement, 106 tabprlvs.sql script
table privileges, 509 DBA_TAB_PRIVS view, 983
table scans see full table scans. TCP/IP
table.column%type Oracle listener default protocol, 155
defining OUT parameters in stored procedures, 426 temporary flies, 170
tablelnfo.sql script potential problems in using for scripts, 7 43
DBA_TABLES view, 980 temporary lnconslsteocles, 477,478
tables, database, 44, 211 temporary segments, 166
aliasing to access object type attributes, SMON will clean up, 179
626,644,652 temporary tables, 226
altering columns in existing tables, 238 SQL-92 Full compliance and, 43
caching tables subjected to frequent full scans, 246 transaction-specific, 250
changes to, which invalidate views, 555 TRUNCATE TABLE statement, 250
creating a control file with createctl.sql, 767 temporary tablespaces, 166
creating and managing, 81, 106 dictionary managed and locally managed, 171
debugging PL/SQL case study, 789 option in CREATE USER statement, 85
DUAL table in the data dictionary, 855 temporary tables use, 227
duplicating with CREATE TABLE AS SELECT, 117 use in index preparation, 255
Finding People Case Study, 830 TERMINATE() procedure
populating, 843 DBMS_RANDOM package, 909
use of staging tables, 833 terminology, 11
flattening using a pipelined function, 683 see a/so naming conventions.
join views and, 554 testing
lookup tables and caching, 237 company employees subtyping example, 652
moving to new tablespace or storage, 244 manual recompiling of invalid modules, 751
object types as columns in, 624 People application, 825
OE sample schema, 132 time zones, 99
properties, 231 TIMED_STATISTICS parameter, 725
changing miscellaneous properties, 245
enabling at system or session level, 726
querying using SELECT, 32
TKPROF tool execution report, 732
renaming, 244
timer, SQL*plus
restricting access to stored procedures, 432
evaluation of control statements, 393
script to list details, 141
star schema design, 137 TIMESTAMP data type, 98
DEBUG package
finding performance bottlenecks, 817
timing code only works with Oracle 9i up, 819

1094
TRIM() procedure

TIMESTAMP WITH LOCAL TIMEZONE data transaction Isolation, 482


type, 101, 102 isolation levels defined by ANSI, 482
TIMESTAMP WITH TIMEZONE data type, 99 setting transaction isolation levels, 4 72
timing calls to DEBUG.F(), 818 transaction management, 465
timing queries see a/so commit operations; rollback processing.
DBMS_UTILITY.GET_TIME utility, 711 ACID transaction properties, 4 75
TKPROF tool, 728 COMMIT and ROLLBACK introduced, 75
command line options listed, 736 commit processing, 467
extracting the worst-performing queries, 737 no BEGIN statement in Oracle, 466
full information requires Oracle 9i, 738 redo log buffer, 17 6
introduced, 725 redo log files, 170
report.txt analysis, 732 transactions
wait times, 737 distributed transactions, use of Recoverer, 183
TNS (Tranparent Networking Substrate) must be terminated explicitly, 467
tnsnames.ora file, 157 temporary tables lasting for, 227
TNS_ADMIN environment variable, 156 triggers and transactions, 609
tnsnames.ora file triggers rolled back with, 586
configuring client tools, 157 transaction-specific temporary tables
servers, may be multiple, 158 COMMIT preferable to TRUNCATE TABLE, 250
TO_CHAR() functions TRANSLATE USING() function, 886
partitioning on the results of, 697 TRANSLATE() function, 876
three types, 879 UTL_RAW package, 927
using to spell out numbers, 702 TRANSLITERATE() function
TO_CLOB() function, 882 UTL_RAW package, 927
TO_DATE() function, 96, 882 TREAT() function
date formatting options, 887 SELECT statements, 644
using to spell out numbers, 702 use in overriding example, 645
TO_DSINTERVAL() function, 883 trigger body
TO_LOB() function, 883 statement trigger example, 586
TO_NCHAR() function, 882 trigger names, 580
TO_NCLOB() function, 882 trigger restrictions, 582
TO_NUMBER() function, 884 triggered actions, 582
people_detail.sql script, 850 triggering statements, 581
TO_TIMESTAMP() function, 885 row triggers, 591
TO_TIMESTAMP_TZ() function, 885 triggers, 579
TO_YMINTERVAL() function, 885 BIFER_ALL_UPPER_DATA trigger, 608
tokens BIFER_FOO_ID_PK trigger, 594
PUTF() and PUTF_NCHAR() procedures, 916 BIUD_EMPLOYEES_COPY trigger, 585, 595
TOO_MANY_ROWS BIUD_FOO trigger, 584
predefined exception, 396 BIUDFER_EMPLOYEES_COPY trigger, 596
toolkit, SQL, 741 BIUFER_EMPLOYEES_DEPARTMENT_ID trigger, 580
BIU_FER_DEBUGTAB trigger, 790, 807
top* values
can use on temporary tables, 227
analytic functions, 694
DDL statements not allowed, 609
inline views, 564
DEBUG package use with, 817
TOTAL_EMP lnllne view, 562
DEBUGTAB table, 790
touch count
displaying for views, 146
managing buffer caches, 175 displaying using desc.sql script, 143
trace flies enabling and disabling triggers, 607
deadlocks lead to the creation of, 486 HR sample schema, 128
generated on database servers, 730 INSTEAD OF triggers, 599
report.txt, 730 I0 _BI FER_DEPT_EM P_VIEW trigger, 604
_trace_flles_publlc parameter main parts, 580
init.ora files, 730 materialized views as alternative, 57 4
TRACE_LEVEL_LISTENER settings, 157 order of firing unpredictable, 583
traceonly option performance effects, 599
AUTOTRACE tool, 723, 724 printing in database consistency example, 4 77
tracing, 726 querying the data dictionary about triggers, 610
Oracle Net operations, 157 row triggers, 591
training department system event triggers, 604
heap table example, 212 transactions and, 609
transaction control statements, 466 types of trigger, 583
SAVEPOINT and ROLLBACK TO SAVEPOINT UPDATE_NAME_COMPANY_PHONE_BOOK trigger, 559
statements, 469 user event triggers, 605
SET TRANSACTION statement, 469 TRIM() function, 877
SQL category, 43 TRIM() procedure
DBMS_LOB package, 946

1095
triple DES

triple DES, 536 SQL *Plus script example, 316


troubleshooting using SQL *Plus from, 26
DEBUG package, 817 UNKNOWN value
TRUNC() datetlme function, 869 NULL comparisons and, 51
TRUNC() number function, 860 UNLIMITED keyword
TRUNCATE TABLE statement, 249 ALTER USER statement, 88
can use on temporary tables, 227 CREATE TABLE statement, 217
commits before and after execution, 249 UNLIMITED TABLESPACE system privilege, 506
truth tables UPDATE CASCADE logic
bitmap indexes, 301 deferrable constraints and, 4 79
tuning see performance optimization. UPDATE object privileges, 506, 511
two-phase commit, 184 update operations
type body, 622 blocking, wait information from, 738
methods implemented in, 634 Finding People Case Study
type conversion errors nightly updates, 844
external tables and, 217 indexed tables, result in unused space in leaf
%TYPE data type, 355 nodes, 269
type evolution, 628 insert or, MERGE statement, 698
materialized views, 573
TYPE IS RECORD syntax, 358
TKPROF tool execution report, 732
type matching
updating object views, 567
parameters in stored procedures, 426
updating through a view, 558
type specification, 622
using object views and a client-side cache, 568
methods defined in, 633
UPDATE statements, 71
using implicit cursors, 375

u UPDATE_CHECK argument
DBMS_RLS.ADD_POLICY procedure, 529
UPDATE_JOB_HISTORY trigger
UGA (User Global Area) EMPLOYEES table, HR sample schema, 129
one of three major memory areas, 17 4 UPDATE_NAME_COMPANY_PHONE_BOOK trigger, 559
session state storage, 178 UPDATING conditional predicate
UID() function, 897 BIUD_EMPLOYEES_COPY trigger, 598
unconstrained loops, 390 statement triggers, 588
UNDER keyword UPGRADE INCLUDING DATA option
subtypes, 641 ALTER TABLE statement, 630
underscore {_) character UPGRADE NOT INCLUDING DATA option
sorts last in index, 268 ALTER TABLE statement, 630
wildcard character, 48 UPPER() function, 294, 877
UNDO mechanism formatting input data, 592
automatic undo manangement, 167 queries
durability of transactions and, 484 Finding People Case Study, 829
rollback segments and, 166 selecting candidate queries for bind variables, 714
UNDO Quota, 167 URI (Uniform Resource Identifiers)
UNDO tablespaces running a script from, 314
automatic undo manangement, 167 UROWID data type
processing of DML statements, 204 not allowed for object type attributes, 623
UNDO_MORE parameter, 167 user accounts
UNDO_RETENTION parameter, 167 avoiding administrative and sample accounts, 84
Unicode creating a new database user, 84, 500
use in Oracle 9i, 92, 93 Finding People Case Study, 826
UNION ALL statement, 68 creating and managing, 81
UNION statement, 67 distinguished from schemas, 12, 500
createctl.sql script, 768 dropping a database user, 89
unique constraints, 115
indexes defined for a user, 775
can cause automatic index creation, 287 introduced, 12
enforcing with non-unique indexes, 289 locking and unlocking, 86
exception handling example, 396 modifying, reasons for, 85
user accounts, SQL*Pius tool, 27
use with bitmap join indexes, 305
unique indexes user defined see user-defined.
automatically created to enforce constraints, 287 user event triggers, 605
compression suitability, 278 available functions, 607
Universal Time Coordinated (UTC), 99 BEFORE DROP trigger, 606
UNIX user Interface
repopulating tables in a nightly update, 845 Finding People Case Study, 846
setting environment variables, 7 43

1096
variable-length data types

user privileges USING clause


CREATE OR REPLACE VIEW statement pre MERGE statement, 700, 703
serves, 549 USING to_char() clause
creating a view, 544 EXECUTE IMMEDIATE statement, 711
database roles as named collections of, 512 UTC (Universal Time Coordinated), 99
Finding People Case Study, 828 UTF8 (UCS Transformation Format) datatype, 93
granting no direct privileges, 521 UTL_FILE package
object privileges, 506 DEBUG package, 805, 806
system and object privileges, 13, 501 procedures and functions, 909
verifying using a statement trigger, 584 UTL_FILE_DIR parameter, 163
user processes init.ora files, 791, 910
connecting to a database instance, 155 troubleshooting the DEBUG package, 817
server processes, communication with, 160 UTL_RAW package
user profiles, SQL*Pius, 313 functions, 924
defining editors within, 336 utlsample.sql script
using login.sql script, 7 44 installing the SCOTT schema, 1025
USER pseudo-column utlxplan.sql script, 716
DEBUG package, 795 utlx* .sql scripts and, 1037
user support utlxpls.sql script, 717
SQL_TRACE and, 728
USER() function, 898
statement trigger example, 586
USER_ prefix v
data dictionary views, 122
USER_COL_COMMENTS view, 149 V$ tables, 192
USER_DUMP_DEST directory PLUSTRACE role, 719
V$0PTION view
trace files, 726
USER_JOBS view, 183
checking option availability, 1057
V$PARAMETER view
USER OBJECTS view, 36, 521
investigating database parameters, 165
co~p* scripts query for invalid objects, 752
V$SESSION view
compiled stored procedures, 456
listing stored procedures, 460 showsql.sql script and, 777
showspace.sql script example, 782 V$SQL view, 192
USER_SEGMENTS view, 780 V$SQLAREA table
USER SOURCE view dynamic performance view, 715
retrieving procedure code from the dictionary, 460 V_$PARAMETER view, 328
USER_TAB_COLUMNS view, 120 valid Oracle Identifiers, 82
createctl.sql script, 768 table and column names in CREATE TABLE, 107
USER TAB COMMENTS view, 149 valid stored procedures
USER-TAB-MODIFICATIONS view, 120 successfully compiled. 456
USER-TAB-PRIVS view, 120, 509 validate structure clause
cre;ting database roles, 514 ANALYZE INDEX statement, 264, 265, 270
USER TABLES view, 32, 118, 120 validating Input
det;rmining the default tablespace names, 231 SQL *Plus ACCEPT command, 325
displaying definition using ALL_ VIEWS XE, 41 validation
USER TRIGGERS view, 144, 610 dependent objects, 630
using CASCADE, 630
USER-UNUSED_COL_TABS view, 243
invalidating and validating views, 555
USER=UPDATABLE_COLUMNS view, 558
using triggers, 595
USER USERS view
VALUE() function, 655
det;rmining the default tablespace names, 231
DBMS_RANDOM package, 905
USER VIEWS view, 547, 554
VALUE_ERROR exception
user-defined aggregate functions, 672, 673
people_detail.sql script, 851
example, 67 4
predefined exception, 399
user-defined data types
VALUES clause
object types as, 621
INSERT INTO statement, 840
user-defined exceptions, 397
VARCHAR2 data type, 92
associating with Oracle exception code, 401
VARIABLE command, SQL*Pius, 425
CHILD ERROR, 403
VARIABLE_ VALUE() procedure
porridge temperature example, 399
DBMS_SQL package, 962
PRAGMA EXCEPTION_INIT, 399, 400
variable-length data types
scope and visibility, 404
NVARCHAR2,93
user-defined functions
VARCHAR2,92
deterministic functions, 295
performance problems, function-based indexes, 295
users.sql script
DBA_USERS view, 1021

1097
variables

variables using constraints in, 550


declaring without data types, 355 security example, 551
defined in PL/SQL declaration section, 346, 349 validating, 555
PL/SQL, order of declaration, 353 YEARLY_HIRE_TOTALS view, 550
SQL *Plus, ampersand character identifies, 316 virtual columns
user input and SQL *Plus ACCEPT, 324 creating in relational views, 546
variables not assigned NULL values, 354 not directly updatable, 558
VARRAYs,368 virtual table functions, 677
distinguished from object types, 621 pipelining, 679
inline object constructors, 369 virtual tables
PL/SQL collections, 358 views as, 543
querying VARRAY columns, 369 visibility
table functions can return, 677 PL/SQL variables and constants, 352
version Information, SQL*Pius, 310 user-defined exceptions, 404
verslons.sql script, 317 VSIZE() function, 899
view definitions
changing, 548
object views, 567
OC_ORDERS view, 146
w
retrieving from the data dictionary, 54 7
walt events
vlewrep.sql script
capturing with SET EVENTS level 8, 728
DBA_UPDATABLE_COLUMNS view, 1004
TKPROF tool, 733, 737
views, 543
WAREHOUSES table, OE schema
ALL_ARGUMENTS view, 1009
Oracle Spatial column, 132
application security through, 511
warnings
can use on temporary tables, 227
changing NLS_DATE_FORMAT setting, 746
checking option availability with V$0PTION, 1057
consequences of renaming tables, 244
COMPANY_PHONE_BOOK view, 545
generated on subtype creation, 646
creating a view, 544
generated on trigger creation, 584
WITH CHECK OPTION constraint, 560
granting system privileges, 503
data dictionary, 118
modifying the DUAL table, 856
data dictionary views
DBA_, ALL_ and USER_ prefixes, 971 setting MAX_DUMP_FILE_SIZE to UNLIMITED, 727
short names, 1023 triggers can change values without warning, 582
DBA_* tabulated and described, 971 weakly-typed REF CURSORs, 382
DICT_COLUMNS view, 974 web applications
DICTIONARY view, 972 accessing next and previous pages, 692
dropping views, 549 application contexts and, 530, 535
extracting DDL to the file system, 764, 766 SQL_TRACE and, 728
GLOBAL_NAME view, 1022 web servers
in line views, 562 calling SQL *Plus scripts from, 315
inserting into a complex view websltes see online resources.
using INSTEAD OF triggers, 601, 604 WHAT() procedure
invalidating and validating, 555 DBMS_JOB package, 922
investigating database objects, 144 WHEN MATCHED THEN UPDATE clause
investigating database parameters, 165 MERGE statement, 700
issuing insert operations against views WHEN NOT MATCHED THEN UPDATE clause
INSTEAD OF triggers and, 600 MERGE statement, 700
join views, 553 WHEN OTHERS THEN exception handler
modifying using INSTEAD OF triggers, 604 DEBUG package, 806
materialized views, 568 nested blocks example, 404
modifying using INSTEAD OF triggers, 601 SQLCODE and SQLERRM variables, 407
my_reports view, 551 stored procedures with NOCOPY hints, 428
naming conventions for data dictionary, 122 WHERE clauses
object views, 565
binary operators, 49
performance issues, 561
DELETE statements, 75
materializing views that don't merge, 561
distinguished from HAVING clauses, 57
read only, 555
LEVEL better specified in CONNECT BY, 668
relational views, 544
SELECT statements, 48
revalidated automatically when queried, 55 7
table joins, 50, 59
scope, 120
trigger restrictions, 582
security policy effects compared to, 528
UPDATE statements, 71
updating and deleting through a view, 558
use of indexes on specified columns, 221
updating columns based on functions
using in views, 553
INSTEAD OF triggers and, 600
WHICH argument
updating using an INSTEAD OF trigger, 559
USER_* views DES3ENCRYPT() and DES3DECRYPT() procedures,
short names, 1023 536

1098
XRANGE() function
WHILE loops, 392 WITH GRANT OPTION clause
alternative to EXIT WHEN command, 392 granting object privileges, 506, 508
white space WITH OBJECT OlD clause
formatting SQL statements, 4 7 CREATE VIEW statement, 567
effects on reusability and performance, 710 WITH READ ONLY clause
LPAD() function, 668 join views, 555
SET SERVEROUT ON FORMAT WRAPPED wizard-like Interface
statement, 662 accessing next and previous pages, 692
WHO_CALLED_ME() procedure wrap around
DEBUG package, 796, 797 query output from SQL *Plus, 33
wildcard characters, 48 overcoming with print_table.sql script, 748
windowing clause, analytic functions, 686 wrap utility, 461
RANGE BETWEEN UNBOUNDED AND CURRENT output files can be compiled, 463
ROW, 687, 689 Write Lists, buffer cache, 175
Windows WRITE() procedure
case sensitivity of UTL_FILE_DIR directories, 910 DBMS_LOB package, 946
platforms supporting Oracle Personal Edition, 20 WRITEAPPEND() procedure
repopulating tables in a nightly update DBMS_LOB package, 947
Finding People Case Study, 844
Scheduled Tasks interface, 844
setting environment variables, 7 43
SQL *Plus script example, 316 X
using SQL *Plus from
command line operation, 26 XML (Extensible Markup Langauge)
with a GUI tool, 30 Oracle can make use of, 135
WITH ADMIN OPTION clause XRANGE() function
granting system privileges, 502 UTL_RAW package, 930
WITH CHECK OPTION constraint
CREATE VIEW statement, 560

1099
JOIN THE APRESS FORUMS AND BE PART OF OUR COMMUNITY. You'll find discussions that cover topics
of interest to IT professionals, programmers, and enthusiasts just like you. If you post a query to one of our
forums, you can expect that some of the best minds in the business-especially Apress authors, who all write
with The Expert's Voice™-will chime in to help you. Why not aim to become one of our most valuable partic-
ipants (MVPs) and win cool stuff? Here's a sampling of what you'll find:

DATABASES PROGRAMMING/BUSINESS
Data drives everything. Unfortunately, it is.
Share information, exchange ideas, and discuss any database Talk about the Apress line of books that cover software
programming or administration issues. methodology, best practices, and how programmers interact with
the "suits."

INTERNET TECHNOLOGIES AND NETWORKING WEB DEVELOPMENT/DESIGN


Try living without plumbing (and eventually 1Pv6). Ugly doesn't cut it anymore, and CGI is absurd.
Talk about networking topics including protocols, design, Help is in sight for your site. Find design solutions for your
administration, wireless, wired, storage, backup, certifications, projects and get ideas for building an interactive Web site.
trends, and new technologies.

JAVA SECURITY
We've come a long way from the old Oak tree. Lots of bad guys out there-the good guys need help.
Hang out and discuss Java in whatever ftavor you choose: Discuss computer and network security issues here. Just don't let
J2SE, J2EE, J2ME, Jakarta, and so on. anyone else know the answers!

MAC OS X TECHNOLOGY IN ACTION


All about the Zen of OS X. Cool things. Fun things.
OS X is both the present and the future for Mac apps. Make It's after hours. It's time to play. Whether you're into LEGQ®
suggestions, offer up ideas, or boast about your new hardware. MINDSTORMS™ or turning an old PC into a DVR, this is where
technology turns into fun.

OPEN SOURCE WINDOWS


Source code is good; understanding (open) source is better. No defenestration here.
Discuss open source technologies and related topics such as Ask questions about all aspects of Windows programming, get
PHP, MySQL, Linux, Peri, Apache, Python, and more. help on Microsoft technologies covered in Apress books, or
provide feedback on any Apress Windows book.

HOW TO PARTICIPATE:
Go to the Apress Forums site at http://forums.apress.com/.
Click the New User link.

Вам также может понравиться