0% found this document useful (0 votes)
138 views

Reguler Functions in SQL

The document discusses different types of functions available in SQL including single-row functions that operate on single rows and return one result per row, and multiple-row functions that can manipulate groups of rows to return one result per group. It provides examples of numeric, character, date, and conversion single-row functions and their purposes.

Uploaded by

pawan_32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views

Reguler Functions in SQL

The document discusses different types of functions available in SQL including single-row functions that operate on single rows and return one result per row, and multiple-row functions that can manipulate groups of rows to return one result per group. It provides examples of numeric, character, date, and conversion single-row functions and their purposes.

Uploaded by

pawan_32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

What are the different types of function available in SQL ?

There are two types of functions:


• Single-row functions
• Multiple-row functions
Single-Row Functions
These functions operate on single rows only and return one result per row. There are different
types of single-row functions. This lesson covers the following ones:
• Character functions: ccept character input and can return both character and number values
• Number functions: Accept numeric input and return numeric values
• Date functions: Operate on values of the DATE data type (All date functions return a value of
DATE data type except the MONTHS_BETWEEN function, which returns a number.)
• Conversion functions: Convert a value from one data type to another
• General functions:
- NVL - NVL2 – NULLIF – COALESCE – CASE - DECODE
Multiple-Row Functions
Functions can manipulate groups of rows to give one result per group of rows. These functions are
also known as group functions

Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric functions that
return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS,
COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The
transcendental

Function Name Purpose Example


ABS ABS ( n ) ABS returns the absolute value of n. SELECT ABS(-15) "Absolute" FROM DUAL;
--ANS=>15
ACOS ACOS ( n ) ACOS returns the arc cosine of n. The argument SELECT ACOS(.3)"Arc_Cosine" FROM
DUAL; --ANS=>1.266
n must be in the range of -1 to 1, and the function
returns a value in the range of 0 to pi, expressed
in radians.
ASIN ASIN ( n ) ASIN returns the arc sine of n. The argument n SELECT ASIN(.3) "Arc_Sine" FROM
must be in the range of - 1 to 1, and the function DUAL; --ANS=>0.30469
returns a value in the range of -pi/2 to pi/2,
expressed in radians.
ATAN ATAN ( n ) ATAN returns the arc tangent of n. The argument SELECT ATAN(.3) "Arc_Tangent" FROM
DUAL; --ANS=>0.291
n can be in an unbounded range and returns a
value in the range of -pi/2 to pi/2, expressed in
radians.
FLOOR FLOOR ( n ) FLOOR returns largest integer equal to or less SELECT FLOOR(23.78)FROM DUAL;
ans=>23
than n.
CEIL CEIL ( n ) CEIL returns smallest integer greater than or SELECT CEIL(23.668)FROM DUAL;
ans=>24
equal to n.
COS COS ( n ) COS returns the cosine of n (an angle expressed SELECT COS(180 *
in radians). 3.14159265359/180) "Cosine of
180 degrees" FROM DUAL; --ANS=>1
COSH COSH ( n ) COSH returns the hyperbolic cosine of n. SELECT COSH(0) "Hyperbolic cosine
of 0" FROM DUAL; --ANS=>1
EXP EXP ( n ) EXP returns e raised to the nth power, where e SELECT EXP(4) "e to the 4th
power" FROM DUAL; --ANS=>54.59
= 2.71828183 ...
LN LN ( n ) LN returns the natural logarithm of n, where n is SELECT LN(95) "Natural log of 95"
FROM DUAL; --ANS=>4.5538
greater than 0.
LOG LOG ( n2 , n1 ) LOG returns the logarithm, base n2, of n1. SELECT LOG(10,100) "Log base 10
of 100" FROM DUAL; --ANS=>2
The base n1 can be any positive value other
than 0 or 1 and n2 can be any positive value.
MOD MOD ( n2 , n1 ) MOD returns the remainder of n2 divided by n1. SELECT MOD(11,4) "Modulus" FROM
DUAL; --ANS=>3
Returns n2 if n1 is 0.
The MOD function is similar to REMAINDER
except that it uses FLOOR in its formula,
whereas REMAINDER uses ROUND
REMAINDER REMAINDER returns the remainder of n2 SELECT bin_float,bin_double,
REMAINDE( n2 , n1 ) divided by n1. REMAINDER(bin_float,bin_double)F
ROM float_point_demo;
NANVL The NANVL function is useful only for floating- SELECT bin_float,
NANVL(bin_float,0) FROM
NANVL ( n2 , n1 ) point numbers of type BINARY_FLOAT or float_point_demo;
BINARY_DOUBLE. It instructs Oracle
Database to return an alternative value n1 if the
input value n2 is NaN (not a number). If n2 is not
NaN, then Oracle returns n2. This function is
useful for mapping NaN values to NULL.
POWER POWER returns n2 raised to the n1 power. The SELECT POWER(3,2) "Raised" FROM
base n2 and the exponent n1 can be any numbers, DUAL; --ANS =>9
POWER ( n2 , n1 )
but if n2 is negative, then n1 must be an integer.
ROUND (number) ROUND returns n rounded to integer places to SELECT ROUND(45.93738) FROM DUAL;
the right of the decimal point. --ANS =>46
ROUND
If you omit integer, then n is rounded to 0 SELECT ROUND(45.93738,0) FROM
(column|expression,n) places. DUAL; --ANS =>46
Rounds the column, expression, The argument integer can be negative to round SELECT ROUND(45.93738,2) FROM
or value to ndecimal places or, off digits left of the decimal point. DUAL; --ANS =>45.94
if nis omitted, no decimal
. SELECT ROUND(45.93738,-1) FROM
DUAL; --ANS =>50
places (If n is negative, numbers SELECT ROUND(46.93738,-1) FROM
to left of the decimal point are DUAL; --ANS =>0
rounded.) SELECT ROUND(41.93738,-1) FROM
DUAL; --ANS =>0
SELECT ROUND(45.93738,-4) FROM
DUAL; --ANS =>0
TRUNC (number) The TRUNC (number) function returns n1 SELECT TRUNC(45.93738) FROM DUAL;
--ANS =>45
TRUNC(column|expressi truncated to n2 decimal places. If n2 is omitted, SELECT TRUNC(45.93738,0) FROM
on,n) then n1 is truncated to 0 places. n2 can be DUAL; --ANS =>45
Truncates the column, negative to truncate (make zero) n2 digits left of SELECT TRUNC(45.93738,2) FROM
the decimal point. DUAL; --ANS =>45.93
expression, or value to n SELECT TRUNC(45.93738,-1) FROM
decimal places or, if nis DUAL; --ANS =>40
omitted, n defaults to zero SELECT TRUNC(47.93738,-1) FROM
DUAL; --ANS =>0
SELECT TRUNC(41.93738,-1) FROM
DUAL; --ANS =>0
SELECT TRUNC(45.93738,-4) FROM
DUAL; --ANS =>0
SIGN SIGN ( n ) SIGN returns the sign of n. This function SELECT SIGN(-15) "Sign" FROM DUAL;
takes as an argument any numeric datatype, or --ANS =>-1
any nonnumeric datatype that can be
implicitly converted ton NUMBER, and returns
NUMBER.
SIN SINH ( n ) SINH returns the hyperbolic sine of n. SELECT SINH(1) "Hyperbolic sine
of 1" FROM DUAL; --ANS =>1.172
SINH SINH ( n ) SINH returns the hyperbolic sine of n. SELECT SINH(1) "Hyperbolic sine
of 1" FROM DUAL; --ANS =>1.175
SQRT SQRT ( n ) SQRT returns the square root of n. SELECT SQRT(26) "Square root" FROM
DUAL; --ANS =>5.09
TAN TAN ( n ) TAN returns the tangent of n (an angle expressed SELECT TAN(135 *
in radians). 3.14159265359/180)"Tangent of
135 degrees" FROM DUAL; --ANS =>-
0.9999
TANH TANH ( n ) TANH returns the hyperbolic tangent of n. SELECT TANH(.5) "Hyperbolic
tangent of .5"FROM DUAL; --ANS
=>0.461
GREATEST GREATEST ( GREATEST returns the greatest of the list of SELECT GREATEST
('HARRY','HARRIOT','HAROLD')
expr , ) one or more expressions. "Greatest" FROM DUAL; --ANS
=>HARRY
LEAST LEAST returns the least of the list of exprs. All SELECT GREATEST
LEAST ( expr , ) ('HARRY','HARRIOT','HAROLD')
exprs after the first are implicitly converted to the "Greatest" FROM DUAL; --ANS =>
datatype of the first expr before the comparison. HAROLD
Oracle Database compares the exprs using
nonpadded comparison semantics.
GROUP OR AGGREGATE FUNCTIONS

Function Name Purpose Example


AVG AVG returns average value of expr. SELECT AVG(salary) "Average" FROM
employees;-- Average =>6425
AVG ( DISTINCT ALL expr
) OVER ( analytic_clause )
CORR CORR returns the coefficient of correlation of a SELECT CORR(list_price,
min_price) FROM
CORR ( expr1 , expr2 ) set of number pairs. You can use it as an aggregate product_information GROUP BY
OVER ( analytic_clause ) or analytic function. weight_class;

COUNT The COUNT function has three formats: SELECT * FROM EMPLOYEES; ANS :-
COUNT ( * DISTINCT ALL • COUNT(*) TOTAL 107 ROW
SELECT COUNT(*) FROM EMPLOYEES;
Expr ) • COUNT(expr) ANS :- 107
OVER ( analytic_clause ) • COUNT(DISTINCT expr) SELECT COUNT(*) FROM EMPLOYEES
COUNT(*) returns the number of rows in a table WHERE DEPARTMENT_ID =50; ANS :- 45
that satisfy the criteria of the SELECT statement, SELECT COUNT(DEPARTMENT_ID) FROM
EMPLOYEES; ANS :- 106 AS 1 IS NULL
including duplicate rows and rows containing null
SELECT
values in any of the columns. COUNT(NVL(DEPARTMENT_ID,8)) FROM
EMPLOYEES ; ANS :- 107 INCLUDING 1
If a WHERE clause is included in the SELECT NULL NULL
statement, COUNT(*) returns the number of rows SELECT COUNT(DEPARTMENT_ID) FROM
EMPLOYEES WHERE DEPARTMENT_ID
that satisfy the condition in the WHERE clause. =50; ANS :- 45
SELECT COUNT(DISTINCT
In contrast, COUNT(expr) returns the number of DEPARTMENT_ID) FROM EMPLOYEES;
non-null values that are in the column identified by ANS :- 11
SELECT COUNT(DISTINCT
expr. DEPARTMENT_ID) FROM EMPLOYEES
COUNT(DISTINCT expr) returns the number of WHERE DEPARTMENT_ID=50; ANS :- 1
unique, non-null values that are in the column SELECT
identified by expr. COUNT(NVL(COMMISSION_PCT,9))
FROM EMPLOYEES; ANS :- 107 WITH
COUNT(DISTINCT expr) returns the number of NULL
distinct non-null values of expr. SELECT COUNT(1) FROM DUAL; --
ANS=>1
SELECT COUNT(10) FROM EMP; --
ANS=>14
SELECT COUNT(10) FROM DUAL; --
ANS=>1
SELECT COUNT(2) FROM EMP ; --
ANS=>14
MAX MAX ( MAX returns maximum value of expr. You can SELECT MAX(salary) "Maximum" FROM
employees; --ANS=> 2400
DISTINCT ALL expr ) use it as an aggregate or analytic function.
OVER ( nalytic_clause)
MEDIAN MEDIAN is an inverse distribution function SELECT DEPARTMENT_ID,
MEDIAN ( expr ) MEDIAN(SALARY) FROM EMPLOYEES
that assumes a continuous distribution model. It GROUP BY DEPARTMENT_ID;
OVER ( takes a numeric or datetime value and returns the DEPARTMENT_ID MEDIAN(SALARY)
query_partition_clause ) middle value or an interpolated value that would ------------- --------------
be the middle value once the values are sorted. 10 4400
20 9500
Nulls are ignored in the calculation. 30 2850
If you specify only expr, then the function returns 40 6500
the same datatype as the numeric datatype of the 50 3100
argument. if you specify the OVER clause, then 60 4800
70 10000
Oracle Database determines the argument with the 80 8900
highest numeric precedence, implicitly converts the 90 17000
remaining arguments to that datatype, and returns 100 8000
that datatype. 110 10150
7000

