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

Oracle String Functions

The document describes various Oracle string functions. It provides examples of functions such as ASCII, CHR, COALESCE, CONCAT, CONVERT, DUMP, INSTR, INITCAP, LENGTH, LOWER, LPAD, LTRIM, REPLACE, REVERSE, RPAD, RTRIM, SOUNDEX, SUBSTR, TRANSLATE, TRIM, UPPER, and others. It also describes the Oracle INSTR function and number formatting in Oracle using TO_CHAR and TO_NUMBER.

Uploaded by

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

Oracle String Functions

The document describes various Oracle string functions. It provides examples of functions such as ASCII, CHR, COALESCE, CONCAT, CONVERT, DUMP, INSTR, INITCAP, LENGTH, LOWER, LPAD, LTRIM, REPLACE, REVERSE, RPAD, RTRIM, SOUNDEX, SUBSTR, TRANSLATE, TRIM, UPPER, and others. It also describes the Oracle INSTR function and number formatting in Oracle using TO_CHAR and TO_NUMBER.

Uploaded by

Ale Botello
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Oracle string functions

The ASCII function returns the decimal representation in the database character set of the first character
of char. Example: ASCII('b') =98
The CHR function returns the character having the binary equivalent to n as a VARCHAR2 value in either
CHR
the database character set. Example: CHR(10)||CHR(13) = carriage return plus line feed.
The COALESCE function returns the first non-null expr in the expression list. At least one expr must not
COALESCE be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null. Example:
select COALESCE(col1, col2, col3) FROM emp;
The CONCAT function returns the concatenation of 2 strings. You can also use the || command for this.
CONCAT
Example: CONCAT('abc','def') = 'abcdef'
The CONVERT function converts a string from one characterset to another. The datatype of the returned
value is VARCHAR2. Example: CONVERT('This is an example','UTF-8','WE8ISO8859P1') SELECT
CONVERT
CONVERT(' A B C D E ', 'US7ASCII', 'WE8ISO8859P1') FROM DUAL; = A E I ? ? A
BCDE?
The DUMP function returns a VARCHAR2 value containing the datatype code, length in bytes, and
DUMP
internal representation of expr. The returned result is always in the database character set.
INSTR
Returns the position of a String within a String. For more information see Oracle instr function
INITCAP
Transform String to init cap Example: INITCAP('ORADEV') = 'Oradev'
INSTRB
Returns the position of a String within a String, expressed in bytes.
INSTRC
Returns the position of a String within a String, expressed in Unicode complete characters
INSTR2
Returns the position of a String within a String, expressed in UCS2 code points
INSTR4
Returns the position of a String within a String, expressed in UCS4 code points
The LENGTH functions returns the length of char. LENGTH calculates length using characters as defined
LENGTH
by the input character set. Example: length('oradev.com') = 10
LENGTHB
Returns the length of a string, expressed in bytes.
The LOWER function returns a string with all lower case characters. Example: LOWER('ORADEV') =
LOWER
'oradev'
Add characters to the left of a string until a fixed number is reached. Example: lpad('abc',8,'x') =
LPAD
'xxxxxabc'. If the last parameter is not specified, spaces are added to the left.
LTRIM removed characters from the left of a string if they are equal to the specified string. Example:
LTRIM
ltrim('aaaaaabc','a') = 'bc' If the last parameter is not specified, spaces are removed from the left side.
The replace function replaces every occurrence of a search_string with a new string. If no new string is
REPLACE
specified, all occurrences of the search_string are removed. Example: replace('a1a1a1','a','2') = '212121'.
REVERSE
Reverses the characters of a String. Example: REVERSE('oradev.com') = 'moc.vedaro'
Add characters to the right of a string until a fixed number is reached. Example: rpad('abc',8,'x') =
RPAD
'abcxxxxx'. If the last parameter is not specified, spaces are added to the right.
RTRIM removed characters from the right of a string if they are equal to the specified string. Example:
RTRIM
rtrim('bcaaaaaa','a') = 'bc' If the last parameter is not specified, spaces are removed from the right side.
SOUNDEX returns a character string containing the phonetic representation of char. This function lets you
SOUNDEX compare words that are spelled differently, but sound alike in English. Example: select * from emp where
lastname SOUNDEX('SMITH');
SUBSTR
Returns a substring. For more information see Oracle substring
SUBSTRB
Returns a substring expressed in bytes instead of characters.
SUBSTRC
Returns a substring expressed in Unicode code points instead of characters.
SUBSTR2
Returns a substring using USC2 code points.
SUBSTR4
Returns a substring using USC4 code points.
TRANSLATE returns expr with all occurrences of each character in from_string replaced by its
corresponding character in to_string. Characters in expr that are not in from_string are not replaced.
TRANSLATE
Example: SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '___') FROM DUAL; =
'SQL_Plus_Users_Guide'
The TRIM function trims specified characters from the left and/or right. If no characters are specified, the
TRIM
left and right spaces are left out. Example: trim(' Oradev dot com ') = 'Oradev dot com'.
|| (pipes)
With pipes you can concattenate strings. Example 'Oradev'||'.com' = 'Oradev.com'.
UPPER
Transform a string to all upper case characters. Example: UPPER('oradev') = 'ORADEV'
ASCII

VSIZE

The VSIZE function returns the byte size of a String.

Oracle INSTR function


The Oracle function instr returns an integer indicating the position of the character in string that is the first character of this
occurrence.
This function has the following syntax:
instr(string, substring [,position [,occurrence]])
with:
string: the string that is searched.
substring: the substring which we are looking for in the string
position: The position from which we start the search (an integer value). If position is negative, then Oracle counts and
searches backward from the end of string. If omitted, this defaults to 1.
occurrence is an integer indicating which occurrence of string Oracle should search for. The value of occurrence must be
positive. If this is omitted, this defaults to 1.
Both string and substring can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
The value returned is of NUMBER datatype
If no value is found, the instr will return the value 0.
Examples
INSTR('CORPORATE FLOOR','OR', 3, 2) = 14
INSTR('CORPORATE FLOOR','OR', -3, 2) = 2
INSTR('ab ab ab','ab') = 1
INSTR('ab ab ab','ab',1,2) = 4
INSTR('ab ab ab','ab',2,2) = 7
INSTR('abcabcabcdef','de') = 7

Oracle number format


