Professional Documents
Culture Documents
Wordware Publishing Advanced SQL Functions in Oracle 10g
Wordware Publishing Advanced SQL Functions in Oracle 10g
ISBN-13: 978-1-59822-021-6
ISBN-10: 1-59822-021-7
10 9 8 7 6 5 4 3 2 1
0601
All inquiries for volume purchases of this book should be addressed to Wordware
Publishing, Inc., at the above address. Telephone inquiries may be made by calling:
(972) 423-0090
To my wife, Brenda,
and
my children, Beryl, Rich, Gen, and Mary Jo
R.W.E.
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . xiii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
v
Contents
vi
Contents
vii
Contents
viii
Contents
ix
Contents
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
x
Preface
xi
Preface
xii
Acknowledgments
xiii
This page intentionally left blank.
Introduction
Prerequisites
Some knowledge of SQL is assumed before beginning
this study, as this book is not meant to be a SQL
primer. More specifically, some knowledge of Oracle
functions is desirable, although some common func-
tions are reviewed in Chapter 1. Functions have been
refined and expanded as Oracle versions have evolved,
culminating with the latest in Oracle 10g — analytical
functions, MODEL statements, and regular expres-
sions. Additionally, the collection/object-oriented
structures of later versions of Oracle are covered and
xv
Introduction
xvi
Introduction
SELECT MAX(enrollment)
FROM
(SELECT class, COUNT(*) enrollment
FROM students
GROUP BY class)
xvii
This page intentionally left blank.
Chapter | 1
Chapter 1
Common Oracle
Functions: A
Function Review
1
Common Oracle Functions: A Function Review
Answer = SQRT(original_value)
2
Chapter | 1
Calling Simple SQL Functions
Oracle has a large number of simple functions. Wher-
ever a value is used directly or computed in a SQL
statement, a simple SQL function may be used. To
illustrate the above square root function, suppose that
a table named Measurement contained a series of
numeric measured values like this:
Subject Value
First 35.78
Second 22.22
Third 55.55
SELECT *
FROM measurement
3
Common Oracle Functions: A Function Review
Numeric Functions
In this section we present and discuss several useful
numeric functions, which we divide into the following
categories: common numerical manipulation functions,
near value functions, null value functions, log and expo-
nential functions, ordinary trigonometry functions, and
hyperbolic trignometrical functions.
Common Numerical
Manipulation Functions
These are functions that are commonly used in numeri-
cal manipulations. Examples of common numerical
manipulation functions include:
ABS — Returns the absolute value of a number or
value.
SQRT — Returns the square root of a number or
value.
MOD — Returns the remainder of n/m where both
n and m are integers.
SIGN — Returns 1 if the argument is positive; –1 if
the argument is negative; and 0 if the argument is
negative.
4
Chapter | 1
Next we present a discussion on the use of these com-
mon numerical manipulation functions. Suppose we had
a table that looked like this:
DESC function_illustrator
Now, if we typed:
SELECT *
FROM function_illustrator
ORDER BY lineno
We would get:
LINENO VALUE
---------- ----------
0 9
1 3.44
2 3.88
3 -6.27
4 -6.82
5 0
6 2.5
5
Common Oracle Functions: A Function Review
We would get:
ERROR:
ORA-01428: argument '-6.27' is out of range
no rows selected
6
Chapter | 1
SELECT lineno, value, ABS(value), SQRT(ABS(value))
FROM function_illustrator
ORDER BY lineno
7
Common Oracle Functions: A Function Review
8
Chapter | 1
Will give:
The value 3.88, when viewed from one place to the right
of the decimal point, rounds up to 3.9 and truncates to
3.8.
The second argument defaults to 0 as previously
illustrated. The following query may be compared with
previous versions, which have no second argument:
9
Common Oracle Functions: A Function Review
10
Chapter | 1
Now, if you type:
SELECT *
FROM function_illustrator
LINENO VALUE
---------- ----------
0 9
1 3.44
2 3.88
3 -6.27
4 -6.82
5 0
6 2.5
7
LINENO NVL(VALUE,10)
---------- -------------
0 9
1 3.44
2 3.88
3 -6.27
4 -6.82
5 0
6 2.5
7 10
11
Common Oracle Functions: A Function Review
SELECT LN(value)
FROM function_illustrator
WHERE lineno = 2
LN(VALUE)
----------
1.35583515
12
Chapter | 1
SELECT LOG(value, 2)
FROM function_illustrator
WHERE lineno = 2
LOG(VALUE,2)
------------
.511232637
SELECT LOG(2,8)
FROM function_illustrator
WHERE rownum = 1
Giving:
LOG(2,8)
----------
3
SELECT EXP(value)
FROM function_illustrator
WHERE lineno = 2
Gives:
EXP(VALUE)
----------
48.4242151
13
Common Oracle Functions: A Function Review
SELECT POWER(value,2)
FROM function_illustrator
WHERE lineno = 0
Which gives:
POWER(VALUE,2)
--------------
81
Ordinary Trigonometry
Functions
SQL’s ordinary trigonometry functions include:
SIN — Returns the sine of a value.
COS — Returns the cosine of a value.
TAN — Returns the tangent of a value.
DESC trig
Will give:
14
Chapter | 1
And,
SELECT *
FROM trig
Will give:
SELECT SIN(value1*2*3.1416/360)
FROM trig
Gives:
SIN(VALUE1*2*3.1416/360)
------------------------
.50000106
SELECT COS(value2*2*3.1416/360)
FROM trig
Gives:
COS(VALUE2*2*3.1416/360)
------------------------
.499997879
SELECT TAN(value1*2*3.1416/360)
FROM trig
15
Common Oracle Functions: A Function Review
Gives:
TAN(VALUE1*2*3.1416/360)
------------------------
.577351902
SELECT SINH(value1*2*3.1416/360)
FROM trig
Gives:
SINH(VALUE1*2*3.1416/360)
-------------------------
.54785487
16
Chapter | 1
Example 2: Using the COSH function to find the
hyperbolic cosine of 30 degrees:
SELECT COSH(value1*2*3.1416/360)
FROM trig
Gives:
COSH(VALUE1*2*3.1416/360)
-------------------------
1.14023899
SELECT TANH(value1*2*3.1416/360)
FROM trig
Gives:
TANH(VALUE1*2*3.1416/360)
-------------------------
.48047372
17
Common Oracle Functions: A Function Review
String Functions
A host of string functions are available in Oracle.
String functions refer to alphanumeric character
strings. Among the most common string functions are
INSTR, SUBSTR, REPLACE, and TRIM. Here we
present and discuss these string functions. INSTR,
SUBSTR, and REPLACE have analogs in Chapter 7,
“Regular Expressions: String Searching and Oracle
10g.”
INSTR('THISISATEST','IS')
-------------------------
3
18
Chapter | 1
The first character of string to search is numbered 1.
Since “is” is the search pattern, it is found in string to
search at position 3. If we had chosen to look for the
second occurrence of “is,” the query would look like
this:
INSTR('THISISATEST','IS',1,2)
-----------------------------
6
INSTR('THISISATEST','ABC',1,2)
------------------------------
0
19
Common Oracle Functions: A Function Review
SUBSTR('MYAD
------------
My address i
SUBSTR('MYAD
------------
ddress is 12
20
Chapter | 1
Here is an example of a retrieval with no third
argument, meaning it starts at begin and retrieves the
rest of the string:
SUBSTR('MYADDRESSIS123F
-----------------------
dress is 123 Fourth St.
SUBST
-----
ourth
21
Common Oracle Functions: A Function Review
SUBSTR('HAR
-----------
John Edward
SUBSTR('HARRI
-------------
, John Edward
SUBSTR('HARRISON,JOHN
---------------------
Harrison, John Edward
22
Chapter | 1
which is actually this:
SUBSTR('HARRISON,JOHN
---------------------
Harrison, John Edward
This gives:
REPLACE('THISISATE
------------------
This may be a test
23
Common Oracle Functions: A Function Review
REPLACE('THISISATEST','IS'
--------------------------
Th may be may be a test
REPLACE('THISI
--------------
This is a test
24
Chapter | 1
If the optional trim character is not present, then
blanks will be trimmed. Trim character may be any
character. The word FROM is necessary only if where
or trim character is present. Here is an example:
Which gives:
TRIM('THISSTRINGHASLEADINGANDTRAILINGSPACES
-------------------------------------------
This string has leading and trailing spaces
SELECT TRIM (both ' ' from ' String with blanks ')
FROM dual
Which gives:
TRIM(BOTH''FROM'ST
------------------
String with blanks
TRIM('F'FROM'FROGSPREF
----------------------
rogs prefer deep water
25
Common Oracle Functions: A Function Review
Example 1:
TRIM(LEADING'F'FROM'FR
----------------------
rogs prefer deep water
Example 2:
TRIM(TRAILING'R'FROM'F
----------------------
Frogs prefer deep wate
Example 3:
TRIM(BOTH'Z'F
-------------
I am asleep
In the last example, note that the blank space was pre-
served because it was not trimmed. To get rid of the
leading/trailing blank(s) we can nest TRIMs like this:
26
Chapter | 1
This would give:
TRIM(TRIM(B
-----------
I am asleep
Date Functions
Oracle’s date functions allow one to manage and handle
dates in a far easier manner than if one had to actually
create calendar tables or use complex algorithms for
date calculations. First we must note that the date data
type is not a character format. Columns with date data
types contain both date and time. We must format
dates to see all of the information contained in a date.
If you type:
SELECT SYSDATE
FROM dual
SYSDATE
---------
10-SEP-06
27
Common Oracle Functions: A Function Review
This gives:
TO_CHAR(SYSDATE,'DDMO
---------------------
10 Sep, 2006 14:04:59
SELECT TO_CHAR(LAST_DAY('23SEP2006'))
FROM dual
TO_CHAR(L
---------
30-SEP-06
28
Chapter | 1
This example illustrates that Oracle will convert char-
acter dates to date data types implicitly. There is also a
TO_DATE function to convert from characters to dates
explicitly. It is usually not a good idea to take advan-
tage of implicit conversion, and therefore a more
proper version of the above query would look like this:
SELECT TO_CHAR(LAST_DAY(TO_DATE('23SEP2006','ddMONyyyy')))
FROM dual
TO_CHAR(L
---------
30-SEP-06
SELECT TO_CHAR(LAST_DAY(TO_DATE('23SEP2006','ddMONyyyy')),
'Month dd, yyyy')
FROM dual
TO_CHAR(LAST_DAY(T
------------------
September 30, 2006
MONTHS_BETWEEN(date1, date2)
29
Common Oracle Functions: A Function Review
Here is an example:
SELECT MONTHS_BETWEEN(TO_DATE('22SEP2006','ddMONyyyy'),
TO_DATE('13OCT2001','ddMONyyyy')) "Months difference"
FROM dual
This gives:
Months difference
-----------------
59.2903226
SELECT NEXT_DAY(TO_DATE('15SEP2006','DDMONYYYY'),'Monday')
FROM dual
This gives:
NEXT_DAY(
---------
18-SEP-06
30
Chapter | 2
Chapter 2
Reporting Tools in
Oracle’s SQL*Plus
31
Reporting Tools in Oracle’s SQL*Plus
COLUMN
Often, when generating result sets with queries in Ora-
cle, we get results with odd-looking headings. For
example, suppose we had a table called Employee,
which looked like this:
DESC employee
Giving:
32
Chapter | 2
To get the output illustrated above, we used COLUMN
formatting. Had we not used COLUMN formatting, we
would have seen this:
SELECT *
FROM employee
Giving:
33
Reporting Tools in Oracle’s SQL*Plus
34
Chapter | 2
We’d see this result:
Formatting Numbers
For simple formatting of numbers, we can use 9n just
as we used an, where n is the width of the output field.
For example, if we format the empno field to make
it shorter, we can use:
and type:
EMPNO ENAME
----- ----------
101 John
102 Stephanie
104 Christina
108 David
111 Kate
106 Chloe
122 Lindsey
35
Reporting Tools in Oracle’s SQL*Plus
EMPNO ENAME
----- ----------
### John
### Stephanie
### Christina
### David
### Kate
### Chloe
### Lindsey
Gives:
36
Chapter | 2
111 Kate 45,000 49000.00
106 Chloe 33,000 44000.00
122 Lindsey 40,000 52000.00
COFFEE_FUND
-----------------------
EMPNO NUMBER(3)
AMOUNT NUMBER(5,2)
SELECT *
FROM coffee_fund
Gives:
EMPNO AMOUNT
----- ----------
102 33.25
104 3.28
106 .35
101 .07
37
Reporting Tools in Oracle’s SQL*Plus
produces:
EMPNO AMOUNT
----- -------
102 33.25
104 3.28
106 0.35
101 0.07
Then,
produces:
EMPNO AMOUNT
----- -------
102 33.25
104 03.28
106 00.35
101 00.07
38
Chapter | 2
Gives:
EMPNO AMOUNT
----- --------
102 $33.25
104 $3.28
106 $0.35
101 $0.07
Scripts
Often, a formatting command is used but is meant for
only one executable statement. For example, suppose
we formatted the AMOUNT column as above with
“COLUMN amount FORMAT $990.99.” The format
will stay in effect for the entire session unless the col-
umn is CLEARed or another “COLUMN amount
FORMAT ..” is executed. To undo all column format-
ting, the command is:
CLEAR COLUMNS
39
Reporting Tools in Oracle’s SQL*Plus
START myscript.txt
or
@myscript.txt
40
Chapter | 2
Other feature values that may be manipulated in
this way are “pagesize,” which defaults to 24 and may
be insufficient for a particular query, and “feedback,”
which shows how many records were selected if it
exceeds a certain amount.
All of the feature values may be seen using the
SHOW ALL command from the command line, and
any of the parameters may be changed to suit any par-
ticular user.
Formatting Dates
While not specifically a report feature, the formatting
of dates is common and related to overall report for-
matting. The appropriate way to format a date is to use
the TO_CHAR function. TO_CHAR takes a date data
type and converts it to a character string according to
an acceptable format. There are several variations on
“acceptable formats,” and we will illustrate a few here
(we also used TO_CHAR in Chapter 1). First, we show
the use of the TO_CHAR function to format a date.
The syntax of TO_CHAR is:
41
Reporting Tools in Oracle’s SQL*Plus
This gives:
Gives:
42
Chapter | 2
Format Will look like
Day Mon yyyy Sunday Mar 2006
Day fmMonth dd, yyyy Sunday March 5, 2006
Mon ddsp yyyy Mar five 2006
ddMon yy hh24:mi:ss 05Mar 06 00:00:00
BREAK
Often when looking at a result set it is convenient to
“break” the report on some column to produce easy-
to-read output. Consider the Employee table result set
like this (with columns formatted):
Giving:
BREAK ON region
43
Reporting Tools in Oracle’s SQL*Plus
to produce:
44
Chapter | 2
Giving:
COMPUTE
The COMPUTE command may be used in conjunction
with BREAK to give summary results. COMPUTE
allows us to calculate an aggregate value and place the
result at the break point. The syntax of COMPUTE is:
45
Reporting Tools in Oracle’s SQL*Plus
Giving:
46
Chapter | 2
...
111 Kate $49,000
122 Lindsey $52,000
----------- ******
######## sum
...
47
Reporting Tools in Oracle’s SQL*Plus
Giving:
-----------
sum $322,000
Remarks in Scripts
All scripts should contain minimal remarks to docu-
ment the writer, the date, and the purpose of the
report. Remarks are called “comments” in other lan-
guages. Remarks are allowable anywhere in the script
except for within the SELECT statement. In the
SELECT statement, normal comments may be used
(/* comment */ or two dashes at the end of a single
line).
48
Chapter | 2
Here is the above script with some remarks, indi-
cated by REM:
49
Reporting Tools in Oracle’s SQL*Plus
The same holds for BTITLE. The titles, line sizes, and
page sizes (for bottom titles) need to be coordinated to
make the report look attractive. In addition, page num-
bers may be added with the extension:
50
Chapter | 2
ORDER BY region
/
REM clean up parameters set before the SELECT
CLEAR BREAKS
CLEAR COMPUTES
CLEAR COLUMNS
BTITLE OFF
TTITLE OFF
SET verify on
SET feedback on
SET echo on
Giving:
-----------
sum $322,000
51
Reporting Tools in Oracle’s SQL*Plus
References
A good reference on the web is titled “SQL*Plus
User’s Guide and Reference.” It may be found under
“Oracle9i Database Online Documentation, Release 2
(9.2)” for SQL*Plus commands at http://web.njit.edu/
info/limpid/DOC/index.htm. (Copyright © 2002, Oracle
Corporation, Redwood Shores, CA.)
52
Chapter | 3
Chapter 3
The Analytical
Functions in
Oracle (Analytical
Functions I)
53
The Analytical Functions in Oracle (Analytical Functions I)
54
Chapter | 3
analytical functions may provide useful counts and
rankings and may provide offset columns much like
spreadsheets.
These analytic clauses in analytical functions are
most easily explained by way of examples, so let’s
begin with the row numbering and ranking functions.
55
The Analytical Functions in Oracle (Analytical Functions I)
56
Chapter | 3
Giving:
57
The Analytical Functions in Oracle (Analytical Functions I)
Giving:
58
Chapter | 3
which gives:
How can you deal with the tie problem? Without ana-
lytical functions you must resort to a workaround of
some kind. For example, you could again wrap this
result set in parentheses and look for distinct values of
salary by doing a self-join comparison. You could also
use PL/SQL. However, each of these workarounds is
awkward and messy compared to the ease with which
the analytical functions provide a solution.
There are three ranking-type analytical functions
that deal with just such a problem as this: ROW_
NUMBER, RANK, and DENSE_RANK. We will first
use ROW_NUMBER as an orientation in the use of
analytical functions and then solve the tie problem in
ranking. First, recall that the format of an analytical
function is this:
59