MIN MIN returns minimum value of expr. You can SELECT MIN(HIRE_DATE) "Earliest"
MIN ( DISTINCT ALL FROM EMPLOYEES; --ANS=>17-JUN-87
use it as an aggregate or analytic function.
expr )
OVER ( nalytic_clause )
STDDEV STDDEV returns the sample standard deviation of SELECT STDDEV OVER (SALARY)
"Deviation" FROM
STDDEV ( DISTINCT expr, a set of numbers. You can use it as both an EMPLOYEES;Deviation
ALL expr ) aggregate and analytic function. It differs from ----------
OVER ( analytic_clause ) STDDEV_SAMP in that STDDEV returns zero 3909.36575
when it has only 1 row of input data, whereas
STDDEV_SAMP returns null.
SUM SUM returns the sum of values of expr. You SELECT SUM(salary) "Total" FROM
employees; --ANS=>691400
SUM ( DISTINCT ALL can use it as an aggregate or analytic function.
expr )
OVER ( analytic_clause )
VARIANCE VARIANCE returns the variance of expr. You can SELECT VARIANCE(salary)
VARIANCE ( DISTINCT "Variance" FROM employees; --
use it as an aggregate or analytic function. ANS=>15283140.5
ALL Oracle Database calculates the variance of
expr ) OVER ( expr as follows:
analytic_clause ) ■ 0 if the number of rows in expr = 1
■ VAR_SAMP if the number of rows in expr > 1
If you specify DISTINCT, then you can specify
only the query_partition_clause of the
analytic_clause. The order_by_clause and
windowing_clause are not allowed.

Character Functions Returning Character Values


Character functions that return character values return values of the following datatypes unless
otherwise documented:
• If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2.
• If the input argument is NCHAR or NVARCHAR2, then the value returned is NVARCHAR2.
The length of the value returned by the function is limited by the maximum length of the
datatype returned.
• For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the
limit, then Oracle Database truncates it and returns the result without an error message.
• For functions that return CLOB values, if the length of the return values exceeds the limit,
then Oracle raises an error and returns no data. SQL Functions

Function Name Purpose Example