You can use a number format in Oracle in :
1. The TO_CHAR function to format a number datatype.
i.e. TO_CHAR(value,'90.99')
2. The TO_NUMBER function to convert a CHAR or VARCHAR2 value to a NUMBER datatype.
i.e. TO_CHAR('24.33','99.99')
All number format models cause the number to be rounded to the specified number of significant digits. If a value has
more significant digits to the left of the decimal place than are specified in the format, then pound signs (#) replace the
value. If a positive value is extremely large and cannot be represented in the specified format, then the infinity sign (~)
replaces the value. Likewise, if a negative value is extremely small and cannot be represented by the specified format,
then the negative infinity sign replaces the value (-~).
Element Example Description
9,999
,
(comma)

Returns a comma in the specified position. You can specify multiple commas in a number format
model.
Restrictions:

A comma element cannot begin a number format model.

Element Example Description

A comma cannot appear to the right of a decimal character or period in a number format
model.

Returns a decimal point, which is a period (.) in the specified position.


. (period) 99.99
Restriction: You can specify only one period in a number format model.
$

$9999

Returns value with a leading dollar sign.

0999

Returns leading zeros.

9990

Returns trailing zeros.

Returns value with the specified number of digits with a leading space if positive or with a leading
minus if negative.
9

9999
Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the
fixed-point number.

B9999

Returns blanks for the integer part of a fixed-point number when the integer part is zero (regardless
of "0"s in the format model).

C999

Returns in the specified position the ISO currency symbol (the current value of
the NLS_ISO_CURRENCY parameter).

99D99

Returns in the specified position the decimal character, which is the current value of
the NLS_NUMERIC_CHARACTER parameter. The default is a period (.).
Restriction: You can specify only one decimal character in a number format model.

EEEE

9.9EEEE Returns a value using in scientific notation.

FM

FM90.9

9G999

Returns a value with no leading or trailing blanks.


Returns in the specified position the group separator (the current value of
the NLS_NUMERIC_CHARACTER parameter). You can specify multiple group separators in a number
format model.
Restriction: A group separator cannot appear to the right of a decimal character or period in a
number format model.

L999

Returns in the specified position the local currency symbol (the current value of
the NLS_CURRENCY parameter).

MI

9999MI

Returns negative value with a trailing minus sign (-).

Element Example Description

Returns positive value with a trailing blank.


Restriction: The MI format element can appear only in the last position of a number format model.
Returns negative value in <angle brackets>.
PR

9999PR

Returns positive value with a leading and trailing blank.


Restriction: The PR format element can appear only in the last position of a number format model.
Returns a value as Roman numerals in uppercase.

RN

RN

rn

rn

Returns a value as Roman numerals in lowercase.


Value can be an integer between 1 and 3999.
Returns negative value with a leading minus sign (-).
Returns positive value with a leading plus sign (+).
S9999
S
9999S

Returns negative value with a trailing minus sign (-).


Returns positive value with a trailing plus sign (+).
Restriction: The S format element can appear only in the first or last position of a number format
model.
"Text minimum". Returns (in decimal output) the smallest number of characters possible. This
element is case-insensitive.

TM

TM

The default is TM9, which returns the number in fixed notation unless the output exceeds 64
characters. If output exceeds 64 characters, then Oracle automatically returns the number in
scientific notation.
Restrictions:

You cannot precede this element with any other element.

You can follow this element only with 9 or E (only one) or e (only one).

U9999

Returns in the specified position the "Euro" (or other) dual currency symbol (the current value of
the NLS_DUAL_CURRENCY parameter).

999V99

Returns a value multiplied by 10n (and if necessary, round it up), where n is the number of 9's after
the "V".

Element Example Description


Returns the hexadecimal value of the specified number of digits. If the specified number is not an
integer, then Oracle rounds it to an integer.
XXXX
X
xxxx

Restrictions:

This element accepts only positive values or 0. Negative values return an error.

You can precede this element only with 0 (which returns leading zeroes) or FM. Any other
elements return an error. If you specify neither 0 nor FM with X, then the return always has
1 leading blank.

The Oracle decode function


The decode function can be used in SQL for and IF-THEN-ELSE construction. It's an alternative for the CASE statement
which was introduced in Oracle 8.
Syntax:
decode( expression , compare_value, return_value, [,compare, return_value] ... [,default_return_value] )
with:
expression is the value to evaluate
compare_value is the value that can match the evaluated value
return_value is the value that is returned if compare_value equals the value.
The default_return_value is the value that is returned if no match is found.
To evaluate this expression, Oracle compares the expression to each compare_value one by one. If expression is equal to
a compare_value, Oracle returns the corresponding return_value. If no match is found, Oracle returns the
defaul_return_value. If no default value is specified, the null value will be returned.
Sample code
select id, decode(status,'A','Accepted','D','Denied','Other')
from
contracts;
Will return for each id:
If status = 'A' : 'Accepted'
If status = 'D' : 'Denied'
Else
: 'Other'
Oracle automatically converts the values for expression and compare_value to the datatype of the first compare_value.
Also the datatype of the return_value is converted to the datatype of the first return_value. If the first result has the
datatype CHAR or if the first result is null, then Oracle converts the return value to the datatype VARCHAR2.
Note: two null values are considered equivalent in the decode statement.

How to use the case statement in Oracle


The CASE statement can be used in SQL for and IF-THEN-ELSE construction. It's an alternative for the decode statement
and was introduced in Oracle 8. Syntax:
case( when condition then expr1 [when condition then expr2] ... [else exprN] ) end
Oracle searches for the first when condition that is true. The expr belonging the this condition is returned. If Oracle does
not find such a condition, the expression belonging to the else statement is returned. If no else is specified the null value
will be returned.
Sample code
select id
,
case (when status ='A' then 'Accepted'

from

when status ='D' then 'Denied'


else 'Other') end
contracts;

Will return for each id:


If status = 'A' : 'Accepted'
If status = 'D' : 'Denied'
Else
: 'Other'

Oracle NVL function


The NVL function is used to replace NULL values by another value.
The syntax for the NVL function is:
NVL( value_in, replace_with )
value_in if the function to test on null values. The value_in field can have a datatype char, varchar2, date or number
datatype.
replace_with is the value that is returned if value_in has a null value. The NVL statement works like this pl/sql code:
if (value_in is NULL) then
return replace_with;
else
return value_in;
end if;
Sample code:
select nvl(salary, 0)
from
employees;
select nvl(ref_code,'Unknown')
from
users;

XML Functions
Oracle provides XML functions to operate on or return XML documents or fragments.
Here is a list of all the XML functions (in version 10.2):
Function

Usage

Description
APPENDCHILDXML

APPENDCHILDXML(XMLTYPE_instance,XPath_string,value_expr) or
APPENDCHILDXML(XMLTYPE_instance,XPath_string,value_expr,namespace_string)

APPENDCHILDXML appends a user-supplied value onto the target XML as the child of the node indicated by an XPath
expression. XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes onto which one or more child nodes are to be
appended. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial
slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The value_expr specifies one or more nodes of XMLType. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
DELETEXML

DELETEXML(XMLTYPE_instance, XPath_string) or

DELETEXML(XMLTYPE_instance, XPath_string, namespace_string)


DELETEXML deletes the node or nodes matched by the XPath expression in the target XML.
XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes that are to be deleted. You can specify an
absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial
slash, the context of the relative path defaults to the root node. Any child nodes of the nodes specified by XPath_string
are also deleted.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
DEPTH

DEPTH(correlation_integer)

DEPTH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the number
of levels in the path specified by the UNDER_PATH condition with the same correlation variable. The correlation_integer
can be any NUMBER integer. Use it to correlate this ancillary function with its primary condition if the statement contains
multiple primary conditions. Values less than 1 are treated as 1.
EXTRACT (XML)

EXTRACT(XMLTYPE_instance,XPath_string) or
EXTRACT(XMLTYPE_instance,XPath_string, namespace_string)

EXTRACT (XML) is similar to the EXISTSNODE function. It applies a VARCHAR2 XPath string and returns an XMLType
instance containing an XML fragment. You can specify an absolute XPath_string with an initial slash or a relative
XPath_string by omitting the initial slash. If you omit the initial slash, the context of the relative path defaults to the root
node. The optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or
namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath expression(s).
EXISTSNODE

EXISTSNODE(XMLTYPE_instance,XPath_string) or
EXISTSNODE(XMLTYPE_instance,XPath_string, namespace_string)

EXISTSNODE determines whether traversal of an XML document using a specified path results in any nodes. It takes as
arguments the XMLType instance containing an XML document and a VARCHAR2 XPath string designating a path. The
optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping
for prefixes, which Oracle Database uses when evaluating the XPath expression(s).
The namespace_string argument defaults to the namespace of the root element. If you refer to any subelement in
Xpath_string, then you must specify namespace_string, and you must specify the "who" prefix in both of these
arguments.
EXTRACTVALUE

EXTRACTVALUE(XMLTYPE_instance,XPath_string) or
EXTRACTVALUE(XMLTYPE_instance,XPath_string, namespace_string)

The EXTRACTVALUE function takes as arguments an XMLType instance and an XPath expression and returns a scalar
value of the resultant node. The result must be a single node and be either a text node, attribute, or element. If the result
is an element, then the element must have a single text node as its child, and it is this value that the function returns. You
can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you
omit the initial slash, the context of the relative path defaults to the root node.

INSERTCHILDXML

INSERTCHILDXML(XMLTYPE_instance,XPath_string, child_expr, value_expr) or


INSERTCHILDXML(XMLTYPE_instance,XPath_string, child_expr, value_expr,
namespace_string)

INSERTCHILDXML inserts a user-supplied value into the target XML at the node indicated by the XPath expression.
Compare this function with INSERTXMLBEFORE.
XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes into which the one or more child nodes are to be
inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial

slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The child_expr specifies the one or more element or attribute nodes to be inserted.
The value_expr is an fragment of XMLType that specifies one or more notes being inserted. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
INSERTXMLBEFORE

INSERTXMLBEFORE(XMLTYPE_instance,XPath_string, value_expr) or
INSERTXMLBEFORE(XMLTYPE_instance,XPath_string, value_expr, namespace_string)

INSERTXMLBEFORE inserts a user-supplied value into the target XML before the node indicated by the XPath
expression. Compare this function with INSERTCHILDXML.
XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes into which one or more child nodes are to be
inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial
slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The value_expr is a fragment of XMLType that defines one or more nodes being inserted and their position within the
parent node. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
PATH

PATH(correlation_integer)

PATH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the relative
path that leads to the resource specified in the parent condition.
The correlation_integer can be any NUMBER integer and is used to correlate this ancillary function with its primary
condition. Values less than 1 are treated as 1.
SYS_DBURIGEN

SYS_DBURIGEN(column,text)

SYS_DBURIGen takes as its argument one or more columns or attributes, and optionally a rowid, and generates a URL
of datatype DBURIType to a particular column or row object. You can then use the URL to retrieve an XML document
from the database.
SYS_XMLAGG

SYS_XMLAGG(expr) or
SYS_XMLAGG(expr,fmt)

SYS_XMLAgg aggregates all of the XML documents or fragments represented by expr and produces a single XML
document. It adds a new enclosing element with a default name ROWSET. If you want to format the XML document
differently, then specify fmt, which is an instance of the XMLFormat object.
SYS_XMLGEN

SYS_XMLGEN(expr) or
SYS_XMLGEN(expr,fmt)

SYS_XMLGen takes an expression that evaluates to a particular row and column of the database, and returns an
instance of type XMLType containing an XML document. The expr can be a scalar value, a user-defined type, or an
XMLType instance.
If expr is a scalar value, then the function returns an XML element containing the scalar value.
If expr is a type, then the function maps the user-defined type attributes to XML elements.
If expr is an XMLType instance, then the function encloses the document in an XML element whose default tag name is
ROW.
By default the elements of the XML document match the elements of expr. For example, if expr resolves to a column
name, then the enclosing XML element will be the same column name. If you want to format the XML document
differently, then specify fmt, which is an instance of the XMLFormat object.
UPDATEXML

UPDATEXML(XMLTYPE_instance,XPath_string, value_expr) or
UPDATEXML(XMLTYPE_instance,XPath_string, value_expr, namespace_string)

UPDATEXML takes as arguments an XMLType instance and an XPath-value pair and returns an XMLType instance with
the updated value. If XPath_string is an XML element, then the corresponding value_expr must be an XMLType instance.
If XPath_string is an attribute or text node, then the value_expr can be any scalar datatype. You can specify an absolute
XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, the
context of the relative path defaults to the root node. The datatypes of the target of each XPath_string and its
corresponding value_expr must match. The optional namespace_string must resolve to a VARCHAR2 value that
specifies a default mapping or namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath
expression(s).
XMLAGG

XMLAGG(XMLTYPE_instance) or
XMLAGG(XMLTYPE_instance, order_by_clause)

XMLAgg is an aggregate function. It takes a collection of XML fragments and returns an aggregated XML document. Any
arguments that return null are dropped from the result.
XMLAgg is similar to SYS_XMLAgg except that XMLAgg returns a collection of nodes but it does not accept formatting
using the XMLFormat object. Also, XMLAgg does not enclose the output in an element tag as does SYS_XMLAgg.
Within the order_by_clause, Oracle Database does not interpret number literals as column positions, as it does in other
uses of this clause, but simply as number literals.
XMLCDATA

XMLCDATA(value_expr)

XMLCData generates a CDATA section by evaluating value_expr. The value_expr must resolve to a string. The value
returned by the function takes the following form:
If the resulting value is not a valid XML CDATA section, then the function returns an error.The following conditions apply
to XMLCData:
The value_expr cannot contain the substring ]]>.
If value_expr evaluates to null, then the function returns null.
XMLCOLATTVAL

