SQL Functions
SQL Functions
1
none
GE Confidential
TO_NCLOB FUNCTION.............................................................................................................................. ..............26
TO_NUMBER FUNCTION...................................................................................................................................... ...27
TO_DSINTERVAL FUNCTION................................................................................................................ .................27
TO_SINGLE_BYTE FUNCTION............................................................................................................................ ...28
TO_LOB FUNCTION............................................................................................................................................ ......28
TO_TIMESTAMP FUNCTION............................................................................................................. .....................28
TO_TIMESTAMP_TZ FUNCTION............................................................................................................... ............29
TO_YMINTERVAL FUNCTION........................................................................................................................... .....30
BFILENAME FUNCTION................................................................................................................................. .........31
CARDINALITY FUNCTION (NEW IN ORACLE 10).................................................................................... .........31
CASE STATEMENT........................................................................................................................................ ............32
COALESCE FUNCTION............................................................................................................................... .............34
DECODE FUNCTION......................................................................................................................................... ........34
GROUP_ID FUNCTION.............................................................................................................................. ...............37
NANVL FUNCTION (NEW IN ORACLE 10).............................................................................................. .............37
NVL FUNCTION......................................................................................................................................................... .38
NVL2 FUNCTION................................................................................................................................... ....................39
SYS_CONTEXT FUNCTION...................................................................................................................... ...............40
UID FUNCTION..................................................................................................................................... .....................42
USER FUNCTION........................................................................................................................................ ...............42
USERENV FUNCTION..................................................................................................................................... ..........43
ABS FUNCTION............................................................................................................................................... ...........44
ACOS FUNCTION.................................................................................................................................................. .....44
ASIN FUNCTION....................................................................................................................................... .................45
ATAN FUNCTION.......................................................................................................................................... .............45
ATAN2 FUNCTION....................................................................................................................................... ..............45
AVG FUNCTION..................................................................................................................................... ....................46
BIN_TO_NUM FUNCTION.................................................................................................................................. ......47
BITAND FUNCTION................................................................................................................................................ ...47
CEIL FUNCTION....................................................................................................................................... .................48
CORR FUNCTION......................................................................................................................................... .............48
COS FUNCTION......................................................................................................................................................... .49
COSH FUNCTION............................................................................................................................... .......................49
COVAR_POP FUNCTION........................................................................................................................... ...............49
COVAR_SAMP FUNCTION.............................................................................................................................. .........50
COUNT FUNCTION.................................................................................................................................................... 50
CUME_DIST FUNCTION......................................................................................................................................... ..52
DENSE_RANK FUNCTION.......................................................................................................................... .............53
EXP FUNCTION............................................................................................................................................... ...........54
EXTRACT FUNCTION............................................................................................................................................... 54
2
none
GE Confidential
FLOOR FUNCTION................................................................................................................................................ ....55
GREATEST FUNCTION.......................................................................................................................................... ...55
LEAST FUNCTION.............................................................................................................................................. .......56
LN FUNCTION............................................................................................................................................. ...............56
LOG FUNCTION................................................................................................................................................ .........57
MAX FUNCTION....................................................................................................................................... .................57
MEDIAN FUNCTION (NEW IN ORACLE 10)................................................................................. .......................60
MIN FUNCTION......................................................................................................................................................... .60
MOD FUNCTION............................................................................................................................................ ............61
POWER FUNCTION............................................................................................................................................ .......61
RANK FUNCTION......................................................................................................................................... .............62
REMAINDER FUNCTION (NEW IN ORACLE 10)............................................................................... .................63
ROUND FUNCTION (WITH NUMBERS).................................................................................................... ............63
ROUND FUNCTION (WITH DATES)................................................................................................................ .......64
SIGN FUNCTION............................................................................................................................................ ............65
SIN FUNCTION.............................................................................................................................................. .............65
SINH FUNCTION............................................................................................................................................ ............66
SQRT FUNCTION......................................................................................................................................... ..............66
STDDEV FUNCTION............................................................................................................................................ ......67
SUM FUNCTION................................................................................................................................................ .........67
TAN FUNCTION........................................................................................................................................................ ..69
TANH FUNCTION...................................................................................................................................................... .69
TRUNC FUNCTION (WITH DATES)...................................................................................................... .................70
TRUNC FUNCTION (WITH NUMBERS).......................................................................................... ......................71
VAR_POP FUNCTION.................................................................................................................................... ............71
VAR_SAMP FUNCTION....................................................................................................................................... ......71
VARIANCE FUNCTION.................................................................................................................................. ...........72
ADD_MONTHS FUNCTION................................................................................................................................ ......72
CURRENT_DATE FUNCTION.............................................................................................................................. ....73
CURRENT_TIMESTAMP FUNCTION.................................................................................................................. ...74
TZ_OFFSET FUNCTION.......................................................................................................................... .................74
DBTIMEZONE FUNCTION.................................................................................................................................... ...75
FROM_TZ FUNCTION........................................................................................................................ ......................76
LAST_DAY FUNCTION........................................................................................................................ .....................77
LOCALTIMESTAMP FUNCTION....................................................................................................... .....................77
NEW_TIME FUNCTION.................................................................................................................................... ........78
NEXT_DAY FUNCTION....................................................................................................................................... ......79
ROUND FUNCTION (WITH DATES)................................................................................................................ .......79
SESSIONTIMEZONE FUNCTION........................................................................................................................... .80
MONTHS_BETWEEN FUNCTION.................................................................................................... ......................81
3
none
GE Confidential
SYSTIMESTAMP FUNCTION............................................................................................................................. ......82
TO_CHAR FUNCTION............................................................................................................................................... 83
SYSDATE FUNCTION......................................................................................................................................... .......85
TO_DATE FUNCTION......................................................................................................................... ......................86
TRUNC FUNCTION (WITH DATES)...................................................................................................... .................87
SQLCODE FUNCTION........................................................................................................................ ......................88
SQLERRM FUNCTION....................................................................................................................................... .......89
UID FUNCTION..................................................................................................................................... .....................90
USER FUNCTION........................................................................................................................................ ...............91
In Oracle/PLSQL, the ascii function returns the NUMBER code that represents the specified character.
ascii( single_character )
single_character is the specified character to retrieve the NUMBER code for. If more than one character is
entered, the function will return the value for the first character and ignore all of the characters after the first.
For example:
4
none
GE Confidential
AsciiStr Function
In Oracle/PLSQL, the asciistr function converts a string in any character set to an ASCII string using the
database character set.
asciistr( string )
string is a string in any character set that you want converted to an ASCII string in the database character
set.
For example:
Chr Function
In Oracle/PLSQL, the chr function is the opposite of the ascii function. It returns the character based on the
NUMBER code.
chr( number_code )
For example:
Compose Function
5
none
GE Confidential
compose( string )
string is the input value used to create the Unicode string. It can be a char, varchar2, nchar, nvarchar2, clob,
or nclob.
Below is a listing of unistring values that can be combined with other characters in the compose function.
For example:
Concat Function
In Oracle/PLSQL, the concat function allows you to concatenate two strings together.
For example:
concat('Tech on', ' the Net'); would return 'Tech on the Net'.
concat('a', 'b') would return 'ab'.
|| Operator
6
none
GE Confidential
The syntax for the || operator is:
For example:
'Tech on' || ' the Net' would return 'Tech on the Net'.
'a' || 'b' || 'c' || 'd' would return 'abcd'.
Convert Function
In Oracle/PLSQL, the convert function converts a string from one character set to another.
7
none
GE Confidential
For example:
Decompose Function
In Oracle/PLSQL, the decompose function accepts a string and returns a Unicode string.
decompose( string )
For example:
Dump Function
In Oracle/PLSQL, the dump function returns a varchar2 value that includes the datatype code, the length in
bytes, and the internal representation of the expression.
return_format is optional. It determines the format of the return value. This parameter can be any of the
following values:
Value Explanation
8 octal notation
10 decimal notation
16 hexadecimal notation
17 single characters
1008 octal notation with the character set name
1010 decimal notation with the character set name
1016 hexadecimal notation with the character set name
1017 single characters with the character set name
8
none
GE Confidential
start_position and length are optional parameters. They determines which portion of the internal
representation to display. If these parameters are omitted, the dump function will display the entire internal
representation in decimal notation.
For example:
Initcap Function
In Oracle/PLSQL, the initcap function sets the first character in each word to uppercase and the rest to
lowercase.
initcap( string1 )
string1 is the string argument whose first character in each word will be converted to uppercase and all
remaining characters converted to lowercase.
For example:
Instr Function
start_position is the position in string1 where the search will start. This argument is optional. If omitted, it
defaults to 1. The first position in the string is 1. If the start_position is negative, the function counts back
start_position number of characters from the end of string1 and then searches towards the beginning of
string1.
9
none
GE Confidential
nth_appearance is the nth appearance of string2. This is optional. If omitted, it defaults to 1.
Note: If string2 is not found in string1, then the instr Oracle function will return 0.
For example:
instr('Tech on the net', 'e') would return 2; the first occurrence of 'e'
instr('Tech on the net', 'e', 1, 1) would return 2; the first occurrence of 'e'
instr('Tech on the net', 'e', 1, 2) would return 11; the second occurrence of 'e'
instr('Tech on the net', 'e', 1, 3) would return 14; the third occurrence of 'e'
instr('Tech on the net', 'e', -3, 2) would return 2.
Length Function
In Oracle/PLSQL, the length function returns the length of the specified string.
length( string1 )
string1 is the string to return the length for. If string1 is NULL, then the function returns NULL.
For example:
Lower Function
In Oracle/PLSQL, the lower function converts all letters in the specified string to lowercase. If there are
characters in the string that are not letters, they are unaffected by this function.
lower( string1 )
10
none
GE Confidential
For example:
Lpad Function
In Oracle/PLSQL, the lpad function pads the left-side of a string with a specific set of characters.
padded_length is the number of characters to return. If the padded_length is smaller than the original string,
the lpad function will truncate the string to the size of padded_length.
pad_string is optional. This is the string that will be padded to the left-hand side of string1. If this parameter
is omitted, the lpad function will pad spaces to the left-side of string1.
For example:
Ltrim Function
In Oracle/PLSQL, the ltrim function removes all specified characters from the left-hand side of a string.
string1 is the string to trim the characters from the left-hand side.
trim_string is the string that will be removed from the left-hand side of string1. If this parameter is omitted,
the ltrim function will remove all leading spaces from string1.
11
none
GE Confidential
For example:
The ltrim function may appear to remove patterns, but this is not the case as demonstrated in the following
example.
It actually removes the individual occurrences of 'x', 'y', and 'z', as opposed to the pattern of 'xyz'.
The ltrim function can also be used to remove all leading numbers as demonstrated in the next example.
In this example, every number combination from 0 to 9 has been listed in the trim_string parameter. By
doing this, it does not matter the order that the numbers appear in string1, all leading numbers will be
removed by the ltrim function.
Replace Function
In Oracle/PLSQL, the replace function replaces a sequence of characters in a string with another set of
characters.
string1 is the string to replace a sequence of characters with another set of characters.
For example:
12
none
GE Confidential
replace('222tech, '2', '3'); would return '333tech'
replace('0000123', '0'); would return '123'
replace('0000123', '0', ' '); would return ' 123'
Rpad Function
In Oracle/PLSQL, the rpad function pads the right-side of a string with a specific set of characters.
padded_length is the number of characters to return. If the padded_length is smaller than the original string,
the rpad function will truncate the string to the size of padded_length.
pad_string is optional. This is the string that will be padded to the right-hand side of string1. If this parameter
is omitted, the rpad function will pad spaces to the right-side of string1.
For example:
Rtrim Function
In Oracle/PLSQL, the rtrim function removes all specified characters from the right-hand side of a string.
string1 is the string to trim the characters from the right-hand side.
trim_string is the string that will be removed from the right-hand side of string1. If this parameter is omitted,
the rtrim function will remove all trailing spaces from string1.
For example:
13
none
GE Confidential
rtrim('tech ', ' '); would return 'tech'
rtrim('123000', '0'); would return '123'
rtrim('Tech123123', '123'); would return 'Tech'
rtrim('123Tech123', '123'); would return '123Tech'
rtrim('Techxyxzyyy', 'xyz'); would return 'Tech'
rtrim('Tech6372', '0123456789'); would return 'Tech'
The rtrim function may appear to remove patterns, but this is not the case as demonstrated in the following
example.
It actually removes the individual occurrences of 'x', 'y', and 'z', as opposed to the pattern of 'xyz'.
The rtrim function can also be used to remove all trailing numbers as demonstrated in the next example.
In this example, every number combination from 0 to 9 has been listed in the trim_string parameter. By
doing this, it does not matter the order that the numbers appear in string1, all trailing numbers will be
removed by the rtrim function.
Soundex Function
In Oracle/PLSQL, the soundex function returns a phonetic representation (the way it sounds) of a string.
soundex( string1 )
1. The soundex return value will always begin with the first letter of string1.
2. The soundex function uses only the first 5 consonants to determine the NUMERIC portion of the
return value, except if the first letter of string1 is a vowel.
3. The soundex function is not case-sensitive. What this means is that both uppercase and lowercase
characters will generate the same soundex return value.
14
none
GE Confidential
For example:
Substr Function
In Oracle/PLSQL, the substr functions allows you to extract a substring from a string.
start_position is the position for extraction. The first position in the string is always 1.
length is optional. It is the number of characters to extract. If this parameter is omitted, substr will return the
entire string.
Note:
If start_position is 0, then substr treats start_position as 1 (ie: the first position in the string).
If start_position is a positive number, then substr starts from the beginning of the string.
If start_position is a negative number, then substr starts from the end of the string and counts backwards.
For example:
Translate Function
15
none
GE Confidential
In Oracle/PLSQL, the translate function replaces a sequence of characters in a string with another set of
characters. However, it replaces a single character at a time. For example, it will replace the 1st character in
the string_to_replace with the 1st character in the replacement_string. Then it will replace the 2nd character
in the string_to_replace with the 2nd character in the replacement_string, and so on.
string1 is the string to replace a sequence of characters with another set of characters.
replacement_string - All characters in the string_to_replace will be replaced with the corresponding
character in the replacement_string.
For example:
Trim Function
In Oracle/PLSQL, the trim function removes all specified characters either from the beginning or the ending
of a string.
If none of these are chosen (ie: leading, trailing, both), the trim function will remove trim_string from both the
front and end of string1.
trim_character is the character that will be removed from string1. If this parameter is omitted, the trim
function will remove all leading and trailing spaces from string1.
For example:
16
none
GE Confidential
trim(' tech ') would return 'tech'
trim(' ' from ' tech ') would return 'tech'
trim(leading '0' from '000123') would return '123'
trim(trailing '1' from 'Tech1') would return 'Tech'
trim(both '1' from '123Tech111') would return '23Tech'
Upper Function
In Oracle/PLSQL, the upper function converts all letters in the specified string to uppercase. If there are
characters in the string that are not letters, they are unaffected by this function.
upper( string1 )
For example:
VSize Function
In Oracle/PLSQL, the vsize function returns the number of bytes in the internal representation of an
expression.
vsize( expression )
For example:
2. Conversion Functions:
17
none
GE Confidential
Bin_To_Num Function
expr1, expr2, ... expr_n must be either 0 or 1 values. They represent bits in a bit vector.
For example:
Cast Function
TO FROM
char, varchar2 X X X X X
number X X
datetime / interval X X
raw X X
18
none
GE Confidential
rowid, urowid X X
nchar, nvarchar2 X X X X X
For example:
This would convert the date (ie: 22-Aug-2003) into a varchar2(30) value.
CharToRowid Function
In Oracle/PLSQL, the chartorowid function converts a char, varchar2, nchar, or nvarchar2 to a rowid.
chartorowid( value1 )
BBBBBBB.RRRR.FFFFF
where:
For example:
From_Tz function
In Oracle/PLSQL, the from_tz function converts a TIMESTAMP value (given a TIME ZONE) to a
TIMESTAMP WITH TIME ZONE value.
19
none
GE Confidential
timestamp_value is the value to convert to a TIMESTAMP WITH TIME ZONE value.
time_zone_value is the time zone used to convert timestamp_value to a TIMESTAMP WITH TIME ZONE
value.
For example:
If you executed the same SQL statement, but set the time zone to '-7:00' as follows:
HexToRaw Function
In Oracle/PLSQL, the hextoraw function converts a hexadecimal value into a raw value.
hextoraw( char )
For example:
NumToDSInterval Function
20
none
GE Confidential
The syntax for the numtodsinterval function is:
expression is the unit. It must be one of the following values: DAY, HOUR, MINUTE, or SECOND.
For example:
NumToYMInterval Function
expression is the unit. It must be one of the following values: YEAR or MONTH.
For example:
To_Char Function
format_mask is optional. This is the format that will be used to convert value to a string.
21
none
GE Confidential
nls_language is optional. This is the nls language used to convert value to a string.
Examples - Numbers
The following are number examples for the to_char function.
Examples - Dates
The following is a list of valid parameters when the to_char function is used to convert a date to a string.
These parameters can be used in many combinations.
Parameter Explanation
YEAR Year, spelled out
YYYY 4-digit year
YYY Last 3, 2, or 1 digit(s) of year.
YY
Y
IYY Last 3, 2, or 1 digit(s) of ISO year.
IY
I
IYYY 4-digit year based on the ISO standard
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
WW Week of year (1-53) where week 1 starts on the first day of the year and
continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and
ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
22
none
GE Confidential
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
FF Fractional seconds.
You will notice that in some examples, the format_mask parameter begins with "FM". This means that zeros
and blanks are suppressed. This can be seen in the examples below.
The zeros have been suppressed so that the day component shows as "9" as opposed to "09".
Question: Why doesn't this sort the day's of the week in order?
Answer:
The fmDay parameter will return the name of the Day and not the numeric value of the day.
Try the following:
23
none
GE Confidential
select ename, hiredate, to_char((hiredate),'fmDD') "Day"
from emp
order by "Day";
To_Clob Function
In Oracle/PLSQL, the to_clob function converts a LOB value from the national character set to the database
character set.
to_clob( expression )
expression can either be a lob_column, char, varchar2, nchar, nvarchar2, clob or nclob value.
For example:
select to_clob(nclob_column)
from suppliers;
This example would convert the value in the field called nclob_column to a CLOB value.
To_Date Function
format_mask is optional. This is the format that will be used to convert string1 to a date.
nls_language is optional. This is the nls language used to convert string1 to a date.
The following is a list of options for the format_mask parameter. These parameters can be used in many
combinations.
Parameter Explanation
YEAR Year, spelled out
YYYY 4-digit year
24
none
GE Confidential
YYY
YY Last 3, 2, or 1 digit(s) of year.
Y
IYY
IY Last 3, 2, or 1 digit(s) of ISO year.
I
IYYY 4-digit year based on the ISO standard
Accepts a 2-digit year and returns a 4-digit year.
RRRR A value between 0-49 will return a 20xx year.
A value between 50-99 will return a 19xx year.
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
Week of year (1-53) where week 1 starts on the first day of the year
WW
and continues to the seventh day of the year.
Week of month (1-5) where week 1 starts on the first day of the
W
month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
Fractional seconds. Use a value from 1 to 9 after FF to indicate the
FF
number of digits in the fractional seconds. For example, 'FF4'.
AM, A.M., PM, or P.M. Meridian indicator
AD or A.D AD indicator
BC or B.C. BC indicator
TZD Daylight savings information. For example, 'PST'
TZH Time zone hour.
25
none
GE Confidential
TZM Time zone minute.
TZR Time zone region.
For example:
To_Multi_Byte Function
In Oracle/PLSQL, the to_multi_byte function returns a character value with all of the single-byte characters
converted to multibyte characters. To use this function, your database character set contains both single-
byte and multibyte characters.
to_multi_byte( char )
char can be a char, varchar2, nchar, or nvarchar2 value. This function will return its result in the same
character set as char.
For example:
To_NClob Function
to_nclob( expression )
For example:
select to_nclob(lob_column)
from suppliers;
26
none
GE Confidential
This example would convert the value in the field called lob_column to an NCLOB value.
To_Number Function
format_mask is optional. This is the format that will be used to convert string1 to a number.
nls_language is optional. This is the nls language used to convert string1 to a number.
For example:
Since the format_mask and nls_language parameters are optional, you can simply convert a text string to a
numeric value as follows:
To_DSInterval Function
In Oracle/PLSQL, the to_dsinterval function converts a string to an INTERVAL DAY TO SECOND type.
character is the value to convert to an INTERVAL DAY TO SECOND type. It can be a char, varchar2, nchar,
or nvarchar2 value.
For example:
27
none
GE Confidential
to_dsinterval('80 12:30:00') would return '+000000080'
to_dsinterval('95 18:30:00') would return '+000000095'
To_Single_Byte Function
In Oracle/PLSQL, the to_single_byte function returns a character value with all of the multibyte characters
converted to single-byte characters. To use this function, your database character set contains both single-
byte and multibyte characters.
to_single_byte( char )
char can be a char, varchar2, nchar, or nvarchar2 value. This function will return its result in the same
character set as char.
For example:
To_Lob Function
In Oracle/PLSQL, the to_lob function converts LONG or LONG RAW values to LOB values.
to_lob( long_column )
For example:
This example would convert the value in the field called long_column to a LOB value.
To_Timestamp Function
28
none
GE Confidential
The syntax for the to_timestamp function is:
format_mask is optional. This is the format that will be used to convert string1 to a timestamp.
The following is a list of options for the format_mask parameter. These parameters can be used in many
combinations.
Parameter Explanation
YYYY 4-digit year
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
DD Day of month (1-31).
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
For example:
To_Timestamp_Tz Function
In Oracle/PLSQL, the to_timestamp_tz function converts a string to a timestamp with time zone.
29
none
GE Confidential
string1 is the string that will be converted to a timestamp with time zone.
format_mask is optional. This is the format that will be used to convert string1 to a timestamp with time zone.
The following is a list of options for the format_mask parameter These parameters can be used in many
combinations.
Parameter Explanation
YYYY 4-digit year
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
DD Day of month (1-31).
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
TZM Time zone minute.
TZH Time zone hour.
For example:
would return '13-DEC-03 10.13.18.000000000 AM -08:00' as a timestamp with time zone value.
would also return '13-DEC-03 10.13.18.000000000 AM -08:00' as a timestamp with time zone value.
To_YMInterval Function
In Oracle/PLSQL, the to_yminterval function converts a string to an INTERVAL YEAR TO MONTH type.
to_yminterval( character )
character is the value to convert to an INTERVAL YEAR TO MONTH type. It can be a char, varchar2, nchar,
or nvarchar2 value.
30
none
GE Confidential
For example:
The to_yminterval function is most commonly used to add an interval to a date field. For example, you may
wish to add 1 year and 5 months to an order date.
This SQL statement would return the order date, as well as the order date plus 1 year and 5 months.
3. Advanced Functions:
BFilename Function
In Oracle/PLSQL, the bfilename function returns a BFILE locator for a physical LOB binary file.
directory is a directory object that serves as an alias for the full path to where the file is located on the file
server.
For example:
First, we need to create a directory object called exampleDir that points to /example/totn on the file server.
Then we can use the exampleDir directory object in the bfilename function as follows:
31
none
GE Confidential
In Oracle/PLSQL, the cardinality function returns the number of elements in a nested table.
nested table column is the column in the nested table that you wish to return the cardinality for.
Note:
If the nested table is empty, the cardinality function will return NULL.
If the nested table is a null collection, the cardinality function will return NULL.
For example:
Case Statement
In Oracle 9i, you can use the case statement within an SQL statement. It has the functionality of an IF-
THEN-ELSE statement.
CASE expression
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result END
expression is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ...
condition_n)
condition_1 to condition_n must all be the same datatype. Conditions are evaluated in the order listed. Once
a condition is found to be true, the case statement will return the result and not evaluate the conditions any
further.
result_1 to result_n must all be the same datatype. This is the value returned once a condition is found to be
true.
Note:
32
none
GE Confidential
If no condition is found to be true, then the case statement will return the value in the ELSE clause.
If the ELSE clause is omitted and no condition is found to be true, then the case statement will return NULL.
You can have up to 255 comparisons in a case statement. Each WHEN ... THEN clause is considered 2
comparisons.
For Example:
select table_name,
CASE owner
WHEN 'SYS' THEN 'The owner is SYS'
WHEN 'SYSTEM' THEN 'The owner is SYSTEM'
ELSE 'The owner is another value' END
from all_tables;
ELSE
result := 'The owner is another value';
END IF;
The case statement will compare each owner value, one by one.
One thing to note is that the ELSE clause within the case statement is optional. You could have omitted it.
Let's take a look at the SQL statement above with the ELSE clause omitted.
select table_name,
CASE owner
WHEN 'SYS' THEN 'The owner is SYS'
WHEN 'SYSTEM' THEN 'The owner is SYSTEM' END
from all_tables;
With the ELSE clause omitted, if no condition was found to be true, the case statement would return NULL.
33
none
GE Confidential
Coalesce Function
In Oracle/PLSQL, the coalesce function returns the first non-null expression in the list. If all expressions
evaluate to null, then the coalesce function will return null.
For Example:
ELSE
result := null;
END IF;
Decode Function
default is optional. If no matches are found, the decode will return default. If default is omitted, then the
decode statement will return null (if no matches are found).
For Example:
SELECT supplier_name,
decode(supplier_id, 10000, 'IBM',
10001, 'Microsoft',
10002, 'Hewlett Packard',
'Gateway') result
FROM suppliers;
ELSE
result := 'Gateway';
END IF;
The decode function will compare each supplier_id value, one by one.
Question: One of our viewers wanted to know how to use the decode function to compare two dates (ie:
date1 and date2), where if date1 > date2, the decode function should return date2. Otherwise, the decode
function should return date1.
35
none
GE Confidential
(date1 - date2) - abs(date1 - date2)
Question: I would like to know if it's possible to use decode for ranges of numbers, ie 1-10 = 'category 1',
11-20 = 'category 2', rather than having to individually decode each number.
Answer: Unfortunately, you can not use the decode for ranges of numbers. However, you can try to create a
formula that will evaluate to one number for a given range, and another number for the next range, and so
on.
For example:
SELECT supplier_id,
decode(trunc ((supplier_id - 1) / 10), 0, 'category 1',
1, 'category 2',
2, 'category 3',
'unknown') result
FROM suppliers;
trunc ((supplier_id - 1) / 10
and so on...
Question: I need to write a decode statement that will return the following:
Answer: You will need to create a formula that will evaluate to a single number for each one of your ranges.
For example:
SELECT emp_name,
decode(trunc (( yrs_of_service + 3) / 4), 0, 0.04,
1, 0.04,
0.06) as perc_value
FROM employees;
Helpful Tip: One of our viewers suggested combining the SIGN function with the DECODE function as
follows:
36
none
GE Confidential
DECODE(SIGN(date1-date2), 1, date2, date1)
The SIGN/DECODE combination is also helpful for numeric comparisons e.g. Sales Bonuses
DECODE(SIGN(actual-target), -1, 'NO Bonus for you', 0,'Just made it', 1, 'Congrats, you are a winner')
Group_ID Function
In Oracle/PLSQL, the group_id function assigns a number to each group resulting from a GROUP BY
clause. The group_id function is most commonly used to identify duplicated groups in your query results.
For each unique group, the group_id function will return 0. When a duplicated group is found, the group_id
function will return a value >0.
For example:
You could use the HAVING clause to eliminated duplicated groups as follows:
In Oracle/PLSQL, the NANVL function lets you substitute a value for a floating point number such as
BINARY_FLOAT or BINARY_DOUBLE, when a Nan (Not a number) value is encountered. This is most
commonly used to convert Nan (Not a number) values into either NULL or 0.
37
none
GE Confidential
value is the BINARY_FLOAT or BINARY_NUMBER to test for a Nan (Not a number).
Example #1:
select NANVL(binary1, 0)
from test_table;
The SQL statement above would return 0 if the binary1 field contained a Nan (Not a number) value.
Otherwise, it would return the binary1 value.
Example #2:
The SQL statement above would return NULL if the binary1 field contained a Nan (Not a number) value.
Otherwise, it would return the binary1 value.
NVL Function
In Oracle/PLSQL, the NVL function lets you substitute a value when a null value is encountered.
Example #1:
The SQL statement above would return 'n/a' if the supplier_city field contained a null value. Otherwise, it
would return the supplier_city value.
Example #2:
select supplier_id,
NVL(supplier_desc, supplier_name)
from suppliers;
38
none
GE Confidential
This SQL statement would return the supplier_name field if the supplier_desc contained a null value.
Otherwise, it would return the supplier_desc.
Example #3:
select NVL(commission, 0)
from sales;
This SQL statement would return 0 if the commission field contained a null value. Otherwise, it would return
the commission field.
Question: I tried to use the NVL function through VB to access Oracle DB.
To be precise,
I got an oracle error when I use distinct clause with NVL, but when I remove distinct it works fine.
Answer: It is possible to the use the DISTINCT clause with the NVL function. However, the DISTINCT must
come before the use of the NVL function. For example:
Question: Is it possible to use the NVL function with more than one column with the same function call? To
be clear, if i need to apply this NVL function to more than one column like this:
Answer: You will need to make separate NVL function calls for each column. For example:
NVL2 Function
In Oracle/PLSQL, the NVL2 function extends the functionality found in the NVL function. It lets you
substitutes a value when a null value is encountered as well as when a non-null value is encountered.
Example #1:
The SQL statement above would return 'n/a' if the supplier_city field contained a null value. Otherwise, it
would return the 'Completed'.
Example #2:
select supplier_id,
NVL2(supplier_desc, supplier_name, supplier_name2)
from suppliers;
This SQL statement would return the supplier_name2 field if the supplier_desc contained a null value.
Otherwise, it would return the supplier_name field.
Sys_Context Function
In Oracle/PLSQL, the sys_context function can be used to retrieve information about the Oracle
environment.
namespace is an Oracle namespace that has already been created. If the namespace of 'USERENV' is
used, attributes describing the current Oracle session can be returned.
parameter is a valid attribute that has been set using the DBMS_SESSION.set_context procedure.
length is optional. It is the length of the return value in bytes. If this parameter is omitted or if an invalid entry
is provided, the sys_context function will default to 256 bytes.
The valid parameters for the namespace called 'USERENV' are as follows:
40
none
GE Confidential
Parameter Explanation Return
Length
AUDITED_CURSORID Returns the cursor ID of the SQL that triggered the audit N/A
AUTHENTICATION_DATA Authentication data 256
AUTHENTICATION_TYPE Describes how the user was authenticated. Can be one of the 30
following values: Database, OS, Network, or Proxy
BG_JOB_ID If the session was established by an Oracle background 30
process, this parameter will return the Job ID. Otherwise, it will
return NULL.
CLIENT_IDENTIFIER Returns the client identifier (global context) 64
CLIENT_INFO User session information 64
CURRENT_SCHEMA Returns the default schema used in the current schema 30
CURRENT_SCHEMAID Returns the identifier of the default schema used in the current 30
schema
CURRENT_SQL Returns the SQL that triggered the audit event 64
CURRENT_USER Name of the current user 30
CURRENT_USERID Userid of the current user 30
DB_DOMAIN Domain of the database from the DB_DOMAIN initialization 256
parameter
DB_NAME Name of the database from the DB_NAME initialization 30
parameter
ENTRYID Available auditing entry identifier 30
EXTERNAL_NAME External of the database user 256
FG_JOB_ID If the session was established by a client foreground process, 30
this parameter will return the Job ID. Otherwise, it will return
NULL.
GLOBAL_CONTEXT_MEMORY The number used in the System Global Area by the globally N/A
accessed context
HOST Name of the host machine from which the client has connected 54
INSTANCE The identifier number of the current instance 30
IP_ADDRESS IP address of the machine from which the client has connected 30
ISDBA Returns TRUE if the user has DBA privileges. Otherwise, it will 30
return FALSE.
LANG The ISO abbreviate for the language 62
LANGUAGE The language, territory, and character of the session. In the 52
following format:
language_territory.characterset
NETWORK_PROTOCOL Network protocol used 256
NLS_CALENDAR The calendar of the current session 62
NLS_CURRENCY The currency of the current session 62
41
none
GE Confidential
NLS_DATE_FORMAT The date format for the current session 62
NLS_DATE_LANGUAGE The language used for dates 62
NLS_SORT BINARY or the linguistic sort basis 62
NLS_TERRITORY The territory of the current session 62
OS_USER The OS username for the user logged in 30
PROXY_USER The name of the user who opened the current session on 30
behalf of SESSION_USER
PROXY_USERID The identifier of the user who opened the current session on 30
behalf of SESSION_USER
SESSION_USER The database user name of the user logged in 30
SESSION_USERID The database identifier of the user logged in 30
SESSIONID The identifier of the auditing session 30
TERMINAL The OS identifier of the current session 10
For example:
Uid function
In Oracle/PLSQL, the uid function returns the id number for a user's session (the user who is currently
logged in).
uid
For example:
select uid
into parm_uid
from dual;
The variable called parm_uid will now contain the id number for the user's session. The value could be 25,
for example.
User function
In Oracle/PLSQL, the user function returns the user_id from the current Oracle session.
42
none
GE Confidential
The syntax for the user function is:
user
For example:
select user
into parm_user_ID
from dual;
The variable called parm_user_ID will now contain the Oracle user ID from the current Oracle session.
UserEnv Function
In Oracle/PLSQL, the userenv function can be used to retrieve information about the current Oracle
session. Although this function still exists in Oracle for backwards compatibility, it is recommended that you
use the sys_context function instead.
userenv( parameter )
parameter is the value to return from the current Oracle session. The possible values are:
Parameter Explanation
CLIENT_INFO Returns user session information stored using the
DBMS_APPLICATION_INFO package
ENTRYID Available auditing entry identifier
INSTANCE The identifier number of the current instance
ISDBA Returns TRUE if the user has DBA privileges.
Otherwise, it will return FALSE.
LANG The ISO abbreviate for the language
LANGUAGE The language, territory, and character of the session. In
the following format:
language_territory.characterset
SESSIONID The identifier of the auditing session
TERMINAL The OS identifier of the current session
For example:
43
none
GE Confidential
4. Mathematical Functions:
Abs Function
abs( number )
For example:
Acos Function
acos( number )
For example:
44
none
GE Confidential
Asin Function
asin( number )
For example:
Atan Function
atan( number )
For example:
Atan2 Function
atan2( n, m )
45
none
GE Confidential
For example:
Avg Function
Simple Example
For example, you might wish to know how the average salary of all employees whose salary is above
$25,000 / year.
If there were two salaries of $30,000/year, only one of these values were be used in the Avg function.
46
none
GE Confidential
Example using GROUP BY
You could also use the Avg function to return the name of the department and the average sales (in the
associated department). For example,
Because you have listed one column in your SELECT statement that is not encapsulated in the Avg function,
you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY
section.
Bin_To_Num Function
expr1, expr2, ... expr_n must be either 0 or 1 values. They represent bits in a bit vector.
For example:
BitAnd Function
In Oracle/PLSQL, the bitand function returns an integer representing an AND operation on the bits of expr1
and expr2.
For example:
47
none
GE Confidential
bitand(5,3) would return 1
bitand(15,7) would return 7
bitand(5,2) would return 0
bitand(5,0) would return 0
bitand(6,2) would return 2
Ceil Function
In Oracle/PLSQL, the ceil function returns the smallest integer value that is greater than or equal to a
number.
ceil( number )
For example:
Corr Function
In Oracle/PLSQL, the corr function returns the coefficient of correlation of a set of number pairs.
For example:
48
none
GE Confidential
select max_entents, corr(max_trans, initial_extent)
from data
group by max_extents;
Cos Function
cos( number )
For example:
Cosh Function
cosh( number )
For example:
Covar_pop Function
49
none
GE Confidential
In Oracle/PLSQL, the covar_pop function returns the population covariance of a set of number pairs.
The covar_pop function eliminates all pairs where expression1 or expression2 has a null value.
For example:
Covar_samp Function
In Oracle/PLSQL, the covar_samp function returns the sample covariance of a set of number pairs.
The covar_samp function eliminates all pairs where expression1 or expression2 has a null value.
For example:
COUNT Function
SELECT COUNT(expression)
FROM tables
WHERE predicates;
50
none
GE Confidential
Simple Example
For example, you might wish to know how many employees have a salary that is above $25,000 / year.
In this example, we've aliased the count(*) field as "Number of employees". As a result, "Number of
employees" will display as the field name when the result set is returned.
For example, the SQL statement below returns the number of unique departments where at least one
employee makes over $25,000 / year.
Again, the count(DISTINCT department) field is aliased as "Unique departments". This is the field name that
will display in the result set.
For example, you could use the COUNT function to return the name of the department and the number of
employees (in the associated department) that make over $25,000 / year.
Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT
function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP
BY section.
51
none
GE Confidential
For example, based on the example above, the following syntax would result in better performance:
Now, the COUNT function does not need to retrieve all fields from the employees table as it had to when you
used the COUNT(*) syntax. It will merely retrieve the numeric value of 1 for each record that meets your
criteria.
Cume_Dist Function
In Oracle/PLSQL, the cume_dist function returns the cumulative distribution of a value in a group of values.
The cume_dist function will return a value that is >0 and <=1.
The cume_dist function can be used two ways - as an Aggregate function or as an Analytic function.
The syntax for the cume_dist function when used as an Aggregate function is:
expression1 .. expression_n can be one or more expressions which identify a unique row in the group.
Note:
There must be the same number of expressions in the first expression list as there is in the ORDER BY
clause.
The expression lists match by position so the data types must be compatible between the expressions in the
first expression list as in the ORDER BY clause.
For Example:
The SQL statement above would return the cumulative distribution of an employee with a salary of $1,000
and a bonus of $500 from within the employees table.
52
none
GE Confidential
Syntax #2 - Used as an Analytic Function
As an Analytic function, the cume_dist returns the relative position of a value within a group of values.
The syntax for the cume_dist function when used as an Analytic function is:
For Example:
The SQL statement above would return the salary percentile for each employee in the Marketing
department.
Dense_Rank Function
In Oracle/PLSQL, the dense_rank function returns the rank of a row in a group of rows. It is very similar to
the rank function. However, the rank function can cause non-consecutive rankings if the tested values are
the same. Whereas, the dense_rank function will always result in consecutive rankings.
The dense_rank function can be used two ways - as an Aggregate function or as an Analytic function.
The syntax for the dense_rank function when used as an Aggregate function is:
expression1 .. expression_n can be one or more expressions which identify a unique row in the group.
Note:
There must be the same number of expressions in the first expression list as there is in the ORDER BY
clause.
The expression lists match by position so the data types must be compatible between the expressions in the
first expression list as in the ORDER BY clause.
53
none
GE Confidential
For Example:
The SQL statement above would return the dense rank of an employee with a salary of $1,000 and a bonus
of $500 from within the employees table.
The syntax for the dense_rank function when used as an Analytic function is:
For Example:
The SQL statement above would return all employees who work in the Marketing department and then
calculate a rank for each unique salary in the Marketing department. If two employees had the same salary,
the dense_rank function would return the same rank for both employees.
Exp Function
In Oracle/PLSQL, the exp function returns e raised to the nth power, where e = 2.71828183.
exp( number )
For example:
Extract Function
54
none
GE Confidential
In Oracle/PLSQL, the extract function extracts a value from a date or interval value.
EXTRACT (
{ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND }
| { TIMEZONE_HOUR | TIMEZONE_MINUTE }
| { TIMEZONE_REGION | TIMEZONE_ABBR }
FROM { date_value | interval_value } )
You can only extract YEAR, MONTH, and DAY from a DATE.
You can only extract TIMEZONE_HOUR and TIMEZONE_MINUTE from a timestamp with a time zone
datatype.
For example:
Floor Function
In Oracle/PLSQL, the floor function returns the largest integer value that is equal to or less than a number.
floor( number )
number is the value used to determine the largest integer value that is equal to or less than a number.
For example:
Greatest Function
In Oracle/PLSQL, the greatest function returns the greatest value in a list of expressions.
If the datatypes of the expressions are different, all expressions will be converted to whatever datatype
expr1 is.
If the comparison is based on a character comparison, one character is considered greater than another if it
has a higher character set value.
For example:
Least Function
In Oracle/PLSQL, the least function returns the smallest value in a list of expressions.
expr1, expr2, . expr_n are expressions that are evaluated by the greatest function.
If the datatypes of the expressions are different, all expressions will be converted to whatever datatype
expr1 is.
If the comparison is based on a character comparison, one character is considered smaller than another if it
has a lower character set value.
For example:
Ln Function
56
none
GE Confidential
ln( number )
For example:
Log Function
log( m, n )
For example:
MAX Function
SELECT MAX(expression )
FROM tables
WHERE predicates;
Simple Example
For example, you might wish to know the maximum salary of all employees.
57
none
GE Confidential
SELECT MAX(salary) as "Highest salary"
FROM employees;
In this example, we've aliased the max(salary) field as "Highest salary". As a result, "Highest salary" will
display as the field name when the result set is returned.
For example, you could also use the MAX function to return the name of each department and the maximum
salary in the department.
Because you have listed one column in your SELECT statement that is not encapsulated in the MAX
function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP
BY section.
Question: I'm trying to pull some info out of a table. To simplify, let's say the table (report_history) has 4
columns:
Each time a report is run in Oracle, a record is written to this table noting the above info. What I am trying to
do is pull from this table when the last time each distinct report was run and who ran it last.
My initial query:
runs fine. However, it does not provide the name of the user who ran the report.
Adding user_name to both the select list and to the group by clause returns multiple lines for each report;
the results show the last time each person ran each report in question. (i.e. User1 ran Report 1 on 01-JUL-
03, User2 ran Report1 on 01-AUG-03). I don't want that....I just want to know who ran a particular report the
last time it was run.
Any suggestions?
Answer: This is where things get a bit complicated. The SQL statement below will return the results that
you want:
58
none
GE Confidential
SELECT rh.user_name, rh.report_name, rh.report_run_date
FROM report_history rh,
(SELECT max(report_run_date) as maxdate, report_name
FROM report_history
GROUP BY report_name) maxresults
WHERE rh.report_name = maxresults.report_name
AND rh.report_run_date= maxresults.maxdate;
First, we've aliased the first instance of the report_history table as rh.
Second, we've included two components in our FROM clause. The first is the table called report_history
(aliased as rh). The second is a select statement:
We've aliased the max(report_run_date) as maxdate and we've aliased the entire result set as maxresults.
Now, that we've created this select statement within our FROM clause, Oracle will let us join these results
against our original report_history table. So we've joined the report_name and report_run_date fields
between the tables called rh and maxresults. This allows us to retrieve the report_name,
max(report_run_date) as well as the user_name.
Question: I need help in an SQL query. I have a table in Oracle called orders which has the following fields:
order_no, customer, and amount.
I need a query that will return the customer who has ordered the highest total amount.
Answer: The following SQL should return the customer with the highest total amount in the orders table.
This SQL statement will summarize the total orders for each customer and then return the customer with the
highest total orders. This syntax is optimized for Oracle and may not work for other database technologies.
Question: I'm trying to retrieve some info from an Oracle database. I've got a table named Scoring with two
fields - Name and Score. What I want to get is the highest score from the table and the name of the player.
59
none
GE Confidential
SELECT Name, Score
FROM Scoring
WHERE Score = (select Max(Score) from Scoring);
Note:
The median function is NEW to Oracle 10! In older versions of Oracle, try using the percentile_cont function
to calculate the median value.
For example:
select median(salary)
from employees
where department = 'Marketing';
The SQL statement above would return the median salary for all employees in the Marketing department.
MIN Function
SELECT MIN(expression )
FROM tables
WHERE predicates;
Simple Example
For example, you might wish to know the minimum salary of all employees.
In this example, we've aliased the min(salary) field as "Lowest salary". As a result, "Lowest salary" will
display as the field name when the result set is returned.
60
none
GE Confidential
Example using GROUP BY
In some cases, you will be required to use a GROUP BY clause with the MIN function.
For example, you could also use the MIN function to return the name of each department and the minimum
salary in the department.
Because you have listed one column in your SELECT statement that is not encapsulated in the MIN
function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP
BY section.
Mod Function
mod( m, n )
Returns m if n is 0.
For example:
Power Function
power( m, n )
m is the base.
n is the exponent.
If m is negative, then n must be an integer.
61
none
GE Confidential
For example:
Rank Function
In Oracle/PLSQL, the rank function returns the rank of a value in a group of values. It is very similar to the
dense_rank function. However, the rank function can cause non-consecutive rankings if the tested values
are the same. Whereas, the dense_rank function will always result in consecutive rankings.
The rank function can be used two ways - as an Aggregate function or as an Analytic function.
The syntax for the rank function when used as an Aggregate function is:
rank( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY expression1, ... expression_n )
expression1 .. expression_n can be one or more expressions which identify a unique row in the group.
Note:
There must be the same number of expressions in the first expression list as there is in the ORDER BY
clause.
The expression lists match by position so the data types must be compatible between the expressions in the
first expression list as in the ORDER BY clause.
For Example:
The SQL statement above would return the rank of an employee with a salary of $1,000 and a bonus of
$500 from within the employees table.
62
none
GE Confidential
Syntax #2 - Used as an Analytic Function
As an Analytic function, the rank returns the rank of each row of a query with respective to the other rows.
The syntax for the rank function when used as an Analytic function is:
For Example:
The SQL statement above would return all employees who work in the Marketing department and then
calculate a rank for each unique salary in the Marketing department. If two employees had the same salary,
the rank function would return the same rank for both employees. However, this will cause a gap in the
ranks (ie: non-consecutive ranks). This is quite different from the dense_rank function which generates
consecutive rankings.
remainder( m, n )
Note:
The remainder function is NEW to Oracle 10! In older versions of Oracle, try using the mod function.
For example:
63
none
GE Confidential
In Oracle/PLSQL, the round function returns a number rounded to a certain number of decimal places.
decimal_places is the number of decimal places rounded to. This value must be an integer. If this parameter
is omitted, the round function will round the number to 0 decimal places.
For example:
In Oracle/PLSQL, the round function returns a date rounded to a specific unit of measure.
format is the unit of measure to apply for rounding. If the format parameter is omitted, the round function will
round to the nearest day.
64
none
GE Confidential
day of the year
Same day of the week as the first
IW IW
day of the ISO year
Same day of the week as the first
W W
day of the month
Day DDD, DD, J
Start day of the week DAY, DY, D
Hour HH, HH12, HH24
Minute MI
For example:
Sign Function
In Oracle/PLSQL, the sign function returns a value indicating the sign of a number.
sign( number )
For example:
Sin Function
65
none
GE Confidential
In Oracle/PLSQL, the sin function returns the sine of n.
sin( n )
For example:
Sinh Function
sinh( n )
n is a number.
For example:
Sqrt Function
sqrt( n )
n is a positive number.
For example:
66
none
GE Confidential
sqrt(9) would return 3
sqrt(37) would return 6.08276253029822
sqrt(5.617) would return 2.37002109695251
StdDev Function
In Oracle/PLSQL, the stddev function returns the standard deviation of a set of numbers.
The stddev function can be used two ways - as an Aggregate function or as an Analytic function.
For Example:
select stddev(bonus)
from employees;
The SQL statement above would return the standard deviation of the bonus field in the employees table.
For Example:
The SQL statement above would return the cumulative standard deviation of the bonuses in the Marketing
department in the employees table, ordered by salary.
SUM Function
67
none
GE Confidential
The SUM function returns the summed value of an expression.
SELECT SUM(expression )
FROM tables
WHERE predicates;
Simple Example
For example, you might wish to know how the combined total salary of all employees whose salary is above
$25,000 / year.
In this example, we've aliased the sum(salary) field as "Total Salary". As a result, "Total Salary" will display
as the field name when the result set is returned.
If there were two salaries of $30,000/year, only one of these values would be used in the SUM function.
You might also want to perform a mathematical operation within a SUM function. For example, you might
determine total commission as 10% of total sales.
68
none
GE Confidential
SELECT SUM(sales * 0.10) as "Commission"
FROM order_details;
For example, you could also use the SUM function to return the name of the department and the total sales
(in the associated department).
Because you have listed one column in your SELECT statement that is not encapsulated in the SUM
function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP
BY section.
Tan Function
tan( n )
For example:
Tanh Function
tanh( n )
n is a number.
69
none
GE Confidential
For example:
In Oracle/PLSQL, the trunc function returns a date truncated to a specific unit of measure.
format is the unit of measure to apply for truncating. If the format parameter is omitted, the trunc function
will truncate the date to the day value, so that any hours, minutes, or seconds will be truncated off.
For example:
70
none
GE Confidential
Trunc Function (with numbers)
In Oracle/PLSQL, the trunc function returns a number truncated to a certain number of decimal places.
decimal_places is the number of decimal places to truncate to. This value must be an integer. If this
parameter is omitted, the round function will truncate the number to 0 decimal places.
For example:
Var_pop Function
In Oracle/PLSQL, the var_pop function returns the population variance of a set of numbers.
var_pop( expression )
The var_pop function eliminates all null values before performing its calculations.
For example:
select var_pop(data_length)
from all_tab_columns;
Var_samp Function
71
none
GE Confidential
In Oracle/PLSQL, the var_samp function returns the sample variance of a set of numbers.
var_samp( expression )
The var_samp function eliminates all null values before performing its calculations.
For example:
select var_samp(char_length)
from all_tab_columns;
Variance Function
variance( expression )
For example:
select variance(char_length)
from all_tab_columns;
5. Date Functions:
Add_Months Function
add_months( date1, n )
date1 is the starting date (before the n months have been added.
72
none
GE Confidential
n is the number of months to add to date1.
For example:
Current_Date function
In Oracle/PLSQL, the current_date function returns the current date in the time zone of the current SQL
session as set by the ALTER SESSION command.
current_date
For example:
select current_date
from dual;
9/10/2005 10:58:24 PM
You then modified the session time zone with the following ALTER SESSION command:
select current_date
from dual;
9/11/2005 3:58:24 AM
73
none
GE Confidential
The session time zone value has changed from -7:0 to -2:0, causing the current_date function to return the
current date as a value 5 hours ahead.
Current_Timestamp function
In Oracle/PLSQL, the current_timestamp function returns the current date and time in the time zone of the
current SQL session as set by the ALTER SESSION command. It returns a TIMESTAMP WITH TIME ZONE
value.
A similar function to the current_timestamp function is the localtimestamp function. The difference
between these two functions is that the current_timestamp function returns a TIMESTAMP WITH TIME
ZONE value while the localtimestamp function returns a TIMESTAMP value.
current_timestamp
For example:
select current_timestamp
from dual;
You then modified the session time zone with the following ALTER SESSION command:
select current_timestamp
from dual;
The session time zone value has changed from -7:0 to -2:0, causing the current_timestamp function to
return the current date and time as a value 5 hours ahead.
Tz_Offset Function
74
none
GE Confidential
In Oracle/PLSQL, the tz_offset function returns the time zone offset of a value.
tz_offset( timezone )
timezone can be a valid time zone name, a time zone offset from UTC, the sessiontimezone function, or
the dbtimezone function.
Canada/Atlantic Pacific/Easter
Canada/Central Pacific/Honolulu
Canada/East-Saskatchewan Pacific/Kwajalein
Canada/Eastern Pacific/Pago_Pago
Canada/Mountain Pacific/Samoa
Canada/Newfoundland US/Alaska
Canada/Pacific US/Aleutian
Canada/Saskatchewan US/Arizona
Canada/Yukon US/Central
Europe/Dublin US/East-Indiana
Europe/Istanbul US/Eastern
Europe/Lisbon US/Hawaii
Europe/London US/Michigan
Europe/Moscow US/Mountain
Europe/Warsaw US/Pacific
Greenwich US/Pacific-New
Pacific/Auckland US/Samoa
Pacific/Chatham
To find more time zone values, you can run the following query:
For example:
DbTimeZone Function
75
none
GE Confidential
In Oracle/PLSQL, the dbtimezone function returns the database time zone as a time zone offset (in the
following format: '[+|-]TZH:TZM') or a time zone region name.
dbtimezone
For example:
select dbtimezone
from dual;
+00:00
-07:00
The value returned depends on the time zone value set in your individual Oracle database.
From_Tz function
In Oracle/PLSQL, the from_tz function converts a TIMESTAMP value (given a TIME ZONE) to a
TIMESTAMP WITH TIME ZONE value.
time_zone_value is the time zone used to convert timestamp_value to a TIMESTAMP WITH TIME ZONE
value.
For example:
76
none
GE Confidential
select from_tz(TIMESTAMP '2005-09-11 01:50:42', '5:00')
from dual;
If you executed the same SQL statement, but set the time zone to '-7:00' as follows:
Last_Day Function
In Oracle/PLSQL, the last_day function returns the last day of the month based on a date value.
last_day( date )
date is the date value to use to calculate the last day of the month.
For example:
LocalTimestamp function
In Oracle/PLSQL, the localtimestamp function returns the current date and time in the time zone of the
current SQL session as set by the ALTER SESSION command. It returns a TIMESTAMP value.
A similar function to the localtimestamp function is the current_timestamp function. The difference
between these two functions is that the localtimestamp function returns a TIMESTAMP value while the
current_timestamp function returns a TIMESTAMP WITH TIME ZONE value.
localtimestamp
77
none
GE Confidential
For example:
select localtimestamp
from dual;
10-Sep-05 10.58.24 PM
You then modified the session time zone with the following ALTER SESSION command:
select localtimestamp
from dual;
10-Sep-05 03.58.24 AM
The session time zone value has changed from -7:0 to -2:0, causing the localtimestamp function to return
the current date and time as a value 5 hours ahead.
New_Time Function
In Oracle/PLSQL, the new_time function returns a date in time zone1 to a date in time zone2.
Value Description
AST Atlantic Standard Time
ADT Atlantic Daylight Time
BST Bering Standard Time
BDT Bering Daylight Time
CST Central Standard Time
CDT Central Daylight Time
78
none
GE Confidential
EST Eastern Standard Time
EDT Eastern Daylight Time
GMT Greenwich Mean Time
HST Alaska-Hawaii Standard Time
HDT Alaska-Hawaii Daylight Time
MST Mountain Standard Time
MDT Mountain Daylight Time
NST Newfoundland Standard Time
PST Pacific Standard Time
PDT Pacific Daylight Time
YST Yukon Standard Time
YDT Yukon Daylight Time
For example:
The following new_time example converts an Atlantic Standard Time into a Mountain Standard Time:
Next_Day Function
In Oracle/PLSQL, the next_day function returns the first weekday that is greater than a date.
weekday is a day of the week (ie: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY)
For example:
79
none
GE Confidential
In Oracle/PLSQL, the round function returns a date rounded to a specific unit of measure.
format is the unit of measure to apply for rounding. If the format parameter is omitted, the round function will
round to the nearest day.
For example:
SessionTimeZone Function
80
none
GE Confidential
In Oracle/PLSQL, the sessiontimezone function returns the current session's time zone as a time zone
offset (in the following format: '[+|-]TZH:TZM') or a time zone region name.
sessiontimezone
For example:
select sessiontimezone
from dual;
+00:00
-07:00
The value returned depends on how the user specified the session time zone value in the most recent
ALTER SESSION statement. An example of an ALTER SESSION command is:
Months_Between Function
In Oracle/PLSQL, the months_between function returns the number of months between date1 and date2.
date1 and date2 are the dates used to calculate the number of months.
If a fractional month is calculated, the months_between function calculates the fraction based on a 31-day
month.
Example #1
months_between (to_date ('2003/01/01', 'yyyy/mm/dd'), to_date ('2003/03/14', 'yyyy/mm/dd') )
81
none
GE Confidential
Example #2
months_between (to_date ('2003/07/01', 'yyyy/mm/dd'), to_date ('2003/03/14', 'yyyy/mm/dd') )
Example #3
months_between (to_date ('2003/07/02', 'yyyy/mm/dd'), to_date ('2003/07/02', 'yyyy/mm/dd') )
would return 0
Example #4
months_between (to_date ('2003/08/02', 'yyyy/mm/dd'), to_date ('2003/06/02', 'yyyy/mm/dd') )
would return 2
SysTimestamp function
In Oracle/PLSQL, the systimestamp function returns the current system date and time (including fractional
seconds and time zone) on your local database.
systimestamp
For example:
select systimestamp
from dual;
03-11-21 20:4
You can also choose to use the to_char function with the systimestamp function. For example:
82
none
GE Confidential
4141.550774
To_Char Function
format_mask is optional. This is the format that will be used to convert value to a string.
nls_language is optional. This is the nls language used to convert value to a string.
Examples - Numbers
The following are number examples for the to_char function.
Examples - Dates
The following is a list of valid parameters when the to_char function is used to convert a date to a string.
These parameters can be used in many combinations.
Parameter Explanation
YEAR Year, spelled out
YYYY 4-digit year
YYY Last 3, 2, or 1 digit(s) of year.
YY
Y
IYY Last 3, 2, or 1 digit(s) of ISO year.
IY
I
IYYY 4-digit year based on the ISO standard
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
83
none
GE Confidential
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
WW Week of year (1-53) where week 1 starts on the first day of the year and
continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and
ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
FF Fractional seconds.
You will notice that in some examples, the format_mask parameter begins with "FM". This means that zeros
and blanks are suppressed. This can be seen in the examples below.
The zeros have been suppressed so that the day component shows as "9" as opposed to "09".
84
none
GE Confidential
Frequently Asked Questions
Question: Why doesn't this sort the day's of the week in order?
Answer:
The fmDay parameter will return the name of the Day and not the numeric value of the day.
Try the following:
Sysdate function
In Oracle/PLSQL, the sysdate function returns the current system date and time on your local database.
sysdate
Example #1
select sysdate
into v_date
from dual;
The variable called v_date will now contain the current date and time value.
Example #2
You could also use the sysdate function in any SQL statement. For example:
Example #3
If you wanted to extract the date portion only (and exclude the time component), you could use the to_char
function. For example:
85
none
GE Confidential
select supplier_id, to_char(sysdate, 'yyyy/mm/dd')
from suppliers
where supplier_id > 5000;
To_Date Function
format_mask is optional. This is the format that will be used to convert string1 to a date.
nls_language is optional. This is the nls language used to convert string1 to a date.
The following is a list of options for the format_mask parameter. These parameters can be used in many
combinations.
Parameter Explanation
YEAR Year, spelled out
YYYY 4-digit year
YYY
YY Last 3, 2, or 1 digit(s) of year.
Y
IYY
IY Last 3, 2, or 1 digit(s) of ISO year.
I
IYYY 4-digit year based on the ISO standard
Accepts a 2-digit year and returns a 4-digit year.
RRRR A value between 0-49 will return a 20xx year.
A value between 50-99 will return a 19xx year.
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
Week of year (1-53) where week 1 starts on the first day of the year
WW
and continues to the seventh day of the year.
Week of month (1-5) where week 1 starts on the first day of the
W
month and ends on the seventh.
86
none
GE Confidential
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
Fractional seconds. Use a value from 1 to 9 after FF to indicate the
FF
number of digits in the fractional seconds. For example, 'FF4'.
AM, A.M., PM, or P.M. Meridian indicator
AD or A.D AD indicator
BC or B.C. BC indicator
TZD Daylight savings information. For example, 'PST'
TZH Time zone hour.
TZM Time zone minute.
TZR Time zone region.
For example:
In Oracle/PLSQL, the trunc function returns a date truncated to a specific unit of measure.
87
none
GE Confidential
format is the unit of measure to apply for truncating. If the format parameter is omitted, the trunc function
will truncate the date to the day value, so that any hours, minutes, or seconds will be truncated off.
For example:
6. Error Functions:
SQLCODE Function
88
none
GE Confidential
EXCEPTION
WHEN exception_name1 THEN
[statements]
END [procedure_name];
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;
EXCEPTION
WHEN OTHERS THEN
err_code := SQLCODE;
err_msg := substr(SQLERRM, 1, 200);
SQLERRM Function
EXCEPTION
WHEN exception_name1 THEN
[statements]
END [procedure_name];
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;
EXCEPTION
WHEN OTHERS THEN
err_code := SQLCODE;
err_msg := substr(SQLERRM, 1, 200);
7. Miscellaneous Functions:
Uid function
In Oracle/PLSQL, the uid function returns the id number for a user's session (the user who is currently
logged in).
uid
For example:
select uid
into parm_uid
from dual;
The variable called parm_uid will now contain the id number for the user's session. The value could be 25,
for example.
90
none
GE Confidential
User function
In Oracle/PLSQL, the user function returns the user_id from the current Oracle session.
user
For example:
select user
into parm_user_ID
from dual;
The variable called parm_user_ID will now contain the Oracle user ID from the current
Oracle session.
91
none
GE Confidential