CHR CHR returns the character having the binary SELECT CHR(67)||CHR(65)||CHR(84)
"Dog" FROM DUAL;--ANS=>CAT
equivalent to n as a VARCHAR2 value in either
the database character set or, if you specify
USING NCHAR_CS, the national character set.
For single-byte character sets, if n > 256, then
Oracle Database returns the binary equivalent of
n mod 256. For multibyte character sets, n must
resolve to one entire code point. Invalid code
points are not validated, and the result of
specifying invalid code points is indeterminate.
This function takes as an argument a NUMBER
value, or any value that can be implicitly converted
to NUMBER, and returns a character.
CONCAT CONCAT CONCAT returns char1 concatenated with char2. SELECT CONCAT(CONCAT(last_name,
(column1|expression1, '''s jobcategory is '),job_id)
Both char1 and char2 can be any of the "Job" FROM employeesWHERE
column2|expression2) datatypes CHAR, VARCHAR2, NCHAR, employee_id = 152;
NVARCHAR2, CLOB, or NCLOB. The string CONCAT('Hello', 'World')=>
Concatenates the first returned is in the same character set as char1. Its HelloWorld
character value to the second datatype depends on the datatypes of the
character value; equivalent to arguments.
concatenation operator (||)
■ CONCAT(CLOB, NCLOB) returns NCLOB
■ CONCAT(NCLOB, NCHAR) returns NCLOB
■ CONCAT(NCLOB, CHAR) returns NCLOB
■ CONCAT(NCHAR, CLOB) returns NCLOB
INITCAP INITCAP INITCAP returns char, with the first letter of SELECT INITCAP('the soap')
(column|expression) "Capitals" FROM DUAL;
each word in uppercase, all other letters in SELECT INITCAP(ENAME) FROM EMP;
lowercase.
Converts alpha character values to uppercase for
the first letter of each word; all other letters in
lowercase
LOWER LOWER returns char, with all letters lowercase. SELECT LOWER('the soap')
LOWER(column|expression) "Capitals" FROM DUAL;
Converts alpha character values to lowercase SELECT LOWER(ENAME) FROM EMP;

UPPER UPPER returns char, with all letters uppercase. SELECT UPPER('the soap')
UPPER(column|expression) "Capitals" FROM DUAL;
Converts alpha character values to uppercase SELECT UPPER(ENAME) FROM EMP;

LPAD LPAD returns expr1, left-padded to length n SELECT


LPAD(column|expression,n,' LPAD/RPAD('PANKAJPATIL',14,'%')
characters with the sequence of characters in FROM DUAL; --ANS=>%%%PANKAJPATIL
string') expr2. This function is useful for formatting the SELECT LPAD(ENAME,14,'%') FROM
output of a query. EMP; --ANS=>%%%PANKAJPATIL
Pads the character value The argument n must be a NUMBER integer .
right-justified to a total width SELECT
If you do not specify expr2, then the default is a LPAD/RPAD('PANKAJPATIL',-
of n character positions single blank. If expr1 is longer than n, then this 14,'%') FROM DUAL; --ANS=>NULL
function returns the portion of expr1 that fits in n. SELECT
LPAD('PANKAJPATIL',14,'%',-8)
FROM DUAL; --ANS=>ERROR
RPAD RPAD returns expr1, right-padded to length n SELECT
LPAD/RPAD('PANKAJPATIL',-
RPAD(column|expression,n,' characters with expr2, replicated as many times as 14,'%') FROM DUAL; --ANS=>NULL
string') necessary. SELECT
Pads the character value left-justified to a total LPAD('PANKAJPATIL',14,'%',-8)
width of n character positions FROM DUAL; --ANS=>ERROR
TRIM TRIM enables you to trim leading or trailing SELECT employee_id,TRIM(LEADING
TRIM(leading|trailing|b characters (or both) from a character string. If 0 FROM hire_date)FROM employees;-
oth, trim_character trim_character or trim_source is a character -ANS=>7-JUN-02
SELECT employee_id,TRIM(TRAILING
FROM trim_source) literal, then you must enclose it in single quotes. 0 FROM hire_date)FROM employees;
■ If you specify LEADING, then Oracle SELECT employee_id,TRIM(BOTH 0
Enables you to trim heading Database removes any leading characters equal FROM hire_date)FROM employees;
or trailing characters (or to trim_character. TRIM('H' FROM 'HelloWorld')=>
elloWorld
both) from a character ■ If you specify TRAILING, then Oracle
string. If trim_characteror removes any trailing characters equal to
trim_sourceis a character trim_character.
literal, you must enclose it ■ If you specify BOTH or none of the three, then
in single quotation marks. Oracle removes leading and trailing characters
This is a feature that is equal to trim_character.
available in Oracle8i ■ If you do not specify trim_character, then the
and later versions. default value is a blank space.
■ If you specify only trim_source, then Oracle
removes leading and trailing blank spaces.
■ The function returns a value with datatype
VARCHAR2. The maximum length of the value
is the length of trim_source.
■ If either trim_source or trim_character is null,
then the TRIM function returns null. Both
trim_character and trim_source can be any of
the datatypes CHAR, VARCHAR2,

LTRIM LTRIM removes from the left end of char all of SELECT LTRIM('ABCD','B') FROM
LTRIM ( char , set ) the characters contained in set. If you do not EMP;
specify set, it defaults to a single blank. If char is a
character literal, then you must enclose it in single
quotes. Oracle Database begins scanning char
from its first character and removes all characters
that appear in set until reaching a character not in
set and then returns the result.
RTRIM RTRIM removes from the right end of char all of SELECT RTRIM('ABCD','B') FROM
RTRIM ( char , set ) the characters that appear in set. This function is EMP;
useful for formatting the output of a query.

SUBSTR The SUBSTR functions return a portion of char, SELECT SUBSTR('PANKAJPATIL',1,5)


SUBSTRB FROM DUAL;--ANS=>PANKA
beginning at character position, SELECT SUBSTR('PANKAJPATIL',5,3)
SUBSTRC Substring_length characters long. SUBSTR FROM DUAL;--ANS=>AJP
SUBSTR2 calculates lengths using characters as defined by SELECT SUBSTR('PANKAJPATIL',0,3)
SUBSTR4 the input character set. SUBSTRB uses bytes FROM DUAL;--ANS=>PAN
SUBSTR(column|expression, SELECT SUBSTR('PANKAJPATIL',-
instead of characters. SUBSTRC uses Unicode 2,5) FROM DUAL;--ANS=>IL
m[ complete characters. SUBSTR2 uses UCS2 code SELECT SUBSTR('PANKAJPATIL',-
,n]) points. 2,7) FROM DUAL;--ANS=>IL
SUBSTR(S,M,N) SUBSTR4 uses UCS4 code points. SELECT SUBSTR('PANKAJPATIL',5,1)
S=STRING ■ If position is 0, then it is treated as 1. FROM DUAL;--ANS=>A
SELECT SUBSTR('PANKAJPATIL',5)
M=POSITION ■If position is positive, then Oracle Database FROM DUAL;--ANS=>AJPATIL
N=NO OF CHARECHER counts from the beginning of char to find the SELECT SUBSTR('PANKAJPATIL',1,-
Returns specified characters first character. 5) FROM DUAL;--ANS=>NULL
SELECT SUBSTR('PANKAJPATIL',5,-
from character value starting ■If position is negative, then Oracle counts 3) FROM DUAL;--ANS=>NULL
at character position m, n backward from the end of char. SELECT SUBSTR('PANKAJPATIL',1,0)
characters long (If m is ■ If substring_length is omitted, then Oracle FROM DUAL;--ANS=>NULL
negative, the count starts returns all characters to the end of char. SELECT SUBSTR( 50000-7, 2, 4 ) FROM
from the end of the character If substring_length is less than 1, then Oracle DUAL;--ANS=>993
SELECT SUBSTR ( sysdate, 4, 3) FROM
value. If n is omitted, all returns null. Move forword from Left => DUAL;--ANS=>12-
characters to the end of the right
string are returned.)
SOUNDEX SOUNDEX ( SOUNDEX returns a character string containing SELECT last_name, first_name FROM
employees WHERE
char ) the phonetic representation of char. This function SOUNDEX(last_name)=
lets you compare words that are spelled SOUNDEX('SMYTHE');--FIRST_NAME
differently, but sound alike in English. The SMITH OR LAST_NAME LINDESY
phonetic representation is defined in The Art of
Computer Programming, Volume 3: Sorting and
Searching, by Donald E. Knuth, as follows:
1. Retain the first letter of the string and remove
all other occurrences of the following letters: a,
e, h, i, o, u, w, y.
2. Assign numbers to the remaining letters (after
the first) as follows:B,f,v,=1 c, g, j, k, q, s, x, z =
2
d, t = 3 l = 4
m, n = 5 r = 6
3. If two or more letters with the same number
were adjacent in the original name (before step
1), or adjacent except for any intervening h and
w, then omit all but the first.
4. Return the first four bytes padded with 0. char
can be of any of the datatypes CHAR,
VARCHAR2, NCHAR, or NVARCHAR2. The
return value is the same datatype as char. This
function does not support CLOB data directly.
However, CLOBs can be passed in as arguments
through implicit data conversion.
TREAT TREAT changes the declared type of SELECT name, TREAT(VALUE(p) AS
employee_t).salary salary FROM
TREAT ( expr AS REF an expression. persons p;
schema .type ) You must have the EXECUTE object privilege
on type to use this function.
■ Type must be some super type or subtype of the
declared type of expr. If the most specific type
of expr is type (or some subtype of type), then
TREAT returns expr. If the most specific type of
expr is not type (or some subtype of type),
then TREAT returns NULL.
■ You can specify REF only if the declared type
of expr is a REF type.
■ If the declared type of expr is a REF to a source
type of expr, then type must be some subtype or
supertype of the source type of expr. If the most
specific type of DEREF (expr) is type (or a
subtype of type), then TREAT returns expr. If the
most specific type of DEREF (expr) is not type
(or a subtype of type), then TREAT returns
NULL.
REVERSE (S) IT Is used to reverse the string SELECT reverse(FIRST_NAME) FROM
EMPLOYEES;
TRANSLATE(S,C,C) It is used to translate the character wise in given SELECT
TRANSLATE ( expr , TRANSALTE(‘WELCOME’,’W’,’T’)
string ,if the character is found. FROM DUAL—ANS=>TELCOME
from_string , to_string ) It is possible to translate entire string. SELECT
TRANSALTE(‘ORACLA’,’A’,’M’)
FROM DUAL—ANS=>ORMCLM
SELECT
TRANSALTE(‘ORACLA’,’OR’,’M’)
FROM DUAL—ANS=>MACLA
SELECT
TRANSALTE(‘ORACLA’,’OA’,’M’)
FROM DUAL—ANS=>MRCL
SELECT
TRANSALTE(‘ORACLA’,’OA’,’MB’)
FROM DUAL—ANS=>MRBCLB
TRANSALTE(‘ORACLA’,’ORACLA’,’MB
’) FROM DUAL—ANS=>MB

REPLACE(S,S,S) REPLACE returns char with every SELECT REPLACE('JACK and


JUE','J','BL') "Changes" FROM
REPLACE(text, occurrence of search_string replaced with DUAL;--ANS=> BLACK AND BLUE
search_string, replacement_string. If replacement_string is
replacement_string) omitted or null, then all occurrences of SELECT
search_string are removed. If search_string is REPLACE(FIRST_NAME,'D',123) FROM
EMPLOYEES;
Searches a text expression null, then char is returned.
for a character string and, if Both search_string and replacement_string, as
found, replaces it with a well as char, can be any of the datatypes CHAR,
specified replacement string VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB. The string returned is in the same
character set as char. The function returns
VARCHAR2 if the first argument is not a LOB and
returns CLOB if the first argument is a LOB.
ASCII ASCII returns the decimal representation in the SELECT last_name FROM employees
WHERE ASCII(SUBSTR(last_name, 1,
database character set of the first character of 1,)) = 76;
char. char can be of datatype CHAR,
VARCHAR2, NCHAR, or NVARCHAR2. The
value returned is of datatype NUMBER. If your
database character set is 7-bit ASCII, then this
function returns an ASCII value. If your
database character set is EBCDIC Code, then
this function returns an EBCDIC value. There is
no corresponding EBCDIC character function.
This function does not support CLOB data directly.
However, CLOBs can be passed in as arguments
through implicit data conversion.
INSTR The INSTR functions search string for substring. SELECT INSTR('PANKAJPATIL','K')
INSTR The function returns an integer indicating the FROM DUAL; --ANS=>4
SELECT
INSTRB position of the character in string that is the first INSTR('PANKAJPATIL','K',1) FROM
INSTRC character of this occurrence. INSTR calculates DUAL;--ANS=>4
INSTR2 strings using characters as defined by the input SELECT INSTR('PANKAJPATIL','K',-
INSTR4 character set. INSTRB uses bytes instead of 1) FROM DUAL;--ANS=>4
INSTR(column|expression, SELECT
characters. INSTRC uses Unicode complete INSTR('PANKAJPATIL','K',1,1)
’string’, [,m], [n] ) characters. INSTR2 uses UCS2 code points. FROM DUAL;--ANS=>4
INSTR(S,C,M,N) INSTR4 uses UCS4 code points. SELECT INSTR('PANKAJPATIL','T',-
S=STRING ■ Position is an nonzero integer indicating 1) FROM DUAL;---ANS=>9
SELECT INSTR('PANKAJPATIL','A',-
C=CHARACTER the character of string where Oracle Database
1) FROM DUAL;---ANS=>8
M=POSTION begins the search. If position is negative, then SELECT
N=OCCURANCE Oracle counts backward from the end of INSTR('PANKAJPATIL','J',1,2)
string and then searches backward from the FROM DUAL;--ANS=>0
SELECT
Returns the numeric position resulting position. INSTR('PANKAJPATIL','J',1,-2)
of a named string. ■ Occurrence is an integer indicating which FROM DUAL;--ANS=>ERROR
Optionally, you can provide a occurrence of string Oracle should search for. SELECT
position mto start searching, The value of occurrence must be positive. INSTR('PANKAJPATIL','A',1,1)
FROM DUAL;---ANS=>2 A S 1ST
and the occurrence nof the Both string and substring can be any of the OCCURANCE FORWORD DIRCECTION
string. mand ndefault to 1, datatypes CHAR, VARCHAR2, NCHAR, SELECT
meaning start the search at NVARCHAR2, CLOB, or NCLOB. The value INSTR('PANKAJPATIL','A',1,2)
the beginning of the search returned is of NUMBER datatype. FROM DUAL;---ANS=>5 A S 2ND
OCCURANCE FORWORD DIRCECTION
and report the first Both position and occurrence must be of SELECT
occurrence. datatype NUMBER, or any datatype that can be INSTR('PANKAJPATIL','A',1,3)
implicitly converted to NUMBER, and must FROM DUAL;---ANS=>8 A S 3RD
resolve to an integer. OCCURANCE FORWORD DIRCECTION
SELECT INSTR('PANKAJPATIL','A',-
1,1) FROM DUAL;---ANS=>8 A S 1ST
OCCURANCE REVERSE DIRCECTION
SELECT INSTR('PANKAJPATIL','A',-
1,2) FROM DUAL;---ANS=>5 A S 1ST
OCCURANCE REVERSE DIRCECTION
SELECT INSTR('PANKAJPATIL','A',-
1,3) FROM DUAL;---ANS=>2 A S 1ST
OCCURANCE REVERSE DIRCECTION

LENGTH The LENGTH functions return the length of char. SELECT LENGTH('CANDIDE') "Length
in characters" FROM DUAL;--
LENGTH LENGTH calculates length using characters as ANS=>7
LENGTHB defined by the input character set. LENGTHB SELECT LENGTHB (ENAME) "Length in
LENGTHC LENGTH2 uses bytes instead of characters. LENGTHC bytes"FROM EMP;--ANS=> 14BYTE
LENGTH4 ( char ) uses Unicode complete characters. LENGTH2
uses UCS2 code points. LENGTH4 uses UCS4
code points.
char can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2,
NCLOB. The return value is of datatype
NUMBER. If char has datatype CHAR,
then the length includes all trailing blanks. If char
is null, then this function returns null.
Restriction on LENGTHB The LENGTHB
function is supported for single- byte LOBs only.
It cannot be used with CLOB and NCLOB data in a
multibyte character set.

DATE FUNCTION
Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME
ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL DAY TO SECOND,
INTERVAL YEAR TO MONTH) values. Some of the datetime functions were designed for the Oracle
DATE datatype (ADD_MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you
provide a timestamp value as their argument, Oracle Database internally converts the input type to a
DATE value and returns a DATE value. The exceptions are the MONTHS_BETWEEN function, which
returns a number, and the ROUND and TRUNC functions, which do not accept timestamp or interval
values at all. The remaining datetime functions were designed to accept any of the three types of data
(date, timestamp, and interval) and to return a value of one of these types. The datetime functions
are:
Operation Result Description
date + number Date Adds a number of days to a date
date – number Date Subtracts a number of days from a date
date – date Number of days Subtracts one date from another
date + number/24 Date Adds a number of hours to a date

Function Name Purpose Example


ADD_MONTHS ADD_MONTHS returns the date date plus integer SELECT ADD_MONTHS('21-10-18',2)
FROM DUAL; --ANS =>21-12-18
months. The date argument can be a datetime SELECT ADD_MONTHS('21-10-18',-2)
ADD_MONTHS(date, n) value or any value that can be implicitly converted FROM DUAL; --ANS =>21-08-18
Adds n number of to DATE. The integer argument can be an integer
calendar months to date. or any value that can be implicitly converted to an
The value of nmust be an integer. The return type is always DATE,
integer and can be negative. regardless of the datatype of date. If te is the last
day of the month or if the resulting month has
fewer days than the day component of date, then
the result is the last day of the resulting month.
Otherwise, the result has the same day component
as date.
MONTHS_BETWEEN MONTHS_BETWEEN returns number of months SELECT
MONTHS_BETWEEN(SYSDATE,HIREDATE
between dates date1 and date2. If date1 is later ) FROM EMP;
MONTHS_BETWEEN(dat than date2, then the result is positive. If date1 is
e1, date2) earlier than date2, then the result is negative. If
Finds the number of date1 and date2 are either the same days of the
months between date1 and month or both last days of months, then the result
date2. is always an integer. Otherwise Oracle Database
The result can be positive calculates the fractional portion of the result
or negative. If date1is later based on a 31-day month and considers the
than date2, the result is difference in time components date1 and
positive; if date1is earlier date2.
than date2, the result is
negative. The noninteger part
of the result represents a
portion of the month.
NEXT_DAY NEXT_DAY returns the date of the first weekday SELECT NEXT_DAY('21-10-
18','MONDAY') FROM DUAL; --
named by char that is later than the date date. The ANS=>24-10-18
NEXT_DAY(date, return type is always DATE, regardless of the SELECT NEXT_DAY('21-10-18',3)
'char') datatype of date. The argument char must be a day FROM DUAL; --ANS =>23-10-18
Finds the date of the next of the week in the date language of your session,
specified day of the either the full name or the abbreviation. The
week ('char') following minimum number of letters required is the number
date. of letters in the abbreviated version. Any
The value of char may be a characters immediately following the valid
number representing a day or abbreviation are ignored. The return value has the
a character string same hours, minutes, and seconds component as
the argument date.
LAST_DAY LAST_DAY returns the date of the last day of the --CURRENT DATE 01/02/2019
SELECT LAST_DAY(SYSDATE) FROM
month that contains date. The return type is DUAL;--ANS=>2/28/2019 11:09:31
LAST_DAY(date) always DATE, regardless of the datatype of date. PM

Finds the date of the last day


of the month that contains
date
ROUND (date) ROUND returns date rounded to the unit SELECT ROUND(SYSDATE,'DAY') FROM
DUAL; --ANS =>23-12-18
ROUND(date[,'fmt']) specified by the format model fmt. The value SELECT ROUND(SYSDATE,'D') FROM
returned is always of datatype DATE, even if you DUAL; --ANS =>23-12-18
Returns daterounded to the specify a different datetime datatype for date. If SELECT ROUND(SYSDATE,'DD') FROM
unit that is specified by the you omit fmt, then date is rounded to the nearest DUAL; --ANS =>22-12-18
SELECT ROUND(SYSDATE,'DDD') FROM
format model fmt. If the day. The date expression must resolve to a DATE DUAL; --ANS =>22-12-18
format model fmt is omitted, value. SELECT ROUND(SYSDATE,'W') FROM
date is rounded to the nearest DUAL; --ANS =>22-12-18
day. SELECT ROUND(SYSDATE,'WW') FROM
DUAL; --ANS =>24-12-18
SELECT ROUND(SYSDATE,'MM') FROM
DUAL; --ANS =>01-01-19
SELECT ROUND(SYSDATE,'MON') FROM
DUAL; --ANS =>01-01-19
SELECT ROUND(SYSDATE,'MONTH')
FROM DUAL; --ANS =>01-01-19
SELECT ROUND(SYSDATE,'YEAR')
FROM DUAL; --ANS =>01-01-19
TRUNC (date) The TRUNC (date) function returns date with the --TRUNC POSIBILITY--
SELECT TRUNC(SYSDATE,'DAY') FROM
TRUNC(date[, 'fmt']) time portion of the day truncated to the unit DUAL; --ANS =>16-12-18
specified by the format model fmt. The value SELECT TRUNC(SYSDATE,'D') FROM
Returns datewith the time returned is always of datatype DATE, even if you DUAL; --ANS =>16-12-18
specify a different datetime datatype for date. If SELECT TRUNC(SYSDATE,'DD') FROM
portion of the day truncated DUAL; --ANS =>21-12-18
to the unit that is specified by you omit fmt, then date is truncated to the nearest SELECT TRUNC(SYSDATE,'DDD') FROM
the format model fmt. If the day. DUAL; --ANS =>21-12-18
format model fmtis omitted, t. SELECT TRUNC(SYSDATE,'W') FROM
DUAL; --ANS =>15-12-18
dateis truncated to the nearest SELECT TRUNC(SYSDATE,'WW') FROM
day. DUAL; --ANS =>17-12-18
SELECT TRUNC(SYSDATE,'MM') FROM
DUAL; --ANS =>01-12-18
SELECT TRUNC(SYSDATE,'MON') FROM
DUAL; --ANS =>01-12-18
SELECT TRUNC(SYSDATE,'MONTH')
FROM DUAL; --ANS =>01-12-18
SELECT TRUNC(SYSDATE,'YEAR')
FROM DUAL; --ANS =>01-01-18
CURRENT_DATE CURRENT_DATE returns the current date in the SELECT SESSIONTIMEZONE,
CURRENT_DATE FROM DUAL;
CURRENT_DATE session time zone, in a value in the Gregorian --SESSIONTIMEZONE = -08:00
calendar of datatype DATE. It shows the server ,CURRENT_DATE=>2/28/2019
date 11:12:10 PM
CURRENT_TIM CURRENT_TIMESTAMP returns the current SELECT CURRENT_TIMESTAMP FROM
DUAL; --CURRENT_DATE=>2/28/2019
ESTAMP date and time in the session time zone, in a value 11:14:00.390000 PM -08:00
CURRENT_TIM of datatype TIMESTAMP WITH TIME ZONE.
ESTAMP The time zone offset reflects the current local time
( precision ) of the SQL session. If you omit precision, then
the default is 6. The difference between this
function and LOCALTIMESTAMP is that
CURRENT_TIMESTAMP returns a
TIMESTAMP WITH TIME ZONE value
while LOCALTIMESTAMP returns a
TIMESTAMP value.
In the optional argument, precision specifies the
fractional second precision of the time value
returned.
DBTIMEZONE DBTIMEZONE returns the value of the database SELECT DBTIMEZONE FROM DUAL; --
DBTIMEZONE time zone. The return type is a time zone offset (a ANS=> -08:00
character type in the format
'[+|- TZH:TZM') or a time zone region name,
depending on how the user specified the
database time zone value in the most recent
CREATE DATABASE or ALTER
DATABASE statement.
EXTRACT (datetime) SELECT EXTRACT(YEAR FROM
EXTRACT extracts and returns the value of a
EXTRACT ( specified datetime field from a datetime or interval TO_DATE(SYSDATE, 'DD-MON-RR'))
FROM DUAL; --ANS=> 2019
YEAR value expression. When you extract a
MONTH TIMEZONE_REGION or TIMEZONE_ABBR SELECT EXTRACT(YEAR FROM
DAY (abbreviation), the value returned is a string TO_DATE(HIREDATE, 'DD-MON-RR'))
HOUR containing the appropriate time zone name or FROM EMP; --ANS=>
MINUTE abbreviation. When you extract any of the other
SECOND values, the value returned is in the Gregorian SELECT EXTRACT(TIMEZONE_REGION
FROM TIMESTAMP '1999-01-01
TIMEZONE_HOUR calendar. When extracting from a datetime with a 10:00:00 -08:00') FROM DUAL;
TIMEZONE_MINUTE time zone value, the value returned is in UTC. For
TIMEZONE_REGION a listing of time zone names and their
TIMEZONE_ABBR corresponding abbreviations, query the
FROM V$TIMEZONE_NAMES dynamic performance
datetime_value_expression view.
interval_value_expression This function can be very useful for
) manipulating datetime field values in very large
tables, as shown in the first example below.
Some combinations of datetime field and datetime
or interval value expression result in ambiguity.
In these cases, Oracle Database returns
UNKNOWN (see the examples that follow for
additional information).
The field you are extracting must be a field of the
datetime_value_expr or interval_value_expr. For
example, you can extract only YEAR, MONTH,
and DAY from a DATE value. Likewise, you can
extract TIMEZONE_HOUR and
TIMEZONE_MINUTE only from the
TIMESTAMP WITH TIME ZONE datatype.
FROM_TZ FROM_TZ converts a timestamp value and a time SELECT FROM_TZ(TIMESTAMP '2000-
03-28 08:00:00','3:00') FROM
FROM_TZ ( zone to a TIMESTAMP WITH TIME ZONE DUAL;--ANS=>3/28/2000
timestamp_value , value. time_zone_value is a character string in the 8:00:00.000000000 AM +03:00
time_zone_value ) format 'TZH:TZM' or a character expression that
returns a string in TZR with optional TZD
format.
LOCALTIMESTAMP LOCALTIMESTAMP returns the current date SELECT CURRENT_TIMESTAMP,
LOCALTIMESTAMP LOCALTIMESTAMP FROM DUAL;
and time in the session time zone in a value of --CURRENT_TIMESTAMP =>2/28/2019
( timestamp_precision ) datatype TIMESTAMP. The difference between 11:22:48.515000 PM -08:00
this function and CURRENT_TIMESTAMP is -- LOCALTIMESTAMP=>2/28/2019
that LOCALTIMESTAMP returns a 11:22:48.515000 PM
TIMESTAMP value while CURRENT_
TIMESTAMP returns a TIMESTAMP WITH
TIME ZONE value. The optional argument
timestamp_precision specifies the fractional second
precision of the time value returned.
NEW_TIME NEW_TIME returns the date and time in time zone SELECT NEW_TIME(TO_DATE('11-10-
99 01:23:45', 'MM-DD-YY
NEW_TIME ( date , timezone2 when date and time in time zone HH24:MI:SS'),'AST', 'PST') "New
timezone1 , timezone2 ) timezone1 are date. Before using this function, you Date and Time" FROM DUAL;
must set the NLS_DATE_FORMAT parameter to --ANS=>11/9/2099 9:23:45
display 24-hour time. The return type is always PM23:45
DATE, regardless of the datatype of date.
The arguments timezone1 and timezone2 can be
any of these text strings:
■ AST, ADT: Atlantic Standard or Daylight
Time
■ BST, BDT: Bering Standard or Daylight Time
■ CST, CDT: Central Standard or Daylight Time
■ EST, EDT: Eastern Standard or Daylight Time
■ GMT: Greenwich Mean Time
■ HST, HDT: Alaska-Hawaii Standard Time or
Daylight Time.
■ MST, MDT: Mountain Standard or Daylight
Time
■ NST: Newfoundland Standard Time
■ PST, PDT: Pacific Standard or Daylight
Time
■ YST, YDT: Yukon Standard or Daylight Time
NUMTODSINTERVAL NUMTODSINTERVAL converts n to an SELECT manager_id, last_name,
NUMTODSINTERVAL ( INTERVAL DAY TO SECOND literal. The hire_date,COUNT(*) OVER
(PARTITION BY manager_id ORDER BY
n , ’ interval_unit ’ ) argument n can be any NUMBER value or an hire_date RANGE
expression that can be implicitly converted to a NUMTODSINTERVAL(100, 'day')
NUMBER value. The argument interval_unit PRECEDING) AS t_count FROM
can be of CHAR, VARCHAR2, NCHAR, or employees;
NVARCHAR2 datatype. The value for
interval_unit specifies the unit of n and must
resolve to one of the following string values:
■ 'DAY' ■ 'HOUR' ■ 'MINUTE' ■ 'SECOND'
Interval_unit is case insensitive. Leading and
trailing values within the parentheses are
ignored. By default, the precision of the return
is 9.
NUMTOYMINTERVAL NUMTOYMINTERVAL converts number n to SELECT last_name, hire_date,
salary, SUM(salary) OVER (ORDER
NUMTOYMINTERVAL ( an INTERVAL YEAR TO MONTH literal. The BY hire_date RANGE
n , ’ argument n can be any NUMBER value or an NUMTOYMINTERVAL(1,'year')
interval_unit ’ ) expression that can be implicitly converted to a PRECEDING) AS t_sal FROM
NUMBER value. The argument interval_unit can employees;
be of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 datatype. The value for
interval_unit specifies the unit of n and must
resolve to one of the following string values:
■ 'YEAR' ■ 'MONTH'
Interval_unit is case insensitive. Leading and
trailing values within the parentheses are
ignored. By default, the precision of the return
is 9.
SESSIONTIMEZONE SESSIONTIMEZONE returns the time zone of SELECT SESSIONTIMEZONE FROM
DUAL;--ANS=>-08:00
SESSIONTIMEZONE the current session. The return type is a time zone
offset (a character type in the format
'[+|]TZH:TZM') or a time zone region name,
depending on how the user specified the session
time zone value in the most recent ALTER
SESSION statement.
SYSDATE SYSDATE SYSDATE returns the current date and time SELECT TO_CHAR (SYSDATE, 'MM-DD-
set for the operating system on which the YYYY HH24:MI:SS')"NOW" FROM
DUAL; NOW
database resides. The datatype of the returned
-------------------
value is DATE, and the format returned depends on 04-13-2001 09:45:51
the value of the NLS_DATE_FORMAT
initialization parameter. The function requires no
arguments. In distributed SQL statements, this
function returns the date and time set for the
operating system of your local database. You
cannot use this function in the condition of a
CHECK constraint.
SYSTIMESTAMP SYSTIMESTAMP returns the system date, SELECT SYSTIMESTAMP FROM
DUAL;SYSTIMESTAMP
SYSTIMESTAMP including fractional seconds and time zone, of the
---------------------------
system on which the database resides. The return 28-MAR-00 12.38.55.538741 PM -
type is TIMESTAMP WITH TIME ZONE. 08:00
TZ_OFFSET TZ_OFFSET ( TZ_OFFSET returns the time zone offset US/Eastern time zone from UTC:
’ time_zone_name ’ corresponding to the argument based on the date SELECT
’+– TZ_OFFSET('US/Easte
the statement is executed. You can enter a valid rn') FROM DUAL;
hh : mi ’ time zone name, a time zone offset from UTC
SESSIONTIMEZONE (which simply returns itself), or the keyword TZ_OFFS
-------
DBTMEZONE ) SESSIONTIMEZONE or DBTIMEZONE. For a
listing of valid values for time_zone_name, query
the TZNAME column of the
V$TIMEZONE_NAMES dynamic performance
view.

CONVERSION FUNCTIONS
Conversion functions convert a value from one datatype to another. Generally, the form of the
function names follows the convention datatype TO datatype. The first datatype is the input
datatype. The second datatype is the output datatype. The SQL conversion functions are

Element Description
SCC or CC Century; server prefixes B.C. date with -
Years in dates YYYY or SYYYY Year; server prefixes B.C. date with -
YYY or YY or Y Last three, two, or one digits of year
Y,YYY Year with comma in this position
IYYY, IYY, IY, I Four-, three-, two-, or one-digit year based on the ISO
standard
SYEAR or YEAR Year spelled out; server prefixes B.C. date with -
BC or AD Indicates B.C. or A.D. year
B.C. or A.D. Indicates B.C. or A.D. year using periods
Q Quarter of year
MM Month: two-digit value
MONTH Name of month padded with blanks to length of nine
characters
MON Name of month, three-letter abbreviation
RM Roman numeral month
WW or W Week of year or month
DDD or DD or D Day of year, month, or week
DAY Name of day padded with blanks to a length of nine
characters
DY Name of day; three-letter abbreviation
J Julian day; the number of days since December 31,
4713
B.C.
AM or PM Meridian indicator
A.M. or P.M. Meridian indicator with periods
HH or HH12 or HH24 Hour of day, or hour (1–12), or hour (0–23)
MI Minute (0–59)
SS Second (0–59)
SSSSS Seconds past midnight (0–86399)
/ . , Punctuation is reproduced in the result.
“of the” Quoted string is reproduced in the result.
TH Ordinal number (for example, DDTH for 4TH)
SP Spelled-out number (for example, DDSP for FOUR)
SPTH or THSP Spelled-out ordinal numbers (for example, DDSPTH for
FOURTH)
Time elements format the time portion of the date:
HH24:MI:SS AM 15:45:32 PM
Add character strings by enclosing them in double quotation marks:
DD "of" MONTH 12 of OCTOBER
Number suffixes spell out numbers:
ddspth fourteenth
Element Description Example Result
9 Numeric position (number of 9s 999999 1234
determine display width)
0 Display leading zeros 099999 001234
$ Floating dollar sign $999999 $1234
L Floating local currency symbol L999999 FF1234
D Returns in the specified position the 99D99 99.99
decimal character. The default is a
period (.).
. Decimal point in position specified 999999.99 1234.00
G Returns the group separator in the 9,999 9G999
specified position. You can specify
multiple group separators in a
number format model.
, Comma in position specified 999,999 1,234
MI Minus signs to right (negative 999999MI 1234-
values)
PR Parenthesize negative numbers 999999PR <1234>
EEEE Scientific notation (format must 99.999EEEE 1.234E+03
specify four Es)
U Returns in the specified position the U9999 €1234
"Euro" (or other) dual currency
V Multiply by 10 n times (n = number 9999V99 123400
of 9s after V)
S Returns the negative or positive S9999 -1234 or
value +1234
B Display zero values as blank, not 0 B9999.99 1234.00

If the specified two-digit year is:

0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one
Current Year Specified Date RR Format YY Format
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095

Function Name Purpose Example


ASCIISTR ASCIISTR ( char ) ASCIISTR takes as its argument a string, or an SELECT ASCIISTR('ABÄCDE') FROM
DUAL;
expression that resolves to a string, in any
character set and returns an ASCII version of
the string in the database character set. Non-
ASCII characters are converted to the form
\xxxx, where xxxx represents a UTF-16 code
unit.
TO_CHAR (character) TO_CHAR (character) converts NCHAR, SELECT TO_CHAR(SYSDATE,'YEAR')
FROM DUAL;
TO_CHAR(number|date,[ NVARCHAR2, CLOB,
fmt],[nlsparams]) or NCLOB data to the database character set.
The value returned is always VARCHAR2.
Date conversion: The When you use this function to convert a
nlsparams parameter specifies character LOB into the database character set,
the language in which month and if the LOB value to be converted is larger than
day names and abbreviations are the target type, then the database returns an
returned. If this parameter is error.
omitted, this function uses the You can use this function in conjunction
default date languages for the with any of the XML functions to generate
session. a date in the database format rather than the
XML Schema standard format.
TO_CHAR (datetime) TO_CHAR (datetime) converts a datetime or SELECT
TO_CHAR(SYSDATE,'DD/MM/YY') FROM
TO_CHAR(number|date,[ interval value of DATE, TIMESTAMP, DUAL;
fmt],[nlsparams]) TIMESTAMP WITH TIME ZONE, or
TIMESTAMP WITH LOCAL TIME ZONE
datatype to a value of VARCHAR2 datatype in
the format specified by the date format fmt. If
you omit fmt, then date is converted to a
VARCHAR2 value as follows:
■ DATE values are converted to values in
the default date format.
■ TIMESTAMP and TIMESTAMP WITH
LOCAL TIME ZONE values are converted
to values in the default timestamp format.
■ TIMESTAMP WITH TIME ZONE values
are converted to values in the default
timestamp with time zone format. Please refer
to "Format Models" on page 2-54 for
information on datetime formats. The
'nlsparam' argument specifies the language
in which month and day names and
abbreviations are returned. This argument
can have this
form:'NLS_DATE_LANGUAGE = language'
If you omit 'nlsparam', then this function uses
the default date language for your session
TO_CHAR (number) TO_CHAR (number) converts n to a value SELECT
TO_CHAR('01110' + 1)
TO_CHAR(number|date,[ of VARCHAR2 datatype, using the optional FROM dual;
fmt],[nlsparams]) number format fmt. The value n can be of TO_C
type NUMBER, BINARY_FLOAT, or ----
BINARY_DOUBLE. If you omit fmt, then n 1111
is converted to a VARCHAR2 value exactly currency symbol.
SELECT TO_CHAR(-
long enough to hold its significant digits. 10000,'L99G999D99MI') "Amount"
The 'nlsparam' argument specifies these FROM DUAL;
characters that are returned by number format Amount
elements: ■ Decimal character --------------
■ Group separator ■ Local currency symbol ■ $10,000.00-
SELECT TO_CHAR(-
International currency symbol This argument 10000,'L99G999D99MI','NLS_NUMER
can have this form: IC_CHARACTERS = '',.''
'NLS_NUMERIC_CHARACTERS = NLS_CURRENCY = ''AusDollars''
''dg'' NLS_CURRENCY = ''text'' ') "Amount" FROM DUAL;
NLS_ISO_CURRENCY = territory ' Amount
-------------------
The characters d and g represent the decimal AusDollars10.000,00-
character and group separator, respectively.
They must be different single- byte characters.
Within the quoted string, you must use two
single quotation marks around the parameter
values. Ten characters are available for the
currency symbol. If you omit 'nlsparam' or any
one of the parameters, then this function uses
the default parameter values for your session
TO_DATE TO_DATE converts char of CHAR, SELECT TO_DATE('January 15,
TO_DATE(char,[fmt],[nlspara VARCHAR2, NCHAR, or NVARCHAR2 1989, 11:00 A.M.','Month dd,
ms]) YYYY, HH:MI
datatype to a value of DATE datatype. The fmt A.M.','NLS_DATE_LANGUAGE =
is a datetime model format specifying the American') FROM DUAL; TO_DATE('
Converts a character format of char. If you omit fmt, then char must ---------
string representing a date be in the default date format. If fmt is J, for 15-JAN-89
to a date value according Julian, then char must be an integer. The value returned reflects the default
to the fmtthat is specified. The default date format is determined date format if the
implicitly by the LS_TERRITORY NLS_TERRITORY parameter is set
If fmtis omitted, the
initialization parameter or can be set to 'AMERICA'. Different
format is DD-MON-YY. NLS_TERRITORY values result in
The nlsparamsparameter has the explicitly by the LS_DATE_FORMAT
different default date formats:
same purpose in this function as parameter. The 'nlsparam' argument has
in the TO_CHARfunction for the same purpose in this function as in the
date conversion TO_CHAR function for date conversion. Do
not use the TO_DATE function with a
DATE value for the char argument. The
first two digits of the returned DATE value
can differ from the original char, depending
on fmt or the default date format.
This function does not support CLOB
data directly.
However, CLOBs can be passed in as
arguments through implicit data conversion.
TO_NUMBER TO_NUMBER converts expr to a value of UPDATE employees SET salary =
TO_NUMBER(char,[fmt], NUMBER datatype. salary +
TO_NUMBER('100.00',
[nlsparams]) The expr can be a BINARY_FLOAT or '9G999D99')
BINARY_DOUBLE value or a value of WHERE last_name = 'Perkins';
Converts a character string CHAR, VARCHAR2, NCHAR, or SELECT TO_NUMBER ('-
NVARCHAR2 datatype containing a number AusDollars100','L9G999D99','NLS
containing digits to a number _NUMERIC_CHARACTERS = '',.''
in the format specified by the in the format specified by the optional format NLS_CURRENCY =
model fmt. This function does not support ''AusDollars'' ') "Amount" FROM
optional format model fmt.
CLOB data directly. However, CLOBs can be DUAL;
The nlsparamsparameter has the
passed in as arguments through implicit data Amount
same purpose in this function as ----------
conversion.
in the TO_CHARfunction for -100
number conversion.
CAST CAST converts one built-in datatype or
CARDINALITY ( nested_table collection-typed value into another built-in
)
CAST (Expr MULTISET ( datatype or collection-typed value.
subquery ) AS CAST lets you convert built-in datatypes or
type_name ) collection-typed values of one type into another
built-in datatype or collection type. You can
cast an unnamed operand (such as a date or the
result set of a subquery) or a named collection
(such as a varray or a nested table) into a type-
compatible datatype or named collection. The
type_name must be the name of a built-in
datatype or collection type and the operand
must be a built-in datatype or must evaluate to
a collection value.

CHARTOROWID CHARTOROWID converts a value from SELECT last_name FROM employees


WHERE ROWID =
CHARTOROWID ( char ) CHAR, VARCHAR2, NCHAR, or CHARTOROWID('AAAFd1AAFAAAABSA
NVARCHAR2 datatype to ROWID datatype. A/');
This function does not support CLOB data LAST_NAME
directly. However, CLOBs can be passed in as -------------------------
Greene
arguments through implicit data conversion.
COMPOSE COMPOSE ( char ) COMPOSE takes as its argument a string, or SELECT COMPOSE ( 'o' ||
an expression that resolves to a string, in UNISTR('\0308') ) FROM DUAL;CO
--
any datatype, and returns a Unicode string in ö
its fully normalized form in the same
character set as the input. char can be any of
the datatypes CHAR, VARCHAR2,
NCHAR,NVARCHAR2, CLOB, or NCLOB.
For example, an o code point qualified by an
umlaut code point will be returned as the o-
umlaut code point. CLOB and NCLOB values
are supported through implicit conversion. If
char is a character LOB value, it is converted to
a VARCHAR value before the COMPOSE
operation. The operation will fail if the size of
the LOB value exceeds the supported length of
the VARCHAR in the particular development
environment.
CONVERT CONVERT converts a character string from SELECT CONVERT('Ä Ê Í Õ Ø A B C
CONVERT ( char , one character set to another. The datatype of D E ','US7ASCII',
dest_char_set 'WE8ISO8859P1') FROM DUAL;
the returned value is VARCHAR2. CONVERT('ÄÊÍÕØABCDE'
, source_char_set ) ■ The char argument is the value to be ---------------------
converted. It can be any of the datatypes A E I ? ? A B C D E ?
CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB.
■ The dest_char_set argument is the
name of the character set to which char is
converted.
■ The source_char_set argument is the name
of the character set in which char is stored in
the database. The default value is the
database character set. Both the
destination and source character set
arguments can be either literals or columns
containing the name of the character set. For
complete correspondence in character
conversion, it is essential that the destination
character set contains a representation of all
the characters defined in the source character
set. Where a character does not exist in the
destination character set, a replacement
character appears. Replacement characters
can be defined as part of a character set
definition.
Common character sets include:
■ US7ASCII: US 7-bit ASCII character set
■ WE8DEC: West European 8-bit character
set
■ F7DEC: DEC French 7-bit character set
■ WE8EBCDIC500: IBM West European
EBCDIC Code Page 500
■ WE8ISO8859P1: ISO 8859-1 West
European 8-bit character set
■ UTF8: Unicode 4.0 UTF-8 Universal
character set, CESU-8 compliat
■ AL32UTF8: Unicode 4.0 UTF-8 Universal
character set
DECOMPOSE DECOMPOSE is valid only for SELECT DECOMPOSE ('Châteaux')
DECOMPOSE ( string Unicode characters. FROM DUAL;
CANONICAL DECOMPOSE
DECOMPOSE takes as its argument a string --------- Cha^teaux
COMPATIBILITY ) in any datatype and returns a Unicode string
after decomposition in the same character set
as the input. For example, an o-umlaut code
point will be returned as the "o" code point
followed by an umlaut code point.
■ String can be any of the datatypes
CHAR, VARCHAR2,NCHAR,
NVARCHAR2, CLOB,or NCLOB.
■ CANONICAL causes canonical
decomposition, which allows
recomposition (for example, with the
COMPOSE
function) to the original string. This
is the default.
■ COMPATIBILITY causes decomposition in
compatibility mode. In this mode,
recomposition is not possible. This mode is
useful, for example, when decomposing half-
width and full-width katakana characters,
where recomposition might not be desirable
without external formatting or style
information.
CLOB and NCLOB values are supported
through implicit conversion. If char is a
character LOB value, it is converted to a
VARCHAR value before the COMPOSE
operation. The operation will fail if the size of
the LOB value exceeds the supported length of
the VARCHAR in the particular development
environment
HEXTORAW HEXTORAW ( HEXTORAW converts char containing CREATE TABLE test (raw_col
RAW(10));
char ) hexadecimal digits in the CHAR, INSERT INTO test VALUES
VARCHAR2,NCHAR, or NVARCHAR2 (HEXTORAW('7D'));
character set to a raw value.
This function does not support CLOB data
directly. However, CLOBs can be passed in as
arguments through implicit data conversion.
RAWTOHEX RAWTOHEX ( RAWTOHEX converts raw to a character SELECT RAWTOHEX(raw_column)
"Graphics" FROM graphics;
raw ) value containing its exadecimal equivalent.
Graphics
The raw argument must be RAW datatype. --------
You can specify a BLOB argument for this 7D
function if it is called from within a PL/SQL
block.
RAWTONHEX RAWTONHEX RAWTONHEX converts raw to an SELECT
( raw ) NVARCHAR2 character value containing its RAWTONHEX(raw_column),DUMP (
RAWTONHEX (raw_column) ) "DUMP"
hexadecimal equivalent. The value returned
FROM graphics;
is always in the national character set. RAWTONHEX(RA) DUMP
----------------------- ---
7D Typ=1 Len=4: 0,55,0,68
ROWIDTOCHAR ROWIDTOCHAR converts a rowid value SELECT ROWID FROM employees
WHERE ROWIDTOCHAR(ROWID) LIKE
ROWIDTOCHAR ( rowid ) to VARCHAR2 datatype. The result of this '%JAAB%';
conversion is always 18 characters long. ROWID
------------------
AAAFfIAAFAAAABSAAb
ROWIDTONCHAR ROWIDTONCHAR converts a rowid value SELECT LENGTHB(
ROWIDTONCHAR(ROWID) ),
ROWIDTONCHAR ( rowid ) to NVARCHAR2 datatype. The result of ROWIDTONCHAR(ROWID) FROM
this conversion is always in the national employees;
character set and is 18 characters long. LENGTHB(ROWIDTONCHAR(ROWID))
ROWIDTONCHAR(ROWID
---------------------------
36 AAAFfIAAFAAAABSAAA
SCN_TO_TIMESTAMP SCN_TO_TIMESTAMP takes as an argument SELECT
SCN_TO_TIMESTAMP(ORA_ROWSCN)
SCN_TO_TIMESTAMP ( a number that evaluates to a system change FROM employees WHERE
number ) number (SCN), and returns the approximate employee_id = 188;
timestamp associated with that SCN. The You could use such a query to convert a
returned value is of TIMESTAMP datatype. system change number to a timestamp
This function is useful any time you want to for use in an Oracle Flashback Query:
know the timestamp associated with an SCN. SELECT salary FROM employees
For example, it can be used in conjunction WHERE employee_id
= 188;
with the ORA_ROWSCN pseudo column to
associate a timestamp with the most recent
change to a row.
TIMESTAMP_TO_SCN TIMESTAMP_TO_SCN takes as an argument TIMESTAMP_TO_SCN to determine the
TIMESTAMP_TO_SCN ( a timestamp value and returns the approximate system change number of the insert
timestamp ) system change number (SCN) associated with operation.
that timestamp. The returned value is of (The actual SCN returned will differ on
datatype NUMBER. This function is useful any each system.)
time you want to know the SCN associated INSERT INTO orders (order_id,
order_date, customer_id,
with a particular timestamp. order_total)
VALUES (5000, SYSTIMESTAMP, 188,
2345);
1 row created.
COMMIT;
Commit complete.
SELECT
TIMESTAMP_TO_SCN(order_date)
FROM orders WHERE order_id =
5000;TIMESTAMP_TO_SCN(ORDER_DAT
E)
---------------------------
574100
TO_BINARY_DOUBL TO_BINARY_DOUBLE returns a double- CREATE TABLE float_point_demo
E (dec_num NUMBER(10,2),
precision floating- bin_double BINARY_DOUBLE,
TO_BINARY_DOUBL point number. bin_float BINARY_FLOAT);
E ( expr , fmt , ’ ■ expr can be a character string or a numeric INSERT INTO float_point_demo
nlsparam ’) value of type NUMBER, BINARY_FLOAT, VALUES
(1234.56,1234.56,1234.56);
or BINARY_DOUBLE. If expr is
SELECT * FROM
BINARY_DOUBLE, then the function float_point_demo;DEC_NUM
returns expr. BIN_DOUBLE BIN_FLOAT
■ The optional 'fmt' and 'nlsparam' ---------- ---------- -----
arguments are valid 1234.56 1.235E+003 1.235E+003
only if expr is a character string. They serve The following example converts a value
the same purpose as for the TO_CHAR of datatype NUMBER
to a value of datatype BINARY_DOUBLE:
(number) function. SELECT dec_num,
TO_BINARY_DOUBLE(dec_num) FROM
– The case-insensitive string 'INF' is float_point_demo;DEC_NUM
converted to positive infinity. TO_BINARY_DOUBLE(DEC_NUM)
– The case-insensitive string '-INF' is ---------- ----------------The
converted to negative identity. following
– The case-insensitive string 'NaN' is example compares extracted dump
converted to NaN (not a number). information from the
You cannot use a floating-point number dec_num and
format element (F, bin_double columns:
f, D, or d) in a SELECT DUMP(dec_num)
character string expr. "Decimal",DUMP(bin_double)
Conversions from character strings or "Double" FROM float_point_demo;
NUMBER to BINARY_DOUBLE can be Decimal Double
---------------------------
inexact, because the NUMBER and character Typ=2 Len=4: 194,13,35,57
types use decimal precision to represent the Typ=101 Len=8:
numeric value, and BINARY_DOUBLE uses 192,147,74,61,112,163,215,10
binary precision. Conversions from
BINARY_FLOAT to BINARY_DOUBLE are
exact.
TO_BINARY_FLOAT TO_BINARY_FLOAT returns a single- SELECT dec_num,
TO_BINARY_FLOAT ( precision floating- point number. TO_BINARY_FLOAT(dec_num) FROM
expr , fmt , ’ nlsparam ’) ■ Expr can be a character string or a numeric float_point_demo;
DEC_NUM
value of type NUMBER, BINARY_FLOAT, TO_BINARY_FLOAT(DEC_NUM)
or BINARY_DOUBLE. If expr is ---------- ----------------
BINARY_FLOAT, then the function returns 1234.56 1.235E+003
expr.
■ The optional 'fmt' and 'nlsparam'
arguments are valid
only if expr is a character string. They serve
the same purpose as for the TO_CHAR
(number) function.
– The incase-sensitive string 'INF' is
converted to positive infinity.
– The incase-sensitive string '-INF' is
converted to negative identity.
– The incase-sensitive string 'NaN' is
converted to NaN (not a number).
You cannot use a floating-point number
format element (F,
f, D, or d) in a
character string expr.
Conversions from character strings or
NUMBER to
BINARY_FLOAT can be inexact, because the
NUMBER and
character types use decimal precision to
represent the
numeric value and BINARY_FLOAT uses
binary precision. Conversions from
BINARY_DOUBLE to BINARY_FLOAT are
inexact if the BINARY_DOUBLE value
uses more bits of precision than supported by
the BINARY_FLOAT.
TO_CLOB TO_CLOB converts NCLOB values in a LOB UPDATE PRINT_MEDIA SET
AD_FINALTEXT = TO_CLOB
TO_CLOB ( lob_column char ) column or other (AD_FLTEXTN);
character strings to CLOB values. char can
be any of the datatypes CHAR,
VARCHAR2, NCHAR,
NVARCHAR2,CLOB, or NCLOB. Oracle
Database executes this function by converting
the underlying
LOB data from the national character set
to the database
character set.
TO_DSINTERVAL TO_DSINTERVAL converts a character SELECT employee_id, last_name
FROM employees WHERE hire_date +
TO_DSINTERVAL ( char , ’ string of CHAR, VARCHAR2, NCHAR, or TO_DSINTERVAL('100 10:00:00')
nlsparam ’ ) NVARCHAR2 datatype to an INTERVAL <= DATE '1990-01-01';
DAY TO SECOND value. EMPLOYEE_ID LAST_NAME
■ char is the character string to ----------- ---------------
be converted. 100 King
101 Kochhar
■ The only valid nlsparam you can specify in 200 Whalen
this function is
NLS_NUMERIC_CHARACTERS. This
argument can have the form:
NLS_NUMERIC_CHARACTERS = "dg"
where d and g represent the decimal
character and group separator respectively.
Neither character can be a space.
TO_LOB TO_LOB converts LONG or LONG CREATE TABLE new_table (col1,
col2, ...lob_col CLOB);
TO_LOB ( long_column ) RAW values in the column long_column to INSERT INTO new_table (select
LOB values. You can apply this function o.col1, o.col2,...
only to a LONG or LONG RAW column, and TO_LOB(o.old_long_col)FROM
only in the select list of a subquery in an old_table o;
INSERT statement. Before using this
function, you must create a LOB column to
receive the converted LONG values. To
convert LONG values, create a CLOB
column. To convert LONG RAW values,
create a BLOB column. You cannot use the
TO_LOB function to convert a LONG
column to a LOB column in the subquery of a
CREATE TABLE ... AS SELECT
statement if you are creating an index-
organized table. Instead, create the index-
organized table without the LONG column,
and then use the TO_LOB function in an
INSERT ... AS SELECT statement.
TO_MULTI_BYTE TO_MULTI_BYTE returns char with all of SELECT dump(TO_MULTI_BYTE( 'A'))
FROM DUAL;
TO_MULTI_BYTE ( char ) its single-byte characters converted to their MULTI_BYTE('A'))
corresponding multibyte characters. char can Typ=1 Len=3: 239,188,161
be of datatype CHAR, VARCHAR2,NCHAR,
or NVARCHAR2. The value returned is in the
same datatype as char.
Any single-byte characters in char that have
no multibyte equivalents appear in the
output string as single-byte characters. This
function is useful only if your database
character set contains both single-byte
and multibyte characters. This function
does not support CLOB data directly.
However, CLOBs can be passed in as
arguments through implicit data conversion
TO_NCHAR (character) TO_NCHAR (character) converts a character The following example converts
TO_NCHAR ( Char clob nclob ) string, CHAR, VARCHAR2, CLOB, or VARCHAR2 data from the
NCLOB value to the national character set. The oe.customers table to the national
value returned is always NVARCHAR2. This character set:
function is equivalent to the TRANSLATE ... SELECT TO_NCHAR(cust_last_name)
USING function with a USING clause in the FROM customers WHERE
customer_id=103;TO_NCHAR(CUST_
national character set.
LAST_NAME)
---------------------------
Taylor
TO_NCHAR (datetime) TO_NCHAR (datetime) converts a datetime or SELECT TO_NCHAR(order_date)
TO_NCHAR ( Datetime interval interval value of DATE, TIMESTAMP, FROM orders WHERE order_status >
, fmt , ’ 9; TO_NCHAR(ORDER_DATE)
TIMESTAMP WITH TIME ZONE,
----------------------------
nlsparam ’ ) TIMESTAMP WITH LOCAL TIME ZONE, 14-SEP-99 08.53.40.223345 AM
INTERVAL MONTH TO YEAR, or 13-SEP-99 09.19.00.654279 AM
INTERVAL DAY TO SECOND datatype
from the database character set to the national
character set.
TO_NCHAR (number) TO_NCHAR (number) converts n to a string SELECT TO_NCHAR(customer_id)
TO_NCHAR ( n , fmt , ’ in the national character set. The value n can "NCHAR_Customer_ID" FROM orders
nlsparam ’ ) WHERE order_status > 9;
be of type NUMBER, BINARY_FLOAT, or
NCHAR_Customer_ID
BINARY_DOUBLE. The function returns a -----------------
value of the same type as the argument. The 102
optional fmt and 'nlsparam' corresponding to 103
n can be of DATE, TIMESTAMP, 148
TIMESTAMP WITH TIME ZONE, 149
148
TIMESTAMP WITH LOCAL TIME ZONE,
INTERVAL MONTH TO YEAR, or
INTERVAL DAY TO SECOND datatype.
TO_NCLOB TO_NCLOB converts CLOB values in a LOB INSERT INTO print_media
(product_id,
TO_NCLOB ( lob_column char column or other character strings to NCLOB ad_id,ad_fltextn)VALUES (3502,
) values. char can be any of the datatypes 31001,
CHAR, VARCHAR2, NCHAR, TO_NCLOB('Placeholder for new
NVARCHAR2, CLOB, or NCLOB. Oracle productdescription'));
Database implements this function by
converting the character set of char from the
database character set to the national character
set.
TO_SINGLE_BYTE TO_SINGLE_BYTE returns char with all of SELECT TO_SINGLE_BYTE(
TO_SINGLE_BYTE ( char ) its multibyte characters converted to their CHR(15711393)) FROM DUAL; T
-
corresponding single-byte characters. char can A
be of datatype CHAR, VARCHAR2,NCHAR,
or NVARCHAR2. The value returned is in the
same datatype as char.Any multibyte
characters in char that have no single-byte
equivalents appear in the output as multibyte
characters. This function is useful only if your
database character set contains both single-byte
and multibyte characters. This function does
not support CLOB data directly. However,
CLOBs can be passed in as arguments through
implicit data conversion.
TO_TIMESTAMP TO_TIMESTAMP converts char of SELECT TO_TIMESTAMP ('10-Sep-02
14:10:10.123000', 'DD-Mon-RR
TO_TIMESTAMP ( char CHAR, VARCHAR2, NCHAR, or HH24:MI:SS.FF')
, fmt , ’ nlsparam ’) NVARCHAR2 datatype to a value of FROM DUAL;
TIMESTAMP datatype. TO_TIMESTAMP('10-SEP-
The optional fmt specifies the format of char. 0214:10:10.123000','DD-
MON-RRHH24:MI:SS.FF')
If you omit fmt, then char must be in the ---------------------------
default format of the TIMESTAMP 10-SEP-02 02.10.10.123000000 PM
datatype, which is determined by the
NLS_TIMESTAMP_FORMAT initialization
parameter. The optional 'nlsparam' argument
has the same purpose in this function as in the
TO_CHAR function for date conversion.
This function does not support CLOB data
directly. However, CLOBs can be passed in as
arguments through implicit data conversion.
TO_TIMESTAMP_TZ TO_TIMESTAMP_TZ converts char of SELECT TO_TIMESTAMP_TZ('1999-
12-01 11:00:00 -8:00','YYYY-
TO_TIMESTAMP_TZ CHAR, VARCHAR2, NCHAR, or MM-DD HH:MI:SS TZH:TZM') FROM
( char , fmt , ’ NVARCHAR2 datatype to a value of DUAL;
nlsparam ’) TIMESTAMP WITH TIME ZONE datatype. TO_TIMESTAMP_TZ('1999-12-
0111:00:00-
The optional fmt specifies the format of char. 08:00','YYYY-MM-
If you omit fmt, then char must be in the DDHH:MI:SSTZH:TZM')
default format of the TIMESTAMP WITH ---------------------------
TIME ZONE datatype. The optional 'nlsparam' 01-DEC-99 11.00.00.000000000 AM
-08:00
has the same purpose in this function as in SELECT order_id,
the TO_CHAR function for date conversion. line_item_id,CAST(NULL AS
TIMESTAMP WITH LOCAL TIME ZONE)
order_date FROM order_items
UNION
SELECT order_id,
to_number(null), order_date
FROM orders;ORDER_ID
LINE_ITEM_ID ORDER_DATE
---------- ------------ ---
2354 1
TO_YMINTERVAL TO_YMINTERVAL converts a character SELECT hire_date, hire_date +
TO_YMINTERVAL ( TO_YMINTERVAL('01-02') "14
string of CHAR, VARCHAR2, NCHAR, or months" FROM employees;
char ) NVARCHAR2 datatype to an INTERVAL HIRE_DATE 14 months
YEAR TO MONTH type, where char is the --------- ---------
character string to be converted. 17-JUN-87 17-AUG-88
21-SEP-89 21-NOV-90
13-JAN-93 13-MAR-94

TRANSLATE ... USING.. TRANSLATE ... USING converts char into the CREATE TABLE translate_tab
(char_col VARCHAR2(100),
USINGTRANSLATE ( char character set specified for conversions between nchar_col NVARCHAR2(50));
USING CHAR_CS the database character set and the national INSERT INTO translate_tab SELECT
NCHAR_CS ) character set. NULL, translated_name FROM
product_descriptions WHERE
product_id = 3501;

NULL-RELATED FUNCTIONS
The NULL-related functions facilitate null handling. The NULL-related functions are:

Function Name Purpose Example


COALESCE COALESCE returns the first non-null expr in SELECT product_id, list_price,
COALESCE (expr1, min_price,
the expression list. At least one expr must not
COALESCE(0.9*list_price,
expr2, ..., exprn) be the literal NULL. If all occurrences of expr min_price, 5) "Sale" FROM
In the syntax: evaluate to null, then the function returns product_information WHERE
null.Oracle Database uses short-circuit supplier_id = 102050;
• expr1returns this expression PRODUCT_ID LIST_PRICE
if it is not null evaluation. That is, the database evaluates MIN_PRICE Sale
• expr2returns this each expr value and determines whether it is ---------- ---------- --------
expression if the first NULL, rather than evaluating all of the expr 2382 850 731 765
values before determining whether any of them 3355 5
expression is null and this 1770 73 73
is NULL. 2378 305 247 274.5
expression is not null
If all occurrences of expr are numeric datatype 1769 48 43.2
• exprnreturns this expression
or any nonnumeric datatype that can be
if the preceding expressions are
implicitly converted to a numeric datatype,
null
then Oracle Database determines the argument
with the highest numeric precedence,
implicitly converts the remaining arguments to
that datatype, and returns that datatype.
NULLIF NULLIF compares expr1 and expr2. If they are SELECT e.last_name,
NULLIF (expr1, expr2) NULLIF(e.job_id,j.job_id) "Old
equal, then the function returns null. If they are Job ID"FROM employees e,
not equal, then the function returns expr1. job_history j WHERE e.employee_id
C om pa re s tw o e x p re ss io You cannot specify the literal NULL for = j.employee_id ORDER BY
ns a nd re turn s nu ll if the y expr1. last_name; SELECT * FROM
translate_tab;
a re e qua l; re tu rns th e firs t e If both arguments are numeric datatypes, then LAST_NAME Old Job ID
xpress io n if th e y a re no t e qu Oracle Database determines the argument with -------------------
De Haan AD_VP
al the higher numeric precedence, implicitly Hartstein MK_MAN
converts the other argument to that datatype, Kaufling ST_MAN
and returns that datatype. If the arguments are Kochhar AD_VP
not numeric, then they must be of the same Kochhar AD_VP
Raphaely PU_MAN
datatype, or Oracle returns an error. Taylor SA_REP Taylor
The NULLIF function is logically equivalent to Whalen AD_ASST
the following CASE expression:
CASE WHEN expr1 = expr 2 THEN NULL
ELSE expr1 END
NVL NVL lets you replace null (returned as a SELECT last_name,
NVL (expr1, expr2) NVL(TO_CHAR(commission_pct),'No
blank) with a string in the results of a query. t Applicable') "COMMISSION" FROM
If expr1 is null, then NVL returns expr2.If employees WHERE last_name LIKE
C o n verts a n u ll valu e to an expr1 is not null, then NVL returns expr1.The 'B%' ORDER BY last_name;
ac tu al valu e arguments expr1 and expr2 can have any
datatype. If their datatypes are different, then NVL(commission_pct,0)
Oracle Database implicitly converts one to the NVL(hire_date,'01-JAN-97')
other. If they are cannot be converted
implicitly, the database returns an error. The NVL(job_id,'No Job Yet')
implicit conversion is implemented as follows:
■ If expr1 is character data, then Oracle
Database converts expr2 to the datatype of
expr1 before comparing them and returns
VARCHAR2 in the character set of expr1.
■ If expr1 is numeric, then Oracle
determines which argument has the highest
numeric precedence, implicitly converts the
other argument to that datatype, and returns
that datatype.
NVL2 NVL2 lets you determine the value returned SELECT last_name,
salary,NVL2(commission_pct,
NVL2 (expr1, expr2, expr3) by a query based on whether a specified
salary + (salary *
expression is null or not null. If expr1 is not commission_pct), salary) income
null, then NVL2 returns expr2. If expr1 is null, FROM employees WHERE last_name
If expr1 is n o t n u ll, NVL2 then NVL2 returns expr3. like 'B%' ORDER BY last_name;
retu rn s expr2. If expr1 is n The argument expr1 can have any datatype.
u ll, NVL2 retu rn s expr3. T The arguments expr2 and expr3 can have any
h e a rgu me n t expr1 c an h a ve datatypes except LONG.
any d ata typ e . If the datatypes of expr2 and expr3 are
different.
DECODE DECODE compares expr to each search value SELECT product_id, DECODE
(warehouse_id, 1, 'Southlake',
DECODE ( expr , search , one by one. If expr is equal to a search, then 2, 'San
result ,, default ) Oracle Database returns the corresponding Francisco',
result. If no match is found, then Oracle returns 3, 'New Jersey',
DECODE(col|expression, default. If default is omitted, then Oracle 4, 'Seattle',
search1, result1 [, 'Non domestic')
returns null. "Location of inventory" FROM
search2, result2,...,]
The arguments can be any of the inventories
[, default]) WHERE product_id < 1775;
numeric types
(NUMBER,BINARY_FLOAT, or
BINARY_DOUBLE) or character types. SELECT last_name, job_id, salary,
It is used to replace more than one string.It DECODE(job_id,
work like a if condition but it does not allow 'IT_PROG', 1.10*salary,
relational oprations. 'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary)REVISED_ SALARY
FROM employees;
CASE SELECT last_name, job_id, salary, SELECT last_name,salary,
CASE job_id WHEN 'IT_PROG' THEN (CASE
CASE expr WHEN salary<5000 THEN 'Low'
WHEN comparison_expr1 1.10*salary WHEN 'ST_CLERK' THEN
WHEN salary<10000 THEN 'Medium'
1.15*salary WHEN 'SA_REP' THEN
THEN return_expr1 1.20*salary ELSE salary WHEN salary<20000 THEN 'Good'
[WHEN comparison_expr2 END "REVISED_SALARY" ELSE 'Excellent'END)
THEN return_expr2 FROM employees; qualified_salary
WHEN comparison_exprn FROM employees;
THEN return_exprn
ELSE else_expr]
END
VSIZE VSIZE returns the number of bytes in the The following example returns the
VSIZE ( expr ) internal representation of number of bytes in the last_name
expr. If expr is null, then this function returns column of the employees in department
null. This function does not support CLOB data 10:
directly. However, CLOBs can be passed in as SELECT last_name, VSIZE
(last_name) "BYTES" FROM
arguments through implicit data conversion.
employees WHERE department_id =
10;
LAST_NAME BYTES
--------------- ----------
Whalen 6
UID UID UID returns an integer that uniquely identifies SELECT UID FROM DUAL;
the session user (the user who logged on).
USER USER USER returns the name of the session user SELECT USER, UID FROM DUAL;
(the user who logged on) with the datatype
VARCHAR2. Oracle Database compares
values of this function with blank-padded
comparison semantics.
USERENV USERENV ( ’ USERENV returns information about the SELECT USERENV('LANGUAGE')
parameter ’ ) "Language" FROM DUAL; Language
current session. This information can be useful -------------------------------
for writing an application-specific audit trail ----
table or for determining the language-specific AMERICAN_AMERICA.WE8ISO8859P1
characters currently used by your session.
You cannot use USERENV in the condition of
a CHECK constraint.
All calls to USERENV return VARCHAR2
data except for calls with the SESSIONID
and ENTRYID parameters, which return
NUMBER.
FIRST FIRST and LAST are very similar SELECT department_id,
MIN(salary) KEEP (DENSE_RANK
functions. Both are aggregate and analytic FIRST ORDER BY commission_pct)
functions that operate on a set of values from a "Worst",
set of rows that rank as the FIRST or LAST MAX(salary) KEEP (DENSE_RANK LAST
with respect to a given sorting specification. If ORDER BY commission_pct) "Best"
FROM employees GROUP BY
only one row ranks as FIRST or LAST, the department_id;
aggregate operates on the set with only one DEPARTMENT_ID Worst Best
element. ------------- ---------- -----
■ The aggregate_function is any one of the 10 4400 4400
MIN, MAX, SUM, AVG, 20 6000 13000
30 2500 11000
COUNT,VARIANCE, or STDDEV functions. 40 6500 6500
It operates on values from the rows that rank 50 2100 8200
either FIRST or LAST. If only one row ranks as 60 4200 9000
FIRST or LAST, the aggregate operates on a 70 10000 10000
80 6100 14000
singleton (nonaggregate) set. 90 17000 24000
100 6900 12000
110 8300 12000
7000 7000
SELECT last_name, department_id,
salary,
MIN(salary) KEEP (DENSE_RANK
FIRST ORDER BY commission_pct)
OVER (PARTITION BY department_id)
"Worst",
MAX(salary) KEEP (DENSE_RANK LAST
ORDER BY commission_pct) OVER
(PARTITION BY department_id)
"Best"
FROM employees
ORDER BY department_id, salary;
LAST_NAME DEPARTMENT_ID SALARY
Worst Best
------------------- ---------
Whalen 10 4400 4400 4400
Fay 20 6000 6000 13000
Hartstein 20 13000 6000 13000

FIRST_VALUE FIRST_VALUE is an analytic function. It SELECT department_id,


last_name, salary,
FIRST_VALUE ( expr returns the first value in an ordered set of FIRST_VALUE(last_name)
IGNORE NULLS values. If the first value in the set is null, then OVER (ORDER BY salary ASC ROWS
) OVER ( analytic_clause ) the function returns NULL unless you UNBOUNDED PRECEDING) AS
specify IGNORE NULLS. This setting is lowest_sal FROM (SELECT * FROM
useful for data densification. If you specify employees WHERE department_id =
90
IGNORE NULLS, then FIRST_VALUE ORDER BY employee_id);
returns the fist non-null value in the set, or DEPARTMENT_ID LAST_NAME SALARY
NULL if all values are null. Please refer to LOWEST_SAL
"Using Partitioned Outer Joins: Examples" on ------------- ------------- --
90 Kochhar 17000 Kochhar
page 19-41 for an example of data 90 De Haan 17000 Kochhar
densification. 90 King 24000 Kochhar
You cannot use FIRST_VALUE or any other
analytic function for expr. That is, you cannot SELECT department_id,
last_name, salary,
nest analytic functions, but you can use other FIRST_VALUE(last_name)
built-in function expressions for expr. Please OVER (ORDER BY salary ASC ROWS
refer to "About SQL Expressions" on page 6-1 UNBOUNDED PRECEDING) as fv
for information on valid forms of expr. FROM (SELECT * FROM employees
WHERE department_id = 90 ORDER by
employee_id DESC);
DEPARTMENT_ID LAST_NAME SALARY
FV
------------- ------------- --
90 De Haan 17000 De Haan
90 Kochhar 17000 De Haan
90 King 24000 De Haan
SELECT department_id, last_name,
salary, hire_date,
FIRST_VALUE(last_name) OVER
(ORDER BY salary ASC, hire_date
ROWS UNBOUNDED PRECEDING) AS
fv
FROM (SELECT * FROM employees
WHERE department_id = 90 ORDER BY
employee_id DESC);
DEPARTMENT_ID
LAST_NAME SALARY
HIRE_DATE FV
------------- ------------- -
90 Kochhar 17000 21-SEP-89
Kochhar
90 De Haan 17000 13-JAN-93
Kochhar
90 King 24000 17-JUN-87 Kochhar
LAST FIRST and LAST are very similar
functions. Both are aggregate and analytic
functions that operate on a set of values
from a set of rows that rank as the FIRST or
LAST with respect to a given sorting
specification. If only one row ranks as FIRST
or LAST, the aggregate operates on the set
with only one element. This function takes as
an argument any numeric datatype or any
nonnumeric datatype that can be implicitly
converted to a numeric datatype. The function
returns the same datatype as the numeric
datatype of the argument.
LAST_VALUE LAST_VALUE is an analytic function. It SELECT last_name, salary,
hire_date, LAST_VALUE(hire_date)
LAST_VALUE ( expr returns the last value in an ordered set of OVER
IGNORE NULLS values. If the last value in the set is null, then (ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING
) OVER ( analytic_clause ) the function returns NULL unless you specify AND UNBOUNDED FOLLOWING) AS
IGNORE NULLS. This setting is useful for lv
data densification. If you specify IGNORE FROM (SELECT * FROM employees
NULLS, then LAST_VALUE returns the first WHERE department_id = 90
non-null value in the set, or NULL if all values ORDER BY hire_date);
LAST_NAME SALARY HIRE_DATE LV
are null. -------------------------
Kochhar 17000 21-SEP-89
17-JUN-87
De Haan 17000 13-JAN-93 17-
JUN-87
King 24000 17-JUN-87 17-JUN-87

SELECT last_name, salary,


hire_date, LAST_VALUE(hire_date)
OVER
(ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS
lv
FROM (SELECT * FROM employees
WHERE department_id = 90 ORDER BY
hire_date DESC);
LAST_NAME SALARY HIRE_DATE LV
-------------------------
De Haan 17000 13-JAN-93
17-JUN-87
Kochhar 17000 21-SEP-89 17-
JUN-87
King 24000 17-JUN-87 17-JUN-87

SELECT last_name, salary,


hire_date, LAST_VALUE(hire_date)
OVER
(ORDER BY salary, hire_date
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS
lv
FROM (SELECT * FROM employees
WHERE department_id = 90
ORDER BY hire_date);
LAST_NAME SALARY HIRE_DATE LV
-------------------------
Kochhar 17000 21-SEP-89
17-JUN-87
De Haan 17000 13-JAN-93 17-
JUN-87
King 24000 17-JUN-87 17-JUN-87
RANK RANK calculates the rank of a value in a SELECT RANK(15500, .05) WITHIN
GROUP
group of values. Th Rows with equal values (ORDER BY salary,
for the ranking criteria receive the same rank. commission_pct) "Rank" FROM
Oracle Database then adds the number of tied employees;
rows to the tied rank to calculate the next rank. Rank
----------
Therefore, the ranks may not be consecutive 105
numbers. This function is useful for top-N and
bottom-N reporting. SELECT RANK(15500) WITHIN
■ As an aggregate function, RANK calculates GROUP
the rank of a hypothetical row identified by the (ORDER BY salary DESC) "Rank
of 15500" FROM employees;
arguments of the function with respect to a Rank of 15500
given sort specification. The arguments of the 4
function must all evaluate to constant
expressions within each aggregate group,
because they identify a single row within each
group. The constant argument expressions and
the expressions in the ORDER BY clause of
the aggregate match by position. Therefore, the
number of arguments must be the same and
their types must be compatible.
■ As an analytic function, RANK computes
the rank of each row returned from a query
with respect to the other rows returned by the
query, based on the values of the value_exprs
in the order_by_clause. e return type is
NUMBER.

Introduction to Oracle decode function

The Oracle DECODE function allows you to add the procedural if-then-else logic to the query. In
the following example, the Oracle DECODE function compares the first argument (1) with the
second argument (1). Because they are equal, the function returns the second argument which is
the string One.

SELECT DECODE (1, 1, 'One') FROM dual;


It works like the following if statement
IF 1 = 1 THEN RETURN 'One';
END IF

The following example is slightly different from the one above. The query returns a null value
because one does not equal two.

SELECT DECODE (1, 2, 'One') FROM dual;

If you want to specify a default value when the first argument is not equal to the second one, you
append the default value to the argument list as shown below:

SELECT DECODE (1, 2, 'One', 'Not one') FROM dual;

It works like the following if-then-else statement:


IF 1 = 2 THEN
RETURN 'One'; ELSE
RETURN 'Not one';
END IF;

SELECT
DECODE ( REGION, 'N','North',
'S','South',
'E','East',
'W','West',
'UNKNOWN' )
FROM CUSTOMER;
What if you want to compare the first argument with a list of arguments? See the following
example:

SELECT DECODE (2, 1, 'One', 2, 'Two') FROM dual;


The result is Two

In this example, the function compares the first argument (2) with the second one. If the first
argument equal the second one, the function returns the third argument (One). Otherwise, it
compares the first argument with the fourth argument (2). If they are equal, the function returns the
fifth argument (Two).
It works like the following if-then-els if statement:
IF 2 = 1 THEN
RETURN 'One';
ELSIF 2 = 2 THEN RETURN 'Two';
END IF;

If you want to specify a default value when the function does not find any match, you do it as follows:

SELECT DECODE (3, 1, 'One', 2, 'Two', 'Not one or two') FROM dual;

The query returned: Not one or two

The query works like the following if-then-elsif-else statement:


IF 3 = 1 THEN
RETURN 'One'; ELSIF 3 = 2 THEN RETURN 'Two';
ELSE
RETURN 'Not one or two'; END
IF;

Oracle DECODE () functions syntax


The following illustrates the syntax of the Oracle DECODE () function: DECODE (e,
s1, r1 [, s2, r2], ..., [,sn,rn] [, d]);
Arguments e
The first argument e is the value to be searched. The function automatically converts e to the data
type of s1 before comparing.
s1, s2, .. sn
The s1, s2, … or sn is an expression to search for. Note that s2, s3, … sn are automatically
converted to the data type of s1 before comparing.
r1, r2, .. rn
The r1, r2, …, or rn is the expression to return when e is equal to s.
d
d is an expression to return when e does not equal to any searched value s1, s2, .. sn.
Return value
The DECODE function returns a value with the data type of the first result (r1, r2, .. rn or d) argument
SELECT DECODE (country_id, 'US','United States',
'UK', 'United Kingdom',
'JP','Japan',
'CA', 'Canada',
'CH','Switzerland',
'IT', 'Italy', country_id) country ,
COUNT(*) FROM locations GROUP BY country_id HAVING COUNT (*) > =2 ORDER BY
country_id;

SELECT category_name,
SUM (DECODE (GREATEST (list_price, 0), LEAST (list_price, 1000), 1, 0)) "< 1000",
SUM (DECODE (GREATEST (list_price, 1001), LEAST (list_price, 2000), 1, 0)) "1001-2000",
SUM (DECODE (GREATEST (list_price, 2001), LEAST (list_price, 3000), 1, 0)) "2001-3000",
SUM (DECODE (GREATEST (list_price, 3001), LEAST (list_price, 8999), 1, 0)) "3001-8999"
FROM products INNER JOIN product_categories USING (category_id) GROUP BY category_name;
Here is the output:

You might also like