XMLCOLATTVAL(value_expr AS c_alias) or
XMLCOLATTVAL(value_expr AS c_alias, value_expr AS c_alias,..)

XMLColAttVal creates an XML fragment and then expands the resulting XML so that each XML fragment has the name
column with the attribute name. You can use the AS c_alias clause to change the value of the name attribute to
something other than the column name. You must specify a value for value_expr. If value_expr is null, then no element is
returned. Restriction on XMLColAttVal: You cannot specify an object type column for value_expr.
XMLCOMMENT

XMLCOMMENT(value_expr)

XMLComment generates an XML comment using an evaluated result of value_expr. The value_expr must resolve to a
string. It cannot contain two consecutive dashes (hyphens). The value returned by the function takes the following form:
<!--string-->
If value_expr resolves to null, then the function returns null.
XMLCONCAT

XMLCONCAT(XMLTYPE_instance) or
XMLCONCAT(XMLTYPE_instance, XMLTYPE_instance, ...)

XMLConcat takes as input a series of XMLType instances, concatenates the series of elements for each row, and returns
the concatenated series. XMLConcat is the inverse of XMLSequence.
Null expressions are dropped from the result. If all the value expressions are null, then the function returns null.
XMLFOREST

XMLFOREST(value_expr AS c_alias) or
XMLFOREST(value_expr AS c_alias, value_expr AS c_alias,..)

