Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Operators,Functions,Expressions,Conditions
Oracle8SQLReference
Release8.0
A5822501
3
Operators,Functions,Expressions,
Conditions
Thischapterdescribesmethodsofmanipulatingindividualdataitems.Standardarithmeticoperatorssuchas
additionandsubtractionarediscussed,aswellaslesscommonfunctionssuchasabsolutevalueandstring
length.Topicsinclude:
Operators
SQLFunctions
UserFunctions
FormatModels
Expressions
Conditions
Note:
Functions,expressions,anddescriptionsprecededby areavailableonlyifthe
Oracleobjectsoptionisinstalledonyourdatabaseserver.
Operators
Anoperatormanipulatesindividualdataitemsandreturnsaresult.Thedataitemsarecalledoperandsor
arguments.Operatorsarerepresentedbyspecialcharactersorbykeywords.Forexample,themultiplication
operatorisrepresentedbyanasterisk(*)andtheoperatorthattestsfornullsisrepresentedbythekeywords
ISNULL.TablesinthissectionlistSQLoperators.
UnaryandBinaryOperators
Therearetwogeneralclassesofoperators:
unary
binary
Aunaryoperatoroperatesononlyoneoperand.Aunaryoperatortypicallyappearswithitsoperand
inthisformat:
operatoroperand
Abinaryoperatoroperatesontwooperands.Abinaryoperatorappearswithitsoperandsinthis
format:
operand1operatoroperand2
Otheroperatorswithspecialformatsacceptmorethantwooperands.Ifanoperatorisgivenanulloperand,
theresultisalwaysnull.Theonlyoperatorthatdoesnotfollowthisruleisconcatenation(||).
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
1/73
1/1/2017
Operators,Functions,Expressions,Conditions
Precedence
PrecedenceistheorderinwhichOracleevaluatesdifferentoperatorsinthesameexpression.When
evaluatinganexpressioncontainingmultipleoperators,Oracleevaluatesoperatorswithhigherprecedence
beforeevaluatingthosewithlowerprecedence.Oracleevaluatesoperatorswithequalprecedencefromleftto
rightwithinanexpression.
Table31liststhelevelsofprecedenceamongSQLoperatorsfromhightolow.Operatorslistedonthesame
linehavethesameprecedence.
Table31SQLOperatorPrecedence
Operator
Operation
+,
identity,negation
*,/
multiplication,division
+,,||
addition,subtraction,concatenation
=,!=,<,>,<=,>=,ISNULL,LIKE,BETWEEN,IN
comparison
NOT
exponentiation,logicalnegation
AND
conjunction
OR
disjunction
Example
Inthefollowingexpressionmultiplicationhasahigherprecedencethanaddition,soOraclefirstmultiplies2
by3andthenaddstheresultto1.
1+2*3
Youcanuseparenthesesinanexpressiontooverrideoperatorprecedence.Oracleevaluatesexpressions
insideparenthesesbeforeevaluatingthoseoutside.
SQLalsosupportssetoperators(UNION,UNIONALL,INTERSECT,andMINUS),whichcombinesetsof
rowsreturnedbyqueries,ratherthanindividualdataitems.Allsetoperatorshaveequalprecedence.
ArithmeticOperators
Youcanuseanarithmeticoperatorinanexpressiontonegate,add,subtract,multiply,anddividenumeric
values.Theresultoftheoperationisalsoanumericvalue.Someoftheseoperatorsarealsousedindate
arithmetic.Table32listsarithmeticoperators.
Table32ArithmeticOperators
Operator
Purpose
+
Denotesapositiveornegativeexpression.Theseareunary
operators.
Example
SELECT*FROMorders
WHEREqtysold=1;
SELECT*FROMemp
WHEREsal<0;
*/
Multiplies,divides.Thesearebinaryoperators.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
UPDATEemp
SETsal=sal*1.1;
2/73
1/1/2017
Operators,Functions,Expressions,Conditions
Adds,subtracts.Thesearebinaryoperators.
SELECTsal+commFROMemp
WHERESYSDATEhiredate
>365;
Donotusetwoconsecutiveminussignswithnoseparation()inarithmeticexpressionstoindicatedouble
negationorthesubtractionofanegativevalue.ThecharactersareusedtobegincommentswithinSQL
statements.Youshouldseparateconsecutiveminussignswithaspaceoraparenthesis.Formoreinformation
oncommentswithinSQLstatements,see"Comments".
ConcatenationOperator
Theconcatenationoperatormanipulatescharacterstrings.Table33describestheconcatenationoperator.
Table33ConcatenationOperator
Operator
Purpose
Example
||
Concatenatescharacterstrings.
SELECT'Nameis'||ename
FROMemp;
Theresultofconcatenatingtwocharacterstringsisanothercharacterstring.Ifbothcharacterstringsareof
datatypeCHAR,theresulthasdatatypeCHARandislimitedto2000characters.Ifeitherstringisof
datatypeVARCHAR2,theresulthasdatatypeVARCHAR2andislimitedto4000characters.Trailingblanks
incharacterstringsarepreservedbyconcatenation,regardlessofthestrings'datatypes.Formoreinformation
onthedifferencesbetweentheCHARandVARCHAR2datatypes,see"CharacterDatatypes".
Onmostplatforms,theconcatenationoperatoristwosolidverticalbars,asshowninTable33.However,
someIBMplatformsusebrokenverticalbarsforthisoperator.WhenmovingSQLscriptfilesbetween
systemshavingdifferentcharactersets,suchasbetweenASCIIandEBCDIC,verticalbarsmightnotbe
translatedintotheverticalbarrequiredbythetargetOracleenvironment.OracleprovidestheCONCAT
characterfunctionasanalternativetotheverticalbaroperatorforcaseswhenitisdifficultorimpossibleto
controltranslationperformedbyoperatingsystemornetworkutilities.Usethisfunctioninapplicationsthat
willbemovedbetweenenvironmentswithdifferingcharactersets.
AlthoughOracletreatszerolengthcharacterstringsasnulls,concatenatingazerolengthcharacterstring
withanotheroperandalwaysresultsintheotheroperand,sonullcanresultonlyfromtheconcatenationof
twonullstrings.However,thismaynotcontinuetobetrueinfutureversionsofOracle.Toconcatenatean
expressionthatmightbenull,usetheNVLfunctiontoexplicitlyconverttheexpressiontoazerolength
string.
Example
ThisexamplecreatesatablewithbothCHARandVARCHAR2columns,insertsvaluesbothwithand
withouttrailingblanks,andthenselectsthesevalues,concatenatingthem.NotethatforbothCHARand
VARCHAR2columns,thetrailingblanksarepreserved.
CREATETABLEtab1(col1VARCHAR2(6),col2CHAR(6),
col3VARCHAR2(6),col4CHAR(6));
Tablecreated.
INSERTINTOtab1(col1,col2,col3,col4)
VALUES('abc','def','ghi','jkl');
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
3/73
1/1/2017
Operators,Functions,Expressions,Conditions
1rowcreated.
SELECTcol1||col2||col3||col4"Concatenation"
FROMtab1;
Concatenation
abcdefghijkl
ComparisonOperators
Comparisonoperatorscompareoneexpressionwithanother.TheresultofsuchacomparisoncanbeTRUE,
FALSE,orUNKNOWN.Forinformationonconditions,see"Conditions".Table34listscomparison
operators.
Table34ComparisonOperators
Operator
Purpose
=
Equalitytest.
Example
SELECT*
FROMemp
WHEREsal=1500;
!=
^=
<>
=
Inequalitytest.Someformsoftheinequalityoperatormaybe
unavailableonsomeplatforms.
>
"Greaterthan"and"lessthan"tests.
<
>=
SELECT*FROMemp
WHEREsal>1500;
SELECT*FROMemp
WHEREsal<1500;
"Greaterthanorequalto"and"lessthanorequalto"tests.
<=
IN
SELECT*
FROMemp
WHEREsal!=1500;
SELECT*FROMemp
WHEREsal>=1500;
SELECT*FROMemp
WHEREsal<=1500;
"Equaltoanymemberof"test.Equivalentto"=ANY".
SELECT*FROMemp
WHEREjobIN
('CLERK','ANALYST');
SELECT*FROMemp
WHEREsalIN
(SELECTsalFROMemp
WHEREdeptno=30);
NOTIN
Equivalentto"!=ALL".EvaluatestoFALSEifanymemberofthe
setisNULL.
SELECT*FROMemp
WHEREsalNOTIN
(SELECTsalFROMemp
WHEREdeptno=30);
SELECT*FROMemp
WHEREjobNOTIN
('CLERK',ANALYST');
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
4/73
1/1/2017
ANY
SOME
Operators,Functions,Expressions,Conditions
Comparesavaluetoeachvalueinalistorreturnedbyaquery.
Mustbeprecededby=,!=,>,<,<=,>=.
EvaluatestoFALSEifthequeryreturnsnorows.
SELECT*FROMemp
WHEREsal=ANY
(SELECTsalFROMemp
WHEREdeptno=30);
ALL
[NOT]
BETWEEN
xANDy
Comparesavaluetoeveryvalueinalistorreturnedbyaquery.
Mustbeprecededby=,!=,>,<,<=,>=.
SELECT*FROMemp
WHEREsal>=
ALL(1400,3000);
EvaluatestoTRUEifthequeryreturnsnorows.
[Not]greaterthanorequaltoxandlessthanorequaltoy.
SELECT*FROMemp
WHEREsal
BETWEEN2000AND3000;
EXISTS
TRUEifasubqueryreturnsatleastonerow.
SELECTename,deptno
FROMdept
WHEREEXISTS
(SELECT*FROMemp
WHEREdept.deptno
=emp.deptno);
TRUEifxdoes[not]matchthepatterny.Withiny,thecharacter
"%"matchesanystringofzeroormorecharactersexceptnull.The
character"_"matchesanysinglecharacter.Anycharacter,
[ESCAPE
exceptingpercent(%)andunderbar(_)mayfollowESCAPEa
'z']
wildcardcharacteristreatedasaliteralifprecededbythecharacter
designatedastheescapecharacter.
x[NOT]
LIKEy
IS
[NOT]
NULL
Testsfornulls.Thisistheonlyoperatorthatyoushouldusetotest
fornulls.See"Nulls".
See"LIKEOperator".
SELECT*FROMtab1
WHEREcol1LIKE
'A_C/%E%'ESCAPE'/';
SELECTename,deptno
FROMemp
WHEREcommISNULL;
AdditionalinformationontheNOTINandLIKEoperatorsappearsinthesectionsthatfollow.
NOTINOperator
IfanyiteminthelistfollowingaNOTINoperationisnull,allrowsevaluatetoUNKNOWN(andnorows
arereturned).Forexample,thefollowingstatementreturnsthestring'TRUE'foreachrow:
SELECT'TRUE'
FROMemp
WHEREdeptnoNOTIN(5,15);
However,thefollowingstatementreturnsnorows:
SELECT'TRUE'
FROMemp
WHEREdeptnoNOTIN(5,15,null);
TheaboveexamplereturnsnorowsbecausetheWHEREclauseconditionevaluatesto:
deptno!=5ANDdeptno!=15ANDdeptno!=null
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
5/73
1/1/2017
Operators,Functions,Expressions,Conditions
Becauseallconditionsthatcompareanullresultinanull,theentireexpressionresultsinanull.This
behaviorcaneasilybeoverlooked,especiallywhentheNOTINoperatorreferencesasubquery.
LIKEOperator
TheLIKEoperatorisusedincharacterstringcomparisonswithpatternmatching.Thesyntaxforacondition
usingtheLIKEoperatorisshowninthisdiagram:
where:
char1
NOT
isavaluetobecomparedwithapattern.ThisvaluecanhavedatatypeCHARorVARCHAR2.
logicallyinvertstheresultofthecondition,returningFALSEiftheconditionevaluatestoTRUE
andTRUEifitevaluatestoFALSE.
char2 isthepatterntowhichchar1iscompared.ThepatternisavalueofdatatypeCHARor
VARCHAR2andcancontainthespecialpatternmatchingcharacters%and_.
ESCAPE identifiesasinglecharacterastheescapecharacter.Theescapecharactercanbeusedtocause
Oracletointerpret%or_literally,ratherthanasaspecialcharacter,inthepattern.
Ifyouwishtosearchforstringscontaininganescapecharacter,youmustspecifythischaracter
twice.Forexample,iftheescapecharacteris'/',tosearchforthestring'client/server',youmust
specify,'client//server'.
Whiletheequal(=)operatorexactlymatchesonecharactervaluetoanother,theLIKEoperatormatchesa
portionofonecharactervaluetoanotherbysearchingthefirstvalueforthepatternspecifiedbythesecond.
NotethatblankpaddingisnotusedforLIKEcomparisons.
WiththeLIKEoperator,youcancompareavaluetoapatternratherthantoaconstant.Thepatterncanonly
appearaftertheLIKEkeyword.Forexample,youcanissuethefollowingquerytofindthesalariesofall
employeeswithnamesbeginningwith'SM':
SELECTsal
FROMemp
WHEREenameLIKE'SM%';
Thefollowingqueryusesthe=operator,ratherthantheLIKEoperator,tofindthesalariesofallemployees
withthename'SM%':
SELECTsal
FROMemp
WHEREename='SM%';
Thefollowingqueryfindsthesalariesofallemployeeswiththename'SM%'.Oracleinterprets'SM%'asa
textliteral,ratherthanasapattern,becauseitprecedestheLIKEoperator:
SELECTsal
FROMemp
WHERE'SM%'LIKEename;
PatternsusuallyusespecialcharactersthatOraclematcheswithdifferentcharactersinthevalue:
Anunderscore(_)inthepatternmatchesexactlyonecharacter(asopposedtoonebyteinamultibyte
characterset)inthevalue.
Apercentsign(%)inthepatterncanmatchzeroormorecharacters(asopposedtobytesinamultibyte
characterset)inthevalue.Notethatthepattern'%'cannotmatchanull.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
6/73
1/1/2017
Operators,Functions,Expressions,Conditions
CaseSensitivityandPatternMatching
CaseissignificantinallconditionscomparingcharacterexpressionsincludingtheLIKEandequality(=)
operators.YoucanusetheUPPER()functiontoperformacaseinsensitivematch,asinthiscondition:
UPPER(ename)LIKE'SM%'
PatternMatchingonIndexedColumns
WhenLIKEisusedtosearchanindexedcolumnforapattern,Oraclecanusetheindextoimprovethe
statement'sperformanceiftheleadingcharacterinthepatternisnot"%"or"_".Inthiscase,Oraclecanscan
theindexbythisleadingcharacter.Ifthefirstcharacterinthepatternis"%"or"_",theindexcannotimprove
thequery'sperformancebecauseOraclecannotscantheindex.
Example1
ThisconditionistrueforallENAMEvaluesbeginningwith"MA":
enameLIKE'MA%'
AlloftheseENAMEvaluesmaketheconditionTRUE:
MARTIN,MA,MARK,MARY
Caseissignificant,soENAMEvaluesbeginningwith"Ma,""ma,"and"mA"maketheconditionFALSE.
Example2
Considerthiscondition:
enameLIKE'SMITH_'
ThisconditionistruefortheseENAMEvalues:
SMITHE,SMITHY,SMITHS
Thisconditionisfalsefor'SMITH',sincethespecialcharacter"_"mustmatchexactlyonecharacterofthe
ENAMEvalue.
ESCAPEOption
Youcanincludetheactualcharacters"%"or"_"inthepatternbyusingtheESCAPEoption.TheESCAPE
optionidentifiestheescapecharacter.Iftheescapecharacterappearsinthepatternbeforethecharacter"%"
or"_"thenOracleinterpretsthischaracterliterallyinthepattern,ratherthanasaspecialpatternmatching
character.
Example:
Tosearchforanyemployeeswiththepattern'A_B'intheirname:
SELECTename
FROMemp
WHEREenameLIKE'%A\_B%'ESCAPE'\';
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
7/73
1/1/2017
Operators,Functions,Expressions,Conditions
TheESCAPEoptionidentifiesthebackslash(\)astheescapecharacter.Inthepattern,theescapecharacter
precedestheunderscore(_).ThiscausesOracletointerprettheunderscoreliterally,ratherthanasaspecial
patternmatchingcharacter.
PatternsWithout%
Ifapatterndoesnotcontainthe"%"character,theconditioncanbeTRUEonlyifbothoperandshavethe
samelength.
Example:
Considerthedefinitionofthistableandthevaluesinsertedintoit:
CREATETABLEfreds(fCHAR(6),vVARCHAR2(6));
INSERTINTOfredsVALUES('FRED','FRED');
BecauseOracleblankpadsCHARvalues,thevalueofFisblankpaddedto6bytes.Visnotblankpadded
andhaslength4.
LogicalOperators
Alogicaloperatorcombinestheresultsoftwocomponentconditionstoproduceasingleresultbasedon
themortoinverttheresultofasinglecondition.Table35listslogicaloperators.
Table35LogicalOperators
Operator
Function
NOT
ReturnsTRUEifthefollowingconditionisFALSE.Returns
FALSEifitisTRUE.IfitisUNKNOWN,itremains
UNKNOWN.
Example
SELECT*
FROMemp
WHERENOT(jobISNULL);
SELECT*
FROMemp
WHERENOT
(salBETWEEN1000AND2000);
AND
ReturnsTRUEifbothcomponentconditionsareTRUE.
ReturnsFALSEifeitherisFALSE.Otherwisereturns
UNKNOWN.
SELECT*
FROMemp
WHEREjob='CLERK'
ANDdeptno=10;
OR
ReturnsTRUEifeithercomponentconditionisTRUE.
ReturnsFALSEifbothareFALSE.Otherwisereturns
UNKNOWN.
SELECT*
FROMemp
WHEREjob='CLERK'
ORdeptno=10;
Forexample,intheWHEREclauseofthefollowingSELECTstatement,theANDlogicaloperatorisusedto
ensurethatonlythosehiredbefore1984andearningmorethan$1000amontharereturned:
SELECT*
FROMemp
WHEREhiredate<TO_DATE('01JAN1984','DDMONYYYY')
ANDsal>1000;
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
8/73
1/1/2017
Operators,Functions,Expressions,Conditions
NOTOperator
Table36showstheresultofapplyingtheNOToperatortoacondition.
Table36NOTTruthTable
NOT
TRUE
FALSE
UNKNOWN
FALSE
TRUE
UNKNOWN
ANDOperator
Table37showstheresultsofcombiningtwoexpressionswithAND.
Table37ANDTruthTable
AND
TRUE
FALSE
UNKNOWN
TRUE
TRUE
FALSE
UNKNOWN
FALSE
FALSE
FALSE
FALSE
UNKNOWN
UNKNOWN
FALSE
UNKNOWN
OROperator
Table38showstheresultsofcombiningtwoexpressionswithOR.
Table38ORTruthTable
OR
TRUE
FALSE
UNKNOWN
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
UNKNOWN
UNKNOWN
TRUE
UNKNOWN
UNKNOWN
SetOperators
Setoperatorscombinetheresultsoftwocomponentqueriesintoasingleresult.Queriescontainingset
operatorsarecalledcompoundqueries.Table39listsSQLsetoperators.
Table39SetOperators
Operator
Returns
UNION
Allrowsselectedbyeitherquery.
UNIONALL
Allrowsselectedbyeitherquery,includingallduplicates.
INTERSECT
Alldistinctrowsselectedbybothqueries.
MINUS
Alldistinctrowsselectedbythefirstquerybutnotthesecond.
Allsetoperatorshaveequalprecedence.IfaSQLstatementcontainsmultiplesetoperators,Oracleevaluates
themfromthelefttorightifnoparenthesesexplicitlyspecifyanotherorder.TocomplywithemergingSQL
standards,afuturereleaseofOraclewillgivetheINTERSECToperatorgreaterprecedencethantheotherset
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
9/73
1/1/2017
Operators,Functions,Expressions,Conditions
operators.Therefore,youshoulduseparenthesestospecifyorderofevaluationinqueriesthatusethe
INTERSECToperatorwithothersetoperators.
Thecorrespondingexpressionsintheselectlistsofthecomponentqueriesofacompoundquerymustmatch
innumberanddatatype.Ifcomponentqueriesselectcharacterdata,thedatatypeofthereturnvaluesare
determinedasfollows:
IfbothqueriesselectvaluesofdatatypeCHAR,thereturnedvalueshavedatatypeCHAR.
IfeitherorbothofthequeriesselectvaluesofdatatypeVARCHAR2,thereturnedvalueshave
datatypeVARCHAR2.
Examples
Considerthesetwoqueriesandtheirresults:
SELECTpart
FROMorders_list1;
PART
SPARKPLUG
FUELPUMP
FUELPUMP
TAILPIPE
SELECTpart
FROMorders_list2;
PART
CRANKSHAFT
TAILPIPE
TAILPIPE
Thefollowingexamplescombinethetwoqueryresultswitheachofthesetoperators.
UNIONExample
ThefollowingstatementcombinestheresultswiththeUNIONoperator,whicheliminatesduplicateselected
rows.Thisstatementshowshowdatatypemustmatchwhencolumnsdonotexistinoneortheothertable:
SELECTpart,partnum,to_date(null)date_in
FROMorders_list1
UNION
SELECTpart,to_null(null),date_in
FROMorders_list2;
PARTPARTNUMDATE_IN
SPARKPLUG3323165
SPARKPLUG10/24/98
FUELPUMP3323162
FUELPUMP12/24/99
TAILPIPE1332999
TAILPIPE01/01/01
CRANKSHAFT9394991
CRANKSHAFT09/12/02
SELECTpart
FROMorders_list1
UNION
SELECTpart
FROMorders_list2;
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
10/73
1/1/2017
Operators,Functions,Expressions,Conditions
PART
SPARKPLUG
FUELPUMP
TAILPIPE
CRANKSHAFT
UNIONALLExample
ThefollowingstatementcombinestheresultswiththeUNIONALLoperator,whichdoesnoteliminate
duplicateselectedrows:
SELECTpart
FROMorders_list1
UNIONALL
SELECTpart
FROMorders_list2;
PART
SPARKPLUG
FUELPUMP
FUELPUMP
TAILPIPE
CRANKSHAFT
TAILPIPE
TAILPIPE
NotethattheUNIONoperatorreturnsonlydistinctrowsthatappearineitherresult,whiletheUNIONALL
operatorreturnsallrows.APARTvaluethatappearsmultipletimesineitherorbothqueries(suchas'FUEL
PUMP')isreturnedonlyoncebytheUNIONoperator,butmultipletimesbytheUNIONALLoperator.
INTERSECTExample
ThefollowingstatementcombinestheresultswiththeINTERSECToperatorwhichreturnsonlythoserows
returnedbybothqueries:
SELECTpart
FROMorders_list1
INTERSECT
SELECTpart
FROMorders_list2;
PART
TAILPIPE
MINUSExample
ThefollowingstatementcombinesresultswiththeMINUSoperator,whichreturnsonlyrowsreturnedbythe
firstquerybutnotbythesecond:
SELECTpart
FROMorders_list1
MINUS
SELECTpart
FROMorders_list2;
PART
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
11/73
1/1/2017
Operators,Functions,Expressions,Conditions
SPARKPLUG
FUELPUMP
OtherOperators
Table310listsotherSQLoperators.
Table310OtherSQLOperators
Operator
Purpose
(+)
Indicatesthattheprecedingcolumnistheouterjoincolumnina
join.See"OuterJoins".
Example
SELECTename,dname
FROMemp,dept
WHEREdept.deptno=
emp.deptno(+);
PRIOR
Evaluatesthefollowingexpressionfortheparentrowofthecurrent
rowinahierarchical,ortreestructured,query.Insuchaquery,you
mustusethisoperatorintheCONNECTBYclausetodefinethe
relationshipbetweenparentandchildrows.Youcanalsousethis
operatorinotherpartsofaSELECTstatementthatperformsa
hierarchicalquery.ThePRIORoperatorisaunaryoperatorandhas
thesameprecedenceastheunary+andarithmeticoperators.See
"HierarchicalQueries".
SELECTempno,ename,mgr
FROMemp
CONNECTBY
PRIORempno=mgr;
SQLFunctions
ASQLfunctionissimilartoanoperatorinthatitmanipulatesdataitemsandreturnsaresult.SQLfunctions
differfromoperatorsintheformatinwhichtheyappearwiththeirarguments.Thisformatallowsthemto
operateonzero,one,two,ormorearguments:
function(argument,argument,...)
IfyoucallaSQLfunctionwithanargumentofadatatypeotherthanthedatatypeexpectedbytheSQL
function,OracleimplicitlyconvertstheargumenttotheexpecteddatatypebeforeperformingtheSQL
function.See"DataConversion".
IfyoucallaSQLfunctionwithanullargument,theSQLfunctionautomaticallyreturnsnull.TheonlySQL
functionsthatdonotfollowthisruleareCONCAT,DECODE,DUMP,NVL,andREPLACE.
SQLfunctionsshouldnotbeconfusedwithuserfunctionswritteninPL/SQL.Userfunctionsaredescribed
in"UserFunctions".
InthesyntaxdiagramsforSQLfunctions,argumentsareindicatedwiththeirdatatypesfollowingthe
conventionsdescribedin"SyntaxDiagramsandNotation"inthePrefaceofthisreference.
SQLfunctionsareofthesegeneraltypes:
singlerow(orscalar)functions
group(oraggregate)functions
ThetwotypesofSQLfunctionsdifferinthenumberofrowsuponwhichtheyact.Asinglerowfunction
returnsasingleresultrowforeveryrowofaqueriedtableorviewagroupfunctionreturnsasingleresult
rowforagroupofqueriedrows.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
12/73
1/1/2017
Operators,Functions,Expressions,Conditions
Singlerowfunctionscanappearinselectlists(iftheSELECTstatementdoesnotcontainaGROUPBY
clause),WHEREclauses,STARTWITHclauses,andCONNECTBYclauses.
GroupfunctionscanappearinselectlistsandHAVINGclauses.IfyouusetheGROUPBYclauseina
SELECTstatement,Oracledividestherowsofaqueriedtableorviewintogroups.Inaquerycontaininga
GROUPBYclause,allelementsoftheselectlistmustbeexpressionsfromtheGROUPBYclause,
expressionscontaininggroupfunctions,orconstants.Oracleappliesthegroupfunctionsintheselectlistto
eachgroupofrowsandreturnsasingleresultrowforeachgroup.
IfyouomittheGROUPBYclause,Oracleappliesgroupfunctionsintheselectlisttoalltherowsinthe
queriedtableorview.YouusegroupfunctionsintheHAVINGclausetoeliminategroupsfromtheoutput
basedontheresultsofthegroupfunctions,ratherthanonthevaluesoftheindividualrowsofthequeried
tableorview.FormoreinformationontheGROUPBYandHAVINGclauses,seetheGROUPBYClause
andtheHAVINGClause.
Inthesectionsthatfollow,functionsaregroupedbythedatatypesoftheirargumentsandreturnvalues.
NumberFunctions
Numberfunctionsacceptnumericinputandreturnnumericvalues.ThissectionliststheSQLnumber
functions.Mostofthesefunctionsreturnvaluesthatareaccurateto38decimaldigits.Thetranscendental
functionsCOS,COSH,EXP,LN,LOG,SIN,SINH,SQRT,TAN,andTANHareaccurateto36decimal
digits.ThetranscendentalfunctionsACOS,ASIN,ATAN,andATAN2areaccurateto30decimaldigits.
ABS
Purpose
Returnstheabsolutevalueofn.
Example
SELECTABS(15)"Absolute"FROMDUAL;
Absolute
15
ACOS
Purpose
Returnsthearccosineofn.Inputsareintherangeof1to1,andoutputsareintherangeof
0to andareexpressedinradians.
Example SELECTACOS(.3)"Arc_Cosine"FROMDUAL;
Arc_Cosine
1.26610367
ASIN
Purpose
Returnsthearcsineofn.Inputsareintherangeof1to1,andoutputsareintherangeof
/2to /2andareexpressedinradians.
Example SELECTASIN(.3)"Arc_Sine"FROMDUAL;
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
13/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example SELECTASIN(.3)"Arc_Sine"FROMDUAL;
Arc_Sine
.304692654
ATAN
Purpose
Returnsthearctangentofn.Inputsareinanunboundedrange,andoutputsareintherange
of /2to /2andareexpressedinradians.
Example SELECTATAN(.3)"Arc_Tangent"FROMDUAL;
Arc_Tangent
.291456794
ATAN2
Purpose
Returnsthearctangentofnandm.Inputsareinanunboundedrange,andoutputsareinthe
rangeof to ,dependingonthesignsofnandm,andareexpressedinradians.
Atan2(n,m)isthesameasatan2(n/m)
Example SELECTATAN2(.3,.2)"Arc_Tangent2"FROMDUAL;
Arc_Tangent2
.982793723
CEIL
Purpose
Returnssmallestintegergreaterthanorequalton.
Example
SELECTCEIL(15.7)"Ceiling"FROMDUAL;
Ceiling
16
COS
Purpose
Returnsthecosineofn(anangleexpressedinradians).
Example
SELECTCOS(180*3.14159265359/180)
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
14/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example
SELECTCOS(180*3.14159265359/180)
"Cosineof180degrees"FROMDUAL;
Cosineof180degrees
COSH
Purpose
Returnsthehyperboliccosineofn.
Example
SELECTCOSH(0)"Hyperboliccosineof0"FROMDUAL;
Hyperboliccosineof0
EXP
Purpose
Returnseraisedtothenthpowere=2.71828183...
Example
SELECTEXP(4)"etothe4thpower"FROMDUAL;
etothe4thpower
54.59815
FLOOR
Purpose
Returnslargestintegerequaltoorlessthann.
Example
SELECTFLOOR(15.7)"Floor"FROMDUAL;
Floor
15
LN
Purpose
Returnsthenaturallogarithmofn,wherenisgreaterthan0.
Example
SELECTLN(95)"Naturallogof95"FROMDUAL;
Naturallogof95
4.55387689
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
15/73
1/1/2017
Operators,Functions,Expressions,Conditions
LOG
Purpose
Returnsthelogarithm,basem,ofn.Thebasemcanbeanypositivenumberotherthan0or
1andncanbeanypositivenumber.
Example SELECTLOG(10,100)"Logbase10of100"FROMDUAL;
Logbase10of100
MOD
Syntax MOD(m,n)
Purpose
Returnsremainderofmdividedbyn.Returnsmifnis0.
Example SELECTMOD(11,4)"Modulus"FROMDUAL;
Modulus
Thisfunctionbehavesdifferentlyfromtheclassicalmathematicalmodulusfunctionwhenm
isnegative.TheclassicalmoduluscanbeexpressedusingtheMODfunctionwiththis
formula:
mn*FLOOR(m/n)
ThefollowingstatementillustratesthedifferencebetweentheMODfunctionandthe
classicalmodulus:
SELECTm,n,MOD(m,n),
mn*FLOOR(m/n)"ClassicalModulus"
FROMtest_mod_table;
MNMOD(M,N)ClassicalModulus
11433
11431
11431
11433
POWER
Purpose
Returnsmraisedtothenthpower.Thebasemandtheexponentncanbeanynumbers,but
ifmisnegative,nmustbeaninteger.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
16/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example SELECTPOWER(3,2)"Raised"FROMDUAL;
Raised
ROUND
Syntax
ROUND(n[,m])
Returnsnroundedtomplacesrightofthedecimalpointifmisomitted,to0places.mcan
benegativetoroundoffdigitsleftofthedecimalpoint.mmustbeaninteger.
Purpose
Example SELECTROUND(15.193,1)"Round"FROMDUAL;
1
Round
15.2
Example SELECTROUND(15.193,1)"Round"FROMDUAL;
2
Round
20
SIGN
Syntax
SIGN(n)
Purpose
Ifn<0,thefunctionreturns1ifn=0,thefunctionreturns0ifn>0,thefunctionreturns1.
Example SELECTSIGN(15)"Sign"FROMDUAL;
Sign
SIN
Purpose
Returnsthesineofn(anangleexpressedinradians).
Example
SELECTSIN(30*3.14159265359/180)
"Sineof30degrees"FROMDUAL;
Sineof30degrees
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
17/73
1/1/2017
Operators,Functions,Expressions,Conditions
.5
SINH
Purpose
Returnsthehyperbolicsineofn.
Example
SELECTSINH(1)"Hyperbolicsineof1"FROMDUAL;
Hyperbolicsineof1
1.17520119
SQRT
Purpose
Returnssquarerootofn.Thevaluencannotbenegative.SQRTreturnsa"real"result.
Example SELECTSQRT(26)"Squareroot"FROMDUAL;
Squareroot
5.09901951
TAN
Purpose
Returnsthetangentofn(anangleexpressedinradians).
Example
SELECTTAN(135*3.14159265359/180)
"Tangentof135degrees"FROMDUAL;
Tangentof135degrees
TANH
Purpose
Returnsthehyperbolictangentofn.
Example
SELECTTANH(.5)"Hyperbolictangentof.5"
FROMDUAL;
Hyperbolictangentof.5
.462117157
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
18/73
1/1/2017
Operators,Functions,Expressions,Conditions
TRUNC
Purpose
Returnsntruncatedtomdecimalplacesifmisomitted,to0places.mcanbenegativeto
truncate(makezero)mdigitsleftofthedecimalpoint.
Examples SELECTTRUNC(15.79,1)"Truncate"FROMDUAL;
Truncate
15.7
SELECTTRUNC(15.79,1)"Truncate"FROMDUAL;
Truncate
10
CharacterFunctions
Singlerowcharacterfunctionsacceptcharacterinputandcanreturneithercharacterornumbervalues.
CharacterFunctionsReturningCharacterValues
Thissectionlistscharacterfunctionsthatreturncharactervalues.Unlessotherwisenoted,thesefunctionsall
returnvalueswiththedatatypeVARCHAR2andarelimitedinlengthto4000bytes.Functionsthatreturn
valuesofdatatypeCHARarelimitedinlengthto2000bytes.Ifthelengthofthereturnvalueexceedsthe
limit,Oracletruncatesitandreturnstheresultwithoutanerrormessage.
CHR
Syntax CHR(n[USINGNCHAR_CS])
Purpose
Returnsthecharacterhavingthebinaryequivalenttonineitherthedatabasecharactersetor
thenationalcharacterset.
IftheUSINGNCHAR_CSclauseisnotspecified,thisfunctionreturnsthecharacterhaving
thebinaryequivalenttonasaVARCHAR2valueinthedatabasecharacterset.
IftheUSINGNCHAR_CSclauseisspecified,thisfunctionreturnsthecharacterhavingthe
binaryequivalenttonasaNVARCHAR2valueinthenationalcharacterset.
Example SELECTCHR(67)||CHR(65)||CHR(84)"Dog"
FROMDUAL;
1
Dog
CAT
Example SELECTCHR(16705USINGNCHAR_CS)FROMDUAL;
2
C
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
19/73
1/1/2017
Operators,Functions,Expressions,Conditions
CONCAT
Syntax CONCAT(char1,char2)
Purpose
Returnschar1concatenatedwithchar2.Thisfunctionisequivalenttotheconcatenation
operator(||).Forinformationonthisoperator,see"ConcatenationOperator".
Example
Thisexampleusesnestingtoconcatenatethreecharacterstrings:
SELECTCONCAT(CONCAT(ename,'isa'),job)"Job"
FROMemp
WHEREempno=7900;
Job
JAMESisaCLERK
INITCAP
Purpose
Returnschar,withthefirstletterofeachwordinuppercase,allotherlettersinlowercase.
Wordsaredelimitedbywhitespaceorcharactersthatarenotalphanumeric.
Example SELECTINITCAP('thesoap')"Capitals"FROMDUAL;
Capitals
TheSoap
LOWER
Purpose
Returnschar,withallletterslowercase.Thereturnvaluehasthesamedatatypeasthe
argumentchar(CHARorVARCHAR2).
Example SELECTLOWER('MR.SCOTTMCMILLAN')"Lowercase"
FROMDUAL;
Lowercase
mr.scottmcmillan
LPAD
Purpose
Returnschar1,leftpaddedtolengthnwiththesequenceofcharactersinchar2char2
defaultstoasingleblank.Ifchar1islongerthann,thisfunctionreturnstheportionofchar1
thatfitsinn.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
20/73
1/1/2017
Operators,Functions,Expressions,Conditions
Theargumentnisthetotallengthofthereturnvalueasitisdisplayedonyourterminal
screen.Inmostcharactersets,thisisalsothenumberofcharactersinthereturnvalue.
However,insomemultibytecharactersets,thedisplaylengthofacharacterstringcandiffer
fromthenumberofcharactersinthestring.
Example SELECTLPAD('Page1',15,'*.')"LPADexample"
FROMDUAL;
LPADexample
*.*.*.*.*Page1
LTRIM
Syntax LTRIM(char[,set])
Purpose
Removescharactersfromtheleftofchar,withalltheleftmostcharactersthatappearinset
removedsetdefaultstoasingleblank.Oraclebeginsscanningcharfromitsfirstcharacter
andremovesallcharactersthatappearinsetuntilreachingacharacternotinsetandthen
returnstheresult.
Example SELECTLTRIM('xyxXxyLASTWORD','xy')"LTRIMexample"
FROMDUAL;
LTRIMexampl
XxyLASTWORD
NLS_INITCAP
Purpose
Returnschar,withthefirstletterofeachwordinuppercase,allotherlettersinlowercase.
Wordsaredelimitedbywhitespaceorcharactersthatarenotalphanumeric.Thevalueof
'nlsparams'canhavethisform:
'NLS_SORT=sort'
wheresortiseitheralinguisticsortsequenceorBINARY.Thelinguisticsortsequence
handlesspeciallinguisticrequirementsforcaseconversions.Notethattheserequirements
canresultinareturnvalueofadifferentlengththanthechar.Ifyouomit'nlsparams',this
functionusesthedefaultsortsequenceforyoursession.Forinformationonsortsequences,
seeOracle8Reference.
Example SELECTNLS_INITCAP
('ijsland','NLS_SORT=XDutch')"Capitalized"
FROMDUAL;
Capital
IJsland
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
21/73
1/1/2017
Operators,Functions,Expressions,Conditions
NLS_LOWER
Syntax NLS_LOWER(char[,'nlsparams'])
Purpose
Returnschar,withallletterslowercase.The'nlsparams'canhavethesameformandserve
thesamepurposeasintheNLS_INITCAPfunction.
Example SELECTNLS_LOWER
('CITTA''','NLS_SORT=XGerman')"Lowercase"
FROMDUAL;
Lower
citt
NLS_UPPER
Syntax NLS_UPPER(char[,'nlsparams'])
Purpose
Returnschar,withalllettersuppercase.The'nlsparams'canhavethesameformandserve
thesamepurposeasintheNLS_INITCAPfunction.
Example SELECTNLS_UPPER
('gro e','NLS_SORT=XGerman')"Uppercase"
FROMDUAL;
Upper
GROSS
REPLACE
Syntax REPLACE(char,search_string[,replacement_string])
Purpose
Returnscharwitheveryoccurrenceofsearch_stringreplacedwithreplacement_string.If
replacement_stringisomittedornull,alloccurrencesofsearch_stringareremoved.If
search_stringisnull,charisreturned.Thisfunctionprovidesasupersetofthefunctionality
providedbytheTRANSLATEfunction.TRANSLATEprovidessinglecharacter,oneto
onesubstitution.REPLACEallowsyoutosubstituteonestringforanotheraswellasto
removecharacterstrings.
Example SELECTREPLACE('JACKandJUE','J','BL')"Changes"
FROMDUAL;
Changes
BLACKandBLUE
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
22/73
1/1/2017
Operators,Functions,Expressions,Conditions
RPAD
Syntax RPAD(char1,n[,char2])
Purpose
Returnschar1,rightpaddedtolengthnwithchar2,replicatedasmanytimesasnecessary
char2defaultstoasingleblank.Ifchar1islongerthann,thisfunctionreturnstheportionof
char1thatfitsinn.
Theargumentnisthetotallengthofthereturnvalueasitisdisplayedonyourterminal
screen.Inmostcharactersets,thisisalsothenumberofcharactersinthereturnvalue.
However,insomemultibytecharactersets,thedisplaylengthofacharacterstringcandiffer
fromthenumberofcharactersinthestring.
Example SELECTRPAD('MORRISON',12,'ab')"RPADexample"
FROMDUAL;
RPADexample
MORRISONabab
RTRIM
Syntax RTRIM(char[,set]
Purpose
Returnschar,withalltherightmostcharactersthatappearinsetremovedsetdefaultstoa
singleblank.RTRIMworkssimilarlytoLTRIM.
Example SELECTRTRIM('BROWNINGyxXxy','xy')"RTRIMe.g."
FROMDUAL;
RTRIMe.g
BROWNINGyxX
SOUNDEX
Syntax SOUNDEX(char)
Purpose
Returnsacharacterstringcontainingthephoneticrepresentationofchar.Thisfunction
allowsyoutocomparewordsthatarespelleddifferently,butsoundalikeinEnglish.
ThephoneticrepresentationisdefinedinTheArtofComputerProgramming,Volume3:
SortingandSearching,byDonaldE.Knuth,asfollows:
Retainthefirstletterofthestringandremoveallotheroccurrencesofthefollowingletters:
a,e,h,i,o,u,w,y.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
23/73
1/1/2017
Operators,Functions,Expressions,Conditions
Assignnumberstotheremainingletters(afterthefirst)asfollows:
b,f,p,v=1
c,g,j,k,q,s,x,z=2
d,t=3
l=4
m,n=5
r=6
Iftwoormoreletterswiththesameassignednumberareadjacent,removeallbutthefirst.
Returnthefirstfourbytespaddedwith0.
Example SELECTename
FROMemp
WHERESOUNDEX(ename)
=SOUNDEX('SMYTHE');
ENAME
SMITH
SUBSTR
Syntax SUBSTR(char,m[,n])
Purpose
Returnsaportionofchar,beginningatcharacterm,ncharacterslong.Ifmis0,itistreated
as1.Ifmispositive,Oraclecountsfromthebeginningofchartofindthefirstcharacter.If
misnegative,Oraclecountsbackwardsfromtheendofchar.Ifnisomitted,Oraclereturns
allcharacterstotheendofchar.Ifnislessthan1,anullisreturned.
Floatingpointnumberspassedasargumentstosubstrareautomaticallyconvertedto
integers.
Example SELECTSUBSTR('ABCDEFG',3.1,4)"Subs"
FROMDUAL;
1
Subs
CDEF
Example SELECTSUBSTR('ABCDEFG',5,4)"Subs"
FROMDUAL;
2
Subs
CDEF
SUBSTRB
Syntax SUBSTR(char,m[,n])
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
24/73
1/1/2017
Operators,Functions,Expressions,Conditions
Syntax SUBSTR(char,m[,n])
Purpose
ThesameasSUBSTR,exceptthattheargumentsmandnareexpressedinbytes,ratherthan
incharacters.Forasinglebytedatabasecharacterset,SUBSTRBisequivalenttoSUBSTR.
Floatingpointnumberspassedasargumentstosubstrbareautomaticallyconvertedto
integers.
Example
Assumeadoublebytedatabasecharacterset:
SELECTSUBSTRB('ABCDEFG',5,4.2)
"Substringwithbytes"
FROMDUAL;
Substringwithbytes
CD
TRANSLATE
Syntax TRANSLATE(char,from,to)
Purpose
Returnscharwithalloccurrencesofeachcharacterinfromreplacedbyitscorresponding
characterinto.Charactersincharthatarenotinfromarenotreplaced.Theargumentfrom
cancontainmorecharactersthanto.Inthiscase,theextracharactersattheendoffromhave
nocorrespondingcharactersinto.Iftheseextracharactersappearinchar,theyareremoved
fromthereturnvalue.Youcannotuseanemptystringfortotoremoveallcharactersinfrom
fromthereturnvalue.Oracleinterpretstheemptystringasnull,andifthisfunctionhasa
nullargument,itreturnsnull.
Example
1
Thefollowingstatementtranslatesalicensenumber.Allletters'ABC...Z'aretranslatedto
'X'andalldigits'012...9'aretranslatedto'9':
SELECTTRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX')"License"
FROMDUAL;
License
9XXX999
Example
2
Thefollowingstatementreturnsalicensenumberwiththecharactersremovedandthedigits
remaining:
SELECTTRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789')
"Translateexample"
FROMDUAL;
Translateexample
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
25/73
1/1/2017
Operators,Functions,Expressions,Conditions
2229
UPPER
Syntax UPPER(char)
Purpose
Returnschar,withalllettersuppercase.Thereturnvaluehasthesamedatatypeasthe
argumentchar.
Example SELECTUPPER('Large')"Uppercase"
FROMDUAL;
Upper
LARGE
CharacterFunctionsReturningNumberValues
Thissectionlistscharacterfunctionsthatreturnnumbervalues.
ASCII
Syntax ASCII(char)
Purpose
Returnsthedecimalrepresentationinthedatabasecharactersetofthefirstcharacterofchar.
Ifyourdatabasecharactersetis7bitASCII,thisfunctionreturnsanASCIIvalue.Ifyour
databasecharactersetisEBCDICCodePage500,thisfunctionreturnsanEBCDICvalue.
NotethatthereisnosimilarEBCDICcharacterfunction.
Example SELECTASCII('Q')
FROMDUAL;
ASCII('Q')
81
INSTR
Syntax INSTR(char1,char2[,n[,m]])
Purpose
Searcheschar1beginningwithitsnthcharacterforthemthoccurrenceofchar2andreturns
thepositionofthecharacterinchar1thatisthefirstcharacterofthisoccurrence.Ifnis
negative,Oraclecountsandsearchesbackwardfromtheendofchar1.Thevalueofmmust
bepositive.Thedefaultvaluesofbothnandmare1,meaningOraclebeginssearchingat
thefirstcharacterofchar1forthefirstoccurrenceofchar2.Thereturnvalueisrelativeto
thebeginningofchar1,regardlessofthevalueofn,andisexpressedincharacters.Ifthe
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
26/73
1/1/2017
Operators,Functions,Expressions,Conditions
searchisunsuccessful(ifchar2doesnotappearmtimesafterthenthcharacterofchar1)the
returnvalueis0.
Example SELECTINSTR('CORPORATEFLOOR','OR',3,2)
"Instring"FROMDUAL;
1
Instring
14
Example SELECTINSTR('CORPORATEFLOOR','OR',3,2)
"ReversedInstring"
2
FROMDUAL;
ReversedInstring
INSTRB
Syntax INSTRB(char1,char2[,n[,m]])
Purpose
ThesameasINSTR,exceptthatnandthereturnvalueareexpressedinbytes,ratherthanin
characters.Forasinglebytedatabasecharacterset,INSTRBisequivalenttoINSTR.
Example
Thisexampleassumesadoublebytedatabasecharacterset.
SELECTINSTRB('CORPORATEFLOOR','OR',5,2)
"Instringinbytes"
FROMDUAL;
Instringinbytes
27
LENGTH
Syntax LENGTH(char)
Purpose
Returnsthelengthofcharincharacters.IfcharhasdatatypeCHAR,thelengthincludesall
trailingblanks.Ifcharisnull,thisfunctionreturnsnull.
Example SELECTLENGTH('CANDIDE')"Lengthincharacters"
FROMDUAL;
Lengthincharacters
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
27/73
1/1/2017
Operators,Functions,Expressions,Conditions
LENGTHB
Syntax LENGTHB(char)
Purpose
Returnsthelengthofcharinbytes.Ifcharisnull,thisfunctionreturnsnull.Forasingle
bytedatabasecharacterset,LENGTHBisequivalenttoLENGTH.
Example
Thisexampleassumesadoublebytedatabasecharacterset.
SELECTLENGTHB('CANDIDE')"Lengthinbytes"
FROMDUAL;
Lengthinbytes
14
NLSSORT
Syntax NLSSORT(char[,'nlsparams'])
Purpose
Returnsthestringofbytesusedtosortchar.Thevalueof'nlsparams'canhavetheform
'NLS_SORT=sort'
wheresortisalinguisticsortsequenceorBINARY.Ifyouomit'nlsparams',thisfunctionusesthe
defaultsortsequenceforyoursession.IfyouspecifyBINARY,thisfunctionreturnschar.For
informationonsortsequences,seethediscussionsofnationallanguagesupportinOracle8
Reference.
Example
Thisfunctioncanbeusedtospecifycomparisonsbasedonalinguisticsortsequencerather
onthebinaryvalueofastring:
SELECTenameFROMemp
WHERENLSSORT(ename,'NLS_SORT=German')
>NLSSORT('S','NLS_SORT=German')ORDERBYename;
ENAME
SCOTT
SMITH
TURNER
WARD
DateFunctions
DatefunctionsoperateonvaluesoftheDATEdatatype.AlldatefunctionsreturnavalueofDATEdatatype,
excepttheMONTHS_BETWEENfunction,whichreturnsanumber.
ADD_MONTHS
Syntax ADD_MONTHS(d,n)
Purpose
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
28/73
1/1/2017
Operators,Functions,Expressions,Conditions
Purpose
Returnsthedatedplusnmonths.Theargumentncanbeanyinteger.Ifdisthelastdayof
themonthoriftheresultingmonthhasfewerdaysthanthedaycomponentofd,thenthe
resultisthelastdayoftheresultingmonth.Otherwise,theresulthasthesameday
componentasd.
Example SELECTTO_CHAR(
ADD_MONTHS(hiredate,1),
'DDMONYYYY')"Nextmonth"
FROMemp
WHEREename='SMITH';
NextMonth
17JAN1981
LAST_DAY
Syntax LAST_DAY(d)
Purpose
Returnsthedateofthelastdayofthemonththatcontainsd.Youmightusethisfunctionto
determinehowmanydaysareleftinthecurrentmonth.
Example SELECTSYSDATE,
LAST_DAY(SYSDATE)"Last",
1
LAST_DAY(SYSDATE)SYSDATE"DaysLeft"
FROMDUAL;
SYSDATELastDaysLeft
23OCT9731OCT978
Example SELECTTO_CHAR(
ADD_MONTHS(
2
LAST_DAY(hiredate),5),
'DDMONYYYY')"Fivemonths"
FROMemp
WHEREename='MARTIN';
Fivemonths
28FEB1982
MONTHS_BETWEEN
Syntax MONTHS_BETWEEN(d1,d2)
Purpose
Returnsnumberofmonthsbetweendatesd1andd2.Ifd1islaterthand2,resultispositive
ifearlier,negative.Ifd1andd2areeitherthesamedaysofthemonthorbothlastdaysof
months,theresultisalwaysanintegerotherwiseOraclecalculatesthefractionalportionof
theresultbasedona31daymonthandconsidersthedifferenceintimecomponentsofd1
andd2.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
29/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example SELECTMONTHS_BETWEEN
(TO_DATE('02021995','MMDDYYYY'),
TO_DATE('01011995','MMDDYYYY'))"Months"
FROMDUAL;
Months
1.03225806
NEW_TIME
Syntax NEW_TIME(d,z1,z2)
Purpose
Returnsthedateandtimeintimezonez2whendateandtimeintimezonez1ared.The
argumentsz1andz2canbeanyofthesetextstrings:
AST
AtlanticStandardorDaylightTime
ADT
BST
BeringStandardorDaylightTime
BDT
CST
CentralStandardorDaylightTime
CDT
EST
EasternStandardorDaylightTime
EDT
GMT
GreenwichMeanTime
HST
AlaskaHawaiiStandardTimeorDaylightTime.
HDT
MST
MountainStandardorDaylightTime
MDT
NST
NewfoundlandStandardTime
PST
PacificStandardorDaylightTime
PDT
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
30/73
1/1/2017
Operators,Functions,Expressions,Conditions
YST
YukonStandardorDaylightTime
YDT
NEXT_DAY
Syntax NEXT_DAY(d,char)
Purpose Returnsthedateofthefirstweekdaynamedbycharthatislaterthanthedated.Theargument
charmustbeadayoftheweekinyoursession'sdatelanguageeitherthefullnameorthe
abbreviation.Theminimumnumberoflettersrequiredisthenumberoflettersintheabbreviated
versionanycharactersimmediatelyfollowingthevalidabbreviationareignored.Thereturnvalue
hasthesamehours,minutes,andsecondscomponentastheargumentd.
Example
ThisexamplereturnsthedateofthenextTuesdayafterMarch15,1992.
SELECTNEXT_DAY('15MAR92','TUESDAY')"NEXTDAY"
FROMDUAL;
NEXTDAY
17MAR92
ROUND
Syntax ROUND(d[,fmt])
Purpose
Returnsdroundedtotheunitspecifiedbytheformatmodelfmt.Ifyouomitfmt,dis
roundedtothenearestday.See"ROUNDandTRUNC"forthepermittedformatmodelsto
useinfmt.
Example SELECTROUND(TO_DATE('27OCT92'),'YEAR')
"NewYear"FROMDUAL;
NewYear
01JAN93
SYSDATE
Syntax SYSDATE
Purpose
Returnsthecurrentdateandtime.Requiresnoarguments.IndistributedSQLstatements,
thisfunctionreturnsthedateandtimeonyourlocaldatabase.Youcannotusethisfunction
intheconditionofaCHECKconstraint.
SELECTTO_CHAR
(SYSDATE,'MMDDYYYYHH24:MI:SS')"NOW"
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
31/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example FROMDUAL;
NOW
1029199320:27:11
TRUNC
Syntax 1TRUNC(d,[fmt])
Purpose
Returnsdwiththetimeportionofthedaytruncatedtotheunitspecifiedbytheformat
modelfmt.Ifyouomitfmt,distruncatedtothenearestday.See"ROUNDandTRUNC"for
thepermittedformatmodelstouseinfmt.
Example SELECTTRUNC(TO_DATE('27OCT92','DDMONYY'),'YEAR')
"NewYear"FROMDUAL;
NewYear
01JAN92
ROUNDandTRUNC
Table311liststheformatmodelsyoucanusewiththeROUNDandTRUNCdatefunctionsandtheunitsto
whichtheyroundandtruncatedates.Thedefaultmodel,'DD',returnsthedateroundedortruncatedtothe
daywithatimeofmidnight.
Table311DateFormatModelsfortheROUNDandTRUNCDateFunctions
FormatModel
RoundingorTruncatingUnit
CC
SCC
Onegreaterthanthefirsttwodigitsofafourdigityear.
SYYYY
YYYY
YEAR
SYEAR
YYY
YY
Y
Year(roundsuponJuly1)
IYYY
IY
IY
I
ISOYear
Quarter(roundsuponthesixteenthdayofthesecondmonthofthequarter)
MONTH
Month(roundsuponthesixteenthday)
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
32/73
1/1/2017
Operators,Functions,Expressions,Conditions
Month(roundsuponthesixteenthday)
MONTH
MON
MM
RM
Samedayoftheweekasthefirstdayoftheyear.
WW
SamedayoftheweekasthefirstdayoftheISOyear.
IW
Samedayoftheweekasthefirstdayofthemonth.
Day
DDD
DD
J
Startingdayoftheweek
DAY
DY
D
Hour
HH
HH12
HH24
Minute
MI
ThestartingdayoftheweekusedbytheformatmodelsDAY,DY,andDisspecifiedimplicitlybythe
initializationparameterNLS_TERRITORY.Forinformationonthisparameter,seeOracle8Reference.
ConversionFunctions
Conversionfunctionsconvertavaluefromonedatatypetoanother.Generally,theformofthefunction
namesfollowstheconventiondatatypeTOdatatype.Thefirstdatatypeistheinputdatatypethelast
datatypeistheoutputdatatype.ThissectionliststheSQLconversionfunctions.
CHARTOROWID
Syntax
CHARTOROWID(char)
Purpose
ConvertsavaluefromCHARorVARCHAR2datatypetoROWIDdatatype.
Example SELECTenameFROMemp
WHEREROWID=CHARTOROWID('AAAAfZAABAAACp8AAO');
ENAME
LEWIS
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
33/73
1/1/2017
Operators,Functions,Expressions,Conditions
CONVERT
Syntax CONVERT(char,dest_char_set[,source_char_set])
Purpose
Convertsacharacterstringfromonecharactersettoanother.
Thecharargumentisthevaluetobeconverted.
Thedest_char_setargumentisthenameofthecharactersettowhichcharisconverted.
Thesource_char_setargumentisthenameofthecharactersetinwhichcharisstoredinthe
database.Thedefaultvalueisthedatabasecharacterset.
Boththedestinationandsourcecharactersetargumentscanbeeitherliteralsorcolumns
containingthenameofthecharacterset.
Forcompletecorrespondenceincharacterconversion,itisessentialthatthedestination
charactersetcontainsarepresentationofallthecharactersdefinedinthesourcecharacter
set.Whereacharacterdoesnotexistinthedestinationcharacterset,areplacementcharacter
appears.Replacementcharacterscanbedefinedaspartofacharactersetdefinition.
Example SELECTCONVERT('Gro','US7ASCII','WE8HP')
"Conversion"
FROMDUAL;
Conversion
Gross
Commoncharactersetsinclude:
US7ASCII
US7bitASCIIcharacterset
WE8DEC
DECWestEuropean8bitcharacterset
WE8HP
HPWestEuropeanLaserjet8bitcharacterset
F7DEC
WE8EBCDIC500
WE8PC850
WE8ISO8859P1
DECFrench7bitcharacterset
IBMWestEuropeanEBCDICCodePage500
IBMPCCodePage850
ISO88591WestEuropean8bitcharacterset
HEXTORAW
Syntax
HEXTORAW(char)
Purpose
Convertscharcontaininghexadecimaldigitstoarawvalue.
Example
INSERTINTOgraphics(raw_column)
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
34/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example
INSERTINTOgraphics(raw_column)
SELECTHEXTORAW('7D')FROMDUAL;
RAWTOHEX
Syntax
RAWTOHEX(raw)
Purpose
Convertsrawtoacharactervaluecontainingitshexadecimalequivalent.
Example
SELECTRAWTOHEX(raw_column)"Graphics"
FROMgraphics;
Graphics
7D
ROWIDTOCHAR
Syntax ROWIDTOCHAR(rowid)
Purpose
ConvertsaROWIDvaluetoVARCHAR2datatype.Theresultofthisconversionisalways
18characterslong.
Example SELECTROWID
FROMoffices
WHERE
ROWIDTOCHAR(ROWID)LIKE'%Br1AAB%';
ROWID
AAAAZ6AABAAABr1AAB
TO_CHAR,dateconversion
Syntax TO_CHAR(d[,fmt[,'nlsparams']])
Purpose
ConvertsdofDATEdatatypetoavalueofVARCHAR2datatypeintheformatspecifiedby
thedateformatfmt.Ifyouomitfmt,disconvertedtoaVARCHAR2valueinthedefault
dateformat.Forinformationondateformats,see"FormatModels".
The'nlsparams'specifiesthelanguageinwhichmonthanddaynamesandabbreviationsare
returned.Thisargumentcanhavethisform:
'NLS_DATE_LANGUAGE=language'
Ifyouomitnlsparams,thisfunctionusesthedefaultdatelanguageforyoursession.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
35/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example SELECTTO_CHAR(HIREDATE,'MonthDD,YYYY')
"Newdateformat"FROMemp
WHEREename='BLAKE';
Newdateformat
May01,1981
TO_CHAR,numberconversion
Syntax
TO_CHAR(n[,fmt[,'nlsparams']])
Purpose
ConvertsnofNUMBERdatatypetoavalueofVARCHAR2datatype,usingtheoptional
numberformatfmt.Ifyouomitfmt,nisconvertedtoaVARCHAR2valueexactlylong
enoughtoholditssignificantdigits.Forinformationonnumberformats,see"Format
Models".
The'nlsparams'specifiesthesecharactersthatarereturnedbynumberformatelements:
decimalcharacter
groupseparator
localcurrencysymbol
internationalcurrencysymbol
Thisargumentcanhavethisform:
'NLS_NUMERIC_CHARACTERS=''dg''
NLS_CURRENCY=''text''
NLS_ISO_CURRENCY=territory'
Thecharactersdandgrepresentthedecimalcharacterandgroupseparator,respectively.
Theymustbedifferentsinglebytecharacters.Notethatwithinthequotedstring,youmust
usetwosinglequotationmarksaroundtheparametervalues.Tencharactersareavailable
forthecurrencysymbol.
Ifyouomit'nlsparams'oranyoneoftheparameters,thisfunctionusesthedefault
parametervaluesforyoursession.
Example
1
Inthisexample,theoutputisblankpaddedtotheleftofthecurrencysymbol.
SELECTTO_CHAR(10000,'L99G999D99MI')"Amount"
FROMDUAL;
Amount
$10,000.00
Example2
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
36/73
1/1/2017
Operators,Functions,Expressions,Conditions
SELECTTO_CHAR(10000,'L99G999D99MI',
'NLS_NUMERIC_CHARACTERS='',.''
NLS_CURRENCY=''AusDollars''')"Amount"
FROMDUAL;
Amount
AusDollars10.000,00
Notes:
Intheoptionalnumberformatfmt,LdesignateslocalcurrencysymbolandMIdesignatesatrailing
minussign.SeeTable313foracompletelistingofnumberformatelements.
DuringaconversionofOraclenumberstostring,ifaroundingoperationoccursthatoverflowsor
underflowstheOracleNUMBERrange,then~or~maybereturned,representinginfinityand
negativeinfinity,respectively.ThiseventtypicallyoccurswhenyouareusingTO_CHAR()witha
restrictivenumberformatstring,causingaroundingoperation.
TO_DATE
Syntax TO_DATE(char[,fmt[,'nlsparams']])
Purpose
ConvertscharofCHARorVARCHAR2datatypetoavalueofDATEdatatype.Thefmtisa
dateformatspecifyingtheformatofchar.Ifyouomitfmt,charmustbeinthedefaultdate
format.Iffmtis'J',forJulian,thencharmustbeaninteger.Forinformationondateformats,
see"FormatModels".
The'nlsparams'hasthesamepurposeinthisfunctionasintheTO_CHARfunctionfordate
conversion.
DonotusetheTO_DATEfunctionwithaDATEvalueforthecharargument.Thereturned
DATEvaluecanhaveadifferentcenturyvaluethantheoriginalchar,dependingonfmtor
thedefaultdateformat.
Forinformationondateformats,see"DateFormatModels".
Example INSERTINTObonus(bonus_date)
SELECTTO_DATE(
'January15,1989,11:00A.M.',
'Monthdd,YYYY,HH:MIA.M.',
'NLS_DATE_LANGUAGE=American')
FROMDUAL;
TO_MULTI_BYTE
Syntax TO_MULTI_BYTE(char)
Purpose
Returnscharwithallofitssinglebytecharactersconvertedtotheircorrespondingmultibyte
characters.Anysinglebytecharactersincharthathavenomultibyteequivalentsappearin
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
37/73
1/1/2017
Operators,Functions,Expressions,Conditions
theoutputstringassinglebytecharacters.Thisfunctionisonlyusefulifyourdatabase
charactersetcontainsbothsinglebyteandmultibytecharacters.
TO_NUMBER
Syntax TO_NUMBER(char[,fmt[,'nlsparams']])
Purpose
Convertschar,avalueofCHARorVARCHAR2datatypecontaininganumberinthe
formatspecifiedbytheoptionalformatmodelfmt,toavalueofNUMBERdatatype.
Example UPDATEempSETsal=sal+
TO_NUMBER('100.00','9G999D99')
1
WHEREename='BLAKE';
The'nlsparams'stringinthisfunctionhasthesamepurposeasitdoesintheTO_CHAR
functionfornumberconversions.
Example SELECTTO_NUMBER('AusDollars100','L9G999D99',
'NLS_NUMERIC_CHARACTERS='',.''
2
NLS_CURRENCY=''AusDollars''
')"Amount"
FROMDUAL;
Amount
100
TO_SINGLE_BYTE
Syntax TO_SINGLE_BYTE(char)
Purpose
Returnscharwithallofitsmultibytecharacterconvertedtotheircorrespondingsinglebyte
characters.Anymultibytecharactersincharthathavenosinglebyteequivalentsappearin
theoutputasmultibytecharacters.Thisfunctionisonlyusefulifyourdatabasecharacterset
containsbothsinglebyteandmultibytecharacters.
TRANSLATEUSING
Syntax TRANSLATE(textUSING{CHAR_CS|NCHAR_CS})
Purpose
Convertstextintothecharactersetspecifiedforconversionsbetweenthedatabasecharacter
setandthenationalcharacterset.
Thetextargumentistheexpressiontobeconverted.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
38/73
1/1/2017
Operators,Functions,Expressions,Conditions
SpecifyingtheUSINGCHAR_CSargumentconvertstextintothedatabasecharacterset.
TheoutputdatatypeisVARCHAR2.
SpecifyingtheUSINGNCHAR_CSargumentconvertstextintothenationalcharacterset.
TheoutputdatatypeisNVARCHAR2.
ThisfunctionissimilartotheOracleCONVERTfunction,butmustbeusedinsteadof
CONVERTifeithertheinputortheoutputdatatypeisbeingusedasNCHARor
NVARCHAR2.
Example CREATETABLEt1(char_colCHAR(20),
nchar_colnchar(20));
1
INSERTINTOt1
VALUES('Hi',N'Bye');
SELECT*FROMt1;
CHAR_COLNCHAR_COL
HiBye
Example UPDATEt1SET
nchar_col=TRANSLATE(char_colUSINGNCHAR_CS);
2
UPDATEt1SET
char_col=TRANSLATE(nchar_colUSINGCHAR_CS);
SELECT*FROMt1;
CHAR_COLNCHAR_COL
HiHi
Example UPDATEt1SET
nchar_col=TRANSLATE('deo'USINGNCHAR_CS);
3
UPDATEt1SET
char_col=TRANSLATE(N'deo'USINGCHAR_CS);
CHAR_COLNCHAR_COL
deodeo
OtherSingleRowFunctions
DUMP
Syntax DUMP(expr[,return_format[,start_position[,length]]])
Purpose
ReturnsaVARCHAR2valuecontainingthedatatypecode,lengthinbytes,andinternal
representationofexpr.Thereturnedresultisalwaysinthedatabasecharacterset.Forthe
datatypecorrespondingtoeachcode,seeTable21.
Theargumentreturn_formatspecifiestheformatofthereturnvalueandcanhaveanyofthe
valueslistedbelow.
Bydefault,thereturnvaluecontainsnocharactersetinformation.Toretrievethecharacter
setnameofexpr,specifyanyoftheformatvaluesbelow,plus1000.Forexample,a
return_formatof1008returnstheresultinoctal,plusprovidesthecharactersetnameof
expr.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
39/73
1/1/2017
Operators,Functions,Expressions,Conditions
returnsresultinoctalnotation.
10
returnsresultindecimalnotation.
16
returnsresultinhexadecimalnotation.
17
returnsresultassinglecharacters.
Theargumentsstart_positionandlengthcombinetodeterminewhichportionoftheinternal
representationtoreturn.Thedefaultistoreturntheentireinternalrepresentationindecimal
notation.
Ifexprisnull,thisfunctionreturns'NULL'.
Example SELECTDUMP('abc',1016)
FROMDUAL;
1
DUMP('ABC',1016)
Typ=96Len=3CharacterSet=WE8DEC:61,62,63
Example SELECTDUMP(ename,8,3,2)"OCTAL"
FROMemp
2
WHEREename='SCOTT';
OCTAL
Type=1Len=5:117,124
Example SELECTDUMP(ename,10,3,2)"ASCII"
FROMemp
3
WHEREename='SCOTT';
ASCII
Type=1Len=5:79,84
EMPTY_[B|C]LOB
Syntax EMPTY_[B|C]LOB()
Purpose
ReturnsanemptyLOBlocatorthatcanbeusedtoinitializeaLOBvariableorinan
INSERTorUPDATEstatementtoinitializeaLOBcolumnorattributetoEMPTY.
EMPTYmeansthattheLOBisinitialized,butnotpopulatedwithdata.
YoucannotusethelocatorreturnedfromthisfunctionasaparametertotheDBMS_LOB
packageortheOCI.
Examples INSERTINTOlob_tab1VALUES(EMPTY_BLOB());
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
40/73
1/1/2017
Operators,Functions,Expressions,Conditions
Examples INSERTINTOlob_tab1VALUES(EMPTY_BLOB());
UPDATElob_tab1
SETclob_col=EMPTY_BLOB();
BFILENAME
Syntax BFILENAME('directory','filename')
Purpose
ReturnsaBFILElocatorthatisassociatedwithaphysicalLOBbinaryfileontheserver's
filesystem.Adirectoryisanaliasforafullpathnameontheserver'sfilesystemwherethe
filesareactuallylocated'filename'isthenameofthefileintheserver'sfilesystem.
Neither'directory'nor'filename'needtopointtoanexistingobjectonthefilesystematthe
timeyouspecifyBFILENAME.However,youmustassociateaBFILEvaluewitha
physicalfilebeforeperformingsubsequentSQL,PL/SQL,DBMS_LOBpackage,orOCI
operations.Formoreinformation,seeCREATEDIRECTORY.
Note:Thisfunctiondoesnotverifythateitherthedirectoryorfilespecifiedactuallyexists.
Therefore,youcancalltheCREATEDIRECTORYcommandafterBFILENAME.
However,theobjectmustexistbythetimeyouactuallyusetheBFILElocator(forexample,
asaparametertooneoftheOCILoborDBMS_LOBoperationssuchasOCILobFileOpen()
orDBMS_LOB.FILEOPEN()).
FormoreinformationaboutLOBs,seeOracle8ApplicationDeveloper'sGuideandOracle
CallInterfaceProgrammer'sGuide.
Example INSERTINTOfile_tbl
VALUES(BFILENAME('lob_dir1','image1.gif'));
GREATEST
Syntax GREATEST(expr[,expr]...)
Purpose
Returnsthegreatestofthelistofexprs.Allexprsafterthefirstareimplicitlyconvertedto
thedatatypeofthefirstexprsbeforethecomparison.Oraclecomparestheexprsusing
nonpaddedcomparisonsemantics.Charactercomparisonisbasedonthevalueofthe
characterinthedatabasecharacterset.Onecharacterisgreaterthananotherifithasahigher
value.Ifthevaluereturnedbythisfunctionischaracterdata,itsdatatypeisalways
VARCHAR2.
Example SELECTGREATEST('HARRY','HARRIOT','HAROLD')
"Great"FROMDUAL;
Great
HARRY
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
41/73
1/1/2017
Operators,Functions,Expressions,Conditions
LEAST
Syntax LEAST(expr[,expr]...)
Purpose
Returnstheleastofthelistofexprs.Allexprsafterthefirstareimplicitlyconvertedtothe
datatypeofthefirstexprbeforethecomparison.Oraclecomparestheexprsusing
nonpaddedcomparisonsemantics.Ifthevaluereturnedbythisfunctionischaracterdata,its
datatypeisalwaysVARCHAR2.
Example SELECTLEAST('HARRY','HARRIOT','HAROLD')"LEAST"
FROMDUAL;
LEAST
HAROLD
NLS_CHARSET_DECL_LEN
Syntax NLS_CHARSET_DECL_LEN(bytecnt,csid)
Purpose Returnsthedeclarationwidth(innumberofcharacters)ofanNCHARcolumn.Thebytecnt
argumentisthewidthofthecolumn.ThecsidargumentisthecharactersetIDofthecolumn.
Example
SELECTNLS_CHARSET_DECL_LEN
(200,nls_charset_id('ja16eucfixed'))
FROMDUAL;
NLS_CHARSET_DECL_LEN(200,NLS_CHARSET_ID('JA16EUCFIXED'))
100
NLS_CHARSET_ID
Syntax NLS_CHARSET_ID(text)
Purpose
ReturnstheNLScharactersetIDnumbercorrespondingtoNLScharactersetname,text.
ThetextargumentisaruntimeVARCHAR2value.Thetextvalue'CHAR_CS'returnsthe
server'sdatabasecharactersetIDnumber.Thetextvalue'NCHAR_CS'returnstheserver's
nationalcharactersetIDnumber.
Invalidcharactersetnamesreturnnull.
Foralistofcharactersetnames,seeOracle8Reference.
Example SELECTNLS_CHARSET_ID('ja16euc')
FROMDUAL;
I
NLS_CHARSET_ID('JA16EUC')
830
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
42/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example SELECTNLS_CHARSET_ID('char_cs')
FROMDUAL;
2
NLS_CHARSET_ID('CHAR_CS')
Example SELECTNLS_CHARSET_ID('nchar_cs')
FROMDUAL;
3
NLS_CHARSET_ID('NCHAR_CS')
NLS_CHARSET_NAME
Syntax NLS_CHARSET_NAME(n)
Purpose
ReturnsthenameoftheNLScharactersetcorrespondingtoIDnumbern.Thecharacterset
nameisreturnedasaVARCHAR2valueinthedatabasecharacterset.
IfnisnotrecognizedasavalidcharactersetID,thisfunctionreturnsnull.
ForalistofcharactersetIDs,seeOracle8Reference.
Example SELECTNLS_CHARSET_NAME(2)
FROMDUAL;
NLS_CH
WE8DEC
NVL
Syntax NVL(expr1,expr2)
Purpose
Ifexpr1isnull,returnsexpr2ifexpr1isnotnull,returnsexpr1.Theargumentsexpr1and
expr2canhaveanydatatype.Iftheirdatatypesaredifferent,Oracleconvertsexpr2tothe
datatypeofexpr1beforecomparingthem.Thedatatypeofthereturnvalueisalwaysthe
sameasthedatatypeofexpr1,unlessexpr1ischaracterdata,inwhichcasethereturn
value'sdatatypeisVARCHAR2.
Example SELECTename,NVL(TO_CHAR(COMM),'NOT
APPLICABLE')
"COMMISSION"FROMemp
WHEREdeptno=30;
ENAMECOMMISSION
ALLEN300
WARD500
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
43/73
1/1/2017
Operators,Functions,Expressions,Conditions
MARTIN1400
BLAKENOTAPPLICABLE
TURNER0
JAMESNOTAPPLICABLE
UID
Syntax
UID
Purpose
Returnsanintegerthatuniquelyidentifiesthecurrentuser.
USER
Syntax USER
Purpose
ReturnsthecurrentOracleuserwiththedatatypeVARCHAR2.Oraclecomparesvaluesof
thisfunctionwithblankpaddedcomparisonsemantics.
InadistributedSQLstatement,theUIDandUSERfunctionsidentifytheuseronyourlocal
database.YoucannotusethesefunctionsintheconditionofaCHECKconstraint.
Example SELECTUSER,UIDFROMDUAL;
USERUID
SCOTT19
USERENV
Syntax USERENV(option)
Purpose
ReturnsinformationofVARCHAR2datatypeaboutthecurrentsession.Thisinformation
canbeusefulforwritinganapplicationspecificaudittrailtableorfordeterminingthe
languagespecificcharacterscurrentlyusedbyyoursession.YoucannotuseUSERENVin
theconditionofaCHECKconstraint.Theargumentoptioncanhaveanyofthesevalues:
'ISDBA'
'LANGUAGE'
returns'TRUE'ifyoucurrentlyhavetheISDBAroleenabledand'FALSE'ifyoudo
not.
returnsthelanguageandterritorycurrentlyusedbyyoursessionalongwiththe
databasecharactersetinthisform:
language_territory.characterset
'TERMINAL' returnstheoperatingsystemidentifierforyourcurrentsession'sterminal.In
distributedSQLstatements,thisoptionreturnstheidentifierforyourlocalsession.In
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
44/73
1/1/2017
Operators,Functions,Expressions,Conditions
adistributedenvironment,thisissupportedonlyforremoteSELECTs,notforremote
INSERTs,UPDATEs,orDELETEs.
'SESSIONID'returnsyourauditingsessionidentifier.YoucannotusethisoptionindistributedSQL
statements.TousethiskeywordinUSERENV,theinitializationparameter
AUDIT_TRAILmustbesettoTRUE.
'ENTRYID'
'LANG'
'INSTANCE'
returnsavailableauditingentryidentifier.Youcannotusethisoptionindistributed
SQLstatements.TousethiskeywordinUSERENV,theinitializationparameter
AUDIT_TRAILmustbesettoTRUE.
ReturnstheISOabbreviationforthelanguagename,ashorterformthantheexisting
'LANGUAGE'parameter.
Returnstheinstanceidentificationnumberofthecurrentinstance.
Example SELECTUSERENV('LANGUAGE')"Language"FROMDUAL;
Language
AMERICAN_AMERICA.WE8DEC
VSIZE
Syntax VSIZE(expr)
Purpose
Returnsthenumberofbytesintheinternalrepresentationofexpr.Ifexprisnull,this
functionreturnsnull.
Example SELECTename,VSIZE(ename)"BYTES"
FROMemp
WHEREdeptno=10;
ENAMEBYTES
CLARK5
KING4
MILLER6
ObjectReferenceFunctions
ObjectreferencefunctionsmanipulateREFsreferencestoobjectsofspecifiedobjecttypes.Formore
informationaboutREFs,seeOracle8ConceptsandOracle8ApplicationDeveloper'sGuide.
DEREF
Syntax DEREF(e)
Purpose
Returnstheobjectreferenceofargumente.Argumentemustbeanexpressionthatreturnsa
REFtoanobject.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
45/73
1/1/2017
Operators,Functions,Expressions,Conditions
Example CREATETABLEtb1(c1NUMBER,c2REFt1);
SELECTDEREF(c2)FROMtb1;
REFTOHEX
Syntax
REFTOHEX(r)
Purpose
Convertsargumentrtoacharactervaluecontainingitshexadecimalequivalent.
Example CREATETABLEtb1(c1NUMBER,c2REFt1);
SELECTREFTOHEX(c2)FROMtb1;
MAKE_REF
Syntax MAKE_REF(table,key[,key...])
Purpose
CreatesaREFtoarowofanobjectviewusingkeyastheprimarykey.Formore
informationaboutobjectviews,seeOracle8ApplicationDeveloper'sGuide.
Example CREATETYPEt1ASOBJECT(aNUMBER,bNUMBER);
CREATETABLEtb1
(c1NUMBER,c2NUMBER,PRIMARYKEY(c1,c2));
CREATEVIEWv1OFt1WITHOBJECTOID(a,b)AS
SELECT*FROMtb1;
SELECTMAKE_REF(v1,1,3)FROMDUAL;
GroupFunctions
Groupfunctionsreturnresultsbasedongroupsofrows,ratherthanonsinglerows.Inthisway,group
functionsaredifferentfromsinglerowfunctions.Foradiscussionofthedifferencesbetweengroup
functionsandsinglerowfunctions,see"SQLFunctions".
Manygroupfunctionsaccepttheseoptions:
DISTINCT Thisoptioncausesagroupfunctiontoconsideronlydistinctvaluesoftheargument
expression.
ALL
Thisoptioncausesagroupfunctiontoconsiderallvalues,includingallduplicates.
Forexample,theDISTINCTaverageof1,1,1,and3is2theALLaverageis1.5.Ifneitheroptionis
specified,thedefaultisALL.
AllgroupfunctionsexceptCOUNT(*)ignorenulls.YoucanusetheNVLintheargumenttoagroup
functiontosubstituteavalueforanull.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
46/73
1/1/2017
Operators,Functions,Expressions,Conditions
Ifaquerywithagroupfunctionreturnsnorowsoronlyrowswithnullsfortheargumenttothegroup
function,thegroupfunctionreturnsnull.
AVG
Syntax
AVG([DISTINCT|ALL]n)
Purpose
Returnsaveragevalueofn.
Example
SELECTAVG(sal)"Average"
FROMemp;
Average
2077.21429
COUNT
Syntax COUNT({*|[DISTINCT|ALL]expr})
Purpose
Returnsthenumberofrowsinthequery.
Ifyouspecifyexpr,thisfunctionreturnsrowswhereexprisnotnull.Youcancounteither
allrows,oronlydistinctvaluesofexpr.
Ifyouspecifytheasterisk(*),thisfunctionreturnsallrows,includingduplicatesandnulls.
Example SELECTCOUNT(*)"Total"
FROMemp;
1
Total
18
Example SELECTCOUNT(job)"Count"
FROMemp;
2
Count
14
Example SELECTCOUNT(DISTINCTjob)"Jobs"
FROMemp;
3
Jobs
MAX
Syntax
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
47/73
1/1/2017
Operators,Functions,Expressions,Conditions
Syntax
MAX([DISTINCT|ALL]expr)
Purpose
Returnsmaximumvalueofexpr.
Example
SELECTMAX(sal)"Maximum"FROMemp;
Maximum
5000
MIN
Syntax
MIN([DISTINCT|ALL]expr)
Purpose
Returnsminimumvalueofexpr.
Example
SELECTMIN(hiredate)"Earliest"FROMemp;
Earliest
17DEC80
STDDEV
Syntax STDDEV([DISTINCT|ALL]x)
Purpose
Returnsstandarddeviationofx,anumber.Oraclecalculatesthestandarddeviationasthe
squarerootofthevariancedefinedfortheVARIANCEgroupfunction.
Example SELECTSTDDEV(sal)"Deviation"
FROMemp;
Deviation
1182.50322
SUM
Syntax
SUM([DISTINCT|ALL]n)
Purpose
Returnssumofvaluesofn.
Example
SELECTSUM(sal)"Total"
FROMemp;
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
48/73
1/1/2017
Operators,Functions,Expressions,Conditions
Total
29081
VARIANCE
Syntax
VARIANCE([DISTINCT|ALL]x)
Purpose
Returnsvarianceofx,anumber.Oraclecalculatesthevarianceofxusingthisformula:
where:
xiisoneoftheelementsofx.
nisthenumberofelementsinthesetx.Ifnis1,thevarianceisdefinedtobe0.
Example SELECTVARIANCE(sal)"Variance"
FROMemp;
Variance
1389313.87
UserFunctions
YoucanwriteyourownuserfunctionsinPL/SQLtoprovidefunctionalitythatisnotavailableinSQLor
SQLfunctions.UserfunctionsareusedinaSQLstatementanywhereSQLfunctionscanbeusedthatis,
whereverexpressioncanoccur.
Forexample,userfunctionscanbeusedinthefollowing:
theselectlistofaSELECTcommand
theconditionofaWHEREclause
CONNECTBY,STARTWITH,ORDERBY,andGROUPBYclauses
theVALUESclauseofanINSERTcommand
theSETclauseofanUPDATEcommand
Foracompletedescriptiononthecreationanduseofuserfunctions,seeOracle8ApplicationDeveloper's
Guide.
Prerequisites
UserfunctionsmustbecreatedastoplevelPL/SQLfunctionsordeclaredwithapackagespecification
beforetheycanbenamedwithinaSQLstatement.CreateuserfunctionsastoplevelPL/SQLfunctionsby
usingtheCREATEFUNCTIONstatementdescribedinCREATEFUNCTION.Specifypackagedfunctions
withapackagewiththeCREATEPACKAGEstatementdescribedinCREATEPACKAGE.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
49/73
1/1/2017
Operators,Functions,Expressions,Conditions
Tocallapackageduserfunction,youmustdeclaretheRESTRICT_REFERENCESpragmainthepackage
specification.
PrivilegesRequired
TouseauserfunctioninaSQLexpression,youmustownorhaveEXECUTEprivilegeontheuserfunction.
Toqueryaviewdefinedwithauserfunction,youmusthaveSELECTprivilegesontheview.Noseparate
EXECUTEprivilegesareneededtoselectfromtheview.
RestrictionsonUserFunctions
Userfunctionscannotbeusedinsituationsthatrequireanunchangingdefinition.Thus,auserfunction
cannot:
beusedinaCHECKconstraintclauseofaCREATETABLEorALTERTABLEcommand
beusedinaDEFAULTclauseofaCREATETABLEorALTERTABLEcommand
containOUTorINOUTparameters
updatethedatabase
readorwritepackagestateifthefunctionisaremotefunction
usetheparallelism_clauseinSQLcommandsinthefunctionifthefunctionalterspackagestate
updatevariablesdefinedinthefunctionunlessthefunctionisalocalfunctionandisusedina
SELECTlist,VALUESclauseofanINSERTcommand,orSETclauseofanUPDATEcommand
NamePrecedence
WithPL/SQL,thenamesofdatabasecolumnstakeprecedenceoverthenamesoffunctionswithno
parameters.Forexample,ifuserSCOTTcreatesthefollowingtwoobjectsinhisownschema:
CREATETABLEemp(new_salNUMBER,...);
CREATEFUNCTIONnew_salRETURNNUMBERISBEGIN...END;
theninthefollowingtwostatements,thereferencetoNEW_SALreferstothecolumnEMP.NEW_SAL:
SELECTnew_salFROMemp;
SELECTemp.new_salFROMemp;
ToaccessthefunctionNEW_SAL,youwouldenter:
SELECTscott.new_salFROMemp;
HerearesomesamplecallstouserfunctionsthatareallowedinSQLexpressions.
circle_area(radius)
payroll.tax_rate(empno)
scott.payroll.tax_rate(dependent,empno)@ny
Example
Forexample,tocalltheTAX_RATEuserfunctionfromschemaSCOTT,executeitagainsttheSS_NOand
SALcolumnsinTAX_TABLE,andplacetheresultsinthevariableINCOME_TAX,specifythefollowing:
SELECTscott.tax_rate(ss_no,sal)
INTOincome_tax
FROMtax_table
WHEREss_no=tax_id;
NamingConventions
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
50/73
1/1/2017
Operators,Functions,Expressions,Conditions
Ifonlyoneoftheoptionalschemaorpackagenamesisgiven,thefirstidentifiercanbeeitheraschemaname
orapackagename.Forexample,todeterminewhetherPAYROLLinthereferencePAYROLL.TAX_RATE
isaschemaorpackagename,Oracleproceedsasfollows:
CheckforthePAYROLLpackageinthecurrentschema.
IfaPAYROLLpackageisnotfound,lookforaschemanamePAYROLLthatcontainsatoplevel
TAX_RATEfunction.Ifnosuchfunctionisfound,returnanerrormessage.
IfthePAYROLLpackageisfoundinthecurrentschema,lookforaTAX_RATEfunctioninthe
PAYROLLpackage.Ifnosuchfunctionisfound,returnanerrormessage.
Youcanalsorefertoastoredtoplevelfunctionusinganysynonymthatyouhavedefinedforit.
FormatModels
AformatmodelisacharacterliteralthatdescribestheformatofDATEorNUMBERdatastoredina
characterstring.YoucanuseaformatmodelasanargumentoftheTO_CHARorTO_DATEfunction:
tospecifytheformatforOracletousetoreturnavaluefromthedatabasetoyou
tospecifytheformatforavalueyouhavespecifiedforOracletostoreinthedatabase
Notethataformatmodeldoesnotchangetheinternalrepresentationofthevalueinthedatabase.
Thissectiondescribeshowtouse:
numberformatmodels
dateformatmodels
formatmodelmodifiers
ChangingtheReturnFormat
YoucanuseaformatmodeltospecifytheformatforOracletousetoreturnvaluesfromthedatabasetoyou.
Example1
ThefollowingstatementselectsthecommissionvaluesoftheemployeesinDepartment30andusesthe
TO_CHARfunctiontoconvertthesecommissionsintocharactervalueswiththeformatspecifiedbythe
numberformatmodel'$9,990.99':
SELECTenameemployee,TO_CHAR(comm,'$9,990.99')commission
FROMemp
WHEREdeptno=30;
EMPLOYEECOMMISSION
ALLEN$300.00
WARD$500.00
MARTIN$1,400.00
BLAKE
TURNER$0.00
JAMES
Becauseofthisformatmodel,Oraclereturnscommissionswithleadingdollarsigns,commaseverythree
digits,andtwodecimalplaces.NotethatTO_CHARreturnsnullforallemployeeswithnullintheCOMM
column.
Example2
Thefollowingstatementselectsthedateonwhicheachemployeefromdepartment20washiredandusesthe
TO_CHARfunctiontoconvertthesedatestocharacterstringswiththeformatspecifiedbythedateformat
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
51/73
1/1/2017
Operators,Functions,Expressions,Conditions
model'fmMonthDD,YYYY':
SELECTename,TO_CHAR(Hiredate,'fmMonthDD,YYYY')hiredate
FROMemp
WHEREdeptno=20;
ENAMEHIREDATE
SMITHDecember17,1980
JONESApril2,1981
SCOTTApril19,1987
ADAMSMay23,1987
FORDDecember3,1981
LEWISOctober23,1997
Withthisformatmodel,Oraclereturnsthehiredateswiththemonthspelledout(asspecifiedby"fm"and
discussedin"FormatModelModifiers"),twodigitsfortheday,andthecenturyincludedintheyear.
SupplyingtheCorrectFormat
Youcanuseformatmodelstospecifytheformatofavaluethatyouareconvertingfromonedatatypeto
anotherdatatyperequiredforacolumn.Whenyouinsertorupdateacolumnvalue,thedatatypeofthevalue
thatyouspecifymustcorrespondtothecolumn'sdatatype.Forexample,avaluethatyouinsertintoaDATE
columnmustbeavalueoftheDATEdatatypeoracharacterstringinthedefaultdateformat(Oracle
implicitlyconvertscharacterstringsinthedefaultdateformattotheDATEdatatype).Ifthevalueisin
anotherformat,youmustusetheTO_DATEfunctiontoconvertthevaluetotheDATEdatatype.Youmust
alsouseaformatmodeltospecifytheformatofthecharacterstring.
Example
ThefollowingstatementupdatesBAKER'shiredateusingtheTO_DATEfunctionwiththeformatmask
'YYYYMMDD'toconvertthecharacterstring'19920520'toaDATEvalue:
UPDATEemp
SEThiredate=TO_DATE('19920520','YYYYMMDD')
WHEREename='BLAKE';
NumberFormatModels
Youcanusenumberformatmodels
intheTO_CHARfunctiontotranslateavalueofNUMBERdatatypetoVARCHAR2datatype
intheTO_NUMBERfunctiontotranslateavalueofCHARorVARCHAR2datatypetoNUMBER
datatype
Allnumberformatmodelscausethenumbertoberoundedtothespecifiednumberofsignificantdigits.Ifa
valuehasmoresignificantdigitstotheleftofthedecimalplacethanarespecifiedintheformat,poundsigns
(#)replacethevalue.Ifapositivevalueisextremelylargeandcannotberepresentedinthespecifiedformat,
thentheinfinitysign(~)replacesthevalue.Likewise,ifanegativevalueisextremelysmallandcannotbe
representedbythespecifiedformat,thenthenegativeinfinitysignreplacesthevalue(~).
NumberFormatElements
Anumberformatmodeliscomposedofoneormorenumberformatelements.Table312liststheelements
ofanumberformatmodel.ExamplesareshowninTable313.
IfanumberformatmodeldoesnotcontaintheMI,S,orPRformatelements,negativereturnvalues
automaticallycontainaleadingnegativesignandpositivevaluesautomaticallycontainaleading
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
52/73
1/1/2017
Operators,Functions,Expressions,Conditions
space.
Anumberformatmodelcancontainonlyasingledecimalcharacter(D)orperiod(.),butitcan
containmultiplegroupseparators(G)orcommas(,).
Anumberformatmodelmustnotbeginwithacomma(,).
Agroupseparatororcommacannotappeartotherightofadecimalcharacterorperiodinanumber
formatmodel.
Table312NumberFormatElements
Element Example
Description
9
9999
Returnvaluewiththespecifiednumberofdigitswithaleadingspaceif
positive.
Returnvaluewiththespecifiednumberofdigitswithaleadingminusif
negative.
Leadingzerosareblank,exceptforazerovalue,whichreturnsazeroforthe
integerpartofthefixedpointnumber.
0999
Returnleadingzeros.
9990
Returntrailingzeros.
$9999
Returnvaluewithaleadingdollarsign.
B9999
Returnblanksfortheintegerpartofafixedpointnumberwhentheinteger
partiszero(regardlessof"0'sintheformatmodel).
MI
9999MI
Returnnegativevaluewithatrailingminussign"".
Returnpositivevaluewithatrailingblank.
S9999
Returnnegativevaluewithaleadingminussign"".
9999S
Returnpositivevaluewithaleadingplussign"+".
Returnnegativevaluewithatrailingminussign"".
Returnpositivevaluewithatrailingplussign"+".
PR
9999PR
Returnnegativevaluein<anglebrackets>.
Returnpositivevaluewithaleadingandtrailingblank.
99D99
Returnadecimalcharacter(thatis,aperiod".")inthespecifiedposition.
9G999
Returnagroupseparatorinthepositionspecified.
C999
ReturntheISOcurrencysymbolinthespecifiedposition.
L999
Returnthelocalcurrencysymbolinthespecifiedposition.
,
9,999
(comma)
Returnacommainthespecifiedposition.
.(period) 99.99
Returnadecimalpoint(thatis,aperiod".")inthespecifiedposition.
999V99
Returnavaluemultipliedby10n(andifnecessary,rounditup),wherenisthe
numberof9'safterthe"V".
EEEE
9.9EEEE
Returnavalueusinginscientificnotation.
RN
RN
ReturnavalueasRomannumeralsinuppercase.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
53/73
1/1/2017
Operators,Functions,Expressions,Conditions
rn
ReturnavalueasRomannumeralsinlowercase.
Valuecanbeanintegerbetween1and3999.
FM
FM90.9
Returnavaluewithnoleadingortrailingblanks.
Example
Table313showstheresultsofthefollowingqueryfordifferentvaluesofnumberand'fmt':
SELECTTO_CHAR(number,'fmt')
FROMDUAL
Table313ResultsofExampleNumberConversions
number
'fmt'
Result
1234567890
9999999999S
'1234567890'
99.99
'.00'
+0.1
99.99
'0.10'
0.2
99.99
'.20'
90.99
'0.00'
+0.1
90.99
'0.10'
0.2
90.99
'0.20'
9999
'0'
9999
'1'
B9999
''
B9999
'1'
B90.99
''
+123.456
999.999
'123.456'
123.456
999.999
'123.456'
+123.456
FM999.009
'123.456'
+123.456
9.9EEEE
'1.2E+02'
+1E+123
9.9EEEE
'1.0E+123'
+123.456
FM9.9EEEE
'1.23E+02'
+123.45
FM999.009
'123.45'
+123.0
FM999.009
'123.00'
+123.45
L999.99
'$123.45'
+123.45
FML99.99
'$123.45'
+1234567890
9999999999S
'1234567890+'
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
54/73
1/1/2017
Operators,Functions,Expressions,Conditions
TheMIandPRformatelementscanappearonlyinthelastpositionofanumberformatmodel.TheSformat
elementcanappearonlyinthefirstorlastpositionofanumberformatmodel.
Thecharactersreturnedbysomeoftheseformatelementsarespecifiedbyinitializationparameters.Table3
14liststheseelementsandparameters.
Table314NumberFormatElementValuesDeterminedbyInitializationParameters
Element
Description
InitializationParameter
Decimalcharacter
NLS_NUMERIC_CHARACTER
Groupseparator
NLS_NUMERIC_CHARACTER
ISOcurrencysymbol
NLS_ISO_CURRENCY
Localcurrencysymbol
NLS_CURRENCY
Youcanspecifythecharactersreturnedbytheseformatelementsimplicitlyusingtheinitializationparameter
NLS_TERRITORY.Forinformationontheseparameters,seeOracle8Reference.
YoucanchangethecharactersreturnedbytheseformatelementsforyoursessionwiththeALTERSESSION
command.YoucanalsochangethedefaultdateformatforyoursessionwiththeALTERSESSION
command.Forinformation,seeALTERSESSION.
DateFormatModels
Youcanusedateformatmodels
intheTO_CHARfunctiontotranslateaDATEvaluethatisinaformatotherthanthedefaultdate
format
intheTO_DATEfunctiontotranslateacharactervaluethatisinaformatotherthanthedefaultdate
format
DefaultDateFormat
ThedefaultdateformatisspecifiedeitherexplicitlywiththeinitializationparameterNLS_DATE_FORMAT
orimplicitlywiththeinitializationparameterNLS_TERRITORY.Forinformationontheseparameters,see
Oracle8Referencee.
YoucanchangethedefaultdateformatforyoursessionwiththeALTERSESSIONcommand.For
information,seeALTERSESSION.
MaximumLength
Thetotallengthofadateformatmodelcannotexceed22characters.
DateFormatElements
AdateformatmodeliscomposedofoneormoredateformatelementsaslistedinTable315.Forinput
formatmodels,formatitemscannotappeartwice,andformatitemsthatrepresentsimilarinformationcannot
becombined.Forexample,youcannotuse'SYYYY'and'BC'inthesameformatstring.Onlysomeofthe
dateformatelementscanbeusedintheTO_DATEfunctionasnotedinTable315.
Table315DateFormatElements
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
55/73
1/1/2017
Operators,Functions,Expressions,Conditions
Specifyin
Element TO_DATE?
Meaning
/
,
.
;
:
'text'
Yes
Punctuationandquotedtextisreproducedintheresult.
Yes
ADindicatorwithorwithoutperiods.
Yes
Meridianindicatorwithorwithoutperiods.
Yes
BCindicatorwithorwithoutperiods.
No
Onegreaterthanthefirsttwodigitsofafourdigityear"S"prefixesBCdates
with"".Forexample,'20'from'1900'.
Yes
Dayofweek(17).
Yes
Nameofday,paddedwithblankstolengthof9characters.
Yes
Dayofmonth(131).
Yes
Dayofyear(1366).
Yes
Abbreviatednameofday.
No
Abbreviatederaname(JapaneseImperial,ROCOfficial,andThaiBuddha
calendars).
No
Fulleraname(JapaneseImperial,ROCOfficial,andThaiBuddhacalendars).
Yes
Hourofday(112).
No
Hourofday(112).
Yes
Hourofday(023).
No
Weekofyear(152or153)basedontheISOstandard.
AD
A.D.
AM
A.M.
BC
B.C.
CC
SCC
DAY
DD
DDD
DY
EE
HH
HH12
HH24
IW
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
56/73
1/1/2017
Operators,Functions,Expressions,Conditions
IYY
IY
I
No
Last3,2,or1digit(s)ofISOyear.
No
4digityearbasedontheISOstandard.
Yes
JuliandaythenumberofdayssinceJanuary1,4712BC.Numberspecifiedwith
'J'mustbeintegers.
Yes
Minute(059).
Yes
Month(0112JAN=01)
Yes
Abbreviatednameofmonth.
Yes
Nameofmonth,paddedwithblankstolengthof9characters.
No
Meridianindicatorwithorwithoutperiods.
No
Quarterofyear(1,2,3,4JANMAR=1)
Yes
Romannumeralmonth(IXIIJAN=I).
Yes
Givenayearwith2digits,returnsayearinthenextcenturyiftheyearis<50and
thelast2digitsofthecurrentyearare>=50returnsayearinthepreceding
centuryiftheyearis>=50andthelast2digitsofthecurrentyearare<50.
Yes
Roundyear.Acceptseither4digitor2digitinput.If2digit,providesthesame
returnasRR.Ifyoudon'twantthisfunctionality,simplyenterthe4digityear.
Yes
Second(059).
Yes
Secondspastmidnight(086399).
No
Weekofyear(153)whereweek1startsonthefirstdayoftheyearandcontinues
totheseventhdayoftheyear.
No
Weekofmonth(15)whereweek1startsonthefirstdayofthemonthandends
ontheseventh.
Yes
Yearwithcommainthisposition.
No
Year,spelledout"S"prefixesBCdateswith"".
IYYY
MI
MM
MON
MONTH
PM
P.M.
RM
RR
RRRR
SS
SSSSS
WW
Y,YYY
YEAR
SYEAR
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
57/73
1/1/2017
Operators,Functions,Expressions,Conditions
YYYY
SYYYY
Yes
4digityear"S"prefixesBCdateswith"".
Yes
Last3,2,or1digit(s)ofyear.
YYY
YY
Y
Oraclereturnsanerrorifanalphanumericcharacterisfoundinthedatestringwherepunctuationcharacteris
foundintheformatstring.Forexample:
TO_CHAR(TO_DATE('0297','MM/YY'),'MM/YY')
returnsanerror.
DateFormatElementsandNationalLanguageSupport
Thefunctionalityofsomedateformatelementsdependsonthecountryandlanguageinwhichyouareusing
Oracle.Forexample,thesedateformatelementsreturnspelledvalues:
MONTH
MON
DAY
DY
BCorADorB.C.orA.D.
AMorPMorA.MorP.M.
Thelanguageinwhichthesevaluesarereturnedisspecifiedeitherexplicitlywiththeinitializationparameter
NLS_DATE_LANGUAGEorimplicitlywiththeinitializationparameterNLS_LANGUAGE.Thevalues
returnedbytheYEARandSYEARdateformatelementsarealwaysinEnglish.
ThedateformatelementDreturnsthenumberofthedayoftheweek(17).Thedayoftheweekthatis
numbered1isspecifiedimplicitlybytheinitializationparameterNLS_TERRITORY.
Forinformationontheseinitializationparameters,seeOracle8Reference.
ISOStandardDateFormatElements
OraclecalculatesthevaluesreturnedbythedateformatelementsIYYY,IYY,IY,I,andIWaccordingtothe
ISOstandard.Forinformationonthedifferencesbetweenthesevaluesandthosereturnedbythedateformat
elementsYYYY,YYY,YY,Y,andWW,seethediscussionofnationallanguagesupportinOracle8
Reference.
TheRRDateFormatElement
TheRRdateformatelementissimilartotheYYdateformatelement,butitprovidesadditionalflexibility
forstoringdatevaluesinothercenturies.TheRRdateformatelementallowsyoutostore21stcenturydates
inthe20thcenturybyspecifyingonlythelasttwodigitsoftheyear.Itwillalsoallowyoutostore20th
centurydatesinthe21stcenturyinthesamewayifnecessary.
IfyouusetheTO_DATEfunctionwiththeYYdateformatelement,thedatevaluereturnedisalwaysinthe
currentcentury.IfyouusetheRRdateformatelementinstead,thecenturyofthereturnvaluevaries
accordingtothespecifiedtwodigityearandthelasttwodigitsofthecurrentyear.Table316summarizes
thebehavioroftheRRdateformatelement.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
58/73
1/1/2017
Operators,Functions,Expressions,Conditions
Table316TheRRDateElementFormat
Ifthespecifiedtwodigityearis
049
Ifthelasttwodigitsofthe
currentyearare:
5099
049 Thereturndateisinthe
currentcentury.
Thereturndateisinthe
precedingcentury.
50
99
Thereturndateisinthecurrent
century.
Thereturndateisinthenext
century.
ThefollowingexampledemonstratesthebehavioroftheRRdateformatelement.
Example1
Assumethesequeriesareissuedbetween1950and1999:
SELECTTO_CHAR(TO_DATE('27OCT95','DDMONRR'),'YYYY')"Year"
FROMDUAL;
Year
1995
SELECTTO_CHAR(TO_DATE('27OCT17','DDMONRR'),'YYYY')"Year";
FROMDUAL;
Year
2017
Example2
Assumethesequeriesareissuedbetween2000and2049:
SELECTTO_CHAR(TO_DATE('27OCT95','DDMONRR'),'YYYY')"Year";
FROMDUAL;
Year
1995
SELECTTO_CHAR(TO_DATE('27OCT17','DDMONRR'),'YYYY')"Year";
FROMDUAL;
Year
2017
Notethatthequeriesreturnthesamevaluesregardlessofwhethertheyareissuedbeforeoraftertheyear
2000.TheRRdateformatelementallowsyoutowriteSQLstatementsthatwillreturnthesamevaluesafter
theturnofthecentury.
DateFormatElementSuffixes
Table317listssuffixesthatcanbeaddedtodateformatelements:
Table317DateFormatElementSuffixes
Suffix
Meaning
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
ExampleElement
ExampleValue
59/73
1/1/2017
Operators,Functions,Expressions,Conditions
TH
OrdinalNumber
DDTH
4TH
SP
SpelledNumber
DDSP
FOUR
SPTHorTHSP
Spelled,ordinalnumber
DDSPTH
FOURTH
Whenyouaddoneofthesesuffixestoadateformatelement,thereturnvalueisalwaysinEnglish.
Note:
Datesuffixesarevalidonlyonoutputandcannotbeusedtoinsertadateintothe
database.
CapitalizationofDateFormatElements
Capitalizationinaspelledoutword,abbreviation,orRomannumeralfollowscapitalizationinthe
correspondingformatelement.Forexample,thedateformatmodel'DAY'producescapitalizedwordslike
'MONDAY''Day'produces'Monday'and'day'produces'monday'.
PunctuationandCharacterLiteralsinDateFormatModels
Youcanalsoincludethesecharactersinadateformatmodel:
punctuationsuchashyphens,slashes,commas,periods,andcolons
characterliterals,enclosedindoublequotationmarks
Thesecharactersappearinthereturnvalueinthesamelocationastheyappearintheformatmodel.
FormatModelModifiers
YoucanusetheFMandFXmodifiersinformatmodelsfortheTO_CHARfunctiontocontrolblankpadding
andexactformatchecking.
Amodifiercanappearinaformatmodelmorethanonce.Insuchacase,eachsubsequentoccurrencetoggles
theeffectsofthemodifier.Itseffectsareenabledfortheportionofthemodelfollowingitsfirstoccurrence,
andthendisabledfortheportionfollowingitssecond,andthenreenabledfortheportionfollowingitsthird,
andsoon.
FM
"Fillmode".ThismodifiersuppressesblankpaddinginthereturnvalueoftheTO_CHARfunction:
InadateformatelementofaTO_CHARfunction,thismodifiersuppressesblanksinsubsequent
characterelements(suchasMONTH)andsuppressesleadingandtrailingzeroesforsubsequent
numberelements(suchasMI)inadateformatmodel.WithoutFM,theresultofacharacterelementis
alwaysrightpaddedwithblankstoafixedlength,andleadingzeroesarealwaysreturnedforanumber
element.WithFM,becausethereisnoblankpadding,thelengthofthereturnvaluemayvary
InanumberformatelementofaTO_CHARfunction,thismodifiersuppressesblanksaddedtotheleft
ofthenumber,sothattheresultisleftjustifiedintheoutputbuffer.WithoutFM,theresultisalways
rightjustifiedinthebuffer,resultinginblankpaddingtotheleftofthenumber.
FX
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
60/73
1/1/2017
Operators,Functions,Expressions,Conditions
"Formatexact".Thismodifierspecifiesexactmatchingforthecharacterargumentanddateformatmodelof
aTO_DATEfunction:
Punctuationandquotedtextinthecharacterargumentmustexactlymatch(exceptforcase)the
correspondingpartsoftheformatmodel.
Thecharacterargumentcannothaveextrablanks.WithoutFX,Oracleignoresextrablanks.
Numericdatainthecharacterargumentmusthavethesamenumberofdigitsasthecorresponding
elementintheformatmodel.WithoutFX,numbersinthecharacterargumentcanomitleadingzeroes.
WhenFXisenabled,youcandisablethischeckforleadingzeroesbyusingtheFMmodifieraswell.
Ifanyportionofthecharacterargumentviolatesanyoftheseconditions,Oraclereturnsanerrormessage.
Example1
Thefollowingstatementusesadateformatmodeltoreturnacharacterexpression:
SELECTTO_CHAR(SYSDATE,'fmDDTH')||'of'||TO_CHAR
(SYSDATE,'Month')||','||TO_CHAR(SYSDATE,'YYYY')"Ides"
FROMDUAL;
Ides
3RDofApril,1995
NotethatthestatementabovealsousestheFMmodifier.IfFMisomitted,themonthisblankpaddedtonine
characters:
SELECTTO_CHAR(SYSDATE,'DDTH')||'of'||
TO_CHAR(Month,YYYY')"Ides"
FROMDUAL;
Ides
03RDofApril,1995
Example2
Thefollowingstatementplacesasinglequotationmarkinthereturnvaluebyusingadateformatmodelthat
includestwoconsecutivesinglequotationmarks:
SELECTTO_CHAR(SYSDATE,'fmDay')||'''sSpecial')"Menu"
FROMDUAL;
Menu
Tuesday'sSpecial
Twoconsecutivesinglequotationmarkscanbeusedforthesamepurposewithinacharacterliteralina
formatmodel.
Example3
Table318showswhetherthefollowingstatementmeetsthematchingconditionsfordifferentvaluesofchar
and'fmt'usingFX:
UPDATEtable
SETdate_column=TO_DATE(char,'fmt');
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
61/73
1/1/2017
Operators,Functions,Expressions,Conditions
Table318MatchingCharacterDataandFormatModelswiththeFXFormatModelModifier
char
'fmt'
MatchorError?
'15/JAN/1993'
'DDMONYYYY'
Match
'15!JAN%/1993'
'DDMONYYYY'
'15/JAN/1993'
'FXDDMONYYYY'
'15JAN1993'
'FXDDMONYYYY'
'1JAN1993'
'FXDDMONYYYY'
'01JAN1993'
'FXDDMONYYYY'
'1JAN1993'
'FXFMDDMONYYYY'
Error
Error
Match
Error
Match
Match
StringtoDateConversionRules
Thefollowingadditionalformattingrulesapplywhenconvertingstringvaluestodatevalues:
Youcanomitpunctuationincludedintheformatstringfromthedatestringifallthedigitsofthe
numericalformatelements,includingleadingzeros,arespecified.Inotherwords,specify02andnot2
fortwodigitformatelementssuchasMM,DD,andYY.
Youcanomittimefieldsfoundattheendofaformatstringfromthedatestring.
Ifamatchfailsbetweenadateformatelementandthecorrespondingcharactersinthedatestring,
Oracleattemptsalternativeformatelements,asshowninTable319.
Table319OracleFormatMatching
OriginalFormatElement AdditionalFormatElementstoTryinPlaceoftheOriginal
'MM'
'MON'and'MONTH'
'MON
'MONTH'
'MONTH'
'MON'
'YY'
'YYYY'
'RR'
'RRRR'
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
62/73
1/1/2017
Operators,Functions,Expressions,Conditions
Expressions
Anexpressionisacombinationofoneormorevalues,operators,andSQLfunctionsthatevaluatetoavalue.
Anexpressiongenerallyassumesthedatatypeofitscomponents.
Thissimpleexpressionevaluatesto4andhasdatatypeNUMBER(thesamedatatypeasitscomponents):
2*2
Thefollowingexpressionisanexampleofamorecomplexexpressionthatusesbothfunctionsand
operators.Theexpressionaddssevendaystothecurrentdate,removesthetimecomponentfromthesum,
andconvertstheresulttoCHARdatatype:
TO_CHAR(TRUNC(SYSDATE+7))
Youcanuseexpressionsin
theselectlistoftheSELECTcommand
aconditionoftheWHEREandHAVINGclauses
theCONNECTBY,STARTWITH,andORDERBYclauses
theVALUESclauseoftheINSERTcommand
theSETclauseoftheUPDATEcommand
Forexample,youcoulduseanexpressioninplaceofthequotedstring'smith'inthisUPDATEstatement
SETclause:
SETename='smith';
ThisSETclausehastheexpressionLOWER(ename)insteadofthequotedstring'smith':
SETename=LOWER(ename)
Expressionshaveseveralforms.OracledoesnotacceptallformsofexpressionsinallpartsofallSQL
commands.Youmustuseappropriateexpressionnotationwheneverexprappearsinconditions,SQL
functions,orSQLcommandsinotherpartsofthisreference.ThedescriptionofeachcommandinChapter4,
"Commands",documentstherestrictionsontheexpressionsinthecommand.Thesectionsthatfollow
describeandprovideexamplesofthevariousformsofexpressions.
FormI
AFormIexpressionspecifiescolumn,pseudocolumn,constant,sequencenumber,orNULL.
Inadditiontotheschemaofauser,schemacanalsobe"PUBLIC"(doublequotationmarksrequired),in
whichcaseitmustqualifyapublicsynonymforatable,view,orsnapshot.Qualifyingapublicsynonym
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
63/73
1/1/2017
Operators,Functions,Expressions,Conditions
with"PUBLIC"issupportedonlyindatamanipulationlanguage(DML)commands,notdatadefinition
language(DDL)commands.
ThepseudocolumncanbeeitherLEVEL,ROWID,orROWNUM.Youcanuseapseudocolumnonlywitha
table,notwithavieworsnapshot.NCHARandNVARCHAR2arenotvalidpseudocolumnorROWLABEL
datatypes.Formoreinformationonpseudocolumns,see"Pseudocolumns".
IfyouarenotusingTrustedOracle,theexpressionROWLABELalwaysreturnsNULL.Forinformationon
usinglabelsandROWLABEL,seeyourTrustedOracledocumentation.
SomevalidFormIexpressionsare:
emp.ename
'thisisatextstring'
10
N'thisisanNCHARstring'
FormII
AFormIIexpressionspecifiesahostvariablewithanoptionalindicatorvariable.Notethatthisformof
expressioncanonlyappearinembeddedSQLstatementsorSQLstatementsprocessedinanOracleCall
Interface(OCI)program.
SomevalidFormIIexpressionsare:
:employee_nameINDICATOR:employee_name_indicator_var
:department_location
FormIII
AFormIIIexpressionspecifiesacalltoaSQLfunctionoperatingonasinglerow.
SomevalidFormIIIexpressionsare:
LENGTH('BLAKE')
ROUND(1234.567*43)
SYSDATE
ForinformationonSQLfunctions,see"SQLFunctions".
FormIV
AFormIVexpressionspecifiesacalltoauserfunction
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
64/73
1/1/2017
Operators,Functions,Expressions,Conditions
SomevalidFormIVexpressionsare:
circle_area(radius)
payroll.tax_rate(empno)
scott.payrol.tax_rate(dependents,empno)@ny
Forinformationonuserfunctions,see"UserFunctions".
FormV
AFormVexpressionspecifiesacombinationofotherexpressions.
Notethatsomecombinationsoffunctionsareinappropriateandarerejected.Forexample,theLENGTH
functionisinappropriatewithinagroupfunction.
SomevalidFormVexpressionsare:
('CLARK'||'SMITH')
LENGTH('MOOSE')*57
SQRT(144)+72
my_fun(TO_CHAR(sysdate,'DDMMMYY')
FormVI
AFormVIexpressionspecifiesacalltoatypeconstructor.
Iftype_nameisanobjecttype,thenthetypeargumentlistmustbeanorderedlistofarguments,wherethe
firstargumentisavaluewhosetypematchesthefirstattributeoftheobjecttype,thesecondargumentisa
valuewhosetypematchesthesecondattributeoftheobjecttype,andsoon.Thetotalnumberofarguments
totheconstructormustmatchthetotalnumberofattributesoftheobjecttypethemaximumnumberof
argumentsis999.
Iftype_nameisaVARRAYornestedtabletype,thentheargumentlistcancontainzeroormorearguments.
Zeroargumentsimplyconstructionofanemptycollection.Otherwise,eachargumentcorrespondstoan
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
65/73
1/1/2017
Operators,Functions,Expressions,Conditions
elementvaluewhosetypeistheelementtypeofthecollectiontype.
Whethertype_nameisanobjecttype,aVARRAY,oranestedtabletype,themaximumnumberofarguments
itcancontainis999.
Example
CREATETYPEaddress_tASOBJECT
(noNUMBER,streetCHAR(31),cityCHAR(21),stateCHAR(3),zipNUMBER);
CREATETYPEaddress_book_tASTABLEOFaddress_t;
DECLARE
/*ObjectTypevariableinitializedviaObjectTypeConstructor*/
myaddraddress_t=address_t(500,'OracleParkway','RedwoodShores',
'CA',94065);
/*nestedtablevariableinitializedtoanemptytableviaa
constructor*/
alladdraddress_book_t=address_book_t();
BEGIN
/*belowisanexampleofanestedtableconstructorwithtwoelements
specified,whereeachelementisspecifiedasanobjecttype
constructor.*/
insertintoemployeevalues(666999,address_book_t(address_t(500,
'OracleParkway','RedwoodShores','CA',94065),address_t(400,
'MissionStreet','Fremont','CA',94555)));
END;
FormVII
AFormVIIexpressionconvertsonecollectiontypedvalueintoanothercollectiontypedvalue.
CASTallowsyoutoconvertcollectiontypedvaluesofonetypeintoanothercollectiontype.Youcancastan
unnamedcollection(suchastheresultsetofasubquery)oranamedcollection(suchasaVARRAYora
nestedtable)intoatypecompatiblenamedcollection.Thetype_namemustbethenameofacollectiontype
andtheoperandmustevaluatetoacollectionvalue.
Tocastanamedcollectiontypeintoanothernamedcollectiontype,theelementsofbothcollectionsmustbe
ofthesametype.
Iftheresultsetofsubquerycanevaluatetomultiplerows,youmustspecifytheMULTISETkeyword.The
rowsresultingfromthesubqueryformtheelementsofthecollectionvalueintowhichtheyarecast.Without
theMULTISETkeyword,thesubqueryistreatedasascalarsubquery,whichisnotsupportedintheCAST
expression.Inotherwords,scalarsubqueriesasargumentsoftheCASToperatorarenotvalidinOracle8.
TheCASTexamplesthatfollowusethefollowinguserdefinedtypesandtables:
CREATETYPEaddress_tASOBJECT
(noNUMBER,streetCHAR(31),cityCHAR(21),stateCHAR(2));
CREATETYPEaddress_book_tASTABLEOFaddress_t;
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
66/73
1/1/2017
Operators,Functions,Expressions,Conditions
CREATETYPEaddress_array_tASVARRAY(3)OFaddress_t;
CREATETABLEemp_address(empnoNUMBER,noNUMBER,streetCHAR(31),
cityCHAR(21),stateCHAR(2));
CREATETABLEemployees(empnoNUMBER,nameCHAR(31));
CREATETABLEdept(dnoNUMBER,addressesaddress_array_t);
Example1
CASTasubquery:
SELECTe.empno,e.name,CAST(MULTISET(SELECTea.no,ea.street,
ea.city,ea.state
FROMemp_addressea
WHEREea.empno=e.empno)
ASaddress_book_t)
FROMemployeese;
Example2
CASTconvertsaVARRAYtypecolumnintoanestedtable.Thetablevaluesaregeneratedbyaflattened
subquery.See"UsingFlattenedSubqueries".
SELECT*
FROMTHE(SELECTCAST(d.addressesASaddress_book_t)
FROMdeptd
WHEREd.dno=111)a
WHEREa.city='RedwoodShores';
Example3
ThefollowingexamplecastsaMULTISETexpressionwithanORDERBYclause:
CREATETABLEprojects(empidNUMBER,projnameVARCHAR2(10));
CREATETABLEemployees(empidNUMBER,enameVARCHAR2(10));
CREATETYPEprojname_table_typeASTABLEOFVARCHAR2(10);
AnexampleofaMULTISETexpressionwiththeaboveschemais:
SELECTe.name,CAST(MULTISET(SELECTp.projname
FROMprojectsp
WHEREp.empid=e.empid
ORDERBYp.projname)
ASprojname_table_type)
FROMemployeese;
FormVIII
AFormVIIIexpressionreturnsanestedCURSOR.ThisformofexpressionissimilartothePL/SQLREF
cursor.
Anestedcursorisimplicitlyopenedwhenthecontainingrowisfetchedfromtheparentcursor.Thenested
cursorisclosedonlywhen
explicitlyclosedbytheuser
theparentcursorisreexecuted
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
67/73
1/1/2017
Operators,Functions,Expressions,Conditions
theparentcursorisclosed
theparentcursoriscancelled
anerrorarisesduringfetchononeofitsparentcursors(itisclosedaspartofthecleanup)
ThefollowingrestrictionsapplytotheCURSORexpression:
NestedcursorscanappearonlyinaSELECTstatementthatisnotnestedinanyotherquery
expression,exceptwhenitisasubqueryoftheCURSORexpressionitself.
NestedcursorscanappearonlyintheoutermostSELECTlistofthequeryspecification.
Nestedcursorscannotappearinviews.
YoucannotperformBINDandEXECUTEoperationsonnestedcursors.
Example
SELECTd.deptno,CURSOR(SELECTe.empno,CURSOR(SELECTp.projnum,
p.projname
FROMprojectsp
WHEREp.empno=e.empno)
FROMTABLE(d.employees)e)
FROMdeptd
WHEREd.dno=605;
FormIX
AFormIXexpressionconstructsareferencetoanobject.
InaSQLstatement,REFtakesasitsargumentatablealiasassociatedwitharowofanobjecttableoran
objectview.AREFvalueisreturnedfortheobjectinstancethatisboundtothevariableorrow.Formore
informationaboutREFs,seeOracle8Concepts.
Example1
SELECTREF(e)
FROMemployee_te
WHEREe.empno=10000;
Example2
ThisexampleusesREFinapredicate:
SELECTe.name
FROMemployee_t
eINTO:x
WHEREREF(e)=empref1;
FormX
AFormXexpressionreturnstherowobject.
InaSQLstatement,VALUEtakesasitsargumentacorrelationvariable(tablealias)associatedwitharowof
anobjecttable.
Example
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
68/73
1/1/2017
Operators,Functions,Expressions,Conditions
SELECTVALUE(e)
FROMemployeee
WHEREe.name='JohnSmith';
FormXI
AFormXIexpressionspecifiesattributereferenceandmethodinvocation.
expr_form_XI::=
ThecolumnparametercanbeanobjectorREFcolumn.Examplesinthissectionusethefollowinguser
definedtypesandtables:
CREATEORREPLACETYPEemployee_tASOBJECT
(empidNUMBER,
nameCHAR(31),
birthdateDATE,
MEMBERFUNCTIONageRETURNNUMBER,
PRAGMARESTRICTREFERENCES(age,RNPS,WNPS,WNDS)
);
CREATEORREPLACETYPEBODYemployee_tAS
MEMBERFUNCTIONageRETURNNUMBERIS
varNUMBER;
BEGIN
var:=months_between(ROUND(SYSDATE,'YEAR'),
ROUND(birthdate,'YEAR'))/12;
RETURN(var);
END;
END;/
CREATETABLEdepartment(dnoNUMBER,managerEMPLOYEE_T);
Examples
Thefollowingexamplesupdateandselectfromtheobjectcolumnsandmethoddefinedabove.
UPDATEdepartmentd
SETd.manager.empid=100;
SELECTd.manager.name,d.manager.age()
FROMdepartmentd;
DecodedExpression
AdecodedexpressionusesthespecialDECODEsyntax:
Toevaluatethisexpression,Oraclecomparesexprtoeachsearchvalueonebyone.Ifexprisequaltoa
search,Oraclereturnsthecorrespondingresult.Ifnomatchisfound,Oraclereturnsdefault,or,ifdefaultis
omitted,returnsnull.Ifexprandsearchcontaincharacterdata,Oraclecomparesthemusingnonpadded
comparisonsemantics.Forinformationonthesesemantics,seethesection"DatatypeComparisonRules".
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
69/73
1/1/2017
Operators,Functions,Expressions,Conditions
Thesearch,result,anddefaultvaluescanbederivedfromexpressions.Oracleevaluateseachsearchvalue
onlybeforecomparingittoexpr,ratherthanevaluatingallsearchvaluesbeforecomparinganyofthemwith
expr.Consequently,Oracleneverevaluatesasearchifaprevioussearchisequaltoexpr.
Oracleautomaticallyconvertsexprandeachsearchvaluetothedatatypeofthefirstsearchvaluebefore
comparing.Oracleautomaticallyconvertsthereturnvaluetothesamedatatypeasthefirstresult.Ifthefirst
resulthasthedatatypeCHARorifthefirstresultisnull,thenOracleconvertsthereturnvaluetothe
datatypeVARCHAR2.Forinformationondatatypeconversion,see"DataConversion".
InaDECODEexpression,Oracleconsiderstwonullstobeequivalent.Ifexprisnull,Oraclereturnsthe
resultofthefirstsearchthatisalsonull.
ThemaximumnumberofcomponentsintheDECODEexpression,includingexpr,searches,results,and
defaultis255.
Example
ThisexpressiondecodesthevalueDEPTNO.IfDEPTNOis10,theexpressionevaluatesto
'ACCOUNTING'ifDEPTNOis20,itevaluatesto'RESEARCH'etc.IfDEPTNOisnot10,20,30,or40,
theexpressionreturns'NONE'.
DECODE(deptno,10,'ACCOUNTING',
20,'RESEARCH',
30,'SALES',
40,'OPERATION',
'NONE')
ListofExpressions
Alistofexpressionsisaparenthesizedseriesofexpressionsseparatedbyacomma.
Anexpressionlistcancontainupto1000expressions.Somevalidexpressionlistsare:
10,20,40)
('SCOTT','BLAKE','TAYLOR')
(LENGTH('MOOSE')*57,SQRT(144)+72,69)
Conditions
Aconditionspecifiesacombinationofoneormoreexpressionsandlogicaloperatorsthatevaluatestoeither
TRUE,FALSE,orunknown.YoumustusethissyntaxwheneverconditionappearsinSQLcommandsin
Chapter4,"Commands".
YoucanuseaconditionintheWHEREclauseofthesestatements:
DELETE
SELECT
UPDATE
YoucanuseaconditioninanyoftheseclausesoftheSELECTcommand:
WHERE
STARTWITH
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
70/73
1/1/2017
Operators,Functions,Expressions,Conditions
CONNECTBY
HAVING
Aconditioncouldbesaidtobeofthe"logical"datatype,althoughOracledoesnotformallysupportsucha
datatype.
ThefollowingsimpleconditionalwaysevaluatestoTRUE:
1=1
ThefollowingmorecomplexconditionaddstheSALvaluetotheCOMMvalue(substitutingthevalue0for
null)anddetermineswhetherthesumisgreaterthanthenumberconstant2500:
NVL(sal,0)+NVL(comm,0)>2500
Logicaloperatorscancombinemultipleconditionsintoasinglecondition.Forexample,youcanusethe
ANDoperatortocombinetwoconditions:
(1=1)AND(5<7)
Herearesomevalidconditions:
name='SMITH'
emp.deptno=dept.deptno
hiredate>'01JAN88'
jobIN('PRESIDENT','CLERK','ANALYST')
salBETWEEN500AND1000
commISNULLANDsal=2000
Conditionscanhaveseveralforms.ThedescriptionofeachcommandinChapter4,"Commands",
documentstherestrictionsontheconditionsinthecommand.Thesectionsthatfollowdescribethevarious
formsofconditions.
FormI
AFormIconditionspecifiesacomparisonwithexpressionsorsubqueryresults.
Forinformationoncomparisonoperators,see"ComparisonOperators".
FormII
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
71/73
1/1/2017
Operators,Functions,Expressions,Conditions
AFormIIconditionspecifiesacomparisonwithanyorallmembersinalistorsubquery.
See"Subqueries".
FormIII
AFormIIIconditiontestsformembershipinalistorsubquery.
FormIV
AFormIVconditiontestsforinclusioninarange.
FormV
AFormVconditiontestsfornulls.
FormVI
AFormVIconditiontestsforexistenceofrowsinasubquery.
FormVII
AFormVIIconditionspecifiesatestinvolvingpatternmatching.
FormVIII
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
72/73
1/1/2017
Operators,Functions,Expressions,Conditions
AFormVIIIconditionspecifiesacombinationofotherconditions.
Prev
Next
Copyright1997OracleCorporation.
AllRightsReserved.
https://docs.oracle.com/cd/A58617_01/server.804/a58225/ch3all.htm
73/73