XMLForest converts each of its argument parameters to XML, and then returns an XML fragment that is the
concatenation of these converted arguments.

If value_expr is a scalar expression, then you can omit the AS clause, and Oracle Database uses the column name as
the element name.
If value_expr is an object type or collection, then the AS clause is mandatory, and Oracle uses the specified c_alias as
the enclosing tag. The c_alias can be up to 4000 characters.
If value_expr is null, then no element is created for that value_expr.

XMLPARSE

XMLPARSE(DOCUMENT, value_expr) or
XMLPARSE(DOCUMENT, value_expr WELLFORMED) or
XMLPARSE(CONTENT, value_expr) or
XMLPARSE(CONTENT, value_expr WELLFORMED)

XMLParse parses and generates an XML instance from the evaluated result of value_expr. The value_expr must resolve
to a string. If value_expr resolves to null, then the function returns null.
If you specify DOCUMENT, then value_expr must resolve to a singly rooted XML document.
If you specify CONTENT, then value_expr must resolve to a valid XML value.
When you specify WELLFORMED, you are guaranteeing that value_expr resolves to a well-formed XML document, so
the database does not perform validity checks to ensure that the input is well formed.

XMLPI

XMLPI(identifier) or
XMLPI(NAME identifier) or
XMLPI(NAME identifier , value_expr)

XMLPI generates an XML processing instruction using identifier and optionally the evaluated result of value_expr. A
processing instruction is commonly used to provide to an application information that is associated with all or part of an
XML document. The application uses the processing instruction to determine how best to process the XML document.
XMLQUERY

XMLQUERY(XQuery_string RETURNING CONTENT) or


XMLQUERY(XQuery_string XML_passing_clause RETURNING CONTENT)

XMLQUERY lets you query XML data in SQL statements. It takes an XQuery expression as a string literal, an optional
context item, and other bind variables and returns the result of evaluating the XQuery expression using these input
values.
XQuery_string is a complete XQuery expression, including prolog.
The expr in the XML_passing_clause is an expression returning an XMLType that is used as the context for evaluating
the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. The result of
evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an
AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string.
RETURNING CONTENT indicates that the result from the XQuery evaluation is either an XML 1.0 document or a
document fragment conforming to the XML 1.0 semantics.
XMLROOT

XMLROOT(...)

XMLROOT lets you create a new XML value by providing version and standalone properties in the XML root information
(prolog) of an existing XML value. If the value_expr already has a prolog, then the database returns an error. If the input
is null, then the function returns null.

XMLSEQUENCE

XMLSEQUENCE(XMLTYPE_instance) or
XMLSEQUENCE(sys_refcursor_instance) or
XMLSEQUENCE(sys_refcursor_instance, fmt)

XMLSequence has two forms:


The first form takes as input an XMLType instance and returns a varray of the top-level nodes in the XMLType. This form
is effectively superseded by the SQL/XML standard function XMLTable, which provides for more readable SQL code.
Prior to Oracle Database 10g Release 2, XMLSequence was used with SQL function TABLE to do some of what can now
be done better with the XMLTable function.
The second form takes as input a REFCURSOR instance, with an optional instance of the XMLFormat object, and

returns as an XMLSequence type an XML document for each row of the cursor.
Because XMLSequence returns a collection of XMLType, you can use this function in a TABLE clause to unnest the
collection values into multiple rows, which can in turn be further processed in the SQL query.

XMLSERIALIZE

XMLSERIALIZE(DOCUMENT, value_expr) or
XMLSERIALIZE(DOCUMENT, value_expr AS datatype) or
XMLSERIALIZE(CONTENT, value_expr) or
XMLSERIALIZE(CONTENT, value_expr AS datatype)

XMLSerialize creates a string or LOB containing the contents of value_expr.


If you specify DOCUMENT, then the value_expr must be a valid XML document.
If you specify CONTENT, then the value_expr need not be a singly rooted XML document. However it must be valid XML
content.
The datatype specified can be a string type (VARCHAR2 or VARCHAR, but not NVARCHAR or NVARCHAR2) or CLOB .
The default is CLOB.
XMLTABLE(XML_namespaces_clause, XQuery_string XMLTABLE_options)
XMLTABLE(XQuery_string XMLTABLE_options)

XMLTABLE

XMLTable maps the result of an XQuery evaluation into relational rows and columns. You can query the result returned
by the function as a virtual relational table using SQL.
XMLTRANSFORM

XMLTRANSFORM(XMLTYPE_instance,XMLTYPE_instance)

XMLTransform takes as arguments an XMLType instance and an XSL style sheet, which is itself a form of XMLType
instance. It applies the style sheet to the instance and returns an XMLType.
This function is useful for organizing data according to a style sheet as you are retrieving it from the database.

Oracle date format


With the functions to_char and to_date, a date format can be used. Example:
select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;
will return something like: 24/03/2006 14:36:43
Here is a list of all the formats that can be used:
Format
mask

Description

CC

Century

SCC

Century BC prefixed with -

YYYY

Year with 4 numbers

SYYY

Year BC prefixed with -

IYYY

ISO Year with 4 numbers

YY

Year with 2 numbers

RR

Year with 2 numbers with Y2k compatibility

YEAR

Year in characters

SYEAR

Year in characters, BC prefixed with -

BC

BC/AD Indicator *

Quarter in numbers (1,2,3,4)

MM

Month of year 01, 02...12

MONTH

Month in characters (i.e. January)

MON

JAN, FEB

WW

Weeknumber (i.e. 1)

Weeknumber of the month (i.e. 5)

IW

Weeknumber of the year in ISO standard.

DDD

Day of year in numbers (i.e. 365)

DD

Day of the month in numbers (i.e. 28)

Day of week in numbers(i.e. 7)

DAY

Day of the week in characters (i.e. Monday)

FMDAY

Day of the week in characters (i.e. Monday)

DY

Day of the week in short character description (i.e. SUN)

Julian Day (number of days since January 1 4713 BC, where January 1 4713 BC is 1 in Oracle)

HH

Hournumber of the day (1-12)

HH12

Hournumber of the day (1-12)

HH24

Hournumber of the day with 24Hours notation (0-23)

AM

AM or PM

PM

AM or PM

MI

Number of minutes (i.e. 59)

SS

Number of seconds (i.e. 59)

SSSSS

Number of seconds this day.

DS

Short date format. Depends on NLS-settings. Use only with timestamp.

DL

Long date format. Depends on NLS-settings. Use only with timestamp.

Abbreviated era name. Valid only for calendars: Japanese Imperial, ROC Official and Thai Buddha.. (Inputonly)

EE

The full era name

FF

The fractional seconds. Use with timestamp.

FF1..FF9

The fractional seconds. Use with timestamp. The digit controls the number of decimal digits used for
fractional seconds.

FM

Fill Mode: suppresses blianks in output from conversion

FX

Format Exact: requires exact pattern matching between data and format model.

IYY or IY or
the last 3,2,1 digits of the ISO standard year. Output only
I
RM

The Roman numeral representation of the month (I .. XII)

RR

The last 2 digits of the year.

RRRR

The last 2 digits of the year when used for output. Accepts fout-digit years when used for input.

SCC

Century. BC dates are prefixed with a minus.

CC

Century

SP

Spelled format. Can appear of the end of a number element. The result is always in english. For example
month 10 in format MMSP returns "ten"

SPTH

Spelled and ordinal format; 1 results in first.

TH

Converts a number to it's ordinal format. For example 1 becoms 1st.

TS

Short time format. Depends on NLS-settings. Use only with timestamp.

TZD

Abbreviated time zone name. ie PST.

TZH

Time zone hour displacement.

TZM

Time zone minute displacement.

TZR

Time zone region

Local radix character. In america this is a period (.)

Single row numeric functions


Oracle provides a lot of standard numeric functions for single rows. Here is a list of all the single row numeric functions
(in version 10.2).

Function

Usage

Description

ABS

ABS(n)

ABS returns the absolute value of n.

ACOS

ACOS(n)

ACOS returns the arc cosine of n. The argument 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 must be in


the range of -1 to 1, and the function 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 n can be in


an unbounded range and returns a value in the range of -pi/2
to pi/2, expressed in radians.

ATAN2(n1,n2) or ATAN2(n1/n2)

ATAN2 returns the arc tangent of n1 and n2. The argument


n1 can be in an unbounded range and returns a value in the
range of -pi to pi, depending on the signs of n1 and n2,
expressed in radians. ATAN2(n1,n2) is the same as
ATAN2(n1/n2).

BITAND(expr1,expr2)

BITAND computes an AND operation on the bits of expr1 and


expr2, both of which must resolve to nonnegative integers,
and returns an integer. This function is commonly used with
the DECODE function, as illustrated in the example that
follows.

CEIL(n)

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.

COS(n)

COS returns the cosine of n (an angle expressed in radians).


This function takes as an argument any numeric datatype or
any nonnumeric datatype that can be implicitly converted to a
numeric datatype. If the argument is BINARY_FLOAT, then
the function returns BINARY_DOUBLE. Otherwise the
function returns the same numeric datatype as the argument.

COSH

COSH(n)

COSH returns the hyperbolic cosine of n. This function takes


as an argument any numeric datatype or any nonnumeric
datatype that can be implicitly converted to a numeric
datatype. If the argument is BINARY_FLOAT, then the
function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric datatype as the argument.

EXP

EXP(n)

ATAN2

BITAND

CEIL

COS

EXP returns e raised to the nth power, where e =


2.71828183... The function returns a value of the same type
as the argument. This function takes as an argument any
numeric datatype or any nonnumeric datatype that can be

implicitly converted to a numeric datatype. If the argument is


BINARY_FLOAT, then the function returns
BINARY_DOUBLE. Otherwise the function returns the same
numeric datatype as the argument.

FLOOR

LN

LOG

MOD

NANVL

POWER

FLOOR(n)

FLOOR returns largest integer equal to or less than n. 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.

LN(n)

LN returns the natural logarithm of n, where n is greater than


0. This function takes as an argument any numeric datatype
or any nonnumeric datatype that can be implicitly converted
to a numeric datatype. If the argument is BINARY_FLOAT,
then the function returns BINARY_DOUBLE. Otherwise the
function returns the same numeric datatype as the argument.

LOG(n2,n1)

LOG returns the logarithm, base n2, of n1. The base n1 can
be any positive value other than 0 or 1 and n2 can be any
positive value. This function takes as arguments any numeric
datatype or any nonnumeric datatype that can be implicitly
converted to a numeric datatype. If any argument is
BINARY_FLOAT or BINARY_DOUBLE, then the function
returns BINARY_DOUBLE. Otherwise the function returns
NUMBER.

MOD(n2,n1)

MOD returns the remainder of n2 divided by n1. Returns n2 if


n1 is 0. This function takes as arguments any numeric
datatype or any nonnumeric datatype that can be implicitly
converted to a numeric datatype. Oracle determines the
argument with the highest numeric precedence, implicitly
converts the remaining arguments to that datatype, and
returns that datatype.

NANVL(n2,n1)

The NANVL function is useful only for floating-point numbers


of type BINARY_FLOAT or 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. This function takes as arguments any numeric
datatype or any nonnumeric datatype that can be implicitly
converted to a numeric datatype. Oracle determines the
argument with the highest numeric precedence, implicitly
converts the remaining arguments to that datatype, and
returns that datatype.

POWER(n2,n1)

POWER returns n2 raised to the n1 power. The base n2 and


the exponent n1 can be any numbers, but if n2 is negative,
then n1 must be an integer. This function takes as arguments
any numeric datatype or any nonnumeric datatype that can
be implicitly converted to a numeric datatype. If any
argument is BINARY_FLOAT or BINARY_DOUBLE, then the
function returns BINARY_DOUBLE. Otherwise the function
returns NUMBER.

REMAINDER

REMAINDER(n2,n1)

ROUND (number) ROUND (n) ROUND(n, integer)

SIGN

SIGN(n)

REMAINDER returns the remainder of n2 divided by n1. This


function takes as arguments any numeric datatype or any
nonnumeric datatype that can be implicitly converted to a
numeric datatype. Oracle determines the argument with the
highest numeric precedence, implicitly converts the
remaining arguments to that datatype, and returns that
datatype. The MOD function is similar to REMAINDER
except that it uses FLOOR in its formula, whereas
REMAINDER uses ROUND.
ROUND returns n rounded to integer places to the right of
the decimal point. If you omit integer, then n is rounded to 0
places. The argument integer can be negative to round off
digits left of the decimal point. n can be any numeric datatype
or any nonnumeric datatype that can be implicitly converted
to a numeric datatype. The argument integer must be an
integer. If you omit integer, then the function returns the same
datatype as the numeric datatype of the argument. If you
include integer, then the function returns NUMBER. For
NUMBER values, the value n is rounded away from 0 (for
example, to x+1 when x.5 is positive and to x-1 when x.5 is
negative). For BINARY_FLOAT and BINARY_DOUBLE
values, the function rounds to the nearest even value. Please
refer to the examples that follow.
SIGN returns the sign of n. This function takes as an
argument any numeric datatype, or any nonnumeric datatype
that can be implicitly converted to NUMBER, and returns
NUMBER. of NUMBER type, the sign is:
-1 if n<0
0 if n=0
1 if n>0
For binary floating-point numbers (BINARY_FLOAT and
BINARY_DOUBLE), this function returns the sign bit of the
number. The sign bit is:
-1 if n<0
+1 if n>=0 or n=NaN

SIN(n)

SIN returns the sine of n (an angle expressed in radians).


This function takes as an argument any numeric datatype or
any nonnumeric datatype that can be implicitly converted to a
numeric datatype. If the argument is BINARY_FLOAT, then
the function returns BINARY_DOUBLE. Otherwise the
function returns the same numeric datatype as the argument.

SINH

SINH(n)

SINH returns the hyperbolic sine of n. This function takes as


an argument any numeric datatype or any nonnumeric
datatype that can be implicitly converted to a numeric
datatype. If the argument is BINARY_FLOAT, then the
function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric datatype as the argument.

SQRT

SQRT(n)

SIN

SQRT returns the square root of n. 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.

TAN(n)

TAN returns the tangent of n (an angle expressed in radians).


This function takes as an argument any numeric datatype or
any nonnumeric datatype that can be implicitly converted to a
numeric datatype. If the argument is BINARY_FLOAT, then
the function returns BINARY_DOUBLE. Otherwise the
function returns the same numeric datatype as the argument.

TANH(n)

TANH returns the hyperbolic tangent of n. This function takes


as an argument any numeric datatype or any nonnumeric
datatype that can be implicitly converted to a numeric
datatype. If the argument is BINARY_FLOAT, then the
function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric datatype as the argument.

TRUNC (number) TRUNC(n1) TRUNC(n1,n2)

The TRUNC (number) function returns n1 truncated to n2


decimal places. If n2 is omitted, then n1 is truncated to 0
places. n2 can be negative to truncate (make zero) n2 digits
left of the decimal point. This function takes as an argument
any numeric datatype or any nonnumeric datatype that can
be implicitly converted to a numeric datatype. If you omit n2,
then the function returns the same datatype as the numeric
datatype of the argument. If you include n2, then the function
returns NUMBER.

TAN

TANH

WIDTH_BUCKET

WIDTH_BUCKET(expr,min_value,
max_value,num_buckets)

Oracle date functions


Oracle has a number of functions that apply to a date

WIDTH_BUCKET lets you construct equiwidth histograms, in


which the histogram range is divided into intervals that have
identical size. (Compare this function with NTILE, which
creates equiheight histograms.) Ideally each bucket is a
closed-open interval of the real number line. For example, a
bucket can be assigned to scores between 10.00 and
19.999... to indicate that 10 is included in the interval and 20
is excluded. This is sometimes denoted [10, 20).
For a given expression, WIDTH_BUCKET returns the bucket
number into which the value of this expression would fall
after being evaluated.
expr is the expression for which the histogram is being
created. This expression must evaluate to a numeric or
datetime value or to a value that can be implicitly converted
to a numeric or datetime value. If expr evaluates to null, then
the expression returns null.
min_value and max_value are expressions that resolve to the
end points of the acceptable range for expr. Both of these
expressions must also evaluate to numeric or datetime
values, and neither can evaluate to null.
num_buckets is an expression that resolves to a constant
indicating the number of buckets. This expression must
evaluate to a positive integer.

Sysdate

Returns the current date/time

ADD_MONTHS

Function to add a number of months to a date. For example: add_months(SYSDATE,3)


returns 3 months after sysdate. This could be rounded to below is the resulting month
has fewer days than the month this function is applied to.

+,- (plus/minus)

In Oracle you can add or substract a number of days from a date. Example: sysdate+5
means systemdate/time plus 5 days

GREATEST

With the greatest function you can select the date/time that is the highest in a range of
date/times. Example: greatest (sysdate+4,sysdate,sysdate-5) = sysdate+4.

LEAST

With the least function you can select the earliest date/time in a range of date/times.
Example: least(sysdate+4,sysdate,sysdate-5) = sysdate-5.

LAST_DAY

Returns the last_day of a month based on the month the passed date is in. Example:
last_day(sysdate) returns the last day of this month.

MONTHS_BETWEEN

Returns the number of months between two dates. The number is not rounded.
Example: months_between(sysdate, to_date('01-01-2007','dd-mm-yyyy')) returns the
number of months since jan 1, 2007.

NEXT_DAY

Date of next specified date following a date NEXT_DAY(, ) Options are SUN, MON, TUE,
WED, THU, FRI, and SAT SELECT NEXT_DAY(SYSDATE, 'FRI') FROM dual; NOTE:
This can be dependend on NLS_SETTINGS!

ROUND

Returns date rounded to the unit specified by the format model. If you omit the format,
the date is rounded to the nearest day ROUND(, ) SELECT ROUND(TO_DATE('27-OCT00'),'YEAR') NEW_YEAR FROM dual;

TRUNC

Convert a date to the date without time (0:00h) Example: TRUNC(sysdate) returns today
without time.

First day of the month.

trunc(example_date,'MM') Example: select trunc(TO_DATE('31-JAN-2007'),'MM') FROM


dual;

TO_CHAR(date,format_mask) Converts a date to a string using a format mask. Format masks are explained here

Storing XML in the Oracle database.


Since Oracle 9iR1, you can store XML in the database as a seperate datatype: XMLType.
There are 2 ways to store data in XMLType:
1. Store XML in CLOB XMLType. (from Oracle 9iR1)
2. Store XML as structured data. Register an XML Schema and store XML in an XML-schema based XMLType using
Object-relational storage.(from Oracle 9iR2)
Oracle also supplies a lot of standard functions for manipulating XML.
1. Store XML in CLOB XMLType
With the CLOB XMLType you can store XML documents as a Character Large OBject.
Using the CLOB XMLType storage there is no need for validation of the XML.
The XML does have to be well-formed, and it's optional to validate the XML document against an XML schema or DTD
yourself.
With this type Oracle implicitly stores the XML in a CLOB column. The original XML is preserved including whitespace All
restrictions on a CLOB column apply also to this XMLType.
Use CLOB storage for XMLType when:

- you are interested in storing and retrieving the whole document.


- you do not need to perform piece-wise updates on XML documents.
Code examples:
create table XmlTest( id number
, data_xml XMLType)
XmlType data_xml STORE AS CLOB;
insert into XmlTest(id, data_xml) values
( 1
, XMLType('<company>
<department>
<id>10</id>
<name>Accounting</name>
</department>
</company>'));
create table XmlTest2 of XmlType;
INSERT INTO XmlTest2 VALUES (
XMLType('<?xml version="1.0"?>
<company>
<department>
<id>10</id>
<name>Accounting</name>
</department>
</company>'
));
SELECT x.getCLobVal() from XmlTest2 x;
2. Register an XML Schema and store XML in an XML-schema based XMLType using Object-relational storage.
From version 9iR2 you can use XML-schema based XMLType.
This will give a much better performance.
XMLType combines the relational storage of the XML document with some standard W3C XML specific methods. The
data is stored in the database using DOM. The Oracle database will know much more about the XML structure. You will
have advantages like sorting, using XML constraints.
Code examples:
begin
dbms_xmlschema.registerSchema(
'http://www.oradev.com/sample.xsd',
'<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.oradev.com/sample.xsd"
xmlns:samp="http://www.oradev.com/sample.xsd"
version="1.0">
<simpleType name="departmentIdType">
<restriction base="integer">
<enumeration value="10"/>
<enumeration value="20"/>
<enumeration value="30"/>
<enumeration value="40"/>
</restriction>
</simpleType>
<element name="company">
<complexType>
<sequence>
<element name="department">

<complexType>
<sequence>
<element name = "id"
type = "samp:departmentIdType"/>
<element name = "name" type = "string"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>',
TRUE, TRUE, FALSE, FALSE);
end;
Now you can create an XMLSchema-based table, as shown in the following example:
CREATE TABLE XmlTest OF XMLType
XMLSCHEMA "http://www.oradev.com/sample.xsd"
ELEMENT "company";
Now XML can be inserted into the XmlTest table as following:
INSERT INTO XmlTest VALUES(
xmltype.createxml('<?xml version="1.0"?>
<samp:company xmlns:samp="http://www.oradev.com/sample.xsd" >
<department>
<id>10</id>
<name>Accounting</name>
</department>
</samp:company>'));
CREATE TABLE XmlTest2 (
id number
, xml_data XmlType)
XMLTYPE xml_data STORE AS OBJECT RELATIONAL
XMLSCHEMA "http://www.oradev.com/sample.xsd"
ELEMENT "company";
INSERT INTO XmlTest2 VALUES(1,
xmltype.createxml('<?xml version="1.0"?>
<samp:company xmlns:samp="http://www.oradev.com/sample.xsd" >
<department>
<id>10</id>
<name>Accounting</name>
</department>
</samp:company>'));
It's also possible to create constraints on on the XMLSchema-based table.

Oracle Regular Expressions


Version 11.1

General Information
Anchoring Characters

Equivalence Classes

Match Options

Posix Characters

Character
Class

Description

Anchor the expression to the start of a line

Anchor the expression to the end of a line

Character
Class

Description

==

Oracle supports the equivalence classes through the POSIX '[==]' syntax. A base
letter and all of its accented versions constitute an equivalence class. For
example, the equivalence class '[=a=]' matches and . The equivalence
classes are valid only inside the bracketed expression

Character
Class

Description

Case sensitive matching

Case insensitive matching

Treat source string as multi-line activating Anchor chars

Allow the period (.) to match any newline character

Character
Class

Description

[:alnum:]

Alphanumeric characters

[:alpha:]

Alphabetic characters

[:blank:]

Blank Space Characters

[:cntrl:]

Control characters (nonprinting)

[:digit:]

Numeric digits

[:graph:]

Any [:punct:], [:upper:], [:lower:], and [:digit:] chars

[:lower:]

Lowercase alphabetic characters

[:print:]

Printable characters

[:punct:]

Punctuation characters

[:space:]

Space characters (nonprinting), such as carriage return, newline, vertical tab,


and form feed

Quantifier Characters

[:upper:]

Uppercase alphabetic characters

[:xdigit:]

Hexidecimal characters

Character
Class

Match 0 or more times

Match 0 or 1 time

Match 1 or more times

{m}

Match exactly m times

{m,}

Match at least m times

{m, n}
\n

Alternative Matching
And Grouping
Characters

Match at least m times but no more than n times


Cause the previous expression to be repeated n times

Character
Class

|
()

[char]

Demo Table

Description

Description
Separates alternates, often used with grouping operator ()
Groups subexpression into a unit for alternations, for quantifiers, or for
backreferencing (see "Backreferences" section)
Indicates a character list; most metacharacters inside a character list are
understood as literals, with the exception of character classes, and the ^ and metacharacters

CREATETABLEtest(
testcolVARCHAR2(50));
INSERTINTOtestVALUES('abcde');
INSERTINTOtestVALUES('12345');
INSERTINTOtestVALUES('1a4A5');
INSERTINTOtestVALUES('12a45');
INSERTINTOtestVALUES('12aBC');
INSERTINTOtestVALUES('12abc');
INSERTINTOtestVALUES('12ab5');
INSERTINTOtestVALUES('12aa5');
INSERTINTOtestVALUES('12AB5');
INSERTINTOtestVALUES('ABCDE');
INSERTINTOtestVALUES('1235');
INSERTINTOtestVALUES('12.45');
INSERTINTOtestVALUES('1a4b5');
INSERTINTOtestVALUES('135');

INSERTINTOtestVALUES('145');
INSERTINTOtestVALUES('15');
INSERTINTOtestVALUES('abcd');
INSERTINTOtestVALUES('abcde');
INSERTINTOtestVALUES('ae');
INSERTINTOtestVALUES('Steven');
INSERTINTOtestVALUES('Stephen');
INSERTINTOtestVALUES('111.222.3333');
INSERTINTOtestVALUES('222.333.4444');
INSERTINTOtestVALUES('333.444.5555');
INSERTINTOtestVALUES('abcdefabcdefabcxyz');
COMMIT;

REGEXP_COUNT
REGEXP_COUNT(<source_string>,<pattern>[[,<start_position>],
[<match_parameter>]])

Syntax

Count's occurrences
based on a regular
expression

matchparameter:
'c'=casesensitive
'i'=caseinsensitivesearch
'm'=treatsthesourcestringasmultiplelines
'n'=allowstheperiod(.)wildcharactertomatchnewline
'x'=ignorewhitespacecharacters
SELECTREGEXP_COUNT(testcol,'2a',1,'i')RESULT
FROMtest;
SELECTREGEXP_COUNT(testcol,'e',1,'i')RESULT
FROMtest;

REGEXP_INSTR

Syntax

Find character 'o'


followed by any 3
alphabetic characters:
case insensitive

REGEXP_INSTR(<source_string>,<pattern>[[,<start_position>][,
<occurrence>][,<return_option>][,<match_parameter>][,
<sub_expression>]])
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
[[:alpha:]]{3}',1,1,0,'i')RESULT
FROMDUAL;
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]

Our thanks to Cassio for [[:alpha:]]{3}',1,1,1,'i')RESULT


spotting a typo here.
FROMDUAL;

SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]

[[:alpha:]]{3}',1,2,0,'i')RESULT
FROMDUAL;
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
[[:alpha:]]{3}',1,2,1,'i')RESULT
FROMDUAL;
Find the position of try,
trying, tried or tries

SELECTREGEXP_INSTR('Wearetryingtomakethesubjecteasier.',
'tr(y(ing)?|(ied)|(ies))')RESULTNUM
FROMDUAL;
SELECTtestcol,REGEXP_INSTR(testcol,'ab',1,1,0,'i',0)
FROMtest;

Using Sub-Expression
option

SELECTtestcol,REGEXP_INSTR(testcol,'ab',1,1,0,'i',1)
FROMtest;
SELECTtestcol,REGEXP_INSTR(testcol,'a(b)',1,1,0,'i',1)
FROMtest;

REGEXP_LIKE
Syntax

REGEXP_LIKE(<source_string>,<pattern>,<match_parameter>)

AlphaNumeric
Characters

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]{5}');

Alphabetic Characters

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]{5}');

Control Characters

INSERTINTOtestVALUES('zyx'||CHR(13)||'wvu');
COMMIT;
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:cntrl:]]{1}');

Digits

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]{5}');

Lower Case

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{5}');

Printable Characters

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{5}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{6}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{7}');

Punctuation

TRUNCATETABLEtest;
SELECT*

FROMtest
WHEREREGEXP_LIKE(testcol,'[[:punct:]]');
Spaces

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{5}');

Upper Case

SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]{3}');

Values Starting with 'a


%b'

SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^ab*');

'a' is the third value

SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^..a.');

SELECTtestcol
Contains two
consecutive occurances FROMtest
of the letter 'a' or 'z'
WHEREREGEXP_LIKE(testcol,'([az])\1','i');
Begins with 'Ste' ends
with 'en' and contains
either 'v' or 'ph' in the
center

SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^Ste(v|ph)en$');

Use a regular
expression in a check
constraint

CREATETABLEmytest(c1VARCHAR2(20),
CHECK(REGEXP_LIKE(c1,'^[[:alpha:]]+$')));

Identify SSN

CREATETABLEssn_test(
ssn_colVARCHAR2(20));

Thanks: Byron Bush


HIOUG

INSERTINTOssn_testVALUES('111223333');
INSERTINTOssn_testVALUES('111=223333');
INSERTINTOssn_testVALUES('111A23333');
INSERTINTOssn_testVALUES('1112233339');
INSERTINTOssn_testVALUES('111223333');
INSERTINTOssn_testVALUES('987654321');
COMMIT;
SELECTssn_col
fromssn_test
WHEREREGEXP_LIKE(ssn_col,'^[09]{3}[09]{2}[09]{4}$');

REGEXP_REPLACE
Syntax

REGEXP_REPLACE(<source_string>,<pattern>,
<replace_string>,<position>,<occurrence>,<match_parameter>)
coltestcolformata15
colresultformata15

Looks for the pattern


xxx.xxx.xxxx and
reformats pattern to
(xxx) xxx-xxxx

SELECTtestcol,REGEXP_REPLACE(testcol,
'([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',
'(\1)\2\3')RESULT
FROMtest
WHERELENGTH(testcol)=12;
SELECTtestcol,REGEXP_REPLACE(testcol,'(.)','\1')RESULT

Put a space after every


FROMtest
character

WHEREtestcollike'S%';

Replace multiple
spaces with a single
space

SELECTREGEXP_REPLACE('500OracleParkway,Redwood
Shores,CA','(){2,}','')RESULT
FROMDUAL;

Insert a space between


a lower case character
followed by an upper
case character

SELECTREGEXP_REPLACE('GeorgeMcGovern','([[:lower:]])
([[:upper:]])','\1\2')CITY
FROMDUAL;
(Produces 'George Mc Govern')

Replace the period with SELECTREGEXP_REPLACE('Wearetryingtomakethesubject


a string (note use of '\') easier.','\.','foryou.')REGEXT_SAMPLE

FROMDUAL;
Demo

CREATETABLEt(
testcolVARCHAR2(10));
INSERTINTOtVALUES('1');
INSERTINTOtVALUES('2');
INSERTINTOtVALUES('3new');
colnewvalformata10
SELECTLENGTH(testcol)len,testcolorigval,
REGEXP_REPLACE(testcol,'\W+$','')newval,
LENGTH(REGEXP_REPLACE(testcol,'\W+$',''))newlen
FROMt;

Code snippet courtesy SELECTREGEXP_REPLACE('ABBBCABBCCCAABAAAAA','(A|B|C)\1+','\1')


of Valentin Matak.
FROMDUAL;
This is a handy way to
remove duplicate
characters from a string.
This example shows the
1+ repeatability qualifier
in use.
Code snippet courtesy
of Jonathan Linder.
This checks for a valid
email address and then
extracts the domain
name.

SELECTREGEXP_REPLACE('[email protected]','^(\S+)@(\S+)','\2')
FROMDUALd
WHERE
REGEXP_LIKE('[email protected]','^[AZaz09._%+]+@([AZa
z09]+.)?+[AZaz]{2,63}$')

REGEXP_SUBSTR

Syntax

REGEXP_SUBSTR(source_string,pattern
[,position[,occurrence
[,match_parameter]]])

Searches for a comma


followed by one or more SELECTREGEXP_SUBSTR('500OracleParkway,RedwoodShores,CA',
',[^,]+,')RESULT
occurrences of noncomma characters
FROMDUAL;
followed by a comma
Look for http:// followed colresultformata50
by a substring of one or
more alphanumeric
SELECTREGEXP_SUBSTR('Gotohttp://www.oracle.com/productsand

characters and
optionally, a period (.)

clickondatabase',
'http://([[:alnum:]]+\.?){3,4}/?')RESULT
FROMDUAL;
SELECTREGEXP_SUBSTR('Wearetryingtomakethesubject

Extracts try, trying, tried


easier.','tr(y(ing)?|(ied)|(ies))')
or tries

FROMDUAL;

SELECTREGEXP_SUBSTR('system/pwd@orabase:1521:sidval',

Extract the 3rd field


'[^:]+',1,3)RESULT
treating ':' as a delimiter

FROMDUAL;

CREATETABLEregexp(

Extract from string with testcolVARCHAR2(50));


vertical bar delimiter

INSERTINTOregexp
(testcol)
VALUES
('One|Two|Three|Four|Five');
SELECT*FROMregexp;
SELECTREGEXP_SUBSTR(testcol,'[^|]+',1,3)
FROMregexp;

Equivalence classes

Parsing Demo

SELECTREGEXP_SUBSTR('iSelfSchoolingNOTISelfSchooling',
'[[=i=]]SelfSchooling')RESULT
FROMDUAL;
setserveroutputon
DECLARE
xVARCHAR2(2);
yVARCHAR2(2);
cVARCHAR2(40):='1:3,4:6,8:10,3:4,7:6,11:12';
BEGIN
x:=REGEXP_SUBSTR(c,'[^:]+',1,1);
y:=REGEXP_SUBSTR(c,'[^,]+',3,1);
dbms_output.put_line(x||''||y);
END;
/

Gary Whitaker wrote in with an addition to this parsing demo, and had the
following comments:

The parsing demo above uses the regular expression '[^,]+' which does not work when
there is a NULL element in the list. This could result in returning the wrong element's

data. Consider this simple example with comments:


set serveroutput on
DECLARE
x VARCHAR2(1);
y VARCHAR2(1);
z VARCHAR2(1);
c VARCHAR2(40) := '1,2,,4,5,6,7';
BEGIN
-- Works as expected if the value you seek is before any null value in the list:
x := REGEXP_SUBSTR(c, '[^,]+', 1, 2);
-- This form only returns the 4th element when all elements are present.
-- It will return the 4th non-null element, which in this example is really '5',
-- which could be misleading.
-- if you are really after the 4th element regardless if there is a null element:
y := REGEXP_SUBSTR(c, '[^,]+', 1, 4);
-- This form gets the actual 4th element, allowing for the null element.
-- Get the 1st substring of the 4th instance of a set of characters that are not a comma,
-- when followed by a comma or the end of the line:
z := REGEXP_SUBSTR(c, '([^,]*)(,|$)', 1, 4, NULL, 1);
dbms_output.put_line(x);
dbms_output.put_line(y);
dbms_output.put_line(z);
END;
/

You might also like