SlideShare a Scribd company logo
Oracle® Database
SQL Language Reference
11g Release 2 (11.2)
E10592-03
September 2009
Oracle Database SQL Language Reference, 11g Release 2 (11.2)
E10592-03
Copyright © 1996, 2009, Oracle and/or its affiliates. All rights reserved.
Primary Authors: Diana Lorentz, Mary Beth Roeser
Contributors: Sundeep Abraham, Angela Amor, Geeta Arora, Vikas Arora, Lance Ashdown, Hermann
Baer, Shrikanth Bellamkonda, Donna Carver, Dan Chiba, Timothy Chien, Alan Choi, Thierry Cruanes,
George Eadon, Amit Ganesh, Barb Glover, Naveen Gopal, Mike Hallas, Min-Hank Ho, Chandrasekharan
Iyer, Mark Jaeger, Vikram Kapoor, Peter Knaggs, Srinath Krishnaswamy, Andre Kruglikov, Paul Lane,
Huagang Li, Yunrui Li, Vince Liang, Bryn Llewellyn, Rich Long, Scott Lynn, Vineet Marwah, Jun
Matsuzawa, Robert McGuirk, Rahil Mir, Gopal Mulagund, Sujatha Muthulingam, Hanlin Qian, Ashish Ray,
John Russell, Laurent Schneider, Vivian Schupmann, Jia Shi, Ajeet Singh, Wayne Smith, Shanshan Song,
Vinay Srihari, Jim Stenoish, Sankar Subramanian, Seema Sundara, Mark van de Wiel, Badhri Varanasi,
William Waddington, Peter Wahl, Charles Wetherell, Sergiusz Wolicki, Daniel Wong, Tsae-feng Yu,
Mohamed Zait, Fred Zemke, Wei Zhang, Weiran Zhang
This software and related documentation are provided under a license agreement containing restrictions on
use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your
license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license,
transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse
engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is
prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If
you find any errors, please report them to us in writing.
If this software or related documentation is delivered to the U.S. Government or anyone licensing it on
behalf of the U.S. Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data
delivered to U.S. Government customers are "commercial computer software" or "commercial technical data"
pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As
such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and
license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of
the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software
License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
This software is developed for general use in a variety of information management applications. It is not
developed or intended for use in any inherently dangerous applications, including applications which may
create a risk of personal injury. If you use this software in dangerous applications, then you shall be
responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use
of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of
this software in dangerous applications.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks
of their respective owners.
This software and documentation may provide access to or information on content, products, and services
from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all
warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and
its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of
third-party content, products, or services.
iii
Contents
Preface............................................................................................................................................................... xxi
Audience..................................................................................................................................................... xxi
Documentation Accessibility................................................................................................................... xxi
Related Documents .................................................................................................................................. xxii
Conventions .............................................................................................................................................. xxii
What's New in the SQL Language Reference?....................................................................... xxiii
Oracle Database 11g Release 2 New Features in the SQL Language Reference............................. xxiii
Oracle Database 11g Release 1 New Features in the SQL Language Reference............................. xxv
1 Introduction to Oracle SQL
History of SQL ......................................................................................................................................... 1-1
SQL Standards ......................................................................................................................................... 1-1
How SQL Works ............................................................................................................................... 1-2
Common Language for All Relational Databases ......................................................................... 1-2
Using Enterprise Manager ..................................................................................................................... 1-3
Lexical Conventions................................................................................................................................. 1-3
Tools Support ........................................................................................................................................... 1-3
2 Pseudocolumns
Hierarchical Query Pseudocolumns .................................................................................................... 2-1
CONNECT_BY_ISCYCLE Pseudocolumn .................................................................................... 2-1
CONNECT_BY_ISLEAF Pseudocolumn ....................................................................................... 2-2
LEVEL Pseudocolumn ...................................................................................................................... 2-2
Sequence Pseudocolumns ..................................................................................................................... 2-3
Where to Use Sequence Values ....................................................................................................... 2-3
How to Use Sequence Values .......................................................................................................... 2-4
Version Query Pseudocolumns ............................................................................................................ 2-6
COLUMN_VALUE Pseudocolumn ...................................................................................................... 2-6
OBJECT_ID Pseudocolumn .................................................................................................................. 2-7
OBJECT_VALUE Pseudocolumn .......................................................................................................... 2-8
iv
ORA_ROWSCN Pseudocolumn ........................................................................................................... 2-8
ROWID Pseudocolumn .......................................................................................................................... 2-9
ROWNUM Pseudocolumn .................................................................................................................... 2-9
XMLDATA Pseudocolumn ................................................................................................................. 2-10
3 Basic Elements of Oracle SQL
Data Types ................................................................................................................................................ 3-1
Oracle Built-in Data Types................................................................................................................ 3-6
CHAR Data Type ....................................................................................................................... 3-9
NCHAR Data Type .................................................................................................................... 3-9
NVARCHAR2 Data Type ......................................................................................................... 3-9
VARCHAR2 Data Type ......................................................................................................... 3-10
VARCHAR Data Type ........................................................................................................... 3-10
NUMBER Data Type .............................................................................................................. 3-10
FLOAT Data Type.................................................................................................................... 3-12
Floating-Point Numbers ........................................................................................................ 3-12
BINARY_FLOAT .............................................................................................................. 3-13
BINARY_DOUBLE........................................................................................................... 3-13
Numeric Precedence ............................................................................................................... 3-14
DATE Data Type ..................................................................................................................... 3-17
Using Julian Days ............................................................................................................. 3-17
TIMESTAMP Data Type ........................................................................................................ 3-18
TIMESTAMP WITH TIME ZONE Data Type .................................................................... 3-18
TIMESTAMP WITH LOCAL TIME ZONE Data Type ..................................................... 3-19
INTERVAL YEAR TO MONTH Data Type ........................................................................ 3-19
INTERVAL DAY TO SECOND Data Type ......................................................................... 3-20
Datetime/Interval Arithmetic ............................................................................................... 3-20
Support for Daylight Saving Times ...................................................................................... 3-22
Datetime and Interval Examples ........................................................................................... 3-23
RAW and LONG RAW Data Types ..................................................................................... 3-24
BFILE Data Type ..................................................................................................................... 3-26
BLOB Data Type ...................................................................................................................... 3-26
CLOB Data Type ..................................................................................................................... 3-26
NCLOB Data Type .................................................................................................................. 3-27
Rowid Data Types .......................................................................................................................... 3-27
ROWID Data Type .................................................................................................................. 3-27
UROWID Data Type ............................................................................................................... 3-28
ANSI, DB2, and SQL/DS Data Types ......................................................................................... 3-28
User-Defined Types ....................................................................................................................... 3-30
Object Types ............................................................................................................................ 3-30
REF Data Types ....................................................................................................................... 3-30
Varrays ...................................................................................................................................... 3-31
Nested Tables .......................................................................................................................... 3-31
Oracle-Supplied Types .................................................................................................................. 3-31
Any Types ....................................................................................................................................... 3-32
ANYTYPE ................................................................................................................................. 3-32
ANYDATA................................................................................................................................ 3-32
v
ANYDATASET......................................................................................................................... 3-32
XML Types ...................................................................................................................................... 3-32
XMLType .................................................................................................................................. 3-32
URI Data Types ....................................................................................................................... 3-33
URIFactory Package ................................................................................................................ 3-34
Spatial Types ................................................................................................................................... 3-34
SDO_GEOMETRY ................................................................................................................... 3-34
SDO_TOPO_GEOMETRY ..................................................................................................... 3-34
SDO_GEORASTER.................................................................................................................. 3-35
Media Types .................................................................................................................................... 3-35
ORDAudio ............................................................................................................................... 3-35
ORDImage ................................................................................................................................ 3-35
ORDVideo ................................................................................................................................ 3-35
ORDDoc ................................................................................................................................... 3-35
ORDDicom ............................................................................................................................... 3-36
SI_StillImage ............................................................................................................................ 3-36
SI_Color .................................................................................................................................... 3-36
SI_AverageColor ..................................................................................................................... 3-36
SI_ColorHistogram ................................................................................................................. 3-36
SI_PositionalColor .................................................................................................................. 3-36
SI_Texture ................................................................................................................................ 3-36
SI_FeatureList .......................................................................................................................... 3-36
ORDImageSignature ............................................................................................................... 3-36
Expression Filter Type.................................................................................................................... 3-36
Expression................................................................................................................................. 3-37
Data Type Comparison Rules ............................................................................................................ 3-37
Numeric Values .............................................................................................................................. 3-37
Date Values ..................................................................................................................................... 3-37
Character Values ............................................................................................................................ 3-37
Object Values .................................................................................................................................. 3-40
Varrays and Nested Tables ........................................................................................................... 3-40
Data Type Precedence .................................................................................................................... 3-40
Data Conversion ............................................................................................................................. 3-40
Implicit and Explicit Data Conversion ................................................................................ 3-40
Implicit Data Conversion ....................................................................................................... 3-40
Implicit Data Conversion Examples...................................................................................... 3-43
Explicit Data Conversion ....................................................................................................... 3-43
Security Considerations for Data Conversion ............................................................................ 3-44
Literals .................................................................................................................................................... 3-45
Text Literals ..................................................................................................................................... 3-46
Numeric Literals ............................................................................................................................. 3-47
Integer Literals ......................................................................................................................... 3-47
NUMBER and Floating-Point Literals .................................................................................. 3-48
Datetime Literals ............................................................................................................................ 3-50
Interval Literals................................................................................................................................ 3-52
INTERVAL YEAR TO MONTH ............................................................................................ 3-53
INTERVAL DAY TO SECOND ............................................................................................. 3-54
vi
Format Models ...................................................................................................................................... 3-55
Number Format Models ................................................................................................................ 3-56
Number Format Elements ..................................................................................................... 3-57
Datetime Format Models .............................................................................................................. 3-59
Datetime Format Elements .................................................................................................... 3-60
Uppercase Letters in Date Format Elements ............................................................... 3-60
Punctuation and Character Literals in Datetime Format Models ............................. 3-60
Datetime Format Elements and Globalization Support .................................................... 3-64
ISO Standard Date Format Elements ................................................................................... 3-64
The RR Datetime Format Element ........................................................................................ 3-64
RR Datetime Format Examples....................................................................................... 3-65
Datetime Format Element Suffixes ....................................................................................... 3-65
Format Model Modifiers ............................................................................................................... 3-66
Format Model Examples......................................................................................................... 3-67
String-to-Date Conversion Rules ................................................................................................. 3-68
XML Format Model ....................................................................................................................... 3-69
Nulls ........................................................................................................................................................ 3-70
Nulls in SQL Functions .................................................................................................................. 3-70
Nulls with Comparison Conditions ............................................................................................ 3-71
Nulls in Conditions ........................................................................................................................ 3-71
Comments .............................................................................................................................................. 3-71
Comments Within SQL Statements ............................................................................................. 3-72
Comments on Schema and Nonschema Objects ....................................................................... 3-72
Hints ................................................................................................................................................. 3-73
Alphabetical Listing of Hints ........................................................................................................ 3-77
ALL_ROWS Hint .................................................................................................................... 3-77
APPEND Hint .......................................................................................................................... 3-78
APPEND_VALUES Hint ....................................................................................................... 3-78
CACHE Hint ............................................................................................................................ 3-79
CHANGE_DUPKEY_ERROR_INDEX Hint ....................................................................... 3-79
CLUSTER Hint ........................................................................................................................ 3-80
CURSOR_SHARING_EXACT Hint ..................................................................................... 3-80
DRIVING_SITE Hint .............................................................................................................. 3-80
DYNAMIC_SAMPLING Hint ............................................................................................... 3-81
FACT Hint ................................................................................................................................ 3-81
FIRST_ROWS Hint .................................................................................................................. 3-81
FULL Hint ................................................................................................................................ 3-82
HASH Hint .............................................................................................................................. 3-82
IGNORE_ROW_ON_DUPKEY_INDEX Hint ..................................................................... 3-83
INDEX Hint ............................................................................................................................. 3-83
INDEX_ASC Hint ................................................................................................................... 3-84
INDEX_COMBINE Hint ........................................................................................................ 3-84
INDEX_DESC Hint ................................................................................................................. 3-85
INDEX_FFS Hint ..................................................................................................................... 3-85
INDEX_JOIN Hint .................................................................................................................. 3-85
INDEX_SS Hint ....................................................................................................................... 3-86
INDEX_SS_ASC Hint ............................................................................................................. 3-86
vii
INDEX_SS_DESC Hint ........................................................................................................... 3-87
LEADING Hint ........................................................................................................................ 3-87
MERGE Hint ............................................................................................................................ 3-87
MODEL_MIN_ANALYSIS Hint ........................................................................................... 3-88
MONITOR Hint ...................................................................................................................... 3-88
NATIVE_FULL_OUTER_JOIN Hint .................................................................................... 3-88
NOAPPEND Hint ................................................................................................................... 3-89
NOCACHE Hint ..................................................................................................................... 3-89
NO_EXPAND Hint ................................................................................................................. 3-89
NO_FACT Hint ....................................................................................................................... 3-89
NO_INDEX Hint ..................................................................................................................... 3-90
NO_INDEX_FFS Hint ............................................................................................................ 3-90
NO_INDEX_SS Hint ............................................................................................................... 3-90
NO_MERGE Hint ................................................................................................................... 3-91
NO_MONITOR Hint .............................................................................................................. 3-91
NO_NATIVE_FULL_OUTER_JOIN Hint ............................................................................ 3-91
NO_PARALLEL Hint ............................................................................................................. 3-91
NOPARALLEL Hint................................................................................................................ 3-92
NO_PARALLEL_INDEX Hint .............................................................................................. 3-92
NOPARALLEL_INDEX Hint................................................................................................. 3-92
NO_PUSH_PRED Hint .......................................................................................................... 3-92
NO_PUSH_SUBQ Hint .......................................................................................................... 3-93
NO_PX_JOIN_FILTER Hint .................................................................................................. 3-93
NO_QUERY_TRANSFORMATION Hint ........................................................................... 3-93
NO_RESULT_CACHE Hint .................................................................................................. 3-93
NO_REWRITE Hint ................................................................................................................ 3-93
NOREWRITE Hint................................................................................................................... 3-94
NO_STAR_TRANSFORMATION Hint ............................................................................... 3-94
NO_UNNEST Hint ................................................................................................................. 3-94
NO_USE_HASH Hint ............................................................................................................ 3-94
NO_USE_MERGE Hint .......................................................................................................... 3-94
NO_USE_NL Hint .................................................................................................................. 3-95
NO_XML_QUERY_REWRITE Hint...................................................................................... 3-95
NO_XMLINDEX_REWRITE Hint ........................................................................................ 3-95
OPT_PARAM Hint ................................................................................................................. 3-95
ORDERED Hint ....................................................................................................................... 3-96
PARALLEL Hint ..................................................................................................................... 3-96
PARALLEL_INDEX Hint ...................................................................................................... 3-98
PQ_DISTRIBUTE Hint ........................................................................................................... 3-98
PUSH_PRED Hint ................................................................................................................. 3-101
PUSH_SUBQ Hint ................................................................................................................. 3-101
PX_JOIN_FILTER Hint ......................................................................................................... 3-101
QB_NAME Hint .................................................................................................................... 3-101
RESULT_CACHE Hint ......................................................................................................... 3-102
RETRY_ON_ROW_CHANGE Hint ................................................................................... 3-102
REWRITE Hint ...................................................................................................................... 3-103
STAR_TRANSFORMATION Hint ..................................................................................... 3-103
viii
UNNEST Hint ........................................................................................................................ 3-104
USE_CONCAT Hint ............................................................................................................. 3-104
USE_HASH Hint ................................................................................................................... 3-104
USE_MERGE Hint ................................................................................................................ 3-105
USE_NL Hint ......................................................................................................................... 3-105
USE_NL_WITH_INDEX Hint ............................................................................................. 3-106
Database Objects................................................................................................................................. 3-106
Schema Objects ............................................................................................................................. 3-106
Nonschema Objects ...................................................................................................................... 3-107
Database Object Names and Qualifiers ......................................................................................... 3-107
Database Object Naming Rules .................................................................................................. 3-107
Schema Object Naming Examples ............................................................................................. 3-111
Schema Object Naming Guidelines ........................................................................................... 3-111
Syntax for Schema Objects and Parts in SQL Statements........................................................... 3-111
How Oracle Database Resolves Schema Object References ................................................... 3-112
References to Objects in Other Schemas ................................................................................... 3-113
References to Objects in Remote Databases ............................................................................. 3-113
Creating Database Links ...................................................................................................... 3-114
Database Link Names .................................................................................................... 3-114
Username and Password............................................................................................... 3-114
Database Connect String................................................................................................ 3-114
References to Database Links .............................................................................................. 3-115
References to Partitioned Tables and Indexes ......................................................................... 3-115
References to Object Type Attributes and Methods ................................................................ 3-117
4 Operators
About SQL Operators.............................................................................................................................. 4-1
Unary and Binary Operators ........................................................................................................... 4-2
Operator Precedence ......................................................................................................................... 4-2
Arithmetic Operators .............................................................................................................................. 4-3
Concatenation Operator.......................................................................................................................... 4-4
Hierarchical Query Operators................................................................................................................ 4-5
PRIOR ................................................................................................................................................. 4-5
CONNECT_BY_ROOT ..................................................................................................................... 4-5
Set Operators ............................................................................................................................................ 4-5
Multiset Operators .................................................................................................................................. 4-6
MULTISET EXCEPT ......................................................................................................................... 4-6
MULTISET INTERSECT .................................................................................................................. 4-7
MULTISET UNION .......................................................................................................................... 4-8
User-Defined Operators ......................................................................................................................... 4-9
5 Functions
About SQL Functions ............................................................................................................................. 5-2
Single-Row Functions ............................................................................................................................ 5-3
Numeric Functions ............................................................................................................................ 5-3
Character Functions Returning Character Values ........................................................................ 5-4
NLS Character Functions ................................................................................................................. 5-5
ix
Character Functions Returning Number Values .......................................................................... 5-5
Datetime Functions ........................................................................................................................... 5-5
General Comparison Functions ...................................................................................................... 5-6
Conversion Functions ....................................................................................................................... 5-6
Large Object Functions ..................................................................................................................... 5-7
Collection Functions ......................................................................................................................... 5-7
Hierarchical Function ....................................................................................................................... 5-7
Data Mining Functions ..................................................................................................................... 5-7
XML Functions .................................................................................................................................. 5-8
Encoding and Decoding Functions ................................................................................................ 5-9
NULL-Related Functions ................................................................................................................. 5-9
Environment and Identifier Functions ........................................................................................... 5-9
Aggregate Functions ............................................................................................................................... 5-9
Analytic Functions ............................................................................................................................... 5-11
Object Reference Functions ............................................................................................................... 5-16
Model Functions ................................................................................................................................... 5-16
Alphabetical Listing of SQL Functions ............................................................................................ 5-17
ABS .......................................................................................................................................................... 5-18
ACOS ...................................................................................................................................................... 5-18
ADD_MONTHS ................................................................................................................................... 5-19
APPENDCHILDXML .......................................................................................................................... 5-19
ASCII ...................................................................................................................................................... 5-20
ASCIISTR .............................................................................................................................................. 5-21
ASIN ....................................................................................................................................................... 5-21
ATAN ...................................................................................................................................................... 5-22
ATAN2 .................................................................................................................................................... 5-22
AVG ......................................................................................................................................................... 5-23
BFILENAME .......................................................................................................................................... 5-24
BIN_TO_NUM ...................................................................................................................................... 5-25
BITAND .................................................................................................................................................. 5-26
CARDINALITY .................................................................................................................................... 5-27
CAST ....................................................................................................................................................... 5-28
CEIL ......................................................................................................................................................... 5-31
CHARTOROWID ................................................................................................................................. 5-31
CHR ......................................................................................................................................................... 5-32
CLUSTER_ID ........................................................................................................................................ 5-33
CLUSTER_PROBABILITY ................................................................................................................. 5-34
CLUSTER_SET ..................................................................................................................................... 5-36
COALESCE ............................................................................................................................................ 5-38
COLLECT ............................................................................................................................................... 5-39
COMPOSE ............................................................................................................................................. 5-40
CONCAT ................................................................................................................................................ 5-40
CONVERT ............................................................................................................................................. 5-41
CORR ...................................................................................................................................................... 5-43
CORR_* .................................................................................................................................................. 5-44
CORR_S ........................................................................................................................................... 5-45
CORR_K .......................................................................................................................................... 5-46
x
COS ......................................................................................................................................................... 5-46
COSH ...................................................................................................................................................... 5-47
COUNT ................................................................................................................................................... 5-47
COVAR_POP ......................................................................................................................................... 5-49
COVAR_SAMP ..................................................................................................................................... 5-50
CUBE_TABLE......................................................................................................................................... 5-51
CUME_DIST ......................................................................................................................................... 5-53
CURRENT_DATE ................................................................................................................................ 5-54
CURRENT_TIMESTAMP ................................................................................................................... 5-55
CV............................................................................................................................................................. 5-56
DATAOBJ_TO_PARTITION .............................................................................................................. 5-57
DBTIMEZONE ..................................................................................................................................... 5-57
DECODE ................................................................................................................................................ 5-58
DECOMPOSE ....................................................................................................................................... 5-59
DELETEXML ......................................................................................................................................... 5-60
DENSE_RANK ..................................................................................................................................... 5-61
DEPTH .................................................................................................................................................... 5-63
DEREF ..................................................................................................................................................... 5-63
DUMP ..................................................................................................................................................... 5-64
EMPTY_BLOB, EMPTY_CLOB ......................................................................................................... 5-65
EXISTSNODE ....................................................................................................................................... 5-66
EXP .......................................................................................................................................................... 5-67
EXTRACT (datetime) ........................................................................................................................... 5-68
EXTRACT (XML) .................................................................................................................................. 5-70
EXTRACTVALUE ................................................................................................................................. 5-71
FEATURE_ID ........................................................................................................................................ 5-72
FEATURE_SET ...................................................................................................................................... 5-73
FEATURE_VALUE ................................................................................................................................ 5-75
FIRST ...................................................................................................................................................... 5-77
FIRST_VALUE ...................................................................................................................................... 5-79
FLOOR .................................................................................................................................................... 5-80
FROM_TZ .............................................................................................................................................. 5-81
GREATEST ............................................................................................................................................ 5-81
GROUP_ID ............................................................................................................................................ 5-82
GROUPING ........................................................................................................................................... 5-83
GROUPING_ID .................................................................................................................................... 5-84
HEXTORAW .......................................................................................................................................... 5-85
INITCAP ................................................................................................................................................ 5-85
INSERTCHILDXML ............................................................................................................................ 5-86
INSERTCHILDXMLAFTER ............................................................................................................... 5-87
INSERTCHILDXMLBEFORE ............................................................................................................ 5-88
INSERTXMLAFTER ............................................................................................................................. 5-89
INSERTXMLBEFORE .......................................................................................................................... 5-90
INSTR ..................................................................................................................................................... 5-91
ITERATION_NUMBER ...................................................................................................................... 5-92
LAG ......................................................................................................................................................... 5-94
LAST ....................................................................................................................................................... 5-95
xi
LAST_DAY ............................................................................................................................................. 5-95
LAST_VALUE ....................................................................................................................................... 5-96
LEAD ....................................................................................................................................................... 5-98
LEAST ..................................................................................................................................................... 5-99
LENGTH .............................................................................................................................................. 5-100
LISTAGG ............................................................................................................................................. 5-101
LN .......................................................................................................................................................... 5-102
LNNVL ................................................................................................................................................. 5-103
LOCALTIMESTAMP ......................................................................................................................... 5-104
LOG ....................................................................................................................................................... 5-105
LOWER ................................................................................................................................................. 5-105
LPAD...................................................................................................................................................... 5-106
LTRIM ................................................................................................................................................... 5-106
MAKE_REF .......................................................................................................................................... 5-107
MAX ...................................................................................................................................................... 5-108
MEDIAN .............................................................................................................................................. 5-109
MIN ....................................................................................................................................................... 5-111
MOD ..................................................................................................................................................... 5-112
MONTHS_BETWEEN ....................................................................................................................... 5-113
NANVL ................................................................................................................................................. 5-114
NCHR ................................................................................................................................................... 5-114
NEW_TIME ......................................................................................................................................... 5-115
NEXT_DAY .......................................................................................................................................... 5-116
NLS_CHARSET_DECL_LEN ........................................................................................................... 5-116
NLS_CHARSET_ID ........................................................................................................................... 5-117
NLS_CHARSET_NAME ................................................................................................................... 5-117
NLS_INITCAP .................................................................................................................................... 5-118
NLS_LOWER ....................................................................................................................................... 5-119
NLS_UPPER ........................................................................................................................................ 5-119
NLSSORT ............................................................................................................................................. 5-120
NTH_VALUE ....................................................................................................................................... 5-122
NTILE ................................................................................................................................................... 5-123
NULLIF ................................................................................................................................................. 5-124
NUMTODSINTERVAL ..................................................................................................................... 5-125
NUMTOYMINTERVAL .................................................................................................................... 5-126
NVL ....................................................................................................................................................... 5-126
NVL2 ..................................................................................................................................................... 5-127
ORA_DST_AFFECTED ..................................................................................................................... 5-128
ORA_DST_CONVERT ...................................................................................................................... 5-129
ORA_DST_ERROR ............................................................................................................................ 5-130
ORA_HASH ........................................................................................................................................ 5-130
PATH...................................................................................................................................................... 5-131
PERCENT_RANK .............................................................................................................................. 5-132
PERCENTILE_CONT ........................................................................................................................ 5-133
PERCENTILE_DISC .......................................................................................................................... 5-135
POWER ................................................................................................................................................. 5-137
POWERMULTISET ............................................................................................................................ 5-137
xii
POWERMULTISET_BY_CARDINALITY ..................................................................................... 5-138
PREDICTION ..................................................................................................................................... 5-139
PREDICTION_BOUNDS ................................................................................................................. 5-141
PREDICTION_COST ........................................................................................................................ 5-142
PREDICTION_DETAILS .................................................................................................................. 5-144
PREDICTION_PROBABILITY ....................................................................................................... 5-146
PREDICTION_SET ............................................................................................................................ 5-147
PRESENTNNV .................................................................................................................................... 5-150
PRESENTV ........................................................................................................................................... 5-151
PREVIOUS ........................................................................................................................................... 5-152
RANK ................................................................................................................................................... 5-153
RATIO_TO_REPORT ........................................................................................................................ 5-155
RAWTOHEX ........................................................................................................................................ 5-155
RAWTONHEX .................................................................................................................................... 5-156
REF ........................................................................................................................................................ 5-157
REFTOHEX .......................................................................................................................................... 5-157
REGEXP_COUNT .............................................................................................................................. 5-158
REGEXP_INSTR ................................................................................................................................. 5-160
REGEXP_REPLACE ........................................................................................................................... 5-162
REGEXP_SUBSTR ............................................................................................................................. 5-164
REGR_ (Linear Regression) Functions ........................................................................................... 5-166
REMAINDER ...................................................................................................................................... 5-171
REPLACE ............................................................................................................................................. 5-172
ROUND (date) .................................................................................................................................... 5-172
ROUND (number) .............................................................................................................................. 5-173
ROW_NUMBER ................................................................................................................................. 5-174
ROWIDTOCHAR ............................................................................................................................... 5-176
ROWIDTONCHAR ........................................................................................................................... 5-176
RPAD .................................................................................................................................................... 5-177
RTRIM .................................................................................................................................................. 5-178
SCN_TO_TIMESTAMP .................................................................................................................... 5-178
SESSIONTIMEZONE ....................................................................................................................... 5-180
SET ........................................................................................................................................................ 5-180
SIGN ..................................................................................................................................................... 5-181
SIN ......................................................................................................................................................... 5-181
SINH ..................................................................................................................................................... 5-182
SOUNDEX ........................................................................................................................................... 5-182
SQRT ..................................................................................................................................................... 5-183
STATS_BINOMIAL_TEST ............................................................................................................... 5-184
STATS_CROSSTAB ........................................................................................................................... 5-185
STATS_F_TEST ................................................................................................................................... 5-186
STATS_KS_TEST ................................................................................................................................ 5-187
STATS_MODE .................................................................................................................................... 5-188
STATS_MW_TEST ............................................................................................................................. 5-189
STATS_ONE_WAY_ANOVA ............................................................................................................ 5-190
STATS_T_TEST_* ............................................................................................................................... 5-191
STATS_T_TEST_ONE .................................................................................................................. 5-192
xiii
STATS_T_TEST_PAIRED ........................................................................................................... 5-193
STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU ....................................................... 5-193
STATS_WSR_TEST ............................................................................................................................ 5-194
STDDEV ............................................................................................................................................... 5-195
STDDEV_POP .................................................................................................................................... 5-196
STDDEV_SAMP ................................................................................................................................. 5-197
SUBSTR ................................................................................................................................................ 5-199
SUM ...................................................................................................................................................... 5-200
SYS_CONNECT_BY_PATH ............................................................................................................. 5-201
SYS_CONTEXT .................................................................................................................................. 5-202
SYS_DBURIGEN ................................................................................................................................ 5-208
SYS_EXTRACT_UTC ........................................................................................................................ 5-209
SYS_GUID ........................................................................................................................................... 5-209
SYS_TYPEID ....................................................................................................................................... 5-210
SYS_XMLAGG ................................................................................................................................... 5-211
SYS_XMLGEN .................................................................................................................................... 5-211
SYSDATE ............................................................................................................................................. 5-212
SYSTIMESTAMP ............................................................................................................................... 5-213
TAN ....................................................................................................................................................... 5-213
TANH .................................................................................................................................................... 5-214
TIMESTAMP_TO_SCN .................................................................................................................... 5-214
TO_BINARY_DOUBLE ..................................................................................................................... 5-215
TO_BINARY_FLOAT ........................................................................................................................ 5-216
TO_BLOB ............................................................................................................................................. 5-217
TO_CHAR (character) ........................................................................................................................ 5-218
TO_CHAR (datetime) ........................................................................................................................ 5-219
TO_CHAR (number) .......................................................................................................................... 5-221
TO_CLOB ............................................................................................................................................. 5-222
TO_DATE ............................................................................................................................................. 5-223
TO_DSINTERVAL ............................................................................................................................. 5-224
TO_LOB ............................................................................................................................................... 5-225
TO_MULTI_BYTE .............................................................................................................................. 5-226
TO_NCHAR (character) .................................................................................................................... 5-227
TO_NCHAR (datetime) ..................................................................................................................... 5-227
TO_NCHAR (number) ...................................................................................................................... 5-228
TO_NCLOB ......................................................................................................................................... 5-229
TO_NUMBER ..................................................................................................................................... 5-229
TO_SINGLE_BYTE ............................................................................................................................ 5-230
TO_TIMESTAMP ............................................................................................................................... 5-230
TO_TIMESTAMP_TZ ........................................................................................................................ 5-231
TO_YMINTERVAL ............................................................................................................................ 5-232
TRANSLATE ....................................................................................................................................... 5-233
TRANSLATE ... USING .................................................................................................................... 5-234
TREAT .................................................................................................................................................. 5-235
TRIM ..................................................................................................................................................... 5-236
TRUNC (date) ...................................................................................................................................... 5-237
TRUNC (number) ............................................................................................................................... 5-238
xiv
TZ_OFFSET ......................................................................................................................................... 5-238
UID ........................................................................................................................................................ 5-239
UNISTR ................................................................................................................................................ 5-239
UPDATEXML ...................................................................................................................................... 5-240
UPPER ................................................................................................................................................... 5-241
USER ..................................................................................................................................................... 5-242
USERENV ............................................................................................................................................ 5-242
VALUE .................................................................................................................................................. 5-243
VAR_POP ............................................................................................................................................. 5-244
VAR_SAMP ......................................................................................................................................... 5-245
VARIANCE .......................................................................................................................................... 5-246
VSIZE .................................................................................................................................................... 5-247
WIDTH_BUCKET .............................................................................................................................. 5-248
XMLAGG ............................................................................................................................................. 5-249
XMLCAST............................................................................................................................................. 5-250
XMLCDATA ........................................................................................................................................ 5-251
XMLCOLATTVAL............................................................................................................................... 5-252
XMLCOMMENT ................................................................................................................................ 5-252
XMLCONCAT ..................................................................................................................................... 5-253
XMLDIFF ............................................................................................................................................. 5-254
XMLELEMENT.................................................................................................................................... 5-255
XMLEXISTS ......................................................................................................................................... 5-257
XMLFOREST ....................................................................................................................................... 5-258
XMLISVALID ...................................................................................................................................... 5-259
XMLPARSE .......................................................................................................................................... 5-259
XMLPATCH ......................................................................................................................................... 5-260
XMLPI ................................................................................................................................................... 5-261
XMLQUERY ......................................................................................................................................... 5-262
XMLROOT ........................................................................................................................................... 5-263
XMLSEQUENCE ................................................................................................................................. 5-264
XMLSERIALIZE ................................................................................................................................. 5-266
XMLTABLE .......................................................................................................................................... 5-267
XMLTRANSFORM ............................................................................................................................. 5-269
ROUND and TRUNC Date Functions ............................................................................................ 5-270
About User-Defined Functions ........................................................................................................ 5-271
Prerequisites................................................................................................................................... 5-272
Name Precedence ......................................................................................................................... 5-272
Naming Conventions ........................................................................................................... 5-272
6 Expressions
About SQL Expressions ......................................................................................................................... 6-1
Simple Expressions ................................................................................................................................. 6-3
Compound Expressions ......................................................................................................................... 6-4
CASE Expressions ................................................................................................................................... 6-5
Column Expressions ............................................................................................................................... 6-6
CURSOR Expressions.............................................................................................................................. 6-7
Datetime Expressions ............................................................................................................................. 6-8
xv
Function Expressions ........................................................................................................................... 6-10
Interval Expressions ............................................................................................................................. 6-10
Model Expressions ................................................................................................................................ 6-11
Object Access Expressions .................................................................................................................. 6-13
Placeholder Expressions ...................................................................................................................... 6-14
Scalar Subquery Expressions ............................................................................................................. 6-14
Type Constructor Expressions ............................................................................................................ 6-14
Expression Lists .................................................................................................................................... 6-16
7 Conditions
About SQL Conditions............................................................................................................................ 7-1
Condition Precedence........................................................................................................................ 7-3
Comparison Conditions ......................................................................................................................... 7-4
Simple Comparison Conditions ...................................................................................................... 7-5
Group Comparison Conditions ...................................................................................................... 7-6
Floating-Point Conditions ..................................................................................................................... 7-7
Logical Conditions ................................................................................................................................... 7-7
Model Conditions ................................................................................................................................... 7-9
IS ANY Condition ............................................................................................................................. 7-9
IS PRESENT Condition ................................................................................................................. 7-10
Multiset Conditions ............................................................................................................................. 7-11
IS A SET Condition ........................................................................................................................ 7-11
IS EMPTY Condition ...................................................................................................................... 7-12
MEMBER Condition ...................................................................................................................... 7-12
SUBMULTISET Condition ............................................................................................................ 7-13
Pattern-matching Conditions ............................................................................................................. 7-14
LIKE Condition ............................................................................................................................... 7-14
REGEXP_LIKE Condition ............................................................................................................. 7-17
Null Conditions .................................................................................................................................... 7-19
XML Conditions ................................................................................................................................... 7-19
EQUALS_PATH Condition .......................................................................................................... 7-19
UNDER_PATH Condition ............................................................................................................ 7-20
Compound Conditions ........................................................................................................................ 7-20
BETWEEN Condition .......................................................................................................................... 7-21
EXISTS Condition ................................................................................................................................ 7-22
IN Condition ......................................................................................................................................... 7-22
IS OF type Condition ........................................................................................................................... 7-24
8 Common SQL DDL Clauses
allocate_extent_clause ............................................................................................................................ 8-2
constraint ................................................................................................................................................... 8-4
deallocate_unused_clause .................................................................................................................... 8-27
file_specification ................................................................................................................................... 8-29
logging_clause ........................................................................................................................................ 8-38
parallel_clause ....................................................................................................................................... 8-41
physical_attributes_clause .................................................................................................................. 8-44
xvi
size_clause .............................................................................................................................................. 8-47
storage_clause ........................................................................................................................................ 8-48
9 SQL Queries and Subqueries
About Queries and Subqueries ............................................................................................................ 9-1
Creating Simple Queries ........................................................................................................................ 9-2
Hierarchical Queries ............................................................................................................................... 9-3
Hierarchical Query Examples .......................................................................................................... 9-5
The UNION [ALL], INTERSECT, MINUS Operators....................................................................... 9-8
Sorting Query Results ......................................................................................................................... 9-10
Joins ......................................................................................................................................................... 9-11
Join Conditions ............................................................................................................................... 9-11
Equijoins .......................................................................................................................................... 9-11
Self Joins .......................................................................................................................................... 9-11
Cartesian Products ......................................................................................................................... 9-12
Inner Joins ....................................................................................................................................... 9-12
Outer Joins ....................................................................................................................................... 9-12
Antijoins .......................................................................................................................................... 9-13
Semijoins .......................................................................................................................................... 9-14
Using Subqueries ................................................................................................................................. 9-14
Unnesting of Nested Subqueries ...................................................................................................... 9-15
Selecting from the DUAL Table ........................................................................................................ 9-15
Distributed Queries ............................................................................................................................. 9-16
10 SQL Statements: ALTER CLUSTER to ALTER JAVA
Types of SQL Statements .................................................................................................................... 10-1
Data Definition Language (DDL) Statements ............................................................................ 10-2
Data Manipulation Language (DML) Statements ..................................................................... 10-2
Transaction Control Statements ................................................................................................... 10-3
Session Control Statements ........................................................................................................... 10-3
System Control Statement ............................................................................................................. 10-3
Embedded SQL Statements .......................................................................................................... 10-3
How the SQL Statement Chapters are Organized ......................................................................... 10-4
ALTER CLUSTER ................................................................................................................................. 10-5
ALTER DATABASE ............................................................................................................................. 10-9
ALTER DATABASE LINK ................................................................................................................ 10-46
ALTER DIMENSION ........................................................................................................................ 10-48
ALTER DISKGROUP ........................................................................................................................ 10-51
ALTER FLASHBACK ARCHIVE .................................................................................................... 10-73
ALTER FUNCTION ........................................................................................................................... 10-76
ALTER INDEX .................................................................................................................................... 10-77
ALTER INDEXTYPE .......................................................................................................................... 10-96
ALTER JAVA ........................................................................................................................................ 10-99
11 SQL Statements: ALTER LIBRARY to ALTER SYSTEM
ALTER LIBRARY................................................................................................................................... 11-2
xvii
ALTER MATERIALIZED VIEW ........................................................................................................ 11-3
ALTER MATERIALIZED VIEW LOG ............................................................................................ 11-18
ALTER OPERATOR ........................................................................................................................... 11-25
ALTER OUTLINE ............................................................................................................................... 11-28
ALTER PACKAGE ............................................................................................................................. 11-30
ALTER PROCEDURE ........................................................................................................................ 11-31
ALTER PROFILE ................................................................................................................................ 11-32
ALTER RESOURCE COST ............................................................................................................... 11-35
ALTER ROLE ....................................................................................................................................... 11-38
ALTER ROLLBACK SEGMENT ..................................................................................................... 11-40
ALTER SEQUENCE ........................................................................................................................... 11-43
ALTER SESSION ................................................................................................................................ 11-45
Initialization Parameters and ALTER SESSION....................................................................... 11-50
Session Parameters and ALTER SESSION ............................................................................... 11-51
ALTER SYSTEM ................................................................................................................................. 11-58
12 SQL Statements: ALTER TABLE to ALTER TABLESPACE
ALTER TABLE ....................................................................................................................................... 12-2
ALTER TABLESPACE ........................................................................................................................ 12-89
13 SQL Statements: ALTER TRIGGER to COMMIT
ALTER TRIGGER ................................................................................................................................. 13-2
ALTER TYPE ......................................................................................................................................... 13-4
ALTER USER ......................................................................................................................................... 13-5
ALTER VIEW ....................................................................................................................................... 13-12
ANALYZE ............................................................................................................................................ 13-15
ASSOCIATE STATISTICS ................................................................................................................ 13-23
AUDIT .................................................................................................................................................. 13-27
CALL ..................................................................................................................................................... 13-40
COMMENT ......................................................................................................................................... 13-44
COMMIT ............................................................................................................................................. 13-47
14 SQL Statements: CREATE CLUSTER to CREATE JAVA
CREATE CLUSTER .............................................................................................................................. 14-2
CREATE CONTEXT ............................................................................................................................. 14-9
CREATE CONTROLFILE ................................................................................................................. 14-12
CREATE DATABASE ......................................................................................................................... 14-19
CREATE DATABASE LINK ............................................................................................................. 14-32
CREATE DIMENSION ..................................................................................................................... 14-37
CREATE DIRECTORY ...................................................................................................................... 14-42
CREATE DISKGROUP ..................................................................................................................... 14-44
CREATE EDITION ............................................................................................................................. 14-52
CREATE FLASHBACK ARCHIVE ................................................................................................. 14-56
CREATE FUNCTION ........................................................................................................................ 14-59
CREATE INDEX ................................................................................................................................. 14-61
CREATE INDEXTYPE ....................................................................................................................... 14-87
xviii
CREATE JAVA ..................................................................................................................................... 14-91
15 SQL Statements: CREATE LIBRARY to CREATE SPFILE
CREATE LIBRARY ............................................................................................................................... 15-2
CREATE MATERIALIZED VIEW ..................................................................................................... 15-3
CREATE MATERIALIZED VIEW LOG ......................................................................................... 15-26
CREATE OPERATOR ........................................................................................................................ 15-34
CREATE OUTLINE ............................................................................................................................ 15-37
CREATE PACKAGE ........................................................................................................................... 15-41
CREATE PACKAGE BODY .............................................................................................................. 15-43
CREATE PFILE .................................................................................................................................... 15-45
CREATE PROCEDURE ..................................................................................................................... 15-47
CREATE PROFILE ............................................................................................................................. 15-49
CREATE RESTORE POINT ............................................................................................................. 15-55
CREATE ROLE .................................................................................................................................... 15-58
CREATE ROLLBACK SEGMENT .................................................................................................. 15-61
CREATE SCHEMA ............................................................................................................................. 15-64
CREATE SEQUENCE ........................................................................................................................ 15-66
CREATE SPFILE ................................................................................................................................. 15-70
16 SQL Statements: CREATE SYNONYM to CREATE TRIGGER
CREATE SYNONYM ........................................................................................................................... 16-2
CREATE TABLE .................................................................................................................................... 16-6
CREATE TABLESPACE ..................................................................................................................... 16-80
CREATE TRIGGER ............................................................................................................................ 16-94
17 SQL Statements: CREATE TYPE to DROP ROLLBACK SEGMENT
CREATE TYPE ....................................................................................................................................... 17-3
CREATE TYPE BODY .......................................................................................................................... 17-5
CREATE USER ...................................................................................................................................... 17-7
CREATE VIEW .................................................................................................................................... 17-14
DELETE ................................................................................................................................................ 17-26
DISASSOCIATE STATISTICS ........................................................................................................ 17-34
DROP CLUSTER ................................................................................................................................ 17-36
DROP CONTEXT ............................................................................................................................... 17-38
DROP DATABASE ............................................................................................................................. 17-39
DROP DATABASE LINK ................................................................................................................. 17-40
DROP DIMENSION .......................................................................................................................... 17-41
DROP DIRECTORY .......................................................................................................................... 17-42
DROP DISKGROUP ......................................................................................................................... 17-43
DROP EDITION ................................................................................................................................. 17-45
DROP FLASHBACK ARCHIVE ..................................................................................................... 17-46
DROP FUNCTION ............................................................................................................................ 17-47
DROP INDEX....................................................................................................................................... 17-49
DROP INDEXTYPE ........................................................................................................................... 17-51
DROP JAVA ......................................................................................................................................... 17-52
xix
DROP LIBRARY ................................................................................................................................. 17-53
DROP MATERIALIZED VIEW........................................................................................................ 17-54
DROP MATERIALIZED VIEW LOG ............................................................................................. 17-56
DROP OPERATOR ............................................................................................................................ 17-58
DROP OUTLINE ................................................................................................................................ 17-59
DROP PACKAGE ............................................................................................................................... 17-61
DROP PROCEDURE ......................................................................................................................... 17-63
DROP PROFILE .................................................................................................................................. 17-64
DROP RESTORE POINT ................................................................................................................. 17-65
DROP ROLE ........................................................................................................................................ 17-66
DROP ROLLBACK SEGMENT ...................................................................................................... 17-67
18 SQL Statements: DROP SEQUENCE to ROLLBACK
DROP SEQUENCE .............................................................................................................................. 18-2
DROP SYNONYM ............................................................................................................................... 18-3
DROP TABLE ........................................................................................................................................ 18-5
DROP TABLESPACE ........................................................................................................................... 18-9
DROP TRIGGER................................................................................................................................. 18-12
DROP TYPE ......................................................................................................................................... 18-13
DROP TYPE BODY ............................................................................................................................ 18-15
DROP USER ........................................................................................................................................ 18-16
DROP VIEW ........................................................................................................................................ 18-18
EXPLAIN PLAN .................................................................................................................................. 18-20
FLASHBACK DATABASE ................................................................................................................ 18-24
FLASHBACK TABLE ......................................................................................................................... 18-27
GRANT ................................................................................................................................................. 18-33
INSERT ................................................................................................................................................. 18-54
LOCK TABLE ...................................................................................................................................... 18-72
MERGE ................................................................................................................................................. 18-75
NOAUDIT ............................................................................................................................................ 18-80
PURGE .................................................................................................................................................. 18-84
RENAME .............................................................................................................................................. 18-86
REVOKE ............................................................................................................................................... 18-88
ROLLBACK ......................................................................................................................................... 18-97
19 SQL Statements: SAVEPOINT to UPDATE
SAVEPOINT .......................................................................................................................................... 19-2
SELECT ................................................................................................................................................... 19-4
SET CONSTRAINT[S] ...................................................................................................................... 19-58
SET ROLE ............................................................................................................................................ 19-60
SET TRANSACTION ........................................................................................................................ 19-62
TRUNCATE CLUSTER ..................................................................................................................... 19-65
TRUNCATE TABLE ........................................................................................................................... 19-67
UPDATE ............................................................................................................................................... 19-71
xx
A How to Read Syntax Diagrams
Graphic Syntax Diagrams...................................................................................................................... A-1
Required Keywords and Parameters ............................................................................................ A-2
Optional Keywords and Parameters ............................................................................................. A-3
Syntax Loops...................................................................................................................................... A-3
Multipart Diagrams ......................................................................................................................... A-4
Database Objects .............................................................................................................................. A-4
B Automatic and Manual Locking Mechanisms During SQL Operations
Automatic Locks in DML Operations ................................................................................................. B-1
Automatic Locks in DDL Operations.................................................................................................. B-4
Exclusive DDL Locks........................................................................................................................ B-4
Share DDL Locks............................................................................................................................... B-5
Breakable Parse Locks ...................................................................................................................... B-5
Manual Data Locking ............................................................................................................................. B-5
C Oracle and Standard SQL
ANSI Standards ...................................................................................................................................... C-1
ISO Standards .......................................................................................................................................... C-2
Oracle Compliance To Core SQL:2008................................................................................................. C-3
Oracle Support for Optional Features of SQL/Foundation:2008.................................................... C-9
Oracle Compliance with SQL/CLI:2008 ............................................................................................ C-21
Oracle Compliance with SQL/PSM:2008 .......................................................................................... C-21
Oracle Compliance with SQL/MED:2008 ......................................................................................... C-21
Oracle Compliance with SQL/OLB:2008........................................................................................... C-21
Oracle Compliance with SQL/JRT:2008 ............................................................................................ C-21
Oracle Compliance with SQL/XML:2008.......................................................................................... C-22
Oracle Compliance with FIPS 127-2 ................................................................................................. C-27
Oracle Extensions to Standard SQL .................................................................................................. C-28
Oracle Compliance with Older Standards ....................................................................................... C-29
Character Set Support........................................................................................................................... C-29
D Oracle Regular Expression Support
Multilingual Regular Expression Syntax .......................................................................................... D-1
Regular Expression Operator Multilingual Enhancements............................................................ D-2
Perl-influenced Extensions in Oracle Regular Expressions ........................................................... D-3
E Oracle SQL Reserved Words
F Extended Examples
Using Extensible Indexing ................................................................................................................... F-1
Using XML in SQL Statements ............................................................................................................ F-8
Index
xxi
Preface
This reference contains a complete description of the Structured Query Language
(SQL) used to manage information in an Oracle Database. Oracle SQL is a superset of
the American National Standards Institute (ANSI) and the International Organization
for Standardization (ISO) SQL:1999 standard.
This Preface contains these topics:
■ Audience
■ Documentation Accessibility
■ Related Documents
■ Conventions
Audience
The Oracle Database SQL Language Reference is intended for all users of Oracle SQL.
Documentation Accessibility
Our goal is to make Oracle products, services, and supporting documentation
accessible to all users, including users that are disabled. To that end, our
documentation includes features that make information available to users of assistive
technology. This documentation is available in HTML format, and contains markup to
facilitate access by the disabled community. Accessibility standards will continue to
evolve over time, and Oracle is actively engaged with other market-leading
technology vendors to address technical obstacles so that our documentation can be
accessible to all of our customers. For more information, visit the Oracle Accessibility
Program Web site at http://www.oracle.com/accessibility/.
Accessibility of Code Examples in Documentation
Screen readers may not always correctly read the code examples in this document. The
conventions for writing code require that closing braces should appear on an
otherwise empty line; however, some screen readers may not always read a line of text
that consists solely of a bracket or brace.
Accessibility of Links to External Web Sites in Documentation
This documentation may contain links to Web sites of other companies or
organizations that Oracle does not own or control. Oracle neither evaluates nor makes
any representations regarding the accessibility of these Web sites.
xxii
Deaf/Hard of Hearing Access to Oracle Support Services
To reach Oracle Support Services, use a telecommunications relay service (TRS) to call
Oracle Support at 1.800.223.1711. An Oracle Support Services engineer will handle
technical issues and provide customer support according to the Oracle service request
process. Information about TRS is available at
http://www.fcc.gov/cgb/consumerfacts/trs.html, and a list of phone
numbers is available at http://www.fcc.gov/cgb/dro/trsphonebk.html.
Related Documents
For more information, see these Oracle resources:
■ Oracle Database PL/SQL Language Reference for information on PL/SQL, the
procedural language extension to Oracle SQL
■ Pro*C/C++ Programmer's Guide, Oracle SQL*Module for Ada Programmer's Guide, and
the Pro*COBOL Programmer's Guide for detailed descriptions of Oracle embedded
SQL
Many of the examples in this book use the sample schemas, which are installed by
default when you select the Basic Installation option with an Oracle Database
installation. Refer to Oracle Database Sample Schemas for information on how these
schemas were created and how you can use them yourself.
Conventions
The following text conventions are used in this document:
Convention Meaning
boldface Boldface type indicates graphical user interface elements associated
with an action, or terms defined in text or the glossary.
italic Italic type indicates book titles, emphasis, or placeholder variables for
which you supply particular values.
monospace Monospace type indicates commands within a paragraph, URLs, code
in examples, text that appears on the screen, or text that you enter.
xxiii
What's New in the SQL Language
Reference?
This section describes new features of Oracle Database 11g and provides pointers to
additional information.
For information on features that were new in earlier versions of Oracle Database, refer
to the documentation for the earlier release.
Oracle Database 11g Release 2 New Features in the SQL Language
Reference
Structural Changes in the SQL Language Reference
A number of sections of this book that were make up primarily of PL/SQL were
moved to Oracle Database PL/SQL Language Reference in Oracle Database 11g Release 1.
Please refer to "Structural Changes in the SQL Language Reference" on page xxv for
details on this migration of material.
New Features in the SQL Language Reference
The following top-level SQL statements are new or enhanced in this release:
■ A new top-level SQL statement ALTER DATABASE LINK on page 10-46 lets you
update the fixed user password in a database link when the password of a
connection or authentication user has changed.
■ The ALTER DISKGROUP statement has the following changes:
– A new disk_region_clause on page 10-65 lets you determine the Intelligent Data
Placement attribute of the disk group file.
– New diskgroup_volume_clauses on page 10-67 let you manipulate logical Oracle
Automatic Storage Management (Oracle ASM) volumes corresponding to
physical volume devices.
– Several new clauses let you control access to Oracle ASM files: usergroup_
clauses on page 10-68, user_clauses on page 10-69, file_permissions_clause on
page 10-69, and file_owner_clause on page 10-69.
■ AUDIT and NOAUDIT contain a new clause ALL STATEMENTS on page 13-30 that
lets you enable and disable auditing of all top-level SQL statements executed. In
AUDIT only, a new clause IN SESSION CURRENT on page 13-31 allows you to
limit auditing to the current session.
■ CREATE DISKGROUP and ALTER DISKGROUP have the following changes:
xxiv
– A new clause QUORUM | REGULAR on page 14-46 let you designate a disk
or failure group as a quorum disk or failure group, which can contain the
voting file for Cluster Synchronization Services (CSS).
■ Two new statements, CREATE EDITION on page 14-52 and DROP EDITION on
page 17-45, let you use editions. An edition makes it possible to have two or more
versions of the same editionable objects in the database.
■ CREATE INDEXTYPE on page 14-87 and ALTER INDEXTYPE on page 10-96 have
a new clause WITH SYSTEM MANAGED STORAGE TABLES. This clause makes it
possible to create domain indexes in both range- and list-partitioned tables.
■ ALTER SESSION contains a new clause SYNC WITH PRIMARY on page 11-48 that
lets you synchronize the physical standby database with the primary database. A
new session parameter STANDBY_MAX_DATA_DELAY on page 11-53 lets you
specify a session-specific apply lag tolerance for queries to a physical standby
database that is in real-time query mode.
■ CREATE MATERIALIZED VIEW LOG has a new clause COMMIT SCN on
page 15-30 that instructs the database to use commit SCN data instead of
timestamps to refresh the materialized view, which improves the speed of the
refresh.
■ CREATE MATERIALIZED VIEW LOG and ALTER MATERIALIZED VIEW LOG have a
new clause mv_log_purge_clause on page 15-32 that lets you specify the purge time
for the materialized view log.
■ CREATE TABLE and ALTER TABLE are enhanced in the following ways:
– A new clause deferred_segment_creation on page 16-32 lets you postpone
creation of the table segment until the first row of data is inserted into the
table. This clause is also applicable to materialized views.
– The clause table_compression on page 16-34 has new syntax and terminology.
Use COMPRESS FOR OLTP to specify OLTP table compression. (In earlier
releases, the syntax was COMPRESS FOR ALL OPERATIONS.) Use COMPRESS
BASIC to specify basic table compression. (In earlier releases, the syntax was
COMPRESS FOR DIRECT_LOAD OPERATIONS and this type of compression
was called DSS table compression.)
– A new RESULT_CACHE Clause on page 16-61 lets you specify whether the
results of queries that name the table are considered for result caching.
– The nested_table_col_properties on page 16-48 provides a LOCAL keyword to
equipartition a nested table with partitioned base table. This is the default
behavior in this release. The default in earlier releases was not to equipartition
the nested table with the partitioned base table. Now you must specify the
GLOBAL keyword to store an unpartitioned nested table with a partitioned
base table.
■ The CREATE VIEW has a new keyword EDITIONING on page 17-17 that lets you
create an editioning view.
■ The statement GRANT on page 18-33 has a new EXECUTE object privilege on
directory objects. The ORACLE_LOADER access driver for external tables references
this privilege when deciding whether to execute a preprocessor program.
The following built-in functions are new or enhanced in this release:
■ For a specified measure, the function LISTAGG on page 5-101 orders data within
each group specified in an ORDER BY clause and then concatenates the values of
the measure column.
xxv
■ A new NTH_VALUE on page 5-122 function returns the value of a measure in a
specified row of a window of data.
■ Three new functions are useful when you are changing the time zone data file for
your database: ORA_DST_AFFECTED on page 5-128, ORA_DST_CONVERT on
page 5-129, and ORA_DST_ERROR on page 5-130.
The following miscellaneous features are new or enhanced in this release:
■ Hints, which were introduced in Oracle7, are now superseded by several Oracle
tools, including the SQL Tuning Advisor, SQL plan management, and SQL
Performance Analyzer. See "Hints" on page 3-73 for more information.
■ Beginning with Oracle Database 11g Release 2, the PARALLEL, PARALLEL_INDEX,
NO_PARALLEL, and NO_PARALLEL_INDEX hints are statement-level hints and
supersede the earlier object-level hints. See "Note on Parallel Hints" on page 3-96.
■ A new APPEND_VALUES Hint on page 3-78 lets you use direct-path INSERT
with the VALUES clause.
■ When specifying a redo log file, you can use the new keyword BLOCKSIZE Clause
on page 8-34 to override the operating system-dependent sector size.
■ The LOB_compression_clause on page 16-45 now has a new LOW setting, which
results in significantly higher decompression and compression speeds, at the cost
of a slightly lower compression ratio.
■ The subquery_factoring_clause on page 19-13 now supports recursive subquery
factoring (recursive WITH), which lets you query hierarchical data. This feature is
more powerful than CONNECT BY in that it provides depth-first search and
breadth-first search, and supports multiple recursive branches. A new search_clause
on page 19-14 and cycle_clause on page 19-14 let you specify an ordering for the
rows and mark cycles in the recursion.
Oracle Database 11g Release 1 New Features in the SQL Language
Reference
Structural Changes in the SQL Language Reference
A number of SQL statements are constructed almost entirely of PL/SQL elements.
Those statements continue to appear in this reference, but the bulk of their syntax and
semantics has been moved to Oracle Database PL/SQL Language Reference. The following
table contains links to both the abbreviated SQL syntax and semantics in this book and
to the full syntax and semantics in Oracle Database PL/SQL Language Reference.
Abbreviated SQL Section Full Syntax and Semantics
CREATE FUNCTION on page 14-59 CREATE FUNCTION
CREATE PACKAGE on page 15-41 CREATE PACKAGE
CREATE PACKAGE BODY on page 15-43 CREATE PACKAGE BODY
CREATE PROCEDURE on page 15-47 CREATE PROCEDURE
CREATE TRIGGER on page 16-94 CREATE TRIGGER
CREATE TYPE on page 17-3 CREATE TYPE
CREATE TYPE BODY on page 17-5 CREATE TYPE BODY
ALTER FUNCTION on page 10-76 ALTER FUNCTION
xxvi
New Features in the SQL Language Reference
The following top-level SQL statements are new or enhanced in this release:
■ ALTER DATABASE on page 10-9 has been enhanced as follows:
– The clause managed_standby_recovery on page 10-23 has been greatly
simplified. A number of subclauses have been deprecated as the database now
handles much of the recovery process automatically.
– The supplemental_db_logging on page 10-32 contains new syntax that lets you
enable or disable supplemental logging of PL/SQL calls.
– The standby_database_clauses on page 10-34 have new syntax that lets you
convert a physical standby database into a snapshot standby database or
convert a snapshot standby database into a physical standby database.
– The clause managed_standby_recovery on page 10-23 has new KEEP IDENTITY
syntax that lets you use the rolling upgrade feature provided by a logical
standby and also revert to the original configuration of a primary database
and a physical standby.
■ ALTER DISKGROUP on page 10-51 has been enhanced as follows:
– The check_diskgroup_clause on page 10-63 has simplified syntax for checking
the consistency of disk groups, disks, and files in an Oracle ASM environment.
– The clause diskgroup_availability on page 10-69 offers new options when
mounting a disk group.
– New clauses disk_offline_clause on page 10-61 and disk_online_clause on
page 10-62 let you take a disk offline for repair and then bring it back online.
■ ALTER INDEX on page 10-77 has been enhanced as follows:
– A new MIGRATE parameter lets you migrate a domain index from
user-managed storage tables to system-managed storage tables.
– A new INVISIBLE parameter lets you modify an index so that it is invisible to
the optimizer.
– The "PARAMETERS Clause" on page 10-88 now lets you rebuild an XMLIndex
index as well as a domain index.
■ ALTER SYSTEM on page 11-58 has been enhanced as follows:
– New syntax lets you kill a session on another instance in an Oracle Real
Application Clusters (Oracle RAC) environment.
– New rolling_migration_clauses on page 11-66 let you prepare an Oracle ASM
cluster for migration and return it to normal operation after all nodes have
migrated to the same software version.
■ ALTER TABLE on page 12-2 has been enhanced as follows:
ALTER PACKAGE on page 11-30 ALTER PACKAGE
ALTER PROCEDURE on page 11-31 ALTER PROCEDURE
ALTER TRIGGER on page 13-2 ALTER TRIGGER
ALTER TYPE on page 13-4 ALTER TYPE
Abbreviated SQL Section Full Syntax and Semantics
xxvii
– The behavior of the add_column_clause on page 12-41 when you specify a
DEFAULT value has been enhanced for improved performance.
– The syntax for READ ONLY | READ WRITE on page 12-38 lets you put a
table into read-only mode, to prevent DDL or DML changes during table
maintenance, and then back into read/write mode.
– The clause add_table_partition on page 12-63 has expanded syntax to let you
add a system partition.
– The flashback_archive_clause on page 12-38 lets you enable or disable historical
tracking for the table.
– The add_column_clause on page 12-41 now lets you add a virtual column to a
table.
– A new clause alter_interval_partitioning on page 12-57 lets you convert a
range-partitioned table to an interval_partitioned table.
– A new dependent_tables_clause on page 12-73 lets you instruct the database to
cascade various partition maintenance operations on a table to
reference-partitioned child tables.
■ ALTER TABLESPACE on page 12-89 has new syntax that lets you shrink the space
taken by a temporary tablespace or an individual temp file.
■ ASSOCIATE STATISTICS on page 13-23 has syntax that lets you specify that the
database should manage storage of statistics collected on a system-managed
domain index.
■ AUDIT on page 13-27 has new syntax that lets you audit various activities on data
mining models.
■ CALL on page 13-40 now permits positional, named, and mixed notation in the
argument to the routine being called, if the routine takes any arguments.
■ COMMENT on page 13-44 has a new MINING MODEL clause lets you provide
descriptive comments for a data mining model.
■ CREATE DISKGROUP on page 14-44 and ALTER DISKGROUP on page 10-51
have new syntax that lets you set various attributes of a disk group.
■ The new statements CREATE FLASHBACK ARCHIVE on page 14-56, ALTER
FLASHBACK ARCHIVE on page 10-73, and DROP FLASHBACK ARCHIVE on
page 17-46 let you create, modify, and drop flashback data archives, which in turn
let you track historical changes to tables.
■ CREATE INDEX on page 14-61 has been enhanced as follows:
– A new local_domain_index_clause on page 14-78 lets you create a locally
partitioned domain index.
– The index_attributes on page 14-72 have been modified to let you create an
index that is invisible to the optimizer.
– A new XMLIndex_clause on page 14-79 lets you create an XMLIndex index for
XML data.
■ CREATE INDEXTYPE on page 14-87 and ALTER INDEXTYPE on page 10-96 let
you specify that domain indexes built on the subject indextypes can be range
partitioned, and will have their storage tables and partition maintenance
operations managed by the database.
■ CREATE PFILE on page 15-45 has new syntax that lets you create a parameter file
from current system-wide parameter settings.
xxviii
■ CREATE RESTORE POINT on page 15-55 has new syntax that lets you create a
restore point for a specified datetime or SCN in the past, and to preserve a
flashback database.
■ CREATE SPFILE on page 15-70 has new syntax that lets you create a system
parameter file from current system-wide parameter settings.
■ CREATE TABLE on page 16-6 has been enhanced as follows:
– The flashback_archive_clause on page 16-64 lets you create the table with
tracking of historical changes enabled
– The clause system_partitioning on page 16-59 lets you partition the table BY
SYSTEM
– A new virtual_column_definition on page 16-28 lets you create a virtual column.
– New syntax for XML storage lets you store XML data in binary XML format.
– A new clause reference_partitioning on page 16-55 lets you partition a table by
reference to another partitioned table.
– The LOB_parameters on page 16-43 now include a SECUREFILE parameter,
which lets you specify a new storage for LOBs that is faster, more efficient, and
allows for new features such as LOB compression, encryption, and
deduplication.
– A new LOB_compression_clause on page 16-45 lets you enable or disable
server-side LOB compression for LOBs using SecureFile storage.
– A new LOB_deduplicate_clause on page 16-45 lets you coalesce duplicate data
into a single shared repository, reducing storage consumption and simplifying
storage management for LOBs using SecureFile storage.
– The LOB_parameters on page 16-43 now include ENCRYPT and DECRYPT
clauses to enable and disable encryption of LOB columns for LOBs using
SecureFile storage.
■ CREATE TABLESPACE on page 16-80 has new syntax which, along with a new
ENCRYPT keyword in the storage_clause on page 8-48, lets you encrypt an entire
tablespace.
■ DROP DISKGROUP on page 17-43 has a new FORCE keyword that lets you drop a
disk group that can no longer be mounted by an Oracle ASM instance.
■ GRANT on page 18-33 contains several new system and object privileges that
enable the grantee to work with data mining models.
■ LOCK TABLE on page 18-72 has new syntax that lets you specify the maximum
number of seconds the statement should wait to obtain a DML lock on the table.
■ MERGE on page 18-75 now supports operations on tables with domain indexes.
■ SELECT on page 19-4 has new PIVOT syntax that lets you rotate rows into
columns. A new UNPIVOT operation lets you query data to rotate columns into
rows.
The following SQL built-in functions have been added or enhanced:
■ CUBE_TABLE on page 5-51 is a new built-in function that extracts data from a
cube or dimension and returns it in the two-dimensional format of a relational
table.
■ INSERTXMLAFTER on page 5-89 let you add one or more nodes of any kind
immediately after a target node that is not an attribute node.
xxix
■ REGEXP_INSTR on page 5-160 and REGEXP_SUBSTR on page 5-164 now have an
optional subexpr parameter that lets you target a particular substring of the
regular expression being evaluated.
■ REGEXP_COUNT on page 5-158 is a new built-in function that counts the number
of occurrences of a specified regular expression pattern in a source string.
■ PREDICTION on page 5-139, PREDICTION_COST on page 5-142, and
PREDICTION_SET on page 5-147 have been enhanced. New syntax let you specify
that the stored cost matrix should be used only if it is available, or to specify a cost
matrix inline.
■ PREDICTION_BOUNDS on page 5-141 is a new function that returns the lower
and upper confidence bounds for a prediction.
■ XMLCAST on page 5-250 and XMLEXISTS on page 5-257 are two new functions
that let you cast XML data to SQL scalar data types and determine whether an
XQuery expression returns a nonempty XQuery sequence, respectively.
■ XMLDIFF on page 5-254 and XMLPATCH on page 5-260 are two new functions
that provide SQL interfaces to the corresponding XMLDiff and XMLPatch C APIs.
They let you compare two XMLType documents and use the diff file to patch an
XMLType document.
The following miscellaneous changes have been made:
■ In earlier releases, one form of expression in Chapter 6, "Expressions" was the
variable expression. This form has been renamed to placeholder expression for
consistency with other books in the documentation set. See "Placeholder
Expressions" on page 6-14.
■ In earlier releases, the TRUNCATE statement was presented as a single statement
with separate syntactic branches for TABLE and CLUSTER. That command has
now been divided into TRUNCATE CLUSTER on page 19-65 and TRUNCATE
TABLE on page 19-67 for consistency with other top-level SQL statements. No
actual syntax or semantic changes have occurred.
■ Two new hints, "RESULT_CACHE Hint" on page 3-102 and "NO_RESULT_
CACHE Hint" on page 3-93, let you override settings of the RESULT_CACHE_MODE
initialization parameter.
■ "Function Expressions" on page 6-10 now permit positional, named, and mixed
notation in the argument to a user-defined function being used as an expression.
■ The index_partition_description syntax of ALTER TABLE on page 12-2
and ALTER INDEX on page 10-77 now lets you specify parameters for a partition
of a domain index.
■ A new object type object type is supported with Oracle Multimedia. See
ORDDicom on page 3-36
xxx
1
Introduction to Oracle SQL 1-1
1 Introduction to Oracle SQL
Structured Query Language (SQL) is the set of statements with which all programs
and users access data in an Oracle Database. Application programs and Oracle tools
often allow users access to the database without using SQL directly, but these
applications in turn must use SQL when executing the user's request. This chapter
provides background information on SQL as used by most database systems.
This chapter contains these topics:
■ History of SQL
■ SQL Standards
■ Lexical Conventions
■ Tools Support
History of SQL
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared Data
Banks", in June 1970 in the Association of Computer Machinery (ACM) journal,
Communications of the ACM. Codd's model is now accepted as the definitive model for
relational database management systems (RDBMS). The language, Structured English
Query Language (SEQUEL) was developed by IBM Corporation, Inc., to use Codd's
model. SEQUEL later became SQL (still pronounced "sequel"). In 1979, Relational
Software, Inc. (now Oracle) introduced the first commercially available
implementation of SQL. Today, SQL is accepted as the standard RDBMS language.
SQL Standards
Oracle strives to comply with industry-accepted standards and participates actively in
SQL standards committees. Industry-accepted committees are the American National
Standards Institute (ANSI) and the International Organization for Standardization
(ISO), which is affiliated with the International Electrotechnical Commission (IEC).
Both ANSI and the ISO/IEC have accepted SQL as the standard language for
relational databases. When a new SQL standard is simultaneously published by these
organizations, the names of the standards conform to conventions used by the
organization, but the standards are technically identical.
The latest SQL standard was adopted in July 2008 and is often called SQL:2008. The
formal names of this standard are:
■ ANSI/ISO/IEC 9075:2008, "Database Language SQL", Parts 1
("SQL/Framework"), 2 ("SQL/Foundation"), 3 ("SQL/CLI"), 4 ("SQL/PSM"), 9
SQL Standards
1-2 Oracle Database SQL Language Reference
("SQL/MED"), 10 ("SQL/OLB"), 11("SQL/Schemata"), 13 ("SQL/JRT"), and
ANSI/ISO/IEC 9075-14:2008, "Database Language SQL", Part 14 ("SQL/XML")
■ ISO/IEC 9075:2008, "Database Language SQL", Parts 1 ("SQL/Framework"), 2
("SQL/Foundation"), 3 ("SQL/CLI"), 4 ("SQL/PSM"), 9 ("SQL/MED"), 10
("SQL/OLB"), 11("SQL/Schemata"), 13 ("SQL/JRT"), and ISO/IEC 9075-14:2008,
"Database Language SQL", Part 14 ("SQL/XML")
How SQL Works
The strengths of SQL provide benefits for all types of users, including application
programmers, database administrators, managers, and end users. Technically
speaking, SQL is a data sublanguage. The purpose of SQL is to provide an interface to
a relational database such as Oracle Database, and all SQL statements are instructions
to the database. In this SQL differs from general-purpose programming languages like
C and BASIC. Among the features of SQL are the following:
■ It processes sets of data as groups rather than as individual units.
■ It provides automatic navigation to the data.
■ It uses statements that are complex and powerful individually, and that therefore
stand alone. Flow-control statements were not part of SQL originally, but they are
found in the recently accepted optional part of SQL, ISO/IEC 9075-5: 1996.
Flow-control statements are commonly known as "persistent stored modules"
(PSM), and the PL/SQL extension to Oracle SQL is similar to PSM.
SQL lets you work with data at the logical level. You need to be concerned with the
implementation details only when you want to manipulate the data. For example, to
retrieve a set of rows from a table, you define a condition used to filter the rows. All
rows satisfying the condition are retrieved in a single step and can be passed as a unit
to the user, to another SQL statement, or to an application. You need not deal with the
rows one by one, nor do you have to worry about how they are physically stored or
retrieved. All SQL statements use the optimizer, a part of Oracle Database that
determines the most efficient means of accessing the specified data. Oracle also
provides techniques that you can use to make the optimizer perform its job better.
SQL provides statements for a variety of tasks, including:
■ Querying data
■ Inserting, updating, and deleting rows in a table
■ Creating, replacing, altering, and dropping objects
■ Controlling access to the database and its objects
■ Guaranteeing database consistency and integrity
SQL unifies all of the preceding tasks in one consistent language.
Common Language for All Relational Databases
All major relational database management systems support SQL, so you can transfer
all skills you have gained with SQL from one database to another. In addition, all
programs written in SQL are portable. They can often be moved from one database to
another with very little modification.
See Also: Appendix C, "Oracle and Standard SQL" for a detailed
description of Oracle Database conformance to the SQL:2008
standards
Tools Support
Introduction to Oracle SQL 1-3
Using Enterprise Manager
Many of the operations you can accomplish using SQL syntax can be done much more
easily using Enterprise Manager. For more information, see the Oracle Enterprise
Manager documentation set, Oracle Database 2 Day DBA, or any of the Oracle Database
2 Day + books.
Lexical Conventions
The following lexical conventions for issuing SQL statements apply specifically to the
Oracle Database implementation of SQL, but are generally acceptable in other SQL
implementations.
When you issue a SQL statement, you can include one or more tabs, carriage returns,
spaces, or comments anywhere a space occurs within the definition of the statement.
Thus, Oracle Database evaluates the following two statements in the same manner:
SELECT last_name,salary*12,MONTHS_BETWEEN(hire_date, SYSDATE)
FROM employees
WHERE department_id = 30
ORDER BY last_name;
SELECT last_name,
salary * 12,
MONTHS_BETWEEN( hire_date, SYSDATE )
FROM employees
WHERE department_id = 30
ORDER BY last_name;
Case is insignificant in reserved words, keywords, identifiers and parameters.
However, case is significant in text literals and quoted names. Refer to "Text Literals"
on page 3-46 for a syntax description of text literals.
Tools Support
Oracle provides a number of utilities to facilitate your SQL development process:
■ Oracle SQL Developer is a graphical tool that lets you browse, create, edit, and
delete (drop) database objects, edit and debug PL/SQL code, run SQL statements
and scripts, manipulate and export data, and create and view reports. With SQL
Developer, you can connect to any target Oracle Database schema using standard
Oracle Database authentication. Once connected, you can perform operations on
objects in the database. You can also connect to schemas for selected third-party
(non-Oracle) databases, such as MySQL, Microsoft SQL Server, and Microsoft
Access, view metadata and data in these databases, and migrate these databases to
Oracle.
■ SQL*Plus is an interactive and batch query tool that is installed with every Oracle
Database server or client installation. It has a command-line user interface and a
web-based user interface called iSQL*Plus.
■ Oracle JDeveloper is a multiple-platform integrated development environment
supporting the complete lifecycle of development for Java, Web services, and SQL.
It provides a graphical interface for executing and tuning SQL statements and a
Note: SQL statements are terminated differently in different
programming environments. This documentation set uses the default
SQL*Plus character, the semicolon (;).
Tools Support
1-4 Oracle Database SQL Language Reference
visual schema diagrammer (database modeler). It also supports editing,
compiling, and debugging PL/SQL applications.
■ Oracle Application Express is a hosted environment for developing and deploying
database-related Web applications. SQL Workshop is a component of Oracle
Application Express that lets you view and manage database objects from a Web
browser. SQL Workshop offers quick access to a SQL command processor and a
SQL script repository.
The Oracle Call Interface and Oracle precompilers let you embed standard SQL
statements within a procedure programming language.
■ The Oracle Call Interface (OCI) lets you embed SQL statements in C programs.
■ The Oracle precompilers, Pro*C/C++ and Pro*COBOL, interpret embedded SQL
statements and translate them into statements that can be understood by C/C++
and COBOL compilers, respectively.
Most (but not all) Oracle tools also support all features of Oracle SQL. This reference
describes the complete functionality of SQL. If the Oracle tool that you are using does
not support this complete functionality, then you can find a discussion of the
restrictions in the manual describing the tool, such as SQL*Plus User's Guide and
Reference.
See Also: SQL*Plus User's Guide and Reference and Oracle Application
Express Application Builder User's Guide for more information on these
products
See Also: Oracle C++ Call Interface Programmer's Guide, Pro*COBOL
Programmer's Guide, and Oracle Call Interface Programmer's Guide for
additional information on the embedded SQL statements allowed in
each product
2
Pseudocolumns 2-1
2 Pseudocolumns
A pseudocolumn behaves like a table column, but is not actually stored in the table.
You can select from pseudocolumns, but you cannot insert, update, or delete their
values. A pseudocolumn is also similar to a function without arguments (refer to
Chapter 5, "Functions"). However, functions without arguments typically return the
same value for every row in the result set, whereas pseudocolumns typically return a
different value for each row.
This chapter contains the following sections:
■ Hierarchical Query Pseudocolumns
■ Sequence Pseudocolumns
■ Version Query Pseudocolumns
■ COLUMN_VALUE Pseudocolumn
■ OBJECT_ID Pseudocolumn
■ OBJECT_VALUE Pseudocolumn
■ ORA_ROWSCN Pseudocolumn
■ ROWID Pseudocolumn
■ ROWNUM Pseudocolumn
■ XMLDATA Pseudocolumn
Hierarchical Query Pseudocolumns
The hierarchical query pseudocolumns are valid only in hierarchical queries. The
hierarchical query pseudocolumns are:
■ CONNECT_BY_ISCYCLE Pseudocolumn
■ CONNECT_BY_ISLEAF Pseudocolumn
■ LEVEL Pseudocolumn
To define a hierarchical relationship in a query, you must use the CONNECT BY clause.
CONNECT_BY_ISCYCLE Pseudocolumn
The CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a child
which is also its ancestor. Otherwise it returns 0.
Hierarchical Query Pseudocolumns
2-2 Oracle Database SQL Language Reference
You can specify CONNECT_BY_ISCYCLE only if you have specified the NOCYCLE
parameter of the CONNECT BY clause. NOCYCLE enables Oracle to return the results of
a query that would otherwise fail because of a CONNECT BY loop in the data.
CONNECT_BY_ISLEAF Pseudocolumn
The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a leaf of the
tree defined by the CONNECT BY condition. Otherwise it returns 0. This information
indicates whether a given row can be further expanded to show more of the hierarchy.
CONNECT_BY_ISLEAF Example The following example shows the first three levels
of the hr.employees table, indicating for each row whether it is a leaf row (indicated
by 1 in the IsLeaf column) or whether it has child rows (indicated by 0 in the
IsLeaf column):
SELECT last_name "Employee", CONNECT_BY_ISLEAF "IsLeaf",
LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
WHERE LEVEL <= 3 AND department_id = 80
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id AND LEVEL <= 4;
Employee IsLeaf LEVEL Path
------------------------- ---------- ---------- -------------------------
Abel 1 3 /King/Zlotkey/Abel
Ande 1 3 /King/Errazuriz/Ande
Banda 1 3 /King/Errazuriz/Banda
Bates 1 3 /King/Cambrault/Bates
Bernstein 1 3 /King/Russell/Bernstein
Bloom 1 3 /King/Cambrault/Bloom
Cambrault 0 2 /King/Cambrault
Cambrault 1 3 /King/Russell/Cambrault
Doran 1 3 /King/Partners/Doran
Errazuriz 0 2 /King/Errazuriz
Fox 1 3 /King/Cambrault/Fox
. . .
LEVEL Pseudocolumn
For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for
a root row, 2 for a child of a root, and so on. A root row is the highest row within an
inverted tree. A child row is any nonroot row. A parent row is any row that has
children. A leaf row is any row without children. Figure 2–1 shows the nodes of an
inverted tree with their LEVEL values.
See Also: "Hierarchical Queries" on page 9-3 for more information
about the NOCYCLE parameter and "Hierarchical Query Examples" on
page 9-5 for an example that uses the CONNECT_BY_ISCYCLE
pseudocolumn
See Also: "Hierarchical Queries" on page 9-3 and SYS_CONNECT_
BY_PATH on page 5-201
Sequence Pseudocolumns
Pseudocolumns 2-3
Figure 2–1 Hierarchical Tree
Sequence Pseudocolumns
A sequence is a schema object that can generate unique sequential values. These
values are often used for primary and unique keys. You can refer to sequence values in
SQL statements with these pseudocolumns:
■ CURRVAL: Returns the current value of a sequence
■ NEXTVAL: Increments the sequence and returns the next value
You must qualify CURRVAL and NEXTVAL with the name of the sequence:
sequence.CURRVAL
sequence.NEXTVAL
To refer to the current or next value of a sequence in the schema of another user, you
must have been granted either SELECT object privilege on the sequence or SELECT
ANY SEQUENCE system privilege, and you must qualify the sequence with the schema
containing it:
schema.sequence.CURRVAL
schema.sequence.NEXTVAL
To refer to the value of a sequence on a remote database, you must qualify the
sequence with a complete or partial name of a database link:
schema.sequence.CURRVAL@dblink
schema.sequence.NEXTVAL@dblink
A sequence can be accessed by many users concurrently with no waiting or locking.
Where to Use Sequence Values
You can use CURRVAL and NEXTVAL in the following locations:
■ The select list of a SELECT statement that is not contained in a subquery,
materialized view, or view
See Also: "Hierarchical Queries" on page 9-3 for information on
hierarchical queries in general and "IN Condition" on page 7-22 for
restrictions on using the LEVEL pseudocolumn
See Also: "References to Objects in Remote Databases" on page 3-113
for more information on referring to database links
Level 1
Level 2
Level 3
Level 4
child/
leaf
parent/
child
root/
parent
parent/
child
child/
leaf
child/
leaf
child/
leaf
child/
leaf
parent/
child
parent/
child
Sequence Pseudocolumns
2-4 Oracle Database SQL Language Reference
■ The select list of a subquery in an INSERT statement
■ The VALUES clause of an INSERT statement
■ The SET clause of an UPDATE statement
Restrictions on Sequence Values You cannot use CURRVAL and NEXTVAL in the
following constructs:
■ A subquery in a DELETE, SELECT, or UPDATE statement
■ A query of a view or of a materialized view
■ A SELECT statement with the DISTINCT operator
■ A SELECT statement with a GROUP BY clause or ORDER BY clause
■ A SELECT statement that is combined with another SELECT statement with the
UNION, INTERSECT, or MINUS set operator
■ The WHERE clause of a SELECT statement
■ The DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement
■ The condition of a CHECK constraint
Within a single SQL statement that uses CURRVAL or NEXTVAL, all referenced LONG
columns, updated tables, and locked tables must be located on the same database.
How to Use Sequence Values
When you create a sequence, you can define its initial value and the increment
between its values. The first reference to NEXTVAL returns the initial value of the
sequence. Subsequent references to NEXTVAL increment the sequence value by the
defined increment and return the new value. Any reference to CURRVAL always
returns the current value of the sequence, which is the value returned by the last
reference to NEXTVAL.
Before you use CURRVAL for a sequence in your session, you must first initialize the
sequence with NEXTVAL. Refer to CREATE SEQUENCE on page 15-66 for information
on sequences.
Within a single SQL statement containing a reference to NEXTVAL, Oracle increments
the sequence once:
■ For each row returned by the outer query block of a SELECT statement. Such a
query block can appear in the following places:
– A top-level SELECT statement
– An INSERT ... SELECT statement (either single-table or multitable). For a
multitable insert, the reference to NEXTVAL must appear in the VALUES clause,
and the sequence is updated once for each row returned by the subquery, even
though NEXTVAL may be referenced in multiple branches of the multitable
insert.
– A CREATE TABLE ... AS SELECT statement
– A CREATE MATERIALIZED VIEW ... AS SELECT statement
■ For each row updated in an UPDATE statement
■ For each INSERT statement containing a VALUES clause
■ For each INSERT ... [ALL | FIRST] statement (multitable insert). A multitable
insert is considered a single SQL statement. Therefore, a reference to the NEXTVAL
Sequence Pseudocolumns
Pseudocolumns 2-5
of a sequence will increase the sequence only once for each input record coming
from the SELECT portion of the statement. If NEXTVAL is specified more than once
in any part of the INSERT ... [ALL | FIRST ] statement, then the value will be the
same for all insert branches, regardless of how often a given record might be
inserted.
■ For each row merged by a MERGE statement. The reference to NEXTVAL can
appear in the merge_insert_clause or the merge_update_clause or both.
The NEXTVALUE value is incremented for each row updated and for each row
inserted, even if the sequence number is not actually used in the update or insert
operation. If NEXTVAL is specified more than once in any of these locations, then
the sequence is incremented once for each row and returns the same value for all
occurrences of NEXTVAL for that row.
■ For each input row in a multitable INSERT ALL statement. NEXTVAL is
incremented once for each row returned by the subquery, regardless of how many
occurrences of the insert_into_clause map to each row.
If any of these locations contains more than one reference to NEXTVAL, then Oracle
increments the sequence once and returns the same value for all occurrences of
NEXTVAL.
If any of these locations contains references to both CURRVAL and NEXTVAL, then
Oracle increments the sequence and returns the same value for both CURRVAL and
NEXTVAL.
Finding the next value of a sequence: Example This example selects the next value
of the employee sequence in the sample schema hr:
SELECT employees_seq.nextval
FROM DUAL;
Inserting sequence values into a table: Example This example increments the
employee sequence and uses its value for a new employee inserted into the sample
table hr.employees:
INSERT INTO employees
VALUES (employees_seq.nextval, 'John', 'Doe', 'jdoe',
'555-1212', TO_DATE(SYSDATE), 'PU_CLERK', 2500, null, null,
30);
Reusing the current value of a sequence: Example This example adds a new order
with the next order number to the master order table. It then adds suborders with this
number to the detail order table:
INSERT INTO orders (order_id, order_date, customer_id)
VALUES (orders_seq.nextval, TO_DATE(SYSDATE), 106);
INSERT INTO order_items (order_id, line_item_id, product_id)
VALUES (orders_seq.currval, 1, 2359);
INSERT INTO order_items (order_id, line_item_id, product_id)
VALUES (orders_seq.currval, 2, 3290);
INSERT INTO order_items (order_id, line_item_id, product_id)
VALUES (orders_seq.currval, 3, 2381);
Version Query Pseudocolumns
2-6 Oracle Database SQL Language Reference
Version Query Pseudocolumns
The version query pseudocolumns are valid only in Oracle Flashback Version Query,
which is a form of Oracle Flashback Query. The version query pseudocolumns are:
■ VERSIONS_STARTSCN and VERSIONS_STARTTIME: Starting System Change
Number (SCN) or TIMESTAMP when the row version was created. This
pseudocolumn identifies the time when the data first had the values reflected in
the row version. Use this pseudocolumn to identify the past target time for Oracle
Flashback Table or Oracle Flashback Query. If this pseudocolumn is NULL, then the
row version was created before start.
■ VERSIONS_ENDSCN and VERSIONS_ENDTIME: SCN or TIMESTAMP when the row
version expired. If the pseudocolumn is NULL, then either the row version was
current at the time of the query or the row corresponds to a DELETE operation.
■ VERSIONS_XID: Identifier (a RAW number) of the transaction that created the row
version.
■ VERSIONS_OPERATION: Operation performed by the transaction: I for insertion,
D for deletion, or U for update. The version is that of the row that was inserted,
deleted, or updated; that is, the row after an INSERT operation, the row before a
DELETE operation, or the row affected by an UPDATE operation.
For user updates of an index key, Oracle Flashback Version Query might treat an
UPDATE operation as two operations, DELETE plus INSERT, represented as two
version rows with a D followed by an I VERSIONS_OPERATION.
COLUMN_VALUE Pseudocolumn
When you refer to an XMLTable construct without the COLUMNS clause, or when you
use the TABLE collection expression to refer to a scalar nested table type, the database
returns a virtual table with a single column. This name of this pseudocolumn is
COLUMN_VALUE.
In the context of XMLTable, the value returned is of data type XMLType. For example,
the following two statements are equivalent, and the output for both shows COLUMN_
VALUE as the name of the column being returned:
SELECT * FROM XMLTABLE('<a>123</a>');
COLUMN_VALUE
---------------------------------------
<a>123</a>
SELECT COLUMN_VALUE FROM (XMLTable('<a>123</a>'));
COLUMN_VALUE
----------------------------------------
<a>123</a>
In the context of a TABLE collection expression, the value returned is the data type of
the collection element. The following statements create the two levels of nested tables
See Also:
■ flashback_query_clause on page 19-17 for more information on
version queries
■ Oracle Database Advanced Application Developer's Guide for more
information on using Oracle Flashback Version Query
OBJECT_ID Pseudocolumn
Pseudocolumns 2-7
illustrated in "Creating a Table: Multilevel Collection Example" on page 16-71 to show
the uses of COLUMN_VALUE in this context:
CREATE TYPE phone AS TABLE OF NUMBER;
/
CREATE TYPE phone_list AS TABLE OF phone;
/
The next statement uses COLUMN_VALUE to select from the phone type:
SELECT t.COLUMN_VALUE from table(phone(1,2,3)) t;
COLUMN_VALUE
------------
1
2
3
In a nested type, you can use the COLUMN_VALUE pseudocolumn in both the select list
and the TABLE collection expression:
SELECT t.COLUMN_VALUE FROM
TABLE(phone_list(phone(1,2,3))) p, TABLE(p.COLUMN_VALUE) t;
COLUMN_VALUE
------------
1
2
3
The keyword COLUMN_VALUE is also the name that Oracle Database generates for the
scalar value of an inner nested table without a column or attribute name, as shown in
the example that follows. In this context, COLUMN_VALUE is not a pseudocolumn, but
an actual column name.
CREATE TABLE my_customers (
cust_id NUMBER,
name VARCHAR2(25),
phone_numbers phone_list,
credit_limit NUMBER)
NESTED TABLE phone_numbers STORE AS outer_ntab
(NESTED TABLE COLUMN_VALUE STORE AS inner_ntab);
OBJECT_ID Pseudocolumn
The OBJECT_ID pseudocolumn returns the object identifier of a column of an object
table or view. Oracle uses this pseudocolumn as the primary key of an object table.
OBJECT_ID is useful in INSTEAD OF triggers on views and for identifying the ID of a
substitutable row in an object table.
See Also:
■ XMLTABLE on page 5-267 for information on that function
■ table_collection_expression::= on page 18-57 for information on the
TABLE collection expression
■ ALTER TABLE examples in "Nested Tables: Examples" on
page 12-87
OBJECT_VALUE Pseudocolumn
2-8 Oracle Database SQL Language Reference
OBJECT_VALUE Pseudocolumn
The OBJECT_VALUE pseudocolumn returns system-generated names for the columns
of an object table, XMLType table, object view, or XMLType view. This pseudocolumn is
useful for identifying the value of a substitutable row in an object table and for
creating object views with the WITH OBJECT IDENTIFIER clause.
ORA_ROWSCN Pseudocolumn
For each row, ORA_ROWSCN returns the conservative upper bound system change
number (SCN) of the most recent change to the row in the current session. This
pseudocolumn is useful for determining approximately when a row was last updated.
It is not absolutely precise, because Oracle tracks SCNs by transaction committed for
the block in which the row resides. You can obtain a more fine-grained approximation
of the SCN by creating your tables with row-level dependency tracking. Refer to
CREATE TABLE ... NOROWDEPENDENCIES | ROWDEPENDENCIES on page 16-62
for more information on row-level dependency tracking.
You cannot use this pseudocolumn in a query to a view. However, you can use it to
refer to the underlying table when creating a view. You can also use this
pseudocolumn in the WHERE clause of an UPDATE or DELETE statement.
ORA_ROWSCN is not supported for Flashback Query. Instead, use the version query
pseudocolumns, which are provided explicitly for Flashback Query. Refer to the
SELECT ... flashback_query_clause on page 19-17 for information on Flashback Query
and "Version Query Pseudocolumns" on page 2-6 for additional information on those
pseudocolumns.
Restriction on ORA_ROWSCN: This pseudocolumn is not supported for external
tables.
Example The first statement below uses the ORA_ROWSCN pseudocolumn to get the
system change number of the last operation on the employees table. The second
Note: In earlier releases, this pseudocolumn was called SYS_NC_
OID$. That name is still supported for backward compatibility.
However, Oracle recommends that you use the more intuitive name
OBJECT_ID.
See Also: Oracle Database Object-Relational Developer's Guide for
examples of the use of this pseudocolumn
Note: In earlier releases, this pseudocolumn was called SYS_NC_
ROWINFO$. That name is still supported for backward compatibility.
However, Oracle recommends that you use the more intuitive name
OBJECT_VALUE.
See Also:
■ object_table on page 16-66 and object_view_clause on page 17-18 for
more information on the use of this pseudocolumn
■ Oracle Database Object-Relational Developer's Guide for examples of
the use of this pseudocolumn
ROWNUM Pseudocolumn
Pseudocolumns 2-9
statement uses the pseudocolumn with the SCN_TO_TIMESTAMP function to
determine the timestamp of the operation:
SELECT ORA_ROWSCN, last_name FROM employees WHERE employee_id = 188;
SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN), last_name FROM employees
WHERE employee_id = 188;
ROWID Pseudocolumn
For each row in the database, the ROWID pseudocolumn returns the address of the row.
Oracle Database rowid values contain information necessary to locate a row:
■ The data object number of the object
■ The data block in the data file in which the row resides
■ The position of the row in the data block (first row is 0)
■ The data file in which the row resides (first file is 1). The file number is relative to
the tablespace.
Usually, a rowid value uniquely identifies a row in the database. However, rows in
different tables that are stored together in the same cluster can have the same rowid.
Values of the ROWID pseudocolumn have the data type ROWID or UROWID. Refer to
"Rowid Data Types" on page 3-27 and "UROWID Data Type" on page 3-28 for more
information.
Rowid values have several important uses:
■ They are the fastest way to access a single row.
■ They can show you how the rows in a table are stored.
■ They are unique identifiers for rows in a table.
You should not use ROWID as the primary key of a table. If you delete and reinsert a
row with the Import and Export utilities, for example, then its rowid may change. If
you delete a row, then Oracle may reassign its rowid to a new row inserted later.
Although you can use the ROWID pseudocolumn in the SELECT and WHERE clause of a
query, these pseudocolumn values are not actually stored in the database. You cannot
insert, update, or delete a value of the ROWID pseudocolumn.
Example This statement selects the address of all rows that contain data for
employees in department 20:
SELECT ROWID, last_name
FROM employees
WHERE department_id = 20;
ROWNUM Pseudocolumn
See Also: SCN_TO_TIMESTAMP on page 5-178
Note: The ROW_NUMBER built-in SQL function provides superior
support for ordering the results of a query. Refer to ROW_NUMBER
on page 5-174 for more information.
XMLDATA Pseudocolumn
2-10 Oracle Database SQL Language Reference
For each row returned by a query, the ROWNUM pseudocolumn returns a number
indicating the order in which Oracle selects the row from a table or set of joined rows.
The first row selected has a ROWNUM of 1, the second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query, as in this
example:
SELECT * FROM employees WHERE ROWNUM < 11;
If an ORDER BY clause follows ROWNUM in the same query, then the rows will be
reordered by the ORDER BY clause. The results can vary depending on the way the
rows are accessed. For example, if the ORDER BY clause causes Oracle to use an index
to access the data, then Oracle may retrieve the rows in a different order than without
the index. Therefore, the following statement does not necessarily return the same
rows as the preceding example:
SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY last_name;
If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in
the top-level query, then you can force the ROWNUM condition to be applied after the
ordering of the rows. For example, the following query returns the employees with the
10 smallest employee numbers. This is sometimes referred to as top-N reporting:
SELECT * FROM
(SELECT * FROM employees ORDER BY employee_id)
WHERE ROWNUM < 11;
In the preceding example, the ROWNUM values are those of the top-level SELECT
statement, so they are generated after the rows have already been ordered by
employee_id in the subquery.
Conditions testing for ROWNUM values greater than a positive integer are always false.
For example, this query returns no rows:
SELECT * FROM employees
WHERE ROWNUM > 1;
The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The
second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and
makes the condition false. All rows subsequently fail to satisfy the condition, so no
rows are returned.
You can also use ROWNUM to assign unique values to each row of a table, as in this
example:
UPDATE my_table
SET column1 = ROWNUM;
Refer to the function ROW_NUMBER on page 5-174 for an alternative method of
assigning unique numbers to rows.
XMLDATA Pseudocolumn
Oracle stores XMLType data either in LOB or object-relational columns, based on
XMLSchema information and how you specify the storage clause. The XMLDATA
pseudocolumn lets you access the underlying LOB or object relational column to
specify additional storage clause parameters, constraints, indexes, and so forth.
Note: Using ROWNUM in a query can affect view optimization.
XMLDATA Pseudocolumn
Pseudocolumns 2-11
Example The following statements illustrate the use of this pseudocolumn. Suppose
you create a simple table of XMLType:
CREATE TABLE xml_lob_tab of XMLTYPE;
The default storage is in a CLOB column. To change the storage characteristics of the
underlying LOB column, you can use the following statement:
ALTER TABLE xml_lob_tab MODIFY LOB (XMLDATA)
(STORAGE (MAXSIZE 2G) CACHE);
Now suppose you have created an XMLSchema-based table like the xwarehouses
table created in "Using XML in SQL Statements" on page F-8. You could then use the
XMLDATA column to set the properties of the underlying columns, as shown in the
following statement:
ALTER TABLE xwarehouses ADD (UNIQUE(XMLDATA."WarehouseId"));
XMLDATA Pseudocolumn
2-12 Oracle Database SQL Language Reference
3
Basic Elements of Oracle SQL 3-1
3 Basic Elements of Oracle SQL
This chapter contains reference information on the basic elements of Oracle SQL.
These elements are the simplest building blocks of SQL statements. Therefore, before
using the statements described in Chapter 10 through Chapter 19, you should
familiarize yourself with the concepts covered in this chapter.
This chapter contains these sections:
■ Data Types
■ Data Type Comparison Rules
■ Literals
■ Format Models
■ Nulls
■ Comments
■ Database Objects
■ Database Object Names and Qualifiers
■ Syntax for Schema Objects and Parts in SQL Statements
Data Types
Each value manipulated by Oracle Database has a data type. The data type of a value
associates a fixed set of properties with the value. These properties cause Oracle to
treat values of one data type differently from values of another. For example, you can
add values of NUMBER data type, but not values of RAW data type.
When you create a table or cluster, you must specify a data type for each of its
columns. When you create a procedure or stored function, you must specify a data
type for each of its arguments. These data types define the domain of values that each
column can contain or each argument can have. For example, DATE columns cannot
accept the value February 29 (except for a leap year) or the values 2 or 'SHOE'. Each
value subsequently placed in a column assumes the data type of the column. For
example, if you insert '01-JAN-98' into a DATE column, then Oracle treats the
'01-JAN-98' character string as a DATE value after verifying that it translates to a
valid date.
Oracle Database provides a number of built-in data types as well as several categories
for user-defined types that can be used as data types. The syntax of Oracle data types
appears in the diagrams that follow. The text of this section is divided into the
following sections:
■ Oracle Built-in Data Types
Data Types
3-2 Oracle Database SQL Language Reference
■ ANSI, DB2, and SQL/DS Data Types
■ User-Defined Types
■ Oracle-Supplied Types
■ Data Type Comparison Rules
■ Data Conversion
A data type is either scalar or nonscalar. A scalar type contains an atomic value,
whereas a nonscalar (sometimes called a "collection") contains a set of values. A large
object (LOB) is a special form of scalar data type representing a large scalar value of
binary or character data. LOBs are subject to some restrictions that do not affect other
scalar types because of their size. Those restrictions are documented in the context of
the relevant SQL syntax.
The Oracle precompilers recognize other data types in embedded SQL programs.
These data types are called external data types and are associated with host variables.
Do not confuse built-in data types and user-defined types with external data types. For
information on external data types, including how Oracle converts between them and
built-in data types or user-defined types, see Pro*COBOL Programmer's Guide, and
Pro*C/C++ Programmer's Guide.
datatypes::=
Oracle_built_in_datatypes::=
For descriptions of the Oracle built-in data types, refer to "Oracle Built-in Data Types"
on page 3-6.
See Also: "Restrictions on LOB Columns" on page 3-25
Oracle_built_in_datatypes
ANSI_supported_datatypes
user_defined_types
Oracle_supplied_types
character_datatypes
number_datatypes
long_and_raw_datatypes
datetime_datatypes
large_object_datatypes
rowid_datatypes
Data Types
Basic Elements of Oracle SQL 3-3
character_datatypes::=
number_datatypes::=
long_and_raw_datatypes::=
datetime_datatypes::=
CHAR
( size
BYTE
CHAR
)
VARCHAR2 ( size
BYTE
CHAR
)
NCHAR
( size )
NVARCHAR2 ( size )
NUMBER
( precision
, scale
)
FLOAT
( precision )
BINARY_FLOAT
BINARY_DOUBLE
LONG
LONG RAW
RAW ( size )
DATE
TIMESTAMP
( fractional_seconds_precision ) WITH
LOCAL
TIME ZONE
INTERVAL YEAR
( year_precision )
TO MONTH
INTERVAL DAY
( day_precision )
TO SECOND
( fractional_seconds_precision )
Data Types
3-4 Oracle Database SQL Language Reference
large_object_datatypes::=
rowid_datatypes::=
The ANSI-supported data types appear in the figure that follows. "ANSI, DB2, and
SQL/DS Data Types" on page 3-28 discusses the mapping of ANSI-supported data
types to Oracle built-in data types.
ANSI_supported_datatypes::=
BLOB
CLOB
NCLOB
BFILE
ROWID
UROWID
( size )
CHARACTER
VARYING
( size )
CHAR
NCHAR
VARYING ( size )
VARCHAR ( size )
NATIONAL
CHARACTER
CHAR
VARYING
( size )
NUMERIC
DECIMAL
DEC
( precision
, scale
)
INTEGER
INT
SMALLINT
FLOAT
( size )
DOUBLE PRECISION
REAL
Data Types
Basic Elements of Oracle SQL 3-5
Oracle_supplied_types::=
For a description of the expression_filter_type, refer to "Expression Filter Type"
on page 3-36. Other Oracle-supplied types follow:
any_types::=
For descriptions of the Any types, refer to "Any Types" on page 3-32.
XML_types::=
For descriptions of the XML types, refer to "XML Types" on page 3-32.
spatial_types::=
For descriptions of the spatial types, refer to "Spatial Types" on page 3-34.
media_types::=
any_types
XML_types
spatial_types
media_types
expression_filter_type
SYS.AnyData
SYS.AnyType
SYS.AnyDataSet
XMLType
URIType
SDO_Geometry
SDO_Topo_Geometry
SDO_GeoRaster
ORDAudio
ORDImage
ORDVideo
ORDDoc
ORDDicom
still_image_object_types
Data Types
3-6 Oracle Database SQL Language Reference
still_image_object_types::=
For descriptions of the media types, refer to "Media Types" on page 3-35.
Oracle Built-in Data Types
The table that follows summarizes Oracle built-in data types. Refer to the syntax in the
preceding sections for the syntactic elements. The codes listed for the data types are
used internally by Oracle Database. The data type code of a column or object attribute
is returned by the DUMP function.
Table 3–1 Built-in Data Type Summary
Code Data Type Description
1 VARCHAR2(size [BYTE | CHAR]) Variable-length character string having maximum length size
bytes or characters. Maximum size is 4000 bytes or characters,
and minimum is 1 byte or 1 character. You must specify size for
VARCHAR2.
BYTE indicates that the column will have byte length semantics.
CHAR indicates that the column will have character semantics.
1 NVARCHAR2(size) Variable-length Unicode character string having maximum
length size characters. The number of bytes can be up to two
times size for AL16UTF16 encoding and three times size for
UTF8 encoding. Maximum size is determined by the national
character set definition, with an upper limit of 4000 bytes. You
must specify size for NVARCHAR2.
2 NUMBER [ (p [, s]) ] Number having precision p and scale s. The precision p can
range from 1 to 38. The scale s can range from -84 to 127. Both
precision and scale are in decimal digits. A NUMBER value
requires from 1 to 22 bytes.
2 FLOAT [(p)] A subtype of the NUMBER data type having precision p. A FLOAT
value is represented internally as NUMBER. The precision p can
range from 1 to 126 binary digits. A FLOAT value requires from 1
to 22 bytes.
8 LONG Character data of variable length up to 2 gigabytes, or 231
-1
bytes. Provided for backward compatibility.
12 DATE Valid date range from January 1, 4712 BC, to December 31, 9999
AD. The default format is determined explicitly by the NLS_
DATE_FORMAT parameter or implicitly by the NLS_TERRITORY
parameter. The size is fixed at 7 bytes. This data type contains
the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and
SECOND. It does not have fractional seconds or a time zone.
21 BINARY_FLOAT 32-bit floating point number. This data type requires 4 bytes.
SI_StillImage
SI_AverageColor
SI_PositionalColor
SI_ColorHistogram
SI_Texture
SI_FeatureList
SI_Color
Data Types
Basic Elements of Oracle SQL 3-7
22 BINARY_DOUBLE 64-bit floating point number. This data type requires 8 bytes.
180 TIMESTAMP [(fractional_
seconds_precision)]
Year, month, and day values of date, as well as hour, minute,
and second values of time, where fractional_seconds_
precision is the number of digits in the fractional part of the
SECOND datetime field. Accepted values of fractional_
seconds_precision are 0 to 9. The default is 6. The default
format is determined explicitly by the NLS_DATE_FORMAT
parameter or implicitly by the NLS_TERRITORY parameter. The
size is 7 or 11 bytes, depending on the precision. This data type
contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE,
and SECOND. It contains fractional seconds but does not have a
time zone.
181 TIMESTAMP [(fractional_
seconds)] WITH TIME ZONE
All values of TIMESTAMP as well as time zone displacement
value, where fractional_seconds_precision is the
number of digits in the fractional part of the SECOND datetime
field. Accepted values are 0 to 9. The default is 6. The default
format is determined explicitly by the NLS_DATE_FORMAT
parameter or implicitly by the NLS_TERRITORY parameter. The
size is fixed at 13 bytes. This data type contains the datetime
fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_
HOUR, and TIMEZONE_MINUTE. It has fractional seconds and an
explicit time zone.
231 TIMESTAMP [(fractional_
seconds)] WITH LOCAL TIME ZONE
All values of TIMESTAMP WITH TIME ZONE, with the following
exceptions:
■ Data is normalized to the database time zone when it is
stored in the database.
■ When the data is retrieved, users see the data in the session
time zone.
The default format is determined explicitly by the NLS_DATE_
FORMAT parameter or implicitly by the NLS_TERRITORY
parameter. The size is 7 or 11 bytes, depending on the precision.
182 INTERVAL YEAR [(year_
precision)] TO MONTH
Stores a period of time in years and months, where year_
precision is the number of digits in the YEAR datetime field.
Accepted values are 0 to 9. The default is 2. The size is fixed at 5
bytes.
183 INTERVAL DAY [(day_precision)]
TO SECOND [(fractional_
seconds)]
Stores a period of time in days, hours, minutes, and seconds,
where
■ day_precision is the maximum number of digits in the
DAY datetime field. Accepted values are 0 to 9. The default
is 2.
■ fractional_seconds_precision is the number of
digits in the fractional part of the SECOND field. Accepted
values are 0 to 9. The default is 6.
The size is fixed at 11 bytes.
23 RAW(size) Raw binary data of length size bytes. Maximum size is 2000
bytes. You must specify size for a RAW value.
24 LONG RAW Raw binary data of variable length up to 2 gigabytes.
69 ROWID Base 64 string representing the unique address of a row in its
table. This data type is primarily for values returned by the
ROWID pseudocolumn.
208 UROWID [(size)] Base 64 string representing the logical address of a row of an
index-organized table. The optional size is the size of a column
of type UROWID. The maximum size and default is 4000 bytes.
Table 3–1 (Cont.) Built-in Data Type Summary
Code Data Type Description
Data Types
3-8 Oracle Database SQL Language Reference
The sections that follow describe the Oracle data types as they are stored in Oracle
Database. For information on specifying these data types as literals, refer to "Literals"
on page 3-45.
Character Data Types
Character data types store character (alphanumeric) data, which are words and
free-form text, in the database character set or national character set. They are less
restrictive than other data types and consequently have fewer properties. For example,
character columns can store all alphanumeric values, but NUMBER columns can store
only numeric values.
Character data is stored in strings with byte values corresponding to one of the
character sets, such as 7-bit ASCII or EBCDIC, specified when the database was
created. Oracle Database supports both single-byte and multibyte character sets.
These data types are used for character data:
■ CHAR Data Type
■ NCHAR Data Type
■ NVARCHAR2 Data Type
■ VARCHAR2 Data Type
For information on specifying character data types as literals, refer to "Text Literals" on
page 3-46.
96 CHAR [(size [BYTE | CHAR])] Fixed-length character data of length size bytes or characters.
Maximum size is 2000 bytes or characters. Default and
minimum size is 1 byte.
BYTE and CHAR have the same semantics as for VARCHAR2.
96 NCHAR[(size)] Fixed-length character data of length size characters. The
number of bytes can be up to two times size for AL16UTF16
encoding and three times size for UTF8 encoding. Maximum
size is determined by the national character set definition, with
an upper limit of 2000 bytes. Default and minimum size is 1
character.
112 CLOB A character large object containing single-byte or multibyte
characters. Both fixed-width and variable-width character sets
are supported, both using the database character set. Maximum
size is (4 gigabytes - 1) * (database block size).
112 NCLOB A character large object containing Unicode characters. Both
fixed-width and variable-width character sets are supported,
both using the database national character set. Maximum size is
(4 gigabytes - 1) * (database block size). Stores national character
set data.
113 BLOB A binary large object. Maximum size is (4 gigabytes - 1) *
(database block size).
114 BFILE Contains a locator to a large binary file stored outside the
database. Enables byte stream I/O access to external LOBs
residing on the database server. Maximum size is 4 gigabytes.
Table 3–1 (Cont.) Built-in Data Type Summary
Code Data Type Description
Data Types
Basic Elements of Oracle SQL 3-9
CHAR Data Type
The CHAR data type specifies a fixed-length character string. Oracle ensures that all
values stored in a CHAR column have the length specified by size. If you insert a
value that is shorter than the column length, then Oracle blank-pads the value to
column length. If you try to insert a value that is too long for the column, then Oracle
returns an error.
The default length for a CHAR column is 1 byte and the maximum allowed is 2000
bytes. A 1-byte string can be inserted into a CHAR(10) column, but the string is
blank-padded to 10 bytes before it is stored.
When you create a table with a CHAR column, by default you supply the column
length in bytes. The BYTE qualifier is the same as the default. If you use the CHAR
qualifier, for example CHAR(10 CHAR), then you supply the column length in
characters. A character is technically a code point of the database character set. Its size
can range from 1 byte to 4 bytes, depending on the database character set. The BYTE
and CHAR qualifiers override the semantics specified by the NLS_LENGTH_
SEMANTICS parameter, which has a default of byte semantics. For performance
reasons, Oracle recommends that you use the NLS_LENGTH_SEMANTICS parameter to
set length semantics and that you use the BYTE and CHAR qualifiers only when
necessary to override the parameter.
To ensure proper data conversion between databases with different character sets, you
must ensure that CHAR data consists of well-formed strings.
NCHAR Data Type
The NCHAR data type is a Unicode-only data type. When you create a table with an
NCHAR column, you define the column length in characters. You define the national
character set when you create your database.
The maximum length of a column is determined by the national character set
definition. Width specifications of character data type NCHAR refer to the number of
characters. The maximum column size allowed is 2000 bytes.
If you insert a value that is shorter than the column length, then Oracle blank-pads the
value to column length. You cannot insert a CHAR value into an NCHAR column, nor
can you insert an NCHAR value into a CHAR column.
The following example compares the translated_description column of the
pm.product_descriptions table with a national character set string:
SELECT translated_description FROM product_descriptions
WHERE translated_name = N'LCD Monitor 11/PM';
NVARCHAR2 Data Type
The NVARCHAR2 data type is a Unicode-only data type. When you create a table with
an NVARCHAR2 column, you supply the maximum number of characters it can hold.
Oracle subsequently stores each value in the column exactly as you specify it,
provided the value does not exceed the maximum length of the column.
See Also: Oracle Database Globalization Support Guide for more
information on character set support and "Data Type Comparison
Rules" on page 3-37 for information on comparison semantics
See Also: Oracle Database Globalization Support Guide for information
on Unicode data type support
Data Types
3-10 Oracle Database SQL Language Reference
The maximum length of the column is determined by the national character set
definition. Width specifications of character data type NVARCHAR2 refer to the number
of characters. The maximum column size allowed is 4000 bytes.
VARCHAR2 Data Type
The VARCHAR2 data type specifies a variable-length character string. When you create
a VARCHAR2 column, you supply the maximum number of bytes or characters of data
that it can hold. Oracle subsequently stores each value in the column exactly as you
specify it, provided the value does not exceed the column's maximum length of the
column. If you try to insert a value that exceeds the specified length, then Oracle
returns an error.
You must specify a maximum length for a VARCHAR2 column. This maximum must be
at least 1 byte, although the actual string stored is permitted to be a zero-length string
(''). You can use the CHAR qualifier, for example VARCHAR2(10 CHAR), to give the
maximum length in characters instead of bytes. A character is technically a code point
of the database character set. You can use the BYTE qualifier, for example
VARCHAR2(10 BYTE), to explicitly give the maximum length in bytes. If no explicit
qualifier is included in a column or attribute definition when a database object with
this column or attribute is created, then the length semantics are determined by the
value of the NLS_LENGTH_SEMANTICS parameter of the session creating the object.
Independently of the maximum length in characters, the length of VARCHAR2 data
cannot exceed 4000 bytes. Oracle compares VARCHAR2 values using nonpadded
comparison semantics.
To ensure proper data conversion between databases with different character sets, you
must ensure that VARCHAR2 data consists of well-formed strings. See Oracle Database
Globalization Support Guide for more information on character set support.
VARCHAR Data Type
Do not use the VARCHAR data type. Use the VARCHAR2 data type instead. Although the
VARCHAR data type is currently synonymous with VARCHAR2, the VARCHAR data type
is scheduled to be redefined as a separate data type used for variable-length character
strings compared with different comparison semantics.
Numeric Data Types
The Oracle Database numeric data types store positive and negative fixed and
floating-point numbers, zero, infinity, and values that are the undefined result of an
operation—"not a number" or NAN. For information on specifying numeric data types
as literals, refer to "Numeric Literals" on page 3-47.
NUMBER Data Type
The NUMBER data type stores zero as well as positive and negative fixed numbers with
absolute values from 1.0 x 10-130
to but not including 1.0 x 10126
. If you specify an
arithmetic expression whose value has an absolute value greater than or equal to 1.0 x
10126
, then Oracle returns an error. Each NUMBER value requires from 1 to 22 bytes.
Specify a fixed-point number using the following form:
NUMBER(p,s)
See Also: Oracle Database Globalization Support Guide for information
on Unicode data type support.
See Also: "Data Type Comparison Rules" on page 3-37 for
information on comparison semantics
Data Types
Basic Elements of Oracle SQL 3-11
where:
■ p is the precision, or the maximum number of significant decimal digits, where
the most significant digit is the left-most nonzero digit, and the least significant
digit is the right-most known digit. Oracle guarantees the portability of numbers
with precision of up to 20 base-100 digits, which is equivalent to 39 or 40 decimal
digits depending on the position of the decimal point.
■ s is the scale, or the number of digits from the decimal point to the least
significant digit. The scale can range from -84 to 127.
– Positive scale is the number of significant digits to the right of the decimal
point to and including the least significant digit.
– Negative scale is the number of significant digits to the left of the decimal
point, to but not including the least significant digit. For negative scale the
least significant digit is on the left side of the decimal point, because the actual
data is rounded to the specified number of places to the left of the decimal
point. For example, a specification of (10,-2) means to round to hundreds.
Scale can be greater than precision, most commonly when e notation is used. When
scale is greater than precision, the precision specifies the maximum number of
significant digits to the right of the decimal point. For example, a column defined as
NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all
values past the fifth digit after the decimal point.
It is good practice to specify the scale and precision of a fixed-point number column
for extra integrity checking on input. Specifying scale and precision does not force all
values to a fixed length. If a value exceeds the precision, then Oracle returns an error. If
a value exceeds the scale, then Oracle rounds it.
Specify an integer using the following form:
NUMBER(p)
This represents a fixed-point number with precision p and scale 0 and is equivalent to
NUMBER(p,0).
Specify a floating-point number using the following form:
NUMBER
The absence of precision and scale designators specifies the maximum range and
precision for an Oracle number.
Table 3–2 show how Oracle stores data using different precisions and scales.
See Also: "Floating-Point Numbers" on page 3-12
Table 3–2 Storage of Scale and Precision
Actual Data Specified As Stored As
123.89 NUMBER 123.89
123.89 NUMBER(3) 124
123.89 NUMBER(3,2) exceeds precision
123.89 NUMBER(4,2) exceeds precision
123.89 NUMBER(5,2) 123.89
123.89 NUMBER(6,1) 123.9
Data Types
3-12 Oracle Database SQL Language Reference
FLOAT Data Type
The FLOAT data type is a subtype of NUMBER. It can be specified with or without
precision, which has the same definition it has for NUMBER and can range from 1 to
126. Scale cannot be specified, but is interpreted from the data. Each FLOAT value
requires from 1 to 22 bytes.
To convert from binary to decimal precision, multiply n by 0.30103. To convert from
decimal to binary precision, multiply the decimal precision by 3.32193. The maximum
of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision.
The difference between NUMBER and FLOAT is best illustrated by example. In the
following example the same values are inserted into NUMBER and FLOAT columns:
CREATE TABLE test (col1 NUMBER(5,2), col2 FLOAT(5));
INSERT INTO test VALUES (1.23, 1.23);
INSERT INTO test VALUES (7.89, 7.89);
INSERT INTO test VALUES (12.79, 12.79);
INSERT INTO test VALUES (123.45, 123.45);
SELECT * FROM test;
COL1 COL2
---------- ----------
1.23 1.2
7.89 7.9
12.79 13
123.45 120
In this example, the FLOAT value returned cannot exceed 5 binary digits. The largest
decimal number that can be represented by 5 binary digits is 31. The last row contains
decimal values that exceed 31. Therefore, the FLOAT value must be truncated so that
its significant digits do not require more than 5 binary digits. Thus 123.45 is rounded
to 120, which has only two significant decimal digits, requiring only 4 binary digits.
Oracle Database uses the Oracle FLOAT data type internally when converting ANSI
FLOAT data. Oracle FLOAT is available for you to use, but Oracle recommends that you
use the BINARY_FLOAT and BINARY_DOUBLE data types instead, as they are more
robust. Refer to "Floating-Point Numbers" on page 3-12 for more information.
Floating-Point Numbers
Floating-point numbers can have a decimal point anywhere from the first to the last
digit or can have no decimal point at all. An exponent may optionally be used
123.89 NUMBER(6,-2) 100
.01234 NUMBER(4,5) .01234
.00012 NUMBER(4,5) .00012
.000127 NUMBER(4,5) .00013
.0000012 NUMBER(2,7) .0000012
.00000123 NUMBER(2,7) .0000012
1.2e-4 NUMBER(2,5) 0.00012
1.2e-5 NUMBER(2,5) 0.00001
Table 3–2 (Cont.) Storage of Scale and Precision
Actual Data Specified As Stored As
Data Types
Basic Elements of Oracle SQL 3-13
following the number to increase the range, for example, 1.777 e-20
. A scale value is not
applicable to floating-point numbers, because the number of digits that can appear
after the decimal point is not restricted.
Binary floating-point numbers differ from NUMBER in the way the values are stored
internally by Oracle Database. Values are stored using decimal precision for NUMBER.
All literals that are within the range and precision supported by NUMBER are stored
exactly as NUMBER. Literals are stored exactly because literals are expressed using
decimal precision (the digits 0 through 9). Binary floating-point numbers are stored
using binary precision (the digits 0 and 1). Such a storage scheme cannot represent all
values using decimal precision exactly. Frequently, the error that occurs when
converting a value from decimal to binary precision is undone when the value is
converted back from binary to decimal precision. The literal 0.1 is such an example.
Oracle Database provides two numeric data types exclusively for floating-point
numbers:
BINARY_FLOAT BINARY_FLOAT is a 32-bit, single-precision floating-point number data
type. Each BINARY_FLOAT value requires 4 bytes.
BINARY_DOUBLE BINARY_DOUBLE is a 64-bit, double-precision floating-point number
data type. Each BINARY_DOUBLE value requires 8 bytes.
In a NUMBER column, floating point numbers have decimal precision. In a BINARY_
FLOAT or BINARY_DOUBLE column, floating-point numbers have binary precision.
The binary floating-point numbers support the special values infinity and NaN (not a
number).
You can specify floating-point numbers within the limits listed in Table 3–3 on
page 3-13. The format for specifying floating-point numbers is defined in "Numeric
Literals" on page 3-47.
IEEE754 Conformance The Oracle implementation of floating-point data types
conforms substantially with the Institute of Electrical and Electronics Engineers (IEEE)
Standard for Binary Floating-Point Arithmetic, IEEE Standard 754-1985 (IEEE754). The
floating-point data types conform to IEEE754 in the following areas:
■ The SQL function SQRT implements square root. See SQRT on page 5-183.
■ The SQL function REMAINDER implements remainder. See REMAINDER on
page 5-171.
■ Arithmetic operators conform. See "Arithmetic Operators" on page 4-3.
■ Comparison operators conform, except for comparisons with NaN. Oracle orders
NaN greatest with respect to all other values, and evaluates NaN equal to NaN. See
"Floating-Point Conditions" on page 7-7.
■ Conversion operators conform. See "Conversion Functions" on page 5-6.
■ The default rounding mode is supported.
■ The default exception handling mode is supported.
Table 3–3 Floating Point Number Limits
Value BINARY_FLOAT BINARY_DOUBLE
Maximum positive finite value 3.40282E+38F 1.79769313486231E+308
Minimum positive finite value 1.17549E-38F 2.22507485850720E-308
Data Types
3-14 Oracle Database SQL Language Reference
■ The special values INF, -INF, and NaN are supported. See "Floating-Point
Conditions" on page 7-7.
■ Rounding of BINARY_FLOAT and BINARY_DOUBLE values to integer-valued
BINARY_FLOAT and BINARY_DOUBLE values is provided by the SQL functions
ROUND, TRUNC, CEIL, and FLOOR.
■ Rounding of BINARY_FLOAT/BINARY_DOUBLE to decimal and decimal to
BINARY_FLOAT/BINARY_DOUBLE is provided by the SQL functions TO_CHAR,
TO_NUMBER, TO_NCHAR, TO_BINARY_FLOAT, TO_BINARY_DOUBLE, and CAST.
The floating-point data types do not conform to IEEE754 in the following areas:
■ -0 is coerced to +0.
■ Comparison with NaN is not supported.
■ All NaN values are coerced to either BINARY_FLOAT_NAN or BINARY_DOUBLE_
NAN.
■ Non-default rounding modes are not supported.
■ Non-default exception handling mode are not supported.
Numeric Precedence
Numeric precedence determines, for operations that support numeric data types, the
data type Oracle uses if the arguments to the operation have different data types.
BINARY_DOUBLE has the highest numeric precedence, followed by BINARY_FLOAT,
and finally by NUMBER. Therefore, in any operation on multiple numeric values:
■ If any of the operands is BINARY_DOUBLE, then Oracle attempts to convert all the
operands implicitly to BINARY_DOUBLE before performing the operation.
■ If none of the operands is BINARY_DOUBLE but any of the operands is BINARY_
FLOAT, then Oracle attempts to convert all the operands implicitly to BINARY_
FLOAT before performing the operation.
■ Otherwise, Oracle attempts to convert all the operands to NUMBER before
performing the operation.
If any implicit conversion is needed and fails, then the operation fails. Refer to
Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on
implicit conversion.
In the context of other data types, numeric data types have lower precedence than the
datetime/interval data types and higher precedence than character and all other data
types.
LONG Data Type
Do not create tables with LONG columns. Use LOB columns (CLOB, NCLOB, BLOB)
instead. LONG columns are supported only for backward compatibility.
LONG columns store variable-length character strings containing up to 2 gigabytes -1,
or 231
-1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns.
You can use LONG columns to store long text strings. The length of LONG values may
be limited by the memory available on your computer. LONG literals are formed as
described for "Text Literals" on page 3-46.
Oracle also recommends that you convert existing LONG columns to LOB columns.
LOB columns are subject to far fewer restrictions than LONG columns. Further, LOB
functionality is enhanced in every release, whereas LONG functionality has been static
for several releases. See the modify_col_properties clause of ALTER TABLE on
Data Types
Basic Elements of Oracle SQL 3-15
page 12-2 and TO_LOB on page 5-225 for more information on converting LONG
columns to LOB.
You can reference LONG columns in SQL statements in these places:
■ SELECT lists
■ SET clauses of UPDATE statements
■ VALUES clauses of INSERT statements
The use of LONG values is subject to these restrictions:
■ A table can contain only one LONG column.
■ You cannot create an object type with a LONG attribute.
■ LONG columns cannot appear in WHERE clauses or in integrity constraints (except
that they can appear in NULL and NOT NULL constraints).
■ LONG columns cannot be indexed.
■ LONG data cannot be specified in regular expressions.
■ A stored function cannot return a LONG value.
■ You can declare a variable or argument of a PL/SQL program unit using the LONG
data type. However, you cannot then call the program unit from SQL.
■ Within a single SQL statement, all LONG columns, updated tables, and locked
tables must be located on the same database.
■ LONG and LONG RAW columns cannot be used in distributed SQL statements and
cannot be replicated.
■ If a table has both LONG and LOB columns, then you cannot bind more than 4000
bytes of data to both the LONG and LOB columns in the same SQL statement.
However, you can bind more than 4000 bytes of data to either the LONG or the LOB
column.
In addition, LONG columns cannot appear in these parts of SQL statements:
■ GROUP BY clauses, ORDER BY clauses, or CONNECT BY clauses or with the
DISTINCT operator in SELECT statements
■ The UNIQUE operator of a SELECT statement
■ The column list of a CREATE CLUSTER statement
■ The CLUSTER clause of a CREATE MATERIALIZED VIEW statement
■ SQL built-in functions, expressions, or conditions
■ SELECT lists of queries containing GROUP BY clauses
■ SELECT lists of subqueries or queries combined by the UNION, INTERSECT, or
MINUS set operators
■ SELECT lists of CREATE TABLE ... AS SELECT statements
■ ALTER TABLE ... MOVE statements
■ SELECT lists in subqueries in INSERT statements
Triggers can use the LONG data type in the following manner:
■ A SQL statement within a trigger can insert data into a LONG column.
Data Types
3-16 Oracle Database SQL Language Reference
■ If data from a LONG column can be converted to a constrained data type (such as
CHAR and VARCHAR2), then a LONG column can be referenced in a SQL statement
within a trigger.
■ Variables in triggers cannot be declared using the LONG data type.
■ :NEW and :OLD cannot be used with LONG columns.
You can use Oracle Call Interface functions to retrieve a portion of a LONG value from
the database.
Datetime and Interval Data Types
The datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, and
TIMESTAMP WITH LOCAL TIME ZONE. Values of datetime data types are sometimes
called datetimes. The interval data types are INTERVAL YEAR TO MONTH and
INTERVAL DAY TO SECOND. Values of interval data types are sometimes called
intervals. For information on expressing datetime and interval values as literals, refer
to "Datetime Literals" on page 3-50 and "Interval Literals" on page 3-52.
Both datetimes and intervals are made up of fields. The values of these fields
determine the value of the data type. Table 3–4 lists the datetime fields and their
possible values for datetimes and intervals.
To avoid unexpected results in your DML operations on datetime data, you can verify
the database and session time zones by querying the built-in SQL functions
DBTIMEZONE and SESSIONTIMEZONE. If the time zones have not been set manually,
then Oracle Database uses the operating system time zone by default. If the operating
system time zone is not a valid Oracle time zone, then Oracle uses UTC as the default
value.
See Also: Oracle Call Interface Programmer's Guide
Table 3–4 Datetime Fields and Values
Datetime Field Valid Values for Datetime Valid Values for INTERVAL
YEAR -4712 to 9999 (excluding year 0) Any positive or negative
integer
MONTH 01 to 12 0 to 11
DAY 01 to 31 (limited by the values of MONTH and YEAR,
according to the rules of the current NLS calendar
parameter)
Any positive or negative
integer
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
SECOND 00 to 59.9(n), where 9(n) is the precision of time
fractional seconds. The 9(n) portion is not applicable
for DATE.
0 to 59.9(n), where 9(n) is the
precision of interval
fractional seconds
TIMEZONE_HOUR -12 to 14 (This range accommodates daylight saving
time changes.) Not applicable for DATE or
TIMESTAMP.
Not applicable
Data Types
Basic Elements of Oracle SQL 3-17
DATE Data Type
The DATE data type stores date and time information. Although date and time
information can be represented in both character and number data types, the DATE
data type has special associated properties. For each DATE value, Oracle stores the
following information: century, year, month, date, hour, minute, and second.
You can specify a DATE value as a literal, or you can convert a character or numeric
value to a date value with the TO_DATE function. For examples of expressing DATE
values in both these ways, refer to "Datetime Literals" on page 3-50.
Using Julian Days A Julian day number is the number of days since January 1, 4712 BC.
Julian days allow continuous dating from a common reference. You can use the date
format model "J" with date functions TO_DATE and TO_CHAR to convert between
Oracle DATE values and their Julian equivalents.
The default date values are determined as follows:
■ The year is the current year, as returned by SYSDATE.
■ The month is the current month, as returned by SYSDATE.
■ The day is 01 (the first day of the month).
■ The hour, minute, and second are all 0.
These default values are used in a query that requests date values where the date itself
is not specified, as in the following example, which is issued in the month of May:
TIMEZONE_MINUTE
(See note at end of table)
00 to 59. Not applicable for DATE or TIMESTAMP. Not applicable
TIMEZONE_REGION Query the TZNAME column of the V$TIMEZONE_
NAMES data dictionary view. Not applicable for
DATE or TIMESTAMP. For a complete listing of all
time zone region names, refer to Oracle Database
Globalization Support Guide.
Not applicable
TIMEZONE_ABBR Query the TZABBREV column of the V$TIMEZONE_
NAMES data dictionary view. Not applicable for
DATE or TIMESTAMP.
Not applicable
Note: TIMEZONE_HOUR and TIMEZONE_MINUTE are specified
together and interpreted as an entity in the format +|- hh:mm, with
values ranging from -12:59 to +14:00. Refer to Oracle Data Provider for
.NET Developer's Guide for information on specifying time zone values
for that API.
Note: Oracle Database uses the astronomical system of calculating
Julian days, in which the year 4713 BC is specified as -4712. The
historical system of calculating Julian days, in contrast, specifies 4713
BC as -4713. If you are comparing Oracle Julian days with values
calculated using the historical system, then take care to allow for the
365-day difference in BC dates. For more information, see
http://aa.usno.navy.mil/faq/docs/millennium.php.
Table 3–4 (Cont.) Datetime Fields and Values
Datetime Field Valid Values for Datetime Valid Values for INTERVAL
Data Types
3-18 Oracle Database SQL Language Reference
SELECT TO_DATE('2005', 'YYYY') FROM DUAL;
TO_DATE('
---------
01-MAY-05
Example This statement returns the Julian equivalent of January 1, 1997:
SELECT TO_CHAR(TO_DATE('01-01-1997', 'MM-DD-YYYY'),'J')
FROM DUAL;
TO_CHAR
--------
2450450
TIMESTAMP Data Type
The TIMESTAMP data type is an extension of the DATE data type. It stores the year,
month, and day of the DATE data type, plus hour, minute, and second values. This
data type is useful for storing precise time values and for collecting and evaluating
date information across geographic regions. Specify the TIMESTAMP data type as
follows:
TIMESTAMP [(fractional_seconds_precision)]
where fractional_seconds_precision optionally specifies the number of digits
Oracle stores in the fractional part of the SECOND datetime field. When you create a
column of this data type, the value can be a number in the range 0 to 9. The default is
6.
TIMESTAMP WITH TIME ZONE Data Type
TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time zone
region name or a a time zone offset in its value. The time zone offset is the difference
(in hours and minutes) between local time and UTC (Coordinated Universal
Time—formerly Greenwich Mean Time). This data type is useful for preserving local
time zone information.
Specify the TIMESTAMP WITH TIME ZONE data type as follows:
TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE
where fractional_seconds_precision optionally specifies the number of digits
Oracle stores in the fractional part of the SECOND datetime field. When you create a
column of this data type, the value can be a number in the range 0 to 9. The default is
6.
Oracle time zone data is derived from the public domain information available at
ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most
recent data available at this site.
See Also: "Selecting from the DUAL Table" for a description of the
DUAL table
See Also: TO_TIMESTAMP on page 5-230 for information on
converting character data to TIMESTAMP data
Data Types
Basic Elements of Oracle SQL 3-19
TIMESTAMP WITH LOCAL TIME ZONE Data Type
TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP that includes a
time zone offset in its value. It differs from TIMESTAMP WITH TIME ZONE in that data
stored in the database is normalized to the database time zone, and the time zone
offset is not stored as part of the column data. When a user retrieves the data, Oracle
returns it in the user's local session time zone. The time zone offset is the difference (in
hours and minutes) between local time and UTC (Coordinated Universal
Time—formerly Greenwich Mean Time). This data type is useful for displaying date
information in the time zone of the client system in a two-tier application.
Specify the TIMESTAMP WITH LOCAL TIME ZONE data type as follows:
TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE
where fractional_seconds_precision optionally specifies the number of digits
Oracle stores in the fractional part of the SECOND datetime field. When you create a
column of this data type, the value can be a number in the range 0 to 9. The default is
6.
Oracle time zone data is derived from the public domain information available at
ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most
recent data available at this site.
INTERVAL YEAR TO MONTH Data Type
INTERVAL YEAR TO MONTH stores a period of time using the YEAR and MONTH
datetime fields. This data type is useful for representing the difference between two
datetime values when only the year and month values are significant.
Specify INTERVAL YEAR TO MONTH as follows:
INTERVAL YEAR [(year_precision)] TO MONTH
where year_precision is the number of digits in the YEAR datetime field. The
default value of year_precision is 2.
See Also:
■ Oracle Database Globalization Support Guide for more information
on Oracle time zone data
■ "Support for Daylight Saving Times" on page 3-22 and Table 3–17,
" Matching Character Data and Format Models with the FX
Format Model Modifier" on page 3-67 for information on daylight
saving support
■ TO_TIMESTAMP_TZ on page 5-231 for information on converting
character data to TIMESTAMP WITH TIME ZONE data
■ ALTER SESSION on page 11-45 for information on the ERROR_
ON_OVERLAP_TIME session parameter
See Also:
■ Oracle Database Globalization Support Guide for more information
on Oracle time zone data
■ Oracle Database Advanced Application Developer's Guide for
examples of using this data type and CAST on page 5-28 for
information on converting character data to TIMESTAMP WITH
LOCAL TIME ZONE
Data Types
3-20 Oracle Database SQL Language Reference
You have a great deal of flexibility when specifying interval values as literals. Refer to
"Interval Literals" on page 3-52 for detailed information on specifying interval values
as literals. Also see "Datetime and Interval Examples" on page 3-23 for an example
using intervals.
INTERVAL DAY TO SECOND Data Type
INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes,
and seconds. This data type is useful for representing the precise difference between
two datetime values.
Specify this data type as follows:
INTERVAL DAY [(day_precision)]
TO SECOND [(fractional_seconds_precision)]
where
■ day_precision is the number of digits in the DAY datetime field. Accepted
values are 0 to 9. The default is 2.
■ fractional_seconds_precision is the number of digits in the fractional part
of the SECOND datetime field. Accepted values are 0 to 9. The default is 6.
You have a great deal of flexibility when specifying interval values as literals. Refer to
"Interval Literals" on page 3-52 for detailed information on specify interval values as
literals. Also see "Datetime and Interval Examples" on page 3-23 for an example using
intervals.
Datetime/Interval Arithmetic
You can perform a number of arithmetic operations on date (DATE), timestamp
(TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME
ZONE) and interval (INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH) data.
Oracle calculates the results based on the following rules:
■ You can use NUMBER constants in arithmetic operations on date and timestamp
values, but not interval values. Oracle internally converts timestamp values to
date values and interprets NUMBER constants in arithmetic datetime and interval
expressions as numbers of days. For example, SYSDATE + 1 is tomorrow. SYSDATE
- 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting the
hire_date column of the sample table employees from SYSDATE returns the
number of days since each employee was hired. You cannot multiply or divide
date or timestamp values.
■ Oracle implicitly converts BINARY_FLOAT and BINARY_DOUBLE operands to
NUMBER.
■ Each DATE value contains a time component, and the result of many date
operations include a fraction. This fraction means a portion of one day. For
example, 1.5 days is 36 hours. These fractions are also returned by Oracle built-in
functions for common operations on DATE data. For example, the MONTHS_
BETWEEN function returns the number of months between two dates. The
fractional portion of the result represents that portion of a 31-day month.
■ If one operand is a DATE value or a numeric value, neither of which contains time
zone or fractional seconds components, then:
– Oracle implicitly converts the other operand to DATE data. The exception is
multiplication of a numeric value times an interval, which returns an interval.
Data Types
Basic Elements of Oracle SQL 3-21
– If the other operand has a time zone value, then Oracle uses the session time
zone in the returned value.
– If the other operand has a fractional seconds value, then the fractional seconds
value is lost.
■ When you pass a timestamp, interval, or numeric value to a built-in function that
was designed only for the DATE data type, Oracle implicitly converts the
non-DATE value to a DATE value. Refer to "Datetime Functions" on page 5-5 for
information on which functions cause implicit conversion to DATE.
■ When interval calculations return a datetime value, the result must be an actual
datetime value or the database returns an error. For example, the next two
statements return errors:
SELECT TO_DATE('31-AUG-2004','DD-MON-YYYY') + TO_YMINTERVAL('0-1') FROM DUAL;
SELECT TO_DATE('29-FEB-2004','DD-MON-YYYY') + TO_YMINTERVAL('1-0') FROM DUAL;
The first fails because adding one month to a 31-day month would result in
September 31, which is not a valid date. The second fails because adding one year
to a date that exists only every four years is not valid. However, the next statement
succeeds, because adding four years to a February 29 date is valid:
SELECT TO_DATE('29-FEB-2004', 'DD-MON-YYYY') + TO_YMINTERVAL('4-0') FROM DUAL;
TO_DATE('
---------
29-FEB-08
■ Oracle performs all timestamp arithmetic in UTC time. For TIMESTAMP WITH
LOCAL TIME ZONE, Oracle converts the datetime value from the database time
zone to UTC and converts back to the database time zone after performing the
arithmetic. For TIMESTAMP WITH TIME ZONE, the datetime value is always in
UTC, so no conversion is necessary.
Table 3–5 is a matrix of datetime arithmetic operations. Dashes represent operations
that are not supported.
Table 3–5 Matrix of Datetime Arithmetic
Operand & Operator DATE TIMESTAMP INTERVAL Numeric
DATE
+ — — DATE DATE
- NUMBER INTERVAL DATE DATE
* — — — —
/ — — — —
TIMESTAMP
+ — — TIMESTAMP DATE
- INTERVAL INTERVAL TIMESTAMP DATE
* — — — —
/ — — — —
INTERVAL
+ DATE TIMESTAMP INTERVAL —
Data Types
3-22 Oracle Database SQL Language Reference
Examples You can add an interval value expression to a start time. Consider the
sample table oe.orders with a column order_date. The following statement adds
30 days to the value of the order_date column:
SELECT order_id, order_date + INTERVAL '30' DAY FROM orders
ORDER BY order_id, "Due Date";
Support for Daylight Saving Times
Oracle Database automatically determines, for any given time zone region, whether
daylight saving is in effect and returns local time values accordingly. The datetime
value is sufficient for Oracle to determine whether daylight saving time is in effect for
a given region in all cases except boundary cases. A boundary case occurs during the
period when daylight saving goes into or comes out of effect. For example, in the
US-Pacific region, when daylight saving goes into effect, the time changes from 2:00
a.m. to 3:00 a.m. The one hour interval between 2 and 3 a.m. does not exist. When
daylight saving goes out of effect, the time changes from 2:00 a.m. back to 1:00 a.m.,
and the one-hour interval between 1 and 2 a.m. is repeated.
To resolve these boundary cases, Oracle uses the TZR and TZD format elements, as
described in Table 3–17. TZR represents the time zone region name in datetime input
strings. Examples are 'Australia/North', 'UTC', and 'Singapore'. TZD represents
an abbreviated form of the time zone region name with daylight saving information.
Examples are 'PST' for US/Pacific standard time and 'PDT' for US/Pacific daylight
time. To see a listing of valid values for the TZR and TZD format elements, query the
TZNAME and TZABBREV columns of the V$TIMEZONE_NAMES dynamic performance
view.
For a complete listing of the time zone region names in both files, refer to Oracle
Database Globalization Support Guide.
- — — INTERVAL —
* — — — INTERVAL
/ — — — INTERVAL
Numeric
+ DATE DATE — NA
- — — — NA
* — — INTERVAL NA
/ — — — NA
Note: Time zone region names are needed by the daylight saving
feature. These names are stored in two types of time zone files: one
large and one small. One of these files is the default file, depending
on your environment and the release of Oracle Database you are
using. For more information regarding time zone files and names,
see Oracle Database Globalization Support Guide.
Table 3–5 (Cont.) Matrix of Datetime Arithmetic
Operand & Operator DATE TIMESTAMP INTERVAL Numeric
Data Types
Basic Elements of Oracle SQL 3-23
Oracle time zone data is derived from the public domain information available at
ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most
recent data available at this site.
Datetime and Interval Examples
The following example shows how to specify some datetime and interval data types.
CREATE TABLE time_table (
start_time TIMESTAMP,
duration_1 INTERVAL DAY (6) TO SECOND (5),
duration_2 INTERVAL YEAR TO MONTH);
The start_time column is of type TIMESTAMP. The implicit fractional seconds
precision of TIMESTAMP is 6.
The duration_1 column is of type INTERVAL DAY TO SECOND. The maximum
number of digits in field DAY is 6 and the maximum number of digits in the fractional
second is 5. The maximum number of digits in all other datetime fields is 2.
The duration_2 column is of type INTERVAL YEAR TO MONTH. The maximum
number of digits of the value in each field (YEAR and MONTH) is 2.
Interval data types do not have format models. Therefore, to adjust their presentation,
you must combine character functions such as EXTRACT and concatenate the
components. For example, the following examples query the hr.employees and
oe.orders tables, respectively, and change interval output from the form "yy-mm" to
"yy years mm months" and from "dd-hh" to "dddd days hh hours":
SELECT last_name, EXTRACT(YEAR FROM (SYSDATE - hire_date) YEAR TO MONTH )
|| ' years '
|| EXTRACT(MONTH FROM (SYSDATE - hire_date) YEAR TO MONTH )
|| ' months' "Interval"
FROM employees ;
LAST_NAME Interval
------------------------- --------------------
King 6 years 1 months
Kochhar 3 years 9 months
De Haan 8 years 6 months
Hunold 3 years 6 months
Ernst 2 years 1 months
Austin 4 years 0 months
Pataballa 3 years 5 months
Lorentz 2 years 5 months
Greenberg 6 years 11 months
. . .
SELECT order_id,
EXTRACT(DAY FROM (SYSDATE - order_date) DAY TO SECOND )
See Also:
■ "Datetime Format Models" on page 3-59 for information on the
format elements and the session parameter ERROR_ON_
OVERLAP_TIME on page 11-51.
■ Oracle Database Globalization Support Guide for more information
on Oracle time zone data
■ Oracle Database Reference for information on the dynamic
performance views
Data Types
3-24 Oracle Database SQL Language Reference
|| ' days '
|| EXTRACT(HOUR FROM (SYSDATE - order_date) DAY TO SECOND )
|| ' hours' "Interval"
FROM orders;
ORDER_ID Interval
---------- --------------------
2458 2095 days 18 hours
2397 2000 days 17 hours
2454 2048 days 16 hours
2354 1762 days 16 hours
2358 1950 days 15 hours
2381 1823 days 13 hours
2440 2080 days 12 hours
2357 2680 days 11 hours
2394 1917 days 10 hours
2435 2078 days 10 hours
. . .
RAW and LONG RAW Data Types
The RAW and LONG RAW data types store data that is not to be explicitly converted by
Oracle Database when moving data between different systems. These data types are
intended for binary data or byte strings. For example, you can use LONG RAW to store
graphics, sound, documents, or arrays of binary data, for which the interpretation is
dependent on the use.
Oracle strongly recommends that you convert LONG RAW columns to binary LOB
(BLOB) columns. LOB columns are subject to far fewer restrictions than LONG columns.
See TO_LOB on page 5-225 for more information.
RAW is a variable-length data type like VARCHAR2, except that Oracle Net (which
connects user sessions to the instance) and the Oracle import and export utilities do
not perform character conversion when transmitting RAW or LONG RAW data. In
contrast, Oracle Net and the Oracle import and export utilities automatically convert
CHAR, VARCHAR2, and LONG data from the database character set to the user session
character set. If the two character sets are different, you can set the user session
character set with the NLS_LANGUAGE parameter of the ALTER SESSION statement.
When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the
binary data is represented in hexadecimal form, with one hexadecimal character
representing every four bits of RAW data. For example, one byte of RAW data with bits
11001011 is displayed and entered as CB.
Large Object (LOB) Data Types
The built-in LOB data types BLOB, CLOB, and NCLOB (stored internally) and BFILE
(stored externally) can store large and unstructured data such as text, image, video,
and spatial data. The size of BLOB, CLOB, and NCLOB data can be up to (232
-1 bytes) *
(the value of the CHUNK parameter of LOB storage). If the tablespaces in your database
are of standard block size, and if you have used the default value of the CHUNK
parameter of LOB storage when creating a LOB column, then this is equivalent to
(232
-1 bytes) * (database block size). BFILE data can be up to 264
-1 bytes, although your
operating system may impose restrictions on this maximum.
When creating a table, you can optionally specify different tablespace and storage
characteristics for LOB columns or LOB object attributes from those specified for the
table.
Data Types
Basic Elements of Oracle SQL 3-25
CLOB, NCLOB, and BLOB values up to approximately 4000 bytes are stored inline if you
enable storage in row at the time the LOB column is created. LOBs greater than 4000
bytes are always stored externally. Refer to ENABLE STORAGE IN ROW on
page 16-43 for more information.
LOB columns contain LOB locators that can refer to internal (in the database) or
external (outside the database) LOB values. Selecting a LOB from a table actually
returns the LOB locator and not the entire LOB value. The DBMS_LOB package and
Oracle Call Interface (OCI) operations on LOBs are performed through these locators.
LOBs are similar to LONG and LONG RAW types, but differ in the following ways:
■ LOBs can be attributes of an object type (user-defined data type).
■ The LOB locator is stored in the table column, either with or without the actual
LOB value. BLOB, NCLOB, and CLOB values can be stored in separate tablespaces.
BFILE data is stored in an external file on the server.
■ When you access a LOB column, the locator is returned.
■ A LOB can be up to (232
-1 bytes)*(database block size) in size. BFILE data can be
up to 264
-1 bytes, although your operating system may impose restrictions on this
maximum.
■ LOBs permit efficient, random, piece-wise access to and manipulation of data.
■ You can define more than one LOB column in a table.
■ With the exception of NCLOB, you can define one or more LOB attributes in an
object.
■ You can declare LOB bind variables.
■ You can select LOB columns and LOB attributes.
■ You can insert a new row or update an existing row that contains one or more LOB
columns or an object with one or more LOB attributes. In update operations, you
can set the internal LOB value to NULL, empty, or replace the entire LOB with data.
You can set the BFILE to NULL or make it point to a different file.
■ You can update a LOB row-column intersection or a LOB attribute with another
LOB row-column intersection or LOB attribute.
■ You can delete a row containing a LOB column or LOB attribute and thereby also
delete the LOB value. For BFILEs, the actual operating system file is not deleted.
You can access and populate rows of an inline LOB column (a LOB column stored in
the database) or a LOB attribute (an attribute of an object type column stored in the
database) simply by issuing an INSERT or UPDATE statement.
Restrictions on LOB Columns LOB columns are subject to a number of rules and
restrictions. See Oracle Database SecureFiles and Large Objects Developer's Guide for a
complete listing.
See Also:
■ Oracle Database PL/SQL Packages and Types Reference and Oracle Call
Interface Programmer's Guide for more information about these
interfaces and LOBs
■ the modify_col_properties clause of ALTER TABLE on
page 12-2 and TO_LOB on page 5-225 for more information on
converting LONG columns to LOB columns
Data Types
3-26 Oracle Database SQL Language Reference
BFILE Data Type
The BFILE data type enables access to binary file LOBs that are stored in file systems
outside Oracle Database. A BFILE column or attribute stores a BFILE locator, which
serves as a pointer to a binary file on the server file system. The locator maintains the
directory name and the filename.
You can change the filename and path of a BFILE without affecting the base table by
using the BFILENAME function. Refer to BFILENAME on page 5-24 for more
information on this built-in SQL function.
Binary file LOBs do not participate in transactions and are not recoverable. Rather, the
underlying operating system provides file integrity and durability. BFILE data can be
up to 264
-1 bytes, although your operating system may impose restrictions on this
maximum.
The database administrator must ensure that the external file exists and that Oracle
processes have operating system read permissions on the file.
The BFILE data type enables read-only support of large binary files. You cannot
modify or replicate such a file. Oracle provides APIs to access file data. The primary
interfaces that you use to access file data are the DBMS_LOB package and Oracle Call
Interface (OCI).
BLOB Data Type
The BLOB data type stores unstructured binary large objects. BLOB objects can be
thought of as bitstreams with no character set semantics. BLOB objects can store binary
data up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage). If the
tablespaces in your database are of standard block size, and if you have used the
default value of the CHUNK parameter of LOB storage when creating a LOB column,
then this is equivalent to (4 gigabytes - 1) * (database block size).
BLOB objects have full transactional support. Changes made through SQL, the DBMS_
LOB package, or Oracle Call Interface (OCI) participate fully in the transaction. BLOB
value manipulations can be committed and rolled back. However, you cannot save a
BLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another
transaction or session.
CLOB Data Type
The CLOB data type stores single-byte and multibyte character data. Both fixed-width
and variable-width character sets are supported, and both use the database character
set. CLOB objects can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of
LOB storage) of character data. If the tablespaces in your database are of standard
block size, and if you have used the default value of the CHUNK parameter of LOB
storage when creating a LOB column, then this is equivalent to (4 gigabytes - 1) *
(database block size).
CLOB objects have full transactional support. Changes made through SQL, the DBMS_
LOB package, or Oracle Call Interface (OCI) participate fully in the transaction. CLOB
value manipulations can be committed and rolled back. However, you cannot save a
CLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another
transaction or session.
See Also: Oracle Database SecureFiles and Large Objects Developer's
Guide and Oracle Call Interface Programmer's Guide for more
information about LOBs and CREATE DIRECTORY on page 14-42
Data Types
Basic Elements of Oracle SQL 3-27
NCLOB Data Type
The NCLOB data type stores Unicode data. Both fixed-width and variable-width
character sets are supported, and both use the national character set. NCLOB objects
can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage) of
character text data. If the tablespaces in your database are of standard block size, and if
you have used the default value of the CHUNK parameter of LOB storage when creating
a LOB column, then this is equivalent to (4 gigabytes - 1) * (database block size).
NCLOB objects have full transactional support. Changes made through SQL, the DBMS_
LOB package, or OCI participate fully in the transaction. NCLOB value manipulations
can be committed and rolled back. However, you cannot save an NCLOB locator in a
PL/SQL or OCI variable in one transaction and then use it in another transaction or
session.
Rowid Data Types
Each row in the database has an address. The sections that follow describe the two
forms of row address in an Oracle Database.
ROWID Data Type
The rows in heap-organized tables that are native to Oracle Database have row
addresses called rowids. You can examine a rowid row address by querying the
pseudocolumn ROWID. Values of this pseudocolumn are strings representing the
address of each row. These strings have the data type ROWID. You can also create tables
and clusters that contain actual columns having the ROWID data type. Oracle Database
does not guarantee that the values of such columns are valid rowids. Refer to
Chapter 2, "Pseudocolumns" for more information on the ROWID pseudocolumn.
Rowids contain the following information:
■ The data block of the data file containing the row. The length of this string
depends on your operating system.
■ The row in the data block.
■ The database file containing the row. The first data file has the number 1. The
length of this string depends on your operating system.
■ The data object number, which is an identification number assigned to every
database segment. You can retrieve the data object number from the data
dictionary views USER_OBJECTS, DBA_OBJECTS, and ALL_OBJECTS. Objects
that share the same segment (clustered tables in the same cluster, for example)
have the same object number.
See Also: Oracle Database Globalization Support Guide for information
on Unicode data type support
Note: Beginning with Oracle8, Oracle SQL incorporated an extended
format for rowids to efficiently support partitioned tables and indexes
and tablespace-relative data block addresses without ambiguity. If you
are running Version 7 of the database and you intend to upgrade, use
the DBMS_ROWID package to migrate rowids in your data to the
extended format. Refer to Oracle Database PL/SQL Packages and Types
Reference for information on DBMS_ROWID and to Oracle Database
Upgrade Guide for information on upgrading from Oracle7.
Data Types
3-28 Oracle Database SQL Language Reference
Rowids are stored as base 64 values that can contain the characters A-Z, a-z, 0-9, and
the plus sign (+) and forward slash (/). Rowids are not available directly. You can use
the supplied package DBMS_ROWID to interpret rowid contents. The package functions
extract and provide information on the four rowid elements listed above.
UROWID Data Type
The rows of some tables have addresses that are not physical or permanent or were not
generated by Oracle Database. For example, the row addresses of index-organized
tables are stored in index leaves, which can move. Rowids of foreign tables (such as
DB2 tables accessed through a gateway) are not standard Oracle rowids.
Oracle uses universal rowids (urowids) to store the addresses of index-organized and
foreign tables. Index-organized tables have logical urowids and foreign tables have
foreign urowids. Both types of urowid are stored in the ROWID pseudocolumn (as are
the physical rowids of heap-organized tables).
Oracle creates logical rowids based on the primary key of the table. The logical rowids
do not change as long as the primary key does not change. The ROWID pseudocolumn
of an index-organized table has a data type of UROWID. You can access this
pseudocolumn as you would the ROWID pseudocolumn of a heap-organized table
(using a SELECT ... ROWID statement). If you want to store the rowids of an
index-organized table, then you can define a column of type UROWID for the table and
retrieve the value of the ROWID pseudocolumn into that column.
ANSI, DB2, and SQL/DS Data Types
SQL statements that create tables and clusters can also use ANSI data types and data
types from the IBM products SQL/DS and DB2. Oracle recognizes the ANSI or IBM
data type name that differs from the Oracle Database data type name. It converts the
data type to the equivalent Oracle data type, records the Oracle data type as the name
of the column data type, and stores the column data in the Oracle data type based on
the conversions shown in the tables that follow.
See Also: Oracle Database PL/SQL Packages and Types Reference for
information on the functions available with the DBMS_ROWID package
and how to use them
Note: Heap-organized tables have physical rowids. Oracle does not
recommend that you specify a column of data type UROWID for a
heap-organized table.
Table 3–6 ANSI Data Types Converted to Oracle Data Types
ANSI SQL Data Type Oracle Data Type
CHARACTER(n)
CHAR(n)
CHAR(n)
CHARACTER VARYING(n)
CHAR VARYING(n)
VARCHAR2(n)
NATIONAL CHARACTER(n)
NATIONAL CHAR(n)
NCHAR(n)
NCHAR(n)
Data Types
Basic Elements of Oracle SQL 3-29
Notes:
a. The NUMERIC and DECIMAL data types can specify only fixed-point numbers.
For those data types, the scale (s) defaults to 0.
b. The FLOAT data type is a floating-point number with a binary precision b. The
default precision for this data type is 126 binary, or 38 decimal.
c. The DOUBLE PRECISION data type is a floating-point number with binary
precision 126.
d. The REAL data type is a floating-point number with a binary precision of 63, or
18 decimal.
Do not define columns with the following SQL/DS and DB2 data types, because they
have no corresponding Oracle data type:
■ GRAPHIC
■ LONG VARGRAPHIC
■ VARGRAPHIC
■ TIME
Note that data of type TIME can also be expressed as Oracle datetime data.
NATIONAL CHARACTER VARYING(n)
NATIONAL CHAR VARYING(n)
NCHAR VARYING(n)
NVARCHAR2(n)
NUMERIC[(p,s)]
DECIMAL[(p,s)] (Note a)
NUMBER(p,s)
INTEGER
INT
SMALLINT
NUMBER(38)
FLOAT (Note b)
DOUBLE PRECISION (Note c)
REAL (Note d)
FLOAT(126)
FLOAT(126)
FLOAT(63)
See Also: Data Types in Oracle Database SQL Language Reference
Table 3–7 SQL/DS and DB2 Data Types Converted to Oracle Data Types
SQL/DS or DB2 Data Type Oracle Data Type
CHARACTER(n) CHAR(n)
VARCHAR(n) VARCHAR(n)
LONG VARCHAR LONG
DECIMAL(p,s) (a) NUMBER(p,s)
INTEGER
SMALLINT
NUMBER(38)
FLOAT (b) NUMBER
Table 3–6 (Cont.) ANSI Data Types Converted to Oracle Data Types
ANSI SQL Data Type Oracle Data Type
Data Types
3-30 Oracle Database SQL Language Reference
Notes:
a. The DECIMAL data type can specify only fixed-point numbers. For this data
type, s defaults to 0.
b. The FLOAT data type is a floating-point number with a binary precision b. The
default precision for this data type is 126 binary or 38 decimal.
User-Defined Types
User-defined data types use Oracle built-in data types and other user-defined data
types as the building blocks of object types that model the structure and behavior of
data in applications. The sections that follow describe the various categories of
user-defined types.
Object Types
Object types are abstractions of the real-world entities, such as purchase orders, that
application programs deal with. An object type is a schema object with three kinds of
components:
■ A name, which identifies the object type uniquely within that schema.
■ Attributes, which are built-in types or other user-defined types. Attributes model
the structure of the real-world entity.
■ Methods, which are functions or procedures written in PL/SQL and stored in the
database, or written in a language like C or Java and stored externally. Methods
implement operations the application can perform on the real-world entity.
REF Data Types
An object identifier (represented by the keyword OID) uniquely identifies an object
and enables you to reference the object from other objects or from relational tables. A
data type category called REF represents such references. A REF data type is a
container for an object identifier. REF values are pointers to objects.
When a REF value points to a nonexistent object, the REF is said to be "dangling". A
dangling REF is different from a null REF. To determine whether a REF is dangling or
not, use the condition IS [NOT] DANGLING. For example, given object view oc_
orders in the sample schema oe, the column customer_ref is of type REF to type
customer_typ, which has an attribute cust_email:
SELECT o.customer_ref.cust_email
FROM oc_orders o
WHERE o.customer_ref IS NOT DANGLING;
See Also:
■ Oracle Database Concepts for information about Oracle built-in data
types
■ CREATE TYPE on page 17-3 and the CREATE TYPE BODY on
page 17-5 for information about creating user-defined types
■ Oracle Database Object-Relational Developer's Guide for information
about using user-defined types
Data Types
Basic Elements of Oracle SQL 3-31
Varrays
An array is an ordered set of data elements. All elements of a given array are of the
same data type. Each element has an index, which is a number corresponding to the
position of the element in the array.
The number of elements in an array is the size of the array. Oracle arrays are of
variable size, which is why they are called varrays. You must specify a maximum size
when you declare the varray.
When you declare a varray, it does not allocate space. It defines a type, which you can
use as:
■ The data type of a column of a relational table
■ An object type attribute
■ A PL/SQL variable, parameter, or function return type
Oracle normally stores an array object either in line (as part of the row data) or out of
line (in a LOB), depending on its size. However, if you specify separate storage
characteristics for a varray, then Oracle stores it out of line, regardless of its size. Refer
to the varray_col_properties of CREATE TABLE on page 16-47 for more information
about varray storage.
Nested Tables
A nested table type models an unordered set of elements. The elements may be
built-in types or user-defined types. You can view a nested table as a single-column
table or, if the nested table is an object type, as a multicolumn table, with a column for
each attribute of the object type.
A nested table definition does not allocate space. It defines a type, which you can use
to declare:
■ The data type of a column of a relational table
■ An object type attribute
■ A PL/SQL variable, parameter, or function return type
When a nested table appears as the type of a column in a relational table or as an
attribute of the underlying object type of an object table, Oracle stores all of the nested
table data in a single table, which it associates with the enclosing relational or object
table.
Oracle-Supplied Types
Oracle provides SQL-based interfaces for defining new types when the built-in or
ANSI-supported types are not sufficient. The behavior for these types can be
implemented in C/C++, Java, or PL/ SQL. Oracle Database automatically provides the
low-level infrastructure services needed for input-output, heterogeneous client-side
access for new data types, and optimizations for data transfers between the application
and the database.
These interfaces can be used to build user-defined (or object) types and are also used
by Oracle to create some commonly useful data types. Several such data types are
supplied with the server, and they serve both broad horizontal application areas (for
example, the Any types) and specific vertical ones (for example, the spatial types).
The Oracle-supplied types, along with cross-references to the documentation of their
implementation and use, are described in the following sections:
Data Types
3-32 Oracle Database SQL Language Reference
■ Any Types
■ XML Types
■ Spatial Types
■ Media Types
Any Types
The Any types provide highly flexible modeling of procedure parameters and table
columns where the actual type is not known. These data types let you dynamically
encapsulate and access type descriptions, data instances, and sets of data instances of
any other SQL type. These types have OCI and PL/SQL interfaces for construction
and access.
ANYTYPE
This type can contain a type description of any named SQL type or unnamed transient
type.
ANYDATA
This type contains an instance of a given type, with data, plus a description of the
type. ANYDATA can be used as a table column data type and lets you store
heterogeneous values in a single column. The values can be of SQL built-in types as
well as user-defined types.
ANYDATASET
This type contains a description of a given type plus a set of data instances of that
type. ANYDATASET can be used as a procedure parameter data type where such
flexibility is needed. The values of the data instances can be of SQL built-in types as
well as user-defined types.
XML Types
Extensible Markup Language (XML) is a standard format developed by the World
Wide Web Consortium (W3C) for representing structured and unstructured data on
the World Wide Web. Universal resource identifiers (URIs) identify resources such as
Web pages anywhere on the Web. Oracle provides types to handle XML and URI data,
as well as a class of URIs called DBURIRef types to access data stored within the
database itself. It also provides a set of types to store and access both external and
internal URIs from within the database.
XMLType
This Oracle-supplied type can be used to store and query XML data in the database.
XMLType has member functions you can use to access, extract, and query the XML
data using XPath expressions. XPath is another standard developed by the W3C
committee to traverse XML documents. Oracle XMLType functions support many W3C
XPath expressions. Oracle also provides a set of SQL functions and PL/SQL packages
to create XMLType values from existing relational or object-relational data.
XMLType is a system-defined type, so you can use it as an argument of a function or as
the data type of a table or view column. You can also create tables and views of
See Also: Oracle Database PL/SQL Packages and Types Reference for
information on the ANYTYPE, ANYDATA, and ANYDATASET types
Data Types
Basic Elements of Oracle SQL 3-33
XMLType. When you create an XMLType column in a table, you can choose to store the
XML data in a CLOB column, as binary XML (stored internally as a CLOB), or object
relationally.
You can also register the schema (using the DBMS_XMLSCHEMA package) and create a
table or column conforming to the registered schema. In this case Oracle stores the
XML data in underlying object-relational columns by default, but you can specify
storage in a CLOB or binary XML column even for schema-based data.
Queries and DML on XMLType columns operate the same regardless of the storage
mechanism.
URI Data Types
Oracle supplies a family of URI types—URIType, DBURIType, XDBURIType, and
HTTPURIType—which are related by an inheritance hierarchy. URIType is an object
type and the others are subtypes of URIType. Since URIType is the supertype, you
can create columns of this type and store DBURIType or HTTPURIType type instances
in this column.
HTTPURIType You can use HTTPURIType to store URLs to external Web pages or to
files. Oracle accesses these files using HTTP (Hypertext Transfer Protocol).
XDBURIType You can use XDBURIType to expose documents in the XML database
hierarchy as URIs that can be embedded in any URIType column in a table. The
XDBURIType consists of a URL, which comprises the hierarchical name of the XML
document to which it refers and an optional fragment representing the XPath syntax.
The fragment is separated from the URL part by a pound sign (#). The following lines
are examples of XDBURIType:
/home/oe/doc1.xml
/home/oe/doc1.xml#/orders/order_item
DBURIType DBURIType can be used to store DBURIRef values, which reference data
inside the database. Storing DBURIRef values lets you reference data stored inside or
outside the database and access the data consistently.
DBURIRef values use an XPath-like representation to reference data inside the
database. If you imagine the database as an XML tree, then you would see the tables,
rows, and columns as elements in the XML document. For example, the sample
human resources user hr would see the following XML tree:
<HR>
<EMPLOYEES>
<ROW>
<EMPLOYEE_ID>205</EMPLOYEE_ID>
<LAST_NAME>Higgins</LAST_NAME>
<SALARY>12000</SALARY>
.. <!-- other columns -->
</ROW>
... <!-- other rows -->
</EMPLOYEES>
<!-- other tables..-->
</HR>
<!-- other user schemas on which you have some privilege on..-->
See Also: Oracle XML DB Developer's Guide for information about
using XMLType columns
Data Types
3-34 Oracle Database SQL Language Reference
The DBURIRef is an XPath expression over this virtual XML document. So to reference
the SALARY value in the EMPLOYEES table for the employee with employee number
205, you can write a DBURIRef as,
/HR/EMPLOYEES/ROW[EMPLOYEE_ID=205]/SALARY
Using this model, you can reference data stored in CLOB columns or other columns
and expose them as URLs to the external world.
URIFactory Package
Oracle also provides the URIFactory package, which can create and return instances
of the various subtypes of the URITypes. The package analyzes the URL string,
identifies the type of URL (HTTP, DBURI, and so on), and creates an instance of the
subtype. To create a DBURI instance, the URL must start with the prefix /oradb. For
example, URIFactory.getURI('/oradb/HR/EMPLOYEES') would create a
DBURIType instance and URIFactory.getUri('/sys/schema') would create an
XDBURIType instance.
Spatial Types
Oracle Spatial is designed to make spatial data management easier and more natural
to users of location-enabled applications, geographic information system (GIS)
applications, and geoimaging applications. After the spatial data is stored in an Oracle
Database, you can easily manipulate, retrieve, and relate it to all the other data stored
in the database. The following data types are available only if you have installed
Oracle Spatial.
SDO_GEOMETRY
The geometric description of a spatial object is stored in a single row, in a single
column of object type SDO_GEOMETRY in a user-defined table. Any table that has a
column of type SDO_GEOMETRY must have another column, or set of columns, that
defines a unique primary key for that table. Tables of this sort are sometimes called
geometry tables.
The SDO_GEOMETRY object type has the following definition:
CREATE TYPE SDO_GEOMETRY AS OBJECT (
sgo_gtype NUMBER,
sdo_srid NUMBER,
sdo_point SDO_POINT_TYPE,
sdo_elem_info SDO_ELEM_INFO_ARRAY,
sdo_ordinates SDO_ORDINATE_ARRAY)
/
SDO_TOPO_GEOMETRY
This type describes a topology geometry, which is stored in a single row, in a single
column of object type SDO_TOPO_GEOMETRY in a user-defined table.
See Also:
■ Oracle Database Object-Relational Developer's Guide for general
information on object types and type inheritance
■ Oracle XML DB Developer's Guide for more information about
these supplied types and their implementation
■ Oracle Streams Advanced Queuing User's Guide for information
about using XMLType with Oracle Advanced Queuing
Data Types
Basic Elements of Oracle SQL 3-35
The SDO_TOPO_GEOMETRY object type has the following definition:
CREATE TYPE SDO_TOPO_GEOMETRY AS OBJECT (
tg_type NUMBER,
tg_id NUMBER,
tg_layer_id NUMBER,
topology_id NUMBER)
/
SDO_GEORASTER
In the GeoRaster object-relational model, a raster grid or image object is stored in a
single row, in a single column of object type SDO_GEORASTER in a user-defined table.
Tables of this sort are called GeoRaster tables.
The SDO_GEORASTER object type has the following definition:
CREATE TYPE SDO_GEORASTER AS OBJECT (
rasterType NUMBER,
spatialExtent SDO_GEOMETRY,
rasterDataTable VARCHAR2(32),
rasterID NUMBER,
metadata XMLType)
/
Media Types
Oracle Multimedia uses object types, similar to Java or C++ classes, to describe
multimedia data. An instance of these object types consists of attributes, including
metadata and the media data, and methods. The Multimedia data types are created in
the ORDSYS schema. Public synonyms exist for all the data types, so you can access
them without specifying the schema name.
ORDAudio
The ORDAudio object type supports the storage and management of audio data.
ORDImage
The ORDImage object type supports the storage and management of image data.
ORDVideo
The ORDVideo object type supports the storage and management of video data.
ORDDoc
The ORDDoc object type supports storage and management of any type of media data,
including audio, image and video data. Use this type when you want all media to be
stored in a single column.
See Also: Oracle Spatial Developer's Guide, Oracle Spatial Topology and
Network Data Models Developer's Guide, and Oracle Spatial GeoRaster
Developer's Guide for information on the full implementation of the
spatial data types and guidelines for using them
See Also: Oracle Multimedia Reference for information on the
implementation of these types and guidelines for using them
Data Types
3-36 Oracle Database SQL Language Reference
ORDDicom
The ORDDicom object type supports the storage and management of Digital Imaging
and Communications in Medicine (DICOM), the format universally recognized as the
standard for medical imaging.
The following data types provide compliance with the ISO-IEC 13249-5 Still Image
standard, commonly referred to as SQL/MM StillImage.
SI_StillImage
The SI_StillImage object type represents digital images with inherent image
characteristics such as height, width, and format.
SI_Color
The SI_Color object type encapsulates color values.
SI_AverageColor
The SI_AverageColor object type represents a feature that characterizes an image
by its average color.
SI_ColorHistogram
The SI_ColorHistogram object type represents a feature that characterizes an image
by the relative frequencies of the colors exhibited by samples of the raw image.
SI_PositionalColor
Given an image divided into n by m rectangles, the SI_PositionalColor object
type represents the feature that characterizes an image by the n by m most significant
colors of the rectangles.
SI_Texture
The SI_Texture object type represents a feature that characterizes an image by the
size of repeating items (coarseness), brightness variations (contrast), and predominant
direction (directionality).
SI_FeatureList
The SI_FeatureList object type is a list containing up to four of the image features
represented by the preceding object types (SI_AverageColor, SI_
ColorHistogram, SI_PositionalColor, and SI_Texture), where each feature is
associated with a feature weight.
ORDImageSignature
The ORDImageSignature object type has been deprecated and should no longer be
introduced into your code. Existing occurrences of this object type will continue to
function as in the past.
Expression Filter Type
The Oracle Expression Filter allows application developers to manage and evaluate
conditional expressions that describe users' interests in data. The Expression Filter
includes the following data type:
Data Type Comparison Rules
Basic Elements of Oracle SQL 3-37
Expression
Expression Filter uses a virtual data type called Expression to manage and evaluate
conditional expressions as data in database tables. The Expression Filter creates a
column of Expression data type from a VARCHAR2 column by assigning an attribute
set to the column. This assignment enables a data constraint that ensures the validity
of expressions stored in the column.
You can define conditions using the EVALUATE operator on an Expression data type
to evaluate the expressions stored in a column for some data. If you are using
Enterprise Edition, then you can also define an Expression Filter index on a column of
Expression data type to process queries using the EVALUATE operator.
Data Type Comparison Rules
This section describes how Oracle Database compares values of each data type.
Numeric Values
A larger value is considered greater than a smaller one. All negative numbers are less
than zero and all positive numbers. Thus, -1 is less than 100; -100 is less than -1.
The floating-point value NaN (not a number) is greater than any other numeric value
and is equal to itself.
Date Values
A later date is considered greater than an earlier one. For example, the date equivalent
of '29-MAR-2005' is less than that of '05-JAN-2006' and '05-JAN-2006 1:35pm' is greater
than '05-JAN-2005 10:09am'.
Character Values
Character values are compared on the basis of two measures:
■ Binary or linguistic sorting
■ Blank-padded or nonpadded comparison semantics
The following subsections describe the two measures.
Binary and Linguistic Comparisons
In binary comparison, which is the default, Oracle compares character strings
according to the concatenated value of the numeric codes of the characters in the
database character set. One character is greater than another if it has a greater numeric
value than the other in the character set. Oracle considers blanks to be less than any
character, which is true in most character sets.
These are some common character sets:
■ 7-bit ASCII (American Standard Code for Information Interchange)
■ EBCDIC Code (Extended Binary Coded Decimal Interchange Code)
See Also: Oracle Database Rules Manager and Expression Filter
Developer's Guide for more information on the Expression Filter
See Also: "Numeric Precedence" on page 3-14 and "Floating-Point
Numbers" on page 3-12 for more information on comparison
semantics
Data Type Comparison Rules
3-38 Oracle Database SQL Language Reference
■ ISO 8859/1 (International Organization for Standardization)
■ JEUC Japan Extended UNIX
Linguistic comparison is useful if the binary sequence of numeric codes does not
match the linguistic sequence of the characters you are comparing. Linguistic
comparison is used if the NLS_SORT parameter has a setting other than BINARY and
the NLS_COMP parameter is set to LINGUISTIC. In linguistic sorting, all SQL sorting
and comparison are based on the linguistic rule specified by NLS_SORT.
Blank-Padded and Nonpadded Comparison Semantics
With blank-padded semantics, if the two values have different lengths, then Oracle
first adds blanks to the end of the shorter one so their lengths are equal. Oracle then
compares the values character by character up to the first character that differs. The
value with the greater character in the first differing position is considered greater. If
two values have no differing characters, then they are considered equal. This rule
means that two values are equal if they differ only in the number of trailing blanks.
Oracle uses blank-padded comparison semantics only when both values in the
comparison are either expressions of data type CHAR, NCHAR, text literals, or values
returned by the USER function.
With nonpadded semantics, Oracle compares two values character by character up to
the first character that differs. The value with the greater character in that position is
considered greater. If two values of different length are identical up to the end of the
shorter one, then the longer value is considered greater. If two values of equal length
have no differing characters, then the values are considered equal. Oracle uses
nonpadded comparison semantics whenever one or both values in the comparison
have the data type VARCHAR2 or NVARCHAR2.
The results of comparing two character values using different comparison semantics
may vary. The table that follows shows the results of comparing five pairs of character
values using each comparison semantic. Usually, the results of blank-padded and
nonpadded comparisons are the same. The last comparison in the table illustrates the
differences between the blank-padded and nonpadded comparison semantics.
Portions of the ASCII and EBCDIC character sets appear in Table 3–8 and Table 3–9.
Uppercase and lowercase letters are not equivalent. The numeric values for the
characters of a character set may not match the linguistic sequence for a particular
language.
See Also: Oracle Database Globalization Support Guide for more
information about linguistic sorting
Blank-Padded Nonpadded
'ac' > 'ab' 'ac' > 'ab'
'ab' > 'a ' 'ab' > 'a '
'ab' > 'a' 'ab' > 'a'
'ab' = 'ab' 'ab' = 'ab'
'a ' = 'a' 'a ' > 'a'
Table 3–8 ASCII Character Set
Symbol Decimal value Symbol Decimal value
blank 32 ; 59
Data Type Comparison Rules
Basic Elements of Oracle SQL 3-39
! 33 < 60
" 34 = 61
# 35 > 62
$ 36 ? 63
% 37 @ 64
& 38 A-Z 65-90
' 39 [ 91
( 40  92
) 41 ] 93
* 42 ^ 94
+ 43 _ 95
, 44 ' 96
- 45 a-z 97-122
. 46 { 123
/ 47 | 124
0-9 48-57 } 125
: 58 ~ 126
Table 3–9 EBCDIC Character Set
Symbol Decimal value Symbol Decimal value
blank 64 % 108
¢ 74 _ 109
. 75 > 110
< 76 ? 111
( 77 : 122
+ 78 # 123
| 79 @ 124
& 80 ' 125
! 90 = 126
$ 91 " 127
* 92 a-i 129-137
) 93 j-r 145-153
; 94 s-z 162-169
ÿ 95 A-I 193-201
- 96 J-R 209-217
/ 97 S-Z 226-233
Table 3–8 (Cont.) ASCII Character Set
Symbol Decimal value Symbol Decimal value
Data Type Comparison Rules
3-40 Oracle Database SQL Language Reference
Object Values
Object values are compared using one of two comparison functions: MAP and ORDER.
Both functions compare object type instances, but they are quite different from one
another. These functions must be specified as part of any object type that will be
compared with other object types.
Varrays and Nested Tables
Comparison of nested tables is described in "Comparison Conditions" on page 7-4.
Data Type Precedence
Oracle uses data type precedence to determine implicit data type conversion, which is
discussed in the section that follows. Oracle data types take the following precedence:
■ Datetime and interval data types
■ BINARY_DOUBLE
■ BINARY_FLOAT
■ NUMBER
■ Character data types
■ All other built-in data types
Data Conversion
Generally an expression cannot contain values of different data types. For example, an
expression cannot multiply 5 by 10 and then add 'JAMES'. However, Oracle supports
both implicit and explicit conversion of values from one data type to another.
Implicit and Explicit Data Conversion
Oracle recommends that you specify explicit conversions, rather than rely on implicit
or automatic conversions, for these reasons:
■ SQL statements are easier to understand when you use explicit data type
conversion functions.
■ Implicit data type conversion can have a negative impact on performance,
especially if the data type of a column value is converted to that of a constant
rather than the other way around.
■ Implicit conversion depends on the context in which it occurs and may not work
the same way in every case. For example, implicit conversion from a datetime
value to a VARCHAR2 value may return an unexpected year depending on the
value of the NLS_DATE_FORMAT parameter.
■ Algorithms for implicit conversion are subject to change across software releases
and among Oracle products. Behavior of explicit conversions is more predictable.
Implicit Data Conversion
Oracle Database automatically converts a value from one data type to another when
such a conversion makes sense. Implicit conversion to character data types follows
these rules:
See Also: CREATE TYPE on page 17-3 for a description of MAP and
ORDER methods and the values they return
Data Type Comparison Rules
Basic Elements of Oracle SQL 3-41
Table 3–10 is a matrix of Oracle implicit conversions. The table shows all possible
conversions, without regard to the direction of the conversion or the context in which
it is made. The rules governing these details follow the table.
The following rules govern implicit data type conversions:
■ During INSERT and UPDATE operations, Oracle converts the value to the data
type of the affected column.
■ During SELECT FROM operations, Oracle converts the data from the column to the
type of the target variable.
■ When manipulating numeric values, Oracle usually adjusts precision and scale to
allow for maximum capacity. In such cases, the numeric data type resulting from
such operations can differ from the numeric data type found in the underlying
tables.
■ When comparing a character value with a numeric value, Oracle converts the
character data to a numeric value.
■ Conversions between character values or NUMBER values and floating-point
number values can be inexact, because the character types and NUMBER use
decimal precision to represent the numeric value, and the floating-point numbers
use binary precision.
Table 3–10 Implicit Type Conversion Matrix
CHAR
VARCHAR2
NCHAR
NVARCHAR2
DATE
DATETIME/
INTERVAL
NUMBER
BINARY_FLOAT
BINARY_DOUBLE
LONG
RAW
ROWID
CLOB
BLOB
NCLOB
CHAR -- X X X X X X X X X X -- X X X
VARCHAR2 X -- X X X X X X X X X X X -- X
NCHAR X X -- X X X X X X X X X X -- X
NVARCHAR2 X X X -- X X X X X X X X X -- X
DATE X X X X -- -- -- -- -- -- -- -- -- -- --
DATETIME/
INTERVAL
X X X X -- -- -- -- -- X -- -- -- -- --
NUMBER X X X X -- -- -- X X -- -- -- -- -- --
BINARY_
FLOAT
X X X X -- -- X -- X -- -- -- -- -- --
BINARY_
DOUBLE
X X X X -- -- X X -- -- -- -- -- -- --
LONG X X X X -- X1 -- -- -- -- X -- X -- X
RAW X X X X -- -- -- -- -- X -- -- -- X --
ROWID -- X X X -- -- -- -- -- -- -- -- -- -- --
CLOB X X X X -- -- -- -- -- X -- -- -- -- X
BLOB -- -- -- -- -- -- -- -- -- -- X -- -- -- --
NCLOB X X X X -- -- -- -- -- X -- -- X -- --
Note 1: You cannot convert LONG to INTERVAL directly, but you can convert LONG to VARCHAR2 using TO_CHAR(interval),
and then convert the resulting VARCHAR2 value to INTERVAL.
Data Type Comparison Rules
3-42 Oracle Database SQL Language Reference
■ When converting a CLOB value into a character data type such as VARCHAR2, or
converting BLOB to RAW data, if the data to be converted is larger than the target
data type, then the database returns an error.
■ During conversion from a timestamp value to a DATE value, the fractional seconds
portion of the timestamp value is truncated. This behavior differs from earlier
releases of Oracle Database, when the fractional seconds portion of the timestamp
value was rounded.
■ Conversions from BINARY_FLOAT to BINARY_DOUBLE are exact.
■ Conversions from BINARY_DOUBLE to BINARY_FLOAT are inexact if the BINARY_
DOUBLE value uses more bits of precision that supported by the BINARY_FLOAT.
■ When comparing a character value with a DATE value, Oracle converts the
character data to DATE.
■ When you use a SQL function or operator with an argument of a data type other
than the one it accepts, Oracle converts the argument to the accepted data type.
■ When making assignments, Oracle converts the value on the right side of the
equal sign (=) to the data type of the target of the assignment on the left side.
■ During concatenation operations, Oracle converts from noncharacter data types to
CHAR or NCHAR.
■ During arithmetic operations on and comparisons between character and
noncharacter data types, Oracle converts from any character data type to a
numeric, date, or rowid, as appropriate. In arithmetic operations between
CHAR/VARCHAR2 and NCHAR/NVARCHAR2, Oracle converts to a NUMBER.
■ Comparisons between CHAR and VARCHAR2 and between NCHAR and NVARCHAR2
types may entail different character sets. The default direction of conversion in
such cases is from the database character set to the national character set.
Table 3–11 shows the direction of implicit conversions between different character
types.
■ Most SQL character functions are enabled to accept CLOBs as parameters, and
Oracle performs implicit conversions between CLOB and character types.
Therefore, functions that are not yet enabled for CLOBs can accept CLOBs through
implicit conversion. In such cases, Oracle converts the CLOBs to CHAR or
VARCHAR2 before the function is invoked. If the CLOB is larger than 4000 bytes,
then Oracle converts only the first 4000 bytes to CHAR.
User-defined types such as collections cannot be implicitly converted, but must be
explicitly converted using CAST ... MULTISET.
Table 3–11 Conversion Direction of Different Character Types
to CHAR to VARCHAR2 to NCHAR to NVARCHAR2
from CHAR -- VARCHAR2 NCHAR NVARCHAR2
from VARCHAR2 VARCHAR2 -- NVARCHAR2 NVARCHAR2
from NCHAR NCHAR NCHAR -- NVARCHAR2
from NVARCHAR2 NVARCHAR2 NVARCHAR2 NVARCHAR2 --
Data Type Comparison Rules
Basic Elements of Oracle SQL 3-43
Implicit Data Conversion Examples
Text Literal Example The text literal '10' has data type CHAR. Oracle implicitly
converts it to the NUMBER data type if it appears in a numeric expression as in the
following statement:
SELECT salary + '10'
FROM employees;
Character and Number Values Example When a condition compares a character
value and a NUMBER value, Oracle implicitly converts the character value to a NUMBER
value, rather than converting the NUMBER value to a character value. In the following
statement, Oracle implicitly converts '200' to 200:
SELECT last_name
FROM employees
WHERE employee_id = '200';
Date Example In the following statement, Oracle implicitly converts '24-JUN-06' to
a DATE value using the default date format 'DD-MON-YY':
SELECT last_name
FROM employees
WHERE hire_date = '24-JUN-06';
Explicit Data Conversion
You can explicitly specify data type conversions using SQL conversion functions.
Table 3–12 shows SQL functions that explicitly convert a value from one data type to
another.
You cannot specify LONG and LONG RAW values in cases in which Oracle can perform
implicit data type conversion. For example, LONG and LONG RAW values cannot appear
in expressions with functions or operators. Refer to "LONG Data Type" on page 3-14
for information on the limitations on LONG and LONG RAW data types.
Data Type Comparison Rules
3-44 Oracle Database SQL Language Reference
Security Considerations for Data Conversion
When a datetime value is converted to text, either by implicit conversion or by explicit
conversion that does not specify a format model, the format model is defined by one of
the globalization session parameters. Depending on the source data type, the
parameter name is NLS_DATE_FORMAT, NLS_TIMESTAMP_FORMAT, or NLS_
TIMESTAMP_TZ_FORMAT. The values of these parameters can be specified in the client
environment or in an ALTER SESSION statement.
Table 3–12 Explicit Type Conversions
toCHAR,
VARCHAR2,
NCHAR,
NVARCHAR2
toNUMBER
toDatetime/
Interval
toRAW
toROWID
toLONG,
LONGRAW
toCLOB,NCLOB,
BLOB
toBINARY_FLOAT
toBINARY_DOUBLE
from CHAR,
VARCHAR2,
NCHAR,
NVARCHAR2
TO_CHAR
(char.)
TO_NCHAR
(char.)
TO_
NUMBER
TO_DATE
TO_TIMESTAMP
TO_
TIMESTAMP_TZ
TO_
YMINTERVAL
TO_
DSINTERVAL
HEXTORAW CHARTO=
ROWID
-- TO_CLOB
TO_NCLOB
TO_
BINARY_
FLOAT
TO_
BINARY_
DOUBLE
from NUMBER TO_CHAR
(number)
TO_NCHAR
(number)
-- TO_DATE
NUMTOYM-
INTERVAL
NUMTODS-
INTERVAL
-- -- -- -- TO_
BINARY_
FLOAT
TO_
BINARY_
DOUBLE
from Datetime/
Interval
TO_CHAR
(date)
TO_NCHAR
(datetime)
-- -- -- -- -- -- -- --
from RAW RAWTOHEX
RAWTONHEX
-- -- -- -- -- TO_BLOB -- --
from ROWID ROWIDTOCHAR -- -- -- -- -- -- -- --
from LONG /
LONG RAW
-- -- -- -- -- -- TO_LOB -- --
from CLOB,
NCLOB, BLOB
TO_CHAR
TO_NCHAR
-- -- -- -- -- TO_CLOB
TO_NCLOB
-- --
from CLOB,
NCLOB, BLOB
TO_CHAR
TO_NCHAR
-- -- -- -- -- TO_CLOB
TO_NCLOB
-- --
from BINARY_
FLOAT
TO_CHAR
(char.)
TO_NCHAR
(char.)
TO_
NUMBER
-- -- -- -- -- TO_
BINARY_
FLOAT
TO_
BINARY_
DOUBLE
from BINARY_
DOUBLE
TO_CHAR
(char.)
TO_NCHAR
(char.)
TO_
NUMBER
-- -- -- -- -- TO_
BINARY_
FLOAT
TO_
BINARY_
DOUBLE
See Also: "Conversion Functions" on page 5-6 for details on all of
the explicit conversion functions
Literals
Basic Elements of Oracle SQL 3-45
The dependency of format models on session parameters can have a negative impact
on database security when conversion without an explicit format model is applied to a
datetime value that is being concatenated to text of a dynamic SQL statement.
Dynamic SQL statements are those statements whose text is concatenated from
fragments before being passed to a database for execution. Dynamic SQL is frequently
associated with the built-in PL/SQL package DBMS_SQL or with the PL/SQL
statement EXECUTE IMMEDIATE, but these are not the only places where dynamically
constructed SQL text may be passed as argument. For example:
EXECUTE IMMEDIATE
'SELECT name FROM employee WHERE hiredate > ''' || start_date || '''';
where start_date has the data type DATE.
In the above example, the value of start_date is converted to text using a format
model specified in the session parameter NLS_DATE_FORMAT. The result is
concatenated into SQL text. A datetime format model can consist simply of literal text
enclosed in double quotation marks. Therefore, any user who can explicitly set
globalization parameters for a session can decide what text is produced by the above
conversion. If the SQL statement is executed by a PL/SQL procedure, the procedure
becomes vulnerable to SQL injection through the session parameter. If the procedure
runs with definer's rights, with higher privileges than the session itself, the user can
gain unauthorized access to sensitive data.
Implicit and explicit conversion for numeric values may also suffer from the analogous
problem, as the conversion result may depend on the session parameter NLS_
NUMERIC_CHARACTERS. This parameter defines the decimal and group separator
characters. If the decimal separator is defined to be the quotation mark or the double
quotation mark, some potential for SQL injection emerges.
Literals
The terms literal and constant value are synonymous and refer to a fixed data value.
For example, 'JACK', 'BLUE ISLAND', and '101' are all character literals; 5001 is a
numeric literal. Character literals are enclosed in single quotation marks so that Oracle
can distinguish them from schema object names.
This section contains these topics:
■ Text Literals
See Also: Oracle Database PL/SQL Language Reference for further
examples and for recommendations on avoiding this security risk
Note: This security risk also applies to middle-tier applications that
construct SQL text from datetime values converted to text by the
database or by OCI datetime functions. Those applications are
vulnerable if session globalization parameters are obtained from a
user preference.
See Also:
■ Oracle Database Globalization Support Guide for detailed
descriptions of the session globalization parameters
■ "Format Models" on page 3-55 for information on the format
models
Literals
3-46 Oracle Database SQL Language Reference
■ Numeric Literals
■ Datetime Literals
■ Interval Literals
Many SQL statements and functions require you to specify character and numeric
literal values. You can also specify literals as part of expressions and conditions. You
can specify character literals with the 'text' notation, national character literals with
the N'text' notation, and numeric literals with the integer, or number notation,
depending on the context of the literal. The syntactic forms of these notations appear
in the sections that follow.
To specify a datetime or interval data type as a literal, you must take into account any
optional precisions included in the data types. Examples of specifying datetime and
interval data types as literals are provided in the relevant sections of "Data Types" on
page 3-1.
Text Literals
Use the text literal notation to specify values whenever 'string' appears in the
syntax of expressions, conditions, SQL functions, and SQL statements in other parts of
this reference. This reference uses the terms text literal, character literal, and string
interchangeably. Text, character, and string literals are always surrounded by single
quotation marks. If the syntax uses the term char, then you can specify either a text
literal or another expression that resolves to character data — for example, the last_
name column of the hr.employees table. When char appears in the syntax, the
single quotation marks are not used.
The syntax of text literals or strings follows:
string::=
where N or n specifies the literal using the national character set (NCHAR or
NVARCHAR2 data). By default, text entered using this notation is translated into the
national character set by way of the database character set when used by the server. To
avoid potential loss of data during the text literal conversion to the database character
set, set the environment variable ORA_NCHAR_LITERAL_REPLACE to TRUE. Doing so
transparently replaces the n' internally and preserves the text literal for SQL
processing.
In the top branch of the syntax:
■ c is any member of the user's character set. A single quotation mark (') within the
literal must be preceded by an escape character. To represent one single quotation
mark within a literal, enter two single quotation marks.
■ ' ' are two single quotation marks that begin and end text literals.
In the bottom branch of the syntax:
See Also: Oracle Database Globalization Support Guide for more
information about N-quoted literals
N
n ’ c ’
Q
q
’ quote_delimiter c quote_delimiter ’
Literals
Basic Elements of Oracle SQL 3-47
■ Q or q indicates that the alternative quoting mechanism will be used. This
mechanism allows a wide range of delimiters for the text string.
■ The outermost ' ' are two single quotation marks that precede and follow,
respectively, the opening and closing quote_delimiter.
■ c is any member of the user's character set. You can include quotation marks (") in
the text literal made up of c characters. You can also include the quote_
delimiter, as long as it is not immediately followed by a single quotation mark.
■ quote_delimiter is any single- or multibyte character except space, tab, and
return. The quote_delimiter can be a single quotation mark. However, if the
quote_delimiter appears in the text literal itself, ensure that it is not
immediately followed by a single quotation mark.
If the opening quote_delimiter is one of [, {, <, or (, then the closing quote_
delimiter must be the corresponding ], }, >, or ). In all other cases, the opening
and closing quote_delimiter must be the same character.
Text literals have properties of both the CHAR and VARCHAR2 data types:
■ Within expressions and conditions, Oracle treats text literals as though they have
the data type CHAR by comparing them using blank-padded comparison
semantics.
■ A text literal can have a maximum length of 4000 bytes.
Here are some valid text literals:
'Hello'
'ORACLE.dbs'
'Jackie''s raincoat'
'09-MAR-98'
N'nchar literal'
Here are some valid text literals using the alternative quoting mechanism:
q'!name LIKE '%DBMS_%%'!'
q'<'So,' she said, 'It's finished.'>'
q'{SELECT * FROM employees WHERE last_name = 'Smith';}'
nq'ï Ÿ1234 ï'
q'"name like '['"'
Numeric Literals
Use numeric literal notation to specify fixed and floating-point numbers.
Integer Literals
You must use the integer notation to specify an integer whenever integer appears in
expressions, conditions, SQL functions, and SQL statements described in other parts of
this reference.
The syntax of integer follows:
See Also: "Blank-Padded and Nonpadded Comparison Semantics"
on page 3-38
Literals
3-48 Oracle Database SQL Language Reference
integer::=
where digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
An integer can store a maximum of 38 digits of precision.
Here are some valid integers:
7
+255
NUMBER and Floating-Point Literals
You must use the number or floating-point notation to specify values whenever
number or n appears in expressions, conditions, SQL functions, and SQL statements in
other parts of this reference.
The syntax of number follows:
number::=
where
■ + or - indicates a positive or negative value. If you omit the sign, then a positive
value is the default.
■ digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
■ e or E indicates that the number is specified in scientific notation. The digits after
the E specify the exponent. The exponent can range from -130 to 125.
■ f or F indicates that the number is a 32-bit binary floating point number of type
BINARY_FLOAT.
■ d or D indicates that the number is a 64-bit binary floating point number of type
BINARY_DOUBLE.
If you omit f or F and d or D, then the number is of type NUMBER.
The suffixes f (F) and d (D) are supported only in floating-point number literals,
not in character strings that are to be converted to NUMBER. For example, if Oracle
is expecting a NUMBER and it encounters the string '9', then it converts the string
to the number 9. However, if Oracle encounters the string '9f', then conversion
fails and an error is returned.
+
–
digit
+
– digit
. digit
. digit
e
+
–
digit
f
d
Literals
Basic Elements of Oracle SQL 3-49
A number of type NUMBER can store a maximum of 38 digits of precision. If the literal
requires more precision than provided by NUMBER, BINARY_FLOAT, or BINARY_
DOUBLE, then Oracle truncates the value. If the range of the literal exceeds the range
supported by NUMBER, BINARY_FLOAT, or BINARY_DOUBLE, then Oracle raises an
error.
If you have established a decimal character other than a period (.) with the
initialization parameter NLS_NUMERIC_CHARACTERS, then you must specify numeric
literals with 'text' notation. In these cases, Oracle automatically converts the text
literal to a numeric value.
For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal
character of comma, specify the number 5.123 as follows:
'5,123'
Here are some valid NUMBER literals:
25
+6.34
0.5
25e-03
-1
Here are some valid floating-point number literals:
25f
+6.34F
0.5d
-1D
You can also use the following supplied floating-point literals in situations where a
value cannot be expressed as a numeric literal:
Note: You cannot use this notation for floating-point number literals.
See Also: ALTER SESSION on page 11-45 and Oracle Database
Reference
Literal Meaning Example
binary_float_nan A value of type
BINARY_FLOAT for
which the condition
IS NAN is true
SELECT COUNT(*)
FROM employees
WHERE TO_BINARY_FLOAT(commission_pct)
!= BINARY_FLOAT_NAN;
binary_float_
infinity
Single-precision
positive infinity
SELECT COUNT(*)
FROM employees
WHERE salary < BINARY_FLOAT_INFINITY;
binary_double_nan A value of type
BINARY_DOUBLE for
which the condition
IS NAN is true
SELECT COUNT(*)
FROM employees
WHERE TO_BINARY_FLOAT(commission_pct)
!= BINARY_FLOAT_NAN;
binary_double_
infinity
Double-precision
positive infinity
SELECT COUNT(*)
FROM employees
WHERE salary < BINARY_FLOAT_INFINITY;
Literals
3-50 Oracle Database SQL Language Reference
Datetime Literals
Oracle Database supports four datetime data types: DATE, TIMESTAMP, TIMESTAMP
WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE.
Date Literals You can specify a DATE value as a string literal, or you can convert a
character or numeric value to a date value with the TO_DATE function. DATE literals
are the only case in which Oracle Database accepts a TO_DATE expression in place of a
string literal.
To specify a DATE value as a literal, you must use the Gregorian calendar. You can
specify an ANSI literal, as shown in this example:
DATE '1998-12-25'
The ANSI date literal contains no time portion, and must be specified in the format
'YYYY-MM-DD'. Alternatively you can specify an Oracle date value, as in the following
example:
TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')
The default date format for an Oracle DATE value is specified by the initialization
parameter NLS_DATE_FORMAT. This example date format includes a two-digit
number for the day of the month, an abbreviation of the month name, the last two
digits of the year, and a 24-hour time designation.
Oracle automatically converts character values that are in the default date format into
date values when they are used in date expressions.
If you specify a date value without a time component, then the default time is
midnight (00:00:00 or 12:00:00 for 24-hour and 12-hour clock time, respectively). If you
specify a date value without a date, then the default date is the first day of the current
month.
Oracle DATE columns always contain both the date and time fields. Therefore, if you
query a DATE column, then you must either specify the time field in your query or
ensure that the time fields in the DATE column are set to midnight. Otherwise, Oracle
may not return the query results you expect. You can use the TRUNC date function to
set the time field to midnight, or you can include a greater-than or less-than condition
in the query instead of an equality or inequality condition.
Here are some examples that assume a table my_table with a number column row_
num and a DATE column datecol:
INSERT INTO my_table VALUES (1, SYSDATE);
INSERT INTO my_table VALUES (2, TRUNC(SYSDATE));
SELECT * FROM my_table;
ROW_NUM DATECOL
---------- ---------
1 03-OCT-02
2 03-OCT-02
SELECT * FROM my_table
WHERE datecol = TO_DATE('03-OCT-02','DD-MON-YY');
ROW_NUM DATECOL
---------- ---------
2 03-OCT-02
Literals
Basic Elements of Oracle SQL 3-51
SELECT * FROM my_table
WHERE datecol > TO_DATE('02-OCT-02', 'DD-MON-YY');
ROW_NUM DATECOL
---------- ---------
1 03-OCT-02
2 03-OCT-02
If you know that the time fields of your DATE column are set to midnight, then you
can query your DATE column as shown in the immediately preceding example, or by
using the DATE literal:
SELECT * FROM my_table WHERE datecol = DATE '2002-10-03';
However, if the DATE column contains values other than midnight, then you must
filter out the time fields in the query to get the correct result. For example:
SELECT * FROM my_table WHERE TRUNC(datecol) = DATE '2002-10-03';
Oracle applies the TRUNC function to each row in the query, so performance is better if
you ensure the midnight value of the time fields in your data. To ensure that the time
fields are set to midnight, use one of the following methods during inserts and
updates:
■ Use the TO_DATE function to mask out the time fields:
INSERT INTO my_table VALUES
(3, TO_DATE('3-OCT-2002','DD-MON-YYYY'));
■ Use the DATE literal:
INSERT INTO my_table VALUES (4, '03-OCT-02');
■ Use the TRUNC function:
INSERT INTO my_table VALUES (5, TRUNC(SYSDATE));
The date function SYSDATE returns the current system date and time. The function
CURRENT_DATE returns the current session date. For information on SYSDATE, the
TO_* datetime functions, and the default date format, see "Datetime Functions" on
page 5-5.
TIMESTAMP Literals The TIMESTAMP data type stores year, month, day, hour,
minute, and second, and fractional second values. When you specify TIMESTAMP as a
literal, the fractional_seconds_precision value can be any number of digits up
to 9, as follows:
TIMESTAMP '1997-01-31 09:26:50.124'
TIMESTAMP WITH TIME ZONE Literals The TIMESTAMP WITH TIME ZONE data
type is a variant of TIMESTAMP that includes a time zone region name or time zone
offset. When you specify TIMESTAMP WITH TIME ZONE as a literal, the
fractional_seconds_precision value can be any number of digits up to 9. For
example:
TIMESTAMP '1997-01-31 09:26:56.66 +02:00'
Two TIMESTAMP WITH TIME ZONE values are considered identical if they represent
the same instant in UTC, regardless of the TIME ZONE offsets stored in the data. For
example,
TIMESTAMP '1999-04-15 8:00:00 -8:00'
Literals
3-52 Oracle Database SQL Language Reference
is the same as
TIMESTAMP '1999-04-15 11:00:00 -5:00'
8:00 a.m. Pacific Standard Time is the same as 11:00 a.m. Eastern Standard Time.
You can replace the UTC offset with the TZR (time zone region name) format element.
For example, the following example has the same value as the preceding example:
TIMESTAMP '1999-04-15 8:00:00 US/Pacific'
To eliminate the ambiguity of boundary cases when the daylight saving time switches,
use both the TZR and a corresponding TZD format element. The following example
ensures that the preceding example will return a daylight saving time value:
TIMESTAMP '1999-10-29 01:30:00 US/Pacific PDT'
You can also express the time zone offset using a datetime expression:
SELECT TIMESTAMP '1999-10-29 01:30:00' AT TIME ZONE 'US/Pacific' FROM DUAL;
If you do not add the TZD format element, and the datetime value is ambiguous, then
Oracle returns an error if you have the ERROR_ON_OVERLAP_TIME session parameter
set to TRUE. If that parameter is set to FALSE, then Oracle interprets the ambiguous
datetime as standard time in the specified region.
TIMESTAMP WITH LOCAL TIME ZONE Literals The TIMESTAMP WITH LOCAL
TIME ZONE data type differs from TIMESTAMP WITH TIME ZONE in that data stored
in the database is normalized to the database time zone. The time zone offset is not
stored as part of the column data. There is no literal for TIMESTAMP WITH LOCAL
TIME ZONE. Rather, you represent values of this data type using any of the other valid
datetime literals. The table that follows shows some of the formats you can use to
insert a value into a TIMESTAMP WITH LOCAL TIME ZONE column, along with the
corresponding value returned by a query.
Notice that if the value specified does not include a time component (either explicitly
or implicitly, then the value returned defaults to midnight.
Interval Literals
An interval literal specifies a period of time. You can specify these differences in terms
of years and months, or in terms of days, hours, minutes, and seconds. Oracle
Database supports two types of interval literals, YEAR TO MONTH and DAY TO SECOND.
See Also: "Datetime Expressions" on page 6-8 for more information
Value Specified in INSERT Statement Value Returned by Query
'19-FEB-2004' 19-FEB-2004.00.00.000000 AM
SYSTIMESTAMP 19-FEB-04 02.54.36.497659 PM
TO_TIMESTAMP('19-FEB-2004', 'DD-MON-YYYY')); 19-FEB-04 12.00.00.000000 AM
SYSDATE 19-FEB-04 02.55.29.000000 PM
TO_DATE('19-FEB-2004', 'DD-MON-YYYY')); 19-FEB-04 12.00.00.000000 AM
TIMESTAMP'2004-02-19 8:00:00 US/Pacific'); 19-FEB-04 08.00.00.000000 AM
Literals
Basic Elements of Oracle SQL 3-53
Each type contains a leading field and may contain a trailing field. The leading field
defines the basic unit of date or time being measured. The trailing field defines the
smallest increment of the basic unit being considered. For example, a YEAR TO MONTH
interval considers an interval of years to the nearest month. A DAY TO MINUTE interval
considers an interval of days to the nearest minute.
If you have date data in numeric form, then you can use the NUMTOYMINTERVAL or
NUMTODSINTERVAL conversion function to convert the numeric data into interval
values.
Interval literals are used primarily with analytic functions.
INTERVAL YEAR TO MONTH
Specify YEAR TO MONTH interval literals using the following syntax:
interval_year_to_month::=
where
■ 'integer [-integer]' specifies integer values for the leading and optional
trailing field of the literal. If the leading field is YEAR and the trailing field is
MONTH, then the range of integer values for the month field is 0 to 11.
■ precision is the maximum number of digits in the leading field. The valid range
of the leading field precision is 0 to 9 and its default value is 2.
Restriction on the Leading Field If you specify a trailing field, then it must be less
significant than the leading field. For example, INTERVAL '0-1' MONTH TO YEAR is not
valid.
The following INTERVAL YEAR TO MONTH literal indicates an interval of 123 years, 2
months:
INTERVAL '123-2' YEAR(3) TO MONTH
Examples of the other forms of the literal follow, including some abbreviated versions:
See Also: "Analytic Functions" on page 5-11, NUMTODSINTERVAL
on page 5-125, NUMTOYMINTERVAL on page 5-126, and Oracle
Database Data Warehousing Guide
Form of Interval Literal Interpretation
INTERVAL '123-2' YEAR(3) TO MONTH An interval of 123 years, 2 months. You must
specify the leading field precision if it is
greater than the default of 2 digits.
INTERVAL '123' YEAR(3) An interval of 123 years 0 months.
INTERVAL '300' MONTH(3) An interval of 300 months.
INTERVAL ’ integer
– integer
’
YEAR
MONTH
( precision )
TO
YEAR
MONTH
Literals
3-54 Oracle Database SQL Language Reference
You can add or subtract one INTERVAL YEAR TO MONTH literal to or from another to
yield another INTERVAL YEAR TO MONTH literal. For example:
INTERVAL '5-3' YEAR TO MONTH + INTERVAL'20' MONTH =
INTERVAL '6-11' YEAR TO MONTH
INTERVAL DAY TO SECOND
Specify DAY TO SECOND interval literals using the following syntax:
interval_day_to_second::=
where
■ integer specifies the number of days. If this value contains more digits than the
number specified by the leading precision, then Oracle returns an error.
■ time_expr specifies a time in the format HH[:MI[:SS[.n]]] or MI[:SS[.n]]
or SS[.n], where n specifies the fractional part of a second. If n contains more
digits than the number specified by fractional_seconds_precision, then n
is rounded to the number of digits specified by the fractional_seconds_
precision value. You can specify time_expr following an integer and a space
only if the leading field is DAY.
INTERVAL '4' YEAR Maps to INTERVAL '4-0' YEAR TO MONTH
and indicates 4 years.
INTERVAL '50' MONTH Maps to INTERVAL '4-2' YEAR TO MONTH
and indicates 50 months or 4 years 2 months.
INTERVAL '123' YEAR Returns an error, because the default precision
is 2, and '123' has 3 digits.
Form of Interval Literal Interpretation
INTERVAL ’
integer
integer time_expr
time_expr
’
DAY
HOUR
MINUTE
( leading_precision )
SECOND
( leading_precision
, fractional_seconds_precision
)
TO
DAY
HOUR
MINUTE
SECOND
( fractional_seconds_precision )
Format Models
Basic Elements of Oracle SQL 3-55
■ leading_precision is the number of digits in the leading field. Accepted
values are 0 to 9. The default is 2.
■ fractional_seconds_precision is the number of digits in the fractional part
of the SECOND datetime field. Accepted values are 1 to 9. The default is 6.
Restriction on the Leading Field: If you specify a trailing field, then it must be less
significant than the leading field. For example, INTERVAL MINUTE TO DAY is not valid.
As a result of this restriction, if SECOND is the leading field, the interval literal cannot
have any trailing field.
The valid range of values for the trailing field are as follows:
■ HOUR: 0 to 23
■ MINUTE: 0 to 59
■ SECOND: 0 to 59.999999999
Examples of the various forms of INTERVAL DAY TO SECOND literals follow, including
some abbreviated versions:
You can add or subtract one DAY TO SECOND interval literal from another DAY TO
SECOND literal. For example.
INTERVAL'20' DAY - INTERVAL'240' HOUR = INTERVAL'10-0' DAY TO SECOND
Format Models
A format model is a character literal that describes the format of datetime or numeric
data stored in a character string. A format model does not change the internal
representation of the value in the database. When you convert a character string into a
date or number, a format model determines how Oracle Database interprets the string.
Form of Interval Literal Interpretation
INTERVAL '4 5:12:10.222' DAY TO
SECOND(3)
4 days, 5 hours, 12 minutes, 10 seconds, and
222 thousandths of a second.
INTERVAL '4 5:12' DAY TO MINUTE 4 days, 5 hours and 12 minutes.
INTERVAL '400 5' DAY(3) TO HOUR 400 days 5 hours.
INTERVAL '400' DAY(3) 400 days.
INTERVAL '11:12:10.2222222' HOUR
TO SECOND(7)
11 hours, 12 minutes, and 10.2222222 seconds.
INTERVAL '11:20' HOUR TO MINUTE 11 hours and 20 minutes.
INTERVAL '10' HOUR 10 hours.
INTERVAL '10:22' MINUTE TO SECOND 10 minutes 22 seconds.
INTERVAL '10' MINUTE 10 minutes.
INTERVAL '4' DAY 4 days.
INTERVAL '25' HOUR 25 hours.
INTERVAL '40' MINUTE 40 minutes.
INTERVAL '120' HOUR(3) 120 hours.
INTERVAL '30.12345' SECOND(2,4) 30.1235 seconds. The fractional second '12345'
is rounded to '1235' because the precision is 4.
Format Models
3-56 Oracle Database SQL Language Reference
In SQL statements, you can use a format model as an argument of the TO_CHAR and
TO_DATE functions to specify:
■ The format for Oracle to use to return a value from the database
■ The format for a value you have specified for Oracle to store in the database
For example:
■ The datetime format model for the string '17:45:29' is 'HH24:MI:SS'.
■ The datetime format model for the string '11-Nov-1999' is 'DD-Mon-YYYY'.
■ The number format model for the string '$2,304.25' is '$9,999.99'.
For lists of number and datetime format model elements, see Table 3–13, " Number
Format Elements" on page 3-57 and Table 3–15, " Datetime Format Elements" on
page 3-60.
The values of some formats are determined by the value of initialization parameters.
For such formats, you can specify the characters returned by these format elements
implicitly using the initialization parameter NLS_TERRITORY. You can change the
default date format for your session with the ALTER SESSION statement.
This remainder of this section describes how to use the following format models:
■ Number Format Models
■ Datetime Format Models
■ Format Model Modifiers
Number Format Models
You can use number format models in the following functions:
■ In the TO_CHAR function to translate a value of NUMBER, BINARY_FLOAT, or
BINARY_DOUBLE data type to VARCHAR2 data type
■ In the TO_NUMBER function to translate a value of CHAR or VARCHAR2 data type to
NUMBER data type
■ In the TO_BINARY_FLOAT and TO_BINARY_DOUBLE functions to translate CHAR
and VARCHAR2 expressions to BINARY_FLOAT or BINARY_DOUBLE values
All number format models cause the number to be rounded to the specified number of
significant digits. If a value has more significant digits to the left of the decimal place
than are specified in the format, then pound signs (#) replace the value. This event
typically occurs when you are using TO_CHAR with a restrictive number format string,
causing a rounding operation.
■ If a positive NUMBER value is extremely large and cannot be represented in the
specified format, then the infinity sign (~) replaces the value. Likewise, if a
See Also:
■ ALTER SESSION on page 11-45 for information on changing the
values of these parameters and Format Model Examples on
page 3-67 for examples of using format models
■ TO_CHAR (datetime) on page 5-219, TO_CHAR (number) on
page 5-221, and TO_DATE on page 5-223
■ Oracle Database Reference and Oracle Database Globalization Support
Guide for information on these parameters
Format Models
Basic Elements of Oracle SQL 3-57
negative NUMBER value is extremely small and cannot be represented by the
specified format, then the negative infinity sign replaces the value (-~).
■ If a BINARY_FLOAT or BINARY_DOUBLE value is converted to CHAR or NCHAR,
and the input is either infinity or NaN (not a number), then Oracle always returns
the pound signs to replace the value. However, if you omit the format model, then
Oracle returns either Inf or Nan as a string.
Number Format Elements
A number format model is composed of one or more number format elements. The
tables that follow list the elements of a number format model and provide some
examples.
Negative return values automatically contain a leading negative sign and positive
values automatically contain a leading space unless the format model contains the MI,
S, or PR format element.
Table 3–13 Number Format Elements
Element Example Description
, (comma) 9,999 Returns a comma in the specified position. You can specify multiple commas in a
number format model.
Restrictions:
■ A comma element cannot begin a number format model.
■ A comma cannot appear to the right of a decimal character or period in a
number format model.
. (period) 99.99 Returns a decimal point, which is a period (.) in the specified position.
Restriction: You can specify only one period in a number format model.
$ $9999 Returns value with a leading dollar sign.
0 0999
9990
Returns leading zeros.
Returns trailing zeros.
9 9999 Returns value with the specified number of digits with a leading space if positive
or with a leading minus if negative. Leading zeros are blank, except for a zero
value, which returns a zero for the integer part of the fixed-point number.
B B9999 Returns blanks for the integer part of a fixed-point number when the integer part
is zero (regardless of zeros in the format model).
C C999 Returns in the specified position the ISO currency symbol (the current value of the
NLS_ISO_CURRENCY parameter).
D 99D99 Returns in the specified position the decimal character, which is the current value
of the NLS_NUMERIC_CHARACTER parameter. The default is a period (.).
Restriction: You can specify only one decimal character in a number format model.
EEEE 9.9EEEE Returns a value using in scientific notation.
G 9G999 Returns in the specified position the group separator (the current value of the
NLS_NUMERIC_CHARACTER parameter). You can specify multiple group
separators in a number format model.
Restriction: A group separator cannot appear to the right of a decimal character or
period in a number format model.
L L999 Returns in the specified position the local currency symbol (the current value of
the NLS_CURRENCY parameter).
Format Models
3-58 Oracle Database SQL Language Reference
Table 3–14 shows the results of the following query for different values of number and
'fmt':
SELECT TO_CHAR(number, 'fmt')
FROM DUAL;
MI 9999MI Returns negative value with a trailing minus sign (-).
Returns positive value with a trailing blank.
Restriction: The MI format element can appear only in the last position of a
number format model.
PR 9999PR Returns negative value in <angle brackets>.
Returns positive value with a leading and trailing blank.
Restriction: The PR format element can appear only in the last position of a
number format model.
RN
rn
RN
rn
Returns a value as Roman numerals in uppercase.
Returns a value as Roman numerals in lowercase.
Value can be an integer between 1 and 3999.
S S9999
9999S
Returns negative value with a leading minus sign (-).
Returns positive value with a leading plus sign (+).
Returns negative value with a trailing minus sign (-).
Returns positive value with a trailing plus sign (+).
Restriction: The S format element can appear only in the first or last position of a
number format model.
TM TM The text minimum number format model returns (in decimal output) the smallest
number of characters possible. This element is case insensitive.
The default is TM9, which returns the number in fixed notation unless the output
exceeds 64 characters. If the output exceeds 64 characters, then Oracle Database
automatically returns the number in scientific notation.
Restrictions:
■ You cannot precede this element with any other element.
■ You can follow this element only with one 9 or one E (or e), but not with any
combination of these. The following statement returns an error:
SELECT TO_CHAR(1234, 'TM9e') FROM DUAL;
U U9999 Returns in the specified position the Euro (or other) dual currency symbol,
determined by the current value of the NLS_DUAL_CURRENCY parameter.
V 999V99 Returns a value multiplied by 10n
(and if necessary, round it up), where n is the
number of 9's after the V.
X XXXX
xxxx
Returns the hexadecimal value of the specified number of digits. If the specified
number is not an integer, then Oracle Database rounds it to an integer.
Restrictions:
■ This element accepts only positive values or 0. Negative values return an
error.
■ You can precede this element only with 0 (which returns leading zeroes) or
FM. Any other elements return an error. If you specify neither 0 nor FM with
X, then the return always has one leading blank.
Table 3–13 (Cont.) Number Format Elements
Element Example Description
Format Models
Basic Elements of Oracle SQL 3-59
Datetime Format Models
You can use datetime format models in the following functions:
■ In the TO_* datetime functions to translate a character value that is in a format
other than the default format into a datetime value. (The TO_* datetime functions
are TO_DATE, TO_TIMESTAMP, and TO_TIMESTAMP_TZ.)
■ In the TO_CHAR function to translate a datetime value into a character value that is
in a format other than the default format (for example, to print the date from an
application)
The total length of a datetime format model cannot exceed 22 characters.
The default datetime formats are specified either explicitly with the NLS session
parameters NLS_DATE_FORMAT, NLS_TIMESTAMP_FORMAT, and NLS_TIMESTAMP_
TZ_FORMAT, or implicitly with the NLS session parameter NLS_TERRITORY. You can
change the default datetime formats for your session with the ALTER SESSION
statement.
Table 3–14 Results of Number Conversions
number 'fmt' Result
-1234567890 9999999999S '1234567890-'
0 99.99 ' .00'
+0.1 99.99 ' .10'
-0.2 99.99 ' -.20'
0 90.99 ' 0.00'
+0.1 90.99 ' 0.10'
-0.2 90.99 ' -0.20'
0 9999 ' 0'
1 9999 ' 1'
0 B9999 ' '
1 B9999 ' 1'
0 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.2E+02'
+123.45 FM999.009 '123.45'
+123.0 FM999.009 '123.00'
+123.45 L999.99 ' $123.45'
+123.45 FML999.99 '$123.45'
+1234567890 9999999999S '1234567890+'
Format Models
3-60 Oracle Database SQL Language Reference
Datetime Format Elements
A datetime format model is composed of one or more datetime format elements as
listed in Table 3–15, " Datetime Format Elements" on page 3-60.
■ For input format models, format items cannot appear twice, and format items that
represent similar information cannot be combined. For example, you cannot use
'SYYYY' and 'BC' in the same format string.
■ The second column indicates whether the format element can be used in the TO_*
datetime functions. All format elements can be used in the TO_CHAR function.
■ The following datetime format elements can be used in timestamp and interval
format models, but not in the original DATE format model: FF, TZD, TZH, TZM,
and TZR.
■ Many datetime format elements are padded with blanks or leading zeroes to a
specific length. Refer to the format model modifier FM on page 3-66 for more
information.
Uppercase Letters in Date Format Elements Capitalization in a spelled-out word,
abbreviation, or Roman numeral follows capitalization in the corresponding format
element. For example, the date format model 'DAY' produces capitalized words like
'MONDAY'; 'Day' produces 'Monday'; and 'day' produces 'monday'.
Punctuation and Character Literals in Datetime Format Models You can include these
characters in a date format model:
■ Punctuation such as hyphens, slashes, commas, periods, and colons
■ Character literals, enclosed in double quotation marks
These characters appear in the return value in the same location as they appear in the
format model.
See Also: ALTER SESSION on page 11-45 and Oracle Database
Globalization Support Guide for information on the NLS parameters
Table 3–15 Datetime Format Elements
Element
TO_*
datetime
functions? Description
-
/
,
.
;
:
"text"
Yes Punctuation and quoted text is reproduced in the result.
AD
A.D.
Yes AD indicator with or without periods.
AM
A.M.
Yes Meridian indicator with or without periods.
BC
B.C.
Yes BC indicator with or without periods.
Format Models
Basic Elements of Oracle SQL 3-61
CC
SCC
Century.
■ If the last 2 digits of a 4-digit year are between 01 and 99 (inclusive), then the
century is one greater than the first 2 digits of that year.
■ If the last 2 digits of a 4-digit year are 00, then the century is the same as the first
2 digits of that year.
For example, 2002 returns 21; 2000 returns 20.
D Yes Day of week (1-7). This element depends on the NLS territory of the session.
DAY Yes Name of day.
DD Yes Day of month (1-31).
DDD Yes Day of year (1-366).
DL Yes Returns a value in the long date format, which is an extension of the Oracle
Database DATE format, determined by the current value of the NLS_DATE_FORMAT
parameter. Makes the appearance of the date components (day name, month
number, and so forth) depend on the NLS_TERRITORY and NLS_LANGUAGE
parameters. For example, in the AMERICAN_AMERICA locale, this is equivalent to
specifying the format 'fmDay, Month dd, yyyy'. In the GERMAN_GERMANY locale,
it is equivalent to specifying the format 'fmDay, dd. Month yyyy'.
Restriction: You can specify this format only with the TS element, separated by
white space.
DS Yes Returns a value in the short date format. Makes the appearance of the date
components (day name, month number, and so forth) depend on the NLS_
TERRITORY and NLS_LANGUAGE parameters. For example, in the AMERICAN_
AMERICA locale, this is equivalent to specifying the format 'MM/DD/RRRR'. In the
ENGLISH_UNITED_KINGDOM locale, it is equivalent to specifying the format
'DD/MM/RRRR'.
Restriction: You can specify this format only with the TS element, separated by
white space.
DY Yes Abbreviated name of day.
E Yes Abbreviated era name (Japanese Imperial, ROC Official, and Thai Buddha
calendars).
EE Yes Full era name (Japanese Imperial, ROC Official, and Thai Buddha calendars).
FF [1..9] Yes Fractional seconds; no radix character is printed. Use the X format element to add
the radix character. Use the numbers 1 to 9 after FF to specify the number of digits in
the fractional second portion of the datetime value returned. If you do not specify a
digit, then Oracle Database uses the precision specified for the datetime data type or
the data type's default precision. Valid in timestamp and interval formats, but not in
DATE formats.
Examples: 'HH:MI:SS.FF'
SELECT TO_CHAR(SYSTIMESTAMP, 'SS.FF3') from dual;
FM Yes Returns a value with no leading or trailing blanks.
See Also: Additional discussion on this format model modifier in the Oracle
Database SQL Language Reference
FX Yes Requires exact matching between the character data and the format model.
See Also: Additional discussion on this format model modifier in the Oracle
Database SQL Language Reference
HH
HH12
Yes Hour of day (1-12).
Table 3–15 (Cont.) Datetime Format Elements
Element
TO_*
datetime
functions? Description
Format Models
3-62 Oracle Database SQL Language Reference
HH24 Yes Hour of day (0-23).
IW Week of year (1-52 or 1-53) based on the ISO standard.
IYY
IY
I
Last 3, 2, or 1 digit(s) of ISO year.
IYYY 4-digit year based on the ISO standard.
J Yes Julian day; the number of days since January 1, 4712 BC. Number specified with J
must be integers.
MI Yes Minute (0-59).
MM Yes Month (01-12; January = 01).
MON Yes Abbreviated name of month.
MONTH Yes Name of month.
PM
P.M.
Yes Meridian indicator with or without periods.
Q Quarter of year (1, 2, 3, 4; January - March = 1).
RM Yes Roman numeral month (I-XII; January = I).
RR Yes Lets you store 20th century dates in the 21st century using only two digits.
See Also: Additional discussion on RR datetime format element in the Oracle
Database SQL Language Reference
RRRR Yes Round year. Accepts either 4-digit or 2-digit input. If 2-digit, provides the same
return as RR. If you do not want this functionality, then enter the 4-digit year.
SS Yes Second (0-59).
SSSSS Yes Seconds past midnight (0-86399).
TS Yes Returns a value in the short time format. Makes the appearance of the time
components (hour, minutes, and so forth) depend on the NLS_TERRITORY and
NLS_LANGUAGE initialization parameters.
Restriction: You can specify this format only with the DL or DS element, separated
by white space.
TZD Yes Daylight saving information. The TZD value is an abbreviated time zone string with
daylight saving information. It must correspond with the region specified in TZR.
Valid in timestamp and interval formats, but not in DATE formats.
Example: PST (for US/Pacific standard time); PDT (for US/Pacific daylight time).
TZH Yes Time zone hour. (See TZM format element.) Valid in timestamp and interval formats,
but not in DATE formats.
Example: 'HH:MI:SS.FFTZH:TZM'.
TZM Yes Time zone minute. (See TZH format element.) Valid in timestamp and interval
formats, but not in DATE formats.
Example: 'HH:MI:SS.FFTZH:TZM'.
TZR Yes Time zone region information. The value must be one of the time zone region names
supported in the database. Valid in timestamp and interval formats, but not in DATE
formats.
Example: US/Pacific
Table 3–15 (Cont.) Datetime Format Elements
Element
TO_*
datetime
functions? Description
Format Models
Basic Elements of Oracle SQL 3-63
Oracle Database converts strings to dates with some flexibility. For example, when the
TO_DATE function is used, a format model containing punctuation characters matches
an input string lacking some or all of these characters, provided each numerical
element in the input string contains the maximum allowed number of digits—for
example, two digits '05' for 'MM' or four digits '2007' for 'YYYY'. The following
statement does not return an error:
SELECT TO_CHAR (TO_DATE('0207','MM/YY'), 'MM/YY') FROM DUAL;
TO_CH
-----
02/07
However, the following format string does return an error, because the FX (format
exact) format modifier requires an exact match of the expression and the format string:
SELECT TO_CHAR(TO_DATE('0207', 'fxmm/yy'), 'mm/yy') FROM DUAL;
SELECT TO_CHAR(TO_DATE('0207', 'fxmm/yy'), 'mm/yy') FROM DUAL
*
ERROR at line 1:
ORA-01861: literal does not match format string
Any non-alphanumeric character is allowed to match the punctuation characters in the
format model. For example, the following statement does not return an error:
SELECT TO_CHAR (TO_DATE('02#07','MM/YY'), 'MM/YY') FROM DUAL;
TO_CH
-----
02/07
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to
the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on
the seventh.
X Yes Local radix character.
Example: 'HH:MI:SSXFF'.
Y,YYY Yes Year with comma in this position.
YEAR
SYEAR
Year, spelled out; S prefixes BC dates with a minus sign (-).
YYYY
SYYYY
Yes 4-digit year; S prefixes BC dates with a minus sign.
YYY
YY
Y
Yes Last 3, 2, or 1 digit(s) of year.
See Also: "Format Model Modifiers" on page 3-66 and
"String-to-Date Conversion Rules" on page 3-68 for more information
Table 3–15 (Cont.) Datetime Format Elements
Element
TO_*
datetime
functions? Description
Format Models
3-64 Oracle Database SQL Language Reference
Datetime Format Elements and Globalization Support
The functionality of some datetime format elements depends on the country and
language in which you are using Oracle Database. For example, these datetime format
elements return spelled values:
■ MONTH
■ MON
■ DAY
■ DY
■ BC or AD or B.C. or A.D.
■ AM or PM or A.M or P.M.
The language in which these values are returned is specified either explicitly with the
initialization parameter NLS_DATE_LANGUAGE or implicitly with the initialization
parameter NLS_LANGUAGE. The values returned by the YEAR and SYEAR datetime
format elements are always in English.
The datetime format element D returns the number of the day of the week (1-7). The
day of the week that is numbered 1 is specified implicitly by the initialization
parameter NLS_TERRITORY.
ISO Standard Date Format Elements
Oracle calculates the values returned by the datetime format elements IYYY, IYY, IY, I,
and IW according to the ISO standard. For information on the differences between
these values and those returned by the datetime format elements YYYY, YYY, YY, Y,
and WW, see the discussion of globalization support in Oracle Database Globalization
Support Guide.
The RR Datetime Format Element
The RR datetime format element is similar to the YY datetime format element, but it
provides additional flexibility for storing date values in other centuries. The RR
datetime format element lets you store 20th century dates in the 21st century by
specifying only the last two digits of the year.
If you use the TO_DATE function with the YY datetime format element, then the year
returned always has the same first 2 digits as the current year. If you use the RR
datetime format element instead, then the century of the return value varies according
to the specified two-digit year and the last two digits of the current year.
That is:
■ If the specified two-digit year is 00 to 49, then
– If the last two digits of the current year are 00 to 49, then the returned year has
the same first two digits as the current year.
– If the last two digits of the current year are 50 to 99, then the first 2 digits of
the returned year are 1 greater than the first 2 digits of the current year.
■ If the specified two-digit year is 50 to 99, then
– If the last two digits of the current year are 00 to 49, then the first 2 digits of
the returned year are 1 less than the first 2 digits of the current year.
See Also: Oracle Database Reference and Oracle Database Globalization
Support Guide for information on globalization support initialization
parameters
Format Models
Basic Elements of Oracle SQL 3-65
– If the last two digits of the current year are 50 to 99, then the returned year has
the same first two digits as the current year.
The following examples demonstrate the behavior of the RR datetime format element.
RR Datetime Format Examples
Assume these queries are issued between 1950 and 1999:
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year"
FROM DUAL;
Year
----
1998
SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year"
FROM DUAL;
Year
----
2017
Now assume these queries are issued between 2000 and 2049:
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year"
FROM DUAL;
Year
----
1998
SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year"
FROM DUAL;
Year
----
2017
Note that the queries return the same values regardless of whether they are issued
before or after the year 2000. The RR datetime format element lets you write SQL
statements that will return the same values from years whose first two digits are
different.
Datetime Format Element Suffixes
Table 3–16 lists suffixes that can be added to datetime format elements:
Notes on date format element suffixes:
■ When you add one of these suffixes to a datetime format element, the return value
is always in English.
Table 3–16 Date Format Element Suffixes
Suffix Meaning Example Element Example Value
TH Ordinal Number DDTH 4TH
SP Spelled Number DDSP FOUR
SPTH or THSP Spelled, ordinal number DDSPTH FOURTH
Format Models
3-66 Oracle Database SQL Language Reference
■ Datetime suffixes are valid only to format output. You cannot use them to insert a
date into the database.
Format Model Modifiers
The FM and FX modifiers, used in format models in the TO_CHAR function, control
blank padding and exact format checking.
A modifier can appear in a format model more than once. In such a case, each
subsequent occurrence toggles the effects of the modifier. Its effects are enabled for the
portion of the model following its first occurrence, and then disabled for the portion
following its second, and then reenabled for the portion following its third, and so on.
FM Fill mode. Oracle uses trailing blank characters and leading zeroes to fill format
elements to a constant width. The width is equal to the display width of the largest
element for the relevant format model:
■ Numeric elements are padded with leading zeros to the width of the maximum
value allowed for the element. For example, the YYYY element is padded to four
digits (the length of '9999'), HH24 to two digits (the length of '23'), and DDD to
three digits (the length of '366').
■ The character elements MONTH, MON, DAY, and DY are padded with trailing blanks
to the width of the longest full month name, the longest abbreviated month name,
the longest full date name, or the longest abbreviated day name, respectively,
among valid names determined by the values of NLS_DATE_LANGUAGE and NLS_
CALENDAR parameters. For example, when NLS_DATE_LANGUAGE is AMERICAN
and NLS_CALENDAR is GREGORIAN (the default), the largest element for MONTH is
SEPTEMBER, so all values of the MONTH format element are padded to nine display
characters. The values of the NLS_DATE_LANGUAGE and NLS_CALENDAR
parameters are specified in the third argument to TO_CHAR and TO_* datetime
functions or they are retrieved from the NLS environment of the current session.
■ The character element RM is padded with trailing blanks to the length of 4, which
is the length of 'viii'.
■ Other character elements and spelled-out numbers (SP, SPTH, and THSP suffixes)
are not padded.
The FM modifier suppresses the above padding in the return value of the TO_CHAR
function.
FX Format exact. This modifier specifies exact matching for the character argument
and datetime format model of a TO_DATE function:
■ Punctuation and quoted text in the character argument must exactly match (except
for case) the corresponding parts of the format model.
■ The character argument cannot have extra blanks. Without FX, Oracle ignores
extra blanks.
■ Numeric data in the character argument must have the same number of digits as
the corresponding element in the format model. Without FX, numbers in the
character argument can omit leading zeros.
When FX is enabled, you can disable this check for leading zeros by using the FM
modifier as well.
If any portion of the character argument violates any of these conditions, then Oracle
returns an error message.
Format Models
Basic Elements of Oracle SQL 3-67
Format Model Examples
The following statement uses a date format model to return a character expression:
SELECT TO_CHAR(SYSDATE, 'fmDDTH')||' of '||TO_CHAR
(SYSDATE, 'fmMonth')||', '||TO_CHAR(SYSDATE, 'YYYY') "Ides"
FROM DUAL;
Ides
------------------
3RD of April, 1998
The preceding statement also uses the FM modifier. If FM is omitted, then the month is
blank-padded to nine characters:
SELECT TO_CHAR(SYSDATE, 'DDTH')||' of '||
TO_CHAR(SYSDATE, 'Month')||', '||
TO_CHAR(SYSDATE, 'YYYY') "Ides"
FROM DUAL;
Ides
-----------------------
03RD of April , 1998
The following statement places a single quotation mark in the return value by using a
date format model that includes two consecutive single quotation marks:
SELECT TO_CHAR(SYSDATE, 'fmDay')||'''s Special' "Menu"
FROM DUAL;
Menu
-----------------
Tuesday's Special
Two consecutive single quotation marks can be used for the same purpose within a
character literal in a format model.
Table 3–17 shows whether the following statement meets the matching conditions for
different values of char and 'fmt' using FX (the table named table has a column
date_column of data type DATE):
UPDATE table
SET date_column = TO_DATE(char, 'fmt');
Format of Return Values: Examples You can use a format model to specify the
format for Oracle to use to return values from the database to you.
Table 3–17 Matching Character Data and Format Models with the FX Format Model
Modifier
char 'fmt' Match or Error?
'15/ JAN /1998' 'DD-MON-YYYY' Match
' 15! JAN % /1998' 'DD-MON-YYYY' Error
'15/JAN/1998' 'FXDD-MON-YYYY' Error
'15-JAN-1998' 'FXDD-MON-YYYY' Match
'1-JAN-1998' 'FXDD-MON-YYYY' Error
'01-JAN-1998' 'FXDD-MON-YYYY' Match
'1-JAN-1998' 'FXFMDD-MON-YYYY' Match
Format Models
3-68 Oracle Database SQL Language Reference
The following statement selects the salaries of the employees in Department 80 and
uses the TO_CHAR function to convert these salaries into character values with the
format specified by the number format model '$99,990.99':
SELECT last_name employee, TO_CHAR(salary, '$99,990.99')
FROM employees
WHERE department_id = 80;
Because of this format model, Oracle returns salaries with leading dollar signs,
commas every three digits, and two decimal places.
The following statement selects the date on which each employee from Department 20
was hired and uses the TO_CHAR function to convert these dates to character strings
with the format specified by the date format model 'fmMonth DD, YYYY':
SELECT last_name employee,
TO_CHAR(hire_date,'fmMonth DD, YYYY') hiredate
FROM employees
WHERE department_id = 20;
With this format model, Oracle returns the hire dates without blank padding (as
specified by fm), two digits for the day, and the century included in the year.
Supplying the Correct Format Model: Examples When you insert or update a
column value, the data type of the value that you specify must correspond to the
column data type of the column. You can use format models to specify the format of a
value that you are converting from one data type to another data type required for a
column.
For example, a value that you insert into a DATE column must be a value of the DATE
data type or a character string in the default date format (Oracle implicitly converts
character strings in the default date format to the DATE data type). If the value is in
another format, then you must use the TO_DATE function to convert the value to the
DATE data type. You must also use a format model to specify the format of the
character string.
The following statement updates Hunold's hire date using the TO_DATE function
with the format mask 'YYYY MM DD' to convert the character string '2008 05 20' to a
DATE value:
UPDATE employees
SET hire_date = TO_DATE('2008 05 20','YYYY MM DD')
WHERE last_name = 'Hunold';
String-to-Date Conversion Rules
The following additional formatting rules apply when converting string values to date
values (unless you have used the FX or FXFM modifiers in the format model to control
exact format checking):
■ You can omit punctuation included in the format string from the date string if all
the digits of the numerical format elements, including leading zeros, are specified.
For example, specify 02 and not 2 for two-digit format elements such as MM, DD,
and YY.
■ You can omit time fields found at the end of a format string from the date string.
See Also: "Format Model Modifiers" on page 3-66 for a description
of the fm format element
Format Models
Basic Elements of Oracle SQL 3-69
■ You can use any non-alphanumeric character in the date string to match the
punctuation symbol in the format string.
■ If a match fails between a datetime format element and the corresponding
characters in the date string, then Oracle attempts alternative format elements, as
shown in Table 3–18.
XML Format Model
The SYS_XMLGEN function returns an instance of type XMLType containing an XML
document. Oracle provides the XMLFormat object, which lets you format the output of
the SYS_XMLGEN function.
Table 3–19 lists and describes the attributes of the XMLFormat object. The function that
implements this type follows the table.
Table 3–18 Oracle Format Matching
Original Format Element Additional Format Elements to Try in Place of the Original
'MM' 'MON' and 'MONTH'
'MON 'MONTH'
'MONTH' 'MON'
'YY' 'YYYY'
'RR' 'RRRR'
See Also:
■ SYS_XMLGEN on page 5-211 for information on the SYS_XMLGEN
function
■ Oracle XML Developer's Kit Programmer's Guide for more
information on the implementation of the XMLFormat object and
its use
Table 3–19 Attributes of the XMLFormat Object
Attribute Data Type Purpose
enclTag VARCHAR2(4000) The name of the enclosing tag for the result of the SYS_XMLGEN
function. If the input to the function is a column name, then the
default is the column name. Otherwise the default is ROW. When
schemaType is set to USE_GIVEN_SCHEMA, this attribute also gives
the name of the XMLSchema element.
schemaType VARCHAR2(100) The type of schema generation for the output document. Valid values
are 'NO_SCHEMA' and 'USE_GIVEN_SCHEMA'. The default is 'NO_
SCHEMA'.
schemaName VARCHAR2(4000) The name of the target schema Oracle uses if the value of the
schemaType is 'USE_GIVEN_SCHEMA'. If you specify schemaName,
then Oracle uses the enclosing tag as the element name.
targetNameSpace VARCHAR2(4000) The target namespace if the schema is specified (that is, schemaType
is GEN_SCHEMA_*, or USE_GIVEN_SCHEMA)
dburlPrefix VARCHAR2(4000) The URL to the database to use if WITH_SCHEMA is specified. If this
attribute is not specified, then Oracle declares the URL to the types as
a relative URL reference.
processingIns VARCHAR2(4000) User-provided processing instructions, which are appended to the top
of the function output before the element.
Nulls
3-70 Oracle Database SQL Language Reference
The function that implements the XMLFormat object follows:
STATIC FUNCTION createFormat(
enclTag IN varchar2 := 'ROWSET',
schemaType IN varchar2 := 'NO_SCHEMA',
schemaName IN varchar2 := null,
targetNameSpace IN varchar2 := null,
dburlPrefix IN varchar2 := null,
processingIns IN varchar2 := null) RETURN XMLGenFormatType
deterministic parallel_enable,
MEMBER PROCEDURE genSchema (spec IN varchar2),
MEMBER PROCEDURE setSchemaName(schemaName IN varchar2),
MEMBER PROCEDURE setTargetNameSpace(targetNameSpace IN varchar2),
MEMBER PROCEDURE setEnclosingElementName(enclTag IN varchar2),
MEMBER PROCEDURE setDbUrlPrefix(prefix IN varchar2),
MEMBER PROCEDURE setProcessingIns(pi IN varchar2),
CONSTRUCTOR FUNCTION XMLGenFormatType (
enclTag IN varchar2 := 'ROWSET',
schemaType IN varchar2 := 'NO_SCHEMA',
schemaName IN varchar2 := null,
targetNameSpace IN varchar2 := null,
dbUrlPrefix IN varchar2 := null,
processingIns IN varchar2 := null) RETURN SELF AS RESULT
deterministic parallel_enable,
STATIC function createFormat2(
enclTag in varchar2 := 'ROWSET',
flags in raw) return sys.xmlgenformattype
deterministic parallel_enable
);
Nulls
If a column in a row has no value, then the column is said to be null, or to contain null.
Nulls can appear in columns of any data type that are not restricted by NOT NULL or
PRIMARY KEY integrity constraints. Use a null when the actual value is not known or
when a value would not be meaningful.
Oracle Database treats a character value with a length of zero as null. However, do not
use null to represent a numeric value of zero, because they are not equivalent.
Any arithmetic expression containing a null always evaluates to null. For example,
null added to 10 is null. In fact, all operators (except concatenation) return null when
given a null operand.
Nulls in SQL Functions
For information on null handling in SQL functions, see "Nulls in SQL Functions" on
page 5-2.
Note: Oracle Database currently treats a character value with a
length of zero as null. However, this may not continue to be true in
future releases, and Oracle recommends that you do not treat empty
strings the same as nulls.
Comments
Basic Elements of Oracle SQL 3-71
Nulls with Comparison Conditions
To test for nulls, use only the comparison conditions IS NULL and IS NOT NULL. If you
use any other condition with nulls and the result depends on the value of the null,
then the result is UNKNOWN. Because null represents a lack of data, a null cannot be
equal or unequal to any value or to another null. However, Oracle considers two nulls
to be equal when evaluating a DECODE function. Refer to DECODE on page 5-58 for
syntax and additional information.
Oracle also considers two nulls to be equal if they appear in compound keys. That is,
Oracle considers identical two compound keys containing nulls if all the non-null
components of the keys are equal.
Nulls in Conditions
A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT
statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no
rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further
operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT
FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.
Table 3–20 shows examples of various evaluations involving nulls in conditions. If the
conditions evaluating to UNKNOWN were used in a WHERE clause of a SELECT
statement, then no rows would be returned for that query.
For the truth tables showing the results of logical conditions containing nulls, see
Table 7–5 on page 7-8, Table 7–6 on page 7-8, and Table 7–7 on page 7-8.
Comments
You can create two types of comments:
■ Comments within SQL statements are stored as part of the application code that
executes the SQL statements.
■ Comments associated with individual schema or nonschema objects are stored in
the data dictionary along with metadata on the objects themselves.
Table 3–20 Conditions Containing Nulls
Condition Value of A Evaluation
a IS NULL 10 FALSE
a IS NOT NULL 10 TRUE
a IS NULL NULL TRUE
a IS NOT NULL NULL FALSE
a = NULL 10 UNKNOWN
a != NULL 10 UNKNOWN
a = NULL NULL UNKNOWN
a != NULL NULL UNKNOWN
a = 10 NULL UNKNOWN
a != 10 NULL UNKNOWN
Comments
3-72 Oracle Database SQL Language Reference
Comments Within SQL Statements
Comments can make your application easier for you to read and maintain. For
example, you can include a comment in a statement that describes the purpose of the
statement within your application. With the exception of hints, comments within SQL
statements do not affect the statement execution. Refer to "Hints" on page 3-73 on
using this particular form of comment.
A comment can appear between any keywords, parameters, or punctuation marks in a
statement. You can include a comment in a statement in two ways:
■ Begin the comment with a slash and an asterisk (/*). Proceed with the text of the
comment. This text can span multiple lines. End the comment with an asterisk and
a slash (*/). The opening and terminating characters need not be separated from
the text by a space or a line break.
■ Begin the comment with -- (two hyphens). Proceed with the text of the comment.
This text cannot extend to a new line. End the comment with a line break.
Some of the tools used to enter SQL have additional restrictions. For example, if you
are using SQL*Plus, by default you cannot have a blank line inside a multiline
comment. For more information, refer to the documentation for the tool you use as an
interface to the database.
A SQL statement can contain multiple comments of both styles. The text of a comment
can contain any printable characters in your database character set.
Example These statements contain many comments:
SELECT last_name, salary + NVL(commission_pct, 0),
job_id, e.department_id
/* Select all employees whose compensation is
greater than that of Pataballa.*/
FROM employees e, departments d
/*The DEPARTMENTS table is used to get the department name.*/
WHERE e.department_id = d.department_id
AND salary + NVL(commission_pct,0) > /* Subquery: */
(SELECT salary + NVL(commission_pct,0)
/* total compensation is salar + commission_pct */
FROM employees
WHERE last_name = 'Pataballa');
SELECT last_name, -- select the name
salary + NVL(commission_pct, 0),-- total compensation
job_id, -- job
e.department_id -- and department
FROM employees e, -- of all employees
departments d
WHERE e.department_id = d.department_id
AND salary + NVL(commission_pct, 0) > -- whose compensation
-- is greater than
(SELECT salary + NVL(commission_pct,0) -- the compensation
FROM employees
WHERE last_name = 'Pataballa') -- of Pataballa.
;
Comments on Schema and Nonschema Objects
You can use the COMMENT command to associate a comment with a schema object
(table, view, materialized view, operator, indextype, mining model) or a nonschema
object (edition) using the COMMENT command. You can also create a comment on a
Comments
Basic Elements of Oracle SQL 3-73
column, which is part of a table schema object. Comments associated with schema and
nonschema objects are stored in the data dictionary. Refer to COMMENT on
page 13-44 for a description of this form of comment.
Hints
Hints are comments in a SQL statement that pass instructions to the Oracle Database
optimizer. The optimizer uses these hints to choose an execution plan for the
statement, unless some condition exists that prevents the optimizer from doing so.
Hints were introduced in Oracle7, when users had little recourse if the optimizer
generated suboptimal plans. Now Oracle provides a number of tools, including the
SQL Tuning Advisor, SQL plan management, and SQL Performance Analyzer, to help
you address performance problems that are not solved by the optimizer. Oracle
strongly recommends that you use those tools rather than hints. The tools are far
superior to hints, because when used on an ongoing basis, they provide fresh solutions
as your data and database environment change.
Hints should be used sparingly, and only after you have collected statistics on the
relevant tables and evaluated the optimizer plan without hints using the EXPLAIN
PLAN statement. Changing database conditions as well as query performance
enhancements in subsequent releases can have significant impact on how hints in your
code affect performance.
The remainder of this section provides information on some commonly used hints. If
you decide to use hints rather than the more advanced tuning tools, be aware that any
short-term benefit resulting from the use of hints may not continue to result in
improved performance over the long term.
Using Hints
A statement block can have only one comment containing hints, and that comment
must follow the SELECT, UPDATE, INSERT, MERGE, or DELETE keyword.
The following syntax diagram shows hints contained in both styles of comments that
Oracle supports within a statement block. The hint syntax must follow immediately
after an INSERT, UPDATE, DELETE, SELECT, or MERGE keyword that begins the
statement block.
hint::=
where:
■ The plus sign (+) causes Oracle to interpret the comment as a list of hints. The plus
sign must follow immediately after the comment delimiter. No space is permitted.
■ hint is one of the hints discussed in this section. The space between the plus sign
and the hint is optional. If the comment contains multiple hints, then separate the
hints by at least one space.
■ string is other commenting text that can be interspersed with the hints.
The --+ syntax requires that the entire comment be on a single line.
/*+ hint
string
*/
– – + hint
string
Comments
3-74 Oracle Database SQL Language Reference
Oracle Database ignores hints and does not return an error under the following
circumstances:
■ The hint contains misspellings or syntax errors. However, the database does
consider other correctly specified hints in the same comment.
■ The comment containing the hint does not follow a DELETE, INSERT, MERGE,
SELECT, or UPDATE keyword.
■ A combination of hints conflict with each other. However, the database does
consider other hints in the same comment.
■ The database environment uses PL/SQL version 1, such as Forms version 3
triggers, Oracle Forms 4.5, and Oracle Reports 2.5.
Many hints can apply both to specific tables or indexes and more globally to tables
within a view or to columns that are part of indexes. The syntactic elements
tablespec and indexspec define these global hints.
tablespec::=
You must specify the table to be accessed exactly as it appears in the statement. If the
statement uses an alias for the table, then use the alias rather than the table name in
the hint. However, do not include the schema name with the table name within the
hint, even if the schema name appears in the statement.
indexspec::=
When tablespec is followed by indexspec in the specification of a hint, a comma
separating the table name and index name is permitted but not required. Commas are
also permitted, but not required, to separate multiple occurrences of indexspec.
See Also: Oracle Database Performance Tuning Guide for information
on the following topics:
■ When to use global hints and how Oracle interprets them
■ Using EXPLAIN PLAN to learn how the optimizer is executing a
query
■ References in hints to tables within views
view .
table
index
(
table .
column )
Comments
Basic Elements of Oracle SQL 3-75
Specifying a Query Block in a Hint
You can specify an optional query block name in many hints to specify the query block
to which the hint applies. This syntax lets you specify in the outer query a hint that
applies to an inline view.
The syntax of the query block argument is of the form @queryblock, where
queryblock is an identifier that specifies a query block in the query. The
queryblock identifier can either be system-generated or user-specified. When you
specify a hint in the query block itself to which the hint applies, you omit the
@queryblock syntax.
■ The system-generated identifier can be obtained by using EXPLAIN PLAN for the
query. Pretransformation query block names can be determined by running
EXPLAIN PLAN for the query using the NO_QUERY_TRANSFORMATION hint. See
"NO_QUERY_TRANSFORMATION Hint" on page 3-93.
■ The user-specified name can be set with the QB_NAME hint. See "QB_NAME Hint"
on page 3-101.
Table 3–21 lists the hints by functional category and contains cross-references to the
syntax and semantics for each hint. An alphabetical reference of the hints follows the
table.
Note: Oracle Database ignores global hints that refer to multiple
query blocks. For example, the LEADING hint is ignored in the
following query because it refers to the main query block containing
table a and view query block v:
SELECT /*+ LEADING(v.b a v.c) */ *
FROM a,v
WHERE a.id = v.id;
To avoid this issue, Oracle recommends that you specify a query block
in the hint:
SELECT /*+ LEADING(A@SEL$1 B@SEL$2 C@SEL$2) */
FROM a a, v v
WHERE a.id = v.id;
Refer to Oracle Database Performance Tuning Guide for more information
on specifying hints.
See Also: Oracle Database Performance Tuning Guide for
information on:
■ Using hints to optimize SQL statements and on detailed
information about using the tablespec and indexspec
syntax
■ Specifying a query block in a hint
■ Descriptions of hint categories and when to use them
Table 3–21 Hints by Functional Category
Hint Link to Syntax and Semantics
Optimization Goals and
Approaches
ALL_ROWS Hint on page 3-77
FIRST_ROWS Hint on page 3-81
Comments
3-76 Oracle Database SQL Language Reference
Access Path Hints CLUSTER Hint on page 3-80
-- FULL Hint on page 3-82
-- HASH Hint on page 3-82
-- INDEX Hint on page 3-83
NO_INDEX Hint on page 3-90
-- INDEX_ASC Hint on page 3-84
INDEX_DESC Hint on page 3-85
-- INDEX_COMBINE Hint on page 3-84
-- INDEX_JOIN Hint on page 3-85
-- INDEX_FFS Hint on page 3-85
-- INDEX_SS Hint on page 3-86
-- INDEX_SS_ASC Hint on page 3-86
-- INDEX_SS_DESC Hint on page 3-87
-- NATIVE_FULL_OUTER_JOIN Hint on page 3-88
NO_NATIVE_FULL_OUTER_JOIN Hint on page 3-91
-- NO_INDEX_FFS Hint on page 3-90
-- NO_INDEX_SS Hint on page 3-90
Join Order Hints ORDERED Hint on page 3-96
-- LEADING Hint on page 3-87
Join Operation Hints USE_HASH Hint on page 3-104
NO_USE_HASH Hint on page 3-94
-- USE_MERGE Hint on page 3-105
NO_USE_MERGE Hint on page 3-94
-- USE_NL Hint on page 3-105
USE_NL_WITH_INDEX Hint on page 3-106
NO_USE_NL Hint on page 3-95
Parallel Execution Hints PARALLEL Hint on page 3-96
NO_PARALLEL Hint on page 3-91
-- PARALLEL_INDEX Hint on page 3-98
NO_PARALLEL_INDEX Hint on page 3-92
-- PQ_DISTRIBUTE Hint on page 3-98
Online Application
Upgrade Hints
CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79
IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83
RETRY_ON_ROW_CHANGE Hint on page 3-102
Query Transformation
Hints
FACT Hint on page 3-81
NO_FACT Hint on page 3-89
-- MERGE Hint on page 3-87
NO_MERGE Hint on page 3-91
Table 3–21 (Cont.) Hints by Functional Category
Hint Link to Syntax and Semantics
Comments
Basic Elements of Oracle SQL 3-77
Alphabetical Listing of Hints
This section provides syntax and semantics for all hints in alphabetical order.
ALL_ROWS Hint
-- NO_EXPAND Hint on page 3-89
USE_CONCAT Hint on page 3-104
-- REWRITE Hint on page 3-103
NO_REWRITE Hint on page 3-93
-- UNNEST Hint on page 3-104
NO_UNNEST Hint on page 3-94
-- STAR_TRANSFORMATION Hint on page 3-103
NO_STAR_TRANSFORMATION Hint on page 3-94
-- NO_QUERY_TRANSFORMATION Hint on page 3-93
XML Hints NO_XMLINDEX_REWRITE Hint on page 3-95
-- NO_XML_QUERY_REWRITE Hint on page 3-95
Other Hints APPEND Hint on page 3-78
APPEND_VALUES Hint on page 3-78
NOAPPEND Hint on page 3-89
-- CACHE Hint on page 3-79
NOCACHE Hint on page 3-89
-- CURSOR_SHARING_EXACT Hint on page 3-80
-- DRIVING_SITE Hint on page 3-80
-- DYNAMIC_SAMPLING Hint on page 3-81
-- MODEL_MIN_ANALYSIS Hint on page 3-88
-- MONITOR Hint on page 3-88
-- NO_MONITOR Hint on page 3-91
-- OPT_PARAM Hint on page 3-95
-- PUSH_PRED Hint on page 3-101
NO_PUSH_PRED Hint on page 3-92
-- PUSH_SUBQ Hint on page 3-101
NO_PUSH_SUBQ Hint on page 3-93
-- PX_JOIN_FILTER Hint on page 3-101
NO_PX_JOIN_FILTER Hint on page 3-93
-- QB_NAME Hint on page 3-101
-- RESULT_CACHE Hint on page 3-102
NO_RESULT_CACHE Hint on page 3-93
Table 3–21 (Cont.) Hints by Functional Category
Hint Link to Syntax and Semantics
/*+ ALL_ROWS */
Comments
3-78 Oracle Database SQL Language Reference
The ALL_ROWS hint instructs the optimizer to optimize a statement block with a goal
of best throughput, which is minimum total resource consumption. For example, the
optimizer uses the query optimization approach to optimize this statement for best
throughput:
SELECT /*+ ALL_ROWS */ employee_id, last_name, salary, job_id
FROM employees
WHERE employee_id = 7566;
If you specify either the ALL_ROWS or the FIRST_ROWS hint in a SQL statement, and if
the data dictionary does not have statistics about tables accessed by the statement,
then the optimizer uses default statistical values, such as allocated storage for such
tables, to estimate the missing statistics and to subsequently choose an execution plan.
These estimates might not be as accurate as those gathered by the DBMS_STATS
package, so you should use the DBMS_STATS package to gather statistics.
If you specify hints for access paths or join operations along with either the ALL_ROWS
or FIRST_ROWS hint, then the optimizer gives precedence to the access paths and join
operations specified by the hints.
APPEND Hint
The APPEND hint instructs the optimizer to use direct-path INSERT with the subquery
syntax of the INSERT statement.
■ Conventional INSERT is the default in serial mode. In serial mode, direct path can
be used only if you include the APPEND hint.
■ Direct-path INSERT is the default in parallel mode. In parallel mode, conventional
insert can be used only if you specify the NOAPPEND hint.
The decision whether the INSERT will go parallel or not is independent of the APPEND
hint.
In direct-path INSERT, data is appended to the end of the table, rather than using
existing space currently allocated to the table. As a result, direct-path INSERT can be
considerably faster than conventional INSERT.
The APPEND hint is only supported with the subquery syntax of the INSERT
statement, not the VALUES clause. If you specify the APPEND hint with the VALUES
clause, it is ignored and conventional insert will be used. To use direct-path INSERT
with the VALUES clause, refer to "APPEND_VALUES Hint" on page 3-78.
APPEND_VALUES Hint
The APPEND_VALUES hint instructs the optimizer to use direct-path INSERT with the
VALUES clause. If you do not specify this hint, then conventional INSERT is used.
In direct-path INSERT, data is appended to the end of the table, rather than using
existing space currently allocated to the table. As a result, direct-path INSERT can be
considerably faster than conventional INSERT.
See Also: "NOAPPEND Hint" on page 3-89 for information on
that hint and Oracle Database Administrator's Guide for information
on direct-path inserts
/*+ APPEND */
/*+ APPEND_VALUES */
Comments
Basic Elements of Oracle SQL 3-79
The APPEND_VALUES hint can be used to greatly enhance performance. Some
examples of its uses are:
■ In an Oracle Call Interface (OCI) program, when using large array binds or array
binds with row callbacks
■ In PL/SQL, when loading a large number of rows with a FORALL loop that has an
INSERT statement with a VALUES clause
The APPEND_VALUES hint is only supported with the VALUES clause of the INSERT
statement. If you specify the APPEND_VALUES hint with the subquery syntax of the
INSERT statement, it is ignored and conventional insert will be used. To use
direct-path INSERT with a subquery, refer to "APPEND Hint" on page 3-78.
CACHE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The CACHE hint instructs the optimizer to place the blocks retrieved for the table at the
most recently used end of the LRU list in the buffer cache when a full table scan is
performed. This hint is useful for small lookup tables.
In the following example, the CACHE hint overrides the default caching specification of
the table:
SELECT /*+ FULL (hr_emp) CACHE(hr_emp) */ last_name
FROM employees hr_emp;
The CACHE and NOCACHE hints affect system statistics table scans (long
tables) and table scans (short tables), as shown in the V$SYSSTAT data
dictionary view.
CHANGE_DUPKEY_ERROR_INDEX Hint
The CHANGE_DUPKEY_ERROR_INDEX hint provides a mechanism to unambiguously
identify a unique key violation for a specified set of columns or for a specified index.
When a unique key violation occurs for the specified index, an ORA-38911 error is
reported instead of an ORA-001.
This hint applies to INSERT, UPDATE operations. If you specify an index, then the
index must exist and be unique. If you specify a column list instead of an index, then a
See Also: Oracle Database Administrator's Guide for information on
direct-path inserts
Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_
DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other
hints in that they have a semantic effect. The general philosophy
explained in "Hints" on page 3-73 does not apply for these three hints.
/*+ CACHE (
@ queryblock
tablespec ) */
/*+ CHANGE_DUPKEY_ERROR_INDEX (
table , index
table ( column
,
)
) */
Comments
3-80 Oracle Database SQL Language Reference
unique index whose columns match the specified columns in number and order must
exist.
This use of this hint results in error messages if specific rules are violated. Refer to
IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83 for details.
CLUSTER Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The CLUSTER hint instructs the optimizer to use a cluster scan to access the specified
table. This hint applies only to tables in an index cluster.
CURSOR_SHARING_EXACT Hint
Oracle can replace literals in SQL statements with bind variables, when it is safe to do
so. This replacement is controlled with the CURSOR_SHARING initialization parameter.
The CURSOR_SHARING_EXACT hint instructs the optimizer to switch this behavior off.
When you specify this hint, Oracle executes the SQL statement without any attempt to
replace literals with bind variables.
DRIVING_SITE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The DRIVING_SITE hint instructs the optimizer to execute the query at a different site
than that selected by the database. This hint is useful if you are using distributed
query optimization.
For example:
SELECT /*+ DRIVING_SITE(departments) */ *
FROM employees, departments@rsite
WHERE employees.department_id = departments.department_id;
If this query is executed without the hint, then rows from departments are sent to
the local site, and the join is executed there. With the hint, the rows from employees
are sent to the remote site, and the query is executed there and the result set is
returned to the local site.
Note: This hint disables both APPEND mode and parallel DML.
See Also: IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83
for information on that hint and Oracle Database Performance Tuning
Guide for more information on using the online application upgrade
related hints
/*+ CLUSTER (
@ queryblock
tablespec ) */
/*+ CURSOR_SHARING_EXACT */
/*+ DRIVING_SITE (
@ queryblock
tablespec ) */
Comments
Basic Elements of Oracle SQL 3-81
DYNAMIC_SAMPLING Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The DYNAMIC_SAMPLING hint instructs the optimizer how to control dynamic
sampling to improve server performance by determining more accurate predicate
selectivity and statistics for tables and indexes.
You can set the value of DYNAMIC_SAMPLING to a value from 0 to 10. The higher the
level, the more effort the compiler puts into dynamic sampling and the more broadly it
is applied. Sampling defaults to cursor level unless you specify tablespec.
The integer value is 0 to 10, indicating the degree of sampling.
If a cardinality statistic already exists for the table, then the optimizer uses it.
Otherwise, the optimizer enables dynamic sampling to estimate the cardinality
statistic.
If you specify tablespec and the cardinality statistic already exists, then:
■ If there is no single-table predicate (a WHERE clause that evaluates only one table),
then the optimizer trusts the existing statistics and ignores this hint. For example,
the following query will not result in any dynamic sampling if employees is
analyzed:
SELECT /*+ dynamic_sampling(e 1) */ count(*)
FROM employees e;
■ If there is a single-table predicate, then the optimizer uses the existing cardinality
statistic and estimates the selectivity of the predicate using the existing statistics.
To apply dynamic sampling to a specific table, use the following form of the hint:
SELECT /*+ dynamic_sampling(employees 1) */ *
FROM employees
WHERE ...
FACT Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The FACT hint is used in the context of the star transformation. It instructs the
optimizer that the table specified in tablespec should be considered as a fact table.
FIRST_ROWS Hint
See Also: Oracle Database Performance Tuning Guide for
information about dynamic sampling and the sampling levels that
you can set
/*+ DYNAMIC_SAMPLING (
@ queryblock tablespec
integer ) */
/*+ FACT (
@ queryblock
tablespec ) */
/*+ FIRST_ROWS ( integer ) */
Comments
3-82 Oracle Database SQL Language Reference
The FIRST_ROWS hint instructs Oracle to optimize an individual SQL statement for
fast response, choosing the plan that returns the first n rows most efficiently. For
integer, specify the number of rows to return.
For example, the optimizer uses the query optimization approach to optimize the
following statement for best response time:
SELECT /*+ FIRST_ROWS(10) */ employee_id, last_name, salary, job_id
FROM employees
WHERE department_id = 20;
In this example each department contains many employees. The user wants the first 10
employees of department 20 to be displayed as quickly as possible.
The optimizer ignores this hint in DELETE and UPDATE statement blocks and in
SELECT statement blocks that include any blocking operations, such as sorts or
groupings. Such statements cannot be optimized for best response time, because
Oracle Database must retrieve all rows accessed by the statement before returning the
first row. If you specify this hint in any such statement, then the database optimizes for
best throughput.
FULL Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The FULL hint instructs the optimizer to perform a full table scan for the specified
table. For example:
SELECT /*+ FULL(e) */ employee_id, last_name
FROM hr.employees e
WHERE last_name LIKE :b1;
Oracle Database performs a full table scan on the employees table to execute this
statement, even if there is an index on the last_name column that is made available
by the condition in the WHERE clause.
The employees table has alias e in the FROM clause, so the hint must refer to the table
by its alias rather than by its name. Do not specify schema names in the hint even if
they are specified in the FROM clause.
HASH Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The HASH hint instructs the optimizer to use a hash scan to access the specified table.
This hint applies only to tables in a hash cluster.
See Also: "ALL_ROWS Hint" on page 3-77 for additional
information on the FIRST_ROWS hint and statistics
/*+ FULL (
@ queryblock
tablespec ) */
/*+ HASH (
@ queryblock
tablespec ) */
Comments
Basic Elements of Oracle SQL 3-83
IGNORE_ROW_ON_DUPKEY_INDEX Hint
The IGNORE_ROW_ON_DUPKEY_INDEX hint applies only to single-table INSERT
operations. It is not supported for UPDATE, DELETE, MERGE, or multitable insert
operations. IGNORE_ROW_ON_DUPKEY_INDEX causes the statement to ignore a
unique key violation for a specified set of columns or for a specified index. When a
unique key violation is encountered, a row-level rollback occurs and execution
resumes with the next input row. If you specify this hint when inserting data with
DML error logging enabled, then the unique key violation is not logged and does not
cause statement termination.
The semantic effect of this hint results in error messages if specific rules are violated:
■ If you specify index, then the index must exist and be unique. Otherwise, the
statement causes ORA-38913.
■ You must specify exactly one index. If you specify no index, then the statement
causes ORA-38912. If you specify more than one index, then the statement causes
ORA-38915.
■ You can specify either a CHANGE_DUPKEY_ERROR_INDEX or IGNORE_ROW_ON_
DUPKEY_INDEX hint in an INSERT statement, but not both. If you specify both,
then the statement causes ORA-38915.
As with all hints, a syntax error in the hint causes it to be silently ignored. The result
will be that ORA-00001 will be caused, just as if no hint were used.
INDEX Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_
DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other
hints in that they have a semantic effect. The general philosophy
explained in "Hints" on page 3-73 does not apply for these three hints.
Note: This hint disables both APPEND mode and parallel DML.
See Also: CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79
for information on that hint and Oracle Database Performance Tuning
Guide for more information on using the online application upgrade
related hints
/*+ IGNORE_ROW_ON_DUPKEY_INDEX (
table , index
table ( column
,
)
) */
/*+ INDEX (
@ queryblock
tablespec
indexspec
) */
Comments
3-84 Oracle Database SQL Language Reference
The INDEX hint instructs the optimizer to use an index scan for the specified table. You
can use the INDEX hint for function-based, domain, B-tree, bitmap, and bitmap join
indexes.
The behavior of the hint depends on the indexspec specification:
■ If the INDEX hint specifies a single available index, then the database performs a
scan on this index. The optimizer does not consider a full table scan or a scan of
another index on the table.
■ For a hint on a combination of multiple indexes, Oracle recommends using
INDEX_COMBINE rather than INDEX, because it is a more versatile hint. If the
INDEX hint specifies a list of available indexes, then the optimizer considers the
cost of a scan on each index in the list and then performs the index scan with the
lowest cost. The database can also choose to scan multiple indexes from this list
and merge the results, if such an access path has the lowest cost. The database
does not consider a full table scan or a scan on an index not listed in the hint.
■ If the INDEX hint specifies no indexes, then the optimizer considers the cost of a
scan on each available index on the table and then performs the index scan with
the lowest cost. The database can also choose to scan multiple indexes and merge
the results, if such an access path has the lowest cost. The optimizer does not
consider a full table scan.
For example:
SELECT /*+ INDEX (employees emp_department_ix)*/
employee_id, department_id
FROM employees
WHERE department_id > 50;
INDEX_ASC Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_ASC hint instructs the optimizer to use an index scan for the specified
table. If the statement uses an index range scan, then Oracle Database scans the index
entries in ascending order of their indexed values. Each parameter serves the same
purpose as in "INDEX Hint" on page 3-83.
The default behavior for a range scan is to scan index entries in ascending order of
their indexed values, or in descending order for a descending index. This hint does not
change the default order of the index, and therefore does not specify anything more
than the INDEX hint. However, you can use the INDEX_ASC hint to specify ascending
range scans explicitly should the default behavior change.
INDEX_COMBINE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
/*+ INDEX_ASC (
@ queryblock
tablespec
indexspec
) */
/*+ INDEX_COMBINE (
@ queryblock
tablespec
indexspec
) */
Comments
Basic Elements of Oracle SQL 3-85
The INDEX_COMBINE hint instructs the optimizer to use a bitmap access path for the
table. If indexspec is omitted from the INDEX_COMBINE hint, then the optimizer
uses whatever Boolean combination of indexes has the best cost estimate for the table.
If you specify indexspec, then the optimizer tries to use some Boolean combination
of the specified indexes. Each parameter serves the same purpose as in "INDEX Hint"
on page 3-83. For example:
SELECT /*+ INDEX_COMBINE(e emp_manager_ix emp_department_ix) */ *
FROM employees e
WHERE manager_id = 108
OR department_id = 110;
INDEX_DESC Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_DESC hint instructs the optimizer to use a descending index scan for the
specified table. If the statement uses an index range scan and the index is ascending,
then Oracle scans the index entries in descending order of their indexed values. In a
partitioned index, the results are in descending order within each partition. For a
descending index, this hint effectively cancels out the descending order, resulting in a
scan of the index entries in ascending order. Each parameter serves the same purpose
as in "INDEX Hint" on page 3-83. For example:
SELECT /*+ INDEX_DESC(e emp_name_ix) */ *
FROM employees e;
INDEX_FFS Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_FFS hint instructs the optimizer to perform a fast full index scan rather
than a full table scan.
Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For
example:
SELECT /*+ INDEX_FFS(e emp_name_ix) */ first_name
FROM employees e;
INDEX_JOIN Hint
See Also: Oracle Database Performance Tuning Guide for information
on full scans
/*+ INDEX_DESC (
@ queryblock
tablespec
indexspec
) */
/*+ INDEX_FFS (
@ queryblock
tablespec
indexspec
) */
/*+ INDEX_JOIN (
@ queryblock
tablespec
indexspec
) */
Comments
3-86 Oracle Database SQL Language Reference
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_JOIN hint instructs the optimizer to use an index join as an access path.
For the hint to have a positive effect, a sufficiently small number of indexes must exist
that contain all the columns required to resolve the query.
Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For
example, the following query uses an index join to access the manager_id and
department_id columns, both of which are indexed in the employees table.
SELECT /*+ INDEX_JOIN(e emp_manager_ix emp_department_ix) */ department_id
FROM employees e
WHERE manager_id < 110
AND department_id < 50;
INDEX_SS Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_SS hint instructs the optimizer to perform an index skip scan for the
specified table. If the statement uses an index range scan, then Oracle scans the index
entries in ascending order of their indexed values. In a partitioned index, the results
are in ascending order within each partition.
Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For
example:
SELECT /*+ INDEX_SS(e emp_name_ix) */ last_name
FROM employees e
WHERE first_name = 'Steven';
INDEX_SS_ASC Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_SS_ASC hint instructs the optimizer to perform an index skip scan for the
specified table. If the statement uses an index range scan, then Oracle Database scans
the index entries in ascending order of their indexed values. In a partitioned index, the
results are in ascending order within each partition. Each parameter serves the same
purpose as in "INDEX Hint" on page 3-83.
The default behavior for a range scan is to scan index entries in ascending order of
their indexed values, or in descending order for a descending index. This hint does not
change the default order of the index, and therefore does not specify anything more
than the INDEX_SS hint. However, you can use the INDEX_SS_ASC hint to specify
ascending range scans explicitly should the default behavior change.
See Also: Oracle Database Performance Tuning Guide for information
on index skip scans
/*+ INDEX_SS (
@ queryblock
tablespec
indexspec
) */
/*+ INDEX_SS_ASC (
@ queryblock
tablespec
indexspec
) */
Comments
Basic Elements of Oracle SQL 3-87
INDEX_SS_DESC Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The INDEX_SS_DESC hint instructs the optimizer to perform an index skip scan for
the specified table. If the statement uses an index range scan and the index is
ascending, then Oracle scans the index entries in descending order of their indexed
values. In a partitioned index, the results are in descending order within each
partition. For a descending index, this hint effectively cancels out the descending
order, resulting in a scan of the index entries in ascending order.
Each parameter serves the same purpose as in the "INDEX Hint" on page 3-83. For
example:
SELECT /*+ INDEX_SS_DESC(e emp_name_ix) */ last_name
FROM employees e
WHERE first_name = 'Steven';
LEADING Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The LEADING hint instructs the optimizer to use the specified set of tables as the prefix
in the execution plan. This hint is more versatile than the ORDERED hint. For example:
SELECT /*+ LEADING(e j) */ *
FROM employees e, departments d, job_history j
WHERE e.department_id = d.department_id
AND e.hire_date = j.start_date;
The LEADING hint is ignored if the tables specified cannot be joined first in the order
specified because of dependencies in the join graph. If you specify two or more
conflicting LEADING hints, then all of them are ignored. If you specify the ORDERED
hint, it overrides all LEADING hints.
MERGE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
See Also: Oracle Database Performance Tuning Guide for information
on index skip scans
See Also: Oracle Database Performance Tuning Guide for information
on index skip scans
/*+ INDEX_SS_DESC (
@ queryblock
tablespec
indexspec
) */
/*+ LEADING (
@ queryblock
tablespec ) */
/*+ MERGE
(
@ queryblock
@ queryblock
tablespec
)
*/
Comments
3-88 Oracle Database SQL Language Reference
The MERGE hint lets you merge views in a query.
If a view's query block contains a GROUP BY clause or DISTINCT operator in the
SELECT list, then the optimizer can merge the view into the accessing statement only if
complex view merging is enabled. Complex merging can also be used to merge an IN
subquery into the accessing statement if the subquery is uncorrelated.
For example:
SELECT /*+ MERGE(v) */ e1.last_name, e1.salary, v.avg_salary
FROM employees e1,
(SELECT department_id, avg(salary) avg_salary
FROM employees e2
GROUP BY department_id) v
WHERE e1.department_id = v.department_id AND e1.salary > v.avg_salary;
When the MERGE hint is used without an argument, it should be placed in the view
query block. When MERGE is used with the view name as an argument, it should be
placed in the surrounding query.
MODEL_MIN_ANALYSIS Hint
The MODEL_MIN_ANALYSIS hint instructs the optimizer to omit some compile-time
optimizations of spreadsheet rules—primarily detailed dependency graph analysis.
Other spreadsheet optimizations, such as creating filters to selectively populate
spreadsheet access structures and limited rule pruning, are still used by the optimizer.
This hint reduces compilation time because spreadsheet analysis can be lengthy if the
number of spreadsheet rules is more than several hundreds.
MONITOR Hint
The MONITOR hint forces real-time SQL monitoring for the query, even if the statement
is not long running. This hint is valid only when the parameter CONTROL_
MANAGEMENT_PACK_ACCESS is set to DIAGNOSTIC+TUNING.
NATIVE_FULL_OUTER_JOIN Hint
The NATIVE_FULL_OUTER_JOIN hint instructs the optimizer to use native full outer
join, which is a native execution method based on a hash join.
See Also: Oracle Database Performance Tuning Guide for more
information about real-time SQL monitoring
See Also:
■ NO_NATIVE_FULL_OUTER_JOIN Hint on page 3-91
■ Oracle Database Performance Tuning Guide for more information
about native full outer joins
/*+ MODEL_MIN_ANALYSIS */
/*+ MONITOR */
/*+ NATIVE_FULL_OUTER_JOIN */
Comments
Basic Elements of Oracle SQL 3-89
NOAPPEND Hint
The NOAPPEND hint instructs the optimizer to use conventional INSERT by disabling
parallel mode for the duration of the INSERT statement. Conventional INSERT is the
default in serial mode, and direct-path INSERT is the default in parallel mode.
NOCACHE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NOCACHE hint instructs the optimizer to place the blocks retrieved for the table at
the least recently used end of the LRU list in the buffer cache when a full table scan is
performed. This is the normal behavior of blocks in the buffer cache. For example:
SELECT /*+ FULL(hr_emp) NOCACHE(hr_emp) */ last_name
FROM employees hr_emp;
The CACHE and NOCACHE hints affect system statistics table scans(long tables)
and table scans(short tables), as shown in the V$SYSSTAT view.
NO_EXPAND Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The NO_EXPAND hint instructs the optimizer not to consider OR-expansion for queries
having OR conditions or IN-lists in the WHERE clause. Usually, the optimizer considers
using OR expansion and uses this method if it decides that the cost is lower than not
using it. For example:
SELECT /*+ NO_EXPAND */ *
FROM employees e, departments d
WHERE e.manager_id = 108
OR d.department_id = 110;
NO_FACT Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_FACT hint is used in the context of the star transformation. It instruct the
optimizer that the queried table should not be considered as a fact table.
See Also: Oracle Database Performance Tuning Guide for information
on automatic caching of tables, depending on their size
See Also: The "USE_CONCAT Hint" on page 3-104, which is the
opposite of this hint
/*+ NOAPPEND */
/*+ NOCACHE (
@ queryblock
tablespec ) */
/*+ NO_EXPAND
( @ queryblock )
*/
/*+ NO_FACT (
@ queryblock
tablespec ) */
Comments
3-90 Oracle Database SQL Language Reference
NO_INDEX Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The NO_INDEX hint instructs the optimizer not to use one or more indexes for the
specified table. For example:
SELECT /*+ NO_INDEX(employees emp_empid) */ employee_id
FROM employees
WHERE employee_id > 200;
Each parameter serves the same purpose as in "INDEX Hint" on page 3-83 with the
following modifications:
■ If this hint specifies a single available index, then the optimizer does not consider a
scan on this index. Other indexes not specified are still considered.
■ If this hint specifies a list of available indexes, then the optimizer does not consider
a scan on any of the specified indexes. Other indexes not specified in the list are
still considered.
■ If this hint specifies no indexes, then the optimizer does not consider a scan on any
index on the table. This behavior is the same as a NO_INDEX hint that specifies a
list of all available indexes for the table.
The NO_INDEX hint applies to function-based, B-tree, bitmap, cluster, or domain
indexes. If a NO_INDEX hint and an index hint (INDEX, INDEX_ASC, INDEX_DESC,
INDEX_COMBINE, or INDEX_FFS) both specify the same indexes, then the database
ignores both the NO_INDEX hint and the index hint for the specified indexes and
considers those indexes for use during execution of the statement.
NO_INDEX_FFS Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The NO_INDEX_FFS hint instructs the optimizer to exclude a fast full index scan of the
specified indexes on the specified table. Each parameter serves the same purpose as in
the "INDEX Hint" on page 3-83. For example:
SELECT /*+ NO_INDEX_FFS(items item_order_ix) */ order_id
FROM order_items items;
NO_INDEX_SS Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
/*+ NO_INDEX (
@ queryblock
tablespec
indexspec
) */
/*+ NO_INDEX_FFS (
@ queryblock
tablespec
indexspec
) */
/*+ NO_INDEX_SS (
@ queryblock
tablespec
indexspec
) */
Comments
Basic Elements of Oracle SQL 3-91
The NO_INDEX_SS hint instructs the optimizer to exclude a skip scan of the specified
indexes on the specified table. Each parameter serves the same purpose as in the
"INDEX Hint" on page 3-83.
NO_MERGE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_MERGE hint instructs the optimizer not to combine the outer query and any
inline view queries into a single query.
This hint lets you have more influence over the way in which the view is accessed. For
example, the following statement causes view seattle_dept not to be merged:
SELECT /*+NO_MERGE(seattle_dept)*/ e1.last_name, seattle_dept.department_name
FROM employees e1,
(SELECT location_id, department_id, department_name
FROM departments
WHERE location_id = 1700) seattle_dept
WHERE e1.department_id = seattle_dept.department_id;
When you use the NO_MERGE hint in the view query block, specify it without an
argument. When you specify NO_MERGE in the surrounding query, specify it with the
view name as an argument.
NO_MONITOR Hint
The NO_MONITOR hint disables real-time SQL monitoring for the query, even if the
query is long running.
NO_NATIVE_FULL_OUTER_JOIN Hint
The NO_NATIVE_FULL_OUTER_JOIN hint instructs the optimizer to exclude the
native execution method when joining each specified table. Instead, the full outer join
is executed as a union of left outer join and anti-join.
NO_PARALLEL Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
See Also: Oracle Database Performance Tuning Guide for information
on index skip scans
See Also: NATIVE_FULL_OUTER_JOIN Hint on page 3-88
/*+ NO_MERGE
(
@ queryblock
@ queryblock
tablespec
)
*/
/*+ NO_MONITOR */
/*+ NO_NATIVE_FULL_OUTER_JOIN */
/*+ NO_PARALLEL (
@ queryblock
tablespec ) */
Comments
3-92 Oracle Database SQL Language Reference
The NO_PARALLEL hint overrides a PARALLEL parameter in the DDL that created or
altered the table. For example:
ALTER TABLE employees PARALLEL 8;
SELECT /*+ NO_PARALLEL(hr_emp) */ last_name
FROM employees hr_emp;
NOPARALLEL Hint
The NOPARALLEL hint has been deprecated. Use the NO_PARALLEL hint instead.
NO_PARALLEL_INDEX Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The NO_PARALLEL_INDEX hint overrides a PARALLEL parameter in the DDL that
created or altered the index, thus avoiding a parallel index scan operation.
NOPARALLEL_INDEX Hint
The NOPARALLEL_INDEX hint has been deprecated. Use the NO_PARALLEL_INDEX
hint instead.
NO_PUSH_PRED Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_PUSH_PRED hint instructs the optimizer not to push a join predicate into the
view. For example:
SELECT /*+ NO_MERGE(v) NO_PUSH_PRED(v) */ *
FROM employees e,
(SELECT manager_id
FROM employees
) v
WHERE e.manager_id = v.manager_id(+)
AND e.employee_id = 100;
See Also: "Note on Parallel Hints" on page 3-96 for more
information on the parallel hints
See Also: "Note on Parallel Hints" on page 3-96 for more
information on the parallel hints
/*+ NO_PARALLEL_INDEX (
@ queryblock
tablespec
indexspec
) */
/*+ NO_PUSH_PRED
(
@ queryblock
@ queryblock
tablespec
)
*/
Comments
Basic Elements of Oracle SQL 3-93
NO_PUSH_SUBQ Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The NO_PUSH_SUBQ hint instructs the optimizer to evaluate nonmerged subqueries as
the last step in the execution plan. Doing so can improve performance if the subquery
is relatively expensive or does not reduce the number of rows significantly.
NO_PX_JOIN_FILTER Hint
This hint prevents the optimizer from using parallel join bitmap filtering.
NO_QUERY_TRANSFORMATION Hint
The NO_QUERY_TRANSFORMATION hint instructs the optimizer to skip all query
transformations, including but not limited to OR-expansion, view merging, subquery
unnesting, star transformation, and materialized view rewrite. For example:
SELECT /*+ NO_QUERY_TRANSFORMATION */ employee_id, last_name
FROM (SELECT *
FROM employees e) v
WHERE v.last_name = 'Smith';
NO_RESULT_CACHE Hint
The optimizer caches query results in the result cache if the RESULT_CACHE_MODE
initialization parameter is set to FORCE. In this case, the NO_RESULT_CACHE hint
disables such caching for the current query.
If the query is executed from OCI client and OCI client result cache is enabled, then the
NO_RESULT_CACHE hint disables caching for the current query.
NO_REWRITE Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The NO_REWRITE hint instructs the optimizer to disable query rewrite for the query
block, overriding the setting of the parameter QUERY_REWRITE_ENABLED. For
example:
SELECT /*+ NO_REWRITE */ sum(s.amount_sold) AS dollars
FROM sales s, times t
WHERE s.time_id = t.time_id
GROUP BY t.calendar_month_desc;
/*+ NO_PUSH_SUBQ
( @ queryblock )
*/
/*+ NO_PX_JOIN_FILTER ( tablespec ) */
/*+ NO_QUERY_TRANSFORMATION */
/*+ NO_RESULT_CACHE */
/*+ NO_REWRITE
( @ queryblock )
*/
Comments
3-94 Oracle Database SQL Language Reference
NOREWRITE Hint
The NOREWRITE hint has been deprecated. Use the NO_REWRITE hint instead.
NO_STAR_TRANSFORMATION Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The NO_STAR_TRANSFORMATION hint instructs the optimizer not to perform star
query transformation.
NO_UNNEST Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
Use of the NO_UNNEST hint turns off unnesting .
NO_USE_HASH Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_USE_HASH hint instructs the optimizer to exclude hash joins when joining
each specified table to another row source using the specified table as the inner table.
For example:
SELECT /*+ NO_USE_HASH(e d) */ *
FROM employees e, departments d
WHERE e.department_id = d.department_id;
NO_USE_MERGE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_USE_MERGE hint instructs the optimizer to exclude sort-merge joins when
joining each specified table to another row source using the specified table as the inner
table. For example:
SELECT /*+ NO_USE_MERGE(e d) */ *
FROM employees e, departments d
WHERE e.department_id = d.department_id
ORDER BY d.department_id;
/*+ NO_STAR_TRANSFORMATION
( @ queryblock )
*/
/*+ NO_UNNEST
( @ queryblock )
*/
/*+ NO_USE_HASH (
@ queryblock
tablespec ) */
/*+ NO_USE_MERGE (
@ queryblock
tablespec ) */
Comments
Basic Elements of Oracle SQL 3-95
NO_USE_NL Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The NO_USE_NL hint instructs the optimizer to exclude nested loops joins when
joining each specified table to another row source using the specified table as the inner
table. For example:
SELECT /*+ NO_USE_NL(l h) */ *
FROM orders h, order_items l
WHERE l.order_id = h.order_id
AND l.order_id > 3500;
When this hint is specified, only hash join and sort-merge joins are considered for the
specified tables. However, in some cases tables can be joined only by using nested
loops. In such cases, the optimizer ignores the hint for those tables.
NO_XML_QUERY_REWRITE Hint
The NO_XML_QUERY_REWRITE hint instructs the optimizer to prohibit the rewriting of
XPath expressions in SQL statements. By prohibiting the rewriting of XPath
expressions, this hint also prohibits the use of any XMLIndexes for the current query.
For example:
SELECT /*+NO_XML_QUERY_REWRITE*/ XMLQUERY('<A/>')
FROM dual;
NO_XMLINDEX_REWRITE Hint
The NO_XMLINDEX_REWRITE hint instructs the optimizer not to use any XMLIndex
indexes for the current query. For example:
SELECT /*+NO_XMLINDEX_REWRITE*/ count(*)
FROM table WHERE existsNode(OBJECT_VALUE, '/*') = 1;
OPT_PARAM Hint
The OPT_PARAM hint lets you set an initialization parameter for the duration of the
current query only. This hint is valid only for the following parameters: OPTIMIZER_
DYNAMIC_SAMPLING, OPTIMIZER_INDEX_CACHING, OPTIMIZER_INDEX_COST_
ADJ, OPTIMIZER_SECURE_VIEW_MERGING, and STAR_TRANSFORMATION_
See Also: "NO_XMLINDEX_REWRITE Hint" on page 3-95
See Also: "NO_XML_QUERY_REWRITE Hint" on page 3-95 for
another way to disable the use of XMLIndexes
/*+ NO_USE_NL (
@ queryblock
tablespec ) */
/*+ NO_XML_QUERY_REWRITE */
/*+ NO_XMLINDEX_REWRITE */
/*+ OPT_PARAM ( parameter_name
,
parameter_value ) */
Comments
3-96 Oracle Database SQL Language Reference
ENABLED. For example, the following hint sets the parameter STAR_
TRANSFORMATION_ENABLED to TRUE for the statement to which it is added:
SELECT /*+ OPT_PARAM('star_transformation_enabled' 'true') */ * FROM ... ;
Parameter values that are strings are enclosed in single quotation marks. Numeric
parameter values are specified without quotation marks.
ORDERED Hint
The ORDERED hint instructs Oracle to join tables in the order in which they appear in
the FROM clause. Oracle recommends that you use the LEADING hint, which is more
versatile than the ORDERED hint.
When you omit the ORDERED hint from a SQL statement requiring a join, the optimizer
chooses the order in which to join the tables. You might want to use the ORDERED hint
to specify a join order if you know something that the optimizer does not know about
the number of rows selected from each table. Such information lets you choose an
inner and outer table better than the optimizer could.
The following query is an example of the use of the ORDERED hint:
SELECT /*+ORDERED */ o.order_id, c.customer_id, l.unit_price * l.quantity
FROM customers c, order_items l, orders o
WHERE c.cust_last_name = :b1
AND o.customer_id = c.customer_id
AND o.order_id = l.order_id;
PARALLEL Hint
Note on Parallel Hints Beginning with Oracle Database 11g Release 2, the PARALLEL
and NO_PARALLEL hints are statement-level hints and supersede the earlier
object-level hints: PARALLEL_INDEX, NO_PARALLEL_INDEX, and previously
specified PARALLEL and NO_PARALLEL hints. For PARALLEL, if you specify
integer, then that degree of parallelism will be used for the statement. If you omit
integer, then the database computes the degree of parallelism. All the access paths
that can use parallelism will use the specified or computed degree of parallelism.
In the syntax diagrams below, parallel_hint_statement shows the syntax for
statement-level hints, and parallel_hint_object shows the syntax for object-level
hints. Object-level hints are supported for backward compatibility, and are superseded
by statement-level hints.
parallel_hint_statement::=
/*+ ORDERED */
/*+ PARALLEL
(
DEFAULT
AUTO
MANUAL
integer
)
*/
Comments
Basic Elements of Oracle SQL 3-97
parallel_hint_object::=
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The PARALLEL hint instructs the optimizer to use the specified number of concurrent
servers for a parallel operation. The hint applies to the SELECT, INSERT, MERGE,
UPDATE, and DELETE portions of a statement, as well as to the table scan portion. If
any parallel restrictions are violated, then the hint is ignored.
For a statement-level PARALLEL hint:
■ PARALLEL: The statement always is run parallel, and the database computes the
degree of parallelism, which can be 2 or greater.
■ PARALLEL DEFAULT: The same as PARALLEL. The DEFAULT keyword is included
for completeness.
■ PARALLEL AUTO: The database computes the degree of parallelism, which can be 1
or greater. If the computed degree of parallelism is 1, then the statement runs
serially.
■ PARALLEL MANUAL: The optimizer is forced to use the parallel settings of the
objects in the statement.
■ PARALLEL (integer): The optimizer uses the degree of parallelism specified by
integer.
In the following example, the optimizer calculates the degree of parallelism. The
statement always runs in parallel.
SELECT /*+ PARALLEL */ last_name FROM employees;
In the following example, the optimizer calculates the degree of parallelism, but that
degree may be 1, in which case the statement will run serially.
SELECT /*+ PARALLEL (AUTO) */ last_name from employees;
In the following example, the PARALLEL hint advises the optimizer to use the degree
of parallelization currently in effect for the table itself, which is 5:
CREATE TABLE parallel_table (col1 number, col2 VARCHAR2(10)) PARALLEL 5;
SELECT /*+ PARALLEL (MANUAL) */ col2 FROM parallel_table;
For an object-level PARALLEL hint, the integer value specifies the degree of
parallelism for the specified table. Specifying DEFAULT or no value signifies that the
query coordinator should examine the settings of the initialization parameters to
determine the default degree of parallelism. In the following example, the PARALLEL
hint overrides the degree of parallelism specified in the employees table definition:
SELECT /*+ FULL(hr_emp) PARALLEL(hr_emp, 5) */ last_name
FROM employees hr_emp;
Note: The number of servers that can be used is twice the value in
the PARALLEL hint, if sorting or grouping operations also take
place.
/*+ PARALLEL (
@ queryblock
tablespec
integer
DEFAULT
) */
Comments
3-98 Oracle Database SQL Language Reference
In the next example, the PARALLEL hint overrides the degree of parallelism specified
in the employees table definition and instructs the optimizer to use the default
degree of parallelism determined by the initialization parameters.
SELECT /*+ FULL(hr_emp) PARALLEL(hr_emp, DEFAULT) */ last_name
FROM employees hr_emp;
Oracle ignores parallel hints on temporary tables. Refer to CREATE TABLE on
page 16-6 and Oracle Database Concepts for more information on parallel execution.
PARALLEL_INDEX Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The PARALLEL_INDEX hint instructs the optimizer to use the specified number of
concurrent servers to parallelize index range scans, full scans, and fast full scans for
partitioned indexes.
The integer value indicates the degree of parallelism for the specified index.
Specifying DEFAULT or no value signifies that the query coordinator should examine
the settings of the initialization parameters to determine the default degree of
parallelism. For example, the following hint indicates three parallel execution
processes are to be used:
SELECT /*+ PARALLEL_INDEX(table1, index1, 3) */
PQ_DISTRIBUTE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
See Also:
■ CREATE TABLE on page 16-6 and Oracle Database Concepts for
more information on parallel execution.
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_PARALLEL_EXECUTE package, which
provides methods to apply table changes in chunks of rows.
Changes to each chunk are independently committed when there
are no errors.
See Also: "Note on Parallel Hints" on page 3-96 for more
information on the parallel hints
/*+ PARALLEL_INDEX (
@ queryblock
tablespec
indexspec
integer
DEFAULT
) */
/*+ PQ_DISTRIBUTE (
@ queryblock
tablespec
distribution
outer_distribution inner_distribution
) */
Comments
Basic Elements of Oracle SQL 3-99
The PQ_DISTRIBUTE hint instructs the optimizer how to distribute rows among
producer and consumer query servers. You can control the distribution of rows for
either joins or for load.
Control of Distribution for Load You can control the distribution of rows for parallel
INSERT ... SELECT and parallel CREATE TABLE ... AS SELECT statements to direct
how rows should be distributed between the producer (query) and the consumer
(load) servers. Use the upper branch of the syntax by specifying a single distribution
method. The values of the distribution methods and their semantics are described in
Table 3–22 on page 3-99.
For example, in the following direct-load insert operation, the query and load portions
of the operation are combined into each query server:
INSERT /*+ APPEND PARALLEL(target_table, 16) PQ_DISTRIBUTE(target_table, NONE) */
INTO target_table
SELECT * FROM source_table;
In the following table creation example, the optimizer uses the partitioning of target_
table to distribute the rows:
CREATE /*+ PQ_DISTRIBUTE(target_table, PARTITION) */ TABLE target_table
NOLOGGING PARALLEL 16
PARTITION BY HASH (l_orderkey) PARTITIONS 512
AS SELECT * FROM source_table;
Table 3–22 Distribution Values for Load
Distribution Description
NONE No distribution. That is the query and load operation are
combined into each query server. All servers will load all
partitions. This lack of distribution is useful to avoid the
overhead of distributing rows where there is no skew. Skew can
occur due to empty segments or to a predicate in the statement
that filters out all rows evaluated by the query. If skew occurs
due to using this method, then use either RANDOM or RANDOM_
LOCAL distribution instead.
Note: Use this distribution with care. Each partition loaded
requires a minimum of 512 KB per process of PGA memory. If
you also use compression, then approximately 1.5 MB of PGA
memory is consumer per server.
PARTITION This method uses the partitioning information of tablespec) to
distribute the rows from the query servers to the load servers.
Use this distribution method when it is not possible or desirable
to combine the query and load operations, when the number of
partitions being loaded is greater than or equal to the number of
load servers, and the input data will be evenly distributed across
the partitions being loaded—that is, there is no skew.
RANDOM This method distributes the rows from the producers in a
round-robin fashion to the consumers. Use this distribution
method when the input data is highly skewed.
RANDOM_LOCAL This method distributes the rows from the producers to a set of
servers that are responsible for maintaining a given set of
partitions. Two or more servers can be loading the same
partition, but no servers are loading all partitions. Use this
distribution method when the input data is skewed and
combining query and load operations is not possible due to
memory constraints.
Comments
3-100 Oracle Database SQL Language Reference
Control of Distribution for Joins You control the distribution method for joins by
specifying two distribution methods, as shown in the lower branch of the syntax
diagram, one distribution for the outer table and one distribution for the inner table.
■ outer_distribution is the distribution for the outer table.
■ inner_distribution is the distribution for the inner table.
The values of the distributions are HASH, BROADCAST, PARTITION, and NONE. Only
six combinations table distributions are valid, as described in Table 3–23:
For example, given two tables r and s that are joined using a hash join, the following
query contains a hint to use hash distribution:
SELECT /*+ORDERED PQ_DISTRIBUTE(s HASH, HASH) USE_HASH (s)*/ column_list
FROM r,s
WHERE r.c=s.c;
To broadcast the outer table r, the query is:
Table 3–23 Distribution Values for Joins
Distribution Description
HASH, HASH The rows of each table are mapped to consumer query servers,
using a hash function on the join keys. When mapping is
complete, each query server performs the join between a pair of
resulting partitions. This distribution is recommended when the
tables are comparable in size and the join operation is
implemented by hash-join or sort merge join.
BROADCAST, NONE All rows of the outer table are broadcast to each query server.
The inner table rows are randomly partitioned. This distribution
is recommended when the outer table is very small compared
with the inner table. As a general rule, use this distribution
when the inner table size multiplied by the number of query
servers is greater than the outer table size.
NONE, BROADCAST All rows of the inner table are broadcast to each consumer query
server. The outer table rows are randomly partitioned. This
distribution is recommended when the inner table is very small
compared with the outer table. As a general rule, use this
distribution when the inner table size multiplied by the number
of query servers is less than the outer table size.
PARTITION, NONE The rows of the outer table are mapped using the partitioning of
the inner table. The inner table must be partitioned on the join
keys. This distribution is recommended when the number of
partitions of the outer table is equal to or nearly equal to a
multiple of the number of query servers; for example, 14
partitions and 15 query servers.
Note: The optimizer ignores this hint if the inner table is not
partitioned or not equijoined on the partitioning key.
NONE, PARTITION The rows of the inner table are mapped using the partitioning of
the outer table. The outer table must be partitioned on the join
keys. This distribution is recommended when the number of
partitions of the outer table is equal to or nearly equal to a
multiple of the number of query servers; for example, 14
partitions and 15 query servers.
Note: The optimizer ignores this hint if the outer table is not
partitioned or not equijoined on the partitioning key.
NONE, NONE Each query server performs the join operation between a pair of
matching partitions, one from each table. Both tables must be
equipartitioned on the join keys.
Comments
Basic Elements of Oracle SQL 3-101
SELECT /*+ORDERED PQ_DISTRIBUTE(s BROADCAST, NONE) USE_HASH (s) */ column_list
FROM r,s
WHERE r.c=s.c;
PUSH_PRED Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The PUSH_PRED hint instructs the optimizer to push a join predicate into the view. For
example:
SELECT /*+ NO_MERGE(v) PUSH_PRED(v) */ *
FROM employees e,
(SELECT manager_id
FROM employees
) v
WHERE e.manager_id = v.manager_id(+)
AND e.employee_id = 100;
PUSH_SUBQ Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The PUSH_SUBQ hint instructs the optimizer to evaluate nonmerged subqueries at the
earliest possible step in the execution plan. Generally, subqueries that are not merged
are executed as the last step in the execution plan. If the subquery is relatively
inexpensive and reduces the number of rows significantly, then evaluating the
subquery earlier can improve performance.
This hint has no effect if the subquery is applied to a remote table or one that is joined
using a merge join.
PX_JOIN_FILTER Hint
This hint forces the optimizer to use parallel join bitmap filtering.
QB_NAME Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
See Also: Oracle Database Concepts for more information on how
Oracle parallelizes join operations
/*+ PUSH_PRED
(
@ queryblock
@ queryblock
tablespec
)
*/
/*+ PUSH_SUBQ
( @ queryblock )
*/
/*+ PX_JOIN_FILTER ( tablespec ) */
/*+ QB_NAME ( queryblock ) */
Comments
3-102 Oracle Database SQL Language Reference
Use the QB_NAME hint to define a name for a query block. This name can then be used
in a hint in the outer query or even in a hint in an inline view to affect query execution
on the tables appearing in the named query block.
If two or more query blocks have the same name, or if the same query block is hinted
twice with different names, then the optimizer ignores all the names and the hints
referencing that query block. Query blocks that are not named using this hint have
unique system-generated names. These names can be displayed in the plan table and
can also be used in hints within the query block, or in query block hints. For example:
SELECT /*+ QB_NAME(qb) FULL(@qb e) */ employee_id, last_name
FROM employees e
WHERE last_name = 'Smith';
RESULT_CACHE Hint
The RESULT_CACHE hint instructs the database to cache the results of the current
query or query fragment in memory and then to use the cached results in future
executions of the query or query fragment. The hint is recognized in the top-level
query, the subquery_factoring_clause, or FROM clause inline view. The cached
results reside in the result cache memory portion of the shared pool.
A cached result is automatically invalidated whenever a database object used in its
creation is successfully modified. This hint takes precedence over settings of the
RESULT_CACHE_MODE initialization parameter.
The query is eligible for result caching only if all functions entailed in the query—for
example, built-in or user-defined functions or virtual columns—are deterministic.
If the query is executed from OCI client and OCI client result cache is enabled, then
RESULT_CACHE hint enables client caching for the current query.
RETRY_ON_ROW_CHANGE Hint
This hint is valid only for UPDATE and DELETE operations. It is not supported for
INSERT or MERGE operations. When you specify this hint, the operation is retried
when the ORA_ROWSCN for one or more rows in the set has changed from the time the
set of rows to be modified is determined to the time the block is actually modified.
See Also: Oracle Database Performance Tuning Guide for information
about using this hint, Oracle Database Reference for information about
the RESULT_CACHE_MODE initialization parameter, and Oracle Call
Interface Programmer's Guide for more information about the OCI result
cache and usage guidelines
Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_
DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other
hints in that they have a semantic effect. The general philosophy
explained in "Hints" on page 3-73 does not apply for these three hints.
/*+ RESULT_CACHE */
/*+ RETRY_ON_ROW_CHANGE */
Comments
Basic Elements of Oracle SQL 3-103
REWRITE Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The REWRITE hint instructs the optimizer to rewrite a query in terms of materialized
views, when possible, without cost consideration. Use the REWRITE hint with or
without a view list. If you use REWRITE with a view list and the list contains an
eligible materialized view, then Oracle uses that view regardless of its cost.
Oracle does not consider views outside of the list. If you do not specify a view list,
then Oracle searches for an eligible materialized view and always uses it regardless of
the cost of the final plan.
STAR_TRANSFORMATION Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The STAR_TRANSFORMATION hint instructs the optimizer to use the best plan in
which the transformation has been used. Without the hint, the optimizer could make a
query optimization decision to use the best plan generated without the transformation,
instead of the best plan for the transformed query. For example:
SELECT /*+ STAR_TRANSFORMATION */ s.time_id, s.prod_id, s.channel_id
FROM sales s, times t, products p, channels c
WHERE s.time_id = t.time_id
AND s.prod_id = p.prod_id
AND s.channel_id = c.channel_id
AND c.channel_desc = 'Direct Sales';
Even if the hint is specified, there is no guarantee that the transformation will take
place. The optimizer generates the subqueries only if it seems reasonable to do so. If no
subqueries are generated, then there is no transformed query, and the best plan for the
untransformed query is used, regardless of the hint.
See Also: IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83
and CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79 for
information on those hints and Oracle Database Performance Tuning
Guide for more information on using the online application upgrade
related hints
See Also:
■ Oracle Database Concepts and Oracle Database Advanced
Replication for more information on materialized views
■ Oracle Database Data Warehousing Guide for more information on
using REWRITE with materialized views
/*+ REWRITE
(
@ queryblock
view )
*/
/*+ STAR_TRANSFORMATION
( @ queryblock )
*/
Comments
3-104 Oracle Database SQL Language Reference
UNNEST Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The UNNEST hint instructs the optimizer to unnest and merge the body of the
subquery into the body of the query block that contains it, allowing the optimizer to
consider them together when evaluating access paths and joins.
Before a subquery is unnested, the optimizer first verifies whether the statement is
valid. The statement must then must pass heuristic and query optimization tests. The
UNNEST hint instructs the optimizer to check the subquery block for validity only. If
the subquery block is valid, then subquery unnesting is enabled without checking the
heuristics or costs.
USE_CONCAT Hint
(See "Specifying a Query Block in a Hint" on page 3-75)
The USE_CONCAT hint instructs the optimizer to transform combined OR-conditions in
the WHERE clause of a query into a compound query using the UNION ALL set operator.
Without this hint, this transformation occurs only if the cost of the query using the
concatenations is cheaper than the cost without them. The USE_CONCAT hint overrides
the cost consideration. For example:
SELECT /*+ USE_CONCAT */ *
FROM employees e
WHERE manager_id = 108
OR department_id = 110;
USE_HASH Hint
See Also:
■ Oracle Database Data Warehousing Guide for a full discussion of
star transformation.
■ Oracle Database Reference for more information on the STAR_
TRANSFORMATION_ENABLED initialization parameter.
See Also:
■ "Collection Unnesting: Examples" on page 19-54 for more
information on unnesting nested subqueries and the conditions
that make a subquery block valid
■ Oracle Database Performance Tuning Guide for additional
information on subquery unnesting
See Also: The "NO_EXPAND Hint" on page 3-89, which is the
opposite of this hint
/*+ UNNEST
( @ queryblock )
*/
/*+ USE_CONCAT
( @ queryblock )
*/
/*+ USE_HASH (
@ queryblock
tablespec ) */
Comments
Basic Elements of Oracle SQL 3-105
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The USE_HASH hint instructs the optimizer to join each specified table with another
row source using a hash join. For example:
SELECT /*+ USE_HASH(l h) */ *
FROM orders h, order_items l
WHERE l.order_id = h.order_id
AND l.order_id > 3500;
USE_MERGE Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The USE_MERGE hint instructs the optimizer to join each specified table with another
row source using a sort-merge join. For example:
SELECT /*+ USE_MERGE(employees departments) */ *
FROM employees, departments
WHERE employees.department_id = departments.department_id;
Use of the USE_NL and USE_MERGE hints is recommended with the LEADING and
ORDERED hints. The optimizer uses those hints when the referenced table is forced to
be the inner table of a join. The hints are ignored if the referenced table is the outer
table.
USE_NL Hint
The USE_NL hint instructs the optimizer to join each specified table to another row
source with a nested loops join, using the specified table as the inner table.
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74)
The USE_NL hint instructs the optimizer to join each specified table to another row
source with a nested loops join, using the specified table as the inner table.
Use of the USE_NL and USE_MERGE hints is recommended with the LEADING and
ORDERED hints. The optimizer uses those hints when the referenced table is forced to
be the inner table of a join. The hints are ignored if the referenced table is the outer
table.
In the following example, where a nested loop is forced through a hint, orders is
accessed through a full table scan and the filter condition l.order_id = h.order_
id is applied to every row. For every row that meets the filter condition, order_
items is accessed through the index order_id.
SELECT /*+ USE_NL(l h) */ h.customer_id, l.unit_price * l.quantity
FROM orders h ,order_items l
WHERE l.order_id = h.order_id;
Adding an INDEX hint to the query could avoid the full table scan on orders,
resulting in an execution plan similar to one used on larger systems, even though it
might not be particularly efficient here.
/*+ USE_MERGE (
@ queryblock
tablespec ) */
/*+ USE_NL (
@ queryblock
tablespec ) */
Database Objects
3-106 Oracle Database SQL Language Reference
USE_NL_WITH_INDEX Hint
(See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74,
indexspec::= on page 3-74)
The USE_NL_WITH_INDEX hint instructs the optimizer to join the specified table to
another row source with a nested loops join using the specified table as the inner table.
For example:
SELECT /*+ USE_NL_WITH_INDEX(l item_product_ix) */ *
FROM orders h, order_items l
WHERE l.order_id = h.order_id
AND l.order_id > 3500;
The following conditions apply:
■ If no index is specified, then the optimizer must be able to use some index with at
least one join predicate as the index key.
■ If an index is specified, then the optimizer must be able to use that index with at
least one join predicate as the index key.
Database Objects
Oracle Database recognizes objects that are associated with a particular schema and
objects that are not associated with any particular schema, as described in the sections
that follow.
Schema Objects
A schema is a collection of logical structures of data, or schema objects. A schema is
owned by a database user and has the same name as that user. Each user owns a single
schema. Schema objects can be created and manipulated with SQL and include the
following types of objects:
Clusters
Constraints
Database links
Database triggers
Dimensions
External procedure libraries
Index-organized tables
Indexes
Indextypes
Java classes, Java resources, Java sources
Materialized views
Materialized view logs
Mining models
Object tables
Object types
Object views
Operators
Packages
Sequences
/*+ USE_NL_WITH_INDEX (
@ queryblock
tablespec
indexspec
) */
Database Object Names and Qualifiers
Basic Elements of Oracle SQL 3-107
Stored functions, stored procedures
Synonyms
Tables
Views
Nonschema Objects
Other types of objects are also stored in the database and can be created and
manipulated with SQL but are not contained in a schema:
Contexts
Directories
Editions
Restore points
Roles
Rollback segments
Tablespaces
Users
In this reference, each type of object is described in Chapter 10 through Chapter 19, in
the section devoted to the statement that creates the database object. These statements
begin with the keyword CREATE. For example, for the definition of a cluster, see
CREATE CLUSTER on page 14-2.
You must provide names for most types of database objects when you create them.
These names must follow the rules listed in the sections that follow.
Database Object Names and Qualifiers
Some database objects are made up of parts that you can or must name, such as the
columns in a table or view, index and table partitions and subpartitions, integrity
constraints on a table, and objects that are stored within a package, including
procedures and stored functions. This section provides:
■ Rules for naming database objects and database object location qualifiers
■ Guidelines for naming database objects and qualifiers
Database Object Naming Rules
Every database object has a name. In a SQL statement, you represent the name of an
object with a quoted identifier or a nonquoted identifier.
■ A quoted identifier begins and ends with double quotation marks ("). If you name
a schema object using a quoted identifier, then you must use the double quotation
marks whenever you refer to that object.
See Also: Oracle Database Concepts for an overview of database
objects
Note: Oracle uses system-generated names beginning with "SYS_"
for implicitly generated database objects and subobjects, and names
beginning with "ORA_" for some Oracle-supplied objects. Oracle
discourages you from using these prefixes in the names you explicitly
provide to your database objects and subobjects to avoid possible
conflict in name resolution.
Database Object Names and Qualifiers
3-108 Oracle Database SQL Language Reference
■ A nonquoted identifier is not surrounded by any punctuation.
You can use either quoted or nonquoted identifiers to name any database object.
However, database names, global database names, and database link names are
always case insensitive and are stored as uppercase. If you specify such names as
quoted identifiers, then the quotation marks are silently ignored. Refer to CREATE
USER on page 17-7 for additional rules for naming users and passwords.
The following list of rules applies to both quoted and nonquoted identifiers unless
otherwise indicated:
1. Names must be from 1 to 30 bytes long with these exceptions:
■ Names of databases are limited to 8 bytes.
■ Names of database links can be as long as 128 bytes.
If an identifier includes multiple parts separated by periods, then each attribute
can be up to 30 bytes long. Each period separator, as well as any surrounding
double quotation marks, counts as one byte. For example, suppose you identify a
column like this:
"schema"."table"."column"
The schema name can be 30 bytes, the table name can by 30 bytes, and the column
name can be 30 bytes. Each of the quotation marks and periods is a single-byte
character, so the total length of the identifier in this example can be up to 98 bytes.
2. Nonquoted identifiers cannot be Oracle Database reserved words. Quoted
identifiers can be reserved words, although this is not recommended.
Depending on the Oracle product you plan to use to access a database object,
names might be further restricted by other product-specific reserved words.
3. The Oracle SQL language contains other words that have special meanings. These
words include data types, schema names, function names, the dummy system
table DUAL, and keywords (the uppercase words in SQL statements, such as
Note: Oracle does not recommend using quoted identifiers for
database object names. These quoted identifiers are accepted by
SQL*Plus, but they may not be valid when using other tools that
manage database objects.
Note: The reserved word ROWID is an exception to this rule. You
cannot use the uppercase word ROWID, either quoted or nonquoted, as
a column name. However, you can use the uppercase word as a
quoted identifier that is not a column name, and you can use the word
with one or more lowercase letters (for example, "Rowid" or "rowid")
as any quoted identifier, including a column name.
See Also:
■ Appendix E, "Oracle SQL Reserved Words" for a listing of all
Oracle Database reserved words
■ The manual for a specific product, such as Oracle Database PL/SQL
Language Reference, for a list of the reserved words of that product
Database Object Names and Qualifiers
Basic Elements of Oracle SQL 3-109
DIMENSION, SEGMENT, ALLOCATE, DISABLE, and so forth). These words are not
reserved. However, Oracle uses them internally in specific ways. Therefore, if you
use these words as names for objects and object parts, then your SQL statements
may be more difficult to read and may lead to unpredictable results.
In particular, do not use words beginning with SYS_ or ORA_ as schema object
names, and do not use the names of SQL built-in functions for the names of
schema objects or user-defined functions.
4. You should use ASCII characters in database names, global database names, and
database link names, because ASCII characters provide optimal compatibility
across different platforms and operating systems.
5. You can include multibyte characters in passwords.
6. Nonquoted identifiers must begin with an alphabetic character from your
database character set. Quoted identifiers can begin with any character.
7. Nonquoted identifiers can contain only alphanumeric characters from your
database character set and the underscore (_), dollar sign ($), and pound sign (#).
Database links can also contain periods (.) and "at" signs (@). Oracle strongly
discourages you from using $ and # in nonquoted identifiers.
Quoted identifiers can contain any characters and punctuations marks as well as
spaces. However, neither quoted nor nonquoted identifiers can contain double
quotation marks or the null character (0).
8. Within a namespace, no two objects can have the same name.
The following schema objects share one namespace:
■ Tables
■ Views
■ Sequences
■ Private synonyms
■ Stand-alone procedures
■ Stand-alone stored functions
■ Packages
■ Materialized views
■ User-defined types
Each of the following schema objects has its own namespace:
■ Indexes
■ Constraints
■ Clusters
■ Database triggers
■ Private database links
■ Dimensions
See Also: "Data Types" on page 3-1, About SQL Functions on
page 5-2, and "Selecting from the DUAL Table" on page 9-15
Database Object Names and Qualifiers
3-110 Oracle Database SQL Language Reference
Because tables and views are in the same namespace, a table and a view in the
same schema cannot have the same name. However, tables and indexes are in
different namespaces. Therefore, a table and an index in the same schema can have
the same name.
Each schema in the database has its own namespaces for the objects it contains.
This means, for example, that two tables in different schemas are in different
namespaces and can have the same name.
Each of the following nonschema objects also has its own namespace:
■ User roles
■ Public synonyms
■ Public database links
■ Tablespaces
■ Profiles
■ Parameter files (PFILEs) and server parameter files (SPFILEs)
■ Editions
Because the objects in these namespaces are not contained in schemas, these
namespaces span the entire database.
9. Nonquoted identifiers are not case sensitive. Oracle interprets them as uppercase.
Quoted identifiers are case sensitive.
By enclosing names in double quotation marks, you can give the following names
to different objects in the same namespace:
employees
"employees"
"Employees"
"EMPLOYEES"
Note that Oracle interprets the following names the same, so they cannot be used
for different objects in the same namespace:
employees
EMPLOYEES
"EMPLOYEES"
10. When Oracle stores or compares identifiers in uppercase, the uppercase form of
each character in the identifiers is determined by applying the uppercasing rules
of the database character set. Language-specific rules determined by the session
setting NLS_SORT are not considered. This behavior corresponds to applying the
SQL function UPPER to the identifier rather than the function NLS_UPPER.
The database character set uppercasing rules can yield results that are incorrect
when viewed as being in a certain natural language. For example, small letter
sharp s ("ß"), used in German, does not have an uppercase form according to the
database character set uppercasing rules. It is not modified when an identifier is
converted into uppercase, while the expected uppercase form in German is the
sequence of two characters capital letter S ("SS"). Similarly, the uppercase form of
small letter i, according to the database character set uppercasing rules, is capital
letter I. However, the expected uppercase form in Turkish and Azerbaijani is
capital letter I with dot above.
The database character set uppercasing rules ensure that identifiers are interpreted
the same in any linguistic configuration of a session. If you want an identifier to
Syntax for Schema Objects and Parts in SQL Statements
Basic Elements of Oracle SQL 3-111
look correctly in a certain natural language, then you can quote it to preserve the
lowercase form or you can use the linguistically correct uppercase form whenever
you use that identifier.
11. Columns in the same table or view cannot have the same name. However,
columns in different tables or views can have the same name.
12. Procedures or functions contained in the same package can have the same name, if
their arguments are not of the same number and data types. Creating multiple
procedures or functions with the same name in the same package with different
arguments is called overloading the procedure or function.
Schema Object Naming Examples
The following examples are valid schema object names:
last_name
horse
hr.hire_date
"EVEN THIS & THAT!"
a_very_long_and_valid_name
All of these examples adhere to the rules listed in "Database Object Naming Rules" on
page 3-107. The following example is not valid, because it exceeds 30 characters:
a_very_very_long_and_valid_name
Although column aliases, table aliases, usernames, and passwords are not objects or
parts of objects, they must also follow these naming rules unless otherwise specified in
the rules themselves.
Schema Object Naming Guidelines
Here are several helpful guidelines for naming objects and their parts:
■ Use full, descriptive, pronounceable names (or well-known abbreviations).
■ Use consistent naming rules.
■ Use the same name to describe the same entity or attribute across tables.
When naming objects, balance the objective of keeping names short and easy to use
with the objective of making names as descriptive as possible. When in doubt, choose
the more descriptive name, because the objects in the database may be used by many
people over a period of time. Your counterpart ten years from now may have difficulty
understanding a table column with a name like pmdd instead of payment_due_date.
Using consistent naming rules helps users understand the part that each table plays in
your application. One such rule might be to begin the names of all tables belonging to
the FINANCE application with fin_.
Use the same names to describe the same things across tables. For example, the
department number columns of the sample employees and departments tables are
both named department_id.
Syntax for Schema Objects and Parts in SQL Statements
This section tells you how to refer to schema objects and their parts in the context of a
SQL statement. This section shows you:
■ The general syntax for referring to an object
Syntax for Schema Objects and Parts in SQL Statements
3-112 Oracle Database SQL Language Reference
■ How Oracle resolves a reference to an object
■ How to refer to objects in schemas other than your own
■ How to refer to objects in remote databases
■ How to refer to table and index partitions and subpartitions
The following diagram shows the general syntax for referring to an object or a part:
database_object_or_part::=
where:
■ object is the name of the object.
■ schema is the schema containing the object. The schema qualifier lets you refer to
an object in a schema other than your own. You must be granted privileges to refer
to objects in other schemas. If you omit schema, then Oracle assumes that you are
referring to an object in your own schema.
Only schema objects can be qualified with schema. Schema objects are shown
with list item 8 on page 3-109. Nonschema objects, also shown with list item 8,
cannot be qualified with schema because they are not schema objects. An
exception is public synonyms, which can optionally be qualified with "PUBLIC".
The quotation marks are required.
■ part is a part of the object. This identifier lets you refer to a part of a schema
object, such as a column or a partition of a table. Not all types of objects have
parts.
■ dblink applies only when you are using the Oracle Database distributed
functionality. This is the name of the database containing the object. The dblink
qualifier lets you refer to an object in a database other than your local database. If
you omit dblink, then Oracle assumes that you are referring to an object in your
local database. Not all SQL statements allow you to access objects on remote
databases.
You can include spaces around the periods separating the components of the reference
to the object, but it is conventional to omit them.
How Oracle Database Resolves Schema Object References
When you refer to an object in a SQL statement, Oracle considers the context of the
SQL statement and locates the object in the appropriate namespace. After locating the
object, Oracle performs the operation specified by the statement on the object. If the
named object cannot be found in the appropriate namespace, then Oracle returns an
error.
The following example illustrates how Oracle resolves references to objects within SQL
statements. Consider this statement that adds a row of data to a table identified by the
name departments:
INSERT INTO departments VALUES (
280, 'ENTERTAINMENT_CLERK', 206, 1700);
Based on the context of the statement, Oracle determines that departments can be:
■ A table in your own schema
schema .
object
. part @ dblink
Syntax for Schema Objects and Parts in SQL Statements
Basic Elements of Oracle SQL 3-113
■ A view in your own schema
■ A private synonym for a table or view
■ A public synonym
Oracle always attempts to resolve an object reference within the namespaces in your
own schema before considering namespaces outside your schema. In this example,
Oracle attempts to resolve the name departments as follows:
1. First, Oracle attempts to locate the object in the namespace in your own schema
containing tables, views, and private synonyms. If the object is a private synonym,
then Oracle locates the object for which the synonym stands. This object could be
in your own schema, another schema, or on another database. The object could
also be another synonym, in which case Oracle locates the object for which this
synonym stands.
2. If the object is in the namespace, then Oracle attempts to perform the statement on
the object. In this example, Oracle attempts to add the row of data to
departments. If the object is not of the correct type for the statement, then Oracle
returns an error. In this example, departments must be a table, view, or a private
synonym resolving to a table or view. If departments is a sequence, then Oracle
returns an error.
3. If the object is not in any namespace searched in thus far, then Oracle searches the
namespace containing public synonyms. If the object is in that namespace, then
Oracle attempts to perform the statement on it. If the object is not of the correct
type for the statement, then Oracle returns an error. In this example, if
departments is a public synonym for a sequence, then Oracle returns an error.
If a public synonym has any dependent tables or user-defined types, then you cannot
create an object with the same name as the synonym in the same schema as the
dependent objects.
If a synonym does not have any dependent tables or user-defined types, then you can
create an object with the same name in the same schema as the dependent objects.
Oracle invalidates any dependent objects and attempts to revalidate them when they
are next accessed.
References to Objects in Other Schemas
To refer to objects in schemas other than your own, prefix the object name with the
schema name:
schema.object
For example, this statement drops the employees table in the sample schema hr:
DROP TABLE hr.employees;
References to Objects in Remote Databases
To refer to objects in databases other than your local database, follow the object name
with the name of the database link to that database. A database link is a schema object
that causes Oracle to connect to a remote database to access an object there. This
section tells you:
■ How to create database links
See Also: Oracle Database PL/SQL Language Reference for information
about how PL/SQL resolves identifier names
Syntax for Schema Objects and Parts in SQL Statements
3-114 Oracle Database SQL Language Reference
■ How to use database links in your SQL statements
Creating Database Links
You create a database link with the statement CREATE DATABASE LINK on
page 14-32. The statement lets you specify this information about the database link:
■ The name of the database link
■ The database connect string to access the remote database
■ The username and password to connect to the remote database
Oracle stores this information in the data dictionary.
Database Link Names When you create a database link, you must specify its name.
Database link names are different from names of other types of objects. They can be as
long as 128 bytes and can contain periods (.) and the "at" sign (@).
The name that you give to a database link must correspond to the name of the
database to which the database link refers and the location of that database in the
hierarchy of database names. The following syntax diagram shows the form of the
name of a database link:
dblink::=
where:
■ database should specify the name portion of the global name of the remote
database to which the database link connects. This global name is stored in the
data dictionary of the remote database. You can see this name in the GLOBAL_
NAME data dictionary view.
■ domain should specify the domain portion of the global name of the remote
database to which the database link connects. If you omit domain from the name
of a database link, then Oracle qualifies the database link name with the domain of
your local database as it currently exists in the data dictionary.
■ connection_qualifier lets you further qualify a database link. Using
connection qualifiers, you can create multiple database links to the same database.
For example, you can use connection qualifiers to create multiple database links to
different instances of the Oracle Real Application Clusters that access the same
database.
The combination database.domain is sometimes called the service name.
Username and Password Oracle uses the username and password to connect to the
remote database. The username and password for a database link are optional.
Database Connect String The database connect string is the specification used by Oracle
Net to access the remote database. For information on writing database connect
See Also: Oracle Database Administrator's Guide and Oracle Database
Advanced Replication for more information on connection qualifiers
See Also: Oracle Database Net Services Administrator's Guide
database
. domain @ connection_qualifier
Syntax for Schema Objects and Parts in SQL Statements
Basic Elements of Oracle SQL 3-115
strings, see the Oracle Net documentation for your specific network protocol. The
database string for a database link is optional.
References to Database Links
Database links are available only if you are using Oracle distributed functionality.
When you issue a SQL statement that contains a database link, you can specify the
database link name in one of these forms:
■ The complete database link name as stored in the data dictionary, including the
database, domain, and optional connection_qualifier components.
■ The partial database link name is the database and optional connection_
qualifier components, but not the domain component.
Oracle performs these tasks before connecting to the remote database:
1. If the database link name specified in the statement is partial, then Oracle expands
the name to contain the domain of the local database as found in the global
database name stored in the data dictionary. (You can see the current global
database name in the GLOBAL_NAME data dictionary view.)
2. Oracle first searches for a private database link in your own schema with the same
name as the database link in the statement. Then, if necessary, it searches for a
public database link with the same name.
■ Oracle always determines the username and password from the first matching
database link (either private or public). If the first matching database link has
an associated username and password, then Oracle uses it. If it does not have
an associated username and password, then Oracle uses your current
username and password.
■ If the first matching database link has an associated database string, then
Oracle uses it. Otherwise Oracle searches for the next matching (public)
database link. If no matching database link is found, or if no matching link has
an associated database string, then Oracle returns an error.
3. Oracle uses the database string to access the remote database. After accessing the
remote database, if the value of the GLOBAL_NAMES parameter is true, then
Oracle verifies that the database.domain portion of the database link name
matches the complete global name of the remote database. If this condition is true,
then Oracle proceeds with the connection, using the username and password
chosen in Step 2. If not, Oracle returns an error.
4. If the connection using the database string, username, and password is successful,
then Oracle attempts to access the specified object on the remote database using
the rules for resolving object references and referring to objects in other schemas
discussed earlier in this section.
You can disable the requirement that the database.domain portion of the database
link name must match the complete global name of the remote database by setting to
FALSE the initialization parameter GLOBAL_NAMES or the GLOBAL_NAMES parameter
of the ALTER SYSTEM or ALTER SESSION statement.
References to Partitioned Tables and Indexes
Tables and indexes can be partitioned. When partitioned, these schema objects consist
of a number of parts called partitions, all of which have the same logical attributes.
See Also: Oracle Database Administrator's Guide for more information
on remote name resolution
Syntax for Schema Objects and Parts in SQL Statements
3-116 Oracle Database SQL Language Reference
For example, all partitions in a table share the same column and constraint definitions,
and all partitions in an index share the same index columns.
Partition-extended and subpartition-extended names let you perform some
partition-level and subpartition-level operations, such as deleting all rows from a
partition or subpartition, on only one partition or subpartition. Without extended
names, such operations would require that you specify a predicate (WHERE clause). For
range- and list-partitioned tables, trying to phrase a partition-level operation with a
predicate can be cumbersome, especially when the range partitioning key uses more
than one column. For hash partitions and subpartitions, using a predicate is more
difficult still, because these partitions and subpartitions are based on a system-defined
hash function.
Partition-extended names let you use partitions as if they were tables. An advantage of
this method, which is most useful for range-partitioned tables, is that you can build
partition-level access control mechanisms by granting (or revoking) privileges on these
views to (or from) other users or roles. To use a partition as a table, create a view by
selecting data from a single partition, and then use the view as a table.
Syntax You can specify partition-extended or subpartition-extended table names in
any SQL statements in which the partition_extended_name or subpartition_
extended_name element appears in the syntax.
partition_extended_name::=
subpartition_extended_name::=
The DML statements INSERT, UPDATE, and DELETE and the ANALYZE statement
requires parentheses around the partition or subpartition name. This small distinction
is reflected in the partition_extension_clause:
partition_extension_clause::=
In partition_extended_name, subpartition_extended_name, and
partition_extension_clause, the PARTITION FOR and SUBPARTITION FOR
clauses let you refer to a partition without using its name. They are valid with any
PARTITION partition
PARTITION FOR ( partition_key_value
,
)
SUBPARTITION subpartition
SUBPARTITION FOR ( subpartition_key_value
,
)
PARTITION
( partition )
FOR ( partition_key_value
,
)
SUBPARTITION
( subpartition )
FOR ( subpartition_key_value
,
)
Syntax for Schema Objects and Parts in SQL Statements
Basic Elements of Oracle SQL 3-117
type of partitioning and are especially useful for interval partitions. Interval partitions
are created automatically as needed when data is inserted into a table.
For the respective partition_key_value or subpartition_key_value, specify
one value for each partitioning key column. For multicolumn partitioning keys,
specify one value for each partitioning key. For composite partitions, specify one value
for each partitioning key, followed by one value for each subpartitioning key. All
partitioning key values are comma separated. For interval partitions, you can specify
only one partition_key_value, and it must be a valid NUMBER or datetime value.
Your SQL statement will operate on the partition or subpartitions that contain the
values you specify.
Restrictions on Extended Names Currently, the use of partition-extended and
subpartition-extended table names has the following restrictions:
■ No remote tables: A partition-extended or subpartition-extended table name
cannot contain a database link (dblink) or a synonym that translates to a table with
a dblink. To use remote partitions and subpartitions, create a view at the remote
site that uses the extended table name syntax and then refer to the remote view.
■ No synonyms: A partition or subpartition extension must be specified with a base
table. You cannot use synonyms, views, or any other objects.
■ The PARTITION FOR and SUBPARTITION FOR clauses are not valid for DDL
operations on views.
■ In the PARTITION FOR and SUBPARTITION FOR clauses, you cannot specify the
keywords DEFAULT or MAXVALUE or a bind variable for the partition_key_
value or subpartition_key_value.
Example In the following statement, sales is a partitioned table with partition
sales_q1_2000. You can create a view of the single partition sales_q1_2000, and
then use it as if it were a table. This example deletes rows from the partition.
CREATE VIEW Q1_2000_sales AS
SELECT * FROM sales PARTITION (SALES_Q1_2000);
DELETE FROM Q1_2000_sales WHERE amount_sold < 0;
References to Object Type Attributes and Methods
To refer to object type attributes or methods in a SQL statement, you must fully qualify
the reference with a table alias. Consider the following example from the sample
schema oe, which contains a type cust_address_typ and a table customers with
a cust_address column based on the cust_address_typ:
CREATE TYPE cust_address_typ
OID '82A4AF6A4CD1656DE034080020E0EE3D'
AS OBJECT
( street_address VARCHAR2(40)
, postal_code VARCHAR2(10)
, city VARCHAR2(30)
, state_province VARCHAR2(10)
, country_id CHAR(2)
);
/
CREATE TABLE customers
See Also: The CREATE TABLE "INTERVAL Clause" on page 16-51 for
more information on interval partitions
Syntax for Schema Objects and Parts in SQL Statements
3-118 Oracle Database SQL Language Reference
( customer_id NUMBER(6)
, cust_first_name VARCHAR2(20) CONSTRAINT cust_fname_nn NOT NULL
, cust_last_name VARCHAR2(20) CONSTRAINT cust_lname_nn NOT NULL
, cust_address cust_address_typ
.
.
.
In a SQL statement, reference to the postal_code attribute must be fully qualified
using a table alias, as illustrated in the following example:
SELECT c.cust_address.postal_code FROM customers c;
UPDATE customers c SET c.cust_address.postal_code = 'GU13 BE5'
WHERE c.cust_address.city = 'Fleet';
To reference a member method that does not accept arguments, you must provide
empty parentheses. For example, the sample schema oe contains an object table
categories_tab, based on catalog_typ, which contains the member function
getCatalogName. In order to call this method in a SQL statement, you must provide
empty parentheses as shown in this example:
SELECT TREAT(VALUE(c) AS catalog_typ).getCatalogName() "Catalog Type"
FROM categories_tab c
WHERE category_id = 90;
Catalog Type
------------------------------------
online catalog
4
Operators 4-1
4 Operators
An operator manipulates data items and returns a result. Syntactically, an operator
appears before or after an operand or between two operands.
This chapter contains these sections:
■ About SQL Operators
■ Arithmetic Operators
■ Concatenation Operator
■ Hierarchical Query Operators
■ Set Operators
■ Multiset Operators
■ User-Defined Operators
This chapter discusses nonlogical (non-Boolean) operators. These operators cannot by
themselves serve as the condition of a WHERE or HAVING clause in queries or
subqueries. For information on logical operators, which serve as conditions, refer to
Chapter 7, "Conditions".
About SQL Operators
Operators manipulate individual data items called operands or arguments. Operators
are represented by special characters or by keywords. For example, the multiplication
operator is represented by an asterisk (*).
If you have installed Oracle Text, then you can use the SCORE operator, which is part
of that product, in Oracle Text queries. You can also create conditions with the built-in
Text operators, including CONTAINS, CATSEARCH, and MATCHES. For more
information on these Oracle Text elements, refer to Oracle Text Reference.
If you are using Oracle Expression Filter, then you can create conditions with the
built-in EVALUATE operator that is part of that product. For more information, refer to
Oracle Database Rules Manager and Expression Filter Developer's Guide.
About SQL Operators
4-2 Oracle Database SQL Language Reference
Unary and Binary Operators
The two general classes of operators are:
■ unary: A unary operator operates on only one operand. A unary operator typically
appears with its operand in this format:
operator operand
■ binary: A binary operator operates on two operands. A binary operator appears
with its operands in this format:
operand1 operator operand2
Other operators with special formats accept more than two operands. If an operator is
given a null operand, then the result is always null. The only operator that does not
follow this rule is concatenation (||).
Operator Precedence
Precedence is the order in which Oracle Database evaluates different operators in the
same expression. When evaluating an expression containing multiple operators,
Oracle evaluates operators with higher precedence before evaluating those with lower
precedence. Oracle evaluates operators with equal precedence from left to right within
an expression.
Table 4–1 lists the levels of precedence among SQL operators from high to low.
Operators listed on the same line have the same precedence.
Precedence Example In the following expression, multiplication has a higher
precedence than addition, so Oracle first multiplies 2 by 3 and then adds the result to
1.
1+2*3
Note: The combined values of the NLS_COMP and NLS_SORT
settings determine the rules by which characters are sorted and
compared. If NLS_COMP is set to LINGUISTIC for your database, then
all entities in this chapter will be interpreted according to the rules
specified by the NLS_SORT parameter. If NLS_COMP is not set to
LINGUISTIC, then the functions are interpreted without regard to the
NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set
explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle
Database Globalization Support Guide for more information on these
settings.
Table 4–1 SQL Operator Precedence
Operator Operation
+, - (as unary operators), PRIOR, CONNECT_
BY_ROOT
Identity, negation, location in hierarchy
*, / Multiplication, division
+, - (as binary operators), || Addition, subtraction, concatenation
SQL conditions are evaluated after SQL
operators
See "Condition Precedence" on page 7-3
Arithmetic Operators
Operators 4-3
You can use parentheses in an expression to override operator precedence. Oracle
evaluates expressions inside parentheses before evaluating those outside.
SQL also supports set operators (UNION, UNION ALL, INTERSECT, and MINUS), which
combine sets of rows returned by queries, rather than individual data items. All set
operators have equal precedence.
Arithmetic Operators
You can use an arithmetic operator with one or two arguments to negate, add,
subtract, multiply, and divide numeric values. Some of these operators are also used in
datetime and interval arithmetic. The arguments to the operator must resolve to
numeric data types or to any data type that can be implicitly converted to a numeric
data type.
Unary arithmetic operators return the same data type as the numeric data type of the
argument. For binary arithmetic operators, Oracle determines the argument with the
highest numeric precedence, implicitly converts the remaining arguments to that data
type, and returns that data type. Table 4–2 lists arithmetic operators.
Do not use two consecutive minus signs (--) in arithmetic expressions to indicate
double negation or the subtraction of a negative value. The characters -- are used to
begin comments within SQL statements. You should separate consecutive minus signs
with a space or parentheses. Refer to "Comments" on page 3-71 for more information
on comments within SQL statements.
See Also: "Hierarchical Query Operators" on page 4-5 and
"Hierarchical Queries" on page 9-3 for information on the PRIOR
operator, which is used only in hierarchical queries
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion, "Numeric
Precedence" on page 3-14 for information on numeric precedence, and
"Datetime/Interval Arithmetic" on page 3-20
Table 4–2 Arithmetic Operators
Operator Purpose Example
+ - When these denote a positive or
negative expression, they are unary
operators.
SELECT * FROM order_items
WHERE quantity = -1
ORDER BY order_id,
line_item_id, product_id;
SELECT * FROM employees
WHERE -salary < 0
ORDER BY employee_id;
+ - When they add or subtract, they are
binary operators.
SELECT hire_date
FROM employees
WHERE SYSDATE - hire_date
> 365 ORDER BY hire_date;
* / Multiply, divide. These are binary
operators.
UPDATE employees
SET salary = salary * 1.1;
Concatenation Operator
4-4 Oracle Database SQL Language Reference
Concatenation Operator
The concatenation operator manipulates character strings and CLOB data. Table 4–3
describes the concatenation operator.
The result of concatenating two character strings is another character string. If both
character strings are of data type CHAR, then the result has data type CHAR and is
limited to 2000 characters. If either string is of data type VARCHAR2, the result has data
type VARCHAR2 and is limited to 4000 characters. If either argument is a CLOB, the
result is a temporary CLOB. Trailing blanks in character strings are preserved by
concatenation, regardless of the data types of the string or CLOB.
On most platforms, the concatenation operator is two solid vertical bars, as shown in
Table 4–3. However, some IBM platforms use broken vertical bars for this operator.
When moving SQL script files between systems having different character sets, such as
between ASCII and EBCDIC, vertical bars might not be translated into the vertical bar
required by the target Oracle Database environment. Oracle provides the CONCAT
character function as an alternative to the vertical bar operator for cases when it is
difficult or impossible to control translation performed by operating system or
network utilities. Use this function in applications that will be moved between
environments with differing character sets.
Although Oracle treats zero-length character strings as nulls, concatenating a
zero-length character string with another operand always results in the other operand,
so null can result only from the concatenation of two null strings. However, this may
not continue to be true in future versions of Oracle Database. To concatenate an
expression that might be null, use the NVL function to explicitly convert the expression
to a zero-length string.
Concatenation Example This example creates a table with both CHAR and VARCHAR2
columns, inserts values both with and without trailing blanks, and then selects these
values and concatenates them. Note that for both CHAR and VARCHAR2 columns, the
trailing blanks are preserved.
CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6),
col3 VARCHAR2(6), col4 CHAR(6) );
INSERT INTO tab1 (col1, col2, col3, col4)
VALUES ('abc', 'def ', 'ghi ', 'jkl');
SELECT col1||col2||col3||col4 "Concatenation"
FROM tab1;
Table 4–3 Concatenation Operator
Operator Purpose Example
|| Concatenates character strings
and CLOB data.
SELECT 'Name is ' || last_name
FROM employees
ORDER BY last_name;
See Also:
■ "Character Data Types" on page 3-8 for more information on the
differences between the CHAR and VARCHAR2 data types
■ The functions CONCAT on page 5-40 and NVL on page 5-126
■ Oracle Database SecureFiles and Large Objects Developer's Guide for
more information about CLOBs
Set Operators
Operators 4-5
Concatenation
------------------------
abcdef ghi jkl
Hierarchical Query Operators
Two operators, PRIOR and CONNECT_BY_ROOT, are valid only in hierarchical queries.
PRIOR
In a hierarchical query, one expression in the CONNECT BY condition must be
qualified by the PRIOR operator. If the CONNECT BY condition is compound, then
only one condition requires the PRIOR operator, although you can have multiple
PRIOR conditions. PRIOR evaluates the immediately following expression for the
parent row of the current row in a hierarchical query.
PRIOR is most commonly used when comparing column values with the equality
operator. (The PRIOR keyword can be on either side of the operator.) PRIOR causes
Oracle to use the value of the parent row in the column. Operators other than the
equal sign (=) are theoretically possible in CONNECT BY clauses. However, the
conditions created by these other operators can result in an infinite loop through the
possible combinations. In this case Oracle detects the loop at run time and returns an
error. Refer to "Hierarchical Queries" on page 9-3 for more information on this
operator, including examples.
CONNECT_BY_ROOT
CONNECT_BY_ROOT is a unary operator that is valid only in hierarchical queries.
When you qualify a column with this operator, Oracle returns the column value using
data from the root row. This operator extends the functionality of the CONNECT BY
[PRIOR] condition of hierarchical queries.
Restriction on CONNECT_BY_ROOT You cannot specify this operator in the START
WITH condition or the CONNECT BY condition.
Set Operators
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries. Table 4–4 lists SQL set
operators. They are fully described, including examples and restrictions on these
operators, in "The UNION [ALL], INTERSECT, MINUS Operators" on page 9-8.
See Also: "CONNECT_BY_ROOT Examples" on page 9-7
Table 4–4 Set Operators
Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows selected by the first query but not the second
Multiset Operators
4-6 Oracle Database SQL Language Reference
Multiset Operators
Multiset operators combine the results of two nested tables into a single nested table.
The examples related to multiset operators require that two nested tables be created
and loaded with data as follows:
First, make a copy of the oe.customers table called customers_demo:
CREATE TABLE customers_demo AS
SELECT * FROM customers;
Next, create a table type called cust_address_tab_typ. This type will be used
when creating the nested table columns.
CREATE TYPE cust_address_tab_typ AS
TABLE OF cust_address_typ
/
Now, create two nested table columns in the customers_demo table:
ALTER TABLE customers_demo
ADD (cust_address_ntab cust_address_tab_typ,
cust_address2_ntab cust_address_tab_typ)
NESTED TABLE cust_address_ntab STORE AS cust_address_ntab_store
NESTED TABLE cust_address2_ntab STORE AS cust_address2_ntab_store;
Finally, load data into the two new nested table columns using data from the cust_
address column of the oe.customers table:
UPDATE CUSTOMERS_DEMO cd
SET cust_address_ntab =
CAST(MULTISET(SELECT cust_address
FROM customers c
WHERE c.customer_id =
cd.customer_id) as cust_address_tab_typ);
UPDATE CUSTOMERS_DEMO cd
SET cust_address2_ntab =
CAST(MULTISET(SELECT cust_address
FROM customers c
WHERE c.customer_id =
cd.customer_id) as cust_address_tab_typ);
MULTISET EXCEPT
MULTISET EXCEPT takes as arguments two nested tables and returns a nested table
whose elements are in the first nested table but not in the second nested table. The two
input nested tables must be of the same type, and the returned nested table is of the
same type as well.
■ The ALL keyword instructs Oracle to return all elements in nested_table1 that
are not in nested_table2. For example, if a particular element occurs m times in
nested_table1 and n times in nested_table2, then the result will have
(m-n) occurrences of the element if m >n and 0 occurrences if m<=n. ALL is the
default.
nested_table1 MULTISET EXCEPT
ALL
DISTINCT
nested_table2
Multiset Operators
Operators 4-7
■ The DISTINCT keyword instructs Oracle to eliminate any element in nested_
table1 which is also in nested_table2, regardless of the number of
occurrences.
■ The element types of the nested tables must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example compares two nested tables and returns a nested table of those
elements found in the first nested table but not in the second nested table:
SELECT customer_id, cust_address_ntab
MULTISET EXCEPT DISTINCT cust_address2_ntab multiset_except
FROM customers_demo;
CUSTOMER_ID MULTISET_EXCEPT(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
----------- --------------------------------------------------------------------------------
101 CUST_ADDRESS_TAB_TYP()
102 CUST_ADDRESS_TAB_TYP()
103 CUST_ADDRESS_TAB_TYP()
104 CUST_ADDRESS_TAB_TYP()
105 CUST_ADDRESS_TAB_TYP()
. . .
The preceding example requires the table customers_demo and two nested table
columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
MULTISET INTERSECT
MULTISET INTERSECT takes as arguments two nested tables and returns a nested
table whose values are common in the two input nested tables. The two input nested
tables must be of the same type, and the returned nested table is of the same type as
well.
■ The ALL keyword instructs Oracle to return all common occurrences of elements
that are in the two input nested tables, including duplicate common values and
duplicate common NULL occurrences. For example, if a particular value occurs m
times in nested_table1 and n times in nested_table2, then the result would
contain the element min(m,n) times. ALL is the default.
■ The DISTINCT keyword instructs Oracle to eliminate duplicates from the returned
nested table, including duplicates of NULL, if they exist.
■ The element types of the nested tables must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example compares two nested tables and returns a nested table of those
elements found in both input nested tables:
SELECT customer_id, cust_address_ntab
MULTISET INTERSECT DISTINCT cust_address2_ntab multiset_intersect
FROM customers_demo
ORDER BY customer_id;
nested_table1 MULTISET INTERSECT
ALL
DISTINCT
nested_table2
Multiset Operators
4-8 Oracle Database SQL Language Reference
CUSTOMER_ID MULTISET_INTERSECT(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID
----------- -----------------------------------------------------------------------------------
101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))
102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'))
103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))
104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'))
105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'))
.
.
.
The preceding example requires the table customers_demo and two nested table
columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
MULTISET UNION
MULTISET UNION takes as arguments two nested tables and returns a nested table
whose values are those of the two input nested tables. The two input nested tables
must be of the same type, and the returned nested table is of the same type as well.
■ The ALL keyword instructs Oracle to return all elements that are in the two input
nested tables, including duplicate values and duplicate NULL occurrences. This is
the default.
■ The DISTINCT keyword instructs Oracle to eliminate duplicates from the returned
nested table, including duplicates of NULL, if they exist.
■ The element types of the nested tables must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example compares two nested tables and returns a nested table of
elements from both input nested tables:
SELECT customer_id, cust_address_ntab
MULTISET UNION cust_address2_ntab multiset_union
FROM customers_demo
ORDER BY customer_id;
CUSTOMER_ID MULTISET_UNION(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
----------- -------------------------------------------------------------------------------
101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'),
CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))
102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'),
CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN','US'))
103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'),
CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))
104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'),
CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'))
105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'),
CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'))
.
.
.
The preceding example requires the table customers_demo and two nested table
columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
nested_table1 MULTISET UNION
ALL
DISTINCT
nested_table2
User-Defined Operators
Operators 4-9
User-Defined Operators
Like built-in operators, user-defined operators take a set of operands as input and
return a result. However, you create them with the CREATE OPERATOR statement, and
they are identified by user-defined names. They reside in the same namespace as
tables, views, types, and standalone functions.
After you have defined a new operator, you can use it in SQL statements like any other
built-in operator. For example, you can use user-defined operators in the select list of a
SELECT statement, the condition of a WHERE clause, or in ORDER BY clauses and
GROUP BY clauses. However, you must have EXECUTE privilege on the operator to do
so, because it is a user-defined object.
See Also: CREATE OPERATOR on page 15-34 for an example of
creating an operator and Oracle Database Data Cartridge Developer's
Guide for more information on user-defined operators
User-Defined Operators
4-10 Oracle Database SQL Language Reference
5
Functions 5-1
5Functions
Functions are similar to operators in that they manipulate data items and return a
result. Functions differ from operators in the format of their arguments. This format
enables them to operate on zero, one, two, or more arguments:
function(argument, argument, ...)
A function without any arguments is similar to a pseudocolumn (refer to Chapter 2,
"Pseudocolumns"). However, a pseudocolumn typically returns a different value for
each row in the result set, whereas a function without any arguments typically returns
the same value for each row.
This chapter contains these sections:
■ About SQL Functions
■ Single-Row Functions
– Numeric Functions
– Character Functions Returning Character Values
– NLS Character Functions
– Character Functions Returning Number Values
– Datetime Functions
– General Comparison Functions
– Conversion Functions
– Large Object Functions
– Collection Functions
– Hierarchical Function
– Data Mining Functions
– XML Functions
– Encoding and Decoding Functions
– NULL-Related Functions
– Environment and Identifier Functions
■ Aggregate Functions
■ Analytic Functions
■ Object Reference Functions
About SQL Functions
5-2 Oracle Database SQL Language Reference
■ Model Functions
■ About User-Defined Functions
About SQL Functions
SQL functions are built into Oracle Database and are available for use in various
appropriate SQL statements. Do not confuse SQL functions with user-defined
functions written in PL/SQL.
If you call a SQL function with an argument of a data type other than the data type
expected by the SQL function, then Oracle attempts to convert the argument to the
expected data type before performing the SQL function.
Nulls in SQL Functions Most scalar functions return null when given a null
argument. You can use the NVL function to return a value when a null occurs. For
example, the expression NVL(commission_pct,0) returns 0 if commission_pct is
null or the value of commission_pct if it is not null.
For information on how aggregate functions handle nulls, see "Aggregate Functions"
on page 5-9.
Syntax for SQL Functions In the syntax diagrams for SQL functions, arguments are
indicated by their data types. When the parameter function appears in SQL syntax,
replace it with one of the functions described in this section. Functions are grouped by
the data types of their arguments and their return values.
Note: The combined values of the NLS_COMP and NLS_SORT
settings determine the rules by which characters are sorted and
compared. If NLS_COMP is set to LINGUISTIC for your database, then
all entities in this chapter will be interpreted according to the rules
specified by the NLS_SORT parameter. If NLS_COMP is not set to
LINGUISTIC, then the functions are interpreted without regard to the
NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set
explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle
Database Globalization Support Guide for more information on these
settings.
Note: When you apply SQL functions to LOB columns, Oracle
Database creates temporary LOBs during SQL and PL/SQL
processing. You should ensure that temporary tablespace quota is
sufficient for storing these temporary LOBs for your application.
See Also:
■ "About User-Defined Functions" on page 5-271 for information on
user functions and "Data Conversion" on page 3-40 for implicit
conversion of data types
■ Oracle Text Reference for information on functions used with Oracle
Text
■ Oracle Data Mining Application Developer's Guide for information
on frequent itemset functions used with Oracle Data Mining
Single-Row Functions
Functions 5-3
The syntax showing the categories of functions follows:
function::=
single_row_function::=
The sections that follow list the built-in SQL functions in each of the groups illustrated
in the preceding diagrams except user-defined functions. All of the built-in SQL
functions are then described in alphabetical order.
Single-Row Functions
Single-row functions return a single result row for every row of a queried table or
view. These functions can appear in select lists, WHERE clauses, START WITH and
CONNECT BY clauses, and HAVING clauses.
Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric
functions that return NUMBER values that are accurate to 38 decimal digits. The
transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH
are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and
ATAN2 are accurate to 30 decimal digits. The numeric functions are:
ABS
ACOS
ASIN
ATAN
ATAN2
BITAND
See Also: "About User-Defined Functions" on page 5-271 and
CREATE FUNCTION on page 14-59
single_row_function
aggregate_function
analytic_function
object_reference_function
model_function
user_defined_function
numeric_function
character_function
data_mining_function
datetime_function
conversion_function
collection_function
XML_function
miscellaneous_single_row_function
Single-Row Functions
5-4 Oracle Database SQL Language Reference
CEIL
COS
COSH
EXP
FLOOR
LN
LOG
MOD
NANVL
POWER
REMAINDER
ROUND (number)
SIGN
SIN
SINH
SQRT
TAN
TANH
TRUNC (number)
WIDTH_BUCKET
Character Functions Returning Character Values
Character functions that return character values return values of the following data
types unless otherwise documented:
■ If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2.
■ If the input argument is NCHAR or NVARCHAR2, then the value returned is
NVARCHAR2.
The length of the value returned by the function is limited by the maximum length of
the data type returned.
■ For functions that return CHAR or VARCHAR2, if the length of the return value
exceeds the limit, then Oracle Database truncates it and returns the result without
an error message.
■ For functions that return CLOB values, if the length of the return values exceeds
the limit, then Oracle raises an error and returns no data.
The character functions that return character values are:
CHR
CONCAT
INITCAP
LOWER
LPAD
LTRIM
NLS_INITCAP
NLS_LOWER
NLSSORT
NLS_UPPER
REGEXP_REPLACE
REGEXP_SUBSTR
REPLACE
RPAD
RTRIM
SOUNDEX
Single-Row Functions
Functions 5-5
SUBSTR
TRANSLATE
TREAT
TRIM
UPPER
NLS Character Functions
The NLS character functions return information about the character set. The NLS
character functions are:
NLS_CHARSET_DECL_LEN
NLS_CHARSET_ID
NLS_CHARSET_NAME
Character Functions Returning Number Values
Character functions that return number values can take as their argument any
character data type.
The character functions that return number values are:
ASCII
INSTR
LENGTH
REGEXP_INSTR
Datetime Functions
Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP
WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL
DAY TO SECOND, INTERVAL YEAR TO MONTH) values.
Some of the datetime functions were designed for the Oracle DATE data type (ADD_
MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you provide a
timestamp value as their argument, then Oracle Database internally converts the input
type to a DATE value and returns a DATE value. The exceptions are the MONTHS_
BETWEEN function, which returns a number, and the ROUND and TRUNC functions,
which do not accept timestamp or interval values at all.
The remaining datetime functions were designed to accept any of the three types of
data (date, timestamp, and interval) and to return a value of one of these types.
All of the datetime functions that return current system datetime information, such as
SYSDATE, SYSTIMESTAMP, CURRENT_TIMESTAMP, and so forth, are evaluated once
for each SQL statement, regardless how many times they are referenced in that
statement.
The datetime functions are:
ADD_MONTHS
CURRENT_DATE
CURRENT_TIMESTAMP
DBTIMEZONE
EXTRACT (datetime)
FROM_TZ
LAST_DAY
LOCALTIMESTAMP
MONTHS_BETWEEN
Single-Row Functions
5-6 Oracle Database SQL Language Reference
NEW_TIME
NEXT_DAY
NUMTODSINTERVAL
NUMTOYMINTERVAL
ROUND (date)
SESSIONTIMEZONE
SYS_EXTRACT_UTC
SYSDATE
SYSTIMESTAMP
TO_CHAR (datetime)
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_DSINTERVAL
TO_YMINTERVAL
TRUNC (date)
TZ_OFFSET
General Comparison Functions
The general comparison functions determine the greatest and or least value from a set
of values. The general comparison functions are:
GREATEST
LEAST
Conversion Functions
Conversion functions convert a value from one data type to another. Generally, the
form of the function names follows the convention datatype TO datatype. The first
data type is the input data type. The second data type is the output data type. The SQL
conversion functions are:
ASCIISTR
BIN_TO_NUM
CAST
CHARTOROWID
COMPOSE
CONVERT
DECOMPOSE
HEXTORAW
NUMTODSINTERVAL
NUMTOYMINTERVAL
RAWTOHEX
RAWTONHEX
ROWIDTOCHAR
ROWIDTONCHAR
SCN_TO_TIMESTAMP
TIMESTAMP_TO_SCN
TO_BINARY_DOUBLE
TO_BINARY_FLOAT
TO_CHAR (character)
TO_CHAR (datetime)
TO_CHAR (number)
TO_CLOB
TO_DATE
TO_DSINTERVAL
Single-Row Functions
Functions 5-7
TO_LOB
TO_MULTI_BYTE
TO_NCHAR (character)
TO_NCHAR (datetime)
TO_NCHAR (number)
TO_NCLOB
TO_NUMBER
TO_DSINTERVAL
TO_SINGLE_BYTE
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_YMINTERVAL
TO_YMINTERVAL
TRANSLATE ... USING
UNISTR
Large Object Functions
The large object functions operate on LOBs. The large object functions are:
BFILENAME
EMPTY_BLOB, EMPTY_CLOB
Collection Functions
The collection functions operate on nested tables and varrays. The SQL collection
functions are:
CARDINALITY
COLLECT
POWERMULTISET
POWERMULTISET_BY_CARDINALITY
SET
Hierarchical Function
The hierarchical function applies hierarchical path information to a result set.
SYS_CONNECT_BY_PATH
Data Mining Functions
The data mining functions operate on models that have been built using the DBMS_
DATA_MINING package or the Oracle Data Mining Java API. The SQL data mining
functions are:
CLUSTER_ID
CLUSTER_PROBABILITY
CLUSTER_SET
FEATURE_ID
FEATURE_SET
FEATURE_VALUE
PREDICTION
PREDICTION_BOUNDS
PREDICTION_COST
PREDICTION_DETAILS
PREDICTION_PROBABILITY
Single-Row Functions
5-8 Oracle Database SQL Language Reference
PREDICTION_SET
XML Functions
The XML functions operate on or return XML documents or fragments. These
functions use arguments that are not defined as part of the ANSI/ISO/IEC SQL
Standard but are defined as part of the World Wide Web Consortium (W3C) standards.
The processing and operations that the functions perform are defined by the relevant
W3C standards. The table below provides a link to the appropriate section of the W3C
standard for the rules and guidelines that apply to each of these XML-related
arguments. A SQL statement that uses one of these XML functions, where any of the
arguments does not conform to the relevant W3C syntax, will result in an error. In
particular, of special note is the fact that not every character that is allowed in the
value of a database column is considered legal in XML.
For more information about selecting and querying XML data using these functions,
including information on formatting output, refer to Oracle XML DB Developer's Guide.
The SQL XML functions are:
APPENDCHILDXML
DELETEXML
DEPTH
EXTRACT (XML)
EXISTSNODE
EXTRACTVALUE
INSERTCHILDXML
INSERTCHILDXMLAFTER
INSERTCHILDXMLBEFORE
INSERTXMLAFTER
INSERTXMLBEFORE
PATH
SYS_DBURIGEN
SYS_XMLAGG
SYS_XMLGEN
UPDATEXML
XMLAGG
XMLCAST
XMLCDATA
XMLCOLATTVAL
XMLCOMMENT
XMLCONCAT
XMLDIFF
XMLELEMENT
XMLEXISTS
XMLFOREST
XMLISVALID
Syntax Element W3C Standard URL
value_expr http://www.w3.org/TR/2006/REC-xml-20060816
Xpath_string http://www.w3.org/TR/1999/REC-xpath-19991116
XQuery_string http://www.w3.org/TR/2007/REC-xquery-semantics-20070123/
namespace_string http://www.w3.org/TR/2006/REC-xml-names-20060816/
identifier http://www.w3.org/TR/2006/REC-xml-20060816/#NT-Nmtoken
Aggregate Functions
Functions 5-9
XMLPARSE
XMLPATCH
XMLPI
XMLQUERY
XMLROOT
XMLSEQUENCE
XMLSERIALIZE
XMLTABLE
XMLTRANSFORM
Encoding and Decoding Functions
The encoding and decoding functions let you inspect and decode data in the database.
DECODE
DUMP
ORA_HASH
VSIZE
NULL-Related Functions
The NULL-related functions facilitate null handling. The NULL-related functions are:
COALESCE
LNNVL
NANVL
NULLIF
NVL
NVL2
Environment and Identifier Functions
The environment and identifier functions provide information about the instance and
session. These functions are:
SYS_CONTEXT
SYS_GUID
SYS_TYPEID
UID
USER
USERENV
Aggregate Functions
Aggregate functions return a single result row based on groups of rows, rather than on
single rows. Aggregate functions can appear in select lists and in ORDER BY and
HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT
statement, where Oracle Database divides the rows of a queried table or view into
groups. In a query containing a GROUP BY clause, the elements of the select list can be
aggregate functions, GROUP BY expressions, constants, or expressions involving one of
these. Oracle applies the aggregate functions to each group of rows and returns a
single result row for each group.
If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select
list to all the rows in the queried table or view. You use aggregate functions in the
HAVING clause to eliminate groups from the output based on the results of the
Aggregate Functions
5-10 Oracle Database SQL Language Reference
aggregate functions, rather than on the values of the individual rows of the queried
table or view.
Many (but not all) aggregate functions that take a single argument accept these
clauses:
■ DISTINCT and UNIQUE, which are synonymous, cause an aggregate function to
consider only distinct values of the argument expression. The syntax diagrams for
aggregate functions in this chapter use the keyword DISTINCT for simplicity.
■ ALL causes an aggregate function to consider all values, including all duplicates.
For example, the DISTINCT average of 1, 1, 1, and 3 is 2. The ALL average is 1.5. If you
specify neither, then the default is ALL.
Some aggregate functions allow the windowing_clause, which is part of the syntax
of analytic functions. Refer to windowing_clause on page 5-14 for information about this
clause. In the listing of aggregate functions at the end of this section, the functions that
allow the windowing_clause are followed by an asterisk (*)
All aggregate functions except COUNT(*), GROUPING, and GROUPING_ID ignore nulls.
You can use the NVL function in the argument to an aggregate function to substitute a
value for a null. COUNT and REGR_COUNT never return null, but return either a
number or zero. For all the remaining aggregate functions, if the data set contains no
rows, or contains only rows with nulls as arguments to the aggregate function, then
the function returns null.
The aggregate functions MIN, MAX, SUM, AVG, COUNT, VARIANCE, and STDDEV, when
followed by the KEEP keyword, can be used in conjunction with the FIRST or LAST
function to operate on a set of values from a set of rows that rank as the FIRST or
LAST with respect to a given sorting specification. Refer to FIRST on page 5-77 for
more information.
You can nest aggregate functions. For example, the following example calculates the
average of the maximum salaries of all the departments in the sample schema hr:
SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id;
AVG(MAX(SALARY))
----------------
10925
This calculation evaluates the inner aggregate (MAX(salary)) for each group defined
by the GROUP BY clause (department_id), and aggregates the results again.
The aggregate functions are:
AVG
COLLECT
CORR
CORR_*
COUNT
COVAR_POP
COVAR_SAMP
CUME_DIST
DENSE_RANK
FIRST
See Also: "Using the GROUP BY Clause: Examples" on page 19-42
and the "HAVING Clause" on page 19-28 for more information on the
GROUP BY clause and HAVING clauses in queries and subqueries
Analytic Functions
Functions 5-11
GROUP_ID
GROUPING
GROUPING_ID
LAST
MAX
MEDIAN
MIN
PERCENTILE_CONT
PERCENTILE_DISC
PERCENT_RANK
RANK
REGR_ (Linear Regression) Functions
STATS_BINOMIAL_TEST
STATS_CROSSTAB
STATS_F_TEST
STATS_KS_TEST
STATS_MODE
STATS_MW_TEST
STATS_ONE_WAY_ANOVA
STATS_T_TEST_*
STATS_WSR_TEST
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
SYS_XMLAGG
VAR_POP
VAR_SAMP
VARIANCE
XMLAGG
Analytic Functions
Analytic functions compute an aggregate value based on a group of rows. They differ
from aggregate functions in that they return multiple rows for each group. The group
of rows is called a window and is defined by the analytic_clause. For each row, a
sliding window of rows is defined. The window determines the range of rows used to
perform the calculations for the current row. Window sizes can be based on either a
physical number of rows or a logical interval such as time.
Analytic functions are the last set of operations performed in a query except for the
final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are
completed before the analytic functions are processed. Therefore, analytic functions
can appear only in the select list or ORDER BY clause.
Analytic functions are commonly used to compute cumulative, moving, centered, and
reporting aggregates.
analytic_function::=
analytic_function (
arguments
) OVER ( analytic_clause )
Analytic Functions
5-12 Oracle Database SQL Language Reference
analytic_clause::=
query_partition_clause::=
order_by_clause::=
windowing_clause::=
The semantics of this syntax are discussed in the sections that follow.
analytic_function
Specify the name of an analytic function (see the listing of analytic functions following
this discussion of semantics).
arguments
Analytic functions take 0 to 3 arguments. The arguments can be any numeric data type
or any nonnumeric data type that can be implicitly converted to a numeric data type.
Oracle determines the argument with the highest numeric precedence and implicitly
converts the remaining arguments to that data type. The return type is also that data
type, unless otherwise noted for an individual function.
See Also: "Numeric Precedence" on page 3-14 for information on
numeric precedence and Table 3–10, " Implicit Type Conversion
Matrix" on page 3-41 for more information on implicit conversion
query_partition_clause order_by_clause
windowing_clause
PARTITION BY
expr
,
( expr
,
)
ORDER
SIBLINGS
BY
expr
position
c_alias
ASC
DESC
NULLS FIRST
NULLS LAST
,
ROWS
RANGE
BETWEEN
UNBOUNDED PRECEDING
CURRENT ROW
value_expr
PRECEDING
FOLLOWING
AND
UNBOUNDED FOLLOWING
CURRENT ROW
value_expr
PRECEDING
FOLLOWING
UNBOUNDED PRECEDING
CURRENT ROW
value_expr PRECEDING
Analytic Functions
Functions 5-13
analytic_clause
Use OVER analytic_clause to indicate that the function operates on a query result
set. This clause is computed after the FROM, WHERE, GROUP BY, and HAVING clauses.
You can specify analytic functions with this clause in the select list or ORDER BY clause.
To filter the results of a query based on an analytic function, nest these functions
within the parent query, and then filter the results of the nested subquery.
Notes on the analytic_clause: The following notes apply to the analytic_clause:
■ You cannot nest analytic functions by specifying any analytic function in any part
of the analytic_clause. However, you can specify an analytic function in a
subquery and compute another analytic function over it.
■ You can specify OVER analytic_clause with user-defined analytic functions as
well as built-in analytic functions. See CREATE FUNCTION on page 14-59.
query_partition_clause
Use the PARTITION BY clause to partition the query result set into groups based on
one or more value_expr. If you omit this clause, then the function treats all rows of
the query result set as a single group.
To use the query_partition_clause in an analytic function, use the upper branch
of the syntax (without parentheses). To use this clause in a model query (in the
model_column_clauses) or a partitioned outer join (in the outer_join_clause),
use the lower branch of the syntax (with parentheses).
You can specify multiple analytic functions in the same query, each with the same or
different PARTITION BY keys.
If the objects being queried have the parallel attribute, and if you specify an analytic
function with the query_partition_clause, then the function computations are
parallelized as well.
Valid values of value_expr are constants, columns, nonanalytic functions, function
expressions, or expressions involving any of these.
order_by_clause
Use the order_by_clause to specify how data is ordered within a partition. For all
analytic functions except PERCENTILE_CONT and PERCENTILE_DISC (which take
only a single key), you can order the values in a partition on multiple keys, each
defined by a value_expr and each qualified by an ordering sequence.
Within each function, you can specify multiple ordering expressions. Doing so is
especially useful when using functions that rank values, because the second
expression can resolve ties between identical values for the first expression.
Whenever the order_by_clause results in identical values for multiple rows, the
function returns the same result for each of those rows. Refer to the analytic example
for SUM on page 5-200 for an illustration of this behavior.
Restrictions on the ORDER BY Clause The following restrictions apply to the ORDER
BY clause:
■ When used in an analytic function, the order_by_clause must take an
expression (expr). The SIBLINGS keyword is not valid (it is relevant only in
hierarchical queries). Position (position) and column aliases (c_alias) are also
invalid. Otherwise this order_by_clause is the same as that used to order the
overall query or subquery.
Analytic Functions
5-14 Oracle Database SQL Language Reference
■ An analytic function that uses the RANGE keyword can use multiple sort keys in its
ORDER BY clause if it specifies either of these two windows:
– RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The short form
of this is RANGE UNBOUNDED PRECEDING.
– RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING.
Window boundaries other than these two can have only one sort key in the ORDER
BY clause of the analytic function. This restriction does not apply to window
boundaries specified by the ROW keyword.
ASC | DESC Specify the ordering sequence (ascending or descending). ASC is the
default.
NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls should
appear first or last in the ordering sequence.
NULLS LAST is the default for ascending order, and NULLS FIRST is the default for
descending order.
Analytic functions always operate on rows in the order specified in the order_by_
clause of the function. However, the order_by_clause of the function does not
guarantee the order of the result. Use the order_by_clause of the query to
guarantee the final result ordering.
windowing_clause
Some analytic functions allow the windowing_clause. In the listing of analytic
functions at the end of this section, the functions that allow the windowing_clause
are followed by an asterisk (*).
ROWS | RANGE These keywords define for each row a window (a physical or logical
set of rows) used for calculating the function result. The function is then applied to all
the rows in the window. The window moves through the query result set or partition
from top to bottom.
■ ROWS specifies the window in physical units (rows).
■ RANGE specifies the window as a logical offset.
You cannot specify this clause unless you have specified the order_by_clause.
Some window boundaries defined by the RANGE clause let you specify only one
expression in the order_by_clause. Refer to "Restrictions on the ORDER BY
Clause" on page 5-13.
The value returned by an analytic function with a logical offset is always deterministic.
However, the value returned by an analytic function with a physical offset may
produce nondeterministic results unless the ordering expression results in a unique
ordering. You may have to specify multiple columns in the order_by_clause to
achieve this unique ordering.
BETWEEN ... AND Use the BETWEEN ... AND clause to specify a start point and end
point for the window. The first expression (before AND) defines the start point and the
second expression (after AND) defines the end point.
If you omit BETWEEN and specify only one end point, then Oracle considers it the start
point, and the end point defaults to the current row.
See Also: order_by_clause of SELECT on page 19-33 for more
information on this clause
Analytic Functions
Functions 5-15
UNBOUNDED PRECEDING Specify UNBOUNDED PRECEDING to indicate that the
window starts at the first row of the partition. This is the start point specification and
cannot be used as an end point specification.
UNBOUNDED FOLLOWING Specify UNBOUNDED FOLLOWING to indicate that the
window ends at the last row of the partition. This is the end point specification and
cannot be used as a start point specification.
CURRENT ROW As a start point, CURRENT ROW specifies that the window begins at
the current row or value (depending on whether you have specified ROW or RANGE,
respectively). In this case the end point cannot be value_expr PRECEDING.
As an end point, CURRENT ROW specifies that the window ends at the current row or
value (depending on whether you have specified ROW or RANGE, respectively). In this
case the start point cannot be value_expr FOLLOWING.
value_expr PRECEDING or value_expr FOLLOWING For RANGE or ROW:
■ If value_expr FOLLOWING is the start point, then the end point must be value_
expr FOLLOWING.
■ If value_expr PRECEDING is the end point, then the start point must be value_
expr PRECEDING.
If you are defining a logical window defined by an interval of time in numeric format,
then you may need to use conversion functions.
If you specified ROWS:
■ value_expr is a physical offset. It must be a constant or expression and must
evaluate to a positive numeric value.
■ If value_expr is part of the start point, then it must evaluate to a row before the
end point.
If you specified RANGE:
■ value_expr is a logical offset. It must be a constant or expression that evaluates
to a positive numeric value or an interval literal. Refer to "Literals" on page 3-45
for information on interval literals.
■ You can specify only one expression in the order_by_clause
■ If value_expr evaluates to a numeric value, then the ORDER BY expr must be a
numeric or DATE data type.
■ If value_expr evaluates to an interval value, then the ORDER BY expr must be a
DATE data type.
If you omit the windowing_clause entirely, then the default is RANGE BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW.
Analytic functions are commonly used in data warehousing environments. In the list
of analytic functions that follows, functions followed by an asterisk (*) allow the full
syntax, including the windowing_clause.
AVG *
CORR *
See Also: NUMTOYMINTERVAL on page 5-126 and
NUMTODSINTERVAL on page 5-125 for information on converting
numeric times into intervals
Object Reference Functions
5-16 Oracle Database SQL Language Reference
COVAR_POP *
COVAR_SAMP *
COUNT *
CUME_DIST
DENSE_RANK
FIRST
FIRST_VALUE *
LAG
LAST
LAST_VALUE *
LEAD
MAX *
MIN *
NTH_VALUE*
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
REGR_ (Linear Regression) Functions *
ROW_NUMBER
STDDEV *
STDDEV_POP *
STDDEV_SAMP *
SUM *
VAR_POP *
VAR_SAMP *
VARIANCE *
Object Reference Functions
Object reference functions manipulate REF values, which are references to objects of
specified object types. The object reference functions are:
DEREF
MAKE_REF
REF
REFTOHEX
VALUE
Model Functions
Model functions can be used only in the model_clause of the SELECT statement.
The model functions are:
CV
ITERATION_NUMBER
PRESENTNNV
PRESENTV
See Also: Oracle Database Data Warehousing Guide for more
information on these functions and for scenarios illustrating their use
See Also: Oracle Database Object-Relational Developer's Guide for more
information about REF data types
Alphabetical Listing of SQL Functions
Functions 5-17
PREVIOUS
Alphabetical Listing of SQL Functions
The SQL functions are described in alphabetical order.
ABS
5-18 Oracle Database SQL Language Reference
ABS
Syntax
Purpose
ABS returns the absolute value of n.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
Examples
The following example returns the absolute value of -15:
SELECT ABS(-15) "Absolute" FROM DUAL;
Absolute
----------
15
ACOS
Syntax
Purpose
ACOS returns the arc cosine of n. The argument n must be in the range of -1 to 1, and
the function returns a value in the range of 0 to pi, expressed in radians.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the arc cosine of .3:
SELECT ACOS(.3)"Arc_Cosine" FROM DUAL;
Arc_Cosine
----------
1.26610367
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
ABS ( n )
ACOS ( n )
APPENDCHILDXML
Functions 5-19
ADD_MONTHS
Syntax
Purpose
ADD_MONTHS returns the date date plus integer months. A month is defined by the
session parameter NLS_CALENDAR. The date argument can be a datetime value or any
value that can be implicitly converted to DATE. The integer argument can be an
integer or any value that can be implicitly converted to an integer. The return type is
always DATE, regardless of the data type of date. If date is the last day of the month
or if the resulting month has fewer days than the day component of date, then the
result is the last day of the resulting month. Otherwise, the result has the same day
component as date.
Examples
The following example returns the month after the hire_date in the sample table
employees:
SELECT TO_CHAR(
ADD_MONTHS(hire_date,1),
'DD-MON-YYYY') "Next month"
FROM employees
WHERE last_name = 'Baer';
Next Month
-----------
07-JUL-2002
APPENDCHILDXML
Syntax
Purpose
APPENDCHILDXML appends a user-supplied value onto the target XML as the child of
the node indicated by an XPath expression.
■ XMLType_instance is an instance of XMLType.
■ The XPath_string is an Xpath expression indicating one or more nodes onto
which one or more child nodes are to be appended. You can specify an absolute
XPath_string with an initial slash or a relative XPath_string by omitting the
initial slash. If you omit the initial slash, then the context of the relative path
defaults to the root node.
■ The value_expr specifies one or more nodes of XMLType. It must resolve to a
string.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
ADD_MONTHS ( date , integer )
APPENDCHILDXML ( XMLType_instance , XPath_string , value_expr
, namespace_string
)
ASCII
5-20 Oracle Database SQL Language Reference
■ The optional namespace_string provides namespace information for the
XPath_string. This parameter must be of type VARCHAR2.
Examples
The following example adds an /Owner node to the /Warehouse/Building node of
warehouse_spec in the oe.warehouses table if the value of the /Building node
is "Rented":
UPDATE warehouses SET warehouse_spec =
APPENDCHILDXML(warehouse_spec,
'Warehouse/Building',
XMLType('<Owner>Grandco</Owner>'))
WHERE EXTRACTVALUE(warehouse_spec, '/Warehouse/Building') = 'Rented';
SELECT warehouse_id, warehouse_name,
EXTRACTVALUE(warehouse_spec, '/Warehouse/Building/Owner') "Prop.Owner"
FROM warehouses
WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Building/Owner') = 1;
WAREHOUSE_ID WAREHOUSE_NAME Prop.Owner
------------ --------------- ----------
2 San Francisco Grandco
3 New Jersey Grandco
ASCII
Syntax
Purpose
ASCII returns the decimal representation in the database character set of the first
character of char.
char can be of data type CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value
returned is of data type NUMBER. If your database character set is 7-bit ASCII, then this
function returns an ASCII value. If your database character set is EBCDIC Code, then
this function returns an EBCDIC value. There is no corresponding EBCDIC character
function.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example returns employees whose last names begin with the letter L,
whose ASCII equivalent is 76:
SELECT last_name FROM employees
WHERE ASCII(SUBSTR(last_name, 1, 1,)) = 76;
LAST_NAME
See Also: Oracle XML DB Developer's Guide for more information
about this function
See Also: "Data Type Comparison Rules" on page 3-37 for more
information
ASCII ( char )
ASIN
Functions 5-21
-------------------------
Ladwig
Landry
Lee
Livingston
ASCIISTR
Syntax
Purpose
ASCIISTR takes as its argument a string, or an expression that resolves to a string, in
any character set and returns an ASCII version of the string in the database character
set. Non-ASCII characters are converted to the form xxxx, where xxxx represents a
UTF-16 code unit.
Examples
The following example returns the ASCII string equivalent of the text string "ABÄCDE":
SELECT ASCIISTR('ABÄCDE') FROM DUAL;
ASCIISTR('
----------
AB00C4CDE
ASIN
Syntax
Purpose
ASIN returns the arc sine of n. The argument n must be in the range of -1 to 1, and the
function returns a value in the range of -pi/2 to pi/2, expressed in radians.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the arc sine of .3:
SELECT ASIN(.3) "Arc_Sine" FROM DUAL;
Arc_Sine
See Also: Oracle Database Globalization Support Guide for information
on Unicode character sets and character semantics
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
ASCIISTR ( char )
ASIN ( n )
ATAN
5-22 Oracle Database SQL Language Reference
----------
.304692654
ATAN
Syntax
Purpose
ATAN returns the arc tangent of n. The argument n can be in an unbounded range and
returns a value in the range of -pi/2 to pi/2, expressed in radians.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the arc tangent of .3:
SELECT ATAN(.3) "Arc_Tangent" FROM DUAL;
Arc_Tangent
----------
.291456794
ATAN2
Syntax
Purpose
ATAN2 returns the arc tangent of n1 and n2. The argument n1 can be in an unbounded
range and returns a value in the range of -pi to pi, depending on the signs of n1 and
n2, expressed in radians. ATAN2(n1,n2) is the same as ATAN(n1/n2).
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. If any argument is BINARY_
FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise
the function returns NUMBER.
Examples
The following example returns the arc tangent of .3 and .2:
See Also: ATAN2 on page 5-22 for information about the ATAN2
function and Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: ATAN on page 5-22 for information on the ATAN function
and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for
more information on implicit conversion
ATAN ( n )
ATAN2 ( n1 , n2 )
AVG
Functions 5-23
SELECT ATAN2(.3, .2) "Arc_Tangent2" FROM DUAL;
Arc_Tangent2
------------
.982793723
AVG
Syntax
Purpose
AVG returns average value of expr.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
If you specify DISTINCT, then you can specify only the query_partition_clause
of the analytic_clause. The order_by_clause and windowing_clause are not
allowed.
Aggregate Example
The following example calculates the average salary of all employees in the
hr.employees table:
SELECT AVG(salary) "Average" FROM employees;
Average
--------------
6461.68224
Analytic Example
The following example calculates, for each employee in the employees table, the
average salary of the employees reporting to the same manager who were hired in the
range just before through just after the employee:
SELECT manager_id, last_name, hire_date, salary,
AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS c_mavg
FROM employees
ORDER BY manager_id, hire_date, salary, c_mavg;
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
AVG (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
BFILENAME
5-24 Oracle Database SQL Language Reference
MANAGER_ID LAST_NAME HIRE_DATE SALARY C_MAVG
---------- ------------------------- --------- ---------- ----------
100 De Haan 13-JAN-01 17000 14000
100 Raphaely 07-DEC-02 11000 11966.6667
100 Kaufling 01-MAY-03 7900 10633.3333
100 Hartstein 17-FEB-04 13000 9633.33333
100 Weiss 18-JUL-04 8000 11666.6667
100 Russell 01-OCT-04 14000 11833.3333
100 Partners 05-JAN-05 13500 13166.6667
100 Errazuriz 10-MAR-05 12000 11233.3333
. . .
BFILENAME
Syntax
Purpose
BFILENAME returns a BFILE locator that is associated with a physical LOB binary file
on the server file system.
■ 'directory' is a database object that serves as an alias for a full path name on the
server file system where the files are actually located.
■ 'filename' is the name of the file in the server file system.
You must create the directory object and associate a BFILE value with a physical file
before you can use them as arguments to BFILENAME in a SQL or PL/SQL statement,
DBMS_LOB package, or OCI operation.
You can use this function in two ways:
■ In a DML statement to initialize a BFILE column
■ In a programmatic interface to access BFILE data by assigning a value to the
BFILE locator.
The directory argument is case sensitive. You must ensure that you specify the
directory object name exactly as it exists in the data dictionary. For example, if an
"Admin" directory object was created using mixed case and a quoted identifier in the
CREATE DIRECTORY statement, then when using the BFILENAME function you must
refer to the directory object as 'Admin'. You must specify the filename argument
according to the case and punctuation conventions for your operating system.
Examples
The following example inserts a row into the sample table pm.print_media. The
example uses the BFILENAME function to identify a binary file on the server file
system in the directory /demo/schema/product_media. The example shows how
the directory database object media_dir was created in the PM schema.
See Also:
■ Oracle Database SecureFiles and Large Objects Developer's Guide and
Oracle Call Interface Programmer's Guide for more information on
LOBs and for examples of retrieving BFILE data
■ CREATE DIRECTORY on page 14-42
BFILENAME ( ’ directory ’ , ’ filename ’ )
BIN_TO_NUM
Functions 5-25
CREATE DIRECTORY media_dir AS '/demo/schema/product_media';
INSERT INTO print_media (product_id, ad_id, ad_graphic)
VALUES (3000, 31001,
BFILENAME('MEDIA_DIR', 'modem_comp_ad.gif'));
BIN_TO_NUM
Syntax
Purpose
BIN_TO_NUM converts a bit vector to its equivalent number. Each argument to this
function represents a bit in the bit vector. This function takes as arguments any
numeric data type, or any nonnumeric data type that can be implicitly converted to
NUMBER. Each expr must evaluate to 0 or 1. This function returns Oracle NUMBER.
BIN_TO_NUM is useful in data warehousing applications for selecting groups of
interest from a materialized view using grouping sets.
Examples
The following example converts a binary value to a number:
SELECT BIN_TO_NUM(1,0,1,0) FROM DUAL;
BIN_TO_NUM(1,0,1,0)
-------------------
10
The next example converts three values into a single binary value and uses BIN_TO_
NUM to convert that binary into a number. The example uses a PL/SQL declaration to
specify the original values. These would normally be derived from actual data sources.
SELECT order_status FROM orders WHERE order_id = 2441;
ORDER_STATUS
------------
5
DECLARE
warehouse NUMBER := 1;
ground NUMBER := 1;
insured NUMBER := 1;
result NUMBER;
BEGIN
SELECT BIN_TO_NUM(warehouse, ground, insured) INTO result FROM DUAL;
See Also:
■ group_by_clause on page 19-27 for information on GROUPING SETS
syntax
■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for
more information on implicit conversion
■ Oracle Database Data Warehousing Guide for information on data
aggregation in general
BIN_TO_NUM ( expr
,
)
BITAND
5-26 Oracle Database SQL Language Reference
UPDATE orders SET order_status = result WHERE order_id = 2441;
end;
/
PL/SQL procedure successfully completed.
SELECT order_status FROM orders WHERE order_id = 2441;
ORDER_STATUS
------------
7
Refer to the examples for BITAND on page 5-26 for information on reversing this
process, extracting multiple values from a single column value.
BITAND
Syntax
Purpose
The BITAND function treats its inputs and its output as vectors of bits; the output is the
bitwise AND of the inputs.
The types of expr1 and expr2 are NUMBER, and the result is of type NUMBER. If either
argument to BITAND is NULL, the result is NULL.
The arguments must be in the range -(2(n-1)
) .. ((2(n-1)
)-1). If an argument is out of this
range, the result is undefined.
The result is computed in several steps. First, each argument A is replaced with the
value SIGN(A)*FLOOR(ABS(A)). This conversion has the effect of truncating each
argument towards zero. Next, each argument A (which must now be an integer value)
is converted to an n-bit two's complement binary integer value. The two bit values are
combined using a bitwise AND operation. Finally, the resulting n-bit two's complement
value is converted back to NUMBER.
Notes on the BITAND Function
■ The current implementation of BITAND defines n = 128.
■ PL/SQL supports an overload of BITAND for which the types of the inputs and of
the result are all BINARY_INTEGER and for which n = 32.
Examples
The following example performs an AND operation on the numbers 6 (binary 1,1,0) and
3 (binary 0,1,1):
SELECT BITAND(6,3) FROM DUAL;
BITAND(6,3)
-----------
2
This is the same as the following example, which shows the binary values of 6 and 3.
The BITAND function operates only on the significant digits of the binary values:
SELECT BITAND(
BIN_TO_NUM(1,1,0),
BITAND ( expr1 , expr2 )
CARDINALITY
Functions 5-27
BIN_TO_NUM(0,1,1)) "Binary"
FROM DUAL;
Binary
----------
2
Refer to the example for BIN_TO_NUM on page 5-25 for information on encoding
multiple values in a single column value.
The following example supposes that the order_status column of the sample table
oe.orders encodes several choices as individual bits within a single numeric value.
For example, an order still in the warehouse is represented by a binary value 001
(decimal 1). An order being sent by ground transportation is represented by a binary
value 010 (decimal 2). An insured package is represented by a binary value 100
(decimal 4). The example uses the DECODE function to provide two values for each of
the three bits in the order_status value, one value if the bit is turned on and one if
it is turned off.
SELECT order_id, customer_id, order_status,
DECODE(BITAND(order_status, 1), 1, 'Warehouse', 'PostOffice')
"Location",
DECODE(BITAND(order_status, 2), 2, 'Ground', 'Air') "Method",
DECODE(BITAND(order_status, 4), 4, 'Insured', 'Certified') "Receipt"
FROM orders
WHERE sales_rep_id = 160
ORDER BY order_id;
ORDER_ID CUSTOMER_ID ORDER_STATUS Location Method Receipt
---------- ----------- ------------ ---------- ------ ---------
2455 145 7 Warehouse Ground Insured
2416 104 6 PostOffice Ground Insured
2419 107 3 Warehouse Ground Certified
2420 108 2 PostOffice Ground Certified
2423 145 3 Warehouse Ground Certified
2441 106 5 Warehouse Air Insured
For the Location column, BITAND first compares order_status with 1 (binary
001). Only significant bit values are compared, so any binary value with a 1 in its
rightmost bit (any odd number) will evaluate positively and return 1. Even numbers
will return 0. The DECODE function compares the value returned by BITAND with 1. If
they are both 1, then the location is "Warehouse". If they are different, then the location
is "PostOffice".
The Method and Receipt columns are calculated similarly. For Method, BITAND
performs the AND operation on order_status and 2 (binary 010). For Receipt,
BITAND performs the AND operation on order_status and 4 (binary 100).
CARDINALITY
Syntax
CARDINALITY ( nested_table )
CAST
5-28 Oracle Database SQL Language Reference
Purpose
CARDINALITY returns the number of elements in a nested table. The return type is
NUMBER. If the nested table is empty, or is a null collection, then CARDINALITY returns
NULL.
Examples
The following example shows the number of elements in the nested table column ad_
textdocs_ntab of the sample table pm.print_media:
SELECT product_id, CARDINALITY(ad_textdocs_ntab) Cardinality
FROM print_media
ORDER BY product_id, cardinality;
PRODUCT_ID CARDINALITY
---------- -----------
2056 3
2268 3
3060 3
3106 3
CAST
Syntax
Purpose
CAST converts one built-in data type or collection-typed value into another built-in
data type or collection-typed value.
CAST lets you convert built-in data types or collection-typed values of one type into
another built-in data type or collection type. You can cast an unnamed operand (such
as a date or the result set of a subquery) or a named collection (such as a varray or a
nested table) into a type-compatible data type or named collection. The type_name
must be the name of a built-in data type or collection type and the operand must be a
built-in data type or must evaluate to a collection value.
For the operand, expr can be either a built-in data type, a collection type, or an
instance of an ANYDATA type. If expr is an instance of an ANYDATA type, then CAST
tries to extract the value of the ANYDATA instance and return it if it matches the cast
target type, otherwise, null will be returned. MULTISET informs Oracle Database to
take the result set of the subquery and return a collection value. Table 5–1 shows
which built-in data types can be cast into which other built-in data types. (CAST does
not support LONG, LONG RAW, or the Oracle-supplied types.)
CAST does not directly support any of the LOB data types. When you use CAST to
convert a CLOB value into a character data type or a BLOB value into the RAW data
type, the database implicitly converts the LOB value to character or raw data and then
explicitly casts the resulting value into the target data type. If the resulting value is
larger than the target type, then the database returns an error.
When you use CAST ... MULTISET to get a collection value, each select list item in the
query passed to the CAST function is converted to the corresponding attribute type of
the target collection element type.
CAST (
expr
MULTISET ( subquery )
AS type_name )
CAST
Functions 5-29
Note 1: Datetime/interval includes DATE, TIMESTAMP, TIMESTAMP WITH
TIMEZONE, INTERVAL DAY TO SECOND, and INTERVAL YEAR TO MONTH.
Note 2: You cannot cast a UROWID to a ROWID if the UROWID contains the value of a
ROWID of an index-organized table.
If you want to cast a named collection type into another named collection type, then
the elements of both collections must be of the same type.
If the result set of subquery can evaluate to multiple rows, then you must specify the
MULTISET keyword. The rows resulting from the subquery form the elements of the
collection value into which they are cast. Without the MULTISET keyword, the
subquery is treated as a scalar subquery.
Built-In Data Type Examples
The following examples use the CAST function with scalar data types. The first
example converts text to a timestamp value by applying the format model provided in
the session parameter NLS_TIMESTAMP_FORMAT. If you want to avoid dependency on
this NLS parameter, then you can use the TO_DATE as shown in the second example.
SELECT CAST('22-OCT-1997' AS TIMESTAMP WITH LOCAL TIME ZONE)
FROM dual;
SELECT CAST(TO_DATE('22-Oct-1997', 'DD-Mon-YYYY') AS
TIMESTAMP WITH LOCAL TIME ZONE) FROM dual;
In the preceding example, TO_DATE converts from text to DATE, and CAST converts
from DATE to TIMESTAMP WITH LOCAL TIME ZONE, interpreting the date in the
session time zone (SESSIONTIMEZONE)
SELECT product_id,
CAST(ad_sourcetext AS VARCHAR2(30)) Text
FROM print_media
Table 5–1 Casting Built-In Data Types
from
BINARY_
FLOAT,
BINARY_
DOUBLE
from
CHAR,
VARCHAR2
from
NUMBER
from
DATETIME /
INTERVAL
(Note 1)
from
RAW
from ROWID,
UROWID
(Note 2)
from
NCHAR,
NVARCHAR2
to BINARY_FLOAT,
BINARY_DOUBLE
X X X -- -- -- X
to CHAR,
VARCHAR2
X X X X X X --
to NUMBER X X X -- -- -- X
to DATE,
TIMESTAMP,
INTERVAL
-- X -- X -- -- --
to RAW -- X -- -- X -- --
to ROWID, UROWID -- X -- -- -- Xa --
to NCHAR,
NVARCHAR2
X -- X X X X X
See Also: "Implicit Data Conversion" on page 3-40 for information
on how Oracle Database implicitly converts collection type data into
character data and "Security Considerations for Data Conversion" on
page 3-44
CAST
5-30 Oracle Database SQL Language Reference
ORDER BY product_id, text;
Collection Examples
The CAST examples that follow build on the cust_address_typ found in the sample
order entry schema, oe.
CREATE TYPE address_book_t AS TABLE OF cust_address_typ;
/
CREATE TYPE address_array_t AS VARRAY(3) OF cust_address_typ;
/
CREATE TABLE cust_address (
custno NUMBER,
street_address VARCHAR2(40),
postal_code VARCHAR2(10),
city VARCHAR2(30),
state_province VARCHAR2(10),
country_id CHAR(2));
CREATE TABLE cust_short (custno NUMBER, name VARCHAR2(31));
CREATE TABLE states (state_id NUMBER, addresses address_array_t);
This example casts a subquery:
SELECT s.custno, s.name,
CAST(MULTISET(SELECT ca.street_address,
ca.postal_code,
ca.city,
ca.state_province,
ca.country_id
FROM cust_address ca
WHERE s.custno = ca.custno)
AS address_book_t)
FROM cust_short s
ORDER BY s.custno, s.name;
CAST converts a varray type column into a nested table:
SELECT CAST(s.addresses AS address_book_t)
FROM states s
WHERE s.state_id = 111;
The following objects create the basis of the example that follows:
CREATE TABLE projects
(employee_id NUMBER, project_name VARCHAR2(10));
CREATE TABLE emps_short
(employee_id NUMBER, last_name VARCHAR2(10));
CREATE TYPE project_table_typ AS TABLE OF VARCHAR2(10);
/
The following example of a MULTISET expression uses these objects:
SELECT e.last_name,
CAST(MULTISET(SELECT p.project_name
FROM projects p
WHERE p.employee_id = e.employee_id
ORDER BY p.project_name)
AS project_table_typ)
FROM emps_short e
CHARTOROWID
Functions 5-31
ORDER BY e.last_name;
CEIL
Syntax
Purpose
CEIL returns smallest integer greater than or equal to n. The number n can always be
written as the difference of an integer k and a positive fraction f such that 0 <= f < 1
and n = k - f. The value of CEIL is the integer k. Thus, the value of CEIL is n itself if
and only if n is precisely an integer.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
Examples
The following example returns the smallest integer greater than or equal to the order
total of a specified order:
SELECT order_total, CEIL(order_total) FROM orders
WHERE order_id = 2434;
ORDER_TOTAL CEIL(ORDER_TOTAL)
----------- -----------------
268651.8 268652
CHARTOROWID
Syntax
Purpose
CHARTOROWID converts a value from CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data
type to ROWID data type.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example converts a character rowid representation to a rowid. (The
actual rowid is different for each database instance.)
SELECT last_name FROM employees
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and FLOOR on
page 5-80
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
CEIL ( n )
CHARTOROWID ( char )
CHR
5-32 Oracle Database SQL Language Reference
WHERE ROWID = CHARTOROWID('AAAFd1AAFAAAABSAA/');
LAST_NAME
-------------------------
Greene
CHR
Syntax
Purpose
CHR returns the character having the binary equivalent to n as a VARCHAR2 value in
either the database character set or, if you specify USING NCHAR_CS, the national
character set.
For single-byte character sets, if n > 256, then Oracle Database returns the binary
equivalent of n mod 256. For multibyte character sets, n must resolve to one entire
code point. Invalid code points are not validated, and the result of specifying invalid
code points is indeterminate.
This function takes as an argument a NUMBER value, or any value that can be implicitly
converted to NUMBER, and returns a character.
Examples
The following example is run on an ASCII-based machine with the database character
set defined as WE8ISO8859P1:
SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL;
Dog
---
CAT
To produce the same results on an EBCDIC-based machine with the WE8EBCDIC1047
character set, the preceding example would have to be modified as follows:
SELECT CHR(195)||CHR(193)||CHR(227) "Dog"
FROM DUAL;
Dog
---
CAT
Note: Use of the CHR function (either with or without the optional
USING NCHAR_CS clause) results in code that is not portable between
ASCII- and EBCDIC-based machine architectures.
See Also: NCHR on page 5-114 and Table 3–10, " Implicit Type
Conversion Matrix" on page 3-41 for more information on implicit
conversion
CHR ( n
USING NCHAR_CS
)
CLUSTER_ID
Functions 5-33
For multibyte character sets, this sort of concatenation gives different results. For
example, given a multibyte character whose hexadecimal value is a1a2 (a1
representing the first byte and a2 the second byte), you must specify for n the decimal
equivalent of 'a1a2', or 41378:
SELECT CHR(41378) FROM DUAL;
You cannot specify the decimal equivalent of a1 concatenated with the decimal
equivalent of a2, as in the following example:
SELECT CHR(161)||CHR(162) FROM DUAL;
However, you can concatenate whole multibyte code points, as in the following
example, which concatenates the multibyte characters whose hexadecimal values are
a1a2 and a1a3:
SELECT CHR(41378)||CHR(41379) FROM DUAL;
The following example assumes that the national character set is UTF16:
SELECT CHR (196 USING NCHAR_CS) FROM DUAL;
CH
--
Ä
CLUSTER_ID
Syntax
mining_attribute_clause::=
Purpose
This function is for use with clustering models that have been created using the DBMS_
DATA_MINING package or with the Oracle Data Mining Java API. It returns the cluster
identifier of the predicted cluster with the highest probability for the set of predictors
specified in the mining_attribute_clause. The value returned is an Oracle
NUMBER.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
CLUSTER_ID (
schema .
model mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
CLUSTER_PROBABILITY
5-34 Oracle Database SQL Language Reference
Examples
The following example lists the clusters into which customers of a given dataset have
been grouped.
This example, and the prerequisite data mining operations, including the creation of
the dm_sh_clus_sample model and the dm_sh_sample_apply_prepared view,
can be found in the demo file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql.
General information on data mining demo files is available in Oracle Data Mining
Administrator's Guide. The example is presented here to illustrate the syntactic use of
the function.
SELECT CLUSTER_ID(km_sh_clus_sample USING *) AS clus, COUNT(*) AS cnt
FROM km_sh_sample_apply_prepared
GROUP BY CLUSTER_ID(km_sh_clus_sample USING *)
ORDER BY cnt DESC;
CLUS CNT
---------- ----------
2 580
10 199
6 185
8 115
12 98
16 82
19 81
15 68
18 65
14 27
10 rows selected.
CLUSTER_PROBABILITY
Syntax
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ PREDICTION on page 5-139
CLUSTER_PROBABILITY (
schema .
model
, cluster_id
mining_attribute_clause )
CLUSTER_PROBABILITY
Functions 5-35
mining_attribute_clause::=
Purpose
This function is for use with clustering models that have been created with the DBMS_
DATA_MINING package or with the Oracle Data Mining Java API. It returns a measure
of the degree of confidence of membership of an input row in a cluster associated with
the specified model.
■ For cluster_id, specify the identifier of the cluster in the model. The function
returns the probability for the specified cluster. If you omit this clause, then the
function returns the probability associated with the best predicted cluster. You can
use the form without cluster_id in conjunction with the CLUSTER_ID function
to obtain the best predicted pair of cluster ID and probability.
■ The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140
Examples
The following example determines the ten most representative customers, based on
likelihood, in cluster 2.
This example, and the prerequisite data mining operations, including the creation of
the dm_sh_clus_sample model and the dm_sh_sample_apply_prepared view,
can be found in the demo file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql.
General information on data mining demo files is available in Oracle Data Mining
Administrator's Guide. The example is presented here to illustrate the syntactic use of
the function.
SELECT *
FROM (SELECT cust_id, CLUSTER_PROBABILITY(km_sh_clus_sample, 2 USING *) prob
FROM km_sh_sample_apply_prepared
ORDER BY prob DESC)
WHERE ROWNUM < 11;
CUST_ID PROB
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ CLUSTER_ID on page 5-33 and PREDICTION on page 5-139 for
information on related data mining functions
USING
*
schema .
table . *
expr
AS alias
,
CLUSTER_SET
5-36 Oracle Database SQL Language Reference
---------- ------
100052 .9993
100962 .9993
101208 .9993
100281 .9993
100012 .9993
101009 .9992
100173 .9992
101176 .9991
100672 .9991
101420 .9991
10 rows selected.
CLUSTER_SET
Syntax
mining_attribute_clause::=
Purpose
This function is for use with clustering models that have been created with the DBMS_
DATA_MINING package or with the Oracle Data Mining Java API. It returns a varray of
objects containing all possible clusters that a given row belongs to. Each object in the
varray is a pair of scalar values containing the cluster ID and the cluster probability.
The object fields are named CLUSTER_ID and PROBABILITY, and both are Oracle
NUMBER.
■ For the optional topN argument, specify a positive integer. Doing so restricts the
set of predicted clusters to those that have one of the top N probability values. If
you omit topN or set it to NULL, then all clusters are returned in the collection. If
multiple clusters are tied for the Nth value, the database still returns only N
values.
■ For the optional cutoff argument, specify a positive integer to restrict the
returned clusters to those with a probability greater than or equal to the specified
cutoff. You can filter only by cutoff by specifying NULL for topN and the desired
cutoff value for cutoff.
You can specify topN and cutoff together to restrict the returned clusters to those
that are in the top N and have a probability that passes the threshold.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
CLUSTER_SET (
schema .
model
, topN
, cutoff
mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
CLUSTER_SET
Functions 5-37
Examples
The following example lists the most relevant attributes (with confidence > 55%) of
each cluster to which customer 101362 belongs with > 20% likelihood.
This example, and the prerequisite data mining operations, including the creation of
the dm_sh_clus_sample model and the views and type, can be found in the demo
file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql. General information on data
mining demo files is available in Oracle Data Mining Administrator's Guide. The
example is presented here to illustrate the syntactic use of the function.
WITH
clus_tab AS (
SELECT id,
A.attribute_name aname,
A.conditional_operator op,
NVL(A.attribute_str_value,
ROUND(DECODE(A.attribute_name, N.col,
A.attribute_num_value * N.scale + N.shift,
A.attribute_num_value),4)) val,
A.attribute_support support,
A.attribute_confidence confidence
FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_KM('km_sh_clus_sample')) T,
TABLE(T.rule.antecedent) A,
km_sh_sample_norm N
WHERE A.attribute_name = N.col (+) AND A.attribute_confidence > 0.55
),
clust AS (
SELECT id,
CAST(COLLECT(Cattr(aname, op, TO_CHAR(val), support, confidence))
AS Cattrs) cl_attrs
FROM clus_tab
GROUP BY id
),
custclus AS (
SELECT T.cust_id, S.cluster_id, S.probability
FROM (SELECT cust_id, CLUSTER_SET(km_sh_clus_sample, NULL, 0.2 USING *) pset
FROM km_sh_sample_apply_prepared
WHERE cust_id = 101362) T,
TABLE(T.pset) S
)
SELECT A.probability prob, A.cluster_id cl_id,
B.attr, B.op, B.val, B.supp, B.conf
FROM custclus A,
(SELECT T.id, C.*
FROM clust T,
TABLE(T.cl_attrs) C) B
WHERE A.cluster_id = B.id
ORDER BY prob DESC, cl_id ASC, conf DESC, attr ASC, val ASC;
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
COALESCE
5-38 Oracle Database SQL Language Reference
PROB CL_ID ATTR OP VAL SUPP CONF
------- ---------- --------------- --- --------------- ---------- -------
.7873 8 HOUSEHOLD_SIZE IN 9+ 126 .7500
.7873 8 CUST_MARITAL_ST IN Divorc. 118 .6000
ATUS
.7873 8 CUST_MARITAL_ST IN NeverM 118 .6000
ATUS
.7873 8 CUST_MARITAL_ST IN Separ. 118 .6000
ATUS
.7873 8 CUST_MARITAL_ST IN Widowed 118 .6000
ATUS
.2016 6 AGE >= 17 152 .6667
.2016 6 AGE <= 31.6 152 .6667
.2016 6 CUST_MARITAL_ST IN NeverM 168 .6667
ATUS
8 rows selected.
COALESCE
Syntax
Purpose
COALESCE returns the first non-null expr in the expression list. You must specify at
least two expressions. If all occurrences of expr evaluate to null, then the function
returns null.
Oracle Database uses short-circuit evaluation. The database evaluates each expr
value and determines whether it is NULL, rather than evaluating all of the expr values
before determining whether any of them is NULL.
If all occurrences of expr are numeric data type or any nonnumeric data type that can
be implicitly converted to a numeric data type, then Oracle Database determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
This function is a generalization of the NVL function.
You can also use COALESCE as a variety of the CASE expression. For example,
COALESCE (expr1, expr2)
is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
COALESCE ( expr
,
)
COLLECT
Functions 5-39
Similarly,
COALESCE (expr1, expr2, ..., exprn), for n>=3
is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1
ELSE COALESCE (expr2, ..., exprn) END
Examples
The following example uses the sample oe.product_information table to
organize a clearance sale of products. It gives a 10% discount to all products with a list
price. If there is no list price, then the sale price is the minimum price. If there is no
minimum price, then the sale price is "5":
SELECT product_id, list_price, min_price,
COALESCE(0.9*list_price, min_price, 5) "Sale"
FROM product_information
WHERE supplier_id = 102050
ORDER BY product_id;
PRODUCT_ID LIST_PRICE MIN_PRICE Sale
---------- ---------- ---------- ----------
1769 48 43.2
1770 73 73
2378 305 247 274.5
2382 850 731 765
3355 5
COLLECT
Syntax
Purpose
COLLECT is an aggregate function that takes as its argument a column of any type and
creates a nested table of the input type out of the rows selected. To get accurate results
from this function you must use it within a CAST function.
If column is itself a collection, then the output of COLLECT is a nested table of
collections. If column is of a user-defined type, then column must have a MAP or
ORDER method defined on it in order for you to use the optional DISTINCT, UNIQUE
and ORDER BY clauses.
Examples
The following example creates a nested table from the varray column of phone
numbers in the sample table oe.customers:
CREATE TYPE phone_book_t AS TABLE OF phone_list_typ;
See Also: NVL on page 5-126 and "CASE Expressions" on page 6-5
See Also: CAST on page 5-28 and "Aggregate Functions" on
page 5-9
COLLECT (
DISTINCT
UNIQUE
column
ORDER BY expr
)
COMPOSE
5-40 Oracle Database SQL Language Reference
/
SELECT CAST(COLLECT(phone_numbers) AS phone_book_t) Phone_Book
FROM customers
ORDER BY phone_book;
COMPOSE
Syntax
Purpose
COMPOSE takes as its argument a string, or an expression that resolves to a string, in
any data type, and returns a Unicode string in the same character set as the input.
char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB. For example, an o code point qualified by an umlaut code point will be
returned as the o-umlaut code point.
COMPOSE returns the string in NFC normal form. For a more exclusive setting, you can
first call DECOMPOSE with the CANONICAL setting and then COMPOSE. This
combination returns the string in NFKC normal form.
CLOB and NCLOB values are supported through implicit conversion. If char is a
character LOB value, then it is converted to a VARCHAR value before the COMPOSE
operation. The operation will fail if the size of the LOB value exceeds the supported
length of the VARCHAR in the particular development environment.
Examples
The following example returns the o-umlaut code point:
SELECT COMPOSE ( 'o' || UNISTR('0308') ) FROM DUAL;
CO
--
ö
CONCAT
Syntax
Purpose
CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any
of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string
See Also:
■ Oracle Database Globalization Support Guide for information on
Unicode character sets and character semantics
■ DECOMPOSE on page 5-59
See Also: UNISTR on page 5-239
COMPOSE ( char )
CONCAT ( char1 , char2 )
CONVERT
Functions 5-41
returned is in the same character set as char1. Its data type depends on the data types
of the arguments.
In concatenations of two different data types, Oracle Database returns the data type
that results in a lossless conversion. Therefore, if one of the arguments is a LOB, then
the returned value is a LOB. If one of the arguments is a national data type, then the
returned value is a national data type. For example:
■ CONCAT(CLOB, NCLOB) returns NCLOB
■ CONCAT(NCLOB, NCHAR) returns NCLOB
■ CONCAT(NCLOB, CHAR) returns NCLOB
■ CONCAT(NCHAR, CLOB) returns NCLOB
This function is equivalent to the concatenation operator (||).
Examples
This example uses nesting to concatenate three character strings:
SELECT CONCAT(CONCAT(last_name, '''s job category is '),
job_id) "Job"
FROM employees
WHERE employee_id = 152
ORDER BY "Job";
Job
------------------------------------------------------
Hall's job category is SA_REP
CONVERT
Syntax
Purpose
CONVERT converts a character string from one character set to another.
■ The char argument is the value to be converted. It can be any of the data types
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
■ The dest_char_set argument is the name of the character set to which char is
converted.
■ The source_char_set argument is the name of the character set in which char
is stored in the database. The default value is the database character set.
The return value for CHAR and VARCHAR2 is VARCHAR2. For NCHAR and NVARCHAR2,
it is NVARCHAR2. For CLOB, it is CLOB, and for NCLOB, it is NCLOB.
Both the destination and source character set arguments can be either literals or
columns containing the name of the character set.
For complete correspondence in character conversion, it is essential that the
destination character set contains a representation of all the characters defined in the
See Also: "Concatenation Operator" on page 4-4 for information on
the CONCAT operator
CONVERT ( char , dest_char_set
, source_char_set
)
CONVERT
5-42 Oracle Database SQL Language Reference
source character set. Where a character does not exist in the destination character set, a
replacement character appears. Replacement characters can be defined as part of a
character set definition.
Examples
The following example illustrates character set conversion by converting a Latin-1
string to ASCII. The result is the same as importing the same string from a
WE8ISO8859P1 database to a US7ASCII database.
SELECT CONVERT('Ä Ê Í Õ Ø A B C D E ', 'US7ASCII', 'WE8ISO8859P1')
FROM DUAL;
CONVERT('ÄÊÍÕØABCDE'
---------------------
A E I ? ? A B C D E ?
Common character sets include:
■ US7ASCII: US 7-bit ASCII character set
■ WE8ISO8859P1: ISO 8859-1 West European 8-bit character set
■ EE8MSWIN1250: Microsoft Windows East European Code Page 1250
■ WE8MSWIN1252: Microsoft Windows West European Code Page 1252
■ WE8EBCDIC1047: IBM West European EBCDIC Code Page 1047
■ JA16SJISTILDE: Japanese Shift-JIS Character Set, compatible with MS Code Page
932
■ ZHT16MSWIN950: Microsoft Windows Traditional Chinese Code Page 950
■ UTF8: Unicode 3.0 Universal character set CESU-8 encoding form
■ AL32UTF8: Unicode 5.0 Universal character set UTF-8 encoding form
You can query the V$NLS_VALID_VALUES view to get a listing of valid character sets,
as follows:
SELECT * FROM V$NLS_VALID_VALUES WHERE parameter = 'CHARACTERSET'
Note: Oracle discourages the use of the CONVERT function in the
current Oracle Database release. The return value of CONVERT has a
character data type, so it should be either in the database character set
or in the national character set, depending on the data type. Any
dest_char_set that is not one of these two character sets is
unsupported. The char argument and the source_char_set have
the same requirements. Therefore, the only practical use of the
function is to correct data that has been stored in a wrong character
set.
Values that are in neither the database nor the national character set
should be processed and stored as RAW or BLOB. Procedures in the
PL/SQL packages UTL_RAW and UTL_I18N—for example, UTL_
RAW.CONVERT—allow limited processing of such values. Procedures
accepting RAW argument in the packages UTL_FILE, UTL_TCP, UTL_
HTTP, and UTL_SMTP can be used to output the processed data.
CORR
Functions 5-43
CORR
Syntax
Purpose
CORR returns the coefficient of correlation of a set of number pairs. You can use it as an
aggregate or analytic function.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
Oracle Database applies the function to the set of (expr1, expr2) after eliminating the
pairs for which either expr1 or expr2 is null. Then Oracle makes the following
computation:
COVAR_POP(expr1, expr2) / (STDDEV_POP(expr1) * STDDEV_POP(expr2))
The function returns a value of type NUMBER. If the function is applied to an empty set,
then it returns null.
Aggregate Example
The following example calculates the coefficient of correlation between the list prices
and minimum prices of products by weight class in the sample table oe.product_
information:
SELECT weight_class, CORR(list_price, min_price) "Correlation"
See Also: Oracle Database Globalization Support Guide for information
on supported character sets and Oracle Database Reference for
information on the V$NLS_VALID_VALUES view
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
Note: The CORR function calculates the Pearson's correlation
coefficient, which requires numeric expressions as arguments. Oracle
also provides the CORR_S (Spearman's rho coefficient) and CORR_K
(Kendall's tau-b coefficient) to support nonparametric or rank
correlation.
See Also: "Aggregate Functions" on page 5-9, "About SQL
Expressions" on page 6-1 for information on valid forms of expr, and
CORR_* on page 5-44 and CORR_S on page 5-45
CORR ( expr1 , expr2 )
OVER ( analytic_clause )
CORR_*
5-44 Oracle Database SQL Language Reference
FROM product_information
GROUP BY weight_class
ORDER BY weight_class, "Correlation";
WEIGHT_CLASS Correlation
------------ -----------
1 .999149795
2 .999022941
3 .998484472
4 .999359909
5 .999536087
Analytic Example
The following example shows the correlation between duration at the company and
salary by the employee's position. The result set shows the same correlation for each
employee in a given job:
SELECT employee_id, job_id,
TO_CHAR((SYSDATE - hire_date) YEAR TO MONTH ) "Yrs-Mns", salary,
CORR(SYSDATE-hire_date, salary)
OVER(PARTITION BY job_id) AS "Correlation"
FROM employees
WHERE department_id in (50, 80)
ORDER BY job_id, employee_id;
EMPLOYEE_ID JOB_ID Yrs-Mns SALARY Correlation
----------- ---------- ------- ---------- -----------
145 SA_MAN +04-09 14000 .912385598
146 SA_MAN +04-06 13500 .912385598
147 SA_MAN +04-04 12000 .912385598
148 SA_MAN +01-08 11000 .912385598
149 SA_MAN +01-05 10500 .912385598
150 SA_REP +04-05 10000 .80436755
151 SA_REP +04-03 9500 .80436755
152 SA_REP +03-10 9000 .80436755
153 SA_REP +03-03 8000 .80436755
154 SA_REP +02-07 7500 .80436755
155 SA_REP +01-07 7000 .80436755
...
CORR_*
The CORR_* functions are:
■ CORR_S
■ CORR_K
CORR_*
Functions 5-45
Syntax
correlation::=
Purpose
The CORR function (see CORR on page 5-43) calculates the Pearson's correlation
coefficient and requires numeric expressions as input. The CORR_* functions support
nonparametric or rank correlation. They let you find correlations between expressions
that are ordinal scaled (where ranking of the values is possible). Correlation
coefficients take on a value ranging from -1 to 1, where 1 indicates a perfect
relationship, -1 a perfect inverse relationship (when one variable increases as the other
decreases), and a value close to 0 means no relationship.
These functions takes as arguments any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. Oracle Database
determines the argument with the highest numeric precedence, implicitly converts the
remaining arguments to that data type, makes the calculation, and returns NUMBER.
expr1 and expr2 are the two variables being analyzed. The third argument is a
return value of type VARCHAR2. If you omit the third argument, then the default is
COEFFICIENT. The meaning of the return values is shown in the table that follows:
CORR_S
CORR_S calculates the Spearman's rho correlation coefficient. The input expressions
should be a set of (xi, yi) pairs of observations. The function first replaces each value
with a rank. Each value of xi is replaced with its rank among all the other xis in the
sample, and each value of yi is replaced with its rank among all the other yis. Thus,
each xi and yi take on a value from 1 to n, where n is the total number of pairs of
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
Table 5–2 CORR_* Return Values
Return Value Meaning
COEFFICIENT Coefficient of correlation
ONE_SIDED_SIG Positive one-tailed significance of the correlation
ONE_SIDED_SIG_POS Same as ONE_SIDED_SIG
ONE_SIDED_SIG_NEG Negative one-tailed significance of the correlation
TWO_SIDED_SIG Two-tailed significance of the correlation
CORR_K
CORR_S
( expr1 , expr2
,
COEFFICIENT
ONE_SIDED_SIG
ONE_SIDED_SIG_POS
ONE_SIDED_SIG_NEG
TWO_SIDED_SIG
)
CORR_K
5-46 Oracle Database SQL Language Reference
values. Ties are assigned the average of the ranks they would have had if their values
had been slightly different. Then the function calculates the linear correlation
coefficient of the ranks.
CORR_S Example Using Spearman's rho correlation coefficient, the following
example derives a coefficient of correlation for each of two different comparisons --
salary and commission_pct, and salary and employee_id:
SELECT COUNT(*) count,
CORR_S(salary, commission_pct) commission,
CORR_S(salary, employee_id) empid
FROM employees;
COUNT COMMISSION EMPID
---------- ---------- ----------
107 .735837022 -.04482358
CORR_K
CORR_K calculates the Kendall's tau-b correlation coefficient. As for CORR_S, the input
expressions are a set of (xi, yi) pairs of observations. To calculate the coefficient, the
function counts the number of concordant and discordant pairs. A pair of observations
is concordant if the observation with the larger x also has a larger value of y. A pair of
observations is discordant if the observation with the larger x has a smaller y.
The significance of tau-b is the probability that the correlation indicated by tau-b was
due to chance—a value of 0 to 1. A small value indicates a significant correlation for
positive values of tau-b (or anticorrelation for negative values of tau-b).
CORR_K Example Using Kendall's tau-b correlation coefficient, the following
example determines whether a correlation exists between an employee's salary and
commission percent:
SELECT CORR_K(salary, commission_pct, 'COEFFICIENT') coefficient,
CORR_K(salary, commission_pct, 'TWO_SIDED_SIG') two_sided_p_value
FROM hr.employees;
COEFFICIENT TWO_SIDED_P_VALUE
----------- -----------------
.603079768 3.4702E-07
COS
Syntax
Purpose
COS returns the cosine of n (an angle expressed in radians).
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
COS ( n )
COUNT
Functions 5-47
Examples
The following example returns the cosine of 180 degrees:
SELECT COS(180 * 3.14159265359/180)
"Cosine of 180 degrees" FROM DUAL;
Cosine of 180 degrees
---------------------
-1
COSH
Syntax
Purpose
COSH returns the hyperbolic cosine of n.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the hyperbolic cosine of zero:
SELECT COSH(0) "Hyperbolic cosine of 0" FROM DUAL;
Hyperbolic cosine of 0
----------------------
1
COUNT
Syntax
Purpose
COUNT returns the number of rows returned by the query. You can use it as an
aggregate or analytic function.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
COSH ( n )
COUNT (
*
DISTINCT
ALL
expr
)
OVER ( analytic_clause )
COUNT
5-48 Oracle Database SQL Language Reference
If you specify DISTINCT, then you can specify only the query_partition_clause
of the analytic_clause. The order_by_clause and windowing_clause are not
allowed.
If you specify expr, then COUNT returns the number of rows where expr is not null.
You can count either all rows, or only distinct values of expr.
If you specify the asterisk (*), then this function returns all rows, including duplicates
and nulls. COUNT never returns null.
Aggregate Examples
The following examples use COUNT as an aggregate function:
SELECT COUNT(*) "Total" FROM employees;
Total
----------
107
SELECT COUNT(*) "Allstars" FROM employees
WHERE commission_pct > 0;
Allstars
---------
35
SELECT COUNT(commission_pct) "Count" FROM employees;
Count
----------
35
SELECT COUNT(DISTINCT manager_id) "Managers" FROM employees;
Managers
----------
18
Analytic Example
The following example calculates, for each employee in the employees table, the
moving count of employees earning salaries in the range 50 less than through 150
greater than the employee's salary.
SELECT last_name, salary,
COUNT(*) OVER (ORDER BY salary RANGE BETWEEN 50 PRECEDING
AND 150 FOLLOWING) AS mov_count FROM employees
ORDER BY last_name, salary, COUNT(*);
LAST_NAME SALARY MOV_COUNT
------------------------- ---------- ----------
Olson 2100 3
Markle 2200 2
Philtanker 2200 2
Landry 2400 8
Gee 2400 8
Colmenares 2500 10
Marlow 2500 10
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
COVAR_POP
Functions 5-49
Patel 2500 10
. . .
COVAR_POP
Syntax
Purpose
COVAR_POP returns the population covariance of a set of number pairs. You can use it
as an aggregate or analytic function.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
Oracle Database applies the function to the set of (expr1, expr2) pairs after
eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the
following computation:
(SUM(expr1 * expr2) - SUM(expr2) * SUM(expr1) / n) / n
where n is the number of (expr1, expr2) pairs where neither expr1 nor expr2 is
null.
The function returns a value of type NUMBER. If the function is applied to an empty set,
then it returns null.
Aggregate Example
The following example calculates the population covariance and sample covariance for
time employed (SYSDATE - hire_date) and salary using the sample table
hr.employees:
SELECT job_id,
COVAR_POP(SYSDATE-hire_date, salary) AS covar_pop,
COVAR_SAMP(SYSDATE-hire_date, salary) AS covar_samp
FROM employees
WHERE department_id in (50, 80)
GROUP BY job_id
ORDER BY job_id, covar_pop, covar_samp;
JOB_ID COVAR_POP COVAR_SAMP
---------- ----------- -----------
SA_MAN 660700 825875
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
COVAR_POP ( expr1 , expr2 )
OVER ( analytic_clause )
COVAR_SAMP
5-50 Oracle Database SQL Language Reference
SA_REP 579988.466 600702.34
SH_CLERK 212432.5 223613.158
ST_CLERK 176577.25 185870.789
ST_MAN 436092 545115
Analytic Example
The following example calculates cumulative sample covariance of the list price and
minimum price of the products in the sample schema oe:
SELECT product_id, supplier_id,
COVAR_POP(list_price, min_price)
OVER (ORDER BY product_id, supplier_id)
AS CUM_COVP,
COVAR_SAMP(list_price, min_price)
OVER (ORDER BY product_id, supplier_id)
AS CUM_COVS
FROM product_information p
WHERE category_id = 29
ORDER BY product_id, supplier_id;
PRODUCT_ID SUPPLIER_ID CUM_COVP CUM_COVS
---------- ----------- ---------- ----------
1774 103088 0
1775 103087 1473.25 2946.5
1794 103096 1702.77778 2554.16667
1825 103093 1926.25 2568.33333
2004 103086 1591.4 1989.25
2005 103086 1512.5 1815
2416 103088 1475.97959 1721.97619
. . .
COVAR_SAMP
Syntax
Purpose
COVAR_SAMP returns the sample covariance of a set of number pairs. You can use it as
an aggregate or analytic function.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
COVAR_SAMP ( expr1 , expr2 )
OVER ( analytic_clause )
CUBE_TABLE
Functions 5-51
Oracle Database applies the function to the set of (expr1, expr2) pairs after
eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the
following computation:
(SUM(expr1 * expr2) - SUM(expr1) * SUM(expr2) / n) / (n-1)
where n is the number of (expr1, expr2) pairs where neither expr1 nor expr2 is
null.
The function returns a value of type NUMBER. If the function is applied to an empty set,
then it returns null.
Aggregate Example
Refer to the aggregate example for COVAR_POP on page 5-49.
Analytic Example
Refer to the analytic example for COVAR_POP on page 5-49.
CUBE_TABLE
Syntax
Purpose
CUBE_TABLE extracts data from a cube or dimension and returns it in the
two-dimensional format of a relational table, which can be used by SQL-based
applications.
The function takes a single VARCHAR2 argument. The optional hierarchy clause
enables you to specify a dimension hierarchy. A cube can have multiple hierarchy
clauses, one for each dimension.
You can generate these different types of tables:
■ A cube table contains a key column for each dimension and a column for each
measure and calculated measure in the cube. To create a cube table, you can
specify the cube with or without a cube hierarchy clause. For a dimension with
multiple hierarchies, this clause limits the return values to the dimension members
and levels in the specified hierarchy. Without a hierarchy clause, all dimension
members and all levels are included.
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
CUBE_TABLE
( ’
schema . cube
HIERARCHY
HRR
dimension hierarchy
schema . dimension
HIERARCHY
HRR
dimension
hierarchy
’ )
CUBE_TABLE
5-52 Oracle Database SQL Language Reference
■ A dimension table contains a key column, and a column for each level and each
attribute. All dimension members and all levels are included in the table. To create
a dimension table, specify the dimension without a dimension hierarchy clause.
■ A hierarchy table contains all the columns of a dimension table plus a column for
the parent member and a column for each source level. Any dimension members
and levels that are not part of the named hierarchy are excluded from the table. To
create a hierarchy table, specify the dimension with a dimension hierarchy clause.
CUBE_TABLE is a table function and is always used in the context of a SELECT
statement with this syntax:
SELECT ... FROM TABLE(CUBE_TABLE('arg'));
Examples
The following SELECT statement generates a dimension table of CHANNEL in the
GLOBAL schema.
SELECT * FROM TABLE(CUBE_TABLE('global.channel'));
DIM_KEY LEVEL_NAME LONG_DESCRIP SHORT_DESCRI TOTAL_CHANNEL_ID CHANNEL_ID
-------- --------------- ------------ ------------ ---------------- ----------
1 TOTAL_CHANNEL All Channels All Channels 1
2 CHANNEL Direct Sales Direct Sales 1 2
3 CHANNEL Catalog Catalog 1 3
4 CHANNEL Internet Internet 1 4
The next statement generates a cube table of UNITS_CUBE. It restricts the table to the
MARKET_ROLLUP and CALENDAR hierarchies.
SELECT * FROM TABLE(CUBE_TABLE(
'global.units_cube HIERARCHY customer market_rollup HIERARCHY time calendar'));
SALES UNITS COST TIME CUSTOMER PRODUCT CHANNEL
---------- ---------- ---------- -------- -------- -------- --------
134109248 330425 124918967 2 7 1 1
32275009.5 77425 30255208 10 7 1 1
10768750.7 25780 10058324.5 36 7 1 1
109261.64 278 101798.32 36 5 1 1
22371.47 53 20887.54 36 36 1 1
.
.
.
See Also: Oracle OLAP User's Guide for information about
dimensional objects and about the tables generated by CUBE_TABLE.
CUME_DIST
Functions 5-53
CUME_DIST
Aggregate Syntax
cume_dist_aggregate::=
Analytic Syntax
cume_dist_analytic::=
Purpose
CUME_DIST calculates the cumulative distribution of a value in a group of values. The
range of values returned by CUME_DIST is >0 to <=1. Tie values always evaluate to the
same cumulative distribution value.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle Database determines
the argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, makes the calculation, and returns NUMBER.
■ As an aggregate function, CUME_DIST calculates, for a hypothetical row r
identified by the arguments of the function and a corresponding sort specification,
the relative position of row r among the rows in the aggregation group. Oracle
makes this calculation as if the hypothetical row r were inserted into the group of
rows to be aggregated over. The arguments of the function identify a single
hypothetical row within each aggregate group. Therefore, they must all evaluate to
constant expressions within each aggregate group. The constant argument
expressions and the expressions in the ORDER BY clause of the aggregate match by
position. Therefore, the number of arguments must be the same and their types
must be compatible.
■ As an analytic function, CUME_DIST computes the relative position of a specified
value in a group of values. For a row r, assuming ascending ordering, the CUME_
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
CUME_DIST ( expr
,
) WITHIN GROUP
( ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
CUME_DIST ( ) OVER (
query_partition_clause
order_by_clause )
CURRENT_DATE
5-54 Oracle Database SQL Language Reference
DIST of r is the number of rows with values lower than or equal to the value of r,
divided by the number of rows being evaluated (the entire query result set or a
partition).
Aggregate Example
The following example calculates the cumulative distribution of a hypothetical
employee with a salary of $15,500 and commission rate of 5% among the employees in
the sample table oe.employees:
SELECT CUME_DIST(15500, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) "Cume-Dist of 15500"
FROM employees;
Cume-Dist of 15500
------------------
.972222222
Analytic Example
The following example calculates the salary percentile for each employee in the
purchasing division. For example, 40% of clerks have salaries less than or equal to
Himuro.
SELECT job_id, last_name, salary, CUME_DIST()
OVER (PARTITION BY job_id ORDER BY salary) AS cume_dist
FROM employees
WHERE job_id LIKE 'PU%'
ORDER BY job_id, last_name, salary, cume_dist;
JOB_ID LAST_NAME SALARY CUME_DIST
---------- ------------------------- ---------- ----------
PU_CLERK Baida 2900 .8
PU_CLERK Colmenares 2500 .2
PU_CLERK Himuro 2600 .4
PU_CLERK Khoo 3100 1
PU_CLERK Tobias 2800 .6
PU_MAN Raphaely 11000 1
CURRENT_DATE
Syntax
Purpose
CURRENT_DATE returns the current date in the session time zone, in a value in the
Gregorian calendar of data type DATE.
Examples
The following example illustrates that CURRENT_DATE is sensitive to the session time
zone:
ALTER SESSION SET TIME_ZONE = '-5:0';
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
SESSIONTIMEZONE CURRENT_DATE
CURRENT_DATE
CURRENT_TIMESTAMP
Functions 5-55
--------------- --------------------
-05:00 29-MAY-2000 13:14:03
ALTER SESSION SET TIME_ZONE = '-8:0';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-08:00 29-MAY-2000 10:14:33
CURRENT_TIMESTAMP
Syntax
Purpose
CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a
value of data type TIMESTAMP WITH TIME ZONE. The time zone offset reflects the
current local time of the SQL session. If you omit precision, then the default is 6. The
difference between this function and LOCALTIMESTAMP is that CURRENT_TIMESTAMP
returns a TIMESTAMP WITH TIME ZONE value while LOCALTIMESTAMP returns a
TIMESTAMP value.
In the optional argument, precision specifies the fractional second precision of the
time value returned.
Examples
The following example illustrates that CURRENT_TIMESTAMP is sensitive to the
session time zone:
ALTER SESSION SET TIME_ZONE = '-5:0';
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL;
SESSIONTIMEZONE CURRENT_TIMESTAMP
--------------- ---------------------------------------------------
-05:00 04-APR-00 01.17.56.917550 PM -05:00
ALTER SESSION SET TIME_ZONE = '-8:0';
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL;
SESSIONTIMEZONE CURRENT_TIMESTAMP
--------------- ----------------------------------------------------
-08:00 04-APR-00 10.18.21.366065 AM -08:00
When you use the CURRENT_TIMESTAMP with a format mask, take care that the
format mask matches the value returned by the function. For example, consider the
following table:
CREATE TABLE current_test (col1 TIMESTAMP WITH TIME ZONE);
The following statement fails because the mask does not include the TIME ZONE
portion of the type returned by the function:
See Also: LOCALTIMESTAMP on page 5-104
CURRENT_TIMESTAMP
( precision )
CV
5-56 Oracle Database SQL Language Reference
INSERT INTO current_test VALUES
(TO_TIMESTAMP_TZ(CURRENT_TIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM'));
The following statement uses the correct format mask to match the return type of
CURRENT_TIMESTAMP:
INSERT INTO current_test VALUES (TO_TIMESTAMP_TZ
(CURRENT_TIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM TZH:TZM'));
CV
Syntax
Purpose
The CV function can be used only in the model_clause of a SELECT statement and
then only on the right-hand side of a model rule. It returns the current value of a
dimension column or a partitioning column carried from the left-hand side to the
right-hand side of a rule. This function is used in the model_clause to provide
relative indexing with respect to the dimension column. The return type is that of the
data type of the dimension column. If you omit the argument, then it defaults to the
dimension column associated with the relative position of the function within the cell
reference.
The CV function can be used outside a cell reference. In this case, dimension_column
is required.
Example
The following example assigns the sum of the sales of the product represented by the
current value of the dimension column (Mouse Pad or Standard Mouse) for years 1999
and 2000 to the sales of that product for year 2001:
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s[FOR prod IN ('Mouse Pad', 'Standard Mouse'), 2001] =
s[CV( ), 1999] + s[CV( ), 2000]
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 3000.72
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for the syntax and semantics
CV (
dimension_column
)
DBTIMEZONE
Functions 5-57
France Mouse Pad 2001 6679.41
France Standard Mouse 1998 2390.83
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 1274.31
France Standard Mouse 2001 3554.76
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 7375.46
Germany Mouse Pad 2001 15721.9
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 2637.31
Germany Standard Mouse 2001 8900.45
16 rows selected.
The preceding example requires the view sales_view_ref. Refer to "The MODEL
clause: Examples" on page 19-45 to create this view.
DATAOBJ_TO_PARTITION
Syntax
Purpose
DATAOBJ_TO_PARTITION is useful only to Data Cartridge developers who are
performing data maintenance or query operations on system-partitioned tables that
are used to store domain index data. The DML or query operations are triggered by
corresponding operations on the base table of the domain index.
This function takes as arguments the name of the base table and the partition ID of the
base table partition, both of which are passed to the function by the appropriate
ODCIIndex method. The function returns the partition ID of the corresponding
system-partitioned table, which can be used to perform the operation (DML or query)
on that partition of the system-partitioned table.
DBTIMEZONE
Syntax
Purpose
DBTIMEZONE returns the value of the database time zone. The return type is a time
zone offset (a character type in the format '[+|-]TZH:TZM') or a time zone region
name, depending on how the user specified the database time zone value in the most
recent CREATE DATABASE or ALTER DATABASE statement.
See Also: Oracle Database Data Cartridge Developer's Guide for
information on the use of this function, including examples
DATAOBJ_TO_PARTITION ( table , partition_id )
DBTIMEZONE
DECODE
5-58 Oracle Database SQL Language Reference
Examples
The following example assumes that the database time zone is set to UTC time zone:
SELECT DBTIMEZONE FROM DUAL;
DBTIME
------
+00:00
DECODE
Syntax
Purpose
DECODE compares expr to each search value one by one. If expr is equal to a
search, then Oracle Database returns the corresponding result. If no match is
found, then Oracle returns default. If default is omitted, then Oracle returns null.
The arguments can be any of the numeric types (NUMBER, BINARY_FLOAT, or
BINARY_DOUBLE) or character types.
■ If expr and search are character data, then Oracle compares them using
nonpadded comparison semantics. expr, search, and result can be any of the
data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of
VARCHAR2 data type and is in the same character set as the first result
parameter.
■ If the first search-result pair are numeric, then Oracle compares all
search-result expressions and the first expr to determine the argument with
the highest numeric precedence, implicitly converts the remaining arguments to
that data type, and returns that data type.
The search, result, and default values can be derived from expressions. Oracle
Database uses short-circuit evaluation. The database evaluates each search value
only before comparing it to expr, rather than evaluating all search values before
comparing any of them with expr. Consequently, Oracle never evaluates a search if
a previous search is equal to expr.
Oracle automatically converts expr and each search value to the data type of the
first search value before comparing. Oracle automatically converts the return value
to the same data type as the first result. If the first result has the data type CHAR
or if the first result is null, then Oracle converts the return value to the data type
VARCHAR2.
In a DECODE function, Oracle considers two nulls to be equivalent. If expr is null, then
Oracle returns the result of the first search that is also null.
The maximum number of components in the DECODE function, including expr,
searches, results, and default, is 255.
DECODE ( expr , search , result
,
, default
)
DECOMPOSE
Functions 5-59
Examples
This example decodes the value warehouse_id. If warehouse_id is 1, then the
function returns 'Southlake'; if warehouse_id is 2, then it returns 'San
Francisco'; and so forth. If warehouse_id is not 1, 2, 3, or 4, then the function
returns 'Non domestic'.
SELECT product_id,
DECODE (warehouse_id, 1, 'Southlake',
2, 'San Francisco',
3, 'New Jersey',
4, 'Seattle',
'Non domestic') "Location"
FROM inventories
WHERE product_id < 1775
ORDER BY product_id, "Location";
DECOMPOSE
Syntax
Purpose
DECOMPOSE is valid only for Unicode characters. DECOMPOSE takes as its argument a
string in any data type and returns a Unicode string after decomposition in the same
character set as the input. For example, an o-umlaut code point will be returned as the
"o" code point followed by an umlaut code point.
■ string can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB.
■ CANONICAL causes canonical decomposition, which allows recomposition (for
example, with the COMPOSE function) to the original string. This is the default and
returns the string in NFD normal form.
■ COMPATIBILITY causes decomposition in compatibility mode. In this mode,
recomposition is not possible. This mode is useful, for example, when
decomposing half-width and full-width katakana characters, where recomposition
might not be desirable without external formatting or style information. It returns
the string in NFKD normal form.
See Also:
■ "Data Type Comparison Rules" on page 3-37 for information on
comparison semantics
■ "Data Conversion" on page 3-40 for information on data type
conversion in general
■ "Floating-Point Numbers" on page 3-12 for information on
floating-point comparison semantics
■ "Implicit and Explicit Data Conversion" on page 3-40 for
information on the drawbacks of implicit conversion
DECOMPOSE ( string
CANONICAL
COMPATIBILITY
)
DELETEXML
5-60 Oracle Database SQL Language Reference
CLOB and NCLOB values are supported through implicit conversion. If char is a
character LOB value, then it is converted to a VARCHAR value before the COMPOSE
operation. The operation will fail if the size of the LOB value exceeds the supported
length of the VARCHAR in the particular development environment.
Examples
The following example decomposes the string "Châteaux" into its component code
points:
SELECT DECOMPOSE ('Châteaux') FROM DUAL;
DECOMPOSE
---------
Cha^teaux
DELETEXML
Syntax
Purpose
DELETEXML deletes the node or nodes matched by the XPath expression in the target
XML.
■ XMLType_instance is an instance of XMLType.
■ The XPath_string is an Xpath expression indicating one or more nodes that are
to be deleted. You can specify an absolute XPath_string with an initial slash or
a relative XPath_string by omitting the initial slash. If you omit the initial slash,
then the context of the relative path defaults to the root node. Any child nodes of
the nodes specified by XPath_string are also deleted.
■ The optional namespace_string provides namespace information for the
XPath_string. This parameter must be of type VARCHAR2.
Examples
The following example removes the /Owner node from the warehouse_spec of one
of the warehouses modified in the example for APPENDCHILDXML on page 5-19:
UPDATE warehouses SET warehouse_spec =
See Also:
■ Oracle Database Globalization Support Guide for information on
Unicode character sets and character semantics
■ COMPOSE on page 5-40
Note: The results of this example can vary depending on the
character set of your operating system.
See Also: Oracle XML DB Developer's Guide for more information
about this function
DELETEXML ( XMLType_instance , XPath_string
, namespace_string
)
DENSE_RANK
Functions 5-61
DELETEXML(warehouse_spec,
'/Warehouse/Building/Owner')
WHERE warehouse_id = 2;
SELECT warehouse_id, warehouse_spec FROM warehouses
WHERE warehouse_id in (2,3);
ID WAREHOUSE_SPEC
---------- -----------------------------------
2 <?xml version="1.0"?>
<Warehouse>
<Building>Rented</Building>
<Area>50000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>Y</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Lot</Parking>
<VClearance>12 ft</VClearance>
</Warehouse>
3 <?xml version="1.0"?>
<Warehouse>
<Building>Rented
<Owner>Grandco</Owner>
<Owner>ThirdOwner</Owner>
<Owner>LesserCo</Owner>
</Building>
<Area>85700</Area>
<DockType/>
<WaterAccess>N</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Street</Parking>
<VClearance>11.5 ft</VClearance>
</Warehouse>
DENSE_RANK
Aggregate Syntax
dense_rank_aggregate::=
DENSE_RANK ( expr
,
) WITHIN GROUP
( ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
DENSE_RANK
5-62 Oracle Database SQL Language Reference
Analytic Syntax
dense_rank_analytic::=
Purpose
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the
rank as a NUMBER. The ranks are consecutive integers beginning with 1. The largest
rank value is the number of unique values returned by the query. Rank values are not
skipped in the event of ties. Rows with equal values for the ranking criteria receive the
same rank. This function is useful for top-N and bottom-N reporting.
This function accepts as arguments any numeric data type and returns NUMBER.
■ As an aggregate function, DENSE_RANK calculates the dense rank of a hypothetical
row identified by the arguments of the function with respect to a given sort
specification. The arguments of the function must all evaluate to constant
expressions within each aggregate group, because they identify a single row
within each group. The constant argument expressions and the expressions in the
order_by_clause of the aggregate match by position. Therefore, the number of
arguments must be the same and types must be compatible.
■ As an analytic function, DENSE_RANK computes the rank of each row returned
from a query with respect to the other rows, based on the values of the value_
exprs in the order_by_clause.
Aggregate Example
The following example computes the ranking of a hypothetical employee with the
salary $15,500 and a commission of 5% in the sample table oe.employees:
SELECT DENSE_RANK(15500, .05) WITHIN GROUP
(ORDER BY salary DESC, commission_pct) "Dense Rank"
FROM employees;
Dense Rank
-------------------
3
Analytic Example
The following statement selects the department name, employee name, and salary of
all employees who work in the human resources or purchasing department, and then
computes a rank for each unique salary in each of the two departments. The salaries
that are equal receive the same rank. Compare this example with the example for
RANK on page 5-153.
SELECT d.department_name, e.last_name, e.salary, DENSE_RANK()
OVER (PARTITION BY e.department_id ORDER BY e.salary) AS drank
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND d.department_id IN ('30', '40')
ORDER BY e.last_name, e.salary, d.department_name, drank;
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
DENSE_RANK ( ) OVER (
query_partition_clause
order_by_clause )
DEREF
Functions 5-63
DEPARTMENT_NAME LAST_NAME SALARY DRANK
c------------------------------ ------------------------- ---------- ----------
Purchasing Baida 2900 4
Purchasing Colmenares 2500 1
Purchasing Himuro 2600 2
Purchasing Khoo 3100 5
Human Resources Mavris 6500 1
Purchasing Raphaely 11000 6
Purchasing Tobias 2800 3
DEPTH
Syntax
Purpose
DEPTH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH
conditions. It returns the number of levels in the path specified by the UNDER_PATH
condition with the same correlation variable.
The correlation_integer can be any NUMBER integer. Use it to correlate this
ancillary function with its primary condition if the statement contains multiple
primary conditions. Values less than 1 are treated as 1.
Examples
The EQUALS_PATH and UNDER_PATH conditions can take two ancillary functions,
DEPTH and PATH. The following example shows the use of both ancillary functions.
The example assumes the existence of the XMLSchema warehouses.xsd (created in
"Using XML in SQL Statements" on page F-8).
SELECT PATH(1), DEPTH(2)
FROM RESOURCE_VIEW
WHERE UNDER_PATH(res, '/sys/schemas/OE', 1)=1
AND UNDER_PATH(res, '/sys/schemas/OE', 2)=1;
PATH(1) DEPTH(2)
-------------------------------- --------
/www.example.com 1
/www.example.com/xwarehouses.xsd 2
DEREF
Syntax
Purpose
DEREF returns the object reference of argument expr, where expr must return a REF
to an object. If you do not use this function in a query, then Oracle Database returns
the object ID of the REF instead, as shown in the example that follows.
See Also: EQUALS_PATH Condition on page 7-19, UNDER_PATH
Condition on page 7-20, and the related function PATH on page 5-131
DEPTH ( correlation_integer )
DEREF ( expr )
DUMP
5-64 Oracle Database SQL Language Reference
Examples
The sample schema oe contains an object type cust_address_typ. The "REF
Constraint Examples" on page 8-25 create a similar type, cust_address_typ_new,
and a table with one column that is a REF to the type. The following example shows
how to insert into such a column and how to use DEREF to extract information from
the column:
INSERT INTO address_table VALUES
('1 First', 'G45 EU8', 'Paris', 'CA', 'US');
INSERT INTO customer_addresses
SELECT 999, REF(a) FROM address_table a;
SELECT address FROM customer_addresses
ORDER BY address;
ADDRESS
--------------------------------------------------------------------------------
000022020876B2245DBE325C5FE03400400B40DCB176B2245DBE305C5FE03400400B40DCB1
SELECT DEREF(address) FROM customer_addresses;
DEREF(ADDRESS)(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
--------------------------------------------------------------------------------
CUST_ADDRESS_TYP('1 First', 'G45 EU8', 'Paris', 'CA', 'US')
DUMP
Syntax
Purpose
DUMP returns a VARCHAR2 value containing the data type code, length in bytes, and
internal representation of expr. The returned result is always in the database character
set. For the data type corresponding to each code, see Table 3–1, " Built-in Data Type
Summary" on page 3-6.
The argument return_fmt specifies the format of the return value and can have any
of the following values:
■ 8 returns result in octal notation.
■ 10 returns result in decimal notation.
■ 16 returns result in hexadecimal notation.
■ 17 returns each byte printed as a character if and only if it can be interpreted as a
printable character in the character set of the compiler—typically ASCII or
EBCDIC. Some ASCII control characters may be printed in the form ^X as well.
Otherwise the character is printed in hexidecimal notation. All NLS parameters
are ignored. Do not depend on any particular output format for DUMP with
return_fmt 17.
See Also: MAKE_REF on page 5-107
DUMP ( expr
, return_fmt
, start_position
, length
)
EMPTY_BLOB, EMPTY_CLOB
Functions 5-65
By default, the return value contains no character set information. To retrieve the
character set name of expr, add 1000 to any of the preceding format values. For
example, a return_fmt of 1008 returns the result in octal and provides the character
set name of expr.
The arguments start_position and length combine to determine which portion
of the internal representation to return. The default is to return the entire internal
representation in decimal notation.
If expr is null, then this function returns NULL.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following examples show how to extract dump information from a string
expression and a column:
SELECT DUMP('abc', 1016)
FROM DUAL;
DUMP('ABC',1016)
------------------------------------------
Typ=96 Len=3 CharacterSet=WE8DEC: 61,62,63
SELECT DUMP(last_name, 8, 3, 2) "OCTAL"
FROM employees
WHERE last_name = 'Hunold'
ORDER BY employee_id;
OCTAL
-------------------------------------------------------------------
Typ=1 Len=6: 156,157
SELECT DUMP(last_name, 10, 3, 2) "ASCII"
FROM employees
WHERE last_name = 'Hunold'
ORDER BY employee_id;
ASCII
--------------------------------------------------------------------
Typ=1 Len=6: 110,111
EMPTY_BLOB, EMPTY_CLOB
Syntax
empty_LOB::=
See Also: "Data Type Comparison Rules" on page 3-37 for more
information
EMPTY_BLOB
EMPTY_CLOB
( )
EXISTSNODE
5-66 Oracle Database SQL Language Reference
Purpose
EMPTY_BLOB and EMPTY_CLOB return an empty LOB locator that can be used to
initialize a LOB variable or, in an INSERT or UPDATE statement, to initialize a LOB
column or attribute to EMPTY. EMPTY means that the LOB is initialized, but not
populated with data.
Restriction on LOB Locators You cannot use the locator returned from this function
as a parameter to the DBMS_LOB package or the OCI.
Examples
The following example initializes the ad_photo column of the sample pm.print_
media table to EMPTY:
UPDATE print_media SET ad_photo = EMPTY_BLOB();
EXISTSNODE
Syntax
Purpose
EXISTSNODE determines whether traversal of an XML document using a specified
path results in any nodes. It takes as arguments the XMLType instance containing an
XML document and a VARCHAR2 XPath string designating a path. The optional
namespace_string must resolve to a VARCHAR2 value that specifies a default
mapping or namespace mapping for prefixes, which Oracle Database uses when
evaluating the XPath expression(s).
The namespace_string argument defaults to the namespace of the root element. If
you refer to any subelement in Xpath_string, then you must specify namespace_
string, and you must specify the "who" prefix in both of these arguments.
The return value is NUMBER:
■ 0 if no nodes remain after applying the XPath traversal on the document
■ 1 if any nodes remain
Note: An empty LOB is not the same as a null LOB, and an empty
CLOB is not the same as a LOB containing a string of 0 length. For
more information, see Oracle Database SecureFiles and Large Objects
Developer's Guide.
Note: The EXISTSNODE function is deprecated. It is still supported
for backward compatibility. However, Oracle recommends that you
use the XMLEXISTS function instead. See XMLEXISTS on page 5-257
for more information.
See Also: "Using XML in SQL Statements" on page F-8 for examples
that specify namespace_string and use the "who" prefix.
EXISTSNODE ( XMLType_instance , XPath_string
, namespace_string
)
EXP
Functions 5-67
Examples
The following example tests for the existence of the /Warehouse/Dock node in the
XML path of the warehouse_spec column of the sample table oe.warehouses:
SELECT warehouse_id, warehouse_name
FROM warehouses
WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Docks') = 1
ORDER BY warehouse_id, warehouse_name;
WAREHOUSE_ID WAREHOUSE_NAME
------------ -----------------------------------
1 Southlake, Texas
2 San Francisco
4 Seattle, Washington
EXP
Syntax
Purpose
EXP returns e raised to the nth power, where e = 2.71828183 ... The function returns a
value of the same type as the argument.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns e to the 4th power:
SELECT EXP(4) "e to the 4th power" FROM DUAL;
e to the 4th power
------------------
54.59815
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
EXP ( n )
EXTRACT (datetime)
5-68 Oracle Database SQL Language Reference
EXTRACT (datetime)
Syntax
extract_datetime::=
Purpose
EXTRACT extracts and returns the value of a specified datetime field from a datetime
or interval expression. The expr can be any expression that evaluates to a datetime or
interval data type compatible with the requested field:
■ If YEAR or MONTH is requested, then expr must evaluate to an expression of data
type DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL
TIME ZONE, or INTERVAL YEAR TO MONTH.
■ If DAY is requested, then expr must evaluate to an expression of data type DATE,
TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE,
or INTERVAL DAY TO SECOND.
■ If HOUR, MINUTE, or SECOND is requested, then expr must evaluate to an
expression of data type TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP
WITH LOCAL TIME ZONE, or INTERVAL DAY TO SECOND. DATE is not valid here,
because Oracle Database treats it as ANSI DATE data type, which has no time
fields.
■ If TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_ABBR, TIMEZONE_REGION,
or TIMEZONE_OFFSET is requested, then expr must evaluate to an expression of
data type TIMESTAMP WITH TIME ZONE or TIMESTAMP WITH LOCAL TIME ZONE.
EXTRACT interprets expr as an ANSI datetime data type. For example, EXTRACT
treats DATE not as legacy Oracle DATE but as ANSI DATE, without time elements.
Therefore, you can extract only YEAR, MONTH, and DAY from a DATE value. Likewise,
you can extract TIMEZONE_HOUR and TIMEZONE_MINUTE only from the TIMESTAMP
WITH TIME ZONE data type.
When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value
returned is a string containing the appropriate time zone region name or abbreviation.
When you extract any of the other values, the value returned is an integer representing
the datetime value in the Gregorian calendar. When extracting from a datetime with a
time zone value, the value returned is in UTC. For a listing of time zone region names
EXTRACT (
YEAR
MONTH
DAY
HOUR
MINUTE
SECOND
TIMEZONE_HOUR
TIMEZONE_MINUTE
TIMEZONE_REGION
TIMEZONE_ABBR
FROM expr )
EXTRACT (datetime)
Functions 5-69
and their corresponding abbreviations, query the V$TIMEZONE_NAMES dynamic
performance view.
This function can be very useful for manipulating datetime field values in very large
tables, as shown in the first example below.
Some combinations of datetime field and datetime or interval value expression result
in ambiguity. In these cases, Oracle Database returns UNKNOWN (see the examples that
follow for additional information).
Examples
The following example returns from the oe.orders table the number of orders
placed in each month:
SELECT EXTRACT(month FROM order_date) "Month",
COUNT(order_date) "No. of Orders"
FROM orders
GROUP BY EXTRACT(month FROM order_date)
ORDER BY "No. of Orders" DESC;
Month No. of Orders
---------- -------------
11 15
7 14
6 14
3 11
5 10
9 9
2 9
8 7
10 6
1 5
12 4
4 1
12 rows selected.
The following example returns the year 1998.
SELECT EXTRACT(YEAR FROM DATE '1998-03-07') FROM DUAL;
Note: Time zone region names are needed by the daylight saving
feature. These names are stored in two types of time zone files: one
large and one small. One of these files is the default file, depending
on your environment and the release of Oracle Database you are
using. For more information regarding time zone files and names,
see Oracle Database Globalization Support Guide.
See Also:
■ Oracle Database Globalization Support Guide for a complete listing of
the time zone region names in both files
■ "Datetime/Interval Arithmetic" on page 3-20 for a description of
datetime_value_expr and interval_value_expr
■ Oracle Database Reference for information on the dynamic
performance views
EXTRACT (XML)
5-70 Oracle Database SQL Language Reference
EXTRACT(YEARFROMDATE'1998-03-07')
---------------------------------
1998
The following example selects from the sample table hr.employees all employees
who were hired after 2007:
SELECT last_name, employee_id, hire_date
FROM employees
WHERE EXTRACT(YEAR FROM
TO_DATE(hire_date, 'DD-MON-RR')) > 2007
ORDER BY hire_date;
LAST_NAME EMPLOYEE_ID HIRE_DATE
------------------------- ----------- ---------
Johnson 179 04-JAN-08
Grant 199 13-JAN-08
Marvins 164 24-JAN-08
. . .
The following example results in ambiguity, so Oracle returns UNKNOWN:
SELECT EXTRACT(TIMEZONE_REGION
FROM TIMESTAMP '1999-01-01 10:00:00 -08:00')
FROM DUAL;
EXTRACT(TIMEZONE_REGIONFROMTIMESTAMP'1999-01-0110:00:00-08:00')
----------------------------------------------------------------
UNKNOWN
The ambiguity arises because the time zone numerical offset is provided in the
expression, and that numerical offset may map to more than one time zone region
name.
EXTRACT (XML)
Syntax
extract_xml::=
Purpose
EXTRACT (XML) is similar to the EXISTSNODE function. It applies a VARCHAR2 XPath
string and returns an XMLType instance containing an XML fragment. You can specify
an absolute XPath_string with an initial slash or a relative XPath_string by
omitting the initial slash. If you omit the initial slash, then the context of the relative
Note: The EXTRACT (XML) function is deprecated. It is still
supported for backward compatibility. However, Oracle recommends
that you use the XMLQUERY function instead. See XMLQUERY on
page 5-262 for more information.
EXTRACT ( XMLType_instance , XPath_string
, namespace_string
)
EXTRACTVALUE
Functions 5-71
path defaults to the root node. The optional namespace_string is required if the
XML you are handling uses a namespace prefix. This argument must resolve to a
VARCHAR2 value that specifies a default mapping or namespace mapping for prefixes,
which Oracle Database uses when evaluating the XPath expression(s).
Examples
The following example extracts the value of the /Warehouse/Dock node of the XML
path of the warehouse_spec column in the sample table oe.warehouses:
SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Docks')
"Number of Docks"
FROM warehouses
WHERE warehouse_spec IS NOT NULL
ORDER BY warehouse_name, "Number of Docks";
WAREHOUSE_NAME Number of Docks
------------------------- -------------------------
New Jersey
San Francisco <Docks>1</Docks>
Seattle, Washington <Docks>3</Docks>
Southlake, Texas <Docks>2</Docks>
Compare this example with the example for EXTRACTVALUE on page 5-71, which
returns the scalar value of the XML fragment.
EXTRACTVALUE
Syntax
The EXTRACTVALUE function takes as arguments an XMLType instance and an XPath
expression and returns a scalar value of the resultant node. The result must be a single
node and be either a text node, attribute, or element. If the result is an element, then
the element must have a single text node as its child, and it is this value that the
function returns. You can specify an absolute XPath_string with an initial slash or a
relative XPath_string by omitting the initial slash. If you omit the initial slash, the
context of the relative path defaults to the root node.
If the specified XPath points to a node with more than one child, or if the node pointed
to has a non-text node child, then Oracle returns an error. The optional namespace_
string must resolve to a VARCHAR2 value that specifies a default mapping or
namespace mapping for prefixes, which Oracle uses when evaluating the XPath
expression(s).
For documents based on XML schemas, if Oracle can infer the type of the return value,
then a scalar value of the appropriate type is returned. Otherwise, the result is of type
Note: The EXTRACTVALUE function is deprecated. It is still
supported for backward compatibility. However, Oracle recommends
that you use the XMLTABLE function, or the XMLCAST and XMLQUERY
functions instead. See XMLTABLE on page 5-267, XMLCAST on
page 5-250, and XMLQUERY on page 5-262 for more information.
EXTRACTVALUE ( XMLType_instance , XPath_string
, namespace_string
)
FEATURE_ID
5-72 Oracle Database SQL Language Reference
VARCHAR2. For documents that are not based on XML schemas, the return type is
always VARCHAR2.
Examples
The following example takes as input the same arguments as the example for
EXTRACT (XML) on page 5-70. Instead of returning an XML fragment, as does the
EXTRACT function, it returns the scalar value of the XML fragment:
SELECT warehouse_name,
EXTRACTVALUE(e.warehouse_spec, '/Warehouse/Docks')
"Docks"
FROM warehouses e
WHERE warehouse_spec IS NOT NULL;
WAREHOUSE_NAME Docks
-------------------- ------------
Southlake, Texas 2
San Francisco 1
New Jersey
Seattle, Washington 3
FEATURE_ID
Syntax
mining_attribute_clause:=
Purpose
This function is for use with feature extraction models that have been created using the
DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns an
Oracle NUMBER that is the identifier of the feature with the highest value in the row.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
FEATURE_ID (
schema .
model mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
FEATURE_SET
Functions 5-73
Examples
The following example lists the features and corresponding count of customers in a
dataset.
This example and the prerequisite data mining operations, including creation of the
nmf_sh_sample model and nmf_sh_sample_apply_prepared view, can be found
in the demo file $ORACLE_HOME/rdbms/demo/dmnmdemo.sql. General information
on data mining demo files is available in Oracle Data Mining Administrator's Guide. The
example is presented here to illustrate the syntactic use of the function.
SELECT FEATURE_ID(nmf_sh_sample USING *) AS feat, COUNT(*) AS cnt
FROM nmf_sh_sample_apply_prepared
GROUP BY FEATURE_ID(nmf_sh_sample USING *)
ORDER BY cnt DESC;
FEAT CNT
---------- ----------
7 1443
2 49
3 6
1 1
6 1
FEATURE_SET
Syntax
mining_attribute_clause:=
Purpose
This function is for use with feature extraction models that have been created using the
DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns a
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
FEATURE_SET (
schema .
model
, topN
, cutoff
mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
FEATURE_SET
5-74 Oracle Database SQL Language Reference
varray of objects containing all possible features. Each object in the varray is a pair of
scalar values containing the feature ID and the feature value. The object fields are
named FEATURE_ID and VALUE, and both are Oracle NUMBER.
The optional topN argument is a positive integer that restricts the set of features to
those that have one of the top N values. If there is a tie at the Nth value, then the
database still returns only N values. If you omit this argument, then the function
returns all features.
The optional cutoff argument restricts the returned features to only those that have a
feature value greater than or equal to the specified cutoff. To filter only by cutoff,
specify NULL for topN and the desired cutoff for cutoff.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
Examples
The following example lists the top features corresponding to a given customer record
(based on match quality), and determines the top attributes for each feature (based on
coefficient > 0.25).
This example and the prerequisite data mining operations, including the creation of
the model, views, and type, can be found in the demo file $ORACLE_
HOME/rdbms/demo/dmnmdemo.sql. General information on data mining demo files
is available in Oracle Data Mining Administrator's Guide. The example is presented here
to illustrate the syntactic use of the function.
WITH
feat_tab AS (
SELECT F.feature_id fid,
A.attribute_name attr,
TO_CHAR(A.attribute_value) val,
A.coefficient coeff
FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_NMF('nmf_sh_sample')) F,
TABLE(F.attribute_set) A
WHERE A.coefficient > 0.25
),
feat AS (
SELECT fid,
CAST(COLLECT(Featattr(attr, val, coeff))
AS Featattrs) f_attrs
FROM feat_tab
GROUP BY fid
),
cust_10_features AS (
SELECT T.cust_id, S.feature_id, S.value
FROM (SELECT cust_id, FEATURE_SET(nmf_sh_sample, 10 USING *) pset
FROM nmf_sh_sample_apply_prepared
WHERE cust_id = 100002) T,
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
FEATURE_VALUE
Functions 5-75
TABLE(T.pset) S
)
SELECT A.value, A.feature_id fid,
B.attr, B.val, B.coeff
FROM cust_10_features A,
(SELECT T.fid, F.*
FROM feat T,
TABLE(T.f_attrs) F) B
WHERE A.feature_id = B.fid
ORDER BY A.value DESC, A.feature_id ASC, coeff DESC, attr ASC, val ASC;
VALUE FID ATTR VAL COEFF
-------- ---- ------------------------- -------------------- -------
6.8409 7 YRS_RESIDENCE 1.3879
6.8409 7 BOOKKEEPING_APPLICATION .4388
6.8409 7 CUST_GENDER M .2956
6.8409 7 COUNTRY_NAME United States of Ame .2848
rica
6.4975 3 YRS_RESIDENCE 1.2668
6.4975 3 BOOKKEEPING_APPLICATION .3465
6.4975 3 COUNTRY_NAME United States of Ame .2927
rica
6.4886 2 YRS_RESIDENCE 1.3285
6.4886 2 CUST_GENDER M .2819
6.4886 2 PRINTER_SUPPLIES .2704
6.3953 4 YRS_RESIDENCE 1.2931
5.9640 6 YRS_RESIDENCE 1.1585
5.9640 6 HOME_THEATER_PACKAGE .2576
5.2424 5 YRS_RESIDENCE 1.0067
2.4714 8 YRS_RESIDENCE .3297
2.3559 1 YRS_RESIDENCE .2768
2.3559 1 FLAT_PANEL_MONITOR .2593
17 rows selected.
FEATURE_VALUE
Syntax
mining_attribute_clause:=
FEATURE_VALUE (
schema .
model
, feature_id
mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
FEATURE_VALUE
5-76 Oracle Database SQL Language Reference
Purpose
This function is for use with feature extraction models that have been created using the
DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns the
value of a given feature. If you omit the feature_id argument, then the function
returns the highest feature value. You can use this form in conjunction with the
FEATURE_ID function to obtain the largest feature/value combination.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
Examples
The following example lists the customers that correspond to feature 3, ordered by
match quality.
This example and the prerequisite data mining operations, including the creation of
the model and view, can be found in the demo file $ORACLE_
HOME/rdbms/demo/dmnmdemo.sql. General information on data mining demo files
is available in Oracle Data Mining Administrator's Guide. The example is presented here
to illustrate the syntactic use of the function.
SELECT *
FROM (SELECT cust_id, FEATURE_VALUE(nmf_sh_sample, 3 USING *) match_quality
FROM nmf_sh_sample_apply_prepared
ORDER BY match_quality DESC)
WHERE ROWNUM < 11;
CUST_ID MATCH_QUALITY
---------- -------------
100210 19.4101627
100962 15.2482251
101151 14.5685197
101499 14.4186292
100363 14.4037396
100372 14.3335148
100982 14.1716545
101039 14.1079914
100759 14.0913761
100953 14.0799737
10 rows selected.
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
FIRST
Functions 5-77
FIRST
Syntax
first::=
Purpose
FIRST and LAST are very similar functions. Both are aggregate and analytic functions
that operate on a set of values from a set of rows that rank as the FIRST or LAST with
respect to a given sorting specification. If only one row ranks as FIRST or LAST, then
the aggregate operates on the set with only one element.
If you omit the OVER clause, then the FIRST and LAST functions are treated as
aggregate functions. You can use these functions as analytic functions by specifying
the OVER clause. The query_partition_clause is the only part of the OVER clause
valid with these functions. If you include the OVER clause but omit the query_
partition_clause, then the function is treated as an analytic function, but the
window defined for analysis is the entire table.
These functions take as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
When you need a value from the first or last row of a sorted group, but the needed
value is not the sort key, the FIRST and LAST functions eliminate the need for
self-joins or views and enable better performance.
■ The aggregate_function argument is any one of the MIN, MAX, SUM, AVG,
COUNT, VARIANCE, or STDDEV functions. It operates on values from the rows that
rank either FIRST or LAST. If only one row ranks as FIRST or LAST, then the
aggregate operates on a singleton (nonaggregate) set.
■ The KEEP keyword is for semantic clarity. It qualifies aggregate_function,
indicating that only the FIRST or LAST values of aggregate_function will be
returned.
■ DENSE_RANK FIRST or DENSE_RANK LAST indicates that Oracle Database will
aggregate over only those rows with the minimum (FIRST) or the maximum
(LAST) dense rank (also called olympic rank).
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the ORDER BY clause and OVER
clause
aggregate_function KEEP
( DENSE_RANK FIRST ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
OVER (
query_partition_clause
)
FIRST
5-78 Oracle Database SQL Language Reference
Aggregate Example
The following example returns, within each department of the sample table
hr.employees, the minimum salary among the employees who make the lowest
commission and the maximum salary among the employees who make the highest
commission:
SELECT department_id,
MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) "Worst",
MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) "Best"
FROM employees
GROUP BY department_id
ORDER BY department_id, "Worst", "Best";
DEPARTMENT_ID Worst Best
------------- ---------- ----------
10 4400 4400
20 6000 13000
30 2500 11000
40 6500 6500
50 2100 8200
60 4200 9000
70 10000 10000
80 6100 14000
90 17000 24000
100 6900 12000
110 8300 12000
7000 7000
Analytic Example
The next example makes the same calculation as the previous example but returns the
result for each employee within the department:
SELECT last_name, department_id, salary,
MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct)
OVER (PARTITION BY department_id) "Worst",
MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct)
OVER (PARTITION BY department_id) "Best"
FROM employees
ORDER BY department_id, salary;
LAST_NAME DEPARTMENT_ID SALARY Worst Best
------------------- ------------- ---------- ---------- ----------
Whalen 10 4400 4400 4400
Fay 20 6000 6000 13000
Hartstein 20 13000 6000 13000
. . .
Gietz 110 8300 8300 12000
Higgins 110 12000 8300 12000
Grant 7000 7000 7000
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and LAST on
page 5-95
FIRST_VALUE
Functions 5-79
FIRST_VALUE
Syntax
Purpose
FIRST_VALUE is an analytic function. It returns the first value in an ordered set of
values. If the first value in the set is null, then the function returns NULL unless you
specify IGNORE NULLS. This setting is useful for data densification.
{RESPECT | IGNORE} NULLS determines whether null values of expr are included in
or eliminated from the calculation. The default is RESPECT NULLS. If you specify
IGNORE NULLS, then FIRST_VALUE returns the first non-null value in the set, or
NULL if all values are null.
{RESPECT | IGNORE} NULLS determines whether null values of expr are included in
or eliminated from the calculation. The default is RESPECT NULLS.
Refer to "Using Partitioned Outer Joins: Examples" on page 19-52 for
an example of data densification.
You cannot nest analytic functions by using FIRST_VALUE or any other analytic
function for expr. However, you can use other built-in function expressions for expr.
Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr.
Examples
The following example selects, for each employee in Department 90, the name of the
employee with the lowest salary.
SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS lowest_sal
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY employee_id)
ORDER BY department_id, last_name, salary, lowest_sal;
DEPARTMENT_ID LAST_NAME SALARY LOWEST_SAL
------------- ------------------------- ---------- -------------------------
90 De Haan 17000 Kochhar
90 King 24000 Kochhar
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of expr
Note: The two forms of this syntax have the same behavior. The top
branch is the ANSI format, which Oracle recommends. The bottom
branch is deprecated but is supported for backward compatibility.
FIRST_VALUE
( expr )
RESPECT
IGNORE
NULLS
( expr
RESPECT
IGNORE
NULLS
)
OVER ( analytic_clause )
FLOOR
5-80 Oracle Database SQL Language Reference
90 Kochhar 17000 Kochhar
The example illustrates the nondeterministic nature of the FIRST_VALUE function.
Kochhar and DeHaan have the same salary, so are in adjacent rows. Kochhar appears
first because the rows returned by the subquery are ordered by employee_id.
However, if the rows returned by the subquery are ordered by employee_id in
descending order, as in the next example, then the function returns a different value:
SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) as fv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER by employee_id DESC)
ORDER BY department_id, last_name, salary, fv;
DEPARTMENT_ID LAST_NAME SALARY FV
------------- ------------------------- ---------- -------------------------
90 De Haan 17000 De Haan
90 King 24000 De Haan
90 Kochhar 17000 De Haan
The following example shows how to make the FIRST_VALUE function deterministic
by ordering on a unique key.
SELECT department_id, last_name, salary, hire_date,
FIRST_VALUE(last_name) OVER
(ORDER BY salary ASC, hire_date ROWS UNBOUNDED PRECEDING) AS fv
FROM (SELECT * FROM employees
WHERE department_id = 90 ORDER BY employee_id DESC)
ORDER BY department_id, last_name, salary, hire_date;
DEPARTMENT_ID LAST_NAME SALARY HIRE_DATE FV
------------- --------------- ---------- --------- -------------------------
90 De Haan 17000 13-JAN-01 De Haan
90 King 24000 17-JUN-03 De Haan
90 Kochhar 17000 21-SEP-05 De Haan
When you use a logical offset (RANGE instead of ROWS), the function is deterministic.
When duplicates are found for the ORDER BY expression, the FIRST_VALUE is the
lowest value of expr:
SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
OVER (ORDER BY salary ASC RANGE UNBOUNDED PRECEDING) AS lowest_sal
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY employee_id);
DEPARTMENT_ID LAST_NAME SALARY LOWEST_SAL
------------- ------------------------- ---------- -------------------------
90 De Haan 17000 De Haan
90 Kochhar 17000 De Haan
90 King 24000 De Haan
3 rows selected.
FLOOR
Syntax
FLOOR ( n )
GREATEST
Functions 5-81
Purpose
FLOOR returns the largest integer equal to or less than n. The number n can always be
written as the sum of an integer k and a positive fraction f such that 0 <= f < 1 and n
= k + f. The value of FLOOR is the integer k. Thus, the value of FLOOR is n itself if and
only if n is precisely an integer.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
Examples
The following example returns the largest integer equal to or less than 15.7:
SELECT FLOOR(15.7) "Floor" FROM DUAL;
Floor
----------
15
FROM_TZ
Syntax
Purpose
FROM_TZ converts a timestamp value and a time zone to a TIMESTAMP WITH TIME
ZONE value. time_zone_value is a character string in the format 'TZH:TZM' or a
character expression that returns a string in TZR with optional TZD format.
Examples
The following example returns a timestamp value to TIMESTAMP WITH TIME ZONE:
SELECT FROM_TZ(TIMESTAMP '2000-03-28 08:00:00', '3:00')
FROM DUAL;
FROM_TZ(TIMESTAMP'2000-03-2808:00:00','3:00')
---------------------------------------------------------------
28-MAR-00 08.00.00 AM +03:00
GREATEST
Syntax
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and CEIL on
page 5-31
FROM_TZ ( timestamp_value , time_zone_value )
GREATEST ( expr
,
)
GROUP_ID
5-82 Oracle Database SQL Language Reference
Purpose
GREATEST returns the greatest of the list of one or more expressions. Oracle Database
uses the first expr to determine the return type. If the first expr is numeric, then
Oracle determines the argument with the highest numeric precedence, implicitly
converts the remaining arguments to that data type before the comparison, and returns
that data type. If the first expr is not numeric, then each expr after the first is
implicitly converted to the data type of the first expr before the comparison.
Oracle Database compares each expr using nonpadded comparison semantics. The
comparison is binary by default and is linguistic if the NLS_COMP parameter is set to
LINGUISTIC and the NLS_SORT parameter has a setting other than BINARY.
Character comparison is based on the numerical codes of the characters in the
database character set and is performed on whole strings treated as one sequence of
bytes, rather than character by character. If the value returned by this function is
character data, then its data type is VARCHAR2 if the first expr is a character data type
and NVARCHAR2 if the first expr is a national character data type.
Examples
The following statement selects the string with the greatest value:
SELECT GREATEST ('HARRY', 'HARRIOT', 'HAROLD')
"Greatest" FROM DUAL;
Greatest
--------
HARRY
GROUP_ID
Syntax
Purpose
GROUP_ID distinguishes duplicate groups resulting from a GROUP BY specification. It
is useful in filtering out duplicate groupings from the query result. It returns an Oracle
NUMBER to uniquely identify duplicate groups. This function is applicable only in a
SELECT statement that contains a GROUP BY clause.
If n duplicates exist for a particular grouping, then GROUP_ID returns numbers in the
range 0 to n-1.
Examples
The following example assigns the value 1 to the duplicate co.country_region
grouping from a query on the sample tables sh.countries and sh.sales:
See Also:
■ "Data Type Comparison Rules" on page 3-37 for more information
on character comparison
■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for
more information on implicit conversion and "Floating-Point
Numbers" on page 3-12 for information on binary-float
comparison semantics
GROUP_ID ( )
GROUPING
Functions 5-83
SELECT co.country_region, co.country_subregion,
SUM(s.amount_sold) "Revenue",
GROUP_ID() g
FROM sales s, customers c, countries co
WHERE s.cust_id = c.cust_id AND
c.country_id = co.country_id AND
s.time_id = '1-JAN-00' AND
co.country_region IN ('Americas', 'Europe')
GROUP BY GROUPING SETS ( (co.country_region, co.country_subregion), (co.country_
region, co.country_subregion) )
ORDER BY co.country_region, co.country_subregion, "Revenue", g;
COUNTRY_REGION COUNTRY_SUBREGION Revenue G
-------------------- ------------------------------ ---------- ----------
Americas Northern America 944.6 0
Americas 944.6 1
Europe Western Europe 566.39 0
Europe 566.39 1
To ensure that only rows with GROUP_ID < 1 are returned, add the following HAVING
clause to the end of the statement :
HAVING GROUP_ID() < 1
GROUPING
Syntax
Purpose
GROUPING distinguishes superaggregate rows from regular grouped rows. GROUP BY
extensions such as ROLLUP and CUBE produce superaggregate rows where the set of
all values is represented by null. Using the GROUPING function, you can distinguish a
null representing the set of all values in a superaggregate row from a null in a regular
row.
The expr in the GROUPING function must match one of the expressions in the GROUP
BY clause. The function returns a value of 1 if the value of expr in the row is a null
representing the set of all values. Otherwise, it returns zero. The data type of the value
returned by the GROUPING function is Oracle NUMBER. Refer to the SELECT group_by_
clause on page 19-27 for a discussion of these terms.
Examples
In the following example, which uses the sample tables hr.departments and
hr.employees, if the GROUPING function returns 1 (indicating a superaggregate row
rather than a regular row from the table), then the string "All Jobs" appears in the
"JOB" column instead of the null that would otherwise appear:
SELECT
DECODE(GROUPING(department_name), 1, 'All Departments', department_name) AS department,
DECODE(GROUPING(job_id), 1, 'All Jobs', job_id) AS job,
COUNT(*) "Total Empl",
AVG(salary) * 12 "Average Sal"
FROM employees e, departments d
WHERE d.department_id = e.department_id
GROUP BY ROLLUP (department_name, job_id)
GROUPING ( expr )
GROUPING_ID
5-84 Oracle Database SQL Language Reference
ORDER BY department, job, "Total Empl", "Average Sal";
DEPARTMENT JOB Total Empl Average Sal
------------------------------ ---------- ---------- -----------
Accounting AC_ACCOUNT 1 99600
Accounting AC_MGR 1 144000
Accounting All Jobs 2 121800
Administration AD_ASST 1 52800
Administration All Jobs 1 52800
All Departments All Jobs 106 77479.2453
Executive AD_PRES 1 288000
Executive AD_VP 2 204000
Executive All Jobs 3 232000
Finance All Jobs 6 103200
Finance FI_ACCOUNT 5 95040
. . .
GROUPING_ID
Syntax
Purpose
GROUPING_ID returns a number corresponding to the GROUPING bit vector associated
with a row. GROUPING_ID is applicable only in a SELECT statement that contains a
GROUP BY extension, such as ROLLUP or CUBE, and a GROUPING function. In queries
with many GROUP BY expressions, determining the GROUP BY level of a particular row
requires many GROUPING functions, which leads to cumbersome SQL. GROUPING_ID
is useful in these cases.
GROUPING_ID is functionally equivalent to taking the results of multiple GROUPING
functions and concatenating them into a bit vector (a string of ones and zeros). By
using GROUPING_ID you can avoid the need for multiple GROUPING functions and
make row filtering conditions easier to express. Row filtering is easier with
GROUPING_ID because the desired rows can be identified with a single condition of
GROUPING_ID = n. The function is especially useful when storing multiple levels of
aggregation in a single table.
Examples
The following example shows how to extract grouping IDs from a query of the sample
table sh.sales:
SELECT channel_id, promo_id, sum(amount_sold) s_sales,
GROUPING(channel_id) gc,
GROUPING(promo_id) gp,
GROUPING_ID(channel_id, promo_id) gcp,
GROUPING_ID(promo_id, channel_id) gpc
FROM sales
WHERE promo_id > 496
GROUP BY CUBE(channel_id, promo_id)
ORDER BY channel_id, promo_id, s_sales, gc;
CHANNEL_ID PROMO_ID S_SALES GC GP GCP GPC
---------- ---------- ---------- ---------- ---------- ---------- ----------
GROUPING_ID ( expr
,
)
INITCAP
Functions 5-85
2 999 25797563.2 0 0 0 0
2 25797563.2 0 1 1 2
3 999 55336945.1 0 0 0 0
3 55336945.1 0 1 1 2
4 999 13370012.5 0 0 0 0
4 13370012.5 0 1 1 2
999 94504520.8 1 0 2 1
94504520.8 1 1 3 3
HEXTORAW
Syntax
Purpose
HEXTORAW converts char containing hexadecimal digits in the CHAR, VARCHAR2,
NCHAR, or NVARCHAR2 data type to a raw value.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example creates a simple table with a raw column, and inserts a
hexadecimal value that has been converted to RAW:
CREATE TABLE test (raw_col RAW(10));
INSERT INTO test VALUES (HEXTORAW('7D'));
The following example converts hexadecimal digits to a raw value and casts the raw
value to VARCHAR2:
SELECT UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW('4041424344')) FROM DUAL;
UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW('4041424344'))
------------------------------------------------
@ABCD
INITCAP
Syntax
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
See Also: "RAW and LONG RAW Data Types" on page 3-24 and
RAWTOHEX on page 5-155
HEXTORAW ( char )
INITCAP ( char )
INSERTCHILDXML
5-86 Oracle Database SQL Language Reference
Purpose
INITCAP returns char, with the first letter of each word in uppercase, all other letters
in lowercase. Words are delimited by white space or characters that are not
alphanumeric.
char can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The
return value is the same data type as char. The database sets the case of the initial
characters based on the binary mapping defined for the underlying character set. For
linguistic-sensitive uppercase and lowercase, refer to NLS_INITCAP on page 5-118.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example capitalizes each word in the string:
SELECT INITCAP('the soap') "Capitals" FROM DUAL;
Capitals
---------
The Soap
INSERTCHILDXML
Syntax
Purpose
INSERTCHILDXML inserts a user-supplied value into the target XML at the node
indicated by the XPath expression. Compare this function with INSERTXMLBEFORE
on page 5-90.
■ XMLType_instance is an instance of XMLType.
■ The XPath_string is an Xpath expression indicating one or more nodes into
which the one or more child nodes are to be inserted. You can specify an absolute
XPath_string with an initial slash or a relative XPath_string by omitting the
initial slash. If you omit the initial slash, then the context of the relative path
defaults to the root node.
■ The child_expr specifies the one or more element or attribute nodes to be
inserted.
■ The value_expr is an fragment of XMLType that specifies one or more notes
being inserted. It must resolve to a string.
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
See Also: Oracle XML DB Developer's Guide for more information
about this function
INSERTCHILDXML
( XMLType_instance , XPath_string , child_expr , value_expr
, namespace_string
)
INSERTCHILDXMLAFTER
Functions 5-87
■ The optional namespace_string provides namespace information for the
XPath_string. This parameter must be of type VARCHAR2.
Examples
The following example adds a second /Owner node to the warehouse_spec of one
of the warehouses updated in the example for APPENDCHILDXML on page 5-19:
UPDATE warehouses SET warehouse_spec =
INSERTCHILDXML(warehouse_spec,
'/Warehouse/Building', 'Owner',
XMLType('<Owner>LesserCo</Owner>'))
WHERE warehouse_id = 3;
SELECT warehouse_spec FROM warehouses
WHERE warehouse_id = 3;
WAREHOUSE_SPEC
----------------------------------------------------------------------------
<?xml version="1.0"?>
<Warehouse>
<Building>Rented
<Owner>Grandco</Owner>
<Owner>LesserCo</Owner>
</Building>
<Area>85700</Area>
<DockType/>
<WaterAccess>N</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Street</Parking>
<VClearance>11.5 ft</VClearance>
</Warehouse>
INSERTCHILDXMLAFTER
Syntax
Purpose
INSERTXMLCHILDAFTER inserts one or more collection elements as children of target
parent elements. The insertion for each target occurs immediately after a specified
existing collection element. The existing XML document that is the target of the
insertion can be schema-based or non-schema-based.
■ The XMLType_instance identifies the XML data that is the target of the
insertion.
■ The XPath_string locates the parent elements within target-data; child-data is
inserted under each parent element.
■ The child_expr is a relative XPath 1.0 expression that locates the existing child
that will precede the inserted child-data. It must name a child element of the
element indicated by parent-xpath, and it can include a predicate.
INSERTCHILDXMLAFTER
( XMLType_instance , XPath_string , child_expr , value_expr
, namespace_string
)
INSERTCHILDXMLBEFORE
5-88 Oracle Database SQL Language Reference
■ The value_expr is the XMLType child element data to insert. Each top-level
element node in this argument must have the same data type as the element
indicated by child_expr.
■ The optional namespace_string specifies the namespace for the parent
elements, existing child element, and child element XML data to be inserted.
For more information about this function and its uses, including examples, see Oracle
XML DB Developer's Guide.
Examples
The following example is similar to that for INSERTCHILDXML, but it adds a third
/Owner node after the /Owner node added in the other example. The output of the
query has been formatted for readability.
UPDATE warehouses SET warehouse_spec =
INSERTCHILDXMLAFTER(warehouse_spec,
'/Warehouse/Building','Owner[2]',
XMLType('<Owner>ThirdOwner</Owner>'))
WHERE warehouse_id = 3;
SELECT warehouse_name, EXTRACT(warehouse_spec,
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;
WAREHOUSE_NAME Owners
----------------------------------- ------------------------------
New Jersey <Owner>LesserCo</Owner>
<Owner>GrandCo</Owner>
<Owner>ThirdOwner</Owner>
INSERTCHILDXMLBEFORE
Syntax
Purpose
INSERTXMLCHILDBEFORE inserts one or more collection elements as children of
target parent elements. The insertion for each target occurs immediately before a
specified existing collection element. The existing XML document that is the target of
the insertion can be schema-based or non-schema-based.
■ The XMLType_instance identifies the XML data that is the target of the
insertion.
■ The XPath_string locates the parent elements within target-data; child-data is
inserted under each parent element.
■ The child_expr is a relative XPath 1.0 expression that locates the existing child
that will follow the inserted child-data. It must name a child element of the
element indicated by parent-xpath, and it can include a predicate.
INSERTCHILDXMLBEFORE
( XMLType_instance , XPath_string , child_expr , value_expr
, namespace_string
)
INSERTXMLAFTER
Functions 5-89
■ The value_expr is the XMLType child element data to insert. Each top-level
element node in this argument must have the same data type as the element
indicated by child_expr.
■ The optional namespace_string specifies the namespace for the parent
elements, existing child element, and child element XML data to be inserted.
For more information about this function and its uses, including examples, see Oracle
XML DB Developer's Guide.
Examples
The following example is similar to that for INSERTCHILDXML, but it adds a third
/Owner node before the /Owner node added in the other example. The output of the
query has been formatted for readability.
UPDATE warehouses SET warehouse_spec =
INSERTCHILDXMLBEFORE(warehouse_spec,
'/Warehouse/Building','Owner[2]',
XMLType('<Owner>ThirdOwner</Owner>'))
WHERE warehouse_id = 3;
SELECT warehouse_name, EXTRACT(warehouse_spec,
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;
WAREHOUSE_NAME Owners
----------------------------------- ------------------------------
New Jersey <Owner>LesserCo</Owner>
<Owner>ThirdOwner</Owner>
<Owner>GrandCo</Owner>
INSERTXMLAFTER
Syntax
Purpose
INSERTXMLAFTER inserts one or more nodes of any kind immediately after a target
node that is not an attribute node. The XML document that is the target of the
insertion can be schema-based or non-schema-based. This function is similar to
insertXMLbefore, but it inserts after, not before, the target node.
■ XMLType_instance specifies the target node of the of the insertion.
■ XPath_string is an XPath 1.0 expression that locates in the target node zero or
more nodes of any kind except attribute nodes. XML-data is inserted immediately
after each of these nodes; that is, each node specified becomes the preceding
sibling node of a node specified in value_expr.
■ value_expr is the XML data to be inserted. You can specify one or more nodes of
any kind. The order of the nodes is preserved after the insertion.
■ namespace_string is the namespace for the target node.
For more information about this function and its uses, including examples, see Oracle
XML DB Developer's Guide.
INSERTXMLAFTER ( XMLType_instance , XPath_string , value_expr
, namespace_string
)
INSERTXMLBEFORE
5-90 Oracle Database SQL Language Reference
Examples
The following example is similar to that for INSERTCHILDXML, but it adds a third
/Owner node after the /Owner node added in the other example. The output of the
query has been formatted for readability.
UPDATE warehouses SET warehouse_spec =
INSERTXMLAFTER(warehouse_spec,
'/Warehouse/Building/Owner[1]',
XMLType('<Owner>SecondOwner</Owner>'))
WHERE warehouse_id = 3;
SELECT warehouse_name, EXTRACT(warehouse_spec,
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;
INSERTXMLBEFORE
Syntax
Purpose
INSERTXMLBEFORE inserts a user-supplied value into the target XML before the node
indicated by the XPath expression. This function is similar to INSERTXMLAFTER, but
it inserts before, not after, the target node. Compare this function with
INSERTCHILDXML on page 5-86.
■ XMLType_instance is an instance of XMLType.
■ The XPath_string is an Xpath expression indicating one or more nodes into
which one or more child nodes are to be inserted. You can specify an absolute
XPath_string with an initial slash or a relative XPath_string by omitting the
initial slash. If you omit the initial slash, then the context of the relative path
defaults to the root node.
■ The value_expr is a fragment of XMLType that defines one or more nodes being
inserted and their position within the parent node. It must resolve to a string.
■ The optional namespace_string provides namespace information for the
XPath_string. This parameter must be of type VARCHAR2.
Examples
The following example is similar to that for INSERTCHILDXML on page 5-86, but it
adds a third /Owner node before the /Owner node added in the other example. The
output of the query has been formatted for readability.
UPDATE warehouses SET warehouse_spec =
INSERTXMLBEFORE(warehouse_spec,
'/Warehouse/Building/Owner[2]',
XMLType('<Owner>ThirdOwner</Owner>'))
WHERE warehouse_id = 3;
SELECT warehouse_name, EXTRACT(warehouse_spec,
See Also: Oracle XML DB Developer's Guide for more information
about this function
INSERTXMLBEFORE ( XMLType_instance , XPath_string , value_expr
, namespace_string
)
INSTR
Functions 5-91
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;
Name Owners
------------ --------------------------------------------------------------------
New Jersey <Owner>Grandco</Owner>
<Owner>ThirdOwner</Owner>
<Owner>LesserCo</Owner>
INSTR
Syntax
Purpose
The INSTR functions search string for substring. The search operation is defined
as comparing the substring argument with substrings of string of the same length
for equality until a match is found or there are no more substrings left. Each
consecutive compared substring of string begins one character to the right (for
forward searches) or one character to the left (for backward searches) from the first
character of the previous compared substring. If a substring that is equal to
substring is found, then the function returns an integer indicating the position of
the first character of this substring. If no such substring is found, then the function
returns zero.
■ position is an nonzero integer indicating the character of string where Oracle
Database begins the search—that is, the position of the first character of the first
substring to compare with substring. If position is negative, then Oracle
counts backward from the end of string and then searches backward from the
resulting position.
■ occurrence is an integer indicating which occurrence of substring in string
Oracle should search for. The value of occurrence must be positive. If
occurrence is greater than 1, then the database does not return on the first match
but continues comparing consecutive substrings of string, as described above,
until match number occurrence has been found.
INSTR accepts and returns positions in characters as defined by the input character
set, with the first character of string having position 1. INSTRB uses bytes instead of
characters. INSTRC uses Unicode complete characters. INSTR2 uses UCS2 code
points. INSTR4 uses UCS4 code points.
Both string and substring can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The value returned is of NUMBER data type.
Both position and occurrence must be of data type NUMBER, or any data type that
can be implicitly converted to NUMBER, and must resolve to an integer. The default
values of both position and occurrence are 1, meaning Oracle begins searching at
INSTR
INSTRB
INSTRC
INSTR2
INSTR4
( string , substring
, position
, occurrence
)
ITERATION_NUMBER
5-92 Oracle Database SQL Language Reference
the first character of string for the first occurrence of substring. The return value
is relative to the beginning of string, regardless of the value of position.
Examples
The following example searches the string CORPORATE FLOOR, beginning with the
third character, for the string "OR". It returns the position in CORPORATE FLOOR at
which the second occurrence of "OR" begins:
SELECT INSTR('CORPORATE FLOOR','OR', 3, 2)
"Instring" FROM DUAL;
Instring
----------
14
In the next example, Oracle counts backward from the last character to the third
character from the end, which is the first O in FLOOR. Oracle then searches backward
for the second occurrence of OR, and finds that this second occurrence begins with the
second character in the search string :
SELECT INSTR('CORPORATE FLOOR','OR', -3, 2)
"Reversed Instring"
FROM DUAL;
Reversed Instring
-----------------
2
The next example assumes a double-byte database character set.
SELECT INSTRB('CORPORATE FLOOR','OR',5,2) "Instring in bytes"
FROM DUAL;
Instring in bytes
-----------------
27
ITERATION_NUMBER
Syntax
Purpose
The ITERATION_NUMBER function can be used only in the model_clause of the
SELECT statement and then only when ITERATE(number) is specified in the model_
rules_clause. It returns an integer representing the completed iteration through the
model rules. The ITERATION_NUMBER function returns 0 during the first iteration. For
each subsequent iteration, the ITERATION_NUMBER function returns the equivalent of
iteration_number plus one.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for the syntax and semantics
ITERATION_NUMBER
ITERATION_NUMBER
Functions 5-93
Examples
The following example assigns the sales of the Mouse Pad for the years 1998 and 1999
to the sales of the Mouse Pad for the years 2001 and 2002 respectively:
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER ITERATE(2)
(
s['Mouse Pad', 2001 + ITERATION_NUMBER] =
s['Mouse Pad', 1998 + ITERATION_NUMBER]
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 3000.72
France Mouse Pad 2001 2509.42
France Mouse Pad 2002 3678.69
France Standard Mouse 1998 2390.83
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 1274.31
France Standard Mouse 2001 2164.54
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 7375.46
Germany Mouse Pad 2001 5827.87
Germany Mouse Pad 2002 8346.44
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 2637.31
Germany Standard Mouse 2001 6456.13
18 rows selected.
The preceding example requires the view sales_view_ref. Refer to "The MODEL
clause: Examples" on page 19-45 to create this view.
LAG
5-94 Oracle Database SQL Language Reference
LAG
Syntax
Purpose
LAG is an analytic function. It provides access to more than one row of a table at the
same time without a self join. Given a series of rows returned from a query and a
position of the cursor, LAG provides access to a row at a given physical offset prior to
that position.
If you do not specify offset, then its default is 1. The optional default value is
returned if the offset goes beyond the scope of the window. If you do not specify
default, then its default is null.
{RESPECT | IGNORE} NULLS determines whether null values of value_expr are
included in or eliminated from the calculation. The default is RESPECT NULLS.
You cannot nest analytic functions by using LAG or any other analytic function for
value_expr. However, you can use other built-in function expressions for value_
expr.
Examples
The following example provides, for each salesperson in the employees table, the
salary of the employee hired just before:
SELECT last_name, hire_date, salary,
LAG(salary, 1, 0) OVER (ORDER BY hire_date) AS prev_sal
FROM employees
WHERE job_id = 'PU_CLERK'
ORDER BY last_name, hire_date, salary, prev_sal;
LAST_NAME HIRE_DATE SALARY PREV_SAL
------------------------- --------- ---------- ----------
Baida 24-DEC-05 2900 2800
Colmenares 10-AUG-07 2500 2600
Himuro 15-NOV-06 2600 2900
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of value_
expr
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and LEAD on page 5-98
LAG
( value_expr
, offset
, default
)
RESPECT
IGNORE
NULLS
( value_expr
RESPECT
IGNORE
NULLS
, offset
, default
)
OVER (
query_partition_clause
order_by_clause )
LAST_DAY
Functions 5-95
Khoo 18-MAY-03 3100 0
Tobias 24-JUL-05 2800 3100
LAST
Syntax
last::=
Purpose
FIRST and LAST are very similar functions. Both are aggregate and analytic functions
that operate on a set of values from a set of rows that rank as the FIRST or LAST with
respect to a given sorting specification. If only one row ranks as FIRST or LAST, then
the aggregate operates on the set with only one element.
Refer to FIRST on page 5-77 for complete information on this function and for
examples of its use.
LAST_DAY
Syntax
Purpose
LAST_DAY returns the date of the last day of the month that contains date. The last
day of the month is defined by the session parameter NLS_CALENDAR. The return type
is always DATE, regardless of the data type of date.
Examples
The following statement determines how many days are left in the current month.
SELECT SYSDATE,
LAST_DAY(SYSDATE) "Last",
LAST_DAY(SYSDATE) - SYSDATE "Days Left"
FROM DUAL;
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the query_partitioning_
clause
aggregate_function KEEP
( DENSE_RANK LAST ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
OVER (
query_partition_clause
)
LAST_DAY ( date )
LAST_VALUE
5-96 Oracle Database SQL Language Reference
SYSDATE Last Days Left
--------- --------- ----------
30-MAY-01 31-MAY-01 1
The following example adds 5 months to the hire date of each employee to give an
evaluation date:
SELECT last_name, hire_date, TO_CHAR(
ADD_MONTHS(LAST_DAY(hire_date), 5)) "Eval Date"
FROM employees;
LAST_NAME HIRE_DATE Eval Date
------------------------- --------- ---------
King 17-JUN-03 30-NOV-03
Kochhar 21-SEP-05 28-FEB-05
De Haan 13-JAN-01 30-JUN-01
Hunold 20-MAY-08 31-OCT-08
Ernst 21-MAY-07 31-OCT-07
Austin 25-JUN-05 30-NOV-05
Pataballa 05-FEB-06 31-JUL-06
Lorentz 07-FEB-07 31-JUL-07
. . .
LAST_VALUE
Syntax
Purpose
LAST_VALUE is an analytic function that is useful for data densification. It returns the
last value in an ordered set of values.
{RESPECT | IGNORE} NULLS determines whether null values of expr are included in
or eliminated from the calculation. The default is RESPECT NULLS. If the last value in
the set is null, then the function returns NULL unless you specify IGNORE NULLS. If
you specify IGNORE NULLS, then LAST_VALUE returns the fist non-null value in the
set, or NULL if all values are null. Refer to "Using Partitioned Outer Joins:
Examples" on page 19-52 for an example of data densification.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of expr
Note: The two forms of this syntax have the same behavior. The top
branch is the ANSI format, which Oracle recommends. The bottom
branch is deprecated but is supported for backward compatibility.
LAST_VALUE
( expr )
RESPECT
IGNORE
NULLS
( expr
RESPECT
IGNORE
NULLS
)
OVER ( analytic_clause )
LAST_VALUE
Functions 5-97
You cannot nest analytic functions by using LAST_VALUE or any other analytic
function for expr. However, you can use other built-in function expressions for expr.
Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr.
If you omit the windowing_clause of the analytic_clause, it defaults to RANGE
BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This default sometimes returns
an unexpected value, because the last value in the window is at the bottom of the
window, which is not fixed. It keeps changing as the current row changes. For
expected results, specify the windowing_clause as RANGE BETWEEN UNBOUNDED
PRECEDING AND UNBOUNDED FOLLOWING. Alternatively, you can specify the
windowing_clause as RANGE BETWEEN CURRENT ROW AND UNBOUNDED
FOLLOWING.
Examples
The following example returns, for each row, the hire date of the employee earning the
highest salary:
SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER
(ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date)
ORDER BY last_name, salary, hire_date, lv;
LAST_NAME SALARY HIRE_DATE LV
--------------- ---------- --------- ---------
De Haan 17000 13-JAN-01 17-JUN-03
King 24000 17-JUN-03 17-JUN-03
Kochhar 17000 21-SEP-05 17-JUN-03
This example illustrates the nondeterministic nature of the LAST_VALUE function.
Kochhar and De Haan have the same salary, so they are in adjacent rows. Kochhar
appears first because the rows in the subquery are ordered by hire_date. However,
if the rows are ordered by hire_date in descending order, as in the next example,
then the function returns a different value:
SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER
(ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date DESC)
ORDER BY last_name, salary, hire_datea, lv;
LAST_NAME SALARY HIRE_DATE LV
--------------- ---------- --------- ---------
De Haan 17000 13-JAN-01 17-JUN-03
King 24000 17-JUN-03 17-JUN-03
Kochhar 17000 21-SEP-05 17-JUN-03
The following two examples show how to make the LAST_VALUE function
deterministic by ordering on a unique key. By ordering within the function by both
salary and hire_date, you can ensure the same result regardless of the ordering in
the subquery.
SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER
(ORDER BY salary, hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date)
LEAD
5-98 Oracle Database SQL Language Reference
ORDER BY last_name, salary, hire_date, lv;
LAST_NAME SALARY HIRE_DATE LV
--------------- ---------- --------- ---------
De Haan 17000 13-JAN-01 17-JUN-03
King 24000 17-JUN-03 17-JUN-03
Kochhar 17000 21-SEP-05 17-JUN-03
SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER
(ORDER BY salary, hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date DESC)
ORDER BY last_name, salary, hire_date, lv;
LAST_NAME SALARY HIRE_DATE LV
--------------- ---------- --------- ---------
De Haan 17000 13-JAN-01 17-JUN-03
King 24000 17-JUN-03 17-JUN-03
Kochhar 17000 21-SEP-05 17-JUN-03
When you use a logical offset (RANGE instead of ROWS), the function is deterministic.
When duplicates are found for the ORDER BY expression, the LAST_VALUE is the
highest value of expr:
SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER
(ORDER BY salary
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date DESC);
LAST_NAME SALARY HIRE_DATE LV
------------------------- ---------- --------- ---------
De Haan 17000 13-JAN-01 17-JUN-03
Kochhar 17000 21-SEP-05 17-JUN-03
King 24000 17-JUN-03 17-JUN-03
LEAD
Syntax
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of value_
expr
LEAD
( value_expr
, offset
, default
)
RESPECT
IGNORE
NULLS
( value_expr
RESPECT
IGNORE
NULLS
, offset
, default
)
OVER (
query_partition_clause
order_by_clause )
LEAST
Functions 5-99
Purpose
LEAD is an analytic function. It provides access to more than one row of a table at the
same time without a self join. Given a series of rows returned from a query and a
position of the cursor, LEAD provides access to a row at a given physical offset beyond
that position.
If you do not specify offset, then its default is 1. The optional default value is
returned if the offset goes beyond the scope of the table. If you do not specify
default, then its default value is null.
{RESPECT | IGNORE} NULLS determines whether null values of value_expr are
included in or eliminated from the calculation. The default is RESPECT NULLS.
You cannot nest analytic functions by using LEAD or any other analytic function for
value_expr. However, you can use other built-in function expressions for value_
expr.
Examples
The following example provides, for each employee in the employees table, the hire
date of the employee hired just after:
SELECT last_name, hire_date,
LEAD(hire_date, 1) OVER (ORDER BY hire_date) AS "NextHired"
FROM employees WHERE department_id = 30
ORDER BY last_name, hire_date, "NextHired";
LAST_NAME HIRE_DATE NextHired
------------------------- --------- ---------
Baida 24-DEC-05 15-NOV-06
Colmenares 10-AUG-07
Himuro 15-NOV-06 10-AUG-07
Khoo 18-MAY-03 24-JUL-05
Raphaely 07-DEC-02 18-MAY-03
Tobias 24-JUL-05 24-DEC-05
LEAST
Syntax
Purpose
LEAST returns the least of the list of exprs. All exprs after the first are implicitly
converted to the data type of the first expr before the comparison. Oracle Database
compares the exprs using nonpadded comparison semantics. If the value returned by
this function is character data, then its data type is always VARCHAR2.
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and LAG on page 5-94
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion, "Floating-Point
Numbers" on page 3-12 for information on binary-float comparison
semantics, and "Data Type Comparison Rules" on page 3-37
LEAST ( expr
,
)
LENGTH
5-100 Oracle Database SQL Language Reference
Examples
The following statement selects the string with the least value:
SELECT LEAST('HARRY','HARRIOT','HAROLD') "LEAST"
FROM DUAL;
LEAST
------
HAROLD
LENGTH
Syntax
length::=
Purpose
The LENGTH functions return the length of char. LENGTH calculates length using
characters as defined by the input character set. LENGTHB uses bytes instead of
characters. LENGTHC uses Unicode complete characters. LENGTH2 uses UCS2 code
points. LENGTH4 uses UCS4 code points.
char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB. The return value is of data type NUMBER. If char has data type CHAR, then the
length includes all trailing blanks. If char is null, then this function returns null.
Restriction on LENGTHB The LENGTHB function is supported for single-byte LOBs
only. It cannot be used with CLOB and NCLOB data in a multibyte character set.
Examples
The following example uses the LENGTH function using a single-byte database
character set:
SELECT LENGTH('CANDIDE') "Length in characters"
FROM DUAL;
Length in characters
--------------------
7
The next example assumes a double-byte database character set.
SELECT LENGTHB ('CANDIDE') "Length in bytes"
FROM DUAL;
Length in bytes
---------------
14
LENGTH
LENGTHB
LENGTHC
LENGTH2
LENGTH4
( char )
LISTAGG
Functions 5-101
LISTAGG
Syntax
Purpose
For a specified measure, LISTAGG orders data within each group specified in the
ORDER BY clause and then concatenates the values of the <measure> column.
■ As a single-set aggregate function, LISTAGG operates on all rows and returns a
single output row.
■ As a group-set aggregate, the function operates on and returns an output row for
each group defined by the GROUP BY clause.
■ As an analytic function, LISTAGG partitions the query result set into groups based
on one or more expression in the query_partition_clause.
The arguments to the function are subject to the following rules:
■ The measure_expr can be any expression. Null values in the measure column
are ignored.
■ The delimiter_expr designates the string that is to separate the measure
values. This clause is optional and defaults to NULL.
■ The order_by_clause determines the order in which the concatenated values
are returned. The function is deterministic only if the ORDER BY column list
achieved unique ordering.
The return data type is RAW if the measure column is RAW; otherwise the return value
is VARCHAR2.
Examples
The following single-set aggregate example lists all of the employees in Department 30
in the hr.employees table, ordered by hire date and last name:
SELECT LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date, last_name) "Emp_
list",
MIN(hire_date) "Earliest"
FROM employees
WHERE department_id = 30;
Emp_list Earliest
------------------------------------------------------------ ---------
Raphaely; Khoo; Tobias; Baida; Himuro; Colmenares 07-DEC-02
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the ORDER BY clause and OVER
clause
LISTAGG ( measure_expr
, ’ delimiter ’
) WITHIN GROUP ( order_by_clause )
OVER query_partition_clause
LN
5-102 Oracle Database SQL Language Reference
The following group-set aggregate example lists, for each department ID in the
hr.employees table, the employees in that department in order of their hire date:
SELECT department_id "Dept.",
LISTAGG(last_name, '; ')
WITHIN GROUP (ORDER BY hire_date) "Employees"
FROM employees
GROUP BY department_id;
Dept. Employees
------ ------------------------------------------------------------
10 Whalen
20 Hartstein; Fay
30 Raphaely; Khoo; Tobias; Baida; Himuro; Colmenares
40 Mavris
50 Kaufling; Ladwig; Rajs; Sarchand; Bell; Mallin; Weiss; Davie
s; Marlow; Bull; Everett; Fripp; Chung; Nayer; Dilly; Bissot
; Vollman; Stiles; Atkinson; Taylor; Seo; Fleaur; Matos; Pat
el; Walsh; Feeney; Dellinger; McCain; Vargas; Gates; Rogers;
Mikkilineni; Landry; Cabrio; Jones; Olson; OConnell; Sulliv
an; Mourgos; Gee; Perkins; Grant; Geoni; Philtanker; Markle
60 Austin; Pataballa; Lorentz; Ernst; Hunold
70 Baer
...
The following analytic example shows, for each employee hired earlier than
September 1, 2003, the employee's department, hire date, and all other employees in
that department also hired before September 1, 2003:
SELECT department_id "Dept", hire_date "Date", last_name "Name",
LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date, last_name)
OVER (PARTITION BY department_id) as "Emp_list"
FROM employees
WHERE hire_date < '01-SEP-2003';
Dept Date Name Emp_list
----- --------- --------------- ---------------------------------------------
30 07-DEC-02 Raphaely Raphaely; Khoo
30 18-MAY-03 Khoo Raphaely; Khoo
40 07-JUN-02 Mavris Mavris
50 01-MAY-03 Kaufling Kaufling; Ladwig
50 14-JUL-03 Ladwig Kaufling; Ladwig
70 07-JUN-02 Baer Baer
90 13-JAN-01 De Haan De Haan; King
90 17-JUN-03 King De Haan; King
100 16-AUG-02 Faviet Faviet; Greenberg
100 17-AUG-02 Greenberg Faviet; Greenberg
110 07-JUN-02 Gietz Gietz; Higgins
110 07-JUN-02 Higgins Gietz; Higgins
LN
Syntax
Purpose
LN returns the natural logarithm of n, where n is greater than 0.
LN ( n )
LNNVL
Functions 5-103
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the natural logarithm of 95:
SELECT LN(95) "Natural log of 95" FROM DUAL;
Natural log of 95
-----------------
4.55387689
LNNVL
Syntax
Purpose
LNNVL provides a concise way to evaluate a condition when one or both operands of
the condition may be null. The function can be used only in the WHERE clause of a
query. It takes as an argument a condition and returns TRUE if the condition is FALSE
or UNKNOWN and FALSE if the condition is TRUE. LNNVL can be used anywhere a scalar
expression can appear, even in contexts where the IS [NOT] NULL, AND, or OR
conditions are not valid but would otherwise be required to account for potential
nulls.
Oracle Database sometimes uses the LNNVL function internally in this way to rewrite
NOT IN conditions as NOT EXISTS conditions. In such cases, output from EXPLAIN
PLAN shows this operation in the plan table output. The condition can evaluate any
scalar values but cannot be a compound condition containing AND, OR, or BETWEEN.
The table that follows shows what LNNVL returns given that a = 2 and b is null.
Examples
Suppose that you want to know the number of employees with commission rates of
less than 20%, including employees who do not receive commissions. The following
query returns only employees who actually receive a commission of less than 20%:
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
Condition Truth of Condition LNNVL Return Value
a = 1 FALSE TRUE
a = 2 TRUE FALSE
a IS NULL FALSE TRUE
b = 1 UNKNOWN TRUE
b IS NULL TRUE FALSE
a = b UNKNOWN TRUE
LNNVL ( condition )
LOCALTIMESTAMP
5-104 Oracle Database SQL Language Reference
SELECT COUNT(*) FROM employees WHERE commission_pct < .2;
COUNT(*)
----------
11
To include the 72 employees who receive no commission at all, you could rewrite the
query using the LNNVL function as follows:
SELECT COUNT(*) FROM employees WHERE LNNVL(commission_pct >= .2);
COUNT(*)
----------
83
LOCALTIMESTAMP
Syntax
Purpose
LOCALTIMESTAMP returns the current date and time in the session time zone in a
value of data type TIMESTAMP. The difference between this function and CURRENT_
TIMESTAMP is that LOCALTIMESTAMP returns a TIMESTAMP value while CURRENT_
TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value.
The optional argument timestamp_precision specifies the fractional second
precision of the time value returned.
Examples
This example illustrates the difference between LOCALTIMESTAMP and CURRENT_
TIMESTAMP:
ALTER SESSION SET TIME_ZONE = '-5:00';
SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;
CURRENT_TIMESTAMP LOCALTIMESTAMP
-------------------------------------------------------------------
04-APR-00 01.27.18.999220 PM -05:00 04-APR-00 01.27.19 PM
ALTER SESSION SET TIME_ZONE = '-8:00';
SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;
CURRENT_TIMESTAMP LOCALTIMESTAMP
----------------------------------- ------------------------------
04-APR-00 10.27.45.132474 AM -08:00 04-APR-00 10.27.451 AM
When you use the LOCALTIMESTAMP with a format mask, take care that the format
mask matches the value returned by the function. For example, consider the following
table:
CREATE TABLE local_test (col1 TIMESTAMP WITH LOCAL TIME ZONE);
See Also: CURRENT_TIMESTAMP on page 5-55, "TIMESTAMP
Data Type" on page 3-18, and "TIMESTAMP WITH TIME ZONE Data
Type" on page 3-18
LOCALTIMESTAMP
( timestamp_precision )
LOWER
Functions 5-105
The following statement fails because the mask does not include the TIME ZONE
portion of the return type of the function:
INSERT INTO local_test VALUES
(TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF'));
The following statement uses the correct format mask to match the return type of
LOCALTIMESTAMP:
INSERT INTO local_test VALUES
(TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM'));
LOG
Syntax
Purpose
LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other
than 0 or 1 and n2 can be any positive value.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. If any argument is BINARY_
FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise
the function returns NUMBER.
Examples
The following example returns the log of 100:
SELECT LOG(10,100) "Log base 10 of 100" FROM DUAL;
Log base 10 of 100
------------------
2
LOWER
Syntax
Purpose
LOWER returns char, with all letters lowercase. char can be any of the data types
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same
data type as char. The database sets the case of the characters based on the binary
mapping defined for the underlying character set. For linguistic-sensitive lowercase,
refer to NLS_LOWER on page 5-119.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
LOG ( n2 , n1 )
LOWER ( char )
LPAD
5-106 Oracle Database SQL Language Reference
Examples
The following example returns a string in lowercase:
SELECT LOWER('MR. SCOTT MCMILLAN') "Lowercase"
FROM DUAL;
Lowercase
--------------------
mr. scott mcmillan
LPAD
Syntax
Purpose
LPAD returns expr1, left-padded to length n characters with the sequence of
characters in expr2. This function is useful for formatting the output of a query.
Both expr1 and expr2 can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if expr1
is a character data type, NVARCHAR2 if expr1 is a national character data type, and a
LOB if expr1 is a LOB data type. The string returned is in the same character set as
expr1. The argument n must be a NUMBER integer or a value that can be implicitly
converted to a NUMBER integer.
If you do not specify expr2, then the default is a single blank. If expr1 is longer than
n, then this function returns the portion of expr1 that fits in n.
The argument n is the total length of the return value as it is displayed on your
terminal screen. In most character sets, this is also the number of characters in the
return value. However, in some multibyte character sets, the display length of a
character string can differ from the number of characters in the string.
Examples
The following example left-pads a string with the asterisk (*) and period (.) characters:
SELECT LPAD('Page 1',15,'*.') "LPAD example"
FROM DUAL;
LPAD example
---------------
*.*.*.*.*Page 1
LTRIM
Syntax
LPAD ( expr1 , n
, expr2
)
LTRIM ( char
, set
)
MAKE_REF
Functions 5-107
Purpose
LTRIM removes from the left end of char all of the characters contained in set. If you
do not specify set, then it defaults to a single blank. If char is a character literal, then
you must enclose it in single quotation marks. Oracle Database begins scanning char
from its first character and removes all characters that appear in set until reaching a
character not in set and then returns the result.
Both char and set can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is
a character data type, NVARCHAR2 if char is a national character data type, and a LOB
if char is a LOB data type.
Examples
The following example trims the redundant first word from a group of product names
in the oe.products table:
SELECT product_name, LTRIM(product_name, 'Monitor ') "Short Name"
FROM products
WHERE product_name LIKE 'Monitor%';
PRODUCT_NAME Short Name
-------------------- ---------------
Monitor 17/HR 17/HR
Monitor 17/HR/F 17/HR/F
Monitor 17/SD 17/SD
Monitor 19/SD 19/SD
Monitor 19/SD/M 19/SD/M
Monitor 21/D 21/D
Monitor 21/HR 21/HR
Monitor 21/HR/M 21/HR/M
Monitor 21/SD 21/SD
Monitor Hinge - HD Hinge - HD
Monitor Hinge - STD Hinge - STD
MAKE_REF
Syntax
Purpose
MAKE_REF creates a REF to a row of an object view or a row in an object table whose
object identifier is primary key based. This function is useful, for example, if you are
creating an object view
See Also: RTRIM on page 5-178
See Also: Oracle Database Object-Relational Developer's Guide for more
information about object views and DEREF on page 5-63
MAKE_REF (
table
view
, key
,
)
MAX
5-108 Oracle Database SQL Language Reference
Examples
The sample schema oe contains an object view oc_inventories based on
inventory_typ. The object identifier is product_id. The following example creates
a REF to the row in the oc_inventories object view with a product_id of 3003:
SELECT MAKE_REF (oc_inventories, 3003) FROM DUAL;
MAKE_REF(OC_INVENTORIES,3003)
------------------------------------------------------------------
00004A038A0046857C14617141109EE03408002082543600000014260100010001
00290090606002A00078401FE0000000B03C21F040000000000000000000000000
0000000000
MAX
Syntax
Purpose
MAX returns maximum value of expr. You can use it as an aggregate or analytic
function.
Aggregate Example
The following example determines the highest salary in the hr.employees table:
SELECT MAX(salary) "Maximum" FROM employees;
Maximum
----------
24000
Analytic Example
The following example calculates, for each employee, the highest salary of the
employees reporting to the same manager as the employee.
SELECT manager_id, last_name, salary,
MAX(salary) OVER (PARTITION BY manager_id) AS mgr_max
FROM employees
ORDER BY manager_id, last_name, salary, mgr_max;
MANAGER_ID LAST_NAME SALARY MGR_MAX
---------- ------------------------- ---------- ----------
100 Cambrault 11000 17000
100 De Haan 17000 17000
100 Errazuriz 12000 17000
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr, "Floating-Point Numbers" on page 3-12 for
information on binary-float comparison semantics, and "Aggregate
Functions" on page 5-9
MAX (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
MEDIAN
Functions 5-109
100 Fripp 8200 17000
100 Hartstein 13000 17000
100 Kaufling 7900 17000
100 Kochhar 17000 17000
. . .
If you enclose this query in the parent query with a predicate, then you can determine
the employee who makes the highest salary in each department:
SELECT manager_id, last_name, salary
FROM (SELECT manager_id, last_name, salary,
MAX(salary) OVER (PARTITION BY manager_id) AS rmax_sal
FROM employees) WHERE salary = rmax_sal
ORDER BY manager_id, last_name, salary;
MANAGER_ID LAST_NAME SALARY
---------- ------------------------- ----------
100 De Haan 17000
100 Kochhar 17000
101 Greenberg 12000
101 Higgins 12000
102 Hunold 9000
103 Ernst 6000
108 Faviet 9000
114 Khoo 3100
120 Nayer 3200
120 Taylor 3200
121 Sarchand 4200
122 Chung 3800
123 Bell 4000
124 Rajs 3500
145 Tucker 10000
146 King 10000
147 Vishney 10500
148 Ozer 11500
149 Abel 11000
201 Fay 6000
205 Gietz 8300
King 24000
22 rows selected.
MEDIAN
Syntax
Purpose
MEDIAN is an inverse distribution function that assumes a continuous distribution
model. It takes a numeric or datetime value and returns the middle value or an
interpolated value that would be the middle value once the values are sorted. Nulls
are ignored in the calculation.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
MEDIAN ( expr )
OVER ( query_partition_clause )
MEDIAN
5-110 Oracle Database SQL Language Reference
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. If you specify only expr, then
the function returns the same data type as the numeric data type of the argument. if
you specify the OVER clause, then Oracle Database determines the argument with the
highest numeric precedence, implicitly converts the remaining arguments to that data
type, and returns that data type.
The result of MEDIAN is computed by first ordering the rows. Using N as the number of
rows in the group, Oracle calculates the row number (RN) of interest with the formula
RN = (1 + (0.5*(N-1)). The final result of the aggregate function is computed by linear
interpolation between the values from rows at row numbers CRN = CEILING(RN) and
FRN = FLOOR(RN).
The final result will be:
if (CRN = FRN = RN) then
(value of expression from row at RN)
else
(CRN - RN) * (value of expression for row at FRN) +
(RN - FRN) * (value of expression for row at CRN)
You can use MEDIAN as an analytic function. You can specify only the query_
partition_clause in its OVER clause. It returns, for each row, the value that would
fall in the middle among a set of values within each partition.
Compare this function with these functions:
■ PERCENTILE_CONT on page 5-133, which returns, for a given percentile, the
value that corresponds to that percentile by way of interpolation. MEDIAN is the
specific case of PERCENTILE_CONT where the percentile value defaults to 0.5.
■ PERCENTILE_DISC on page 5-135, which is useful for finding values for a given
percentile without interpolation.
Aggregate Example
The following query returns the median salary for each department in the
hr.employees table:
SELECT department_id, MEDIAN(salary)
FROM employees
GROUP BY department_id
ORDER BY department_id, median(salary);
DEPARTMENT_ID MEDIAN(SALARY)
------------- --------------
10 4400
20 9500
30 2850
40 6500
50 3100
60 4800
70 10000
80 8900
90 17000
100 8000
110 10150
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
MIN
Functions 5-111
7000
Analytic Example
The following query returns the median salary for each manager in a subset of
departments in the hr.employees table:
SELECT manager_id, employee_id, salary,
MEDIAN(salary) OVER (PARTITION BY manager_id) "Median by Mgr"
FROM employees
WHERE department_id > 60
ORDER BY manager_id, employee_id, salary, "Median by Mgr";
MANAGER_ID EMPLOYEE_ID SALARY Median by Mgr
---------- ----------- ---------- -------------
100 101 17000 13500
100 102 17000 13500
100 145 14000 13500
100 146 13500 13500
100 147 12000 13500
100 148 11000 13500
100 149 10500 13500
101 108 12000 12000
101 204 10000 12000
101 205 12000 12000
108 109 9000 7800
108 110 8200 7800
108 111 7700 7800
108 112 7800 7800
108 113 6900 7800
145 150 10000 8500
145 151 9500 8500
145 152 9000 8500
. . .
MIN
Syntax
Purpose
MIN returns minimum value of expr. You can use it as an aggregate or analytic
function.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr, "Floating-Point Numbers" on page 3-12 for
information on binary-float comparison semantics, and "Aggregate
Functions" on page 5-9
MIN (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
MOD
5-112 Oracle Database SQL Language Reference
Aggregate Example
The following statement returns the earliest hire date in the hr.employees table:
SELECT MIN(hire_date) "Earliest" FROM employees;
Earliest
---------
13-JAN-01
Analytic Example
The following example determines, for each employee, the employees who were hired
on or before the same date as the employee. It then determines the subset of
employees reporting to the same manager as the employee, and returns the lowest
salary in that subset.
SELECT manager_id, last_name, hire_date, salary,
MIN(salary) OVER(PARTITION BY manager_id ORDER BY hire_date
RANGE UNBOUNDED PRECEDING) AS p_cmin
FROM employees
ORDER BY manager_id, last_name, hire_date, salary, p_cmin;
MANAGER_ID LAST_NAME HIRE_DATE SALARY P_CMIN
---------- ------------------------- --------- ---------- ----------
100 Cambrault 15-OCT-07 11000 6500
100 De Haan 13-JAN-01 17000 17000
100 Errazuriz 10-MAR-05 12000 7900
100 Fripp 10-APR-05 8200 7900
100 Hartstein 17-FEB-04 13000 7900
100 Kaufling 01-MAY-03 7900 7900
100 Kochhar 21-SEP-05 17000 7900
100 Mourgos 16-NOV-07 5800 5800
100 Partners 05-JAN-05 13500 7900
100 Raphaely 07-DEC-02 11000 11000
100 Russell 01-OCT-04 14000 7900
. . .
MOD
Syntax
Purpose
MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
Examples
The following example returns the remainder of 11 divided by 4:
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
MOD ( n2 , n1 )
MONTHS_BETWEEN
Functions 5-113
SELECT MOD(11,4) "Modulus" FROM DUAL;
Modulus
----------
3
This function behaves differently from the classical mathematical modulus function
when m is negative. The classical modulus can be expressed using the MOD function
with this formula:
n2 - n1 * FLOOR(n2/n1)
The following table illustrates the difference between the MOD function and the
classical modulus:
MONTHS_BETWEEN
Syntax
Purpose
MONTHS_BETWEEN returns number of months between dates date1 and date2. The
month and the last day of the month are defined by the parameter NLS_CALENDAR. If
date1 is later than date2, then the result is positive. If date1 is earlier than date2,
then the result is negative. If date1 and date2 are either the same days of the month
or both last days of months, then the result is always an integer. Otherwise Oracle
Database calculates the fractional portion of the result based on a 31-day month and
considers the difference in time components date1 and date2.
Examples
The following example calculates the months between two dates:
SELECT MONTHS_BETWEEN
(TO_DATE('02-02-1995','MM-DD-YYYY'),
TO_DATE('01-01-1995','MM-DD-YYYY') ) "Months"
FROM DUAL;
Months
----------
1.03225806
n2 n1 MOD(n2,n1) Classical Modulus
11 4 3 3
11 -4 3 -1
-11 4 -3 1
-11 -4 -3 -3
See Also: FLOOR on page 5-80 and REMAINDER on page 5-171,
which is similar to MOD, but uses ROUND in its formula instead of
FLOOR
MONTHS_BETWEEN ( date1 , date2 )
NANVL
5-114 Oracle Database SQL Language Reference
NANVL
Syntax
Purpose
The NANVL function is useful only for floating-point numbers of type BINARY_FLOAT
or BINARY_DOUBLE. It instructs Oracle Database to return an alternative value n1 if
the input value n2 is NaN (not a number). If n2 is not NaN, then Oracle returns n2.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
Examples
Using table float_point_demo created for TO_BINARY_DOUBLE on page 5-215,
insert a second entry into the table:
Insert INTO float_point_demo
VALUES (0,'NaN','NaN');
SELECT * FROM float_point_demo;
DEC_NUM BIN_DOUBLE BIN_FLOAT
---------- ---------- ----------
1234.56 1.235E+003 1.235E+003
0 Nan Nan
The following example returns bin_float if it is a number. Otherwise, 0 is returned.
SELECT bin_float, NANVL(bin_float,0)
FROM float_point_demo;
BIN_FLOAT NANVL(BIN_FLOAT,0)
---------- ------------------
1.235E+003 1.235E+003
Nan 0
NCHR
Syntax
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion, "Floating-Point
Numbers" on page 3-12 for information on binary-float comparison
semantics, and "Numeric Precedence" on page 3-14 for information on
numeric precedence
NANVL ( n2 , n1 )
NCHR ( number )
NEW_TIME
Functions 5-115
Purpose
NCHR returns the character having the binary equivalent to number in the national
character set. The value returned is always NVARCHAR2. This function is equivalent to
using the CHR function with the USING NCHAR_CS clause.
This function takes as an argument a NUMBER value, or any value that can be implicitly
converted to NUMBER, and returns a character.
Examples
The following examples return the nchar character 187:
SELECT NCHR(187) FROM DUAL;
NC
--
>
SELECT CHR(187 USING NCHAR_CS) FROM DUAL;
CH
--
>
NEW_TIME
Syntax
Purpose
NEW_TIME returns the date and time in time zone timezone2 when date and time in
time zone timezone1 are date. Before using this function, you must set the NLS_
DATE_FORMAT parameter to display 24-hour time. The return type is always DATE,
regardless of the data type of date.
The arguments timezone1 and timezone2 can be any of these text strings:
■ AST, ADT: Atlantic Standard or Daylight Time
■ BST, BDT: Bering Standard or Daylight Time
■ CST, CDT: Central Standard or Daylight Time
■ EST, EDT: Eastern Standard or Daylight Time
■ GMT: Greenwich Mean Time
■ HST, HDT: Alaska-Hawaii Standard Time or Daylight Time.
See Also: CHR on page 5-32
Note: This function takes as input only a limited number of time
zones. You can have access to a much greater number of time zones by
combining the FROM_TZ function and the datetime expression. See
FROM_TZ on page 5-81 and the example for "Datetime Expressions"
on page 6-8.
NEW_TIME ( date , timezone1 , timezone2 )
NEXT_DAY
5-116 Oracle Database SQL Language Reference
■ MST, MDT: Mountain Standard or Daylight Time
■ NST: Newfoundland Standard Time
■ PST, PDT: Pacific Standard or Daylight Time
■ YST, YDT: Yukon Standard or Daylight Time
Examples
The following example returns an Atlantic Standard time, given the Pacific Standard
time equivalent:
ALTER SESSION SET NLS_DATE_FORMAT =
'DD-MON-YYYY HH24:MI:SS';
SELECT NEW_TIME(TO_DATE(
'11-10-99 01:23:45', 'MM-DD-YY HH24:MI:SS'),
'AST', 'PST') "New Date and Time" FROM DUAL;
New Date and Time
--------------------
09-NOV-1999 21:23:45
NEXT_DAY
Syntax
Purpose
NEXT_DAY returns the date of the first weekday named by char that is later than the
date date. The return type is always DATE, regardless of the data type of date. The
argument char must be a day of the week in the date language of your session, either
the full name or the abbreviation. The minimum number of letters required is the
number of letters in the abbreviated version. Any characters immediately following
the valid abbreviation are ignored. The return value has the same hours, minutes, and
seconds component as the argument date.
Examples
This example returns the date of the next Tuesday after February 2, 2001:
SELECT NEXT_DAY('02-FEB-2001','TUESDAY') "NEXT DAY"
FROM DUAL;
NEXT DAY
-----------
06-FEB-2001
NLS_CHARSET_DECL_LEN
Syntax
NEXT_DAY ( date , char )
NLS_CHARSET_DECL_LEN ( byte_count , ’ char_set_id ’ )
NLS_CHARSET_NAME
Functions 5-117
Purpose
NLS_CHARSET_DECL_LEN returns the declaration length (in number of characters) of
an NCHAR column. The byte_count argument is the width of the column. The char_
set_id argument is the character set ID of the column.
Examples
The following example returns the number of characters that are in a 200-byte column
when you are using a multibyte character set:
SELECT NLS_CHARSET_DECL_LEN
(200, nls_charset_id('ja16eucfixed'))
FROM DUAL;
NLS_CHARSET_DECL_LEN(200,NLS_CHARSET_ID('JA16EUCFIXED'))
--------------------------------------------------------
100
NLS_CHARSET_ID
Syntax
Purpose
NLS_CHARSET_ID returns the character set ID number corresponding to character set
name string. The string argument is a run-time VARCHAR2 value. The string
value 'CHAR_CS' returns the database character set ID number of the server. The
string value 'NCHAR_CS' returns the national character set ID number of the server.
Invalid character set names return null.
Examples
The following example returns the character set ID of a character set:
SELECT NLS_CHARSET_ID('ja16euc')
FROM DUAL;
NLS_CHARSET_ID('JA16EUC')
-------------------------
830
NLS_CHARSET_NAME
Syntax
See Also: Oracle Database Globalization Support Guide for a list of
character set names
NLS_CHARSET_ID ( string )
NLS_CHARSET_NAME ( number )
NLS_INITCAP
5-118 Oracle Database SQL Language Reference
Purpose
NLS_CHARSET_NAME returns the name of the character set corresponding to ID
number number. The character set name is returned as a VARCHAR2 value in the
database character set.
If number is not recognized as a valid character set ID, then this function returns null.
Examples
The following example returns the character set corresponding to character set ID
number 2:
SELECT NLS_CHARSET_NAME(2)
FROM DUAL;
NLS_CH
------
WE8DEC
NLS_INITCAP
Syntax
Purpose
NLS_INITCAP returns char, with the first letter of each word in uppercase, all other
letters in lowercase. Words are delimited by white space or characters that are not
alphanumeric.
Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, or
NVARCHAR2. The string returned is of VARCHAR2 data type and is in the same
character set as char.
The value of 'nlsparam' can have this form:
'NLS_SORT = sort'
where sort is either a linguistic sort sequence or BINARY. The linguistic sort sequence
handles special linguistic requirements for case conversions. These requirements can
result in a return value of a different length than the char. If you omit 'nlsparam',
then this function uses the default sort sequence for your session.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following examples show how the linguistic sort sequence results in a different
return value from the function:
See Also: Oracle Database Globalization Support Guide for a list of
character set IDs
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
NLS_INITCAP ( char
, ’ nlsparam ’
)
NLS_UPPER
Functions 5-119
SELECT NLS_INITCAP
('ijsland') "InitCap" FROM DUAL;
InitCap
-------
Ijsland
SELECT NLS_INITCAP
('ijsland', 'NLS_SORT = XDutch') "InitCap"
FROM DUAL;
InitCap
-------
IJsland
NLS_LOWER
Syntax
Purpose
NLS_LOWER returns char, with all letters lowercase.
Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is
a character data type and a LOB if char is a LOB data type. The return string is in the
same character set as char.
The 'nlsparam' can have the same form and serve the same purpose as in the NLS_
INITCAP function.
Examples
The following statement returns the lowercase form of the character string
'NOKTASINDA' using the XTurkish linguistic sort sequence. The Turkish uppercase I
becoming a small, dotless i.
SELECT NLS_LOWER
('NOKTASINDA', 'NLS_SORT = XTurkish') "Lowercase"
FROM DUAL;
NLS_UPPER
Syntax
Purpose
NLS_UPPER returns char, with all letters uppercase.
See Also: Oracle Database Globalization Support Guide for information
on sort sequences
NLS_LOWER ( char
, ’ nlsparam ’
)
NLS_UPPER ( char
, ’ nlsparam ’
)
NLSSORT
5-120 Oracle Database SQL Language Reference
Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is
a character data type and a LOB if char is a LOB data type. The return string is in the
same character set as char.
The 'nlsparam' can have the same form and serve the same purpose as in the NLS_
INITCAP function.
Examples
The following example returns a string with all the letters converted to uppercase:
SELECT NLS_UPPER ('große') "Uppercase"
FROM DUAL;
Upper
-----
GROßE
SELECT NLS_UPPER ('große', 'NLS_SORT = XGerman') "Uppercase"
FROM DUAL;
Upperc
------
GROSSE
NLSSORT
Syntax
Purpose
NLSSORT returns the string of bytes used to sort char.
Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, or
NVARCHAR2. The string returned is of RAW data type.
The value of 'nlsparam' can have the form
'NLS_SORT = sort'
where sort is a linguistic sort sequence or BINARY. If you omit 'nlsparam', then
this function uses the default sort sequence for your session. If you specify BINARY,
then this function returns char.
If you specify 'nlsparam', then you can append to the linguistic sort name the suffix
_ai to request an accent-insensitive sort or _ci to request a case-insensitive sort. Refer
to Oracle Database Globalization Support Guide for more information on accent- and
case-insensitive sorting.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
See Also: NLS_INITCAP on page 5-118
NLSSORT ( char
, ’ nlsparam ’
)
NLSSORT
Functions 5-121
Examples
This function can be used to specify sorting and comparison operations based on a
linguistic sort sequence rather than on the binary value of a string. The following
example creates a test table containing two values and shows how the values returned
can be ordered by the NLSSORT function:
CREATE TABLE test (name VARCHAR2(15));
INSERT INTO test VALUES ('Gaardiner');
INSERT INTO test VALUES ('Gaberd');
INSERT INTO test VALUES ('Gaasten');
SELECT * FROM test ORDER BY name;
NAME
---------------
Gaardiner
Gaasten
Gaberd
SELECT * FROM test ORDER BY NLSSORT(name, 'NLS_SORT = XDanish');
NAME
---------------
Gaberd
Gaardiner
Gaasten
The following example shows how to use the NLSSORT function in comparison
operations:
SELECT * FROM test WHERE name > 'Gaberd'
ORDER BY name;
no rows selected
SELECT * FROM test WHERE NLSSORT(name, 'NLS_SORT = XDanish') >
NLSSORT('Gaberd', 'NLS_SORT = XDanish')
ORDER BY name;
NAME
---------------
Gaardiner
Gaasten
If you frequently use NLSSORT in comparison operations with the same linguistic sort
sequence, then consider this more efficient alternative: Set the NLS_COMP parameter
(either for the database or for the current session) to LINGUISTIC, and set the NLS_
SORT parameter for the session to the desired sort sequence. Oracle Database will use
that sort sequence by default for all sorting and comparison operations during the
current session:
ALTER SESSION SET NLS_COMP = 'LINGUISTIC';
ALTER SESSION SET NLS_SORT = 'XDanish';
SELECT * FROM test WHERE name > 'Gaberd'
ORDER BY name;
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
NTH_VALUE
5-122 Oracle Database SQL Language Reference
NAME
---------------
Gaardiner
Gaasten
NTH_VALUE
Syntax
Purpose
NTH_VALUE returns the measure_expr value of the nth row in the window defined
by the analytic_clause. The returned value has the data type of the measure_
expr.
■ {RESPECT | IGNORE} NULLS determines whether null values of measure_expr
are included in or eliminated from the calculation. The default is RESPECT NULLS.
■ n determines the nth row for which the measure value is to be returned. n can be a
constant, bind variable, column, or an expression involving them, as long as it
resolves to a positive integer. The function returns NULL if the data source window
has fewer than n rows. If n is null, then the function returns an error.
■ FROM {FIRST | LAST} determines whether the calculation begins at the first or last
row of the window. The default is FROM FIRST.
Examples
The following example shows the minimum amount_sold value for the second
channel_id in ascending order for each prod_id between 13 and 16:
SELECT prod_id, channel_id, MIN(amount_sold),
NTH_VALUE(MIN(amount_sold), 2) OVER (PARTITION BY prod_id ORDER BY channel_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) NV
FROM sales
WHERE prod_id BETWEEN 13 and 16 GROUP BY prod_id, channel_id;
PROD_ID CHANNEL_ID MIN(AMOUNT_SOLD) NV
---------- ---------- ---------------- ----------
13 2 907.34 906.2
13 3 906.2 906.2
13 4 842.21 906.2
See Also: Oracle Database Globalization Support Guide for information
on sort sequences
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the analytic_clause
See Also: Oracle Database Data Warehousing Guide for more
information on the use of this function
NTH_VALUE ( measure_expr , n )
FROM
FIRST
LAST
RESPECT
IGNORE
NULLS
OVER ( analytic_clause )
NTILE
Functions 5-123
14 2 1015.94 1036.72
14 3 1036.72 1036.72
14 4 935.79 1036.72
15 2 871.19 871.19
15 3 871.19 871.19
15 4 871.19 871.19
16 2 266.84 266.84
16 3 266.84 266.84
16 4 266.84 266.84
16 9 11.99 266.84
13 rows selected.
NTILE
Syntax
Purpose
NTILE is an analytic function. It divides an ordered data set into a number of buckets
indicated by expr and assigns the appropriate bucket number to each row. The
buckets are numbered 1 through expr. The expr value must resolve to a positive
constant for each partition. Oracle Database expects an integer, and if expr is a
noninteger constant, then Oracle truncates the value to an integer. The return value is
NUMBER.
The number of rows in the buckets can differ by at most 1. The remainder values (the
remainder of number of rows divided by buckets) are distributed one for each bucket,
starting with bucket 1.
If expr is greater than the number of rows, then a number of buckets equal to the
number of rows will be filled, and the remaining buckets will be empty.
You cannot nest analytic functions by using NTILE or any other analytic function for
expr. However, you can use other built-in function expressions for expr.
Examples
The following example divides into 4 buckets the values in the salary column of the
oe.employees table from Department 100. The salary column has 6 values in this
department, so the two extra values (the remainder of 6 / 4) are allocated to buckets 1
and 2, which therefore have one more value than buckets 3 or 4.
SELECT last_name, salary, NTILE(4) OVER (ORDER BY salary DESC)
AS quartile FROM employees
WHERE department_id = 100
ORDER BY last_name, salary, quartile;
LAST_NAME SALARY QUARTILE
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of expr
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and Table 3–10, " Implicit Type Conversion
Matrix" on page 3-41 for more information on implicit conversion
NTILE ( expr ) OVER (
query_partition_clause
order_by_clause )
NULLIF
5-124 Oracle Database SQL Language Reference
------------------------- ---------- ----------
Chen 8200 2
Faviet 9000 1
Greenberg 12000 1
Popp 6900 4
Sciarra 7700 3
Urman 7800 2
NULLIF
Syntax
Purpose
NULLIF compares expr1 and expr2. If they are equal, then the function returns null.
If they are not equal, then the function returns expr1. You cannot specify the literal
NULL for expr1.
If both arguments are numeric data types, then Oracle Database determines the
argument with the higher numeric precedence, implicitly converts the other argument
to that data type, and returns that data type. If the arguments are not numeric, then
they must be of the same data type, or Oracle returns an error.
The NULLIF function is logically equivalent to the following CASE expression:
CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END
Examples
The following example selects those employees from the sample schema hr who have
changed jobs since they were hired, as indicated by a job_id in the job_history
table different from the current job_id in the employees table:
SELECT e.last_name, NULLIF(e.job_id, j.job_id) "Old Job ID"
FROM employees e, job_history j
WHERE e.employee_id = j.employee_id
ORDER BY last_name, "Old Job ID";
LAST_NAME Old Job ID
------------------------- ----------
De Haan AD_VP
Hartstein MK_MAN
Kaufling ST_MAN
Kochhar AD_VP
Kochhar AD_VP
Raphaely PU_MAN
Taylor SA_REP
Taylor
Whalen AD_ASST
Whalen
See Also: "CASE Expressions" on page 6-5
NULLIF ( expr1 , expr2 )
NUMTODSINTERVAL
Functions 5-125
NUMTODSINTERVAL
Syntax
Purpose
NUMTODSINTERVAL converts n to an INTERVAL DAY TO SECOND literal. The argument
n can be any NUMBER value or an expression that can be implicitly converted to a
NUMBER value. The argument interval_unit can be of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type. The value for interval_unit specifies the unit of n and must
resolve to one of the following string values:
■ 'DAY'
■ 'HOUR'
■ 'MINUTE'
■ 'SECOND'
interval_unit is case insensitive. Leading and trailing values within the
parentheses are ignored. By default, the precision of the return is 9.
Examples
The following example uses NUMTODSINTERVAL in a COUNT analytic function to
calculate, for each employee, the number of employees hired by the same manager
within the past 100 days from his or her hire date. Refer to "Analytic Functions" on
page 5-11 for more information on the syntax of the analytic functions.
SELECT manager_id, last_name, hire_date,
COUNT(*) OVER (PARTITION BY manager_id ORDER BY hire_date
RANGE NUMTODSINTERVAL(100, 'day') PRECEDING) AS t_count
FROM employees;
MANAGER_ID LAST_NAME HIRE_DATE T_COUNT
---------- ------------------------- --------- ----------
100 De Haan 13-JAN-01 1
100 Raphaely 07-DEC-02 1
100 Kaufling 01-MAY-03 1
100 Hartstein 17-FEB-04 1
100 Weiss 18-JUL-04 1
. . .
149 Grant 24-MAY-07 1
149 Johnson 04-JAN-08 1
201 Fay 17-AUG-05 1
205 Gietz 07-JUN-02 1
King 17-JUN-03 1
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
NUMTODSINTERVAL ( n , ’ interval_unit ’ )
NUMTOYMINTERVAL
5-126 Oracle Database SQL Language Reference
NUMTOYMINTERVAL
Syntax
Purpose
NUMTOYMINTERVAL converts number n to an INTERVAL YEAR TO MONTH literal. The
argument n can be any NUMBER value or an expression that can be implicitly converted
to a NUMBER value. The argument interval_unit can be of CHAR, VARCHAR2,
NCHAR, or NVARCHAR2 data type. The value for interval_unit specifies the unit of
n and must resolve to one of the following string values:
■ 'YEAR'
■ 'MONTH'
interval_unit is case insensitive. Leading and trailing values within the
parentheses are ignored. By default, the precision of the return is 9.
Examples
The following example uses NUMTOYMINTERVAL in a SUM analytic function to
calculate, for each employee, the total salary of employees hired in the past one year
from his or her hire date. Refer to "Analytic Functions" on page 5-11 for more
information on the syntax of the analytic functions.
SELECT last_name, hire_date, salary, SUM(salary)
OVER (ORDER BY hire_date
RANGE NUMTOYMINTERVAL(1,'year') PRECEDING) AS t_sal
FROM employees
ORDER BY last_name, hire_date;
LAST_NAME HIRE_DATE SALARY T_SAL
------------------------- --------- ---------- ----------
Abel 11-MAY-04 11000 90300
Ande 24-MAR-08 6400 112500
Atkinson 30-OCT-05 2800 177000
. . .
Walsh 24-APR-06 3100 177200
Weiss 18-JUL-04 8000 70900
Whalen 17-SEP-03 4400 54000
Zlotkey 29-JAN-08 10500 119000
NVL
Syntax
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
NUMTOYMINTERVAL ( n , ’ interval_unit ’ )
NVL ( expr1 , expr2 )
NVL2
Functions 5-127
Purpose
NVL lets you replace null (returned as a blank) with a string in the results of a query. If
expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.
The arguments expr1 and expr2 can have any data type. If their data types are
different, then Oracle Database implicitly converts one to the other. If they are cannot
be converted implicitly, the database returns an error. The implicit conversion is
implemented as follows:
■ If expr1 is character data, then Oracle Database converts expr2 to the data type
of expr1 before comparing them and returns VARCHAR2 in the character set of
expr1.
■ If expr1 is numeric, then Oracle determines which argument has the highest
numeric precedence, implicitly converts the other argument to that data type, and
returns that data type.
Examples
The following example returns a list of employee names and commissions,
substituting "Not Applicable" if the employee receives no commission:
SELECT last_name, NVL(TO_CHAR(commission_pct), 'Not Applicable')
"COMMISSION" FROM employees
WHERE last_name LIKE 'B%'
ORDER BY last_name;
LAST_NAME COMMISSION
------------------------- ----------------------------------------
Baer Not Applicable
Baida Not Applicable
Banda .1
Bates .15
Bell Not Applicable
Bernstein .25
Bissot Not Applicable
Bloom .2
Bull Not Applicable
NVL2
Syntax
Purpose
NVL2 lets you determine the value returned by a query based on whether a specified
expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1
is null, then NVL2 returns expr3.
The argument expr1 can have any data type. The arguments expr2 and expr3 can
have any data types except LONG.
If the data types of expr2 and expr3 are different:
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
NVL2 ( expr1 , expr2 , expr3 )
ORA_DST_AFFECTED
5-128 Oracle Database SQL Language Reference
■ If expr2 is character data, then Oracle Database converts expr3 to the data type
of expr2 before comparing them unless expr3 is a null constant. In that case, a
data type conversion is not necessary. Oracle returns VARCHAR2 in the character
set of expr2.
■ If expr2 is character data, then Oracle Database converts expr3 to the data type
of expr2 before returning a value unless expr3 is a null constant. In that case, a
data type conversion is not necessary, and the database returns VARCHAR2 in the
character set of expr2.
Examples
The following example shows whether the income of some employees is made up of
salary plus commission, or just salary, depending on whether the commission_pct
column of employees is null or not.
SELECT last_name, salary, NVL2(commission_pct,
salary + (salary * commission_pct), salary) income
FROM employees WHERE last_name like 'B%'
ORDER BY last_name;
LAST_NAME SALARY INCOME
------------------------- ---------- ----------
Baer 10000 10000
Baida 2900 2900
Banda 6200 6882
Bates 7300 8468
Bell 4000 4000
Bernstein 9500 11970
Bissot 3300 3300
Bloom 10000 12100
Bull 4100 4100
ORA_DST_AFFECTED
Syntax
Purpose
ORA_DST_AFFECTED is useful when you are changing the time zone data file for your
database. The function takes as an argument a datetime expression that resolves to a
TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP
WITH TIME ZONE values. The function returns 1 if the datetime value is affected by or
will result in a "nonexisting time" or "duplicate time" error with the new time zone
data. Otherwise, it returns 0.
This function can be issued only when changing the time zone data file of the database
and upgrading the timestamp with the time zone data, and only between the
execution of the DBMS_DST.BEGIN_PREPARE and the DBMS_DST.END_PREPARE
procedures or between the execution of the DBMS_DST.BEGIN_UPGRADE and the
DBMS_DST.END_UPGRADE procedures.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
ORA_DST_AFFECTED ( datetime_expr )
ORA_DST_CONVERT
Functions 5-129
ORA_DST_CONVERT
Syntax
Purpose
ORA_DST_CONVERT is useful when you are changing the time zone data file for your
database. The function lets you specify error handling for a specified datetime
expression.
■ For datetime_expr, specify a datetime expression that resolves to a TIMESTAMP
WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP WITH TIME
ZONE values.
■ The optional second argument specifies handling of "duplicate time" errors.
Specify 0 (false) to suppress the error by returning the source datetime value. This
is the default. Specify 1 (true) to allow the database to return the duplicate time
error.
■ The optional third argument specifies handling of "nonexisting time" errors.
Specify 0 (false) to suppress the error by returning the source datetime value. This
is the default. Specify 1 (true) to allow the database to return the nonexisting time
error.
If no error occurs, this function returns a value of the same data type as datetime_
expr (a TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains
TIMESTAMP WITH TIME ZONE values). The returned datetime value when interpreted
with the new time zone file corresponds to datetime_expr interpreted with the old
time zone file.
This function can be issued only when changing the time zone data file of the database
and upgrading the timestamp with the time zone data, and only between the
execution of the DBMS_DST.BEGIN_UPGRADE and the DBMS_DST.END_UPGRADE
procedures.
See Also: Oracle Database Globalization Support Guide for more
information on time zone datafiles and on how Oracle Database
handles daylight saving time, and Oracle Database PL/SQL Packages and
Types Reference for information on the DBMS_DST package
See Also: Oracle Database Globalization Support Guide for more
information on time zone datafiles and on how Oracle Database
handles daylight saving time, and Oracle Database PL/SQL Packages and
Types Reference for information on the DBMS_DST package
ORA_DST_CONVERT ( datetime_expr
, integer
, integer
)
ORA_DST_ERROR
5-130 Oracle Database SQL Language Reference
ORA_DST_ERROR
Syntax
Purpose
ORA_DST_ERROR is useful when you are changing the time zone data file for your
database. The function takes as an argument a datetime expression that resolves to a
TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP
WITH TIME ZONE values, and indicates whether the datetime value will result in an
error with the new time zone data. The return values are:
■ 0: the datetime value does not result in an error with the new time zone data.
■ 1878: the datetime value results in a "nonexisting time" error.
■ 1883: the datetime value results in a "duplicate time" error.
This function can be issued only when changing the time zone data file of the database
and upgrading the timestamp with the time zone data, and only between the
execution of the DBMS_DST.BEGIN_PREPARE and the DBMS_DST.END_PREPARE
procedures or between the execution of the DBMS_DST.BEGIN_UPGRADE and the
DBMS_DST.END_UPGRADE procedures.
ORA_HASH
Syntax
Purpose
ORA_HASH is a function that computes a hash value for a given expression. This
function is useful for operations such as analyzing a subset of data and generating a
random sample.
■ The expr argument determines the data for which you want Oracle Database to
compute a hash value. There are no restrictions on the length of data represented
by expr, which commonly resolves to a column name. The expr cannot be a
LONG or LOB type. It cannot be a user-defined object type unless it is a nested table
type. The hash value for nested table types does not depend on the order of
elements in the collection. All other data types are supported for expr.
■ The optional max_bucket argument determines the maximum bucket value
returned by the hash function. You can specify any value between 0 and
4294967295. The default is 4294967295.
See Also: Oracle Database Globalization Support Guide for more
information on time zone datafiles and on how Oracle Database
handles daylight saving time, and Oracle Database PL/SQL Packages and
Types Reference for information on the DBMS_DST package
ORA_DST_ERROR ( datetime_expr )
ORA_HASH ( expr
, max_bucket
, seed_value
)
PATH
Functions 5-131
■ The optional seed_value argument enables Oracle to produce many different
results for the same set of data. Oracle applies the hash function to the
combination of expr and seed_value. You can specify any value between 0 and
4294967295. The default is 0.
The function returns a NUMBER value.
Examples
The following example creates a hash value for each combination of customer ID and
product ID in the sh.sales table, divides the hash values into a maximum of 100
buckets, and returns the sum of the amount_sold values in the first bucket (bucket 0).
The third argument (5) provides a seed value for the hash function. You can obtain
different hash results for the same query by changing the seed value.
SELECT SUM(amount_sold) FROM sales
WHERE ORA_HASH(CONCAT(cust_id, prod_id), 99, 5) = 0;
SUM(AMOUNT_SOLD)
----------------
989431.14
PATH
Syntax
Purpose
PATH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH
conditions. It returns the relative path that leads to the resource specified in the parent
condition.
The correlation_integer can be any NUMBER integer and is used to correlate this
ancillary function with its primary condition. Values less than 1 are treated as 1.
Example
Refer to the related function DEPTH on page 5-63 for an example using both of these
ancillary functions of the EQUALS_PATH and UNDER_PATH conditions.
See Also: EQUALS_PATH Condition on page 7-19 and UNDER_
PATH Condition on page 7-20
PATH ( correlation_integer )
PERCENT_RANK
5-132 Oracle Database SQL Language Reference
PERCENT_RANK
Aggregate Syntax
percent_rank_aggregate::=
Analytic Syntax
percent_rank_analytic::=
Purpose
PERCENT_RANK is similar to the CUME_DIST (cumulative distribution) function. The
range of values returned by PERCENT_RANK is 0 to 1, inclusive. The first row in any set
has a PERCENT_RANK of 0. The return value is NUMBER.
■ As an aggregate function, PERCENT_RANK calculates, for a hypothetical row r
identified by the arguments of the function and a corresponding sort specification,
the rank of row r minus 1 divided by the number of rows in the aggregate group.
This calculation is made as if the hypothetical row r were inserted into the group
of rows over which Oracle Database is to aggregate.
The arguments of the function identify a single hypothetical row within each
aggregate group. Therefore, they must all evaluate to constant expressions within
each aggregate group. The constant argument expressions and the expressions in
the ORDER BY clause of the aggregate match by position. Therefore the number of
arguments must be the same and their types must be compatible.
■ As an analytic function, for a row r, PERCENT_RANK calculates the rank of r
minus 1, divided by 1 less than the number of rows being evaluated (the entire
query result set or a partition).
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
PERCENT_RANK ( expr
,
) WITHIN GROUP
( ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
PERCENT_RANK ( ) OVER (
query_partition_clause
order_by_clause )
PERCENTILE_CONT
Functions 5-133
Aggregate Example
The following example calculates the percent rank of a hypothetical employee in the
sample table hr.employees with a salary of $15,500 and a commission of 5%:
SELECT PERCENT_RANK(15000, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) "Percent-Rank"
FROM employees;
Percent-Rank
------------
.971962617
Analytic Example
The following example calculates, for each employee, the percent rank of the
employee's salary within the department:
SELECT department_id, last_name, salary,
PERCENT_RANK()
OVER (PARTITION BY department_id ORDER BY salary DESC) AS pr
FROM employees
ORDER BY pr, salary;
DEPARTMENT_ID LAST_NAME SALARY PR
------------- ------------------------- ---------- ----------
10 Whalen 4400 0
40 Marvis 6500 0
. . .
80 Vishney 10500 .176470588
50 Everett 3900 .181818182
30 Khoo 3100 .2
. . .
80 Johnson 6200 .941176471
50 Markle 2200 .954545455
50 Philtanker 2200 .954545455
50 Olson 2100 1
. . .
PERCENTILE_CONT
Syntax
Purpose
PERCENTILE_CONT is an inverse distribution function that assumes a continuous
distribution model. It takes a percentile value and a sort specification, and returns an
interpolated value that would fall into that percentile value with respect to the sort
specification. Nulls are ignored in the calculation.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the OVER clause
PERCENTILE_CONT ( expr ) WITHIN GROUP ( ORDER BY expr
DESC
ASC
)
OVER ( query_partition_clause )
PERCENTILE_CONT
5-134 Oracle Database SQL Language Reference
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
The first expr must evaluate to a numeric value between 0 and 1, because it is a
percentile value. This expr must be constant within each aggregation group. The
ORDER BY clause takes a single expression that must be a numeric or datetime value,
as these are the types over which Oracle can perform interpolation.
The result of PERCENTILE_CONT is computed by linear interpolation between values
after ordering them. Using the percentile value (P) and the number of rows (N) in the
aggregation group, you can compute the row number you are interested in after
ordering the rows with respect to the sort specification. This row number (RN) is
computed according to the formula RN = (1+ (P*(N-1)). The final result of the
aggregate function is computed by linear interpolation between the values from rows
at row numbers CRN = CEILING(RN) and FRN = FLOOR(RN).
The final result will be:
If (CRN = FRN = RN) then the result is
(value of expression from row at RN)
Otherwise the result is
(CRN - RN) * (value of expression for row at FRN) +
(RN - FRN) * (value of expression for row at CRN)
You can use the PERCENTILE_CONT function as an analytic function. You can specify
only the query_partitioning_clause in its OVER clause. It returns, for each row,
the value that would fall into the specified percentile among a set of values within
each partition.
The MEDIAN function is a specific case of PERCENTILE_CONT where the percentile
value defaults to 0.5. For more information, refer to MEDIAN on page 5-109.
Aggregate Example
The following example computes the median salary in each department:
SELECT department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary DESC)
"Median cont",
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC)
"Median disc"
FROM employees GROUP BY department_id
ORDER BY department_id, "Median cont", "Median disc;
DEPARTMENT_ID Median cont Median disc
------------- ----------- -----------
10 4400 4400
20 9500 13000
30 2850 2900
40 6500 6500
50 3100 3100
60 4800 4800
70 10000 10000
80 8900 9000
90 17000 17000
100 8000 8200
110 10150 12000
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
PERCENTILE_DISC
Functions 5-135
7000 7000
PERCENTILE_CONT and PERCENTILE_DISC may return different results.
PERCENTILE_CONT returns a computed result after doing linear interpolation.
PERCENTILE_DISC simply returns a value from the set of values that are aggregated
over. When the percentile value is 0.5, as in this example, PERCENTILE_CONT returns
the average of the two middle values for groups with even number of elements,
whereas PERCENTILE_DISC returns the value of the first one among the two middle
values. For aggregate groups with an odd number of elements, both functions return
the value of the middle element.
Analytic Example
In the following example, the median for Department 60 is 4800, which has a
corresponding percentile (Percent_Rank) of 0.5. None of the salaries in Department
30 have a percentile of 0.5, so the median value must be interpolated between 2900
(percentile 0.4) and 2800 (percentile 0.6), which evaluates to 2850.
SELECT last_name, salary, department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary DESC)
OVER (PARTITION BY department_id) "Percentile_Cont",
PERCENT_RANK()
OVER (PARTITION BY department_id ORDER BY salary DESC) "Percent_Rank"
FROM employees WHERE department_id IN (30, 60)
ORDER BY last_name, salary, department_id, "Percentile_Cont", "Percent_Rank";
LAST_NAME SALARY DEPARTMENT_ID Percentile_Cont Percent_Rank
------------------------- ---------- ------------- --------------- ------------
Austin 4800 60 4800 .5
Baida 2900 30 2850 .4
Colmenares 2500 30 2850 1
Ernst 6000 60 4800 .25
Himuro 2600 30 2850 .8
Hunold 9000 60 4800 0
Khoo 3100 30 2850 .2
Lorentz 4200 60 4800 1
Pataballa 4800 60 4800 .5
Raphaely 11000 30 2850 0
Tobias 2800 30 2850 .6
PERCENTILE_DISC
Syntax
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions of the OVER clause
PERCENTILE_DISC ( expr ) WITHIN GROUP ( ORDER BY expr
DESC
ASC
)
OVER ( query_partition_clause )
PERCENTILE_DISC
5-136 Oracle Database SQL Language Reference
Purpose
PERCENTILE_DISC is an inverse distribution function that assumes a discrete
distribution model. It takes a percentile value and a sort specification and returns an
element from the set. Nulls are ignored in the calculation.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
The first expr must evaluate to a numeric value between 0 and 1, because it is a
percentile value. This expression must be constant within each aggregate group. The
ORDER BY clause takes a single expression that can be of any type that can be sorted.
For a given percentile value P, PERCENTILE_DISC sorts the values of the expression
in the ORDER BY clause and returns the value with the smallest CUME_DIST value
(with respect to the same sort specification) that is greater than or equal to P.
Aggregate Example
See aggregate example for PERCENTILE_CONT on page 5-133.
Analytic Example
The following example calculates the median discrete percentile of the salary of each
employee in the sample table hr.employees:
SELECT last_name, salary, department_id,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC)
OVER (PARTITION BY department_id) "Percentile_Disc",
CUME_DIST() OVER (PARTITION BY department_id
ORDER BY salary DESC) "Cume_Dist"
FROM employees where department_id in (30, 60)
ORDER BY last_name, salary, department_id, "Percentile_Disc", "Cume_Dist";
LAST_NAME SALARY DEPARTMENT_ID Percentile_Disc Cume_Dist
------------------------- ---------- ------------- --------------- ----------
Austin 4800 60 4800 .8
Baida 2900 30 2900 .5
Colmenares 2500 30 2900 1
Ernst 6000 60 4800 .4
Himuro 2600 30 2900 .833333333
Hunold 9000 60 4800 .2
Khoo 3100 30 2900 .333333333
Lorentz 4200 60 4800 1
Pataballa 4800 60 4800 .8
Raphaely 11000 30 2900 .166666667
Tobias 2800 30 2900 .666666667
The median value for Department 30 is 2900, which is the value whose corresponding
percentile (Cume_Dist) is the smallest value greater than or equal to 0.5. The median
value for Department 60 is 4800, which is the value whose corresponding percentile is
the smallest value greater than or equal to 0.5.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
POWERMULTISET
Functions 5-137
POWER
Syntax
Purpose
POWER returns n2 raised to the n1 power. The base n2 and the exponent n1 can be any
numbers, but if n2 is negative, then n1 must be an integer.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. If any argument is BINARY_
FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise
the function returns NUMBER.
Examples
The following example returns 3 squared:
SELECT POWER(3,2) "Raised" FROM DUAL;
Raised
----------
9
POWERMULTISET
Syntax
Purpose
POWERMULTISET takes as input a nested table and returns a nested table of nested
tables containing all nonempty subsets (called submultisets) of the input nested table.
■ expr can be any expression that evaluates to a nested table.
■ If expr resolves to null, then Oracle Database returns NULL.
■ If expr resolves to a nested table that is empty, then Oracle returns an error.
■ The element types of the nested table must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Examples
First, create a data type that is a nested table of the cust_address_tab_type data
type:
CREATE TYPE cust_address_tab_tab_typ
AS TABLE OF cust_address_tab_typ;
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
Note: This function is not supported in PL/SQL.
POWER ( n2 , n1 )
POWERMULTISET ( expr )
POWERMULTISET_BY_CARDINALITY
5-138 Oracle Database SQL Language Reference
Now, select the nested table column cust_address_ntab from the customers_
demo table using the POWERMULTISET function:
SELECT CAST(POWERMULTISET(cust_address_ntab)
AS cust_address_tab_tab_typ)
FROM customers_demo;
CAST(POWERMULTISET(CUST_ADDRESS_NTAB) AS CUST_ADDRESS_TAB_TAB_TYP)
(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
------------------------------------------------------------------
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP
('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')))
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP
('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US')))
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP
('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')))
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP
('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US')))
. . .
The preceding example requires the customers_demo table and a nested table
column containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
POWERMULTISET_BY_CARDINALITY
Syntax
Purpose
POWERMULTISET_BY_CARDINALITY takes as input a nested table and a cardinality
and returns a nested table of nested tables containing all nonempty subsets (called
submultisets) of the nested table of the specified cardinality.
■ expr can be any expression that evaluates to a nested table.
■ cardinality can be any positive integer.
■ If expr resolves to null, then Oracle Database returns NULL.
■ If expr resolves to a nested table that is empty, then Oracle returns an error.
■ The element types of the nested table must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Examples
First, duplicate the elements in all the nested table rows to increase the cardinality of
the nested table rows to 2:
UPDATE customers_demo
SET cust_address_ntab = cust_address_ntab MULTISET UNION cust_address_ntab;
Note: This function is not supported in PL/SQL.
POWERMULTISET_BY_CARDINALITY ( expr , cardinality )
PREDICTION
Functions 5-139
Now, select the nested table column cust_address_ntab from the customers_
demo table using the POWERMULTISET_BY_CARDINALITY function:
SELECT CAST(POWERMULTISET_BY_CARDINALITY(cust_address_ntab, 2)
AS cust_address_tab_tab_typ)
FROM customers_demo;
CAST(POWERMULTISET_BY_CARDINALITY(CUST_ADDRESS_NTAB,2) AS CUST_ADDRESS_TAB_TAB_TYP)
(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
----------------------------------------------------------------------------------------
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP
(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'),
CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')))
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP
(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'),
CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US')))
CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP
(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'),
CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')))
. . .
The preceding example requires the customers_demo table and a nested table
column containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
PREDICTION
Syntax
cost_matrix_clause::=
mining_attribute_clause::=
Purpose
This function is for use with models created by the DBMS_DATA_MINING package or
with the Oracle Data Mining Java API. It returns the best prediction for the model. The
PREDICTION (
schema .
model
cost_matrix_clause
mining_attribute_clause )
COST
MODEL
AUTO
( class_value
,
) VALUES ( ( cost_value
,
)
,
)
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION
5-140 Oracle Database SQL Language Reference
data type returned depends on the target value type used during the build of the
model. For regression models, this function returns the expected value.
cost_matrix_clause The COST clause is relevant for all classification models.
■ Specify COST MODEL to indicate that the scoring should be performed by taking
into account the scoring cost matrix associated with the model. If no such scoring
cost matrix exists, then the database returns an error.
■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this case
the function returns the lowest cost prediction using the stored cost matrix if it
exists. If no stored cost matrix exists, then the function returns the highest
probability prediction.
■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to
specify an inline cost matrix. You can use an inline cost matrix regardless of
whether the model has an associated scoring cost matrix.
If you omit the cost_matrix_clause clause, then the best prediction is the target
class with the highest probability. If two or more classes are tied with the highest
probability, the database chooses one class.
mining_attribute_clause This maps the predictors that were provided when the
model was built. Specifying USING * maps to all to the columns and expressions that
can be retrieved from the underlying inputs (tables, views, and so on).
■ If you specify more predictors in the mining_attribute_clause than there are
predictors used by the model, then the extra expressions are silently ignored.
■ If you specify fewer predictors than are used during the build, then the operation
proceeds with the subset of predictors you specify and returns information on a
best-effort basis. All types of models will return a result regardless of the number
of predictors you specify in this clause.
■ If you specify a predictor with the same name as was used during the build but a
different data type, then the database implicitly converts to produce a predictor
value of the same type as the original build.
Example
The following example returns by gender the average age of customers who are likely
to use an affinity card. The PREDICTION function takes into account only the cust_
marital_status, education, and household_size predictors.
This example, and the prerequisite data mining operations, including the creation of
the view, can be found in the demo file $ORACLE_
HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_DATA_MINING package
PREDICTION_BOUNDS
Functions 5-141
is available in Oracle Data Mining Administrator's Guide. The example is presented here
to illustrate the syntactic use of the function.
SELECT cust_gender, COUNT(*) AS cnt, ROUND(AVG(age)) AS avg_age
FROM mining_data_apply_v
WHERE PREDICTION(DT_SH_Clas_sample COST MODEL
USING cust_marital_status, education, household_size) = 1
GROUP BY cust_gender
ORDER BY cust_gender;
C CNT AVG_AGE
- ---------- ----------
F 170 38
M 685 42
PREDICTION_BOUNDS
Syntax
mining_attribute_clause::=
Purpose
The PREDICTION_BOUNDS function is for use only with generalized linear models
(GLM). It returns an object with two NUMBER fields LOWER and UPPER. For a
regression mining function, the bounds apply to value of the prediction. For a
classification mining function, the bounds apply to the probability value. If the GLM
was built using ridge regression, or if the covariance matrix is found to be singular
during the build, then this function returns NULL for both fields.
■ For confidence_level, specify a number in the range (0,1). If you omit this
clause, then the default value is 0.95.
■ The class_value argument is valid for classification models but not for
regression models. By default, the function returns the bounds for the prediction
with the highest probability. You can use the class_value argument to filter out
the bounds value specific to a target value.
You can specify class_value while leaving confidence_level at its default
by specifying NULL for confidence_level.
PREDICTION_BOUNDS
(
schema .
model
, confidence_level
, class_value
mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION_COST
5-142 Oracle Database SQL Language Reference
■ The mining_attribute_clause has the same behavior for PREDICTION_
BOUNDS that it has for PREDICTION. Refer to mining_attribute_clause on
page 5-140.
Example
The following example returns the distribution of customers whose ages are predicted
to be between 25 and 45 years with 98% confidence.
This example and the prerequisite data mining operations can be found in the demo
file $ORACLE_HOME/rdbms/demo/dmglcdem.sql. The example is presented here to
illustrate the syntactic use of the function. General information on data mining demo
files is available in Oracle Data Mining Administrator's Guide.
SELECT count(cust_id) cust_count, cust_marital_status
FROM (SELECT cust_id, cust_marital_status
FROM mining_data_apply_v
WHERE PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).LOWER > 24 AND
PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).UPPER < 46)
GROUP BY cust_marital_status;
CUST_COUNT CUST_MARITAL_STATUS
-------------- --------------------
46 NeverM
7 Mabsent
5 Separ.
35 Divorc.
72 Married
PREDICTION_COST
Syntax
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining and about generalized linear models
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_DATA_MINING package
PREDICTION_COST (
schema .
model
, class
cost_matrix_clause mining_attribute_clause )
PREDICTION_COST
Functions 5-143
cost_matrix_clause::=
mining_attribute_clause::=
Purpose
This function is for use with any classification model created by the DBMS_DATA_
MINING package or with the Oracle Data Mining Java API. It returns a measure of cost
for a given prediction as an Oracle NUMBER.
If you specify the optional class parameter, then the function returns the cost for the
specified class. If you omit the class parameter, then the function returns the cost
associated with the best prediction. You can use this form in conjunction with the
PREDICTION function to obtain the best pair of prediction value and cost.
The COST clause is relevant for all classification models.
■ Specify COST MODEL to indicate that the scoring should be performed by taking
into account the scoring cost matrix associated with the model. If no such scoring
cost matrix exists, then the database returns an error.
■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this case
the function returns the cost using the stored cost matrix if it exists. If no stored
cost matrix exists, then the function applies the unit cost matrix (0's on the
diagonal and 1's everywhere else). This is equivalent to one minus probability for
the given class..
■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to
specify an inline cost matrix. You can use an inline cost matrix regardless of
whether the model has an associated scoring cost matrix.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
COST
MODEL
AUTO
( class_value
,
) VALUES ( ( cost_value
,
)
,
)
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION_DETAILS
5-144 Oracle Database SQL Language Reference
Example
The following example finds the ten customers living in Italy who are least expensive
to convince to use an affinity card.
This example and the prerequisite data mining operations can be found in the demo
file $ORACLE_HOME/rdbms/demo/dmdtdemo.sql. General information on data
mining demo files is available in Oracle Data Mining Administrator's Guide. The
example is presented here to illustrate the syntactic use of the function.
WITH
cust_italy AS (
SELECT cust_id
FROM mining_data_apply_v
WHERE country_name = 'Italy'
ORDER BY PREDICTION_COST(DT_SH_Clas_sample, 1 COST MODEL USING *) ASC, 1
)
SELECT cust_id
FROM cust_italy
WHERE rownum < 11;
CUST_ID
----------
100081
100179
100185
100324
100344
100554
100662
100733
101250
101306
10 rows selected.
PREDICTION_DETAILS
Syntax
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining in general and about costs in particular
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_DATA_MINING package
PREDICTION_DETAILS (
schema .
model mining_attribute_clause )
PREDICTION_DETAILS
Functions 5-145
mining_attribute_clause::=
Purpose
This function is for use with decision tree models created by the DBMS_DATA_MINING
package or with the Oracle Data Mining Java API. It returns an XML string containing
model-specific information related to the scoring of the input row. In this release, the
return value takes the following form:
<Node id= "integer"/>
where integer is the identifier of a data mining tree node. The form of the output is
subject to change. It may be enhanced to provide additional prediction information in
future releases.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
Example
The following example uses all attributes from the mining_data_apply_v view that
are relevant predictors for the DT_SH_Clas_sample decision tree model. For
customers who work in technical support and are under age 25, it returns the tree
node that results from scoring those records with the DT_SH_Clas_sample model.
This example, and the prerequisite data mining operations, including the creation of
the view, can be found in the demo files $ORACLE_
HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files
is available in Oracle Data Mining Administrator's Guide. The example is presented here
to illustrate the syntactic use of the function.
SELECT cust_id, education,
PREDICTION_DETAILS(DT_SH_Clas_sample using *) treenode
FROM mining_data_apply_v
WHERE occupation = 'TechSup' AND age < 25
ORDER BY cust_id;
CUST_ID EDUCATION TREENODE
---------- --------------------- -------------------------
100234 < Bach. <Node id="21"/>
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION_PROBABILITY
5-146 Oracle Database SQL Language Reference
100320 < Bach. <Node id="21"/>
100349 < Bach. <Node id="21"/>
100419 < Bach. <Node id="21"/>
100583 < Bach. <Node id="13"/>
100657 HS-grad <Node id="21"/>
101171 < Bach. <Node id="21"/>
101225 < Bach. <Node id="21"/>
101338 < Bach. <Node id="21"/>
9 rows selected.
PREDICTION_PROBABILITY
Syntax
mining_attribute_clause::=
Purpose
This function is for use with classification models created by the DBMS_DATA_MINING
package or with the Oracle Data Mining Java API. It is not valid with other types of
models. It returns the probability for a given prediction as an Oracle NUMBER.
If you specify the optional class parameter, then the function returns the probability
for the specified class. This is equivalent to the probability associated with choosing
the given target class value.
If you omit the class parameter, then the function returns the probability associated
with the best prediction. You can use this form in conjunction with the PREDICTION
function to obtain the best pair of prediction value and probability.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
PREDICTION_PROBABILITY (
schema .
model
, class
mining_attribute_clause )
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION_SET
Functions 5-147
Example
The following example returns the 10 customers living in Italy who are most likely to
use an affinity card.
This example, and the prerequisite data mining operations, including the creation of
the view, can be found in the demo files $ORACLE_
HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files
is available in Oracle Data Mining Administrator's Guide. The example is presented here
to illustrate the syntactic use of the function.
SELECT cust_id FROM (
SELECT cust_id
FROM mining_data_apply_v
WHERE country_name = 'Italy'
ORDER BY PREDICTION_PROBABILITY(DT_SH_Clas_sample, 1 USING *)
DESC, cust_id)
WHERE rownum < 11;
CUST_ID
----------
100081
100179
100185
100324
100344
100554
100662
100733
101250
101306
10 rows selected.
PREDICTION_SET
Syntax
cost_matrix_clause::=
PREDICTION_SET (
schema .
model
, bestN
, cutoff
cost_matrix_clause
mining_attribute_clause )
COST
MODEL
AUTO
( class_value
,
) VALUES ( ( cost_value
,
)
,
)
PREDICTION_SET
5-148 Oracle Database SQL Language Reference
mining_attribute_clause::=
Purpose
This function is for use with classification models created using the DBMS_DATA_
MINING package or with the Oracle Data Mining Java API. It is not valid with other
types of models. It returns a varray of objects containing all classes in a multiclass
classification scenario. The object fields are named PREDICTION, PROBABILITY, and
COST. The data type of the PREDICTION field depends on the target value type used
during the build of the model. The other two fields are both Oracle NUMBER. The
elements are returned in the order of best prediction to worst prediction.
■ For bestN, specify a positive integer to restrict the returned target classes to the N
having the highest probability, or lowest cost if cost matrix clause is specified. If
multiple classes are tied in the Nth value, then the database still returns only N
values. If you want to filter only by cutoff, specify NULL for this parameter.
■ For cutoff, specify a NUMBER value to restrict the returned target classes to those
with a probability greater than or equal to (or a cost less than or equal to if cost
matrix clause is specified) to the specified cutoff value. You can filter solely by
cutoff by specifying NULL for bestN.
When you specify values for both bestN and cutoff, you restrict the returned
predictions to only those that are the bestN and have a probability (or cost when
the cost_matrix_clause is specified) surpassing the threshold.
The cost_matrix_clause clause is relevant for all classification models. When you
specify this clause, both bestN and cutoff are treated with respect to the prediction
cost, not the prediction probability. The value of bestN restricts the result to the target
classes having the N best (lowest) costs, and cutoff restricts the target classes to those
with a cost less than or equal to the specified cutoff.
When you specify this clause, each object in the collection is a triplet of scalar values
containing the prediction value (the data type of which depends on the target value
type used during model build), the prediction probability, and the prediction cost
(both Oracle NUMBER).
If you omit this clause, then each object in the varray is a pair of scalars containing the
prediction value and prediction probability. The data types returned are as described
in the preceding paragraph.
■ Specify COST MODEL to indicate that the scoring should be performed by taking
into account the scoring cost matrix associated with the model. If no such cost
matrix exists, then the database returns an error.
■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this
case:
– If the stored cost matrix exists, then the result is the same as with COST MODEL.
– If no stored cost matrix exists, then the result is almost the same as without the
cost_matrix_clause, except the object in the collection is a triplet and the
USING
*
schema .
table . *
expr
AS alias
,
PREDICTION_SET
Functions 5-149
cost value is computed based on the unit cost matrix (0's on the diagonal and
1's everywhere else). This is equivalent to one minus probability for the given
class. The cutoff parameter is ignored if no stored cost matrix exists.
■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to
specify an inline cost matrix. You can use an inline cost matrix regardless of
whether the model has an associated scoring cost matrix.
The mining_attribute_clause behaves as described for the PREDICTION
function. Refer to mining_attribute_clause on page 5-140.
Example
The following example lists, for ten customers, the likelihood and cost of using or
rejecting an affinity card. This example has a binary target, but such a query is also
useful in multiclass classification such as Low, Med, and High.
This example and the prerequisite data mining operations can be found in the demo
file $ORACLE_HOME/rdbms/demo/dmdtdemo.sql. General information on data
mining demo files is available in Oracle Data Mining Administrator's Guide. The
example is presented here to illustrate the syntactic use of the function.
SELECT T.cust_id, S.prediction, S.probability, S.cost
FROM (SELECT cust_id,
PREDICTION_SET(dt_sh_clas_sample COST MODEL USING *) pset
FROM mining_data_apply_v
WHERE cust_id < 100011) T,
TABLE(T.pset) S
ORDER BY cust_id, S.prediction;
CUST_ID PREDICTION PROBABILITY COST
---------- ---------- ----------- -----
100001 0 .96682 .27
100001 1 .03318 .97
100002 0 .74038 2.08
100002 1 .25962 .74
100003 0 .90909 .73
100003 1 .09091 .91
100004 0 .90909 .73
100004 1 .09091 .91
100005 0 .27236 5.82
100005 1 .72764 .27
100006 0 1.00000 .00
100006 1 .00000 1.00
100007 0 .90909 .73
100007 1 .09091 .91
100008 0 .90909 .73
See Also:
■ Oracle Data Mining Concepts for detailed information about Oracle
Data Mining
■ Oracle Data Mining Administrator's Guide for information on the
demo programs available in the code
■ Oracle Data Mining Application Developer's Guide for detailed
information about real-time scoring with the Data Mining SQL
functions
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_DATA_MINING package
PRESENTNNV
5-150 Oracle Database SQL Language Reference
100008 1 .09091 .91
100009 0 .27236 5.82
100009 1 .72764 .27
100010 0 .80808 1.54
100010 1 .19192 .81
20 rows selected.
PRESENTNNV
Syntax
Purpose
The PRESENTNNV function can be used only in the model_clause of the SELECT
statement and then only on the right-hand side of a model rule. It returns expr1 when
cell_reference exists prior to the execution of the model_clause and is not null
when PRESENTNNV is evaluated. Otherwise it returns expr2. This function differs
from NVL2 in that NVL2 evaluates the data at the time it is executed, rather than
evaluating the data as it was prior to the execution of the model_clause.
Examples
In the following example, if a row containing sales for the Mouse Pad for the year 2002
exists, and the sales value is not null, then the sales value remains unchanged. If the
row exists and the sales value is null, then the sales value is set to 10. If the row does
not exist, then the row is created with the sales value set to 10.
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
( s['Mouse Pad', 2002] =
PRESENTNNV(s['Mouse Pad', 2002], s['Mouse Pad', 2002], 10)
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 3000.72
France Mouse Pad 2001 3269.09
France Mouse Pad 2002 10
France Standard Mouse 1998 2390.83
See Also:
■ model_clause on page 19-28 and "Model Expressions" on page 6-11
for the syntax and semantics
■ NVL2 on page 5-127 for comparison
PRESENTNNV ( cell_reference , expr1 , expr2 )
PRESENTV
Functions 5-151
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 1274.31
France Standard Mouse 2001 2164.54
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 7375.46
Germany Mouse Pad 2001 9535.08
Germany Mouse Pad 2002 10
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 2637.31
Germany Standard Mouse 2001 6456.13
18 rows selected.
The preceding example requires the view sales_view_ref. Refer to "Examples" on
page 19-36 to create this view.
PRESENTV
Syntax
Purpose
The PRESENTV function can be used only within the model_clause of the SELECT
statement and then only on the right-hand side of a model rule. It returns expr1
when, prior to the execution of the model_clause, cell_reference exists.
Otherwise it returns expr2.
Examples
In the following example, if a row containing sales for the Mouse Pad for the year 2000
exists, then the sales value for the Mouse Pad for the year 2001 is set to the sales value
for the Mouse Pad for the year 2000. If the row does not exist, then a row is created
with the sales value for the Mouse Pad for year 20001 set to 0.
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s['Mouse Pad', 2001] =
PRESENTV(s['Mouse Pad', 2000], s['Mouse Pad', 2000], 0)
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for the syntax and semantics
PRESENTV ( cell_reference , expr1 , expr2 )
PREVIOUS
5-152 Oracle Database SQL Language Reference
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 3000.72
France Mouse Pad 2001 3000.72
France Standard Mouse 1998 2390.83
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 1274.31
France Standard Mouse 2001 2164.54
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 7375.46
Germany Mouse Pad 2001 7375.46
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 2637.31
Germany Standard Mouse 2001 6456.13
16 rows selected.
The preceding example requires the view sales_view_ref. Refer to "The MODEL
clause: Examples" on page 19-45 to create this view.
PREVIOUS
Syntax
Purpose
The PREVIOUS function can be used only in the model_clause of the SELECT
statement and then only in the ITERATE ... [ UNTIL ] clause of the model_rules_
clause. It returns the value of cell_reference at the beginning of each iteration.
Examples
The following example repeats the rules, up to 1000 times, until the difference between
the values of cur_val at the beginning and at the end of an iteration is less than one:
SELECT dim_col, cur_val, num_of_iterations
FROM (SELECT 1 AS dim_col, 10 AS cur_val FROM dual)
MODEL
DIMENSION BY (dim_col)
MEASURES (cur_val, 0 num_of_iterations)
IGNORE NAV
UNIQUE DIMENSION
RULES ITERATE (1000) UNTIL (PREVIOUS(cur_val[1]) - cur_val[1] < 1)
(
cur_val[1] = cur_val[1]/2,
num_of_iterations[1] = num_of_iterations[1] + 1
);
DIM_COL CUR_VAL NUM_OF_ITERATIONS
---------- ---------- -----------------
1 .625 4
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for the syntax and semantics
PREVIOUS ( cell_reference )
RANK
Functions 5-153
RANK
Aggregate Syntax
rank_aggregate::=
Analytic Syntax
rank_analytic::=
Purpose
RANK calculates the rank of a value in a group of values. The return type is NUMBER.
Rows with equal values for the ranking criteria receive the same rank. Oracle Database
then adds the number of tied rows to the tied rank to calculate the next rank.
Therefore, the ranks may not be consecutive numbers. This function is useful for top-N
and bottom-N reporting.
■ As an aggregate function, RANK calculates the rank of a hypothetical row
identified by the arguments of the function with respect to a given sort
specification. The arguments of the function must all evaluate to constant
expressions within each aggregate group, because they identify a single row
within each group. The constant argument expressions and the expressions in the
ORDER BY clause of the aggregate match by position. Therefore, the number of
arguments must be the same and their types must be compatible.
■ As an analytic function, RANK computes the rank of each row returned from a
query with respect to the other rows returned by the query, based on the values of
the value_exprs in the order_by_clause.
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
RANK ( expr
,
) WITHIN GROUP
( ORDER BY expr
DESC
ASC
NULLS
FIRST
LAST
,
)
RANK ( ) OVER (
query_partition_clause
order_by_clause )
RANK
5-154 Oracle Database SQL Language Reference
Aggregate Example
The following example calculates the rank of a hypothetical employee in the sample
table hr.employees with a salary of $15,500 and a commission of 5%:
SELECT RANK(15500, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) "Rank"
FROM employees;
Rank
----------
105
Similarly, the following query returns the rank for a $15,500 salary among the
employee salaries:
SELECT RANK(15500) WITHIN GROUP
(ORDER BY salary DESC) "Rank of 15500"
FROM employees;
Rank of 15500
--------------
4
Analytic Example
The following statement ranks the employees in the sample hr schema in department
80 based on their salary and commission. Identical salary values receive the same rank
and cause nonconsecutive ranks. Compare this example with the example for DENSE_
RANK on page 5-61.
SELECT department_id, last_name, salary, commission_pct,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC, commission_pct) "Rank"
FROM employees WHERE department_id = 80
ORDER BY department_id, last_name, salary, commission_pct, "Rank";
DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank
------------- ------------------------- ---------- -------------- ----------
80 Abel 11000 .3 5
80 Ande 6400 .1 31
80 Banda 6200 .1 32
80 Bates 7300 .15 26
80 Bernstein 9500 .25 14
80 Bloom 10000 .2 9
80 Cambrault 7500 .2 23
80 Cambrault 11000 .3 5
80 Doran 7500 .3 24
80 Errazuriz 12000 .3 3
80 Fox 9600 .2 12
80 Greene 9500 .15 13
80 Hall 9000 .25 16
80 Hutton 8800 .25 18
80 Johnson 6200 .1 32
80 King 10000 .35 11
80 Kumar 6100 .1 34
80 Lee 6800 .1 30
80 Livingston 8400 .2 20
80 Marvins 7200 .1 27
80 McEwen 9000 .35 17
80 Olsen 8000 .2 21
80 Ozer 11500 .25 4
RAWTOHEX
Functions 5-155
80 Partners 13500 .3 2
80 Russell 14000 .4 1
80 Sewall 7000 .25 29
80 Smith 7400 .15 25
80 Smith 8000 .3 22
80 Sully 9500 .35 15
80 Taylor 8600 .2 19
80 Tucker 10000 .3 10
80 Tuvault 7000 .15 28
80 Vishney 10500 .25 8
80 Zlotkey 10500 .2 7
RATIO_TO_REPORT
Syntax
Purpose
RATIO_TO_REPORT is an analytic function. It computes the ratio of a value to the sum
of a set of values. If expr evaluates to null, then the ratio-to-report value also
evaluates to null.
The set of values is determined by the query_partition_clause. If you omit that
clause, then the ratio-to-report is computed over all rows returned by the query.
You cannot nest analytic functions by using RATIO_TO_REPORT or any other analytic
function for expr. However, you can use other built-in function expressions for expr.
Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr.
Examples
The following example calculates the ratio-to-report value of each purchasing clerk's
salary to the total of all purchasing clerks' salaries:
SELECT last_name, salary, RATIO_TO_REPORT(salary) OVER () AS rr
FROM employees
WHERE job_id = 'PU_CLERK'
ORDER BY last_name, salary, rr;
LAST_NAME SALARY RR
------------------------- ---------- ----------
Baida 2900 .208633094
Colmenares 2500 .179856115
Himuro 2600 .18705036
Khoo 3100 .223021583
Tobias 2800 .201438849
RAWTOHEX
Syntax
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions, including valid forms of expr
RATIO_TO_REPORT ( expr ) OVER (
query_partition_clause
)
RAWTOHEX ( raw )
RAWTONHEX
5-156 Oracle Database SQL Language Reference
Purpose
RAWTOHEX converts raw to a character value containing its hexadecimal
representation.
As a SQL built-in function, RAWTOHEX accepts an argument of any scalar data type
other than LONG, LONG RAW, CLOB, BLOB, or BFILE. It returns a VARCHAR2 value with
the hexadecimal representation of bytes that make up the value of raw. Each byte is
represented by two hexadecimal digits.
Examples
The following hypothetical example returns the hexadecimal equivalent of a RAW
column value:
SELECT RAWTOHEX(raw_column) "Graphics"
FROM graphics;
Graphics
--------
7D
RAWTONHEX
Syntax
Purpose
RAWTONHEX converts raw to a character value containing its hexadecimal
representation. RAWTONHEX (raw) is equivalent to TO_NCHAR(RAWTOHEX(raw)). The
value returned is always in the national character set.
Examples
The following hypothetical example returns the hexadecimal equivalent of a RAW
column value:
SELECT RAWTONHEX(raw_column),
DUMP ( RAWTONHEX (raw_column) ) "DUMP"
FROM graphics;
RAWTONHEX(RA) DUMP
----------------------- ------------------------------
7D Typ=1 Len=4: 0,55,0,68
Note: RAWTOHEX functions differently when used as a PL/SQL
built-in function. Refer to Oracle Database Advanced Application
Developer's Guide for more information.
See Also: "RAW and LONG RAW Data Types" on page 3-24 and
HEXTORAW on page 5-85
RAWTONHEX ( raw )
REFTOHEX
Functions 5-157
REF
Syntax
Purpose
REF takes as its argument a correlation variable (table alias) associated with a row of
an object table or an object view. A REF value is returned for the object instance that is
bound to the variable or row.
Examples
The sample schema oe contains a type called cust_address_typ, described as
follows:
Attribute Type
----------------------------- ----------------
STREET_ADDRESS VARCHAR2(40)
POSTAL_CODE VARCHAR2(10)
CITY VARCHAR2(30)
STATE_PROVINCE VARCHAR2(10)
COUNTRY_ID CHAR(2)
The following example creates a table based on the sample type oe.cust_address_
typ, inserts a row into the table, and retrieves a REF value for the object instance of the
type in the addresses table:
CREATE TABLE addresses OF cust_address_typ;
INSERT INTO addresses VALUES (
'123 First Street', '4GF H1J', 'Our Town', 'Ourcounty', 'US');
SELECT REF(e) FROM addresses e;
REF(E)
-----------------------------------------------------------------------------------
00002802097CD1261E51925B60E0340800208254367CD1261E51905B60E034080020825436010101820000
REFTOHEX
Syntax
Purpose
REFTOHEX converts argument expr to a character value containing its hexadecimal
equivalent. expr must return a REF.
See Also: Oracle Database Object-Relational Developer's Guide for
information on REFs
REF ( correlation_variable )
REFTOHEX ( expr )
REGEXP_COUNT
5-158 Oracle Database SQL Language Reference
Examples
The sample schema oe contains a warehouse_typ. The following example builds on
that type to illustrate how to convert the REF value of a column to a character value
containing its hexadecimal equivalent:
CREATE TABLE warehouse_table OF warehouse_typ
(PRIMARY KEY (warehouse_id));
CREATE TABLE location_table
(location_number NUMBER, building REF warehouse_typ
SCOPE IS warehouse_table);
INSERT INTO warehouse_table VALUES (1, 'Downtown', 99);
INSERT INTO location_table SELECT 10, REF(w) FROM warehouse_table w;
SELECT REFTOHEX(building) FROM location_table;
REFTOHEX(BUILDING)
--------------------------------------------------------------------------
0000220208859B5E9255C31760E034080020825436859B5E9255C21760E034080020825436
REGEXP_COUNT
Syntax
Purpose
REGEXP_COUNT complements the functionality of the REGEXP_INSTR function by
returning the number of times a pattern occurs in a source string. The function
evaluates strings using characters as defined by the input character set. It returns an
integer indicating the number of occurrences of pattern. If no match is found, then
the function returns 0.
■ source_char is a character expression that serves as the search value. It is
commonly a character column and can be of any of the data types CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
■ pattern is the regular expression. It is usually a text literal and can be of any of
the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512
bytes. If the data type of pattern is different from the data type of source_
char, then Oracle Database converts pattern to the data type of source_char.
REGEXP_COUNT ignores subexpression parentheses in pattern. For example, the
pattern '(123(45))' is equivalent to '12345'. For a listing of the operators you
can specify in pattern, refer to Appendix D, "Oracle Regular Expression
Support".
■ position is a positive integer indicating the character of source_char where
Oracle should begin the search. The default is 1, meaning that Oracle begins the
search at the first character of source_char. After finding the first occurrence of
pattern, the database searches for a second occurrence beginning with the first
character following the first occurrence.
REGEXP_COUNT ( source_char , pattern
, position
, match_param
)
REGEXP_COUNT
Functions 5-159
■ match_param is a text literal that lets you change the default matching behavior
of the function. You can specify one or more of the following values for match_
param:
– 'i' specifies case-insensitive matching.
– 'c' specifies case-sensitive matching.
– 'n' allows the period (.), which is the match-any-character character, to match
the newline character. If you omit this parameter, then the period does not
match the newline character.
– 'm' treats the source string as multiple lines. Oracle interprets the caret (^)
and dollar sign ($) as the start and end, respectively, of any line anywhere in
the source string, rather than only at the start or end of the entire source string.
If you omit this parameter, then Oracle treats the source string as a single line.
– 'x' ignores whitespace characters. By default, whitespace characters match
themselves.
If you specify multiple contradictory values, then Oracle uses the last value. For
example, if you specify 'ic', then Oracle uses case-sensitive matching. If you
specify a character other than those shown above, then Oracle returns an error.
If you omit match_param, then:
– The default case sensitivity is determined by the value of the NLS_SORT
parameter.
– A period (.) does not match the newline character.
– The source string is treated as a single line.
Examples
The following example shows that subexpressions parentheses in pattern are ignored:
SELECT REGEXP_COUNT('123123123123123', '(12)3', 1, 'i') REGEXP_COUNT
FROM DUAL;
REGEXP_COUNT
------------
5
In the following example, the function begins to evaluate the source string at the third
character, so skips over the first occurrence of pattern:
SELECT REGEXP_COUNT('123123123123', '123', 3, 'i') COUNT FROM DUAL;
COUNT
----------
3
REGEXP_INSTR
5-160 Oracle Database SQL Language Reference
REGEXP_INSTR
Syntax
Purpose
REGEXP_INSTR extends the functionality of the INSTR function by letting you search
a string for a regular expression pattern. The function evaluates strings using
characters as defined by the input character set. It returns an integer indicating the
beginning or ending position of the matched substring, depending on the value of the
return_option argument. If no match is found, then the function returns 0.
This function complies with the POSIX regular expression standard and the Unicode
Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle
Regular Expression Support".
■ source_char is a character expression that serves as the search value. It is
commonly a character column and can be of any of the data types CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
■ pattern is the regular expression. It is usually a text literal and can be of any of
the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512
bytes. If the data type of pattern is different from the data type of source_
char, then Oracle Database converts pattern to the data type of source_char.
For a listing of the operators you can specify in pattern, refer to Appendix D,
"Oracle Regular Expression Support".
■ position is a positive integer indicating the character of source_char where
Oracle should begin the search. The default is 1, meaning that Oracle begins the
search at the first character of source_char.
■ occurrence is a positive integer indicating which occurrence of pattern in
source_char Oracle should search for. The default is 1, meaning that Oracle
searches for the first occurrence of pattern. If occurrence is greater than 1,
then the database searches for the second occurrence beginning with the first
character following the first occurrence of pattern, and so forth. This behavior is
different from the INSTR function, which begins its search for the second
occurrence at the second character of the first occurrence.
■ return_option lets you specify what Oracle should return in relation to the
occurrence:
– If you specify 0, then Oracle returns the position of the first character of the
occurrence. This is the default.
– If you specify 1, then Oracle returns the position of the character following the
occurrence.
REGEXP_INSTR ( source_char , pattern
, position
, occurrence
, return_opt
, match_param
, subexpr
)
REGEXP_INSTR
Functions 5-161
■ match_parameter is a text literal that lets you change the default matching
behavior of the function. The behavior of this parameter is the same for this
function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for
detailed information.
■ For a pattern with subexpressions, subexpr is an integer from 0 to 9 indicating
which subexpression in pattern is the target of the function. The subexpr is a
fragment of pattern enclosed in parentheses. Subexpressions can be nested.
Subexpressions are numbered in order in which their left parentheses appear in
pattern. For example, consider the following expression:
0123(((abc)(de)f)ghi)45(678)
This expression has five subexpressions in the following order: "abcdefghi"
followed by "abcdef", "abc", "de" and "678".
If subexpr is zero, then the position of the entire substring that matches the
pattern is returned. If subexpr is greater than zero, then the position of the
substring fragment that corresponds to subexpression number subexpr in the
matched substring is returned. If pattern does not have at least subexpr
subexpressions, the function returns zero. A null subexpr value returns NULL.
The default value for subexpr is zero.
Examples
The following example examines the string, looking for occurrences of one or more
non-blank characters. Oracle begins searching at the first character in the string and
returns the starting position (default) of the sixth occurrence of one or more non-blank
characters.
SELECT
REGEXP_INSTR('500 Oracle Parkway, Redwood Shores, CA',
'[^ ]+', 1, 6) "REGEXP_INSTR"
FROM DUAL;
REGEXP_INSTR
------------
37
The following example examines the string, looking for occurrences of words
beginning with s, r, or p, regardless of case, followed by any six alphabetic characters.
Oracle begins searching at the third character in the string and returns the position in
the string of the character following the second occurrence of a seven-letter word
beginning with s, r, or p, regardless of case.
SELECT
REGEXP_INSTR('500 Oracle Parkway, Redwood Shores, CA',
'[s|r|p][[:alpha:]]{6}', 3, 2, 1, 'i') "REGEXP_INSTR"
FROM DUAL;
REGEXP_INSTR
------------
28
See Also:
■ INSTR on page 5-91 and REGEXP_SUBSTR on page 5-164
■ REGEXP_REPLACE on page 5-162 and REGEXP_LIKE Condition
on page 7-17
REGEXP_REPLACE
5-162 Oracle Database SQL Language Reference
The following examples use the subexpr argument to search for a particular
subexpression in pattern. The first statement returns the position in the source string
of the first character in the first subexpression, which is '123':
SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 1)
"REGEXP_INSTR" FROM DUAL;
REGEXP_INSTR
-------------------
1
The next statement returns the position in the source string of the first character in the
second subexpression, which is '45678':
SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 2)
"REGEXP_INSTR" FROM DUAL;
REGEXP_INSTR
-------------------
4
The next statement returns the position in the source string of the first character in the
fourth subexpression, which is '78':
SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 4)
"REGEXP_INSTR" FROM DUAL;
REGEXP_INSTR
-------------------
7
REGEXP_REPLACE
Syntax
Purpose
REGEXP_REPLACE extends the functionality of the REPLACE function by letting you
search a string for a regular expression pattern. By default, the function returns
source_char with every occurrence of the regular expression pattern replaced with
replace_string. The string returned is in the same character set as source_char.
The function returns VARCHAR2 if the first argument is not a LOB and returns CLOB if
the first argument is a LOB.
This function complies with the POSIX regular expression standard and the Unicode
Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle
Regular Expression Support".
REGEXP_REPLACE ( source_char , pattern
, replace_string
, position
, occurrence
, match_param
)
REGEXP_REPLACE
Functions 5-163
■ source_char is a character expression that serves as the search value. It is
commonly a character column and can be of any of the data types CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB.
■ pattern is the regular expression. It is usually a text literal and can be of any of
the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512
bytes. If the data type of pattern is different from the data type of source_
char, then Oracle Database converts pattern to the data type of source_char.
For a listing of the operators you can specify in pattern, refer to Appendix D,
"Oracle Regular Expression Support".
■ replace_string can be of any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. If replace_string is a CLOB or NCLOB, then
Oracle truncates replace_string to 32K. The replace_string can contain up
to 500 backreferences to subexpressions in the form n, where n is a number from
1 to 9. If n is the backslash character in replace_string, then you must precede
it with the escape character (). For more information on backreference
expressions, refer to the notes to "Oracle Regular Expression Support", Table D–1
on page D-1.
■ position is a positive integer indicating the character of source_char where
Oracle should begin the search. The default is 1, meaning that Oracle begins the
search at the first character of source_char.
■ occurrence is a nonnegative integer indicating the occurrence of the replace
operation:
– If you specify 0, then Oracle replaces all occurrences of the match.
– If you specify a positive integer n, then Oracle replaces the nth occurrence.
If occurrence is greater than 1, then the database searches for the second
occurrence beginning with the first character following the first occurrence of
pattern, and so forth. This behavior is different from the INSTR function, which
begins its search for the second occurrence at the second character of the first
occurrence.
■ match_parameter is a text literal that lets you change the default matching
behavior of the function. The behavior of this parameter is the same for this
function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for
detailed information.
Examples
The following example examines phone_number, looking for the pattern
xxx.xxx.xxxx. Oracle reformats this pattern with (xxx) xxx-xxxx.
SELECT
REGEXP_REPLACE(phone_number,
'([[:digit:]]{3}).([[:digit:]]{3}).([[:digit:]]{4})',
'(1) 2-3') "REGEXP_REPLACE"
FROM employees
ORDER BY "REGEXP_REPLACE";
REGEXP_REPLACE
See Also:
■ REPLACE on page 5-172
■ REGEXP_INSTR on page 5-160, REGEXP_SUBSTR on page 5-164,
and REGEXP_LIKE Condition on page 7-17
REGEXP_SUBSTR
5-164 Oracle Database SQL Language Reference
--------------------------------------------------------------------------------
(515) 123-4444
(515) 123-4567
(515) 123-4568
(515) 123-4569
(515) 123-5555
. . .
The following example examines country_name. Oracle puts a space after each
non-null character in the string.
SELECT
REGEXP_REPLACE(country_name, '(.)', '1 ') "REGEXP_REPLACE"
FROM countries;
REGEXP_REPLACE
--------------------------------------------------------------------------------
A r g e n t i n a
A u s t r a l i a
B e l g i u m
B r a z i l
C a n a d a
. . .
The following example examines the string, looking for two or more spaces. Oracle
replaces each occurrence of two or more spaces with a single space.
SELECT
REGEXP_REPLACE('500 Oracle Parkway, Redwood Shores, CA',
'( ){2,}', ' ') "REGEXP_REPLACE"
FROM DUAL;
REGEXP_REPLACE
--------------------------------------
500 Oracle Parkway, Redwood Shores, CA
REGEXP_SUBSTR
Syntax
Purpose
REGEXP_SUBSTR extends the functionality of the SUBSTR function by letting you
search a string for a regular expression pattern. It is also similar to REGEXP_INSTR,
but instead of returning the position of the substring, it returns the substring itself.
This function is useful if you need the contents of a match string but not its position in
the source string. The function returns the string as VARCHAR2 or CLOB data in the
same character set as source_char.
REGEXP_SUBSTR ( source_char , pattern
, position
, occurrence
, match_param
subexpr
)
REGEXP_SUBSTR
Functions 5-165
This function complies with the POSIX regular expression standard and the Unicode
Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle
Regular Expression Support".
■ source_char is a character expression that serves as the search value. It is
commonly a character column and can be of any of the data types CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
■ pattern is the regular expression. It is usually a text literal and can be of any of
the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512
bytes. If the data type of pattern is different from the data type of source_
char, then Oracle Database converts pattern to the data type of source_char.
For a listing of the operators you can specify in pattern, refer to Appendix D,
"Oracle Regular Expression Support".
■ position is a positive integer indicating the character of source_char where
Oracle should begin the search. The default is 1, meaning that Oracle begins the
search at the first character of source_char.
■ occurrence is a positive integer indicating which occurrence of pattern in
source_char Oracle should search for. The default is 1, meaning that Oracle
searches for the first occurrence of pattern.
If occurrence is greater than 1, then the database searches for the second
occurrence beginning with the first character following the first occurrence of
pattern, and so forth. This behavior is different from the SUBSTR function,
which begins its search for the second occurrence at the second character of the
first occurrence.
■ match_parameter is a text literal that lets you change the default matching
behavior of the function. The behavior of this parameter is the same for this
function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for
detailed information.
■ For a pattern with subexpressions, subexpr is a nonnegative integer from 0 to 9
indicating which subexpression in pattern is to be returned by the function. This
parameter has the same semantics that it has for the REGEXP_INSTR function.
Refer to REGEXP_INSTR on page 5-160 for more information.
Examples
The following example examines the string, looking for the first substring bounded by
commas. Oracle Database searches for a comma followed by one or more occurrences
of non-comma characters followed by a comma. Oracle returns the substring,
including the leading and trailing commas.
SELECT
REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA',
',[^,]+,') "REGEXPR_SUBSTR"
FROM DUAL;
REGEXPR_SUBSTR
-----------------
, Redwood Shores,
See Also:
■ SUBSTR on page 5-199 and REGEXP_INSTR on page 5-160
■ REGEXP_REPLACE on page 5-162, and REGEXP_LIKE Condition
on page 7-17
REGR_ (Linear Regression) Functions
5-166 Oracle Database SQL Language Reference
The following example examines the string, looking for http:// followed by a
substring of one or more alphanumeric characters and optionally, a period (.). Oracle
searches for a minimum of three and a maximum of four occurrences of this substring
between http:// and either a slash (/) or the end of the string.
SELECT
REGEXP_SUBSTR('http://www.example.com/products',
'http://([[:alnum:]]+.?){3,4}/?') "REGEXP_SUBSTR"
FROM DUAL;
REGEXP_SUBSTR
----------------------
http://www.example.com/
The next two examples use the subexpr argument to return a specific subexpression
of pattern. The first statement returns the first subexpression in pattern:
SELECT REGEXP_SUBSTR('1234567890', '(123)(4(56)(78))', 1, 1, 'i', 1)
"REGEXP_SUBSTR" FROM DUAL;
REGEXP_SUBSTR
-------------------
123
The next statement returns the fourth subexpression in pattern:
SELECT REGEXP_SUBSTR('1234567890', '(123)(4(56)(78))', 1, 1, 'i', 4)
"REGEXP_SUBSTR" FROM DUAL;
REGEXP_SUBSTR
-------------------
78
REGR_ (Linear Regression) Functions
The linear regression functions are:
■ REGR_SLOPE
■ REGR_INTERCEPT
■ REGR_COUNT
■ REGR_R2
■ REGR_AVGX
■ REGR_AVGY
■ REGR_SXX
■ REGR_SYY
■ REGR_SXY
REGR_ (Linear Regression) Functions
Functions 5-167
Syntax
linear_regr::=
Purpose
The linear regression functions fit an ordinary-least-squares regression line to a set of
number pairs. You can use them as both aggregate and analytic functions.
These functions take as arguments any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
Oracle applies the function to the set of (expr1, expr2) pairs after eliminating all
pairs for which either expr1 or expr2 is null. Oracle computes all the regression
functions simultaneously during a single pass through the data.
expr1 is interpreted as a value of the dependent variable (a y value), and expr2 is
interpreted as a value of the independent variable (an x value).
■ REGR_SLOPE returns the slope of the line. The return value is a numeric data type
and can be null. After the elimination of null (expr1, expr2) pairs, it makes the
following computation:
COVAR_POP(expr1, expr2) / VAR_POP(expr2)
■ REGR_INTERCEPT returns the y-intercept of the regression line. The return value
is a numeric data type and can be null. After the elimination of null (expr1,
expr2) pairs, it makes the following computation:
AVG(expr1) - REGR_SLOPE(expr1, expr2) * AVG(expr2)
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: "Aggregate Functions" on page 5-9 and "About SQL
Expressions" on page 6-1 for information on valid forms of expr
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
REGR_SLOPE
REGR_INTERCEPT
REGR_COUNT
REGR_R2
REGR_AVGX
REGR_AVGY
REGR_SXX
REGR_SYY
REGR_SXY
( expr1 , expr2 )
OVER ( analytic_clause )
REGR_ (Linear Regression) Functions
5-168 Oracle Database SQL Language Reference
■ REGR_COUNT returns an integer that is the number of non-null number pairs used
to fit the regression line.
■ REGR_R2 returns the coefficient of determination (also called R-squared or
goodness of fit) for the regression. The return value is a numeric data type and can
be null. VAR_POP(expr1) and VAR_POP(expr2) are evaluated after the
elimination of null pairs. The return values are:
NULL if VAR_POP(expr2) = 0
1 if VAR_POP(expr1) = 0 and
VAR_POP(expr2) != 0
POWER(CORR(expr1,expr),2) if VAR_POP(expr1) > 0 and
VAR_POP(expr2 != 0
All of the remaining regression functions return a numeric data type and can be null:
■ REGR_AVGX evaluates the average of the independent variable (expr2) of the
regression line. It makes the following computation after the elimination of null
(expr1, expr2) pairs:
AVG(expr2)
■ REGR_AVGY evaluates the average of the dependent variable (expr1) of the
regression line. It makes the following computation after the elimination of null
(expr1, expr2) pairs:
AVG(expr1)
REGR_SXY, REGR_SXX, REGR_SYY are auxiliary functions that are used to compute
various diagnostic statistics.
■ REGR_SXX makes the following computation after the elimination of null (expr1,
expr2) pairs:
REGR_COUNT(expr1, expr2) * VAR_POP(expr2)
■ REGR_SYY makes the following computation after the elimination of null (expr1,
expr2) pairs:
REGR_COUNT(expr1, expr2) * VAR_POP(expr1)
■ REGR_SXY makes the following computation after the elimination of null (expr1,
expr2) pairs:
REGR_COUNT(expr1, expr2) * COVAR_POP(expr1, expr2)
The following examples are based on the sample tables sh.sales and sh.products.
General Linear Regression Example
The following example provides a comparison of the various linear regression
functions used in their analytic form. The analytic form of these functions can be
useful when you want to use regression statistics for calculations such as finding the
salary predicted for each employee by the model. The sections that follow on the
individual linear regression functions contain examples of the aggregate form of these
functions.
SELECT job_id, employee_id ID, salary,
REGR_SLOPE(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) slope,
REGR_INTERCEPT(SYSDATE-hire_date, salary)
REGR_ (Linear Regression) Functions
Functions 5-169
OVER (PARTITION BY job_id) intcpt,
REGR_R2(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) rsqr,
REGR_COUNT(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) count,
REGR_AVGX(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) avgx,
REGR_AVGY(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) avgy
FROM employees
WHERE department_id in (50, 80)
ORDER BY job_id, employee_id;
JOB_ID ID SALARY SLOPE INTCPT RSQR COUNT AVGX AVGY
---------- ----- ---------- ----- --------- ----- ------ ---------- ---------
SA_MAN 145 14000 .355 -1707.035 .832 5 12200.000 2626.589
SA_MAN 146 13500 .355 -1707.035 .832 5 12200.000 2626.589
SA_MAN 147 12000 .355 -1707.035 .832 5 12200.000 2626.589
SA_MAN 148 11000 .355 -1707.035 .832 5 12200.000 2626.589
SA_MAN 149 10500 .355 -1707.035 .832 5 12200.000 2626.589
SA_REP 150 10000 .257 404.763 .647 29 8396.552 2561.244
SA_REP 151 9500 .257 404.763 .647 29 8396.552 2561.244
SA_REP 152 9000 .257 404.763 .647 29 8396.552 2561.244
SA_REP 153 8000 .257 404.763 .647 29 8396.552 2561.244
SA_REP 154 7500 .257 404.763 .647 29 8396.552 2561.244
SA_REP 155 7000 .257 404.763 .647 29 8396.552 2561.244
SA_REP 156 10000 .257 404.763 .647 29 8396.552 2561.244
...
REGR_SLOPE and REGR_INTERCEPT Examples
The following example calculates the slope and regression of the linear regression
model for time employed (SYSDATE - hire_date) and salary using the sample table
hr.employees. Results are grouped by job_id.
SELECT job_id,
REGR_SLOPE(SYSDATE-hire_date, salary) slope,
REGR_INTERCEPT(SYSDATE-hire_date, salary) intercept
FROM employees
WHERE department_id in (50,80)
GROUP BY job_id
ORDER BY job_id;
JOB_ID SLOPE INTERCEPT
---------- ----- ------------
SA_MAN .355 -1707.030762
SA_REP .257 404.767151
SH_CLERK .745 159.015293
ST_CLERK .904 134.409050
ST_MAN .479 -570.077291
REGR_COUNT Examples
The following example calculates the count of by job_id for time employed
(SYSDATE - hire_date) and salary using the sample table hr.employees. Results
are grouped by job_id.
SELECT job_id,
REGR_COUNT(SYSDATE-hire_date, salary) count
FROM employees
WHERE department_id in (30, 50)
REGR_ (Linear Regression) Functions
5-170 Oracle Database SQL Language Reference
GROUP BY job_id
ORDER BY job_id, count;
JOB_ID COUNT
---------- ----------
PU_CLERK 5
PU_MAN 1
SH_CLERK 20
ST_CLERK 20
ST_MAN 5
REGR_R2 Examples
The following example calculates the coefficient of determination the linear regression
of time employed (SYSDATE - hire_date) and salary using the sample table
hr.employees:
SELECT job_id,
REGR_R2(SYSDATE-hire_date, salary) Regr_R2
FROM employees
WHERE department_id in (80, 50)
GROUP by job_id
ORDER BY job_id, Regr_R2;
JOB_ID REGR_R2
---------- ----------
SA_MAN .83244748
SA_REP .647007156
SH_CLERK .879799698
ST_CLERK .742808493
ST_MAN .69418508
REGR_AVGY and REGR_AVGX Examples
The following example calculates the average values for time employed (SYSDATE -
hire_date) and salary using the sample table hr.employees. Results are grouped
by job_id:
SELECT job_id,
REGR_AVGY(SYSDATE-hire_date, salary) avgy,
REGR_AVGX(SYSDATE-hire_date, salary) avgx
FROM employees
WHERE department_id in (30,50)
GROUP BY job_id
ORDER BY job_id, avgy, avgx;
JOB_ID AVGY AVGX
---------- ---------- ----------
PU_CLERK 2950.3778 2780
PU_MAN 4026.5778 11000
SH_CLERK 2773.0778 3215
ST_CLERK 2872.7278 2785
ST_MAN 3140.1778 7280
REGR_SXY, REGR_SXX, and REGR_SYY Examples
The following example calculates three types of diagnostic statistics for the linear
regression of time employed (SYSDATE - hire_date) and salary using the sample
table hr.employees:
SELECT job_id,
REGR_SXY(SYSDATE-hire_date, salary) regr_sxy,
REMAINDER
Functions 5-171
REGR_SXX(SYSDATE-hire_date, salary) regr_sxx,
REGR_SYY(SYSDATE-hire_date, salary) regr_syy
FROM employees
WHERE department_id in (80, 50)
GROUP BY job_id
ORDER BY job_id;
JOB_ID REGR_SXY REGR_SXX REGR_SYY
---------- ---------- ----------- ----------
SA_MAN 3303500 9300000.0 1409642
SA_REP 16819665.5 65489655.2 6676562.55
SH_CLERK 4248650 5705500.0 3596039
ST_CLERK 3531545 3905500.0 4299084.55
ST_MAN 2180460 4548000.0 1505915.2
REMAINDER
Syntax
Purpose
REMAINDER returns the remainder of n2 divided by n1.
This function takes as arguments any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type. Oracle determines the
argument with the highest numeric precedence, implicitly converts the remaining
arguments to that data type, and returns that data type.
The MOD function is similar to REMAINDER except that it uses FLOOR in its formula,
whereas REMAINDER uses ROUND. Refer to MOD on page 5-112.
■ If n1 = 0 or m2 = infinity, then Oracle returns
– An error if the arguments are of type NUMBER
– NaN if the arguments are BINARY_FLOAT or BINARY_DOUBLE.
■ If n1 != 0, then the remainder is n2 - (n1*N) where N is the integer nearest n2/n1.
If n2/n1 equals x.5, then N is the nearest even integer.
■ If n2 is a floating-point number, and if the remainder is 0, then the sign of the
remainder is the sign of n2. Remainders of 0 are unsigned for NUMBER values.
Examples
Using table float_point_demo, created for the TO_BINARY_DOUBLE "Examples" on
page 5-216, the following example divides two floating-point numbers and returns the
remainder of that operation:
SELECT bin_float, bin_double, REMAINDER(bin_float, bin_double)
FROM float_point_demo;
BIN_FLOAT BIN_DOUBLE REMAINDER(BIN_FLOAT,BIN_DOUBLE)
---------- ---------- -------------------------------
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion and "Numeric
Precedence" on page 3-14 for information on numeric precedence
REMAINDER ( n2 , n1 )
REPLACE
5-172 Oracle Database SQL Language Reference
1.235E+003 1.235E+003 5.859E-005
REPLACE
Syntax
Purpose
REPLACE returns char with every occurrence of search_string replaced with
replacement_string. If replacement_string is omitted or null, then all
occurrences of search_string are removed. If search_string is null, then char
is returned.
Both search_string and replacement_string, as well as char, can be any of
the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string
returned is in the same character set as char. The function returns VARCHAR2 if the
first argument is not a LOB and returns CLOB if the first argument is a LOB.
REPLACE provides functionality related to that provided by the TRANSLATE function.
TRANSLATE provides single-character, one-to-one substitution. REPLACE lets you
substitute one string for another as well as to remove character strings.
Examples
The following example replaces occurrences of J with BL:
SELECT REPLACE('JACK and JUE','J','BL') "Changes"
FROM DUAL;
Changes
--------------
BLACK and BLUE
ROUND (date)
Syntax
round_date::=
Purpose
ROUND returns date rounded to the unit specified by the format model fmt. This
function is not sensitive to the NLS_CALENDAR session parameter. It operates
according to the rules of the Gregorian calendar. The value returned is always of data
type DATE, even if you specify a different datetime data type for date. If you omit
fmt, then date is rounded to the nearest day. The date expression must resolve to a
DATE value.
See Also: TRANSLATE on page 5-233
REPLACE ( char , search_string
, replacement_string
)
ROUND ( date
, fmt
)
ROUND (number)
Functions 5-173
Examples
The following example rounds a date to the first day of the following year:
SELECT ROUND (TO_DATE ('27-OCT-00'),'YEAR')
"New Year" FROM DUAL;
New Year
---------
01-JAN-01
ROUND (number)
Syntax
round_number::=
Purpose
ROUND returns n rounded to integer places to the right of the decimal point. If you
omit integer, then n is rounded to zero places. If integer is negative, then n is
rounded off to the left of the decimal point.
n can be any numeric data type or any nonnumeric data type that can be implicitly
converted to a numeric data type. If you omit integer, then the function returns the
value ROUND(n, 0) in the same data type as the numeric data type of n. If you include
integer, then the function returns NUMBER.
ROUND is implemented using the following rules:
1. If n is 0, then ROUND always returns 0 regardless of integer.
2. If n is negative, then ROUND(n, integer) returns -ROUND(-n, integer).
3. If n is positive, then
ROUND(n, integer) = FLOOR(n * POWER(10, integer) + 0.5) * POWER(10, -integer)
ROUND applied to a NUMBER value may give a slightly different result from ROUND
applied to the same value expressed in floating-point. The different results arise from
differences in internal representations of NUMBER and floating point values. The
difference will be 1 in the rounded digit if a difference occurs.
See Also: "ROUND and TRUNC Date Functions" on page 5-270 for
the permitted format models to use in fmt
ROUND ( n
, integer
)
ROW_NUMBER
5-174 Oracle Database SQL Language Reference
Examples
The following example rounds a number to one decimal point:
SELECT ROUND(15.193,1) "Round" FROM DUAL;
Round
----------
15.2
The following example rounds a number one digit to the left of the decimal point:
SELECT ROUND(15.193,-1) "Round" FROM DUAL;
Round
----------
20
ROW_NUMBER
Syntax
Purpose
ROW_NUMBER is an analytic function. It assigns a unique number to each row to which
it is applied (either each row in the partition or each row returned by the query), in the
ordered sequence of rows specified in the order_by_clause, beginning with 1.
By nesting a subquery using ROW_NUMBER inside a query that retrieves the ROW_
NUMBER values for a specified range, you can find a precise subset of rows from the
results of the inner query. This use of the function lets you implement top-N,
bottom-N, and inner-N reporting. For consistent results, the query must ensure a
deterministic sort order.
You cannot nest analytic functions by using ROW_NUMBER or any other analytic
function for expr. However, you can use other built-in function expressions for expr.
Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr.
See Also:
■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for
more information on implicit conversion
■ "Floating-Point Numbers" on page 3-12 for more information on
how Oracle Database handles BINARY_FLOAT and BINARY_
DOUBLE values
■ FLOOR on page 5-80 and CEIL on page 5-31, TRUNC (number)
on page 5-238 and MOD on page 5-112 for information on
functions that perform related operations
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
ROW_NUMBER ( ) OVER (
query_partition_clause
order_by_clause )
ROW_NUMBER
Functions 5-175
Examples
The following example finds the three highest paid employees in each department in
the hr.employees table. Fewer then three rows are returned for departments with
fewer than three employees.
SELECT department_id, first_name, last_name, salary
FROM
(
SELECT
department_id, first_name, last_name, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary desc) rn
FROM employees
)
WHERE rn <= 3
ORDER BY department_id, salary DESC, last_name;
The following example is a join query on the sh.sales table. It finds the sales
amounts in 2000 of the five top-selling products in 1999 and compares the difference
between 2000 and 1999. The ten top-selling products are calculated within each
distribution channel.
SELECT sales_2000.channel_desc, sales_2000.prod_name,
sales_2000.amt amt_2000, top_5_prods_1999_year.amt amt_1999,
sales_2000.amt - top_5_prods_1999_year.amt amt_diff
FROM
/* The first subquery finds the 5 top-selling products per channel in year 1999. */
(SELECT channel_desc, prod_name, amt
FROM
(
SELECT channel_desc, prod_name, sum(amount_sold) amt,
ROW_NUMBER () OVER (PARTITION BY channel_desc
ORDER BY SUM(amount_sold) DESC) rn
FROM sales, times, channels, products
WHERE sales.time_id = times.time_id
AND times.calendar_year = 1999
AND channels.channel_id = sales.channel_id
AND products.prod_id = sales.prod_id
GROUP BY channel_desc, prod_name
)
WHERE rn <= 5
) top_5_prods_1999_year,
/* The next subquery finds sales per product and per channel in 2000. */
(SELECT channel_desc, prod_name, sum(amount_sold) amt
FROM sales, times, channels, products
WHERE sales.time_id = times.time_id
AND times.calendar_year = 2000
AND channels.channel_id = sales.channel_id
AND products.prod_id = sales.prod_id
GROUP BY channel_desc, prod_name
) sales_2000
WHERE sales_2000.channel_desc = top_5_prods_1999_year.channel_desc
AND sales_2000.prod_name = top_5_prods_1999_year.prod_name
ORDER BY sales_2000.channel_desc, sales_2000.prod_name
;
CHANNEL_DESC PROD_NAME AMT_2000 AMT_1999 AMT_DIFF
--------------- --------------==-------------------------------- ---------- ---------- ----------
Direct Sales 17" LCD w/built-in HDTV Tuner 628855.7 1163645.78 -534790.08
Direct Sales Envoy 256MB - 40GB 502938.54 843377.88 -340439.34
Direct Sales Envoy Ambassador 2259566.96 1770349.25 489217.71
Direct Sales Home Theatre Package with DVD-Audio/Video Play 1235674.15 1260791.44 -25117.29
ROWIDTOCHAR
5-176 Oracle Database SQL Language Reference
Direct Sales Mini DV Camcorder with 3.5" Swivel LCD 775851.87 1326302.51 -550450.64
Internet 17" LCD w/built-in HDTV Tuner 31707.48 160974.7 -129267.22
Internet 8.3 Minitower Speaker 404090.32 155235.25 248855.07
Internet Envoy 256MB - 40GB 28293.87 154072.02 -125778.15
Internet Home Theatre Package with DVD-Audio/Video Play 155405.54 153175.04 2230.5
Internet Mini DV Camcorder with 3.5" Swivel LCD 39726.23 189921.97 -150195.74
Partners 17" LCD w/built-in HDTV Tuner 269973.97 325504.75 -55530.78
Partners Envoy Ambassador 1213063.59 614857.93 598205.66
Partners Home Theatre Package with DVD-Audio/Video Play 700266.58 520166.26 180100.32
Partners Mini DV Camcorder with 3.5" Swivel LCD 404265.85 520544.11 -116278.26
Partners Unix/Windows 1-user pack 374002.51 340123.02 33879.49
15 rows selected.
ROWIDTOCHAR
Syntax
Purpose
ROWIDTOCHAR converts a rowid value to VARCHAR2 data type. The result of this
conversion is always 18 characters long.
Examples
The following example converts a rowid value in the employees table to a character
value. (Results vary for each build of the sample database.)
SELECT ROWID FROM employees
WHERE ROWIDTOCHAR(ROWID) LIKE '%JAAB%'
ORDER BY ROWID;
ROWID
------------------
AAAFfIAAFAAAABSAAb
ROWIDTONCHAR
Syntax
Purpose
ROWIDTONCHAR converts a rowid value to NVARCHAR2 data type. The result of this
conversion is always in the national character set and is 18 characters long.
Examples
The following example converts a rowid value to an NVARCHAR2 string:
SELECT LENGTHB( ROWIDTONCHAR(ROWID) ) Length, ROWIDTONCHAR(ROWID)
FROM employees
ORDER BY length;
LENGTH ROWIDTONCHAR(ROWID
---------- ------------------
ROWIDTOCHAR ( rowid )
ROWIDTONCHAR ( rowid )
RPAD
Functions 5-177
36 AAAL52AAFAAAABSABD
36 AAAL52AAFAAAABSABV
. . .
RPAD
Syntax
Purpose
RPAD returns expr1, right-padded to length n characters with expr2, replicated as
many times as necessary. This function is useful for formatting the output of a query.
Both expr1 and expr2 can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if expr1
is a character data type, NVARCHAR2 if expr1 is a national character data type, and a
LOB if expr1 is a LOB data type. The string returned is in the same character set as
expr1. The argument n must be a NUMBER integer or a value that can be implicitly
converted to a NUMBER integer.
expr1 cannot be null. If you do not specify expr2, then it defaults to a single blank. If
expr1 is longer than n, then this function returns the portion of expr1 that fits in n.
The argument n is the total length of the return value as it is displayed on your
terminal screen. In most character sets, this is also the number of characters in the
return value. However, in some multibyte character sets, the display length of a
character string can differ from the number of characters in the string.
Examples
The following example creates a simple chart of salary amounts by padding a single
space with asterisks:
SELECT last_name, RPAD(' ', salary/1000/1, '*') "Salary"
FROM employees
WHERE department_id = 80
ORDER BY last_name, "Salary";
LAST_NAME Salary
------------------------- ---------------
Abel **********
Ande *****
Banda *****
Bates ******
Bernstein ********
Bloom *********
Cambrault **********
Cambrault ******
Doran ******
Errazuriz ***********
Fox ********
Greene ********
Hall ********
Hutton *******
Johnson *****
King *********
. . .
RPAD ( expr1 , n
, expr2
)
RTRIM
5-178 Oracle Database SQL Language Reference
RTRIM
Syntax
Purpose
RTRIM removes from the right end of char all of the characters that appear in set.
This function is useful for formatting the output of a query.
If you do not specify set, then it defaults to a single blank. If char is a character
literal, then you must enclose it in single quotation marks. RTRIM works similarly to
LTRIM.
Both char and set can be any of the data types CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is
a character data type, NVARCHAR2 if expr1 is a national character data type, and a
LOB if char is a LOB data type.
Examples
The following example trims all the right-most occurrences of period, slash, and equal
sign from a string:
SELECT RTRIM('BROWNING: ./=./=./=./=./=.=','/=.') "RTRIM example" FROM DUAL;
RTRIM exam
----------
BROWNING:
SCN_TO_TIMESTAMP
Syntax
Purpose
SCN_TO_TIMESTAMP takes as an argument a number that evaluates to a system
change number (SCN), and returns the approximate timestamp associated with that
SCN. The returned value is of TIMESTAMP data type. This function is useful any time
you want to know the timestamp associated with an SCN. For example, it can be used
in conjunction with the ORA_ROWSCN pseudocolumn to associate a timestamp with the
most recent change to a row.
See Also: LTRIM on page 5-106
RTRIM ( char
, set
)
SCN_TO_TIMESTAMP ( number )
SCN_TO_TIMESTAMP
Functions 5-179
Examples
The following example uses the ORA_ROWSCN pseudocolumn to determine the system
change number of the last update to a row and uses SCN_TO_TIMESTAMP to convert
that SCN to a timestamp:
SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) FROM employees
WHERE employee_id = 188;
You could use such a query to convert a system change number to a timestamp for use
in an Oracle Flashback Query:
SELECT salary FROM employees WHERE employee_id = 188;
SALARY
----------
3800
UPDATE employees SET salary = salary*10 WHERE employee_id = 188;
COMMIT;
SELECT salary FROM employees WHERE employee_id = 188;
SALARY
----------
38000
SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) FROM employees
WHERE employee_id = 188;
SCN_TO_TIMESTAMP(ORA_ROWSCN)
---------------------------------------------------------------------------
28-AUG-03 01.58.01.000000000 PM
FLASHBACK TABLE employees TO TIMESTAMP
TO_TIMESTAMP('28-AUG-03 01.00.00.000000000 PM');
SELECT salary FROM employees WHERE employee_id = 188;
SALARY
----------
3800
Notes:
■ The usual precision of the result value is 3 seconds.
■ The association between an SCN and a timestamp when the SCN
is generated is remembered by the database for a limited period of
time. This period is the maximum of the auto-tuned undo
retention period, if the database runs in the Automatic Undo
Management mode, and the retention times of all flashback
archives in the database, but no less than 120 hours. The time for
the association to become obsolete elapses only when the database
is open. An error is returned if the SCN specified for the argument
to SCN_TO_TIMESTAMP is too old.
See Also: ORA_ROWSCN Pseudocolumn on page 2-8 and
TIMESTAMP_TO_SCN on page 5-214
SESSIONTIMEZONE
5-180 Oracle Database SQL Language Reference
SESSIONTIMEZONE
Syntax
Purpose
SESSIONTIMEZONE returns the time zone of the current session. The return type is a
time zone offset (a character type in the format '[+|]TZH:TZM') or a time zone
region name, depending on how the user specified the session time zone value in the
most recent ALTER SESSION statement.
Examples
The following example returns the time zone of the current session:
SELECT SESSIONTIMEZONE FROM DUAL;
SESSION
-------
-08:00
SET
Syntax
Purpose
SET converts a nested table into a set by eliminating duplicates. The function returns a
nested table whose elements are distinct from one another. The returned nested table is
of the same type as the input nested table.
The element types of the nested table must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example selects from the customers_demo table the unique elements
of the cust_address_ntab nested table column:
SELECT customer_id, SET(cust_address_ntab) address
FROM customers_demo
ORDER BY customer_id;
CUSTOMER_ID ADDRESS(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
----------- ------------------------------------------------------------------------
Note: The default client session time zone is an offset even if the
client operating system uses a named time zone. If you want the
default session time zone to use a named time zone, then set the ORA_
SDTZ variable in the client environment to an Oracle time zone region
name. Refer to Oracle Database Globalization Support Guide for more
information on this variable.
SESSIONTIMEZONE
SET ( nested_table )
SIN
Functions 5-181
101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))
102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'))
103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))
104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'))
105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'))
. . .
The preceding example requires the table customers_demo and a nested table
column containing data. Refer to "Multiset Operators" on page 4-1 to create this table
and nested table column.
SIGN
Syntax
Purpose
SIGN returns the sign of n. This function takes as an argument any numeric data type,
or any nonnumeric data type that can be implicitly converted to NUMBER, and returns
NUMBER.
For value of NUMBER type, the sign is:
■ -1 if n<0
■ 0 if n=0
■ 1 if n>0
For binary floating-point numbers (BINARY_FLOAT and BINARY_DOUBLE), this
function returns the sign bit of the number. The sign bit is:
■ -1 if n<0
■ +1 if n>=0 or n=NaN
Examples
The following example indicates that the argument of the function (-15) is <0:
SELECT SIGN(-15) "Sign" FROM DUAL;
Sign
----------
-1
SIN
Syntax
Purpose
SIN returns the sine of n (an angle expressed in radians).
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
SIGN ( n )
SIN ( n )
SINH
5-182 Oracle Database SQL Language Reference
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the sine of 30 degrees:
SELECT SIN(30 * 3.14159265359/180)
"Sine of 30 degrees" FROM DUAL;
Sine of 30 degrees
------------------
.5
SINH
Syntax
Purpose
SINH returns the hyperbolic sine of n.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the hyperbolic sine of 1:
SELECT SINH(1) "Hyperbolic sine of 1" FROM DUAL;
Hyperbolic sine of 1
--------------------
1.17520119
SOUNDEX
Syntax
Purpose
SOUNDEX returns a character string containing the phonetic representation of char.
This function lets you compare words that are spelled differently, but sound alike in
English.
The phonetic representation is defined in The Art of Computer Programming, Volume 3:
Sorting and Searching, by Donald E. Knuth, as follows:
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
SINH ( n )
SOUNDEX ( char )
SQRT
Functions 5-183
1. Retain the first letter of the string and remove all other occurrences of the
following letters: a, e, h, i, o, u, w, y.
2. Assign numbers to the remaining letters (after the first) as follows:
b, f, p, v = 1
c, g, j, k, q, s, x, z = 2
d, t = 3
l = 4
m, n = 5
r = 6
3. If two or more letters with the same number were adjacent in the original name
(before step 1), or adjacent except for any intervening h and w, then retain the first
letter and omit rest of all the adjacent letters with same number.
4. Return the first four bytes padded with 0.
char can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The
return value is the same data type as char.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example returns the employees whose last names are a phonetic
representation of "Smyth":
SELECT last_name, first_name
FROM hr.employees
WHERE SOUNDEX(last_name)
= SOUNDEX('SMYTHE')
ORDER BY last_name, first_name;
LAST_NAME FIRST_NAME
---------- ----------
Smith Lindsey
Smith William
SQRT
Syntax
Purpose
SQRT returns the square root of n.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
SQRT ( n )
STATS_BINOMIAL_TEST
5-184 Oracle Database SQL Language Reference
■ If n resolves to a NUMBER, then the value n cannot be negative. SQRT returns a real
number.
■ If n resolves to a binary floating-point number (BINARY_FLOAT or BINARY_
DOUBLE):
– If n >= 0, then the result is positive.
– If n = -0, then the result is -0.
– If n < 0, then the result is NaN.
Examples
The following example returns the square root of 26:
SELECT SQRT(26) "Square root" FROM DUAL;
Square root
-----------
5.09901951
STATS_BINOMIAL_TEST
Syntax
Purpose
STATS_BINOMIAL_TEST is an exact probability test used for dichotomous variables,
where only two possible values exist. It tests the difference between a sample
proportion and a given proportion. The sample size in such tests is usually small.
This function takes four arguments: expr1 is the sample being examined. expr2
contains the values for which the proportion is expected to be, and p is a proportion to
test against. The fourth argument is a return value of type VARCHAR2. If you omit the
fourth argument, then the default is TWO_SIDED_PROB. The meaning of the return
values is shown in Table 5–3.
Table 5–3 STATS_BINOMIAL Return Values
Return Value Meaning
TWO_SIDED_PROB The probability that the given population proportion, p,
could result in the observed proportion or a more extreme
one.
EXACT_PROB The probability that the given population proportion, p,
could result in exactly the observed proportion.
ONE_SIDED_PROB_OR_MORE The probability that the given population proportion, p,
could result in the observed proportion or a larger one.
ONE_SIDED_PROB_OR_LESS The probability that the given population proportion, p,
could result in the observed proportion or a smaller one.
STATS_BINOMIAL_TEST ( expr1 , expr2 , p
,
TWO_SIDED_PROB
EXACT_PROB
ONE_SIDED_PROB_OR_MORE
ONE_SIDED_PROB_OR_LESS
)
STATS_CROSSTAB
Functions 5-185
EXACT_PROB gives the probability of getting exactly proportion p. In cases where you
want to test whether the proportion found in the sample is significantly different from
a 50-50 split, p would normally be 0.50. If you want to test only whether the
proportion is different, then use the return value TWO_SIDED_PROB. If your test is
whether the proportion is more than the value of expr2, then use the return value
ONE_SIDED_PROB_OR_MORE. If the test is to determine whether the proportion of
expr2 is less, then use the return value ONE_SIDED_PROB_OR_LESS.
STATS_BINOMIAL_TEST Example The following example determines the probability
that reality exactly matches the number of men observed under the assumption that
69% of the population is composed of men:
SELECT AVG(DECODE(cust_gender, 'M', 1, 0)) real_proportion,
STATS_BINOMIAL_TEST
(cust_gender, 'M', 0.68, 'EXACT_PROB') exact,
STATS_BINOMIAL_TEST
(cust_gender, 'M', 0.68, 'ONE_SIDED_PROB_OR_LESS') prob_or_less
FROM sh.customers;
STATS_CROSSTAB
Syntax
Purpose
Crosstabulation (commonly called crosstab) is a method used to analyze two nominal
variables. The STATS_CROSSTAB function takes three arguments: two expressions and
a return value of type VARCHAR2. expr1 and expr2 are the two variables being
analyzed. The function returns one number, determined by the value of the third
argument. If you omit the third argument, then the default is CHISQ_SIG. The
meaning of the return values is shown in Table 5–4.
Table 5–4 STATS_CROSSTAB Return Values
Return Value Meaning
CHISQ_OBS Observed value of chi-squared
CHISQ_SIG Significance of observed chi-squared
CHISQ_DF Degree of freedom for chi-squared
PHI_COEFFICIENT Phi coefficient
CRAMERS_V Cramer's V statistic
CONT_COEFFICIENT Contingency coefficient
STATS_CROSSTAB ( expr1 , expr2
,
CHISQ_OBS
CHISQ_SIG
CHISQ_DF
PHI_COEFFICIENT
CRAMERS_V
CONT_COEFFICIENT
COHENS_K
)
STATS_F_TEST
5-186 Oracle Database SQL Language Reference
STATS_CROSSTAB Example The following example determines the strength of the
association between gender and income level:
SELECT STATS_CROSSTAB
(cust_gender, cust_income_level, 'CHISQ_OBS') chi_squared,
STATS_CROSSTAB
(cust_gender, cust_income_level, 'CHISQ_SIG') p_value,
STATS_CROSSTAB
(cust_gender, cust_income_level, 'PHI_COEFFICIENT') phi_coefficient
FROM sh.customers;
CHI_SQUARED P_VALUE PHI_COEFFICIENT
----------- ---------- ---------------
251.690705 1.2364E-47 .067367056
STATS_F_TEST
Syntax
Purpose
STATS_F_TEST tests whether two variances are significantly different. The observed
value of f is the ratio of one variance to the other, so values very different from 1
usually indicate significant differences.
This function takes three arguments: expr1 is the grouping or independent variable
and expr2 is the sample of values. The function returns one number, determined by
the value of the third argument. If you omit the third argument, then the default is
TWO_SIDED_SIG. The meaning of the return values is shown in Table 5–5.
COHENS_K Cohen's kappa
Table 5–5 STATS_F_TEST Return Values
Return Value Meaning
STATISTIC The observed value of f
DF_NUM Degree of freedom for the numerator
DF_DEN Degree of freedom for the denominator
ONE_SIDED_SIG One-tailed significance of f
TWO_SIDED_SIG Two-tailed significance of f
Table 5–4 (Cont.) STATS_CROSSTAB Return Values
Return Value Meaning
STATS_F_TEST ( expr1 , expr2
,
STATISTIC
DF_NUM
DF_DEN
ONE_SIDED_SIG
, expr3
TWO_SIDED_SIG
)
STATS_KS_TEST
Functions 5-187
The one-tailed significance is always in relation to the upper tail. The final argument,
expr3, indicates which of the two groups specified by expr1 is the high value or
numerator (the value whose rejection region is the upper tail).
The observed value of f is the ratio of the variance of one group to the variance of the
second group. The significance of the observed value of f is the probability that the
variances are different just by chance—a number between 0 and 1. A small value for
the significance indicates that the variances are significantly different. The degree of
freedom for each of the variances is the number of observations in the sample minus 1.
STATS_F_TEST Example The following example determines whether the variance in
credit limit between men and women is significantly different. The results, a p_value
not close to zero, and an f_statistic close to 1, indicate that the difference between
credit limits for men and women are not significant.
SELECT VARIANCE(DECODE(cust_gender, 'M', cust_credit_limit, null)) var_men,
VARIANCE(DECODE(cust_gender, 'F', cust_credit_limit, null)) var_women,
STATS_F_TEST(cust_gender, cust_credit_limit, 'STATISTIC', 'F') f_statistic,
STATS_F_TEST(cust_gender, cust_credit_limit) two_sided_p_value
FROM sh.customers;
VAR_MEN VAR_WOMEN F_STATISTIC TWO_SIDED_P_VALUE
---------- ---------- ----------- -----------------
12879896.7 13046865 1.01296348 .311928071
STATS_KS_TEST
Syntax
Purpose
STATS_KS_TEST is a Kolmogorov-Smirnov function that compares two samples to
test whether they are from the same population or from populations that have the
same distribution. It does not assume that the population from which the samples
were taken is normally distributed.
This function takes three arguments: two expressions and a return value of type
VARCHAR2. expr1 classifies the data into the two samples. expr2 contains the values
for each of the samples. If expr1 classifies the rows into only one sample or into more
than two samples, then an error is raised.The function returns one value determined
by the third argument. If you omit the third argument, then the default is SIG. The
meaning of the return values is shown in Table 5–6.
STATS_KS_TEST Example Using the Kolmogorov Smirnov test, the following
example determines whether the distribution of sales between men and women is due
to chance:
Table 5–6 STATS_KS_TEST Return Values
Return Value Meaning
STATISTIC Observed value of D
SIG Significance of D
STATS_KS_TEST ( expr1 , expr2
,
STATISTIC
SIG
)
STATS_MODE
5-188 Oracle Database SQL Language Reference
SELECT stats_ks_test(cust_gender, amount_sold, 'STATISTIC') ks_statistic,
stats_ks_test(cust_gender, amount_sold) p_value
FROM sh.customers c, sh.sales s
WHERE c.cust_id = s.cust_id;
KS_STATISTIC P_VALUE
------------ ----------
.003841396 .004080006
STATS_MODE
Syntax
Purpose
STATS_MODE takes as its argument a set of values and returns the value that occurs
with the greatest frequency. If more than one mode exists, then Oracle Database
chooses one and returns only that one value.
To obtain multiple modes (if multiple modes exist), you must use a combination of
other functions, as shown in the hypothetical query:
SELECT x FROM (SELECT x, COUNT(x) AS cnt1
FROM t GROUP BY x)
WHERE cnt1 =
(SELECT MAX(cnt2) FROM (SELECT COUNT(x) AS cnt2 FROM t GROUP BY x));
Examples
The following example returns the mode of salary per department in the
hr.employees table:
SELECT department_id, STATS_MODE(salary) FROM employees
GROUP BY department_id
ORDER BY department_id, stats_mode(salary);
DEPARTMENT_ID STATS_MODE(SALARY)
------------- ------------------
10 4400
20 6000
30 2500
40 6500
50 2500
60 4800
70 10000
80 9500
90 17000
100 6900
110 8300
7000
If you need to retrieve all of the modes (in cases with multiple modes), you can do so
using a combination of other functions, as shown in the next example:
SELECT commission_pct FROM
(SELECT commission_pct, COUNT(commission_pct) AS cnt1 FROM employees
GROUP BY commission_pct)
WHERE cnt1 =
STATS_MODE ( expr )
STATS_MW_TEST
Functions 5-189
(SELECT MAX (cnt2) FROM
(SELECT COUNT(commission_pct) AS cnt2
FROM employees GROUP BY commission_pct))
ORDER BY commission_pct;
COMMISSION_PCT
--------------
.2
.3
STATS_MW_TEST
Syntax
Purpose
A Mann Whitney test compares two independent samples to test the null hypothesis
that two populations have the same distribution function against the alternative
hypothesis that the two distribution functions are different.
The STATS_MW_TEST does not assume that the differences between the samples are
normally distributed, as do the STATS_T_TEST_* functions. This function takes three
arguments and a return value of type VARCHAR2. expr1 classifies the data into
groups. expr2 contains the values for each of the groups. The function returns one
value, determined by the third argument. If you omit the third argument, then the
default is TWO_SIDED_SIG. The meaning of the return values is shown in the table
that follows.
The significance of the observed value of Z or U is the probability that the variances
are different just by chance—a number between 0 and 1. A small value for the
significance indicates that the variances are significantly different. The degree of
freedom for each of the variances is the number of observations in the sample minus 1.
The one-tailed significance is always in relation to the upper tail. The final argument,
expr3, indicates which of the two groups specified by expr1 is the high value (the
value whose rejection region is the upper tail).
STATS_MW_TEST computes the probability that the samples are from the same
distribution by checking the differences in the sums of the ranks of the values. If the
samples come from the same distribution, then the sums should be close in value.
Table 5–7 STATS_MW_TEST Return Values
Return Value Meaning
STATISTIC The observed value of Z
U_STATISTIC The observed value of U
ONE_SIDED_SIG One-tailed significance of Z
TWO_SIDED_SIG Two-tailed significance of Z
STATS_MW_TEST ( expr1 , expr2
,
STATISTIC
U_STATISTIC
ONE_SIDED_SIG , expr3
TWO_SIDED_SIG
)
STATS_ONE_WAY_ANOVA
5-190 Oracle Database SQL Language Reference
STATS_MW_TEST Example Using the Mann Whitney test, the following example
determines whether the distribution of sales between men and women is due to
chance:
SELECT STATS_MW_TEST
(cust_gender, amount_sold, 'STATISTIC') z_statistic,
STATS_MW_TEST
(cust_gender, amount_sold, 'ONE_SIDED_SIG', 'F') one_sided_p_value
FROM sh.customers c, sh.sales s
WHERE c.cust_id = s.cust_id;
Z_STATISTIC ONE_SIDED_P_VALUE
----------- -----------------
-1.4011509 .080584471
STATS_ONE_WAY_ANOVA
Syntax
Purpose
The one-way analysis of variance function (STATS_ONE_WAY_ANOVA) tests differences
in means (for groups or variables) for statistical significance by comparing two
different estimates of variance. One estimate is based on the variances within each
group or category. This is known as the mean squares within or mean square error.
The other estimate is based on the variances among the means of the groups. This is
known as the mean squares between. If the means of the groups are significantly
different, then the mean squares between will be larger than expected and will not
match the mean squares within. If the mean squares of the groups are consistent, then
the two variance estimates will be about the same.
STATS_ONE_WAY_ANOVA takes three arguments: two expressions and a return value
of type VARCHAR2. expr1 is an independent or grouping variable that divides the
data into a set of groups. expr2 is a dependent variable (a numeric expression)
containing the values corresponding to each member of a group. The function returns
one number, determined by the value of the third argument. If you omit the third
argument, then the default is SIG. The meaning of the return values is shown in
Table 5–8.
Table 5–8 STATS_ONE_WAY_ANOVA Return Values
Return Value Meaning
SUM_SQUARES_BETEEN Sum of squares between groups
STATS_ONE_WAY_ANOVA ( expr1 , expr2
,
SUM_SQUARES_BETWEEN
SUM_SQUARES_WITHIN
DF_BETWEEN
DF_WITHIN
MEAN_SQUARES_BETWEEN
MEAN_SQUARES_WITHIN
F_RATIO
SIG
)
STATS_T_TEST_*
Functions 5-191
The significance of one-way analysis of variance is determined by obtaining the
one-tailed significance of an f-test on the ratio of the mean squares between and the
mean squares within. The f-test should use one-tailed significance, because the mean
squares between can be only equal to or larger than the mean squares within.
Therefore, the significance returned by STATS_ONE_WAY_ANOVA is the probability
that the differences between the groups happened by chance—a number between 0
and 1. The smaller the number, the greater the significance of the difference between
the groups. Refer to the STATS_F_TEST on page 5-186 for information on performing
an f-test.
STATS_ONE_WAY_ANOVA Example The following example determines the
significance of the differences in mean sales within an income level and differences in
mean sales between income levels. The results, p_values close to zero, indicate that, for
both men and women, the difference in the amount of goods sold across different
income levels is significant.
SELECT cust_gender,
STATS_ONE_WAY_ANOVA(cust_income_level, amount_sold, 'F_RATIO') f_ratio,
STATS_ONE_WAY_ANOVA(cust_income_level, amount_sold, 'SIG') p_value
FROM sh.customers c, sh.sales s
WHERE c.cust_id = s.cust_id
GROUP BY cust_gender
ORDER BY cust_gender;
C F_RATIO P_VALUE
- ---------- ----------
F 5.59536943 4.7840E-09
M 9.2865001 6.7139E-17
STATS_T_TEST_*
The t-test functions are:
■ STATS_T_TEST_ONE: A one-sample t-test
■ STATS_T_TEST_PAIRED: A two-sample, paired t-test (also known as a crossed
t-test)
■ STATS_T_TEST_INDEP: A t-test of two independent groups with the same
variance (pooled variances)
■ STATS_T_TEST_INDEPU: A t-test of two independent groups with unequal
variance (unpooled variances)
SUM_SQUARES_WITHIN Sum of squares within groups
DF_BETWEEN Degree of freedom between groups
DF_WITHIN Degree of freedom within groups
MEAN_SQUARES_BETWEEN Mean squares between groups
MEAN_SQUARES_WITHIN Mean squares within groups
F_RATIO Ratio of the mean squares between to the mean squares within
(MSB/MSW)
SIG Significance
Table 5–8 (Cont.) STATS_ONE_WAY_ANOVA Return Values
Return Value Meaning
STATS_T_TEST_ONE
5-192 Oracle Database SQL Language Reference
Syntax
stats_t_test::=
Purpose
The t-test measures the significance of a difference of means. You can use it to compare
the means of two groups or the means of one group with a constant. The one-sample
and two-sample STATS_T_TEST_* functions take three arguments: two expressions
and a return value of type VARCHAR2. The functions return one number, determined
by the value of the third argument. If you omit the third argument, then the default is
TWO_SIDED_SIG. The meaning of the return values is shown in Table 5–9.
The two independent STATS_T_TEST_* functions can take a fourth argument
(expr3) if the third argument is specified as STATISTIC or ONE_SIDED_SIG. In this
case, expr3 indicates which value of expr1 is the high value, or the value whose
rejection region is the upper tail.
The significance of the observed value of t is the probability that the value of t would
have been obtained by chance—a number between 0 and 1. The smaller the value, the
more significant the difference between the means. One-sided significance is always
respect to the upper tail. For one-sample and paired t-test, the high value is the first
expression. For independent t-test, the high value is the one specified by expr3.
The degree of freedom depends on the type of t-test that resulted in the observed
value of t. For example, for a one-sample t-test (STATS_T_TEST_ONE), the degree of
freedom is the number of observations in the sample minus 1.
STATS_T_TEST_ONE
In the STATS_T_TEST_ONE function, expr1 is the sample and expr2 is the constant
mean against which the sample mean is compared. For this t-test only, expr2 is
optional; the constant mean defaults to 0. This function obtains the value of t by
dividing the difference between the sample mean and the known mean by the
standard error of the mean (rather than the standard error of the difference of the
means, as for STATS_T_TEST_PAIRED).
Table 5–9 STATS_T_TEST_* Return Values
Return Value Meaning
STATISTIC The observed value of t
DF Degree of freedom
ONE_SIDED_SIG One-tailed significance of t
TWO_SIDED_SIG Two-tailed significance of t
STATS_T_TEST_INDEP
STATS_T_TEST_INDEPU
STATS_T_TEST_ONE
STATS_T_TEST_PAIRED
( expr1 , expr2
,
STATISTIC
ONE_SIDED_SIG
, expr3
TWO_SIDED_SIG
DF
)
STATS_T_TEST_*
Functions 5-193
STATS_T_TEST_ONE Example The following example determines the significance of
the difference between the average list price and the constant value 60:
SELECT AVG(prod_list_price) group_mean,
STATS_T_TEST_ONE(prod_list_price, 60, 'STATISTIC') t_observed,
STATS_T_TEST_ONE(prod_list_price, 60) two_sided_p_value
FROM sh.products;
GROUP_MEAN T_OBSERVED TWO_SIDED_P_VALUE
---------- ---------- -----------------
139.545556 2.32107746 .023158537
STATS_T_TEST_PAIRED
In the STATS_T_TEST_PAIRED function, expr1 and expr2 are the two samples
whose means are being compared. This function obtains the value of t by dividing the
difference between the sample means by the standard error of the difference of the
means (rather than the standard error of the mean, as for STATS_T_TEST_ONE).
STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU
In the STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU functions, expr1 is the
grouping column and expr2 is the sample of values. The pooled variances version
(STATS_T_TEST_INDEP) tests whether the means are the same or different for two
distributions that have similar variances. The unpooled variances version (STATS_T_
TEST_INDEPU) tests whether the means are the same or different even if the two
distributions are known to have significantly different variances.
Before using these functions, it is advisable to determine whether the variances of the
samples are significantly different. If they are, then the data may come from
distributions with different shapes, and the difference of the means may not be very
useful. You can perform an f-test to determine the difference of the variances. If they
are not significantly different, use STATS_T_TEST_INDEP. If they are significantly
different, use STATS_T_TEST_INDEPU. Refer to STATS_F_TEST on page 5-186 for
information on performing an f-test.
STATS_T_TEST_INDEP Example The following example determines the significance
of the difference between the average sales to men and women where the distributions
are assumed to have similar (pooled) variances:
SELECT SUBSTR(cust_income_level, 1, 22) income_level,
AVG(DECODE(cust_gender, 'M', amount_sold, null)) sold_to_men,
AVG(DECODE(cust_gender, 'F', amount_sold, null)) sold_to_women,
STATS_T_TEST_INDEP(cust_gender, amount_sold, 'STATISTIC', 'F') t_observed,
STATS_T_TEST_INDEP(cust_gender, amount_sold) two_sided_p_value
FROM sh.customers c, sh.sales s
WHERE c.cust_id = s.cust_id
GROUP BY ROLLUP(cust_income_level)
ORDER BY income_level, sold_to_men, sold_to_women, t_observed;
INCOME_LEVEL SOLD_TO_MEN SOLD_TO_WOMEN T_OBSERVED TWO_SIDED_P_VALUE
---------------------- ----------- ------------- ---------- -----------------
A: Below 30,000 105.28349 99.4281447 -1.9880629 .046811482
B: 30,000 - 49,999 102.59651 109.829642 3.04330875 .002341053
C: 50,000 - 69,999 105.627588 110.127931 2.36148671 .018204221
D: 70,000 - 89,999 106.630299 110.47287 2.28496443 .022316997
E: 90,000 - 109,999 103.396741 101.610416 -1.2544577 .209677823
F: 110,000 - 129,999 106.76476 105.981312 -.60444998 .545545304
STATS_WSR_TEST
5-194 Oracle Database SQL Language Reference
G: 130,000 - 149,999 108.877532 107.31377 -.85298245 .393671218
H: 150,000 - 169,999 110.987258 107.152191 -1.9062363 .056622983
I: 170,000 - 189,999 102.808238 107.43556 2.18477851 .028908566
J: 190,000 - 249,999 108.040564 115.343356 2.58313425 .009794516
K: 250,000 - 299,999 112.377993 108.196097 -1.4107871 .158316973
L: 300,000 and above 120.970235 112.216342 -2.0642868 .039003862
107.121845 113.80441 .686144393 .492670059
106.663769 107.276386 1.08013499 .280082357
14 rows selected.
STATS_T_TEST_INDEPU Example The following example determines the
significance of the difference between the average sales to men and women where the
distributions are known to have significantly different (unpooled) variances:
SELECT SUBSTR(cust_income_level, 1, 22) income_level,
AVG(DECODE(cust_gender, 'M', amount_sold, null)) sold_to_men,
AVG(DECODE(cust_gender, 'F', amount_sold, null)) sold_to_women,
STATS_T_TEST_INDEPU(cust_gender, amount_sold, 'STATISTIC', 'F') t_observed,
STATS_T_TEST_INDEPU(cust_gender, amount_sold) two_sided_p_value
FROM sh.customers c, sh.sales s
WHERE c.cust_id = s.cust_id
GROUP BY ROLLUP(cust_income_level)
ORDER BY income_level, sold_to_men, sold_to_women, t_observed;
INCOME_LEVEL SOLD_TO_MEN SOLD_TO_WOMEN T_OBSERVED TWO_SIDED_P_VALUE
---------------------- ----------- ------------- ---------- -----------------
A: Below 30,000 105.28349 99.4281447 -2.0542592 .039964704
B: 30,000 - 49,999 102.59651 109.829642 2.96922332 .002987742
C: 50,000 - 69,999 105.627588 110.127931 2.3496854 .018792277
D: 70,000 - 89,999 106.630299 110.47287 2.26839281 .023307831
E: 90,000 - 109,999 103.396741 101.610416 -1.2603509 .207545662
F: 110,000 - 129,999 106.76476 105.981312 -.60580011 .544648553
G: 130,000 - 149,999 108.877532 107.31377 -.85219781 .394107755
H: 150,000 - 169,999 110.987258 107.152191 -1.9451486 .051762624
I: 170,000 - 189,999 102.808238 107.43556 2.14966921 .031587875
J: 190,000 - 249,999 108.040564 115.343356 2.54749867 .010854966
K: 250,000 - 299,999 112.377993 108.196097 -1.4115514 .158091676
L: 300,000 and above 120.970235 112.216342 -2.0726194 .038225611
107.121845 113.80441 .689462437 .490595765
106.663769 107.276386 1.07853782 .280794207
14 rows selected.
STATS_WSR_TEST
Syntax
Purpose
STATS_WSR_TEST is a Wilcoxon Signed Ranks test of paired samples to determine
whether the median of the differences between the samples is significantly different
from zero. The absolute values of the differences are ordered and assigned ranks. Then
STATS_WSR_TEST ( expr1 , expr2
,
STATISTIC
ONE_SIDED_SIG
TWO_SIDED_SIG
)
STDDEV
Functions 5-195
the null hypothesis states that the sum of the ranks of the positive differences is equal
to the sum of the ranks of the negative differences.
This function takes three arguments: expr1 and expr2 are the two samples being
analyzed, and the third argument is a return value of type VARCHAR2. If you omit the
third argument, then the default is TWO_SIDED_SIG. The meaning of the return
values is shown in Table 5–10.
One-sided significance is always with respect to the upper tail. The high value (the
value whose rejection region is the upper tail) is expr1.
STDDEV
Syntax
Purpose
STDDEV returns the sample standard deviation of expr, a set of numbers. You can use
it as both an aggregate and analytic function. It differs from STDDEV_SAMP in that
STDDEV returns zero when it has only 1 row of input data, whereas STDDEV_SAMP
returns null.
Oracle Database calculates the standard deviation as the square root of the variance
defined for the VARIANCE aggregate function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
If you specify DISTINCT, then you can specify only the query_partition_clause
of the analytic_clause. The order_by_clause and windowing_clause are not
allowed.
Table 5–10 STATS_WSR_TEST_* Return Values
Return Value Meaning
STATISTIC The observed value of Z
ONE_SIDED_SIG One-tailed significance of Z
TWO_SIDED_SIG Two-tailed significance of Z
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
STDDEV (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
STDDEV_POP
5-196 Oracle Database SQL Language Reference
Aggregate Examples
The following example returns the standard deviation of the salaries in the sample
hr.employees table:
SELECT STDDEV(salary) "Deviation"
FROM employees;
Deviation
----------
3909.36575
Analytic Examples
The query in the following example returns the cumulative standard deviation of the
salaries in Department 80 in the sample table hr.employees, ordered by hire_
date:
SELECT last_name, salary,
STDDEV(salary) OVER (ORDER BY hire_date) "StdDev"
FROM employees
WHERE department_id = 30
ORDER BY last_name, salary, "StdDev";
LAST_NAME SALARY StdDev
------------------------- ---------- ----------
Baida 2900 4035.26125
Colmenares 2500 3362.58829
Himuro 2600 3649.2465
Khoo 3100 5586.14357
Raphaely 11000 0
Tobias 2800 4650.0896
STDDEV_POP
Syntax
Purpose
STDDEV_POP computes the population standard deviation and returns the square root
of the population variance. You can use it as both an aggregate and analytic function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
See Also:
■ "Aggregate Functions" on page 5-9, VARIANCE on page 5-246,
and STDDEV_SAMP on page 5-197
■ "About SQL Expressions" on page 6-1 for information on valid
forms of expr
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
STDDEV_POP ( expr )
OVER ( analytic_clause )
STDDEV_SAMP
Functions 5-197
This function is the same as the square root of the VAR_POP function. When VAR_POP
returns null, this function returns null.
Aggregate Example
The following example returns the population and sample standard deviations of the
amount of sales in the sample table sh.sales:
SELECT STDDEV_POP(amount_sold) "Pop",
STDDEV_SAMP(amount_sold) "Samp"
FROM sales;
Pop Samp
---------- ----------
896.355151 896.355592
Analytic Example
The following example returns the population standard deviations of salaries in the
sample hr.employees table by department:
SELECT department_id, last_name, salary,
STDDEV_POP(salary) OVER (PARTITION BY department_id) AS pop_std
FROM employees
ORDER BY department_id, last_name, salary, pop_std;
DEPARTMENT_ID LAST_NAME SALARY POP_STD
------------- ------------------------- ---------- ----------
10 Whalen 4400 0
20 Fay 6000 3500
20 Hartstein 13000 3500
30 Baida 2900 3069.6091
. . .
100 Urman 7800 1644.18166
110 Gietz 8300 1850
110 Higgins 12000 1850
Grant 7000 0
STDDEV_SAMP
Syntax
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also:
■ "Aggregate Functions" on page 5-9 and VAR_POP on page 5-244
■ "About SQL Expressions" on page 6-1 for information on valid
forms of expr
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
STDDEV_SAMP ( expr )
OVER ( analytic_clause )
STDDEV_SAMP
5-198 Oracle Database SQL Language Reference
Purpose
STDDEV_SAMP computes the cumulative sample standard deviation and returns the
square root of the sample variance. You can use it as both an aggregate and analytic
function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
This function is same as the square root of the VAR_SAMP function. When VAR_SAMP
returns null, this function returns null.
Aggregate Example
Refer to the aggregate example for STDDEV_POP on page 5-196.
Analytic Example
The following example returns the sample standard deviation of salaries in the
employees table by department:
SELECT department_id, last_name, hire_date, salary,
STDDEV_SAMP(salary) OVER (PARTITION BY department_id
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sdev
FROM employees
ORDER BY department_id, last_name, hire_date, salary, cum_sdev;
DEPARTMENT_ID LAST_NAME HIRE_DATE SALARY CUM_SDEV
------------- --------------- --------- ---------- ----------
10 Whalen 17-SEP-03 4400
20 Fay 17-AUG-05 6000 4949.74747
20 Hartstein 17-FEB-04 13000
30 Baida 24-DEC-05 2900 4035.26125
30 Colmenares 10-AUG-07 2500 3362.58829
30 Himuro 15-NOV-06 2600 3649.2465
30 Khoo 18-MAY-03 3100 5586.14357
30 Raphaely 07-DEC-02 11000
. . .
100 Greenberg 17-AUG-02 12008 2126.9772
100 Popp 07-DEC-07 6900 1804.13155
100 Sciarra 30-SEP-05 7700 1929.76233
100 Urman 07-MAR-06 7800 1788.92504
110 Gietz 07-JUN-02 8300 2621.95194
110 Higgins 07-JUN-02 12008
Grant 24-MAY-07 7000
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also:
■ "Aggregate Functions" on page 5-9 and VAR_SAMP on page 5-245
■ "About SQL Expressions" on page 6-1 for information on valid
forms of expr
SUBSTR
Functions 5-199
SUBSTR
Syntax
substr::=
Purpose
The SUBSTR functions return a portion of char, beginning at character position,
substring_length characters long. SUBSTR calculates lengths using characters as
defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC
uses Unicode complete characters. SUBSTR2 uses UCS2 code points. SUBSTR4 uses
UCS4 code points.
■ If position is 0, then it is treated as 1.
■ If position is positive, then Oracle Database counts from the beginning of char
to find the first character.
■ If position is negative, then Oracle counts backward from the end of char.
■ If substring_length is omitted, then Oracle returns all characters to the end of
char. If substring_length is less than 1, then Oracle returns null.
char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB. Both position and substring_length must be of data type NUMBER, or
any data type that can be implicitly converted to NUMBER, and must resolve to an
integer. The return value is the same data type as char. Floating-point numbers
passed as arguments to SUBSTR are automatically converted to integers.
Examples
The following example returns several specified substrings of "ABCDEFG":
SELECT SUBSTR('ABCDEFG',3,4) "Substring"
FROM DUAL;
Substring
---------
CDEF
SELECT SUBSTR('ABCDEFG',-5,4) "Substring"
FROM DUAL;
Substring
---------
See Also: Oracle Database Globalization Support Guide for more
information about SUBSTR functions and length semantics in different
locales
SUBSTR
SUBSTRB
SUBSTRC
SUBSTR2
SUBSTR4
( char , position
, substring_length
)
SUM
5-200 Oracle Database SQL Language Reference
CDEF
Assume a double-byte database character set:
SELECT SUBSTRB('ABCDEFG',5,4.2) "Substring with bytes"
FROM DUAL;
Substring with bytes
--------------------
CD
SUM
Syntax
Purpose
SUM returns the sum of values of expr. You can use it as an aggregate or analytic
function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
If you specify DISTINCT, then you can specify only the query_partition_clause
of the analytic_clause. The order_by_clause and windowing_clause are not
allowed.
Aggregate Example
The following example calculates the sum of all salaries in the sample hr.employees
table:
SELECT SUM(salary) "Total"
FROM employees;
Total
----------
691400
Analytic Example
The following example calculates, for each manager in the sample table
hr.employees, a cumulative total of salaries of employees who answer to that
manager that are equal to or less than the current salary. You can see that Raphaely
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
SUM (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
SYS_CONNECT_BY_PATH
Functions 5-201
and Cambrault have the same cumulative total. This is because Raphaely and
Cambrault have the identical salaries, so Oracle Database adds together their salary
values and applies the same cumulative total to both rows.
SELECT manager_id, last_name, salary,
SUM(salary) OVER (PARTITION BY manager_id ORDER BY salary
RANGE UNBOUNDED PRECEDING) l_csum
FROM employees
ORDER BY manager_id, last_name, salary, l_csum;
MANAGER_ID LAST_NAME SALARY L_CSUM
---------- --------------- ---------- ----------
MANAGER_ID LAST_NAME SALARY L_CSUM
---------- ------------------------- ---------- ----------
100 Cambrault 11000 68900
100 De Haan 17000 155400
100 Errazuriz 12000 80900
100 Fripp 8200 36400
100 Hartstein 13000 93900
100 Kaufling 7900 20200
100 Kochhar 17000 155400
100 Mourgos 5800 5800
100 Partners 13500 107400
100 Raphaely 11000 68900
100 Russell 14000 121400
. . .
149 Hutton 8800 39000
149 Johnson 6200 6200
149 Livingston 8400 21600
149 Taylor 8600 30200
201 Fay 6000 6000
205 Gietz 8300 8300
King 24000 24000
SYS_CONNECT_BY_PATH
Syntax
Purpose
SYS_CONNECT_BY_PATH is valid only in hierarchical queries. It returns the path of a
column value from root to node, with column values separated by char for each row
returned by CONNECT BY condition.
Both column and char can be any of the data types CHAR, VARCHAR2, NCHAR, or
NVARCHAR2. The string returned is of VARCHAR2 data type and is in the same
character set as column.
Examples
The following example returns the path of employee names from employee Kochhar
to all employees of Kochhar (and their employees):
SELECT LPAD(' ', 2*level-1)||SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
See Also: "Hierarchical Queries" on page 9-3 for more information
about hierarchical queries and CONNECT BY conditions
SYS_CONNECT_BY_PATH ( column , char )
SYS_CONTEXT
5-202 Oracle Database SQL Language Reference
START WITH last_name = 'Kochhar'
CONNECT BY PRIOR employee_id = manager_id;
Path
------------------------------
/Kochhar/Greenberg/Chen
/Kochhar/Greenberg/Faviet
/Kochhar/Greenberg/Popp
/Kochhar/Greenberg/Sciarra
/Kochhar/Greenberg/Urman
/Kochhar/Higgins/Gietz
/Kochhar/Baer
/Kochhar/Greenberg
/Kochhar/Higgins
/Kochhar/Mavris
/Kochhar/Whalen
/Kochhar
SYS_CONTEXT
Syntax
Purpose
SYS_CONTEXT returns the value of parameter associated with the context
namespace at the current instant. You can use this function in both SQL and PL/SQL
statements.
For namespace and parameter, you can specify either a string or an expression that
resolves to a string designating a namespace or an attribute. If you specify literal
arguments for namespace and parameter, and you are using SYS_CONTEXT
explicitly in a SQL statement—rather than in a PL/SQL function that in turn is in
mentioned in a SQL statement—then Oracle Database evaluates SYS_CONTEXT only
once per SQL statement execution for each call site that invokes the SYS_CONTEXT
function.
The context namespace must already have been created, and the associated
parameter and its value must also have been set using the DBMS_SESSION.set_
context procedure. The namespace must be a valid SQL identifier. The parameter
name can be any string. It is not case sensitive, but it cannot exceed 30 bytes in length.
The data type of the return value is VARCHAR2. The default maximum size of the
return value is 256 bytes. You can override this default by specifying the optional
length parameter, which must be a NUMBER or a value that can be implicitly
converted to NUMBER. The valid range of values is 1 to 4000 bytes. If you specify an
invalid value, then Oracle Database ignores it and uses the default.
Oracle provides a built-in namespace called USERENV, which describes the current
session. The predefined parameters of namespace USERENV are listed in Table 5–11 on
page 5-203.
SYS_CONTEXT ( ’ namespace ’ , ’ parameter ’
, length
)
SYS_CONTEXT
Functions 5-203
Examples
The following statement returns the name of the user who logged onto the database:
CONNECT OE/password
SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER')
FROM DUAL;
SYS_CONTEXT ('USERENV', 'SESSION_USER')
------------------------------------------------------
OE
The following hypothetical example returns the group number that was set as the
value for the attribute group_no in the PL/SQL package that was associated with the
context hr_apps when hr_apps was created:
SELECT SYS_CONTEXT ('hr_apps', 'group_no') "User Group"
FROM DUAL;
See Also:
■ Oracle Database Security Guide for information on using the
application context feature in your application development
■ CREATE CONTEXT on page 14-9 for information on creating
user-defined context namespaces
■ Oracle Database PL/SQL Packages and Types Reference for
information on the DBMS_SESSION.set_context procedure
Note: For simplicity in demonstrating this feature, this example does
not perform the password management techniques that a deployed
system normally uses. In a production environment, follow the Oracle
Database password management guidelines, and disable any sample
accounts. See Oracle Database Security Guide for password management
guidelines and other security recommendations.
Table 5–11 Predefined Parameters of Namespace USERENV
Parameter Return Value
ACTION Identifies the position in the module (application name) and is set through the
DBMS_APPLICATION_INFO package or OCI.
AUDITED_CURSORID Returns the cursor ID of the SQL that triggered the audit. This parameter is not
valid in a fine-grained auditing environment. If you specify it in such an
environment, then Oracle Database always returns NULL.
SYS_CONTEXT
5-204 Oracle Database SQL Language Reference
AUTHENTICATED_IDENTITY Returns the identity used in authentication. In the list that follows, the type of user
is followed by the value returned:
■ Kerberos-authenticated enterprise user: kerberos principal name
■ Kerberos-authenticated external user : kerberos principal name; same as the
schema name
■ SSL-authenticated enterprise user: the DN in the user's PKI certificate
■ SSL-authenticated external user: the DN in the user's PKI certificate
■ Password-authenticated enterprise user: nickname; same as the login name
■ Password-authenticated database user: the database username; same as the
schema name
■ OS-authenticated external user: the external operating system user name
■ Radius/DCE-authenticated external user: the schema name
■ Proxy with DN : Oracle Internet Directory DN of the client
■ Proxy with certificate: certificate DN of the client
■ Proxy with username: database user name if client is a local database user;
nickname if client is an enterprise user.
■ SYSDBA/SYSOPER using Password File: login name
■ SYSDBA/SYSOPER using OS authentication: operating system user name
AUTHENTICATION_DATA Data being used to authenticate the login user. For X.503 certificate authenticated
sessions, this field returns the context of the certificate in HEX2 format.
Note: You can change the return value of the AUTHENTICATION_DATA attribute
using the length parameter of the syntax. Values of up to 4000 are accepted. This
is the only attribute of USERENV for which Oracle Database implements such a
change.
AUTHENTICATION_METHOD Returns the method of authentication. In the list that follows, the type of user is
followed by the method returned:
■ Password-authenticated enterprise user, local database user, or
SYSDBA/SYSOPER using Password File; proxy with username using
password: PASSWORD
■ Kerberos-authenticated enterprise or external user: KERBEROS
■ SSL-authenticated enterprise or external user: SSL
■ Radius-authenticated external user: RADIUS
■ OS-authenticated external user or SYSDBA/SYSOPER: OS
■ DCE-authenticated external user: DCE
■ Proxy with certificate, DN, or username without using password: NONE
■ Background process (job queue slave process): JOB
You can use IDENTIFICATION_TYPE to distinguish between external and
enterprise users when the authentication method is Password, Kerberos, or SSL.
BG_JOB_ID Job ID of the current session if it was established by an Oracle Database
background process. Null if the session was not established by a background
process.
CLIENT_IDENTIFIER Returns an identifier that is set by the application through the DBMS_
SESSION.SET_IDENTIFIER procedure, the OCI attribute OCI_ATTR_CLIENT_
IDENTIFIER, or the Java class
Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is
used by various database components to identify lightweight application users
who authenticate as the same database user.
Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV
Parameter Return Value
SYS_CONTEXT
Functions 5-205
CLIENT_INFO Returns up to 64 bytes of user session information that can be stored by an
application using the DBMS_APPLICATION_INFO package.
CURRENT_BIND The bind variables for fine-grained auditing.
CURRENT_EDITION_ID The identifier of the current edition.
CURRENT_EDITION_NAME The name of the current edition.
CURRENT_SCHEMA The name of the currently active default schema. This value may change during
the duration of a session through use of an ALTER SESSION SET CURRENT_
SCHEMA statement. This may also change during the duration of a session to reflect
the owner of any active definer's rights object. When used directly in the body of a
view definition, this returns the default schema used when executing the cursor
that is using the view; it does not respect views used in the cursor as being
definer's rights.
Note: Oracle recommends against issuing the SQL statement ALTER SESSION SET
CURRENT_SCHEMA from within a stored PL/SQL unit.
CURRENT_SCHEMAID Identifier of the currently active default schema.
CURRENT_SQL
CURRENT_SQLn
CURRENT_SQL returns the first 4K bytes of the current SQL that triggered the
fine-grained auditing event. The CURRENT_SQLn attributes return subsequent
4K-byte increments, where n can be an integer from 1 to 7, inclusive. CURRENT_
SQL1 returns bytes 4K to 8K; CURRENT_SQL2 returns bytes 8K to 12K, and so
forth. You can specify these attributes only inside the event handler for the
fine-grained auditing feature.
CURRENT_SQL_LENGTH The length of the current SQL statement that triggers fine-grained audit or
row-level security (RLS) policy functions or event handlers. Valid only inside the
function or event handler.
CURRENT_USER The name of the database user whose privileges are currently active. This may
change during the duration of a session to reflect the owner of any active definer's
rights object. When no definer's rights object is active, CURRENT_USER returns the
same value as SESSION_USER. When used directly in the body of a view
definition, this returns the user that is executing the cursor that is using the view; it
does not respect views used in the cursor as being definer's rights.
CURRENT_USERID The identifier of the database user whose privileges are currently active.
DATABASE_ROLE The database role using the SYS_CONTEXT function with the USERENV namespace.
The role is one of the following: PRIMARY, PHYSICAL STANDBY, LOGICAL
STANDBY, SNAPSHOT STANDBY.
DB_DOMAIN Domain of the database as specified in the DB_DOMAIN initialization parameter.
DB_NAME Name of the database as specified in the DB_NAME initialization parameter.
DB_UNIQUE_NAME Name of the database as specified in the DB_UNIQUE_NAME initialization
parameter.
ENTRYID The current audit entry number. The audit entryid sequence is shared between
fine-grained audit records and regular audit records. You cannot use this attribute
in distributed SQL statements. The correct auditing entry identifier can be seen
only through an audit handler for standard or fine-grained audit.
Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV
Parameter Return Value
SYS_CONTEXT
5-206 Oracle Database SQL Language Reference
ENTERPRISE_IDENTITY Returns the user's enterprise-wide identity:
■ For enterprise users: the Oracle Internet Directory DN.
■ For external users: the external identity (Kerberos principal name, Radius and
DCE schema names, OS user name, Certificate DN).
■ For local users and SYSDBA/SYSOPER logins: NULL.
The value of the attribute differs by proxy method:
■ For a proxy with DN: the Oracle Internet Directory DN of the client
■ For a proxy with certificate: the certificate DN of the client for external users;
the Oracle Internet Directory DN for global users
■ For a proxy with username: the Oracle Internet Directory DN if the client is an
enterprise users; NULL if the client is a local database user.
FG_JOB_ID Job ID of the current session if it was established by a client foreground process.
Null if the session was not established by a foreground process.
GLOBAL_CONTEXT_MEMORY Returns the number being used in the System Global Area by the globally accessed
context.
GLOBAL_UID Returns the global user ID from Oracle Internet Directory for Enterprise User
Security (EUS) logins; returns null for all other logins.
HOST Name of the host machine from which the client has connected.
IDENTIFICATION_TYPE Returns the way the user's schema was created in the database. Specifically, it
reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that
follows, the syntax used during schema creation is followed by the identification
type returned:
■ IDENTIFIED BY password: LOCAL
■ IDENTIFIED EXTERNALLY: EXTERNAL
■ IDENTIFIED GLOBALLY: GLOBAL SHARED
■ IDENTIFIED GLOBALLY AS DN: GLOBAL PRIVATE
INSTANCE The instance identification number of the current instance.
INSTANCE_NAME The name of the instance.
IP_ADDRESS IP address of the machine from which the client is connected. If the client and
server are on the same machine and the connection uses IPv6 addressing, then ::1
is returned.
ISDBA Returns TRUE if the user has been authenticated as having DBA privileges either
through the operating system or through a password file.
LANG The abbreviated name for the language, a shorter form than the existing
'LANGUAGE' parameter.
LANGUAGE The language and territory currently used by your session, along with the
database character set, in this form:
language_territory.characterset
MODULE The application name (module) set through the DBMS_APPLICATION_INFO
package or OCI.
NETWORK_PROTOCOL Network protocol being used for communication, as specified in the
'PROTOCOL=protocol' portion of the connect string.
NLS_CALENDAR The current calendar of the current session.
NLS_CURRENCY The currency of the current session.
NLS_DATE_FORMAT The date format for the session.
Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV
Parameter Return Value
SYS_CONTEXT
Functions 5-207
Table 5–12 lists the parameters of namespace USERENV that have been deprecated. Do
not specify any of these parameters. Instead use the alternatives suggested in the
Comments column.
NLS_DATE_LANGUAGE The language used for expressing dates.
NLS_SORT BINARY or the linguistic sort basis.
NLS_TERRITORY The territory of the current session.
OS_USER Operating system user name of the client process that initiated the database
session.
POLICY_INVOKER The invoker of row-level security (RLS) policy functions.
PROXY_ENTERPRISE_
IDENTITY
Returns the Oracle Internet Directory DN when the proxy user is an enterprise
user.
PROXY_GLOBAL_UID Returns the global user ID from Oracle Internet Directory for Enterprise User
Security (EUS) proxy users; returns NULL for all other proxy users.
PROXY_USER Name of the database user who opened the current session on behalf of SESSION_
USER.
PROXY_USERID Identifier of the database user who opened the current session on behalf of
SESSION_USER.
SERVER_HOST The host name of the machine on which the instance is running.
SERVICE_NAME The name of the service to which a given session is connected.
SESSION_EDITION_ID The identifier of the session edition.
SESSION_EDITION_NAME The name of the session edition.
SESSION_USER The name of the database user at logon. For enterprise users, returns the schema.
For other users, returns the database user name. This value remains the same
throughout the duration of the session.
SESSION_USERID The identifier of the database user at logon.
SESSIONID The auditing session identifier. You cannot use this attribute in distributed SQL
statements.
SID The session ID.
STATEMENTID The auditing statement identifier. STATEMENTID represents the number of SQL
statements audited in a given session. You cannot use this attribute in distributed
SQL statements. The correct auditing statement identifier can be seen only through
an audit handler for standard or fine-grained audit.
TERMINAL The operating system identifier for the client of the current session. In distributed
SQL statements, this attribute returns the identifier for your local session. In a
distributed environment, this is supported only for remote SELECT statements, not
for remote INSERT, UPDATE, or DELETE operations. (The return length of this
parameter may vary by operating system.)
Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV
Parameter Return Value
SYS_DBURIGEN
5-208 Oracle Database SQL Language Reference
SYS_DBURIGEN
Syntax
Purpose
SYS_DBURIGen takes as its argument one or more columns or attributes, and
optionally a rowid, and generates a URL of data type DBURIType to a particular
column or row object. You can then use the URL to retrieve an XML document from
the database.
All columns or attributes referenced must reside in the same table. They must perform
the function of a primary key. They need not actually match the primary key of the
table, but they must reference a unique value. If you specify multiple columns, then all
but the final column identify the row in the database, and the last column specified
identifies the column within the row.
By default the URL points to a formatted XML document. If you want the URL to
point only to the text of the document, then specify the optional 'text()'.
If the table or view containing the columns or attributes does not have a schema
specified in the context of the query, then Oracle Database interprets the table or view
name as a public synonym.
Examples
The following example uses the SYS_DBURIGen function to generate a URL of data
type DBURIType to the email column of the row in the sample table hr.employees
where the employee_id = 206:
SELECT SYS_DBURIGEN(employee_id, email)
FROM employees
Table 5–12 Deprecated Parameters of Namespace USERENV
Parameter Comments
AUTHENTICATION_TYPE This parameter returned a value indicating how the user was authenticated. The same
information is now available from the new AUTHENTICATION_METHOD parameter
combined with IDENTIFICATION_TYPE.
EXTERNAL_NAME This parameter returned the external name of the user. More complete information
can now be obtained from the AUTHENTICATED_IDENTITY and ENTERPRISE_
IDENTITY parameter.
Note: In this XML context, the lowercase text is a keyword, not a
syntactic placeholder.
See Also: Oracle XML Developer's Kit Programmer's Guide for
information on the URIType data type and XML documents in the
database
SYS_DBURIGEN (
column
attribute
rowid
,
, ’ text ( ) ’
)
SYS_GUID
Functions 5-209
WHERE employee_id = 206;
SYS_DBURIGEN(EMPLOYEE_ID,EMAIL)(URL, SPARE)
--------------------------------------------------------------------
DBURITYPE('/PUBLIC/EMPLOYEES/ROW[EMPLOYEE_ID=''206'']/EMAIL', NULL)
SYS_EXTRACT_UTC
Syntax
Purpose
SYS_EXTRACT_UTC extracts the UTC (Coordinated Universal Time—formerly
Greenwich Mean Time) from a datetime value with time zone offset or time zone
region name. If a time zone is not specified, the time is associated with the database
time zone.
Examples
The following example extracts the UTC from a specified datetime:
SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -08:00')
FROM DUAL;
SYS_EXTRACT_UTC(TIMESTAMP'2000-03-2811:30:00.00-08:00')
-----------------------------------------------------------------
28-MAR-00 07.30.00 PM
SYS_GUID
Syntax
Purpose
SYS_GUID generates and returns a globally unique identifier (RAW value) made up of
16 bytes. On most platforms, the generated identifier consists of a host identifier, a
process or thread identifier of the process or thread invoking the function, and a
nonrepeating value (sequence of bytes) for that process or thread.
Examples
The following example adds a column to the sample table hr.locations, inserts
unique identifiers into each row, and returns the 32-character hexadecimal
representation of the 16-byte RAW value of the global unique identifier:
ALTER TABLE locations ADD (uid_col RAW(16));
UPDATE locations SET uid_col = SYS_GUID();
SELECT location_id, uid_col FROM locations
ORDER BY location_id, uid_col;
LOCATION_ID UID_COL
----------- ----------------------------------------------------------------
SYS_EXTRACT_UTC ( datetime_with_timezone )
SYS_GUID ( )
SYS_TYPEID
5-210 Oracle Database SQL Language Reference
1000 09F686761827CF8AE040578CB20B7491
1100 09F686761828CF8AE040578CB20B7491
1200 09F686761829CF8AE040578CB20B7491
1300 09F68676182ACF8AE040578CB20B7491
1400 09F68676182BCF8AE040578CB20B7491
1500 09F68676182CCF8AE040578CB20B7491
. . .
SYS_TYPEID
Syntax
Purpose
SYS_TYPEID returns the typeid of the most specific type of the operand. This value is
used primarily to identify the type-discriminant column underlying a substitutable
column. For example, you can use the value returned by SYS_TYPEID to build an
index on the type-discriminant column.
You can use this function only on object type operands. All final root object
types—final types not belonging to a type hierarchy—have a null typeid. Oracle
Database assigns to all types belonging to a type hierarchy a unique non-null typeid.
Examples
The following examples use the tables persons and books, which are created in
"Substitutable Table and Column Examples" on page 16-69. The first query returns the
most specific types of the object instances stored in the persons table.
SELECT name, SYS_TYPEID(VALUE(p)) "Type_id" FROM persons p;
NAME Type_id
------------------------- --------------------------------
Bob 01
Joe 02
Tim 03
The next query returns the most specific types of authors stored in the table books:
SELECT b.title, b.author.name, SYS_TYPEID(author)
"Type_ID" FROM books b;
TITLE AUTHOR.NAME Type_ID
------------------------- -------------------- -------------------
An Autobiography Bob 01
Business Rules Joe 02
Mixing School and Work Tim 03
You can use the SYS_TYPEID function to create an index on the type-discriminant
column of a table. For an example, see "Indexing on Substitutable Columns: Examples"
on page 14-86.
See Also: Oracle Database Object-Relational Developer's Guide for more
information on typeids
SYS_TYPEID ( object_type_value )
SYS_XMLGEN
Functions 5-211
SYS_XMLAGG
Syntax
Purpose
SYS_XMLAgg aggregates all of the XML documents or fragments represented by expr
and produces a single XML document. It adds a new enclosing element with a default
name ROWSET. If you want to format the XML document differently, then specify fmt,
which is an instance of the XMLFormat object.
Examples
The following example uses the SYS_XMLGen function to generate an XML document
for each row of the sample table employees where the employee's last name begins
with the letter R, and then aggregates all of the rows into a single XML document in
the default enclosing element ROWSET:
SELECT SYS_XMLAGG(SYS_XMLGEN(last_name)) XMLAGG
FROM employees
WHERE last_name LIKE 'R%'
ORDER BY xmlagg;
XMLAGG
--------------------------------------------------------------------------------
<?xml version="1.0"?>
<ROWSET>
<LAST_NAME>Rajs</LAST_NAME>
<LAST_NAME>Raphaely</LAST_NAME>
<LAST_NAME>Rogers</LAST_NAME>
<LAST_NAME>Russell</LAST_NAME>
</ROWSET>
SYS_XMLGEN
Syntax
Purpose
SYS_XMLGen takes an expression that evaluates to a particular row and column of the
database, and returns an instance of type XMLType containing an XML document. The
expr can be a scalar value, a user-defined type, or an XMLType instance.
■ If expr is a scalar value, then the function returns an XML element containing the
scalar value.
See Also: SYS_XMLGEN on page 5-211 and "XML Format Model"
on page 3-69 for using the attributes of the XMLFormat type to format
SYS_XMLAgg results
SYS_XMLAGG ( expr
, fmt
)
SYS_XMLGEN ( expr
, fmt
)
SYSDATE
5-212 Oracle Database SQL Language Reference
■ If expr is a type, then the function maps the user-defined type attributes to XML
elements.
■ If expr is an XMLType instance, then the function encloses the document in an
XML element whose default tag name is ROW.
By default the elements of the XML document match the elements of expr. For
example, if expr resolves to a column name, then the enclosing XML element will be
the same column name. If you want to format the XML document differently, then
specify fmt, which is an instance of the XMLFormat object.
Examples
The following example retrieves the employee email ID from the sample table
oe.employees where the employee_id value is 205, and generates an instance of
an XMLType containing an XML document with an EMAIL element.
SELECT SYS_XMLGEN(email)
FROM employees
WHERE employee_id = 205;
SYS_XMLGEN(EMAIL)
-------------------------------------------------------------------
<?xml version="1.0"?>
<EMAIL>SHIGGINS</EMAIL>
SYSDATE
Syntax
Purpose
SYSDATE returns the current date and time set for the operating system on which the
database server resides. The data type of the returned value is DATE, and the format
returned depends on the value of the NLS_DATE_FORMAT initialization parameter. The
function requires no arguments. In distributed SQL statements, this function returns
the date and time set for the operating system of your local database. You cannot use
this function in the condition of a CHECK constraint.
Examples
The following example returns the current operating system date and time:
SELECT TO_CHAR
(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW"
FROM DUAL;
NOW
-------------------
04-13-2001 09:45:51
See Also: "XML Format Model" on page 3-69 for a description of the
XMLFormat type and how to use its attributes to format SYS_XMLGen
results
SYSDATE
TAN
Functions 5-213
SYSTIMESTAMP
Syntax
Purpose
SYSTIMESTAMP returns the system date, including fractional seconds and time zone,
of the system on which the database resides. The return type is TIMESTAMP WITH
TIME ZONE.
Examples
The following example returns the system timestamp:
SELECT SYSTIMESTAMP FROM DUAL;
SYSTIMESTAMP
------------------------------------------------------------------
28-MAR-00 12.38.55.538741 PM -08:00
The following example shows how to explicitly specify fractional seconds:
SELECT TO_CHAR(SYSTIMESTAMP, 'SSSSS.FF') FROM DUAL;
TO_CHAR(SYSTIME
---------------
55615.449255
The following example returns the current timestamp in a specified time zone:
SELECT SYSTIMESTAMP AT TIME ZONE 'UTC' FROM dual;
SYSTIMESTAMPATTIMEZONE'UTC'
---------------------------------------------------------------------------
08-07-21 20:39:52,743557 UTC
The output format in this example depends on the NLS_TIMESTAMP_TZ_FORMAT for
the session.
TAN
Syntax
Purpose
TAN returns the tangent of n (an angle expressed in radians).
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
SYSTIMESTAMP
TAN ( n )
TANH
5-214 Oracle Database SQL Language Reference
Examples
The following example returns the tangent of 135 degrees:
SELECT TAN(135 * 3.14159265359/180)
"Tangent of 135 degrees" FROM DUAL;
Tangent of 135 degrees
----------------------
- 1
TANH
Syntax
Purpose
TANH returns the hyperbolic tangent of n.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If the argument is
BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function
returns the same numeric data type as the argument.
Examples
The following example returns the hyperbolic tangent of .5:
SELECT TANH(.5) "Hyperbolic tangent of .5"
FROM DUAL;
Hyperbolic tangent of .5
------------------------
.462117157
TIMESTAMP_TO_SCN
Syntax
Purpose
TIMESTAMP_TO_SCN takes as an argument a timestamp value and returns the
approximate system change number (SCN) associated with that timestamp. The
returned value is of data type NUMBER. This function is useful any time you want to
know the SCN associated with a particular timestamp.
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
TANH ( n )
TIMESTAMP_TO_SCN ( timestamp )
TO_BINARY_DOUBLE
Functions 5-215
Examples
The following example inserts a row into the oe.orders table and then uses
TIMESTAMP_TO_SCN to determine the system change number of the insert operation.
(The actual SCN returned will differ on each system.)
INSERT INTO orders (order_id, order_date, customer_id, order_total)
VALUES (5000, SYSTIMESTAMP, 188, 2345);
1 row created.
COMMIT;
Commit complete.
SELECT TIMESTAMP_TO_SCN(order_date) FROM orders
WHERE order_id = 5000;
TIMESTAMP_TO_SCN(ORDER_DATE)
----------------------------
574100
TO_BINARY_DOUBLE
Syntax
Purpose
TO_BINARY_DOUBLE returns a double-precision floating-point number.
■ expr can be a character string or a numeric value of type NUMBER, BINARY_
FLOAT, or BINARY_DOUBLE. If expr is BINARY_DOUBLE, then the function
returns expr.
■ The optional 'fmt' and 'nlsparam' arguments are valid only if expr is a character
string. They serve the same purpose as for the TO_CHAR (number) function.
– The case-insensitive string 'INF' is converted to positive infinity.
– The case-insensitive string '-INF' is converted to negative identity.
– The case-insensitive string 'NaN' is converted to NaN (not a number).
Note: The association between an SCN and a timestamp when the
SCN is generated is remembered by the database for a limited period
of time. This period is the maximum of the auto-tuned undo retention
period, if the database runs in the Automatic Undo Management
mode, and the retention times of all flashback archives in the database,
but no less than 120 hours. The time for the association to become
obsolete elapses only when the database is open. An error is returned
if the timestamp specified for the argument to TIMESTAMP_TO_SCN is
too old.
See Also: SCN_TO_TIMESTAMP on page 5-178 for information on
converting SCNs to timestamp
TO_BINARY_DOUBLE ( expr
, fmt
, ’ nlsparam ’
)
TO_BINARY_FLOAT
5-216 Oracle Database SQL Language Reference
You cannot use a floating-point number format element (F, f, D, or d) in a character
string expr.
Conversions from character strings or NUMBER to BINARY_DOUBLE can be inexact,
because the NUMBER and character types use decimal precision to represent the
numeric value, and BINARY_DOUBLE uses binary precision.
Conversions from BINARY_FLOAT to BINARY_DOUBLE are exact.
Examples
The examples that follow are based on a table with three columns, each with a
different numeric data type:
CREATE TABLE float_point_demo
(dec_num NUMBER(10,2), bin_double BINARY_DOUBLE, bin_float BINARY_FLOAT);
INSERT INTO float_point_demo
VALUES (1234.56,1234.56,1234.56);
SELECT * FROM float_point_demo;
DEC_NUM BIN_DOUBLE BIN_FLOAT
---------- ---------- ----------
1234.56 1.235E+003 1.235E+003
The following example converts a value of data type NUMBER to a value of data type
BINARY_DOUBLE:
SELECT dec_num, TO_BINARY_DOUBLE(dec_num)
FROM float_point_demo;
DEC_NUM TO_BINARY_DOUBLE(DEC_NUM)
---------- -------------------------
1234.56 1.235E+003
The following example compares extracted dump information from the dec_num and
bin_double columns:
SELECT DUMP(dec_num) "Decimal",
DUMP(bin_double) "Double"
FROM float_point_demo;
Decimal Double
--------------------------- ---------------------------------------------
Typ=2 Len=4: 194,13,35,57 Typ=101 Len=8: 192,147,74,61,112,163,215,10
TO_BINARY_FLOAT
Syntax
See Also: TO_CHAR (number) on page 5-221 and "Floating-Point
Numbers" on page 3-12
TO_BINARY_FLOAT ( expr
, fmt
, ’ nlsparam ’
)
TO_BLOB
Functions 5-217
Purpose
TO_BINARY_FLOAT returns a single-precision floating-point number.
■ expr can be a character string or a numeric value of type NUMBER, BINARY_
FLOAT, or BINARY_DOUBLE. If expr is BINARY_FLOAT, then the function returns
expr.
■ The optional 'fmt' and 'nlsparam' arguments are valid only if expr is a character
string. They serve the same purpose as for the TO_CHAR (number) function.
– The incase-sensitive string 'INF' is converted to positive infinity.
– The incase-sensitive string '-INF' is converted to negative identity.
– The incase-sensitive string 'NaN' is converted to NaN (not a number).
You cannot use a floating-point number format element (F, f, D, or d) in a character
string expr.
Conversions from character strings or NUMBER to BINARY_FLOAT can be inexact,
because the NUMBER and character types use decimal precision to represent the
numeric value and BINARY_FLOAT uses binary precision.
Conversions from BINARY_DOUBLE to BINARY_FLOAT are inexact if the BINARY_
DOUBLE value uses more bits of precision than supported by the BINARY_FLOAT.
Examples
Using table float_point_demo created for TO_BINARY_DOUBLE on page 5-215,
the following example converts a value of data type NUMBER to a value of data type
BINARY_FLOAT:
SELECT dec_num, TO_BINARY_FLOAT(dec_num)
FROM float_point_demo;
DEC_NUM TO_BINARY_FLOAT(DEC_NUM)
---------- ------------------------
1234.56 1.235E+003
TO_BLOB
Syntax
to_blob::=
Purpose
TO_BLOB converts LONG RAW and RAW values to BLOB values.
From within a PL/SQL package, you can use TO_BLOB to convert RAW and BLOB
values to BLOB.
Example
The following hypothetical example returns the BLOB of a RAW column value:
SELECT TO_BLOB(raw_column) blob FROM raw_table;
See Also: TO_CHAR (number) on page 5-221 and "Floating-Point
Numbers" on page 3-12
TO_BLOB ( raw_value )
TO_CHAR (character)
5-218 Oracle Database SQL Language Reference
BLOB
-----------------------
00AADD343CDBBD
TO_CHAR (character)
Syntax
to_char_char::=
Purpose
TO_CHAR (character) converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the
database character set. The value returned is always VARCHAR2.
When you use this function to convert a character LOB into the database character set,
if the LOB value to be converted is larger than the target type, then the database
returns an error.
You can use this function in conjunction with any of the XML functions to generate a
date in the database format rather than the XML Schema standard format.
Examples
The following example interprets a simple string as character data:
SELECT TO_CHAR('01110') FROM DUAL;
TO_CH
-----
01110
Compare this example with the first example for TO_CHAR (number) on page 5-221.
The following example converts some CLOB data from the pm.print_media table to
the database character set:
SELECT TO_CHAR(ad_sourcetext) FROM print_media
WHERE product_id = 2268;
TO_CHAR(AD_SOURCETEXT)
--------------------------------------------------------------------
******************************
TIGER2 2268...Standard Hayes Compatible Modem
Product ID: 2268
The #1 selling modem in the universe! Tiger2's modem includes call management
and Internet voicing. Make real-time full duplex phone calls at the same time
See Also:
■ Oracle XML DB Developer's Guide for information about formatting
of XML dates and timestamps, including examples
■ "XML Functions" on page 5-8 for a listing of the XML function
TO_CHAR (
nchar
clob
nclob
)
TO_CHAR (datetime)
Functions 5-219
you're online.
**********************************
TO_CHAR (datetime)
Syntax
to_char_date::=
Purpose
TO_CHAR (datetime) converts a datetime or interval value of DATE, TIMESTAMP,
TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL DAY
TO SECOND, or INTERVAL YEAR TO MONTH data type to a value of VARCHAR2 data
type in the format specified by the date format fmt. If you omit fmt, then date is
converted to a VARCHAR2 value as follows:
■ DATE values are converted to values in the default date format.
■ TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONE values are converted to
values in the default timestamp format.
■ TIMESTAMP WITH TIME ZONE values are converted to values in the default
timestamp with time zone format.
■ Interval values are converted to the numeric representation of the interval literal.
Refer to "Format Models" on page 3-55 for information on datetime formats.
The 'nlsparam' argument specifies the language in which month and day names
and abbreviations are returned. This argument can have this form:
'NLS_DATE_LANGUAGE = language'
If you omit 'nlsparam', then this function uses the default date language for your
session.
Examples
The following example uses this table:
CREATE TABLE date_tab (
ts_col TIMESTAMP,
tsltz_col TIMESTAMP WITH LOCAL TIME ZONE,
tstz_col TIMESTAMP WITH TIME ZONE);
The example shows the results of applying TO_CHAR to different TIMESTAMP data
types. The result for a TIMESTAMP WITH LOCAL TIME ZONE column is sensitive to
session time zone, whereas the results for the TIMESTAMP and TIMESTAMP WITH
TIME ZONE columns are not sensitive to session time zone:
ALTER SESSION SET TIME_ZONE = '-8:00';
INSERT INTO date_tab VALUES (
See Also: "Security Considerations for Data Conversion" on
page 3-44
TO_CHAR (
datetime
interval
, fmt
, ’ nlsparam ’
)
TO_CHAR (datetime)
5-220 Oracle Database SQL Language Reference
TIMESTAMP'1999-12-01 10:00:00',
TIMESTAMP'1999-12-01 10:00:00',
TIMESTAMP'1999-12-01 10:00:00');
INSERT INTO date_tab VALUES (
TIMESTAMP'1999-12-02 10:00:00 -8:00',
TIMESTAMP'1999-12-02 10:00:00 -8:00',
TIMESTAMP'1999-12-02 10:00:00 -8:00');
SELECT TO_CHAR(ts_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS ts_date,
TO_CHAR(tstz_col, 'DD-MON-YYYY HH24:MI:SSxFF TZH:TZM') AS tstz_date
FROM date_tab
ORDER BY ts_date, tstz_date;
TS_DATE TSTZ_DATE
------------------------------ -------------------------------------
01-DEC-1999 10:00:00.000000 01-DEC-1999 10:00:00.000000 -08:00
02-DEC-1999 10:00:00.000000 02-DEC-1999 10:00:00.000000 -08:00
SELECT SESSIONTIMEZONE,
TO_CHAR(tsltz_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS tsltz
FROM date_tab
ORDER BY sessiontimezone, tsltz;
SESSIONTIM TSLTZ
---------- ------------------------------
-08:00 01-DEC-1999 10:00:00.000000
-08:00 02-DEC-1999 10:00:00.000000
ALTER SESSION SET TIME_ZONE = '-5:00';
SELECT TO_CHAR(ts_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS ts_col,
TO_CHAR(tstz_col, 'DD-MON-YYYY HH24:MI:SSxFF TZH:TZM') AS tstz_col
FROM date_tab
ORDER BY ts_col, tstz_col;
TS_COL TSTZ_COL
------------------------------ -------------------------------------
01-DEC-1999 10:00:00.000000 01-DEC-1999 10:00:00.000000 -08:00
02-DEC-1999 10:00:00.000000 02-DEC-1999 10:00:00.000000 -08:00
SELECT SESSIONTIMEZONE,
TO_CHAR(tsltz_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS tsltz_col
FROM date_tab
ORDER BY sessiontimezone, tsltz_col;
2 3 4
SESSIONTIM TSLTZ_COL
---------- ------------------------------
-05:00 01-DEC-1999 13:00:00.000000
-05:00 02-DEC-1999 13:00:00.000000
The following example converts an interval literal into a text literal:
SELECT TO_CHAR(INTERVAL '123-2' YEAR(3) TO MONTH) FROM DUAL;
TO_CHAR
-------
+123-02
TO_CHAR (number)
Functions 5-221
TO_CHAR (number)
Syntax
to_char_number::=
Purpose
TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the optional
number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or BINARY_
DOUBLE. If you omit fmt, then n is converted to a VARCHAR2 value exactly long
enough to hold its significant digits.
If n is negative, then the sign is applied after the format is applied. Thus TO_
CHAR(-1, '$9') returns -$1, rather than $-1.
Refer to "Format Models" on page 3-55 for information on number formats.
The 'nlsparam' argument specifies these characters that are returned by number
format elements:
■ Decimal character
■ Group separator
■ Local currency symbol
■ International currency symbol
This argument can have this form:
'NLS_NUMERIC_CHARACTERS = ''dg''
NLS_CURRENCY = ''text''
NLS_ISO_CURRENCY = territory '
The characters d and g represent the decimal character and group separator,
respectively. They must be different single-byte characters. Within the quoted string,
you must use two single quotation marks around the parameter values. Ten characters
are available for the currency symbol.
If you omit 'nlsparam' or any one of the parameters, then this function uses the
default parameter values for your session.
Examples
The following statement uses implicit conversion to combine a string and a number
into a number:
SELECT TO_CHAR('01110' + 1) FROM dual;
TO_C
----
1111
See Also: "Security Considerations for Data Conversion" on
page 3-44
TO_CHAR ( n
, fmt
, ’ nlsparam ’
)
TO_CLOB
5-222 Oracle Database SQL Language Reference
Compare this example with the first example for TO_CHAR (character) on page 5-218.
In the next example, the output is blank padded to the left of the currency symbol.
SELECT TO_CHAR(-10000,'L99G999D99MI') "Amount"
FROM DUAL;
Amount
--------------
$10,000.00-
SELECT TO_CHAR(-10000,'L99G999D99MI',
'NLS_NUMERIC_CHARACTERS = '',.''
NLS_CURRENCY = ''AusDollars'' ') "Amount"
FROM DUAL;
Amount
-------------------
AusDollars10.000,00-
In the optional number format fmt, L designates local currency symbol and MI
designates a trailing minus sign. See Table 3–17, " Matching Character Data and
Format Models with the FX Format Model Modifier" on page 3-67 for a complete
listing of number format elements.
TO_CLOB
Syntax
Purpose
TO_CLOB converts NCLOB values in a LOB column or other character strings to CLOB
values. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB. Oracle Database executes this function by converting the underlying
LOB data from the national character set to the database character set.
From within a PL/SQL package, you can use the TO_CLOB function to convert RAW,
CHAR, VARCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB values to CLOB or
NCLOB values.
Examples
The following statement converts NCLOB data from the sample pm.print_media
table to CLOB and inserts it into a CLOB column, replacing existing data in that column.
UPDATE PRINT_MEDIA
SET AD_FINALTEXT = TO_CLOB (AD_FLTEXTN);
TO_CLOB (
lob_column
char
)
TO_DATE
Functions 5-223
TO_DATE
Syntax
Purpose
TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to a
value of DATE data type.
The fmt is a datetime model format specifying the format of char. If you omit fmt,
then char must be in the default date format. The default date format is determined
implicitly by the NLS_TERRITORY initialization parameter or can be set explicitly by
the NLS_DATE_FORMAT parameter. If fmt is J, for Julian, then char must be an
integer.
The 'nlsparam' argument specifies the language of the text string that is being
converted to a date. This argument can have this form:
'NLS_DATE_LANGUAGE = language'
Do not use the TO_DATE function with a DATE value for the char argument. The first
two digits of the returned DATE value can differ from the original char, depending on
fmt or the default date format.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example converts a character string into a date:
SELECT TO_DATE(
'January 15, 1989, 11:00 A.M.',
Note: This function does not convert data to any of the other
datetime data types. For information on other datetime conversions,
refer to TO_TIMESTAMP on page 5-230, TO_TIMESTAMP_TZ on
page 5-231, TO_DSINTERVAL on page 5-224, and TO_YMINTERVAL
on page 5-232.
Caution: It is good practice always to specify a format mask (fmt)
with TO_DATE, as shown in the examples in the section that follows.
When it is used without a format mask, the function is valid only if
char uses the same format as is determined by the NLS_TERRITORY
or NLS_DATE_FORMAT parameters. Furthermore, the function may
not be stable across databases unless the explicit format mask is
specified to avoid dependencies.
See Also: "Datetime Format Models" on page 3-59 and "Data Type
Comparison Rules" on page 3-37 for more information
TO_DATE ( char
, fmt
, ’ nlsparam ’
)
TO_DSINTERVAL
5-224 Oracle Database SQL Language Reference
'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American')
FROM DUAL;
TO_DATE('
---------
15-JAN-89
The value returned reflects the default date format if the NLS_TERRITORY parameter
is set to 'AMERICA'. Different NLS_TERRITORY values result in different default date
formats:
ALTER SESSION SET NLS_TERRITORY = 'KOREAN';
SELECT TO_DATE(
'January 15, 1989, 11:00 A.M.',
'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American')
FROM DUAL;
TO_DATE(
--------
89/01/15
TO_DSINTERVAL
Syntax
sql_format::=
ds_iso_format::=
Purpose
TO_DSINTERVAL converts a character string of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type to an INTERVAL DAY TO SECOND type.
TO_DSINTERVAL accepts argument in one of the two formats:
■ SQL interval format compatible with the SQL standard (ISO/IEC 9075:2003)
■ ISO duration format compatible with the ISO 8601:2004 standard
TO_DSINTERVAL ( ’
sql_format
ds_iso_format
’ )
+
–
days hours : minutes : seconds
. frac_secs
–
P
days D
T
hours H minutes M
seconds
. frac_secs
S
TO_LOB
Functions 5-225
In the SQL format, days is an integer between 0 and 999999999, hours is an integer
between 0 and 23, and minutes and seconds are integers between 0 and 59. frac_
secs is the fractional part of seconds between .0 and .999999999. One or more blanks
separate days from hours. Additional blanks are allowed between format elements.
In the ISO format, days, hours, minutes and seconds are integers between 0 and
999999999. frac_secs is the fractional part of seconds between .0 and .999999999. No
blanks are allowed in the value.
Examples
The following example uses the SQL format to select from the hr.employees table
the employees who had worked for the company for at least 100 days on November 1,
2002:
SELECT employee_id, last_name FROM employees
WHERE hire_date + TO_DSINTERVAL('100 00:00:00')
<= DATE '2002-11-01'
ORDER BY employee_id;
EMPLOYEE_ID LAST_NAME
----------- ---------------
102 De Haan
203 Mavris
204 Baer
205 Higgins
206 Giet
The following example uses the ISO format to display the timestamp 100 days and 5
hours after the beginning of the year 2009:
SELECT TO_CHAR(TIMESTAMP '2009-01-01 00:00:00' + TO_DSINTERVAL('P100DT05H'),
'YYYY-MM-DD HH24:MI:SS') "Time Stamp"
FROM DUAL;
Time Stamp
-------------------
2009-04-11 05:00:00
TO_LOB
Syntax
Purpose
TO_LOB converts LONG or LONG RAW values in the column long_column to LOB
values. You can apply this function only to a LONG or LONG RAW column, and only in
the select list of a subquery in an INSERT statement.
Before using this function, you must create a LOB column to receive the converted
LONG values. To convert LONG values, create a CLOB column. To convert LONG RAW
values, create a BLOB column.
You cannot use the TO_LOB function to convert a LONG column to a LOB column in the
subquery of a CREATE TABLE ... AS SELECT statement if you are creating an
index-organized table. Instead, create the index-organized table without the LONG
column, and then use the TO_LOB function in an INSERT ... AS SELECT statement.
TO_LOB ( long_column )
TO_MULTI_BYTE
5-226 Oracle Database SQL Language Reference
You cannot use this function within a PL/SQL package. Instead use the TO_CLOB or
TO_BLOB functions.
Example
The following syntax shows how to use the TO_LOB function on your LONG data in a
hypothetical table old_table:
CREATE TABLE new_table (col1, col2, ... lob_col CLOB);
INSERT INTO new_table (select o.col1, o.col2, ... TO_LOB(o.old_long_col)
FROM old_table o;
TO_MULTI_BYTE
Syntax
Purpose
TO_MULTI_BYTE returns char with all of its single-byte characters converted to their
corresponding multibyte characters. char can be of data type CHAR, VARCHAR2,
NCHAR, or NVARCHAR2. The value returned is in the same data type as char.
Any single-byte characters in char that have no multibyte equivalents appear in the
output string as single-byte characters. This function is useful only if your database
character set contains both single-byte and multibyte characters.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example illustrates converting from a single byte A to a multibyte A in
UTF8:
SELECT dump(TO_MULTI_BYTE( 'A')) FROM DUAL;
DUMP(TO_MULTI_BYTE('A'))
------------------------
Typ=1 Len=3: 239,188,161
See Also:
■ the modify_col_properties clause of ALTER TABLE on
page 12-2 for an alternative method of converting LONG columns
to LOB
■ INSERT on page 18-54 for information on the subquery of an
INSERT statement
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
TO_MULTI_BYTE ( char )
TO_NCHAR (datetime)
Functions 5-227
TO_NCHAR (character)
Syntax
to_nchar_char::=
Purpose
TO_NCHAR (character) converts a character string, CHAR, VARCHAR2, CLOB, or NCLOB
value to the national character set. The value returned is always NVARCHAR2. This
function is equivalent to the TRANSLATE ... USING function with a USING clause in the
national character set.
Examples
The following example converts VARCHAR2 data from the oe.customers table to the
national character set:
SELECT TO_NCHAR(cust_last_name) FROM customers
WHERE customer_id=103;
TO_NCHAR(CUST_LAST_NAME)
--------------------------------------------------
Taylor
TO_NCHAR (datetime)
Syntax
to_nchar_date::=
Purpose
TO_NCHAR (datetime) converts a datetime or interval value of DATE, TIMESTAMP,
TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL
MONTH TO YEAR, or INTERVAL DAY TO SECOND data type from the database character
set to the national character set.
See Also: "Data Conversion" on page 3-40 and TRANSLATE ...
USING on page 5-234
See Also: "Security Considerations for Data Conversion" on
page 3-44
TO_NCHAR (
char
clob
nclob
)
TO_NCHAR (
datetime
interval
, fmt
, ’ nlsparam ’
)
TO_NCHAR (number)
5-228 Oracle Database SQL Language Reference
Examples
The following example converts the order_date of all orders whose status is 9 to the
national character set:
SELECT TO_NCHAR(ORDER_DATE) AS order_date
FROM ORDERS
WHERE ORDER_STATUS > 9
ORDER BY order_date;
ORDER_DATE
--------------------------------------------------------------------------
06-DEC-99 02.22.34.225609 PM
13-SEP-99 10.19.00.654279 AM
14-SEP-99 09.53.40.223345 AM
26-JUN-00 10.19.43.190089 PM
27-JUN-00 09.53.32.335522 PM
TO_NCHAR (number)
Syntax
to_nchar_number::=
Purpose
TO_NCHAR (number) converts n to a string in the national character set. The value n
can be of type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE. The function returns a
value of the same type as the argument. The optional fmt and 'nlsparam'
corresponding to n can be of DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE,
TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL MONTH TO YEAR, or INTERVAL DAY
TO SECOND data type.
Examples
The following example converts the customer_id values from the sample table
oe.orders to the national character set:
SELECT TO_NCHAR(customer_id) "NCHAR_Customer_ID" FROM orders
WHERE order_status > 9
ORDER BY "NCHAR_Customer_ID";
NCHAR_Customer_ID
----------------------------------------
102
103
148
148
149
See Also: "Security Considerations for Data Conversion" on
page 3-44
TO_NCHAR ( n
, fmt
, ’ nlsparam ’
)
TO_NUMBER
Functions 5-229
TO_NCLOB
Syntax
Purpose
TO_NCLOB converts CLOB values in a LOB column or other character strings to NCLOB
values. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB. Oracle Database implements this function by converting the
character set of char from the database character set to the national character set.
Examples
The following example inserts some character data into an NCLOB column of the
pm.print_media table by first converting the data with the TO_NCLOB function:
INSERT INTO print_media (product_id, ad_id, ad_fltextn)
VALUES (3502, 31001,
TO_NCLOB('Placeholder for new product description'));
TO_NUMBER
Syntax
Purpose
TO_NUMBER converts expr to a value of NUMBER data type. The expr can be a
BINARY_DOUBLE value or a value of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data
type containing a number in the format specified by the optional format model fmt.
You can specify an expr of BINARY_FLOAT. However, it makes no sense to do so
because a float can be interpreted only by its internal presentation.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following examples convert character string data into a number:
UPDATE employees SET salary = salary +
TO_NUMBER('100.00', '9G999D99')
WHERE last_name = 'Perkins';
The 'nlsparam' argument in this function has the same purpose as it does in the
TO_CHAR function for number conversions. Refer to TO_CHAR (number) on
page 5-221 for more information.
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
TO_NCLOB (
lob_column
char
)
TO_NUMBER ( expr
, fmt
, ’ nlsparam ’
)
TO_SINGLE_BYTE
5-230 Oracle Database SQL Language Reference
SELECT TO_NUMBER('-AusDollars100','L9G999D99',
' NLS_NUMERIC_CHARACTERS = '',.''
NLS_CURRENCY = ''AusDollars''
') "Amount"
FROM DUAL;
Amount
----------
-100
TO_SINGLE_BYTE
Syntax
Purpose
TO_SINGLE_BYTE returns char with all of its multibyte characters converted to their
corresponding single-byte characters. char can be of data type CHAR, VARCHAR2,
NCHAR, or NVARCHAR2. The value returned is in the same data type as char.
Any multibyte characters in char that have no single-byte equivalents appear in the
output as multibyte characters. This function is useful only if your database character
set contains both single-byte and multibyte characters.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example illustrates going from a multibyte A in UTF8 to a single byte
ASCII A:
SELECT TO_SINGLE_BYTE( CHR(15711393)) FROM DUAL;
T
-
A
TO_TIMESTAMP
Syntax
Purpose
TO_TIMESTAMP converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type
to a value of TIMESTAMP data type.
The optional fmt specifies the format of char. If you omit fmt, then char must be in
the default format of the TIMESTAMP data type, which is determined by the NLS_
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
TO_SINGLE_BYTE ( char )
TO_TIMESTAMP ( char
, fmt
, ’ nlsparam ’
)
TO_TIMESTAMP_TZ
Functions 5-231
TIMESTAMP_FORMAT initialization parameter. The optional 'nlsparam' argument
has the same purpose in this function as in the TO_CHAR function for date conversion.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example converts a character string to a timestamp. The character string
is not in the default TIMESTAMP format, so the format mask must be specified:
SELECT TO_TIMESTAMP ('10-Sep-02 14:10:10.123000', 'DD-Mon-RR HH24:MI:SS.FF')
FROM DUAL;
TO_TIMESTAMP('10-SEP-0214:10:10.123000','DD-MON-RRHH24:MI:SS.FF')
---------------------------------------------------------------------------
10-SEP-02 02.10.10.123000000 PM
TO_TIMESTAMP_TZ
Syntax
Purpose
TO_TIMESTAMP_TZ converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data
type to a value of TIMESTAMP WITH TIME ZONE data type.
The optional fmt specifies the format of char. If you omit fmt, then char must be in
the default format of the TIMESTAMP WITH TIME ZONE data type. The optional
'nlsparam' has the same purpose in this function as in the TO_CHAR function for
date conversion.
Examples
The following example converts a character string to a value of TIMESTAMP WITH
TIME ZONE:
SELECT TO_TIMESTAMP_TZ('1999-12-01 11:00:00 -8:00',
'YYYY-MM-DD HH:MI:SS TZH:TZM') FROM DUAL;
TO_TIMESTAMP_TZ('1999-12-0111:00:00-08:00','YYYY-MM-DDHH:MI:SSTZH:TZM')
--------------------------------------------------------------------
See Also: "Data Type Comparison Rules" on page 3-37 for more
information.
See Also: NLS_TIMESTAMP_FORMAT parameter for information on
the default TIMESTAMP format and "Datetime Format Models" on
page 3-59 for information on specifying the format mask
Note: This function does not convert character strings to TIMESTAMP
WITH LOCAL TIME ZONE. To do this, use a CAST function, as shown in
CAST on page 5-28.
TO_TIMESTAMP_TZ ( char
, fmt
, ’ nlsparam ’
)
TO_YMINTERVAL
5-232 Oracle Database SQL Language Reference
01-DEC-99 11.00.00.000000000 AM -08:00
The following example casts a null column in a UNION operation as TIMESTAMP WITH
LOCAL TIME ZONE using the sample tables oe.order_items and oe.orders:
SELECT order_id, line_item_id,
CAST(NULL AS TIMESTAMP WITH LOCAL TIME ZONE) order_date
FROM order_items
UNION
SELECT order_id, to_number(null), order_date
FROM orders;
ORDER_ID LINE_ITEM_ID ORDER_DATE
---------- ------------ -----------------------------------
2354 1
2354 2
2354 3
2354 4
2354 5
2354 6
2354 7
2354 8
2354 9
2354 10
2354 11
2354 12
2354 13
2354 14-JUL-00 05.18.23.234567 PM
2355 1
2355 2
...
TO_YMINTERVAL
Syntax
ym_iso_format::=
Purpose
TO_YMINTERVAL converts a character string of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type to an INTERVAL YEAR TO MONTH type.
TO_YMINTERVAL accepts argument in one of the two formats:
TO_YMINTERVAL ( ’
+
–
years – months
ym_iso_format
’ )
–
P
years Y months M days D
T
hours H minutes M seconds
. frac_secs
S
TRANSLATE
Functions 5-233
■ SQL interval format compatible with the SQL standard (ISO/IEC 9075:2003)
■ ISO duration format compatible with the ISO 8601:2004 standard
In the SQL format, years is an integer between 0 and 999999999, and months is an
integer between 0 and 11. Additional blanks are allowed between format elements.
In the ISO format, years and months are integers between 0 and 999999999. Days,
hours, minutes, seconds, and frac_secs are non-negative integers, and are ignored,
if specified. No blanks are allowed in the value.
Examples
The following example calculates for each employee in the sample hr.employees
table a date one year two months after the hire date:
SELECT hire_date, hire_date + TO_YMINTERVAL('01-02') "14 months"
FROM employees;
HIRE_DATE 14 months
--------- ---------
17-JUN-03 17-AUG-04
21-SEP-05 21-NOV-06
13-JAN-01 13-MAR-02
20-MAY-08 20-JUL-09
21-MAY-07 21-JUL-08
. . .
The following example makes the same calculation using the ISO format:
SELECT hire_date, hire_date + TO_YMINTERVAL('P1Y2M') FROM employees;
TRANSLATE
Syntax
Purpose
TRANSLATE returns expr with all occurrences of each character in from_string
replaced by its corresponding character in to_string. Characters in expr that are
not in from_string are not replaced. The argument from_string can contain more
characters than to_string. In this case, the extra characters at the end of from_
string have no corresponding characters in to_string. If these extra characters
appear in expr, then they are removed from the return value.
If a character appears multiple times in from_string, then the to_string mapping
corresponding to the first occurrence is used.
You cannot use an empty string for to_string to remove all characters in from_
string from the return value. Oracle Database interprets the empty string as null,
and if this function has a null argument, then it returns null. To remove all characters
in from_string, concatenate another character to the beginning of from_string
and specify this character as the to_string. For example, TRANSLATE(expr,
'x0123456789', 'x') removes all digits from expr.
TRANSLATE provides functionality related to that provided by the REPLACE function.
REPLACE lets you substitute a single string for another single string, as well as remove
TRANSLATE ( expr , from_string , to_string )
TRANSLATE ... USING
5-234 Oracle Database SQL Language Reference
character strings. TRANSLATE lets you make several single-character, one-to-one
substitutions in one operation.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following statement translates a book title into a string that could be used (for
example) as a filename. The from_string contains four characters: a space, asterisk,
slash, and apostrophe (with an extra apostrophe as the escape character). The to_
string contains only three underscores. This leaves the fourth character in the from_
string without a corresponding replacement, so apostrophes are dropped from the
returned value.
SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '___') FROM DUAL;
TRANSLATE('SQL*PLUSU
--------------------
SQL_Plus_Users_Guide
TRANSLATE ... USING
Syntax
Purpose
TRANSLATE ... USING converts char into the character set specified for conversions
between the database character set and the national character set.
The char argument is the expression to be converted.
■ Specifying the USING CHAR_CS argument converts char into the database
character set. The output data type is VARCHAR2.
■ Specifying the USING NCHAR_CS argument converts char into the national
character set. The output data type is NVARCHAR2.
This function is similar to the Oracle CONVERT function, but must be used instead of
CONVERT if either the input or the output data type is being used as NCHAR or
NVARCHAR2. If the input contains UCS2 code points or backslash characters (), then
use the UNISTR function.
See Also: "Data Type Comparison Rules" on page 3-37 for more
information and REPLACE on page 5-172
Note: The TRANSLATE ... USING function is supported primarily for
ANSI compatibility. Oracle recommends that you use the TO_CHAR
and TO_NCHAR functions, as appropriate, for converting data to the
database or national character set. TO_CHAR and TO_NCHAR can take
as arguments a greater variety of data types than TRANSLATE ...
USING, which accepts only character data.
See Also: CONVERT on page 5-41 and UNISTR on page 5-239
TRANSLATE ( char USING
CHAR_CS
NCHAR_CS
)
TREAT
Functions 5-235
Examples
The following statements use data from the sample table oe.product_
descriptions to show the use of the TRANSLATE ... USING function:
CREATE TABLE translate_tab (char_col VARCHAR2(100),
nchar_col NVARCHAR2(50));
INSERT INTO translate_tab
SELECT NULL, translated_name
FROM product_descriptions
WHERE product_id = 3501;
SELECT * FROM translate_tab;
CHAR_COL NCHAR_COL
-------------------- --------------------------------------------------
. . .
C pre SPNIX4.0 - Sys
C pro SPNIX4.0 - Sys
C til SPNIX4.0 - Sys
C voor SPNIX4.0 - Sys
. . .
UPDATE translate_tab
SET char_col = TRANSLATE (nchar_col USING CHAR_CS);
SELECT * FROM translate_tab;
CHAR_COL NCHAR_COL
------------------------- -------------------------
. . .
C per a SPNIX4.0 - Sys C per a SPNIX4.0 - Sys
C pro SPNIX4.0 - Sys C pro SPNIX4.0 - Sys
C for SPNIX4.0 - Sys C for SPNIX4.0 - Sys
C til SPNIX4.0 - Sys C til SPNIX4.0 - Sys
. . .
TREAT
Syntax
Purpose
TREAT changes the declared type of an expression.
You must have the EXECUTE object privilege on type to use this function.
■ type must be some supertype or subtype of the declared type of expr. If the most
specific type of expr is type (or some subtype of type), then TREAT returns
expr. If the most specific type of expr is not type (or some subtype of type),
then TREAT returns NULL.
■ You can specify REF only if the declared type of expr is a REF type.
■ If the declared type of expr is a REF to a source type of expr, then type must be
some subtype or supertype of the source type of expr. If the most specific type of
DEREF(expr) is type (or a subtype of type), then TREAT returns expr. If the
TREAT ( expr AS
REF schema .
type )
TRIM
5-236 Oracle Database SQL Language Reference
most specific type of DEREF(expr) is not type (or a subtype of type), then TREAT
returns NULL.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following statement uses the table oe.persons, which is created in
"Substitutable Table and Column Examples" on page 16-69. The example retrieves the
salary attribute of all people in the persons table, the value being null for instances of
people that are not employees.
SELECT name, TREAT(VALUE(p) AS employee_t).salary salary
FROM persons p;
NAME SALARY
------------------------- ----------
Bob
Joe 100000
Tim 1000
You can use the TREAT function to create an index on the subtype attributes of a
substitutable column. For an example, see "Indexing on Substitutable Columns:
Examples" on page 14-86.
TRIM
Syntax
Purpose
TRIM enables you to trim leading or trailing characters (or both) from a character
string. If trim_character or trim_source is a character literal, then you must
enclose it in single quotation marks.
■ If you specify LEADING, then Oracle Database removes any leading characters
equal to trim_character.
■ If you specify TRAILING, then Oracle removes any trailing characters equal to
trim_character.
■ If you specify BOTH or none of the three, then Oracle removes leading and trailing
characters equal to trim_character.
■ If you do not specify trim_character, then the default value is a blank space.
■ If you specify only trim_source, then Oracle removes leading and trailing blank
spaces.
See Also: "Data Type Comparison Rules" on page 3-37 for more
information
TRIM (
LEADING
TRAILING
BOTH
trim_character
trim_character
FROM
trim_source )
TRUNC (date)
Functions 5-237
■ The function returns a value with data type VARCHAR2. The maximum length of
the value is the length of trim_source.
■ If either trim_source or trim_character is null, then the TRIM function
returns null.
Both trim_character and trim_source can be VARCHAR2 or any data type that
can be implicitly converted to VARCHAR2. The string returned is a VARCHAR2
(NVARCHAR2) data type if trim_source is a CHAR or VARCHAR2 (NCHAR or
NVARCHAR2) data type, and a CLOB if trim_source is a CLOB data type. The return
string is in the same character set as trim_source.
Examples
This example trims leading zeros from the hire date of the employees in the hr
schema:
SELECT employee_id,
TO_CHAR(TRIM(LEADING 0 FROM hire_date))
FROM employees
WHERE department_id = 60
ORDER BY employee_id;
EMPLOYEE_ID TO_CHAR(T
----------- ---------
103 20-MAY-08
104 21-MAY-07
105 25-JUN-05
106 5-FEB-06
107 7-FEB-07
TRUNC (date)
Syntax
trunc_date::=
Purpose
The TRUNC (date) function returns date with the time portion of the day truncated to
the unit specified by the format model fmt. This function is not sensitive to the NLS_
CALENDAR session parameter. It operates according to the rules of the Gregorian
calendar. The value returned is always of data type DATE, even if you specify a
different datetime data type for date. If you omit fmt, then date is truncated to the
nearest day. Refer to "ROUND and TRUNC Date Functions" on page 5-270 for the
permitted format models to use in fmt.
Examples
The following example truncates a date:
SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR')
"New Year" FROM DUAL;
New Year
---------
TRUNC ( date
, fmt
)
TRUNC (number)
5-238 Oracle Database SQL Language Reference
01-JAN-92
TRUNC (number)
Syntax
trunc_number::=
Purpose
The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is
omitted, then n1 is truncated to 0 places. n2 can be negative to truncate (make zero)
n2 digits left of the decimal point.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. If you omit n2, then the
function returns the same data type as the numeric data type of the argument. If you
include n2, then the function returns NUMBER.
Examples
The following examples truncate numbers:
SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;
Truncate
----------
15.7
SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL;
Truncate
----------
10
TZ_OFFSET
Syntax
Purpose
TZ_OFFSET returns the time zone offset corresponding to the argument based on the
date the statement is executed. You can enter a valid time zone region name, a time
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
TRUNC ( n1
, n2
)
TZ_OFFSET (
’ time_zone_name ’
’
+
–
hh : mi ’
SESSIONTIMEZONE
DBTMEZONE
)
UNISTR
Functions 5-239
zone offset from UTC (which simply returns itself), or the keyword
SESSIONTIMEZONE or DBTIMEZONE. For a listing of valid values for time_zone_
name, query the TZNAME column of the V$TIMEZONE_NAMES dynamic performance
view.
Examples
The following example returns the time zone offset of the US/Eastern time zone from
UTC:
SELECT TZ_OFFSET('US/Eastern') FROM DUAL;
TZ_OFFS
-------
-04:00
UID
Syntax
Purpose
UID returns an integer that uniquely identifies the session user (the user who logged
on).
Examples
The following example returns the UID of the current user:
SELECT UID FROM DUAL;
UNISTR
Syntax
Purpose
UNISTR takes as its argument a text literal or an expression that resolves to character
data and returns it in the national character set. The national character set of the
database can be either AL16UTF16 or UTF8. UNISTR provides support for Unicode
string literals by letting you specify the Unicode encoding value of characters in the
string. This is useful, for example, for inserting data into NCHAR columns.
The Unicode encoding value has the form 'xxxx' where 'xxxx' is the hexadecimal
value of a character in UCS-2 encoding format. Supplementary characters are encoded
Note: Time zone region names are needed by the daylight saving
feature. These names are stored in two types of time zone files: one
large and one small. One of these files is the default file, depending
on your environment and the release of Oracle Database you are
using. For more information regarding time zone files and names,
see Oracle Database Globalization Support Guide.
UID
UNISTR ( string )
UPDATEXML
5-240 Oracle Database SQL Language Reference
as two code units, the first from the high-surrogates range (U+D800 to U+DBFF), and
the second from the low-surrogates range (U+DC00 to U+DFFF). To include the
backslash in the string itself, precede it with another backslash ().
For portability and data preservation, Oracle recommends that in the UNISTR string
argument you specify only ASCII characters and the Unicode encoding values.
Examples
The following example passes both ASCII characters and Unicode encoding values to
the UNISTR function, which returns the string in the national character set:
SELECT UNISTR('abc00e500f100f6') FROM DUAL;
UNISTR
------
abcåñö
UPDATEXML
Syntax
Purpose
UPDATEXML takes as arguments an XMLType instance and an XPath-value pair and
returns an XMLType instance with the updated value. If XPath_string is an XML
element, then the corresponding value_expr must be an XMLType instance. If
XPath_string is an attribute or text node, then the value_expr can be any scalar
data type. You can specify an absolute XPath_string with an initial slash or a
relative XPath_string by omitting the initial slash. If you omit the initial slash, then
the context of the relative path defaults to the root node.
The data types of the target of each XPath_string and its corresponding value_
expr must match. The optional namespace_string must resolve to a VARCHAR2
value that specifies a default mapping or namespace mapping for prefixes, which
Oracle Database uses when evaluating the XPath expression(s).
If you update an XML element to null, then Oracle removes the attributes and children
of the element, and the element becomes empty. If you update the text node of an
element to null, Oracle removes the text value of the element, and the element itself
remains but is empty.
In most cases, this function materializes an XML document in memory and updates
the value. However, UPDATEXML is optimized for UPDATE statements on
object-relational columns so that the function updates the value directly in the column.
This optimization requires the following conditions:
■ The XMLType_instance must be the same as the column in the UPDATE ... SET
clause.
■ The XPath_string must resolve to scalar content.
See Also: Oracle Database Globalization Support Guide for information
on Unicode and national character sets
UPDATEXML ( XMLType_instance , XPath_string , value_expr
,
, namespace_string
)
UPPER
Functions 5-241
Examples
The following example updates to 4 the number of docks in the San Francisco
warehouse in the sample schema OE, which has a warehouse_spec column of type
XMLType:
SELECT warehouse_name,
EXTRACT(warehouse_spec, '/Warehouse/Docks')
"Number of Docks"
FROM warehouses
WHERE warehouse_name = 'San Francisco';
WAREHOUSE_NAME Number of Docks
-------------------- --------------------
San Francisco <Docks>1</Docks>
UPDATE warehouses SET warehouse_spec =
UPDATEXML(warehouse_spec,
'/Warehouse/Docks/text()',4)
WHERE warehouse_name = 'San Francisco';
1 row updated.
SELECT warehouse_name,
EXTRACT(warehouse_spec, '/Warehouse/Docks')
"Number of Docks"
FROM warehouses
WHERE warehouse_name = 'San Francisco';
WAREHOUSE_NAME Number of Docks
-------------------- --------------------
San Francisco <Docks>4</Docks>
UPPER
Syntax
Purpose
UPPER returns char, with all letters uppercase. char can be any of the data types
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same
data type as char. The database sets the case of the characters based on the binary
mapping defined for the underlying character set. For linguistic-sensitive uppercase,
refer to NLS_UPPER on page 5-119.
Examples
The following example returns each employee's last name in uppercase:
SELECT UPPER(last_name) "Uppercase"
FROM employees;
UPPER ( char )
USER
5-242 Oracle Database SQL Language Reference
USER
Syntax
Purpose
USER returns the name of the session user (the user who logged on) with the data type
VARCHAR2. Oracle Database compares values of this function with blank-padded
comparison semantics.
In a distributed SQL statement, the UID and USER functions together identify the user
on your local database. You cannot use these functions in the condition of a CHECK
constraint.
Examples
The following example returns the current user and the user's UID:
SELECT USER, UID FROM DUAL;
USERENV
Syntax
Purpose
USERENV returns information about the current session. This information can be
useful for writing an application-specific audit trail table or for determining the
language-specific characters currently used by your session. You cannot use USERENV
in the condition of a CHECK constraint. Table 5–13 describes the values for the
parameter argument.
All calls to USERENV return VARCHAR2 data except for calls with the SESSIONID, SID,
and ENTRYID parameters, which return NUMBER.
Note: USERENV is a legacy function that is retained for backward
compatibility. Oracle recommends that you use the SYS_CONTEXT
function with the built-in USERENV namespace for current
functionality. See SYS_CONTEXT on page 5-202 for more information.
USER
USERENV ( ’ parameter ’ )
VALUE
Functions 5-243
Examples
The following example returns the LANGUAGE parameter of the current session:
SELECT USERENV('LANGUAGE') "Language" FROM DUAL;
Language
-----------------------------------
AMERICAN_AMERICA.WE8ISO8859P1
VALUE
Syntax
Table 5–13 Parameters of the USERENV Function
Parameter Return Value
CLIENT_INFO CLIENT_INFO returns up to 64 bytes of user session information that
can be stored by an application using the DBMS_APPLICATION_INFO
package.
Caution: Some commercial applications may be using this context
value. Refer to the applicable documentation for those applications to
determine what restrictions they may impose on use of this context
area.
See Also:
■ Oracle Database Security Guide for more information on application
context
■ CREATE CONTEXT on page 14-9 and SYS_CONTEXT on
page 5-202
ENTRYID The current audit entry number. The audit entryid sequence is shared
between fine-grained audit records and regular audit records. You
cannot use this attribute in distributed SQL statements.
ISDBA ISDBA returns 'TRUE' if the user has been authenticated as having
DBA privileges either through the operating system or through a
password file.
LANG LANG returns the ISO abbreviation for the language name, a shorter
form than the existing 'LANGUAGE' parameter.
LANGUAGE LANGUAGE returns the language and territory used by the current
session along with the database character set in this form:
language_territory.characterset
SESSIONID SESSIONID returns the auditing session identifier. You cannot specify
this parameter in distributed SQL statements.
SID SID returns the session ID.
TERMINAL TERMINAL returns the operating system identifier for the terminal of
the current session. In distributed SQL statements, this parameter
returns the identifier for your local session. In a distributed
environment, this parameter is supported only for remote SELECT
statements, not for remote INSERT, UPDATE, or DELETE operations.
VALUE ( correlation_variable )
VAR_POP
5-244 Oracle Database SQL Language Reference
Purpose
VALUE takes as its argument a correlation variable (table alias) associated with a row
of an object table and returns object instances stored in the object table. The type of the
object instances is the same type as the object table.
Examples
The following example uses the sample table oe.persons, which is created in
"Substitutable Table and Column Examples" on page 16-69:
SELECT VALUE(p) FROM persons p;
VALUE(P)(NAME, SSN)
-------------------------------------------------------------
PERSON_T('Bob', 1234)
EMPLOYEE_T('Joe', 32456, 12, 100000)
PART_TIME_EMP_T('Tim', 5678, 13, 1000, 20)
VAR_POP
Syntax
Purpose
VAR_POP returns the population variance of a set of numbers after discarding the nulls
in this set. You can use it as both an aggregate and analytic function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
If the function is applied to an empty set, then it returns null. The function makes the
following calculation:
(SUM(expr2
) - SUM(expr)2
/ COUNT(expr)) / COUNT(expr)
Aggregate Example
The following example returns the population variance of the salaries in the
employees table:
SELECT VAR_POP(salary) FROM employees;
See Also: "IS OF type Condition" on page 7-24 for information on
using IS OF type conditions with the VALUE function
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
VAR_POP ( expr )
OVER ( analytic_clause )
VAR_SAMP
Functions 5-245
VAR_POP(SALARY)
---------------
15140307.5
Analytic Example
The following example calculates the cumulative population and sample variances in
the sh.sales table of the monthly sales in 1998:
SELECT t.calendar_month_desc,
VAR_POP(SUM(s.amount_sold))
OVER (ORDER BY t.calendar_month_desc) "Var_Pop",
VAR_SAMP(SUM(s.amount_sold))
OVER (ORDER BY t.calendar_month_desc) "Var_Samp"
FROM sales s, times t
WHERE s.time_id = t.time_id AND t.calendar_year = 1998
GROUP BY t.calendar_month_desc
ORDER BY t.calendar_month_desc, "Var_Pop", "Var_Samp";
CALENDAR Var_Pop Var_Samp
-------- ---------- ----------
1998-01 0
1998-02 2269111326 4538222653
1998-03 5.5849E+10 8.3774E+10
1998-04 4.8252E+10 6.4336E+10
1998-05 6.0020E+10 7.5025E+10
1998-06 5.4091E+10 6.4909E+10
1998-07 4.7150E+10 5.5009E+10
1998-08 4.1345E+10 4.7252E+10
1998-09 3.9591E+10 4.4540E+10
1998-10 3.9995E+10 4.4439E+10
1998-11 3.6870E+10 4.0558E+10
1998-12 4.0216E+10 4.3872E+10
VAR_SAMP
Syntax
Purpose
VAR_SAMP returns the sample variance of a set of numbers after discarding the nulls in
this set. You can use it as both an aggregate and analytic function.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
If the function is applied to an empty set, then it returns null. The function makes the
following calculation:
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
VAR_SAMP ( expr )
OVER ( analytic_clause )
VARIANCE
5-246 Oracle Database SQL Language Reference
(SUM(expr2
) - SUM(expr)2
/ COUNT(expr)) / (COUNT(expr) - 1)
This function is similar to VARIANCE, except that given an input set of one element,
VARIANCE returns 0 and VAR_SAMP returns null.
Aggregate Example
The following example returns the sample variance of the salaries in the sample
employees table.
SELECT VAR_SAMP(salary) FROM employees;
VAR_SAMP(SALARY)
----------------
15283140.5
Analytic Example
Refer to the analytic example for VAR_POP on page 5-244.
VARIANCE
Syntax
Purpose
VARIANCE returns the variance of expr. You can use it as an aggregate or analytic
function.
Oracle Database calculates the variance of expr as follows:
■ 0 if the number of rows in expr = 1
■ VAR_SAMP if the number of rows in expr > 1
If you specify DISTINCT, then you can specify only the query_partition_clause
of the analytic_clause. The order_by_clause and windowing_clause are not
allowed.
This function takes as an argument any numeric data type or any nonnumeric data
type that can be implicitly converted to a numeric data type. The function returns the
same data type as the numeric data type of the argument.
See Also: "About SQL Expressions" on page 6-1 for information on
valid forms of expr and "Aggregate Functions" on page 5-9
See Also: "Analytic Functions" on page 5-11 for information on
syntax, semantics, and restrictions
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion, "About SQL
Expressions" on page 6-1 for information on valid forms of expr and
"Aggregate Functions" on page 5-9
VARIANCE (
DISTINCT
ALL
expr )
OVER ( analytic_clause )
VSIZE
Functions 5-247
Aggregate Example
The following example calculates the variance of all salaries in the sample employees
table:
SELECT VARIANCE(salary) "Variance"
FROM employees;
Variance
----------
15283140.5
Analytic Example
The following example returns the cumulative variance of salary values in Department
30 ordered by hire date.
SELECT last_name, salary, VARIANCE(salary)
OVER (ORDER BY hire_date) "Variance"
FROM employees
WHERE department_id = 30
ORDER BY last_name, salary, "Variance";
LAST_NAME SALARY Variance
------------------------- ---------- ----------
Baida 2900 16283333.3
Colmenares 2500 11307000
Himuro 2600 13317000
Khoo 3100 31205000
Raphaely 11000 0
Tobias 2800 21623333.3
VSIZE
Syntax
Purpose
VSIZE returns the number of bytes in the internal representation of expr. If expr is
null, then this function returns null.
This function does not support CLOB data directly. However, CLOBs can be passed in
as arguments through implicit data conversion.
Examples
The following example returns the number of bytes in the last_name column of the
employees in department 10:
SELECT last_name, VSIZE (last_name) "BYTES"
FROM employees
WHERE department_id = 10
ORDER BY employee_id;
LAST_NAME BYTES
--------------- ----------
See Also: "Data Type Comparison Rules" on page 3-37 for more
information
VSIZE ( expr )
WIDTH_BUCKET
5-248 Oracle Database SQL Language Reference
Whalen 6
WIDTH_BUCKET
Syntax
Purpose
WIDTH_BUCKET lets you construct equiwidth histograms, in which the histogram
range is divided into intervals that have identical size. (Compare this function with
NTILE, which creates equiheight histograms.) Ideally each bucket is a closed-open
interval of the real number line. For example, a bucket can be assigned to scores
between 10.00 and 19.999 ... to indicate that 10 is included in the interval and 20 is
excluded. This is sometimes denoted [10, 20).
For a given expression, WIDTH_BUCKET returns the bucket number into which the
value of this expression would fall after being evaluated.
■ expr is the expression for which the histogram is being created. This expression
must evaluate to a numeric or datetime value or to a value that can be implicitly
converted to a numeric or datetime value. If expr evaluates to null, then the
expression returns null.
■ min_value and max_value are expressions that resolve to the end points of the
acceptable range for expr. Both of these expressions must also evaluate to
numeric or datetime values, and neither can evaluate to null.
■ num_buckets is an expression that resolves to a constant indicating the number
of buckets. This expression must evaluate to a positive integer.
When needed, Oracle Database creates an underflow bucket numbered 0 and an
overflow bucket numbered num_buckets+1. These buckets handle values less than
min_value and more than max_value and are helpful in checking the
reasonableness of endpoints.
Examples
The following example creates a ten-bucket histogram on the credit_limit column
for customers in Switzerland in the sample table oe.customers and returns the
bucket number ("Credit Group") for each customer. Customers with credit limits
greater than the maximum value are assigned to the overflow bucket, 11:
SELECT customer_id, cust_last_name, credit_limit,
WIDTH_BUCKET(credit_limit, 100, 5000, 10) "Credit Group"
FROM customers WHERE nls_territory = 'SWITZERLAND'
ORDER BY "Credit Group", customer_id, cust_last_name, credit_limit;
CUSTOMER_ID CUST_LAST_NAME CREDIT_LIMIT Credit Group
----------- -------------------- ------------ ------------
825 Dreyfuss 500 1
826 Barkin 500 1
827 Siegel 500 1
853 Palin 400 1
843 Oates 700 2
See Also: Table 3–10, " Implicit Type Conversion Matrix" on
page 3-41 for more information on implicit conversion
WIDTH_BUCKET ( expr , min_value , max_value , num_buckets )
XMLAGG
Functions 5-249
844 Julius 700 2
835 Eastwood 1200 3
836 Berenger 1200 3
837 Stanton 1200 3
840 Elliott 1400 3
841 Boyer 1400 3
842 Stern 1400 3
848 Olmos 1800 4
849 Kaurusmdki 1800 4
828 Minnelli 2300 5
829 Hunter 2300 5
850 Finney 2300 5
851 Brown 2300 5
852 Tanner 2300 5
830 Dutt 3500 7
831 Bel Geddes 3500 7
832 Spacek 3500 7
833 Moranis 3500 7
834 Idle 3500 7
838 Nicholson 3500 7
839 Johnson 3500 7
845 Fawcett 5000 11
846 Brando 5000 11
847 Streep 5000 11
XMLAGG
Syntax
Purpose
XMLAgg is an aggregate function. It takes a collection of XML fragments and returns an
aggregated XML document. Any arguments that return null are dropped from the
result.
XMLAgg is similar to SYS_XMLAgg except that XMLAgg returns a collection of nodes
but it does not accept formatting using the XMLFormat object. Also, XMLAgg does not
enclose the output in an element tag as does SYS_XMLAgg.
Within the order_by_clause, Oracle Database does not interpret number literals as
column positions, as it does in other uses of this clause, but simply as number literals.
Examples
The following example produces a Department element containing Employee
elements with employee job ID and last name as the contents of the elements:
SELECT XMLELEMENT("Department",
XMLAGG(XMLELEMENT("Employee",
e.job_id||' '||e.last_name)
ORDER BY last_name))
as "Dept_list"
FROM employees e
WHERE e.department_id = 30;
See Also: XMLELEMENT on page 5-255 and SYS_XMLAGG on
page 5-211
XMLAGG ( XMLType_instance
order_by_clause
)
XMLCAST
5-250 Oracle Database SQL Language Reference
Dept_list
-------------------------------------------------------------
<Department>
<Employee>PU_CLERK Baida</Employee>
<Employee>PU_CLERK Colmenares</Employee>
<Employee>PU_CLERK Himuro</Employee>
<Employee>PU_CLERK Khoo</Employee>
<Employee>PU_MAN Raphaely</Employee>
<Employee>PU_CLERK Tobias</Employee>
</Department>
The result is a single row, because XMLAgg aggregates the rows. You can use the
GROUP BY clause to group the returned set of rows into multiple groups:
SELECT XMLELEMENT("Department",
XMLAGG(XMLELEMENT("Employee", e.job_id||' '||e.last_name)))
AS "Dept_list"
FROM employees e
GROUP BY e.department_id;
Dept_list
---------------------------------------------------------
<Department>
<Employee>AD_ASST Whalen</Employee>
</Department>
<Department>
<Employee>MK_MAN Hartstein</Employee>
<Employee>MK_REP Fay</Employee>
</Department>
<Department>
<Employee>PU_MAN Raphaely</Employee>
<Employee>PU_CLERK Khoo</Employee>
<Employee>PU_CLERK Tobias</Employee>
<Employee>PU_CLERK Baida</Employee>
<Employee>PU_CLERK Colmenares</Employee>
<Employee>PU_CLERK Himuro</Employee>
</Department>
. . .
XMLCAST
Syntax
Purpose
XMLCast casts value_expression to the scalar SQL data type specified by data
type. The value_expression argument is a SQL expression that is evaluated. The
data type argument can be of data type NUMBER, VARCHAR2, and any of the
datetime data types.
See Also: Oracle XML DB Developer's Guide for more information on
uses for this function and examples
XMLCAST ( value_expression AS datatype )
XMLCDATA
Functions 5-251
XMLCDATA
Syntax
Purpose
XMLCData generates a CDATA section by evaluating value_expr. The value_expr
must resolve to a string. The value returned by the function takes the following form:
<![CDATA[string]]>
If the resulting value is not a valid XML CDATA section, then the function returns an
error.
The following conditions apply to XMLCData:
■ The value_expr cannot contain the substring ]]>.
■ If value_expr evaluates to null, then the function returns null.
Examples
The following statement uses the DUAL table to illustrate the syntax of XMLCData:
SELECT XMLELEMENT("PurchaseOrder",
XMLAttributes(dummy as "pono"),
XMLCdata('<!DOCTYPE po_dom_group [
<!ELEMENT po_dom_group(student_name)*>
<!ELEMENT po_purch_name (#PCDATA)>
<!ATTLIST po_name po_no ID #REQUIRED>
<!ATTLIST po_name trust_1 IDREF #IMPLIED>
<!ATTLIST po_name trust_2 IDREF #IMPLIED>
]>')) "XMLCData" FROM DUAL;
XMLCData
----------------------------------------------------------
<PurchaseOrder pono="X"><![CDATA[
<!DOCTYPE po_dom_group [
<!ELEMENT po_dom_group(student_name)*>
<!ELEMENT po_purch_name (#PCDATA)>
<!ATTLIST po_name po_no ID #REQUIRED>
<!ATTLIST po_name trust_1 IDREF #IMPLIED>
<!ATTLIST po_name trust_2 IDREF #IMPLIED>
]>
]]>
</PurchaseOrder>
See Also: Oracle XML DB Developer's Guide for more information on
this function
XMLCDATA ( value_expr )
XMLCOLATTVAL
5-252 Oracle Database SQL Language Reference
XMLCOLATTVAL
Syntax
Purpose
XMLColAttVal creates an XML fragment and then expands the resulting XML so that
each XML fragment has the name column with the attribute name.
You can use the AS clause to change the value of the name attribute to something other
than the column name. You can do this by specifying c_alias, which is a string
literal, or by specifying EVALNAME value_expr. In the latter case, the value
expression is evaluated and the result, which must be a string literal, is used as the
alias. The alias can be up to 4000 characters.
You must specify a value for value_expr. If value_expr is null, then no element is
returned.
Restriction on XMLColAttVal You cannot specify an object type column for value_
expr.
Examples
The following example creates an Emp element for a subset of employees, with nested
employee_id, last_name, and salary elements as the contents of Emp. Each
nested element is named column and has a name attribute with the column name as
the attribute value:
SELECT XMLELEMENT("Emp",
XMLCOLATTVAL(e.employee_id, e.last_name, e.salary)) "Emp Element"
FROM employees e
WHERE employee_id = 204;
Emp Element
--------------------------------------------------------------------
<Emp>
<column name="EMPLOYEE_ID">204</column>
<column name="LAST_NAME">Baer</column>
<column name="SALARY">10000</column>
</Emp>
Refer to the example for XMLFOREST on page 5-258 to compare the output of these
two functions.
XMLCOMMENT
Syntax
XMLCOLATTVAL ( value_expr
AS
c_alias
EVALNAME value_expr
,
)
XMLCOMMENT ( value_expr )
XMLCONCAT
Functions 5-253
Purpose
XMLComment generates an XML comment using an evaluated result of value_expr.
The value_expr must resolve to a string. It cannot contain two consecutive dashes
(hyphens). The value returned by the function takes the following form:
<!--string-->
If value_expr resolves to null, then the function returns null.
Examples
The following example uses the DUAL table to illustrate the XMLComment syntax:
SELECT XMLCOMMENT('OrderAnalysisComp imported, reconfigured, disassembled')
AS "XMLCOMMENT" FROM DUAL;
XMLCOMMENT
--------------------------------------------------------------------------------
<!--OrderAnalysisComp imported, reconfigured, disassembled-->
XMLCONCAT
Syntax
Purpose
XMLConcat takes as input a series of XMLType instances, concatenates the series of
elements for each row, and returns the concatenated series. XMLConcat is the inverse
of XMLSequence.
Null expressions are dropped from the result. If all the value expressions are null, then
the function returns null.
Examples
The following example creates XML elements for the first and last names of a subset of
employees, and then concatenates and returns those elements:
SELECT XMLCONCAT(XMLELEMENT("First", e.first_name),
XMLELEMENT("Last", e.last_name)) AS "Result"
FROM employees e
WHERE e.employee_id > 202;
Result
----------------------------------------------------------------
<First>Susan</First>
<Last>Mavris</Last>
<First>Hermann</First>
<Last>Baer</Last>
See Also: Oracle XML DB Developer's Guide for more information on
this function
See Also: XMLSEQUENCE on page 5-264
XMLCONCAT ( XMLType_instance
,
)
XMLDIFF
5-254 Oracle Database SQL Language Reference
<First>Shelley</First>
<Last>Higgins</Last>
<First>William</First>
<Last>Gietz</Last>
4 rows selected.
XMLDIFF
Syntax
Purpose
The XMLDiff function is the SQL interface for the XmlDiff C API. This function
compares two XML documents and captures the differences in XML conforming to an
Xdiff schema. The diff document is returned as an XMLType document.
■ For the first two arguments, specify the names of two XMLType documents.
■ For the integer, specify a number representing the hashLevel for a C function
XmlDiff. If you do not want hashing, set this argument to 0 or omit it entirely. If
you do not want hashing, but you want to specify flags, then you must set this
argument to 0.
■ For string, specify the flags that control the behavior of the function. These flags
are specified by one or more names separated by semicolon. The names are the
same as the names of constants for XmlDiff function.
Examples
The following example compares two XML documents and returns the difference as
an XMLType document:
SELECT XMLDIFF(
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://example.com">
<bk:tr>
<bk:td>
<bk:chapter>
Chapter 1.
</bk:chapter>
</bk:td>
<bk:td>
<bk:chapter>
Chapter 2.
</bk:chapter>
</bk:td>
</bk:tr>
</bk:book>'),
See Also: Oracle XML Developer's Kit Programmer's Guide for more
information on using this function, including examples, and Oracle
Database XML C API Reference for information on the XML APIs for C
XMLDiff
( XMLType_document , XMLType_document
, integer , string
)
XMLELEMENT
Functions 5-255
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://example.com">
<bk:tr>
<bk:td>
<bk:chapter>
Chapter 1.
</bk:chapter>
</bk:td>
<bk:td/>
</bk:tr>
</bk:book>')
)
FROM DUAL;
XMLELEMENT
Syntax
XML_attributes_clause::=
Purpose
XMLElement takes an element name for identifier or evaluates an element name
for EVALNAME value_expr, an optional collection of attributes for the element, and
arguments that make up the content of the element. It returns an instance of type
XMLType. XMLElement is similar to SYS_XMLGen except that XMLElement can
include attributes in the XML returned, but it does not accept formatting using the
XMLFormat object.
The XMLElement function is typically nested to produce an XML document with a
nested structure, as in the example in the following section.
XMLELEMENT (
ENTITYESCAPING
NOENTITYESCAPING
NAME
identifier
EVALNAME value_expr
, XML_attributes_clause , value_expr
AS c_alias
)
XMLATTRIBUTES
(
ENTITYESCAPING
NOENTITYESCAPING
SCHEMACHECK
NOSCHEMACHECK
value_expr
AS
c_alias
EVALNAME value_expr
,
)
XMLELEMENT
5-256 Oracle Database SQL Language Reference
For an explanation of the ENTITYESCAPING and NONENTITYESCAPING keywords,
please refer to Oracle XML DB Developer's Guide.
You must specify a value for Oracle Database to use an the enclosing tag. You can do
this by specifying identifier, which is a string literal, or by specifying EVALNAME
value_expr. In the latter case, the value expression is evaluated and the result, which
must be a string literal, is used as the identifier. The identifier can be up to 4000
characters and does not have to be a column name or column reference. It cannot be an
expression or null.
The objects that make up the element content follow the XMLATTRIBUTES keyword. In
the XML_attributes_clause, if the value_expr is null, then no attribute is
created for that value expression. The type of value_expr cannot be an object type or
collection. If you specify an alias for value_expr using the AS clause, then the c_
alias or the evaluated value expression (EVALNAME value_expr) can be up to 4000
characters.
For the optional value_expr that follows the XML_attributes_clause in the
diagram:
■ If value_expr is a scalar expression, then you can omit the AS clause, and Oracle
uses the column name as the element name.
■ If value_expr is an object type or collection, then the AS clause is mandatory,
and Oracle uses the specified c_alias as the enclosing tag.
■ If value_expr is null, then no element is created for that value expression.
Examples
The following example produces an Emp element for a series of employees, with
nested elements that provide the employee's name and hire date:
SELECT XMLELEMENT("Emp", XMLELEMENT("Name",
e.job_id||' '||e.last_name),
XMLELEMENT("Hiredate", e.hire_date)) as "Result"
FROM employees e WHERE employee_id > 200;
Result
-------------------------------------------------------------------
<Emp>
<Name>MK_MAN Hartstein</Name>
<Hiredate>2004-02-17</Hiredate>
</Emp>
<Emp>
<Name>MK_REP Fay</Name>
<Hiredate>2005-08-17</Hiredate>
</Emp>
<Emp>
<Name>HR_REP Mavris</Name>
<Hiredate>2002-06-07</Hiredate>
</Emp>
<Emp>
<Name>PR_REP Baer</Name>
<Hiredate>2002-06-07</Hiredate>
</Emp>
See Also: SYS_XMLGEN on page 5-211
XMLEXISTS
Functions 5-257
<Emp>
<Name>AC_MGR Higgins</Name>
<Hiredate>2002-06-07</Hiredate>
</Emp>
<Emp>
<Name>AC_ACCOUNT Gietz</Name>
<Hiredate>2002-06-07</Hiredate>
</Emp>
6 rows selected.
The following similar example uses the XMLElement function with the XML_
attributes_clause to create nested XML elements with attribute values for the
top-level element:
SELECT XMLELEMENT("Emp",
XMLATTRIBUTES(e.employee_id AS "ID", e.last_name),
XMLELEMENT("Dept", e.department_id),
XMLELEMENT("Salary", e.salary)) AS "Emp Element"
FROM employees e
WHERE e.employee_id = 206;
Emp Element
---------------------------------------------------------------
<Emp ID="206" LAST_NAME="Gietz">
<Dept>110</Dept>
<Salary>8300</Salary>
</Emp>
Notice that the AS identifier clause was not specified for the last_name column.
As a result, the XML returned uses the column name last_name as the default.
Finally, the next example uses a subquery within the XML_attributes_clause to
retrieve information from another table into the attributes of an element:
SELECT XMLELEMENT("Emp", XMLATTRIBUTES(e.employee_id, e.last_name),
XMLELEMENT("Dept", XMLATTRIBUTES(e.department_id,
(SELECT d.department_name FROM departments d
WHERE d.department_id = e.department_id) as "Dept_name")),
XMLELEMENT("salary", e.salary),
XMLELEMENT("Hiredate", e.hire_date)) AS "Emp Element"
FROM employees e
WHERE employee_id = 205;
Emp Element
-------------------------------------------------------------------
<Emp EMPLOYEE_ID="205" LAST_NAME="Higgins">
<Dept DEPARTMENT_ID="110" Dept_name="Accounting"/>
<salary>12008</salary>
<Hiredate>2002-06-07</Hiredate>
</Emp>
XMLEXISTS
Syntax
XMLEXISTS ( XQuery_string
XML_passing_clause
)
XMLFOREST
5-258 Oracle Database SQL Language Reference
XML_passing_clause::=
Purpose
XMLExists checks whether a given XQuery expression returns a nonempty XQuery
sequence. If so, the function returns TRUE; otherwise, it returns FALSE. The argument
XQuery_string is a literal string, but it can contain XQuery variables that you bind
using the XML_passing_clause.
The expr in the XML_passing_clause is an expression returning an XMLType or an
instance of a SQL scalar data type that is used as the context for evaluating the XQuery
expression. You can specify only one expr in the PASSING clause without an
identifier. The result of evaluating each expr is bound to the corresponding identifier
in the XQuery_string. If any expr that is not followed by an AS clause, then the
result of evaluating that expression is used as the context item for evaluating the
XQuery_string.
XMLFOREST
Syntax
Purpose
XMLForest converts each of its argument parameters to XML, and then returns an
XML fragment that is the concatenation of these converted arguments.
■ If value_expr is a scalar expression, then you can omit the AS clause, and Oracle
Database uses the column name as the element name.
■ If value_expr is an object type or collection, then the AS clause is mandatory,
and Oracle uses the specified expression as the enclosing tag.
You can do this by specifying c_alias, which is a string literal, or by specifying
EVALNAME value_expr. In the latter case, the value expression is evaluated and
the result, which must be a string literal, is used as the identifier. The identifier can
be up to 4000 characters and does not have to be a column name or column
reference. It cannot be an expression or null.
■ If value_expr is null, then no element is created for that value_expr.
Examples
The following example creates an Emp element for a subset of employees, with nested
employee_id, last_name, and salary elements as the contents of Emp:
See Also: Oracle XML DB Developer's Guide for more information on
uses for this function and examples
PASSING
BY VALUE
expr
AS identifier
,
XMLFOREST ( value_expr
AS
c_alias
EVALNAME value_expr
,
)
XMLPARSE
Functions 5-259
SELECT XMLELEMENT("Emp",
XMLFOREST(e.employee_id, e.last_name, e.salary))
"Emp Element"
FROM employees e WHERE employee_id = 204;
Emp Element
----------------------------------------------------------------
<Emp>
<EMPLOYEE_ID>204</EMPLOYEE_ID>
<LAST_NAME>Baer</LAST_NAME>
<SALARY>10000</SALARY>
</Emp>
Refer to the example for XMLCOLATTVAL on page 5-252 to compare the output of
these two functions.
XMLISVALID
Syntax
Purpose
XMLISVALID checks whether the input XMLType_instance conforms to the relevant
XML schema. It does not change the validation status recorded for XMLType_
instance.
If the input XML document is determined to be valid, then XMLISVALID returns 1;
otherwise, it returns 0. If you provide XMLSchema_URL as an argument, then that is
used to check conformance. Otherwise, the XML schema specified by the XML
document is used to check conformance.
■ XMLType_instance is the XMLType instance to be validated.
■ XMLSchema_URL is the URL of the XML schema against which to check
conformance.
■ element is the element of the specified schema against which to check
conformance. Use this if you have an XML schema that defines more than one top
level element, and you want to check conformance against a specific one of those
elements.
XMLPARSE
Syntax
See Also: Oracle XML DB Developer's Guide for information on the
use of this function, including examples
XMLISVALID ( XMLType_instance
, XMLSchema_URL
, element
)
XMLPARSE (
DOCUMENT
CONTENT
value_expr
WELLFORMED
)
XMLPATCH
5-260 Oracle Database SQL Language Reference
Purpose
XMLParse parses and generates an XML instance from the evaluated result of value_
expr. The value_expr must resolve to a string. If value_expr resolves to null, then
the function returns null.
■ If you specify DOCUMENT, then value_expr must resolve to a singly rooted XML
document.
■ If you specify CONTENT, then value_expr must resolve to a valid XML value.
■ When you specify WELLFORMED, you are guaranteeing that value_expr resolves
to a well-formed XML document, so the database does not perform validity checks
to ensure that the input is well formed.
Examples
The following example uses the DUAL table to illustrate the syntax of XMLParse:
SELECT XMLPARSE(CONTENT '124 <purchaseOrder poNo="12435">
<customerName> Acme Enterprises</customerName>
<itemNo>32987457</itemNo>
</purchaseOrder>'
WELLFORMED) AS PO FROM DUAL;
PO
-----------------------------------------------------------------
124 <purchaseOrder poNo="12435">
<customerName> Acme Enterprises</customerName>
<itemNo>32987457</itemNo>
</purchaseOrder>
XMLPATCH
Syntax
Purpose
The XMLPatch function is the SQL interface for the XmlPatch C API. This function
patches an XML document with the changes specified. A patched XMLType document
is returned.
■ For the first argument, specify the name of the input XMLType document
For the second argument, specify the XMLType document containing the changes
to be applied to the first document. The changes should conform to the Xdiff
XML schema
■ For string, specify the flags that control the behavior of the function. These flags
are specified by one or more names separated by semicolon. The names are the
same as the names of constants for XmlPatch C function.
See Also: Oracle XML DB Developer's Guide for more information on
this function
See Also: Oracle XML Developer's Kit Programmer's Guide for more
information on using this function, including examples, and Oracle
Database XML C API Reference for information on the XML APIs for C
XMLPatch ( XMLType_document , XMLType_document )
XMLPI
Functions 5-261
Example
The following example patches an XMLType document with the changes specified in
another XMLType and returns a patched XMLType document:
SELECT XMLPATCH(
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://example.com">
<bk:tr>
<bk:td>
<bk:chapter>
Chapter 1.
</bk:chapter>
</bk:td>
<bk:td>
<bk:chapter>
Chapter 2.
</bk:chapter>
</bk:td>
</bk:tr>
</bk:book>'),
XMLTYPE('<?xml version="1.0"?>
<xd:xdiff xsi:schemaLocation="http://xmlns.example.com/xdb/xdiff.xsd
http://xmlns.example.com/xdb/xdiff.xsd"
xmlns:xd="http://xmlns.example.com/xdb/xdiff.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:bk="http://example.com">
<?oracle-xmldiff operations-in-docorder="true" output-model="snapshot"
diff-algorithm="global"?>
<xd:delete-node xd:node-type="element"
xd:xpath="/bk:book[1]/bk:tr[1]/bk:td[2]/bk:chapter[1]"/>
</xd:xdiff>')
)
FROM DUAL;
XMLPI
Syntax
Purpose
XMLPI generates an XML processing instruction using identifier and optionally
the evaluated result of value_expr. A processing instruction is commonly used to
provide to an application information that is associated with all or part of an XML
document. The application uses the processing instruction to determine how best to
process the XML document.
You must specify a value for Oracle Database to use an the enclosing tag. You can do
this by specifying identifier, which is a string literal, or by specifying EVALNAME
value_expr. In the latter case, the value expression is evaluated and the result, which
must be a string literal, is used as the identifier. The identifier can be up to 4000
characters and does not have to be a column name or column reference. It cannot be an
expression or null.
XMLPI (
NAME
identifier
EVALNAME value_expr
, value_expr
)
XMLQUERY
5-262 Oracle Database SQL Language Reference
The optional value_expr must resolve to a string. If you omit the optional value_
expr, then a zero-length string is the default. The value returned by the function takes
this form:
<?identifier string?>
XMLPI is subject to the following restrictions:
■ The identifier must be a valid target for a processing instruction.
■ You cannot specify xml in any case combination for identifier.
■ The identifier cannot contain the consecutive characters ?>.
Examples
The following statement uses the DUAL table to illustrate the use of the XMLPI syntax:
SELECT XMLPI(NAME "Order analysisComp", 'imported, reconfigured, disassembled')
AS "XMLPI" FROM DUAL;
XMLPI
--------------------------------------------------------------------------------
<?Order analysisComp imported, reconfigured, disassembled?>
XMLQUERY
Syntax
XML_passing_clause::=
Purpose
XMLQUERY lets you query XML data in SQL statements. It takes an XQuery expression
as a string literal, an optional context item, and other bind variables and returns the
result of evaluating the XQuery expression using these input values.
■ XQuery_string is a complete XQuery expression, including prolog.
■ The expr in the XML_passing_clause is an expression returning an XMLType
or an instance of a SQL scalar data type that is used as the context for evaluating
the XQuery expression. You can specify only one expr in the PASSING clause
without an identifier. The result of evaluating each expr is bound to the
corresponding identifier in the XQuery_string. If any expr that is not followed
by an AS clause, then the result of evaluating that expression is used as the context
item for evaluating the XQuery_string.
See Also: Oracle XML DB Developer's Guide for more information on
this function
XMLQUERY
( XQuery_string
XML_passing_clause
RETURNING CONTENT
NULL ON EMPTY
)
PASSING
BY VALUE
expr
AS identifier
,
XMLROOT
Functions 5-263
■ RETURNING CONTENT indicates that the result from the XQuery evaluation is
either an XML 1.0 document or a document fragment conforming to the XML 1.0
semantics.
■ If the result set is empty, then the function returns the SQL NULL value. The NULL
ON EMPTY keywords are implemented by default and are shown for syntactic
clarity.
Examples
The following statement specifies the warehouse_spec column of the
oe.warehouses table in the XML_passing_clause as a context item. The statement
returns specific information about the warehouses with area greater than 50K.
SELECT warehouse_name,
EXTRACTVALUE(warehouse_spec, '/Warehouse/Area'),
XMLQuery(
'for $i in /Warehouse
where $i/Area > 50000
return <Details>
<Docks num="{$i/Docks}"/>
<Rail>
{
if ($i/RailAccess = "Y") then "true" else "false"
}
</Rail>
</Details>' PASSING warehouse_spec RETURNING CONTENT) "Big_warehouses"
FROM warehouses;
WAREHOUSE_ID Area Big_warehouses
------------ --------- --------------------------------------------------------
1 25000
2 50000
3 85700 <Details><Docks></Docks><Rail>false</Rail></Details>
4 103000 <Details><Docks num="3"></Docks><Rail>true</Rail></Details>
. . .
XMLROOT
Syntax
Purpose
XMLROOT lets you create a new XML value by providing version and standalone
properties in the XML root information (prolog) of an existing XML value. If the
value_expr already has a prolog, then the database returns an error. If the input is
null, then the function returns null.
The value returned takes the following form:
See Also: Oracle XML DB Developer's Guide for more information on
this function
XMLROOT ( value_expr , VERSION
value_expr
NO VALUE
, STANDALONE
YES
NO
NO VALUE
)
XMLSEQUENCE
5-264 Oracle Database SQL Language Reference
<?xml version = "version" [ STANDALONE = "{yes | no}" ]?>
■ The first value_expr specifies the XML value for which you are providing
prolog information.
■ In the VERSION clause, value_expr must resolve to a string representing a valid
XML version. If you specify NO VALUE for VERSION, then the version defaults to
1.0.
■ If you omit the optional STANDALONE clause, or if you specify it with NO VALUE,
then the standalone property is absent from the value returned by the function.
Examples
The following statement uses the DUAL table to illustrate the syntax of XMLROOT:
SELECT XMLROOT ( XMLType('<poid>143598</poid>'), VERSION '1.0', STANDALONE YES)
AS "XMLROOT" FROM DUAL;
XMLROOT
--------------------------------------------------------------------------------
<?xml version="1.0" standalone="yes"?>
<poid>143598</poid>
XMLSEQUENCE
Syntax
Purpose
XMLSequence has two forms:
■ The first form takes as input an XMLType instance and returns a varray of the
top-level nodes in the XMLType. This form is effectively superseded by the
SQL/XML standard function XMLTable, which provides for more readable SQL
code. Prior to Oracle Database 10g Release 2, XMLSequence was used with SQL
function TABLE to do some of what can now be done better with the XMLTable
function.
■ The second form takes as input a REFCURSOR instance, with an optional instance
of the XMLFormat object, and returns as an XMLSequence type an XML
document for each row of the cursor.
Because XMLSequence returns a collection of XMLType, you can use this function in a
TABLE clause to unnest the collection values into multiple rows, which can in turn be
further processed in the SQL query.
Note: The XMLSEQUENCE function is deprecated. It is still supported
for backward compatibility. However, Oracle recommends that you
use the XMLTABLE function instead. See XMLTABLE on page 5-267 for
more information.
XMLSEQUENCE (
XMLType_instance
sys_refcursor_instance
, fmt )
XMLSEQUENCE
Functions 5-265
Examples
The following example shows how XMLSequence divides up an XML document with
multiple elements into VARRAY single-element documents. In this example, the TABLE
keyword instructs Oracle Database to consider the collection a table value that can be
used in the FROM clause of the subquery:
SELECT EXTRACT(warehouse_spec, '/Warehouse') as "Warehouse"
FROM warehouses WHERE warehouse_name = 'San Francisco';
Warehouse
------------------------------------------------------------
<Warehouse>
<Building>Rented</Building>
<Area>50000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>Y</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Lot</Parking>
<VClearance>12 ft</VClearance>
</Warehouse>
1 row selected.
SELECT VALUE(p)
FROM warehouses w,
TABLE(XMLSEQUENCE(EXTRACT(warehouse_spec, '/Warehouse/*'))) p
WHERE w.warehouse_name = 'San Francisco';
VALUE(P)
----------------------------------------------------------------
<Building>Rented</Building>
<Area>50000</Area>
<Docks>1</Docks>
<DockType>Side load</DockType>
<WaterAccess>Y</WaterAccess>
<RailAccess>N</RailAccess>
<Parking>Lot</Parking>
<VClearance>12 ft</VClearance>
8 rows selected.
See Also: Oracle XML DB Developer's Guide for more information on
this function, and XMLTABLE on page 5-267
XMLSERIALIZE
5-266 Oracle Database SQL Language Reference
XMLSERIALIZE
Syntax
Purpose
XMLSerialize creates a string or LOB containing the contents of value_expr.
■ If you specify DOCUMENT, then the value_expr must be a valid XML document.
■ If you specify CONTENT, then the value_expr need not be a singly rooted XML
document. However it must be valid XML content.
■ The datatype specified can be a string type (VARCHAR2 or VARCHAR, but not
NVARCHAR or NVARCHAR2), BLOB, or CLOB . The default is CLOB.
■ If datatype is BLOB, then you can specify the ENCODING clause to use the
specified encoding in the prolog.
■ Specify the VERSION clause to use the version you provide as string_literal
in the XML declaration (<?xml version="..." ...?>).
■ Specify NO INDENT to strip all insignificant whitespace from the output. Specify
INDENT SIZE = N, where N is a whole number, for output that is pretty-printed
using a relative indentation of N spaces. If N is 0, then pretty-printing inserts a
newline character after each element, placing each element on a line by itself, but
omitting all other insignificant whitespace in the output. If INDENT is present
without a SIZE specification, then 2-space indenting is used. If you omit this
clause, then the behavior (pretty-printing or not) is indeterminate.
■ HIDE DEFAULTS and SHOW DEFAULTS apply only to XML schema-based data. If
you specify SHOW DEFAULTS and the input data is missing any optional elements
or attributes for which the XML schema defines default values, then those
elements or attributes are included in the output with their default values. If you
specify HIDE DEFAULTS, then no such elements or attributes are included in the
output. HIDE DEFAULTS is the default behavior.
Examples
The following statement uses the DUAL table to illustrate the syntax of
XMLSerialize:
SELECT XMLSERIALIZE(CONTENT XMLTYPE('<Owner>Grandco</Owner>'))
See Also: Oracle XML DB Developer's Guide for more information on
this function
XMLSERIALIZE (
DOCUMENT
CONTENT
value_expr
AS datatype
ENCODING xml_encoding_spec VERSION string_literal
NO INDENT
INDENT
SIZE = number
HIDE
SHOW
DEFAULTS
)
XMLTABLE
Functions 5-267
FROM DUAL;
XMLTABLE
Syntax
XMLnamespaces_clause::=
XMLTABLE_options::=
XML_passing_clause::=
XML_table_column::=
Purpose
XMLTable maps the result of an XQuery evaluation into relational rows and columns.
You can query the result returned by the function as a virtual relational table using
SQL.
■ The XMLNAMESPACES clause contains a set of XML namespace declarations. These
declarations are referenced by the XQuery expression (the evaluated XQuery_
string), which computes the row, and by the XPath expression in the PATH
clause of XML_table_column, which computes the columns for the entire
XMLTable function. If you want to use qualified names in the PATH expressions of
the COLUMNS clause, then you need to specify the XMLNAMESPACES clause.
■ XQuery_string is a complete XQuery expression and can include prolog
declarations.
■ The expr in the XML_passing_clause is an expression returning an XMLType
or an instance of a SQL scalar data type that is used as the context for evaluating
the XQuery expression. You can specify only one expr in the PASSING clause
without an identifier. The result of evaluating each expr is bound to the
XMLTABLE (
XMLnamespaces_clause
XQuery_string XMLTABLE_options )
XMLNAMESPACES (
string AS identifier
,
DEFAULT string
)
XML_passing_clause COLUMNS XML_table_column
,
PASSING
BY VALUE
expr
AS identifier
,
column
FOR ORDINALITY
datatype
PATH string DEFAULT expr
XMLTABLE
5-268 Oracle Database SQL Language Reference
corresponding identifier in the XQuery_string. If any expr that is not followed
by an AS clause, then the result of evaluating that expression is used as the context
item for evaluating the XQuery_string.
■ The optional COLUMNS clause defines the columns of the virtual table to be created
by XMLTable.
– If you omit the COLUMNS clause, then XMLTable returns a row with a single
XMLType pseudocolumn named COLUMN_VALUE.
– The datatype is required unless XMLTable is used with XML schema-based
storage of XMLType, datatype. In this case, if you omit datatype, Oracle
XML DB infers the data type from the XML schema. If the database is unable
to determine the proper type for a node, then a default type of
VARCHAR2(4000) is used.
– FOR ORDINALITY specifies that column is to be a column of generated row
numbers. There must be at most one FOR ORDINALITY clause. It is created as
a NUMBER column.
– The optional PATH clause specifies that the portion of the XQuery result that is
addressed by XQuery expression string is to be used as the column content. If
you omit PATH, then the XQuery expression column is assumed. For example:
XMLTable(... COLUMNS xyz
is equivalent to
XMLTable(... COLUMNS xyz PATH 'XYZ')
You can use different PATH clauses to split the XQuery result into different
virtual-table columns.
– The optional DEFAULT clause specifies the value to use when the PATH
expression results in an empty sequence. Its expr is an XQuery expression
that is evaluated to produce the default value.
Examples
The following example converts the result of applying the XQuery '/Warehouse' to
each value in the warehouse_spec column of the warehouses table into a virtual
relational table with columns Water and Rail:
SELECT warehouse_name warehouse,
warehouse2."Water", warehouse2."Rail"
FROM warehouses,
XMLTABLE('/Warehouse'
PASSING warehouses.warehouse_spec
COLUMNS
"Water" varchar2(6) PATH '/Warehouse/WaterAccess',
"Rail" varchar2(6) PATH '/Warehouse/RailAccess')
warehouse2;
WAREHOUSE Water Rail
----------------------------------- ------ ------
Southlake, Texas Y N
San Francisco Y N
New Jersey N N
See Also: Oracle XML DB Developer's Guide for more information on
the XMLTable function, including additional examples, and on
XQuery in general
XMLTRANSFORM
Functions 5-269
Seattle, Washington N Y
XMLTRANSFORM
Syntax
Purpose
XMLTransform takes as arguments an XMLType instance and an XSL style sheet,
which is itself a form of XMLType instance. It applies the style sheet to the instance and
returns an XMLType.
This function is useful for organizing data according to a style sheet as you are
retrieving it from the database.
Examples
The XMLTransform function requires the existence of an XSL style sheet. Here is an
example of a very simple style sheet that alphabetizes elements within a node:
CREATE TABLE xsl_tab (col1 XMLTYPE);
INSERT INTO xsl_tab VALUES (
XMLTYPE.createxml(
'<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output encoding="utf-8"/>
<!-- alphabetizes an xml tree -->
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="*|text()">
<xsl:sort select="name(.)" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:stylesheet> '));
1 row created.
The next example uses the xsl_tab XSL style sheet to alphabetize the elements in one
warehouse_spec of the sample table oe.warehouses:
SELECT XMLTRANSFORM(w.warehouse_spec, x.col1).GetClobVal()
FROM warehouses w, xsl_tab x
WHERE w.warehouse_name = 'San Francisco';
XMLTRANSFORM(W.WAREHOUSE_SPEC,X.COL1).GETCLOBVAL()
--------------------------------------------------------------------------------
<Warehouse>
<Area>50000</Area>
See Also: Oracle XML DB Developer's Guide for more information on
this function
XMLTRANSFORM ( XMLType_instance ,
XMLType_instance
string
)
ROUND and TRUNC Date Functions
5-270 Oracle Database SQL Language Reference
<Building>Rented</Building>
<DockType>Side load</DockType>
<Docks>1</Docks>
<Parking>Lot</Parking>
<RailAccess>N</RailAccess>
<VClearance>12 ft</VClearance>
<WaterAccess>Y</WaterAccess>
</Warehouse>
ROUND and TRUNC Date Functions
Table 5–14 lists the format models you can use with the ROUND and TRUNC date
functions and the units to which they round and truncate dates. The default model,
'DD', returns the date rounded or truncated to the day with a time of midnight.
Table 5–14 Date Format Models for the ROUND and TRUNC Date Functions
Format Model Rounding or Truncating Unit
CC
SCC
One greater than the first two digits of a four-digit year
SYYYY
YYYY
YEAR
SYEAR
YYY
YY
Y
Year (rounds up on July 1)
IYYY
IY
IY
I
ISO Year
Q Quarter (rounds up on the sixteenth day of the second month of the
quarter)
MONTH
MON
MM
RM
Month (rounds up on the sixteenth day)
WW Same day of the week as the first day of the year
IW Same day of the week as the first day of the ISO week, which is Monday
W Same day of the week as the first day of the month
DDD
DD
J
Day
DAY
DY
D
Starting day of the week
HH
HH12
HH24
Hour
MI Minute
About User-Defined Functions
Functions 5-271
The starting day of the week used by the format models DAY, DY, and D is specified
implicitly by the initialization parameter NLS_TERRITORY.
About User-Defined Functions
You can write user-defined functions in PL/SQL, Java, or C to provide functionality
that is not available in SQL or SQL built-in functions. User-defined functions can
appear in a SQL statement wherever an expression can occur.
For example, user-defined functions can be used in the following:
■ The select list of a SELECT statement
■ The condition of a WHERE clause
■ CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses
■ The VALUES clause of an INSERT statement
■ The SET clause of an UPDATE statement
user_defined_function::=
The optional expression list must match attributes of the function, package, or
operator.
Restriction on User-defined Functions The DISTINCT and ALL keywords are valid
only with a user-defined aggregate function.
See Also: Oracle Database Reference and Oracle Database Globalization
Support Guide for information on this parameter
Note: Oracle SQL does not support calling of functions with
Boolean parameters or returns. Therefore, if your user-defined
functions will be called from SQL statements, you must design
them to return numbers (0 or 1) or character strings ('TRUE' or
'FALSE').
See Also:
■ CREATE FUNCTION on page 14-59 for information on creating
functions, including restrictions on user-defined functions
■ Oracle Database Advanced Application Developer's Guide for a
complete discussion of the creation and use of user functions
schema .
package .
function
user_defined_operator
@ dblink . (
DISTINCT
ALL
expr
,
)
Prerequisites
5-272 Oracle Database SQL Language Reference
Prerequisites
User-defined functions must be created as top-level functions or declared with a
package specification before they can be named within a SQL statement.
To use a user function in a SQL expression, you must own or have EXECUTE privilege
on the user function. To query a view defined with a user function, you must have
SELECT privileges on the view. No separate EXECUTE privileges are needed to select
from the view.
Name Precedence
Within a SQL statement, the names of database columns take precedence over the
names of functions with no parameters. For example, if the Human Resources
manager creates the following two objects in the hr schema:
CREATE TABLE new_emps (new_sal NUMBER, ...);
CREATE FUNCTION new_sal RETURN NUMBER IS BEGIN ... END;
then in the following two statements, the reference to new_sal refers to the column
new_emps.new_sal:
SELECT new_sal FROM new_emps;
SELECT new_emps.new_sal FROM new_emps;
To access the function new_sal, you would enter:
SELECT hr.new_sal FROM new_emps;
Here are some sample calls to user functions that are allowed in SQL expressions:
circle_area (radius)
payroll.tax_rate (empno)
hr.employees.tax_rate (dependent, empno)@remote
Example To call the tax_rate user function from schema hr, execute it against the
ss_no and sal columns in tax_table, specify the following:
SELECT hr.tax_rate (ss_no, sal)
INTO income_tax
FROM tax_table WHERE ss_no = tax_id;
The INTO clause is PL/SQL that lets you place the results into the variable income_
tax.
Naming Conventions
If only one of the optional schema or package names is given, then the first identifier
can be either a schema name or a package name. For example, to determine whether
PAYROLL in the reference PAYROLL.TAX_RATE is a schema or package name, Oracle
Database proceeds as follows:
1. Check for the PAYROLL package in the current schema.
See Also: CREATE FUNCTION on page 14-59 for information on
creating top-level functions and CREATE PACKAGE on page 15-41 for
information on specifying packaged functions
About User-Defined Functions
Functions 5-273
2. If a PAYROLL package is not found, then look for a schema name PAYROLL that
contains a top-level TAX_RATE function. If no such function is found, then return
an error.
3. If the PAYROLL package is found in the current schema, then look for a TAX_RATE
function in the PAYROLL package. If no such function is found, then return an
error.
You can also refer to a stored top-level function using any synonym that you have
defined for it.
Name Precedence
5-274 Oracle Database SQL Language Reference
6
Expressions 6-1
6 Expressions
This chapter describes how to combine values, operators, and functions into
expressions.
This chapter includes these sections:
■ About SQL Expressions
■ Simple Expressions
■ Compound Expressions
■ CASE Expressions
■ Column Expressions
■ CURSOR Expressions
■ Datetime Expressions
■ Function Expressions
■ Interval Expressions
■ Model Expressions
■ Object Access Expressions
■ Placeholder Expressions
■ Scalar Subquery Expressions
■ Type Constructor Expressions
■ Expression Lists
About SQL Expressions
An expression is a combination of one or more values, operators, and SQL functions
that evaluates to a value. An expression generally assumes the data type of its
components.
About SQL Expressions
6-2 Oracle Database SQL Language Reference
This simple expression evaluates to 4 and has data type NUMBER (the same data type as
its components):
2*2
The following expression is an example of a more complex expression that uses both
functions and operators. The expression adds seven days to the current date, removes
the time component from the sum, and converts the result to CHAR data type:
TO_CHAR(TRUNC(SYSDATE+7))
You can use expressions in:
■ The select list of the SELECT statement
■ A condition of the WHERE clause and HAVING clause
■ The CONNECT BY, START WITH, and ORDER BY clauses
■ The VALUES clause of the INSERT statement
■ The SET clause of the UPDATE statement
For example, you could use an expression in place of the quoted string 'Smith' in
this UPDATE statement SET clause:
SET last_name = 'Smith';
This SET clause has the expression INITCAP(last_name) instead of the quoted string
'Smith':
SET last_name = INITCAP(last_name);
Expressions have several forms, as shown in the following syntax:
Note: The combined values of the NLS_COMP and NLS_SORT
settings determine the rules by which characters are sorted and
compared. If NLS_COMP is set to LINGUISTIC for your database, then
all entities in this chapter will be interpreted according to the rules
specified by the NLS_SORT parameter. If NLS_COMP is not set to
LINGUISTIC, then the functions are interpreted without regard to the
NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set
explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle
Database Globalization Support Guide for more information on these
settings.
Simple Expressions
Expressions 6-3
expr::=
Oracle Database does not accept all forms of expressions in all parts of all SQL
statements. Refer to the individual SQL statements in Chapter 10 through Chapter 19
for information on restrictions on the expressions in that statement.
You must use appropriate expression notation whenever expr appears in conditions,
SQL functions, or SQL statements in other parts of this reference. The sections that
follow describe and provide examples of the various forms of expressions.
Simple Expressions
A simple expression specifies a column, pseudocolumn, constant, sequence number, or
null.
simple_expression::=
In addition to the schema of a user, schema can also be "PUBLIC" (double quotation
marks required), in which case it must qualify a public synonym for a table, view, or
simple_expression
compound_expression
case_expression
cursor_expression
datetime_expression
function_expression
interval_expression
object_access_expression
scalar_subquery_expression
model_expression
type_constructor_expression
variable_expression
query_name
schema
table
view
materialized view
.
column
ROWID
ROWNUM
string
number
sequence .
CURRVAL
NEXTVAL
NULL
Compound Expressions
6-4 Oracle Database SQL Language Reference
materialized view. Qualifying a public synonym with "PUBLIC" is supported only in
data manipulation language (DML) statements, not data definition language (DDL)
statements.
You can specify ROWID only with a table, not with a view or materialized view. NCHAR
and NVARCHAR2 are not valid pseudocolumn data types.
Some valid simple expressions are:
employees.last_name
'this is a text string'
10
N'this is an NCHAR string'
Compound Expressions
A compound expression specifies a combination of other expressions.
compound_expression::=
You can use any built-in function as an expression ("Function Expressions" on
page 6-10). However, in a compound expression, some combinations of functions are
inappropriate and are rejected. For example, the LENGTH function is inappropriate
within an aggregate function.
The PRIOR operator is used in CONNECT BY clauses of hierarchical queries.
Some valid compound expressions are:
('CLARK' || 'SMITH')
LENGTH('MOOSE') * 57
SQRT(144) + 72
my_fun(TO_CHAR(sysdate,'DD-MMM-YY'))
See Also: Chapter 2, "Pseudocolumns" for more information on
pseudocolumns and subquery_factoring_clause on page 19-13 for
information on query_name
See Also: "Operator Precedence" on page 4-2 and "Hierarchical
Queries" on page 9-3
( expr )
+
–
PRIOR
expr
expr
*
/
+
–
| |
expr
CASE Expressions
Expressions 6-5
CASE Expressions
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without
having to invoke procedures. The syntax is:
simple_case_expression::=
searched_case_expression::=
else_clause::=
In a simple CASE expression, Oracle Database searches for the first WHEN ... THEN pair
for which expr is equal to comparison_expr and returns return_expr. If none of
the WHEN ... THEN pairs meet this condition, and an ELSE clause exists, then Oracle
returns else_expr. Otherwise, Oracle returns null. You cannot specify the literal
NULL for every return_expr and the else_expr.
In a searched CASE expression, Oracle searches from left to right until it finds an
occurrence of condition that is true, and then returns return_expr. If no
condition is found to be true, and an ELSE clause exists, then Oracle returns else_
expr. Otherwise, Oracle returns null.
Oracle Database uses short-circuit evaluation. For a simple CASE expression, the
database evaluates each comparison_expr value only before comparing it to expr,
rather than evaluating all comparison_expr values before comparing any of them
with expr. Consequently, Oracle never evaluates a comparison_expr if a previous
comparison_expr is equal to expr. For a searched CASE expression, the database
evaluates each condition to determine whether it is true, and never evaluates a
condition if the previous condition was true.
For a simple CASE expression, the expr and all comparison_expr values must
either have the same data type (CHAR, VARCHAR2, NCHAR, or NVARCHAR2, NUMBER,
BINARY_FLOAT, or BINARY_DOUBLE) or must all have a numeric data type. If all
expressions have a numeric data type, then Oracle determines the argument with the
highest numeric precedence, implicitly converts the remaining arguments to that data
type, and returns that data type.
For both simple and searched CASE expressions, all of the return_exprs must either
have the same data type (CHAR, VARCHAR2, NCHAR, or NVARCHAR2, NUMBER, BINARY_
FLOAT, or BINARY_DOUBLE) or must all have a numeric data type. If all return
expressions have a numeric data type, then Oracle determines the argument with the
highest numeric precedence, implicitly converts the remaining arguments to that data
type, and returns that data type.
The maximum number of arguments in a CASE expression is 65535. All expressions
count toward this limit, including the initial expression of a simple CASE expression
CASE
simple_case_expression
searched_case_expression
else_clause
END
expr WHEN comparison_expr THEN return_expr
WHEN condition THEN return_expr
ELSE else_expr
Column Expressions
6-6 Oracle Database SQL Language Reference
and the optional ELSE expression. Each WHEN ... THEN pair counts as two arguments.
To avoid exceeding this limit, you can nest CASE expressions so that the return_
expr itself is a CASE expression.
Simple CASE Example For each customer in the sample oe.customers table, the
following statement lists the credit limit as "Low" if it equals $100, "High" if it equals
$5000, and "Medium" if it equals anything else.
SELECT cust_last_name,
CASE credit_limit WHEN 100 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium' END AS credit
FROM customers
ORDER BY cust_last_name, credit;
CUST_LAST_NAME CREDIT
-------------------- ------
Adjani Medium
Adjani Medium
Alexander Medium
Alexander Medium
Altman High
Altman Medium
. . .
Searched CASE Example The following statement finds the average salary of the
employees in the sample table oe.employees, using $2000 as the lowest salary
possible:
SELECT AVG(CASE WHEN e.salary > 2000 THEN e.salary
ELSE 2000 END) "Average Salary" FROM employees e;
Average Salary
--------------
6461.68224
Column Expressions
A column expression, which is designated as column_expression in subsequent
syntax diagrams, is a limited form of expr. A column expression can be a simple
expression, compound expression, function expression, or expression list, but it can
contain only the following forms of expression:
■ Columns of the subject table — the table being created, altered, or indexed
■ Constants (strings or numbers)
See Also:
■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for
more information on implicit conversion
■ "Numeric Precedence" on page 3-14 for information on numeric
precedence
■ COALESCE on page 5-38 and NULLIF on page 5-124 for
alternative forms of CASE logic
■ Oracle Database Data Warehousing Guide for examples using various
forms of the CASE expression
CURSOR Expressions
Expressions 6-7
■ Deterministic functions — either SQL built-in functions or user-defined functions
No other expression forms described in this chapter are valid. In addition, compound
expressions using the PRIOR keyword are not supported, nor are aggregate functions.
You can use a column expression for these purposes:
■ To create a function-based index.
■ To explicitly or implicitly define a virtual column. When you define a virtual
column, the defining column_expression must refer only to columns of the
subject table that have already been defined, in the current statement or in a prior
statement.
The combined components of a column expression must be deterministic. That is, the
same set of input values must return the same set of output values.
CURSOR Expressions
A CURSOR expression returns a nested cursor. This form of expression is equivalent to
the PL/SQL REF CURSOR and can be passed as a REF CURSOR argument to a function.
A nested cursor is implicitly opened when the cursor expression is evaluated. For
example, if the cursor expression appears in a select list, a nested cursor will be
opened for each row fetched by the query. The nested cursor is closed only when:
■ The nested cursor is explicitly closed by the user
■ The parent cursor is reexecuted
■ The parent cursor is closed
■ The parent cursor is cancelled
■ An error arises during fetch on one of its parent cursors (it is closed as part of the
clean-up)
Restrictions on CURSOR Expressions The following restrictions apply to CURSOR
expressions:
■ If the enclosing statement is not a SELECT statement, then nested cursors can
appear only as REF CURSOR arguments of a procedure.
■ If the enclosing statement is a SELECT statement, then nested cursors can also
appear in the outermost select list of the query specification or in the outermost
select list of another nested cursor.
■ Nested cursors cannot appear in views.
■ You cannot perform BIND and EXECUTE operations on nested cursors.
Examples The following example shows the use of a CURSOR expression in the
select list of a query:
SELECT department_name, CURSOR(SELECT salary, commission_pct
FROM employees e
See Also: "Simple Expressions" on page 6-3, "Compound
Expressions" on page 6-4, "Function Expressions" on page 6-10, and
"Expression Lists" on page 6-16 for information on these forms of
expr
CURSOR ( subquery )
Datetime Expressions
6-8 Oracle Database SQL Language Reference
WHERE e.department_id = d.department_id)
FROM departments d
ORDER BY department_name;
The next example shows the use of a CURSOR expression as a function argument. The
example begins by creating a function in the sample OE schema that can accept the
REF CURSOR argument. (The PL/SQL function body is shown in italics.)
CREATE FUNCTION f(cur SYS_REFCURSOR, mgr_hiredate DATE)
RETURN NUMBER IS
emp_hiredate DATE;
before number :=0;
after number:=0;
begin
loop
fetch cur into emp_hiredate;
exit when cur%NOTFOUND;
if emp_hiredate > mgr_hiredate then
after:=after+1;
else
before:=before+1;
end if;
end loop;
close cur;
if before > after then
return 1;
else
return 0;
end if;
end;
/
The function accepts a cursor and a date. The function expects the cursor to be a query
returning a set of dates. The following query uses the function to find those managers
in the sample employees table, most of whose employees were hired before the
manager.
SELECT e1.last_name FROM employees e1
WHERE f(
CURSOR(SELECT e2.hire_date FROM employees e2
WHERE e1.employee_id = e2.manager_id),
e1.hire_date) = 1
ORDER BY last_name;
LAST_NAME
-------------------------
Cambrault
Higgins
Hunold
Kochhar
Mourgos
Zlotkey
Datetime Expressions
A datetime expression yields a value of one of the datetime data types.
Datetime Expressions
Expressions 6-9
datetime_expression::=
The initial expr is any expression, except a scalar subquery expression, that evaluates
to a value of data type TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP
WITH LOCAL TIME ZONE. The DATE data type is not supported. If this expr is itself a
datetime_expression, then it must be enclosed in parentheses.
Datetimes and intervals can be combined according to the rules defined in Table 3–5
on page 3-21. The three combinations that yield datetime values are valid in a datetime
expression.
If you specify AT LOCAL, then Oracle uses the current session time zone.
The settings for AT TIME ZONE are interpreted as follows:
■ The string '(+|-)HH:MM' specifies a time zone as an offset from UTC.
■ DBTIMEZONE: Oracle uses the database time zone established (explicitly or by
default) during database creation.
■ SESSIONTIMEZONE: Oracle uses the session time zone established by default or in
the most recent ALTER SESSION statement.
■ time_zone_name: Oracle returns the datetime_value_expr in the time zone
indicated by time_zone_name. For a listing of valid time zone region names,
query the V$TIMEZONE_NAMES dynamic performance view.
■ expr: If expr returns a character string with a valid time zone format, then Oracle
returns the input in that time zone. Otherwise, Oracle returns an error.
Note: Time zone region names are needed by the daylight saving
feature. These names are stored in two types of time zone files: one
large and one small. One of these files is the default file, depending
on your environment and the release of Oracle Database you are
using. For more information regarding time zone files and names,
see Oracle Database Globalization Support Guide.
See Also:
■ Oracle Database Globalization Support Guide for a complete listing of
the time zone region names in both files
■ Oracle Database Reference for information on the dynamic
performance views
expr AT
LOCAL
TIME ZONE
’
+
–
hh : mm ’
DBTIMEZONE
SESSIONTIMEZONE
’ time_zone_name ’
expr
Function Expressions
6-10 Oracle Database SQL Language Reference
Example The following example converts the datetime value of one time zone to
another time zone:
SELECT FROM_TZ(CAST(TO_DATE('1999-12-01 11:00:00',
'YYYY-MM-DD HH:MI:SS') AS TIMESTAMP), 'America/New_York')
AT TIME ZONE 'America/Los_Angeles' "West Coast Time"
FROM DUAL;
West Coast Time
------------------------------------------------
01-DEC-99 08.00.00.000000 AM AMERICA/LOS_ANGELES
Function Expressions
You can use any built-in SQL function or user-defined function as an expression. Some
valid built-in function expressions are:
LENGTH('BLAKE')
ROUND(1234.567*43)
SYSDATE
A user-defined function expression specifies a call to:
■ A function in an Oracle-supplied package (see Oracle Database PL/SQL Packages and
Types Reference)
■ A function in a user-defined package or type or in a standalone user-defined
function (see "About User-Defined Functions" on page 5-271)
■ A user-defined function or operator (see CREATE OPERATOR on page 15-34,
CREATE FUNCTION on page 14-59, and Oracle Database Data Cartridge Developer's
Guide)
Some valid user-defined function expressions are:
circle_area(radius)
payroll.tax_rate(empno)
hr.employees.comm_pct@remote(dependents, empno)
DBMS_LOB.getlength(column_name)
my_function(a_column)
In a user-defined function being used as an expression, positional, named, and mixed
notation are supported. For example, all of the following notations are correct:
CALL my_function(arg1 => 3, arg2 => 4) ...
CALL my_function(3, 4) ...
CALL my_function(3, arg2 => 4) ...
Restriction on User-Defined Function Expressions You cannot pass arguments of
object type or XMLType to remote functions and procedures.
Interval Expressions
An interval expression yields a value of INTERVAL YEAR TO MONTH or INTERVAL DAY
TO SECOND.
See Also: "About SQL Functions" on page 5-2' and "Aggregate
Functions" on page 5-9 for information on built-in functions
Model Expressions
Expressions 6-11
interval_expression::=
The expressions expr1 and expr2 can be any expressions that evaluate to values of
data type DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP WITH
LOCAL TIME ZONE.
Datetimes and intervals can be combined according to the rules defined in Table 3–5
on page 3-21. The six combinations that yield interval values are valid in an interval
expression.
Both leading_field_precision and fractional_second_precision can be
any integer from 0 to 9. If you omit the leading_field_precision for either DAY
or YEAR, then Oracle Database uses the default value of 2. If you omit the
fractional_second_precision for second, then the database uses the default
value of 6. If the value returned by a query contains more digits that the default
precision, then Oracle Database returns an error. Therefore, it is good practice to
specify a precision that you know will be at least as large as any value returned by the
query.
For example, the following statement subtracts the value of the order_date column
in the sample table orders (a datetime value) from the system timestamp (another
datetime value) to yield an interval value expression. It is not known how many days
ago the oldest order was placed, so the maximum value of 9 for the DAY leading field
precision is specified:
SELECT (SYSTIMESTAMP - order_date) DAY(9) TO SECOND FROM orders
WHERE order_id = 2458;
Model Expressions
A model expression is used only in the model_clause of a SELECT statement and
then only on the right-hand side of a model rule. It yields a value for a cell in a
measure column previously defined in the model_clause. For additional
information, refer to model_clause on page 19-28.
( expr1 – expr2 )
DAY
( leading_field_precision )
TO SECOND
( fractional_second_precision )
YEAR
( leading_field_precision )
TO MONTH
Model Expressions
6-12 Oracle Database SQL Language Reference
model_expression::=
When you specify a measure column in a model expression, any conditions and
expressions you specify must resolve to single values.
When you specify an aggregate function in a model expression, the argument to the
function is a measure column that has been previously defined in the model_clause.
An aggregate function can be used only on the right-hand side of a model rule.
Specifying an analytic function on the right-hand side of the model rule lets you
express complex calculations directly in the model_clause. The following
restrictions apply when using an analytic function in a model expression:
■ Analytic functions can be used only in an UPDATE rule.
■ You cannot specify an analytic function on the right-hand side of the model rule if
the left-hand side of the rule contains a FOR loop or an ORDER BY clause.
■ The arguments in the OVER clause of the analytic function cannot contain an
aggregate.
■ The arguments before the OVER clause of the analytic function cannot contain a
cell reference.
When expr is itself a model expression, it is referred to as a nested cell reference. The
following restrictions apply to nested cell references:
■ Only one level of nesting is allowed.
■ A nested cell reference must be a single-cell reference.
■ When AUTOMATIC ORDER is specified in the model_rules_clause, a nested cell
reference can be used on the left-hand side of a model rule only if the measure
used in the nested cell reference is never updated for any cell in the spreadsheet
clause.
The model expressions shown below are based on the model_clause of the
following SELECT statement:
SELECT country,prod,year,s
FROM sales_view_ref
See Also: "The MODEL clause: Examples" on page 19-45 for an
example of using an analytic function on the right-hand side of a
model rule
measure_column [
condition
expr
,
]
aggregate_function [
condition
expr
,
single_column_for_loop
,
multi_column_for_loop
]
analytic_function
Object Access Expressions
Expressions 6-13
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s[prod='Mouse Pad', year=2000] =
s['Mouse Pad', 1998] + s['Mouse Pad', 1999],
s['Standard Mouse', 2001] = s['Standard Mouse', 2000]
)
ORDER BY country, prod, year;
The following model expression represents a single cell reference using symbolic
notation. It represents the sales of the Mouse Pad for the year 2000.
s[prod='Mouse Pad',year=2000]
The following model expression represents a multiple cell reference using positional
notation, using the CV function. It represents the sales of the current value of the
dimension column prod for the year 2001.
s[CV(prod), 2001]
The following model expression represents an aggregate function. It represents the
sum of sales of the Mouse Pad for the years between the current value of the
dimension column year less two and the current value of the dimension column
year less one.
SUM(s)['Mouse Pad',year BETWEEN CV()-2 AND CV()-1]
Object Access Expressions
An object access expression specifies attribute reference and method invocation.
object_access_expression::=
The column parameter can be an object or REF column. If you specify expr, then it
must resolve to an object type.
When a type's member function is invoked in the context of a SQL statement, if the
SELF argument is null, Oracle returns null and the function is not invoked.
Examples The following example creates a table based on the sample oe.order_
item_typ object type, and then shows how you would update and select from the
object column attributes.
See Also: CV on page 5-56 and model_clause on page 19-28
table_alias . column .
object_table_alias .
( expr ) .
attribute
.
. method (
argument
,
)
method (
argument
,
)
Placeholder Expressions
6-14 Oracle Database SQL Language Reference
CREATE TABLE short_orders (
sales_rep VARCHAR2(25), item order_item_typ);
UPDATE short_orders s SET sales_rep = 'Unassigned';
SELECT o.item.line_item_id, o.item.quantity FROM short_orders o;
Placeholder Expressions
A placeholder expression provides a location in a SQL statement for which a
third-generation language bind variable will provide a value. You can specify the
placeholder expression with an optional indicator variable. This form of expression
can appear only in embedded SQL statements or SQL statements processed in an
Oracle Call Interface (OCI) program.
placeholder_expression::=
Some valid placeholder expressions are:
:employee_name INDICATOR :employee_name_indicator_var
:department_location
Scalar Subquery Expressions
A scalar subquery expression is a subquery that returns exactly one column value
from one row. The value of the scalar subquery expression is the value of the select list
item of the subquery. If the subquery returns 0 rows, then the value of the scalar
subquery expression is NULL. If the subquery returns more than one row, then Oracle
returns an error.
You can use a scalar subquery expression in most syntax that calls for an expression
(expr). In all cases, a scalar subquery must be enclosed in its own parentheses, even if
its syntactic location already positions it within parentheses (for example, when the
scalar subquery is used as the argument to a built-in function).
Scalar subqueries are not valid expressions in the following places:
■ As default values for columns
■ As hash expressions for clusters
■ In the RETURNING clause of DML statements
■ As the basis of a function-based index
■ In CHECK constraints
■ In GROUP BY clauses
■ In statements that are unrelated to queries, such as CREATE PROFILE
Type Constructor Expressions
A type constructor expression specifies a call to a constructor method. The argument
to the type constructor is any expression. Type constructors can be invoked anywhere
functions are invoked.
: host_variable
INDICATOR
: indicator_variable
Type Constructor Expressions
Expressions 6-15
type_constructor_expression::=
The NEW keyword applies to constructors for object types but not for collection types.
It instructs Oracle to construct a new object by invoking an appropriate constructor.
The use of the NEW keyword is optional, but it is good practice to specify it.
If type_name is an object type, then the expressions must be an ordered list, where
the first argument is a value whose type matches the first attribute of the object type,
the second argument is a value whose type matches the second attribute of the object
type, and so on. The total number of arguments to the constructor must match the total
number of attributes of the object type.
If type_name is a varray or nested table type, then the expression list can contain
zero or more arguments. Zero arguments implies construction of an empty collection.
Otherwise, each argument corresponds to an element value whose type is the element
type of the collection type.
Restriction on Type Constructor Invocation In an invocation of a type constructor
method, the number of parameters (expr) specified cannot exceed 999, even if the
object type has more than 999 attributes. This limitation applies only when the
constructor is called from SQL. For calls from PL/SQL, the PL/SQL limitations apply.
Expression Example This example uses the cust_address_typ type in the sample
oe schema to show the use of an expression in the call to a constructor method (the
PL/SQL is shown in italics):
CREATE TYPE address_book_t AS TABLE OF cust_address_typ;
DECLARE
myaddr cust_address_typ := cust_address_typ(
'500 Oracle Parkway', 94065, 'Redwood Shores', 'CA','USA');
alladdr address_book_t := address_book_t();
BEGIN
INSERT INTO customers VALUES (
666999, 'Joe', 'Smith', myaddr, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
END;
/
Subquery Example This example uses the warehouse_typ type in the sample
schema oe to illustrate the use of a subquery in the call to the constructor method.
CREATE TABLE warehouse_tab OF warehouse_typ;
INSERT INTO warehouse_tab
VALUES (warehouse_typ(101, 'new_wh', 201));
CREATE TYPE facility_typ AS OBJECT (
facility_id NUMBER,
warehouse_ref REF warehouse_typ);
See Also: Oracle Database Object-Relational Developer's Guide for
additional information on constructor methods and Oracle Database
PL/SQL Language Reference for information on PL/SQL limitations on
calls to type constructors
NEW schema .
type_name (
expr
,
)
Expression Lists
6-16 Oracle Database SQL Language Reference
CREATE TABLE buildings (b_id NUMBER, building facility_typ);
INSERT INTO buildings VALUES (10, facility_typ(102,
(SELECT REF(w) FROM warehouse_tab w
WHERE warehouse_name = 'new_wh')));
SELECT b.b_id, b.building.facility_id "FAC_ID",
DEREF(b.building.warehouse_ref) "WH" FROM buildings b;
B_ID FAC_ID WH(WAREHOUSE_ID, WAREHOUSE_NAME, LOCATION_ID)
---------- ---------- ---------------------------------------------
10 102 WAREHOUSE_TYP(101, 'new_wh', 201)
Expression Lists
An expression list is a combination of other expressions.
expression_list::=
Expression lists can appear in comparison and membership conditions and in GROUP
BY clauses of queries and subqueries. An expression lists in a comparision or
membership condition is sometimes referred to as a row value constructor or row
constructor.
Comparison and membership conditions appear in the conditions of WHERE clauses.
They can contain either one or more comma-delimited expressions or one or more sets
of expressions where each set contains one or more comma-delimited expressions. In
the latter case (multiple sets of expressions):
■ Each set is bounded by parentheses
■ Each set must contain the same number of expressions
■ The number of expressions in each set must match the number of expressions
before the operator in the comparison condition or before the IN keyword in the
membership condition.
A comma-delimited list of expressions can contain no more than 1000 expressions. A
comma-delimited list of sets of expressions can contain any number of sets, but each
set can contain no more than 1000 expressions.
The following are some valid expression lists in conditions:
(10, 20, 40)
('SCOTT', 'BLAKE', 'TAYLOR')
( ('Guy', 'Himuro', 'GHIMURO'),('Karen', 'Colmenares', 'KCOLMENA') )
In the third example, the number of expressions in each set must equal the number of
expressions in the first part of the condition. For example:
SELECT * FROM employees
WHERE (first_name, last_name, email) IN
expr
,
(
expr
,
)
Expression Lists
Expressions 6-17
(('Guy', 'Himuro', 'GHIMURO'),('Karen', 'Colmenares', 'KCOLMENA'))
In a simple GROUP BY clause, you can use either the upper or lower form of expression
list:
SELECT department_id, MIN(salary) min, MAX(salary) max FROM employees
GROUP BY department_id, salary
ORDER BY department_id, min, max;
SELECT department_id, MIN(salary) min, MAX(salary) max FROM employees
GROUP BY (department_id, salary)
ORDER BY department_id, min, max;
In ROLLUP, CUBE, and GROUPING SETS clauses of GROUP BY clauses, you can combine
individual expressions with sets of expressions in the same expression list. The
following example shows several valid grouping sets expression lists in one SQL
statement:
SELECT
prod_category, prod_subcategory, country_id, cust_city, count(*)
FROM products, sales, customers
WHERE sales.prod_id = products.prod_id
AND sales.cust_id=customers.cust_id
AND sales.time_id = '01-oct-00'
AND customers.cust_year_of_birth BETWEEN 1960 and 1970
GROUP BY GROUPING SETS
(
(prod_category, prod_subcategory, country_id, cust_city),
(prod_category, prod_subcategory, country_id),
(prod_category, prod_subcategory),
country_id
)
ORDER BY prod_category, prod_subcategory, country_id, cust_city;
See Also: "Comparison Conditions" on page 7-4 and IN Condition
conditions on page 7-22
See Also: SELECT on page 19-4
Expression Lists
6-18 Oracle Database SQL Language Reference
7
Conditions 7-1
7 Conditions
A condition specifies a combination of one or more expressions and logical (Boolean)
operators and returns a value of TRUE, FALSE, or UNKNOWN.
This chapter contains the following sections:
■ About SQL Conditions
■ Comparison Conditions
■ Floating-Point Conditions
■ Logical Conditions
■ Model Conditions
■ Multiset Conditions
■ Pattern-matching Conditions
■ Null Conditions
■ XML Conditions
■ Compound Conditions
■ BETWEEN Condition
■ EXISTS Condition
■ IN Condition
■ IS OF type Condition
About SQL Conditions
Conditions can have several forms, as shown in the following syntax.
About SQL Conditions
7-2 Oracle Database SQL Language Reference
condition::=
If you have installed Oracle Text, then you can create conditions with the built-in
operators that are part of that product, including CONTAINS, CATSEARCH, and
MATCHES. For more information on these Oracle Text elements, refer to Oracle Text
Reference.
If you are using Oracle Expression Filter, then you can create conditions with the
built-in EVALUATE operator that is part of that product. For more information, refer to
Oracle Database Rules Manager and Expression Filter Developer's Guide.
The sections that follow describe the various forms of conditions. You must use
appropriate condition syntax whenever condition appears in SQL statements.
You can use a condition in the WHERE clause of these statements:
■ DELETE
■ SELECT
■ UPDATE
You can use a condition in any of these clauses of the SELECT statement:
■ WHERE
■ START WITH
■ CONNECT BY
■ HAVING
comparison_condition
floating_point_condition
logical_condition
model_condition
multiset_condition
pattern_matching_condition
range_condition
null_condition
XML_condition
compound_condition
exists_condition
in_condition
is_of_type_condition
About SQL Conditions
Conditions 7-3
A condition could be said to be of a logical data type, although Oracle Database does
not formally support such a data type.
The following simple condition always evaluates to TRUE:
1 = 1
The following more complex condition adds the salary value to the commission_
pct value (substituting the value 0 for null) and determines whether the sum is
greater than the number constant 25000:
NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)
Logical conditions can combine multiple conditions into a single condition. For
example, you can use the AND condition to combine two conditions:
(1 = 1) AND (5 < 7)
Here are some valid conditions:
name = 'SMITH'
employees.department_id = departments.department_id
hire_date > '01-JAN-08'
job_id IN ('SA_MAN', 'SA_REP')
salary BETWEEN 5000 AND 10000
commission_pct IS NULL AND salary = 2100
Condition Precedence
Precedence is the order in which Oracle Database evaluates different conditions in the
same expression. When evaluating an expression containing multiple conditions,
Oracle evaluates conditions with higher precedence before evaluating those with
lower precedence. Oracle evaluates conditions with equal precedence from left to right
within an expression, with the following exceptions:
■ Left to right evaluation is not guaranteed for multiple conditions connected using
AND
■ Left to right evaluation is not guaranteed for multiple conditions connected using
OR
Table 7–1 lists the levels of precedence among SQL condition from high to low.
Conditions listed on the same line have the same precedence. As the table indicates,
Oracle evaluates operators before conditions.
Note: The combined values of the NLS_COMP and NLS_SORT
settings determine the rules by which characters are sorted and
compared. If NLS_COMP is set to LINGUISTIC for your database, then
all entities in this chapter will be interpreted according to the rules
specified by the NLS_SORT parameter. If NLS_COMP is not set to
LINGUISTIC, then the functions are interpreted without regard to the
NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set
explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle
Database Globalization Support Guide for more information on these
settings.
See Also: The description of each statement in Chapter 10 through
Chapter 19 for the restrictions on the conditions in that statement
Comparison Conditions
7-4 Oracle Database SQL Language Reference
Comparison Conditions
Comparison conditions compare one expression with another. The result of such a
comparison can be TRUE, FALSE, or NULL.
Large objects (LOBs) are not supported in comparison conditions. However, you can
use PL/SQL programs for comparisons on CLOB data.
When comparing numeric expressions, Oracle uses numeric precedence to determine
whether the condition compares NUMBER, BINARY_FLOAT, or BINARY_DOUBLE
values. Refer to "Numeric Precedence" on page 3-14 for information on numeric
precedence.
Two objects of nonscalar type are comparable if they are of the same named type and
there is a one-to-one correspondence between their elements. In addition, nested tables
of user-defined object types, even if their elements are comparable, must have MAP
methods defined on them to be used in equality or IN conditions.
Table 7–2 lists comparison conditions.
Table 7–1 SQL Condition Precedence
Type of Condition Purpose
SQL operators are evaluated before SQL
conditions
See "Operator Precedence" on page 4-2
=, !=, <, >, <=, >=, comparison
IS [NOT] NULL, LIKE, [NOT] BETWEEN,
[NOT] IN, EXISTS, IS OF type
comparison
NOT exponentiation, logical negation
AND conjunction
OR disjunction
See Also: Oracle Database Object-Relational Developer's Guide for
information on using MAP methods to compare objects
Table 7–2 Comparison Conditions
Type of
Condition Purpose Example
= Equality test. SELECT *
FROM employees
WHERE salary = 2500
ORDER BY employee_id;
!=
^=
< >
¬=
Inequality test. Some forms of the inequality
condition may be unavailable on some platforms.
SELECT *
FROM employees
WHERE salary != 2500
ORDER BY employee_id;
>
<
Greater-than and less-than tests. SELECT * FROM employees
WHERE salary > 2500
ORDER BY employee_id;
SELECT * FROM employees
WHERE salary < 2500
ORDER BY employee_id;
Comparison Conditions
Conditions 7-5
Simple Comparison Conditions
A simple comparison condition specifies a comparison with expressions or subquery
results.
simple_comparison_condition::=
>=
<=
Greater-than-or-equal-to and less-than-or-equal-to
tests.
SELECT * FROM employees
WHERE salary >= 2500
ORDER BY employee_id;
SELECT * FROM employees
WHERE salary <= 2500
ORDER BY employee_id;
ANY
SOME
Compares a value to each value in a list or returned
by a query. Must be preceded by =, !=, >, <, <=, >=.
Can be followed by any expression or subquery that
returns one or more values.
Evaluates to FALSE if the query returns no rows.
SELECT * FROM employees
WHERE salary = ANY
(SELECT salary
FROM employees
WHERE department_id = 30)
ORDER BY employee_id;
ALL Compares a value to every value in a list or returned
by a query. Must be preceded by =, !=, >, <, <=, >=.
Can be followed by any expression or subquery that
returns one or more values.
Evaluates to TRUE if the query returns no rows.
SELECT * FROM employees
WHERE salary >=
ALL ( 1400, 3000)
ORDER BY employee_id;
Table 7–2 (Cont.) Comparison Conditions
Type of
Condition Purpose Example
expr
=
!=
^=
<>
>
<
>=
<=
expr
( expr
,
)
=
!=
^=
<>
( subquery )
Comparison Conditions
7-6 Oracle Database SQL Language Reference
expression_list::=
If you use the lower form of this condition (with multiple expressions to the left of the
operator), then you must use the lower form of the expression_list, and the
values returned by the subquery must match in number and data type the expressions
in expression_list.
Group Comparison Conditions
A group comparison condition specifies a comparison with any or all members in a list
or subquery.
group_comparison_condition::=
expression_list::=
See Also: "Expression Lists" on page 6-16 for more information
about combining expressions and SELECT on page 19-4 for
information about subqueries
expr
,
(
expr
,
)
expr
=
!=
^=
<>
>
<
>=
<=
ANY
SOME
ALL
(
expression_list
subquery
)
( expr
,
)
=
!=
^=
<>
ANY
SOME
ALL
(
expression_list
’
subquery
)
expr
,
(
expr
,
)
Logical Conditions
Conditions 7-7
If you use the upper form of this condition (with a single expression to the left of the
operator), then you must use the upper form of expression_list. If you use the
lower form of this condition (with multiple expressions to the left of the operator),
then you must use the lower form of expression_list, and the expressions in each
expression_list must match in number and data type the expressions to the left of
the operator.
Floating-Point Conditions
The floating-point conditions let you determine whether an expression is infinite or is
the undefined result of an operation (is not a number or NaN).
floating_point_condition::=
In both forms of floating-point condition, expr must resolve to a numeric data type or
to any data type that can be implicitly converted to a numeric data type. Table 7–3
describes the floating-point conditions.
Logical Conditions
A logical condition combines the results of two component conditions to produce a
single result based on them or to invert the result of a single condition. Table 7–4 lists
logical conditions.
See Also:
■ "Expression Lists" on page 6-16
■ SELECT on page 19-4
Table 7–3 Floating-Point Conditions
Type of
Condition Operation Example
IS [NOT]
NAN
Returns TRUE if expr is the special
value NaN when NOT is not
specified. Returns TRUE if expr is
not the special value NaN when NOT
is specified.
SELECT COUNT(*) FROM employees
WHERE commission_pct IS NOT NAN;
IS [NOT]
INFINITE
Returns TRUE if expr is the special
value +INF or -INF when NOT is
not specified. Returns TRUE if expr
is neither +INF nor -INF when NOT
is specified.
SELECT last_name FROM employees
WHERE salary IS NOT INFINITE;
See Also:
■ "Floating-Point Numbers" on page 3-12 for more information on
the Oracle implementation of floating-point numbers
■ "Implicit Data Conversion" on page 3-40 for more information on
how Oracle converts floating-point data types
expr IS
NOT NAN
INFINITE
Logical Conditions
7-8 Oracle Database SQL Language Reference
Table 7–5 shows the result of applying the NOT condition to an expression.
Table 7–6 shows the results of combining the AND condition to two expressions.
For example, in the WHERE clause of the following SELECT statement, the AND logical
condition is used to ensure that only those hired before 2004 and earning more than
$2500 a month are returned:
SELECT * FROM employees
WHERE hire_date < TO_DATE('01-JAN-2004', 'DD-MON-YYYY')
AND salary > 2500
ORDER BY employee_id;
Table 7–7 shows the results of applying OR to two expressions.
Table 7–4 Logical Conditions
Type of
Condition Operation Examples
NOT Returns TRUE if the following
condition is FALSE. Returns
FALSE if it is TRUE. If it is
UNKNOWN, then it remains
UNKNOWN.
SELECT *
FROM employees
WHERE NOT (job_id IS NULL)
ORDER BY employee_id;
SELECT *
FROM employees
WHERE NOT
(salary BETWEEN 1000 AND 2000)
ORDER BY employee_id;
AND Returns TRUE if both component
conditions are TRUE. Returns
FALSE if either is FALSE.
Otherwise returns UNKNOWN.
SELECT *
FROM employees
WHERE job_id = 'PU_CLERK'
AND department_id = 30
ORDER BY employee_id;
OR Returns TRUE if either component
condition is TRUE. Returns FALSE
if both are FALSE. Otherwise
returns UNKNOWN.
SELECT *
FROM employees
WHERE job_id = 'PU_CLERK'
OR department_id = 10
ORDER BY employee_id;
Table 7–5 NOT Truth Table
-- TRUE FALSE UNKNOWN
NOT FALSE TRUE UNKNOWN
Table 7–6 AND Truth Table
AND TRUE FALSE UNKNOWN
TRUE TRUE FALSE UNKNOWN
FALSE FALSE FALSE FALSE
UNKNOWN UNKNOWN FALSE UNKNOWN
Table 7–7 OR Truth Table
OR TRUE FALSE UNKNOWN
TRUE TRUE TRUE TRUE
Model Conditions
Conditions 7-9
For example, the following query returns employees who have a 40% commission rate
or a salary greater than $20,000:
SELECT employee_id FROM employees
WHERE commission_pct = .4 OR salary > 20000
ORDER BY employee_id;
Model Conditions
Model conditions can be used only in the MODEL clause of a SELECT statement.
IS ANY Condition
The IS ANY condition can be used only in the model_clause of a SELECT statement.
Use this condition to qualify all values of a dimension column, including NULL.
is_any_condition::=
The condition always returns a Boolean value of TRUE in order to qualify all values of
the column.
Example
The following example sets sales for each product for year 2000 to 0:
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s[ANY, 2000] = 0
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 0
France Mouse Pad 2001 3269.09
France Standard Mouse 1998 2390.83
FALSE TRUE FALSE UNKNOWN
UNKNOWN TRUE UNKNOWN UNKNOWN
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for information
Table 7–7 (Cont.) OR Truth Table
OR TRUE FALSE UNKNOWN
dimension_column IS
ANY
Model Conditions
7-10 Oracle Database SQL Language Reference
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 0
France Standard Mouse 2001 2164.54
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 0
Germany Mouse Pad 2001 9535.08
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 0
Germany Standard Mouse 2001 6456.13
16 rows selected.
The preceding example requires the view sales_view_ref. Refer to "The MODEL
clause: Examples" on page 19-45 to create this view.
IS PRESENT Condition
is_present_condition::=
The IS PRESENT condition can be used only in the model_clause of a SELECT
statement. Use this condition to test whether the cell referenced is present prior to the
execution of the model_clause.
The condition returns TRUE if the cell exists prior to the execution of the model_
clause and FALSE if it does not.
Example
In the following example, if sales of the Mouse Pad for year 1999 exist, then sales of the
Mouse Pad for year 2000 is set to sales of the Mouse Pad for year 1999. Otherwise,
sales of the Mouse Pad for year 2000 is set to 0.
SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s['Mouse Pad', 2000] =
CASE WHEN s['Mouse Pad', 1999] IS PRESENT
THEN s['Mouse Pad', 1999]
ELSE 0
END
)
ORDER BY country, prod, year;
COUNTRY PROD YEAR S
---------- ----------------------------------- -------- ---------
See Also: model_clause on page 19-28 and "Model Expressions" on
page 6-11 for information
cell_reference IS PRESENT
Multiset Conditions
Conditions 7-11
France Mouse Pad 1998 2509.42
France Mouse Pad 1999 3678.69
France Mouse Pad 2000 3678.69
France Mouse Pad 2001 3269.09
France Standard Mouse 1998 2390.83
France Standard Mouse 1999 2280.45
France Standard Mouse 2000 1274.31
France Standard Mouse 2001 2164.54
Germany Mouse Pad 1998 5827.87
Germany Mouse Pad 1999 8346.44
Germany Mouse Pad 2000 8346.44
Germany Mouse Pad 2001 9535.08
Germany Standard Mouse 1998 7116.11
Germany Standard Mouse 1999 6263.14
Germany Standard Mouse 2000 2637.31
Germany Standard Mouse 2001 6456.13
16 rows selected.
The preceding example requires the view sales_view_ref. Refer to "The MODEL
clause: Examples" on page 19-45 to create this view.
Multiset Conditions
Multiset conditions test various aspects of nested tables.
IS A SET Condition
Use IS A SET conditions to test whether a specified nested table is composed of
unique elements. The condition returns NULL if the nested table is NULL. Otherwise, it
returns TRUE if the nested table is a set, even if it is a nested table of length zero, and
FALSE otherwise.
is_a_set_condition::=
Example
The following example selects from the table customers_demo those rows in which
the cust_address_ntab nested table column contains unique elements:
SELECT customer_id, cust_address_ntab
FROM customers_demo
WHERE cust_address_ntab IS A SET
ORDER BY customer_id;
CUSTOMER_ID CUST_ADDRESS_NTAB(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
----------------------------------------------------------------------------------------------
101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))
102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'))
103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))
104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'))
105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'))
The preceding example requires the table customers_demo and a nested table
column containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table column.
nested_table IS
NOT
A SET
Multiset Conditions
7-12 Oracle Database SQL Language Reference
IS EMPTY Condition
Use the IS [NOT] EMPTY conditions to test whether a specified nested table is empty.
A nested table that consists of a single value, a NULL, is not considered an empty
nested table.
is_empty_condition::=
The condition returns a Boolean value: TRUE for an IS EMPTY condition if the
collection is empty, and TRUE for an IS NOT EMPTY condition if the collection is not
empty. If you specify NULL for the nested table or varray, then the result is NULL.
Example
The following example selects from the sample table pm.print_media those rows in
which the ad_textdocs_ntab nested table column is not empty:
SELECT product_id, TO_CHAR(ad_finaltext) AS text
FROM print_media
WHERE ad_textdocs_ntab IS NOT EMPTY
ORDER BY product_id, text;
MEMBER Condition
member_condition::=
A member_condition is a membership condition that tests whether an element is a
member of a nested table. The return value is TRUE if expr is equal to a member of the
specified nested table or varray. The return value is NULL if expr is null or if the
nested table is empty.
■ expr must be of the same type as the element type of the nested table.
■ The OF keyword is optional and does not change the behavior of the condition.
■ The NOT keyword reverses the Boolean output: Oracle returns FALSE if expr is a
member of the specified nested table.
■ The element types of the nested table must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example selects from the table customers_demo those rows in which
the cust_address_ntab nested table column contains the values specified in the
WHERE clause:
SELECT customer_id, cust_address_ntab
FROM customers_demo
WHERE cust_address_typ('8768 N State Rd 37', 47404,
'Bloomington', 'IN', 'US')
MEMBER OF cust_address_ntab
ORDER BY customer_id;
CUSTOMER_ID CUST_ADDRESS_NTAB(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID)
nested_table IS
NOT
EMPTY
expr
NOT
MEMBER
OF
nested_table
Multiset Conditions
Conditions 7-13
------------ ---------------------------------------------------------------------------------
103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))
The preceding example requires the table customers_demo and a nested table
column containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table column.
SUBMULTISET Condition
The SUBMULTISET condition tests whether a specified nested table is a submultiset of
another specified nested table.
The operator returns a Boolean value. TRUE is returned when nested_table1 is a
submultiset of nested_table2. nested_table1 is a submultiset of nested_
table2 when one of the following conditions occur:
■ nested_table1 is not null and contains no rows. TRUE is returned even if
nested_table2 is null since an empty multiset is a submultiset of any non-null
replacement for nested_table2.
■ nested_table1 and nested_table2 are not null, nested_table1 does not
contain a null element, and there is a one-to-one mapping of each element in
nested_table1 to an equal element in nested_table2.
NULL is returned when one of the following conditions occurs:
■ nested_table1 is null.
■ nested_table2 is null, and nested_table1 is not null and not empty.
■ nested_table1 is a submultiset of nested_table2 after modifying each null
element of nested_table1 and nested_table2 to some non-null value,
enabling a one-to-one mapping of each element in nested_table1 to an equal
element in nested_table2.
If none of the above conditions occur, then FALSE is returned.
submultiset_condition::=
■ The OF keyword is optional and does not change the behavior of the operator.
■ The NOT keyword reverses the Boolean output: Oracle returns FALSE if nested_
table1 is a subset of nested_table2.
■ The element types of the nested table must be comparable. Refer to "Comparison
Conditions" on page 7-4 for information on the comparability of nonscalar types.
Example
The following example selects from the customers_demo table those rows in which
the cust_address_ntab nested table is a submultiset of the cust_address2_ntab
nested table:
SELECT customer_id, cust_address_ntab
FROM customers_demo
WHERE cust_address_ntab SUBMULTISET OF cust_address2_ntab
ORDER BY customer_id;
nested_table1
NOT
SUBMULTISET
OF
nested_table2
Pattern-matching Conditions
7-14 Oracle Database SQL Language Reference
The preceding example requires the table customers_demo and two nested table
columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table
and nested table columns.
Pattern-matching Conditions
The pattern-matching conditions compare character data.
LIKE Condition
The LIKE conditions specify a test involving pattern matching. Whereas the equality
operator (=) exactly matches one character value to another, the LIKE conditions
match a portion of one character value to another by searching the first value for the
pattern specified by the second. LIKE calculates strings using characters as defined by
the input character set. LIKEC uses Unicode complete characters. LIKE2 uses UCS2
code points. LIKE4 uses UCS4 code points.
like_condition::=
In this syntax:
■ char1 is a character expression, such as a character column, called the search
value.
■ char2 is a character expression, usually a literal, called the pattern.
■ esc_char is a character expression, usually a literal, called the escape character.
The LIKE condition is the best choice in almost all situations. Use the following
guidelines to determine whether any of the variations would be helpful in your
environment:
■ Use LIKE2 to process strings using UCS-2 semantics. LIKE2 treats a Unicode
supplementary character as two characters.
■ Use LIKE4 to process strings using UCS-4 semantics. LIKE4 treats a Unicode
supplementary character as one character.
■ Use LIKEC to process strings using Unicode complete character semantics. LIKEC
treats a composite character as one character.
If esc_char is not specified, then there is no default escape character. If any of char1,
char2, or esc_char is null, then the result is unknown. Otherwise, the escape
character, if specified, must be a character string of length 1.
All of the character expressions (char1, char2, and esc_char) can be of any of the
data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. If they differ, then Oracle
converts all of them to the data type of char1.
The pattern can contain special pattern-matching characters:
■ An underscore (_) in the pattern matches exactly one character (as opposed to one
byte in a multibyte character set) in the value.
char1
NOT
LIKE
LIKEC
LIKE2
LIKE4
char2
ESCAPE esc_char
Pattern-matching Conditions
Conditions 7-15
■ A percent sign (%) in the pattern can match zero or more characters (as opposed to
bytes in a multibyte character set) in the value. The pattern '%' cannot match a
null.
You can include the actual characters % or _ in the pattern by using the ESCAPE clause,
which identifies the escape character. If the escape character precedes the character %
or _ in the pattern, then Oracle interprets this character literally in the pattern rather
than as a special pattern-matching character. You can also search for the escape
character itself by repeating it. For example, if @ is the escape character, then you can
use @@ to search for @.
Table 7–8 describes the LIKE conditions.
To process the LIKE conditions, Oracle divides the pattern into subpatterns consisting
of one or two characters each. The two-character subpatterns begin with the escape
character and the other character is %, or _, or the escape character.
Let P1, P2, ..., Pn be these subpatterns. The like condition is true if there is a way to
partition the search value into substrings S1, S2, ..., Sn so that for all i between 1 and n:
■ If Pi is _, then Si is a single character.
■ If Pi is %, then Si is any string.
■ If Pi is two characters beginning with an escape character, then Si is the second
character of Pi.
■ Otherwise, Pi = Si.
With the LIKE conditions, you can compare a value to a pattern rather than to a
constant. The pattern must appear after the LIKE keyword. For example, you can issue
the following query to find the salaries of all employees with names beginning with R:
SELECT salary
FROM employees
WHERE last_name LIKE 'R%'
ORDER BY salary;
The following query uses the = operator, rather than the LIKE condition, to find the
salaries of all employees with the name 'R%':
SELECT salary
FROM employees
WHERE last_name = 'R%'
ORDER BY salary;
Table 7–8 LIKE Condition
Type of
Condition Operation Example
x [NOT]
LIKE y
[ESCAPE
'z']
TRUE if x does [not] match the pattern
y. Within y, the character % matches any
string of zero or more characters except
null. The character _ matches any single
character. Any character can follow
ESCAPE except percent (%) and
underbar (_). A wildcard character is
treated as a literal if preceded by the
escape character.
SELECT last_name
FROM employees
WHERE last_name
LIKE '%A_B%' ESCAPE ''
ORDER BY last_name;
Pattern-matching Conditions
7-16 Oracle Database SQL Language Reference
The following query finds the salaries of all employees with the name 'SM%'. Oracle
interprets 'SM%' as a text literal, rather than as a pattern, because it precedes the LIKE
keyword:
SELECT salary
FROM employees
WHERE 'SM%' LIKE last_name
ORDER BY salary;
Case Sensitivity
Case is significant in all conditions comparing character expressions that use the LIKE
condition and the equality (=) operators. You can perform case or accent insensitive
LIKE searches by setting the NLS_SORT and the NLS_COMP session parameters.
Pattern Matching on Indexed Columns
When you use LIKE to search an indexed column for a pattern, Oracle can use the
index to improve performance of a query if the leading character in the pattern is not %
or _. In this case, Oracle can scan the index by this leading character. If the first
character in the pattern is % or _, then the index cannot improve performance because
Oracle cannot scan the index.
LIKE Condition: General Examples
This condition is true for all last_name values beginning with Ma:
last_name LIKE 'Ma%'
All of these last_name values make the condition true:
Mallin, Markle, Marlow, Marvins, Marvis, Matos
Case is significant, so last_name values beginning with MA, ma, and mA make the
condition false.
Consider this condition:
last_name LIKE 'SMITH_'
This condition is true for these last_name values:
SMITHE, SMITHY, SMITHS
This condition is false for SMITH because the special underscore character (_) must
match exactly one character of the last_name value.
ESCAPE Clause Example The following example searches for employees with the
pattern A_B in their name:
SELECT last_name
FROM employees
WHERE last_name LIKE '%A_B%' ESCAPE ''
ORDER BY last_name;
The ESCAPE clause identifies the backslash () as the escape character. In the pattern,
the escape character precedes the underscore (_). This causes Oracle to interpret the
underscore literally, rather than as a special pattern matching character.
See Also: Oracle Database Globalization Support Guide for more
information on this case- and accent-insensitive linguistic sorts
Pattern-matching Conditions
Conditions 7-17
Patterns Without % Example If a pattern does not contain the % character, then the
condition can be true only if both operands have the same length. Consider the
definition of this table and the values inserted into it:
CREATE TABLE ducks (f CHAR(6), v VARCHAR2(6));
INSERT INTO ducks VALUES ('DUCK', 'DUCK');
SELECT '*'||f||'*' "char",
'*'||v||'*' "varchar"
FROM ducks;
char varchar
-------- --------
*DUCK * *DUCK*
Because Oracle blank-pads CHAR values, the value of f is blank-padded to 6 bytes. v is
not blank-padded and has length 4.
REGEXP_LIKE Condition
REGEXP_LIKE is similar to the LIKE condition, except REGEXP_LIKE performs
regular expression matching instead of the simple pattern matching performed by
LIKE. This condition evaluates strings using characters as defined by the input
character set.
This condition complies with the POSIX regular expression standard and the Unicode
Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle
Regular Expression Support".
regexp_like_condition::=
■ source_char is a character expression that serves as the search value. It is
commonly a character column and can be of any of the data types CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
■ pattern is the regular expression. It is usually a text literal and can be of any of
the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512
bytes. If the data type of pattern is different from the data type of source_
char, Oracle converts pattern to the data type of source_char. For a listing of
the operators you can specify in pattern, refer to Appendix D, "Oracle Regular
Expression Support".
■ match_parameter is a text literal that lets you change the default matching
behavior of the function. You can specify one or more of the following values for
match_parameter:
– 'i' specifies case-insensitive matching.
– 'c' specifies case-sensitive matching.
– 'n' allows the period (.), which is the match-any-character wildcard character,
to match the newline character. If you omit this parameter, then the period
does not match the newline character.
– 'm' treats the source string as multiple lines. Oracle interprets ^ and $ as the
start and end, respectively, of any line anywhere in the source string, rather
than only at the start or end of the entire source string. If you omit this
parameter, then Oracle treats the source string as a single line.
REGEXP_LIKE ( source_char , pattern
, match_param
)
Pattern-matching Conditions
7-18 Oracle Database SQL Language Reference
– 'x' ignores whitespace characters. By default, whitespace characters match
themselves.
If you specify multiple contradictory values, then Oracle uses the last value. For
example, if you specify 'ic', then Oracle uses case-sensitive matching. If you
specify a character other than those shown above, then Oracle returns an error.
If you omit match_parameter, then:
– The default case sensitivity is determined by the value of the NLS_SORT
parameter.
– A period (.) does not match the newline character.
– The source string is treated as a single line.
Examples
The following query returns the first and last names for those employees with a first
name of Steven or Stephen (where first_name begins with Ste and ends with en
and in between is either v or ph):
SELECT first_name, last_name
FROM employees
WHERE REGEXP_LIKE (first_name, '^Ste(v|ph)en$')
ORDER BY first_name, last_name;
FIRST_NAME LAST_NAME
-------------------- -------------------------
Steven King
Steven Markle
Stephen Stiles
The following query returns the last name for those employees with a double vowel in
their last name (where last_name contains two adjacent occurrences of either a, e, i,
o, or u, regardless of case):
SELECT last_name
FROM employees
WHERE REGEXP_LIKE (last_name, '([aeiou])1', 'i')
ORDER BY last_name;
LAST_NAME
-------------------------
De Haan
Greenberg
Khoo
Gee
Greene
Lee
Bloom
Feeney
See Also:
■ "LIKE Condition" on page 7-14
■ REGEXP_INSTR on page 5-160, REGEXP_REPLACE on
page 5-162, and REGEXP_SUBSTR on page 5-164 for functions
that provide regular expression support
XML Conditions
Conditions 7-19
Null Conditions
A NULL condition tests for nulls. This is the only condition that you should use to test
for nulls.
null_condition::=
Table 7–9 lists the null conditions.
XML Conditions
XML conditions determines whether a specified XML resource can be found in a
specified path.
EQUALS_PATH Condition
The EQUALS_PATH condition determines whether a resource in the Oracle XML
database can be found in the database at a specified path.
Use this condition in queries to RESOURCE_VIEW and PATH_VIEW. These public views
provide a mechanism for SQL access to data stored in the XML database repository.
RESOURCE_VIEW contains one row for each resource in the repository, and PATH_
VIEW contains one row for each unique path in the repository.
equals_path_condition::=
This condition applies only to the path as specified. It is similar to but more restrictive
than UNDER_PATH.
For path_string, specify the (absolute) path name to resolve. This can contain
components that are hard or weak resource links.
The optional correlation_integer argument correlates the EQUALS_PATH
condition with its ancillary functions DEPTH and PATH.
Example
The view RESOURCE_VIEW computes the paths (in the any_path column) that lead to
all XML resources (in the res column) in the database repository. The following
Table 7–9 Null Condition
Type of
Condition Operation Example
IS [NOT]
NULL
Tests for nulls.
See Also: "Nulls" on page 3-70
SELECT last_name
FROM employees
WHERE commission_pct
IS NULL
ORDER BY last_name;
See Also: UNDER_PATH Condition on page 7-20, DEPTH on
page 5-63, and PATH on page 5-131
expr IS
NOT
NULL
EQUALS_PATH ( column , path_string
, correlation_integer
)
Compound Conditions
7-20 Oracle Database SQL Language Reference
example queries the RESOURCE_VIEW view to find the paths to the resources in the
sample schema oe. The EQUALS_PATH condition causes the query to return only the
specified path:
SELECT ANY_PATH FROM RESOURCE_VIEW
WHERE EQUALS_PATH(res, '/sys/schemas/OE/www.example.com')=1;
ANY_PATH
-----------------------------------------------
/sys/schemas/OE/www.example.com
Compare this example with that for UNDER_PATH Condition on page 7-20.
UNDER_PATH Condition
The UNDER_PATH condition determines whether resources specified in a column can
be found under a particular path specified by path_string in the Oracle XML
database repository. The path information is computed by the RESOURCE_VIEW view,
which you query to use this condition.
Use this condition in queries to RESOURCE_VIEW and PATH_VIEW. These public views
provide a mechanism for SQL access to data stored in the XML database repository.
RESOURCE_VIEW contains one row for each resource in the repository, and PATH_
VIEW contains one row for each unique path in the repository.
under_path_condition::=
The optional levels argument indicates the number of levels down from path_
string Oracle should search. For levels, specify any nonnegative integer.
The optional correlation_integer argument correlates the UNDER_PATH
condition with its ancillary functions PATH and DEPTH.
Example
The view RESOURCE_VIEW computes the paths (in the any_path column) that lead to
all XML resources (in the res column) in the database repository. The following
example queries the RESOURCE_VIEW view to find the paths to the resources in the
sample schema oe. The query returns the path of the XML schema that was created in
"XMLType Table Examples" on page 16-73:
SELECT ANY_PATH FROM RESOURCE_VIEW
WHERE UNDER_PATH(res, '/sys/schemas/OE/www.example.com')=1;
ANY_PATH
----------------------------------------------
/sys/schemas/OE/www.example.com/xwarehouses.xsd
Compound Conditions
A compound condition specifies a combination of other conditions.
See Also: The related condition EQUALS_PATH Condition on
page 7-19 and the ancillary functions DEPTH on page 5-63 and PATH
on page 5-131
UNDER_PATH ( column
, levels
, path_string
, correlation_integer
)
BETWEEN Condition
Conditions 7-21
compound_condition::=
BETWEEN Condition
A BETWEEN condition determines whether the value of one expression is in an interval
defined by two other expressions.
between_condition::=
All three expressions must be numeric, character, or datetime expressions. In SQL, it is
possible that expr1 will be evaluated more than once. If the BETWEEN expression
appears in PL/SQL, expr1 is guaranteed to be evaluated only once. If the expressions
are not all the same data type, then Oracle Database implicitly converts the
expressions to a common data type. If it cannot do so, then it returns an error.
The value of
expr1 NOT BETWEEN expr2 AND expr3
is the value of the expression
NOT (expr1 BETWEEN expr2 AND expr3)
And the value of
expr1 BETWEEN expr2 AND expr3
is the value of the boolean expression:
expr2 <= expr1 AND expr1 <= expr3
If expr3 < expr2, then the interval is empty. If expr1 is NULL, then the result is
NULL. If expr1 is not NULL, then the value is FALSE in the ordinary case and TRUE
when the keyword NOT is used.
The boolean operator AND may produce unexpected results. Specifically, in the
expression x AND y, the condition x IS NULL is not sufficient to determine the value
See Also: "Logical Conditions" on page 7-7 for more information
about NOT, AND, and OR conditions
Note: The implicit data type conversion rules for PL/SQL are
different from those for SQL. For more information, see Oracle
Database PL/SQL Language Reference.
See Also: "Implicit Data Conversion" on page 3-40 for more
information on SQL data type conversion
( condition )
NOT condition
condition
AND
OR
condition
expr1
NOT
BETWEEN expr2 AND expr3
EXISTS Condition
7-22 Oracle Database SQL Language Reference
of the expression. The second operand still must be evaluated. The result is FALSE if
the second operand has the value FALSE and NULL otherwise. See "Logical
Conditions" on page 7-7 for more information on AND.
EXISTS Condition
An EXISTS condition tests for existence of rows in a subquery.
Table 7–11 shows the EXISTS condition.
IN Condition
An in_condition is a membership condition. It tests a value for membership in a
list of values or subquery
in_condition::=
Table 7–10 BETWEEN Condition
Type of
Condition Operation Example
[NOT]
BETWEEN x
AND y
[NOT] (expr2 less than or equal to
expr1 AND expr1 less than or
equal to expr3)
SELECT * FROM employees
WHERE salary
BETWEEN 2000 AND 3000
ORDER BY employee_id;
Table 7–11 EXISTS Condition
Type of
Condition Operation Example
EXISTS TRUE if a subquery returns at
least one row.
SELECT department_id
FROM departments d
WHERE EXISTS
(SELECT * FROM employees e
WHERE d.department_id
= e.department_id)
ORDER BY department_id;
EXISTS ( subquery )
expr
NOT
IN (
expression_list
subquery
)
( expr
,
)
NOT
IN (
expression_list
,
subquery
)
IN Condition
Conditions 7-23
expression_list::=
If you use the upper form of the in_condition condition (with a single expression to
the left of the operator), then you must use the upper form of expression_list. If
you use the lower form of this condition (with multiple expressions to the left of the
operator), then you must use the lower form of expression_list, and the
expressions in each expression_list must match in number and data type the
expressions to the left of the operator. You can specify up to 1000 expressions in
expression_list.
Oracle Database does not always evaluate the expressions in an expression_list in
the order in which they appear in the IN list. However, expressions in the select list of
a subquery are evaluated in their specified order.
Table 7–12 lists the form of IN condition.
If any item in the list following a NOT IN operation evaluates to null, then all rows
evaluate to FALSE or UNKNOWN, and no rows are returned. For example, the following
statement returns the string 'True' for each row:
SELECT 'True' FROM employees
WHERE department_id NOT IN (10, 20);
However, the following statement returns no rows:
See Also: "Expression Lists" on page 6-16
Table 7–12 IN Condition
Type of Condition Operation Example
IN Equal-to-any-member-of test.
Equivalent to =ANY.
SELECT * FROM employees
WHERE job_id IN
('PU_CLERK','SH_CLERK')
ORDER BY employee_id;
SELECT * FROM employees
WHERE salary IN
(SELECT salary
FROM employees
WHERE department_id =30)
ORDER BY employee_id;
NOT IN Equivalent to !=ALL. Evaluates
to FALSE if any member of the
set is NULL.
SELECT * FROM employees
WHERE salary NOT IN
(SELECT salary
FROM employees
WHERE department_id = 30)
ORDER BY employee_id;
SELECT * FROM employees
WHERE job_id NOT IN
('PU_CLERK', 'SH_CLERK')
ORDER BY employee_id;
expr
,
(
expr
,
IS OF type Condition
7-24 Oracle Database SQL Language Reference
SELECT 'True' FROM employees
WHERE department_id NOT IN (10, 20, NULL);
The preceding example returns no rows because the WHERE clause condition evaluates
to:
department_id != 10 AND department_id != 20 AND department_id != null
Because the third condition compares department_id with a null, it results in an
UNKNOWN, so the entire expression results in FALSE (for rows with department_id
equal to 10 or 20). This behavior can easily be overlooked, especially when the NOT IN
operator references a subquery.
Moreover, if a NOT IN condition references a subquery that returns no rows at all, then
all rows will be returned, as shown in the following example:
SELECT 'True' FROM employees
WHERE department_id NOT IN (SELECT 0 FROM DUAL WHERE 1=2);
Restriction on LEVEL in WHERE Clauses In a [NOT] IN condition in a WHERE clause,
if the right-hand side of the condition is a subquery, you cannot use LEVEL on the
left-hand side of the condition. However, you can specify LEVEL in a subquery of the
FROM clause to achieve the same result. For example, the following statement is not
valid:
SELECT employee_id, last_name FROM employees
WHERE (employee_id, LEVEL)
IN (SELECT employee_id, 2 FROM employees)
START WITH employee_id = 2
CONNECT BY PRIOR employee_id = manager_id;
But the following statement is valid because it encapsulates the query containing the
LEVEL information in the FROM clause:
SELECT v.employee_id, v.last_name, v.lev FROM
(SELECT employee_id, last_name, LEVEL lev
FROM employees v
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id) v
WHERE (v.employee_id, v.lev) IN
(SELECT employee_id, 2 FROM employees);
IS OF type Condition
Use the IS OF type condition to test object instances based on their specific type
information.
is_of_type_condition::=
You must have EXECUTE privilege on all types referenced by type, and all types
must belong to the same type family.
This condition evaluates to null if expr is null. If expr is not null, then the condition
evaluates to true (or false if you specify the NOT keyword) under either of these
circumstances:
expr IS
NOT
OF
TYPE
(
ONLY schema .
type
,
)
IS OF type Condition
Conditions 7-25
■ The most specific type of expr is the subtype of one of the types specified in the
type list and you have not specified ONLY for the type, or
■ The most specific type of expr is explicitly specified in the type list.
The expr frequently takes the form of the VALUE function with a correlation variable.
The following example uses the sample table oe.persons, which is built on a type
hierarchy in "Substitutable Table and Column Examples" on page 16-69. The example
uses the IS OF type condition to restrict the query to specific subtypes:
SELECT * FROM persons p
WHERE VALUE(p) IS OF TYPE (employee_t);
NAME SSN
----------------------------
Joe 32456
Tim 5678
SELECT * FROM persons p
WHERE VALUE(p) IS OF (ONLY part_time_emp_t);
NAME SSN
----------------------------
Tim 5678
IS OF type Condition
7-26 Oracle Database SQL Language Reference
8
Common SQL DDL Clauses 8-1
8 Common SQL DDL Clauses
This chapter describes some SQL data definition clauses that appear in multiple SQL
statements.
This chapter contains these sections:
■ allocate_extent_clause
■ constraint
■ deallocate_unused_clause
■ file_specification
■ logging_clause
■ parallel_clause
■ physical_attributes_clause
■ size_clause
■ storage_clause
allocate_extent_clause
8-2 Oracle Database SQL Language Reference
allocate_extent_clause
Purpose
Use the allocate_extent_clause clause to explicitly allocate a new extent for a
database object.
Explicitly allocating an extent with this clause does not change the values of the NEXT
and PCTINCREASE storage parameters, so does not affect the size of the next extent to
be allocated implicitly by Oracle Database. Refer to storage_clause on page 8-48 for
information about the NEXT and PCTINCREASE storage parameters.
You can allocate an extent in the following SQL statements:
■ ALTER CLUSTER (see ALTER CLUSTER on page 10-5)
■ ALTER INDEX: to allocate an extent to the index, an index partition, or an index
subpartition (see ALTER INDEX on page 10-77)
■ ALTER MATERIALIZED VIEW: to allocate an extent to the materialized view, one of
its partitions or subpartitions, or the overflow segment of an index-organized
materialized view (see ALTER MATERIALIZED VIEW on page 11-3)
■ ALTER MATERIALIZED VIEW LOG (see ALTER MATERIALIZED VIEW LOG on
page 11-18)
■ ALTER TABLE: to allocate an extent to the table, a table partition, a table
subpartition, the mapping table of an index-organized table, the overflow segment
of an index-organized table, or a LOB storage segment (see ALTER TABLE on
page 12-2)
Syntax
allocate_extent_clause::=
(size_clause::= on page 8-47)
Semantics
This section describes the parameters of the allocate_extent_clause. For
additional information, refer to the SQL statement in which you set or reset these
parameters for a particular database object.
You cannot specify the allocate_extent_clause and the deallocate_unused_
clause in the same statement.
SIZE
Specify the size of the extent in bytes. The value of integer can be 0 through
2147483647. To specify a larger extent size, use an integer within this range with K, M,
G, or T to specify the extent size in kilobytes, megabytes, gigabytes, or terabytes.
ALLOCATE EXTENT
(
SIZE size_clause
DATAFILE ’ filename ’
INSTANCE integer
)
allocate_extent_clause
Common SQL DDL Clauses 8-3
For a table, index, materialized view, or materialized view log, if you omit SIZE, then
Oracle Database determines the size based on the values of the storage parameters of
the object. However, for a cluster, Oracle does not evaluate the cluster's storage
parameters, so you must specify SIZE if you do not want Oracle to use a default
value.
DATAFILE 'filename'
Specify one of the data files in the tablespace of the table, cluster, index, materialized
view, or materialized view log to contain the new extent. If you omit DATAFILE, then
Oracle chooses the data file.
INSTANCE integer
Use this parameter only if you are using Oracle Real Application Clusters.
Specifying INSTANCE integer makes the new extent available to the freelist group
associated with the specified instance. If the instance number exceeds the maximum
number of freelist groups, then Oracle divides the specified number by the maximum
number and uses the remainder to identify the freelist group to be used. An instance is
identified by the value of its initialization parameter INSTANCE_NUMBER.
If you omit this parameter, then the space is allocated to the table, cluster, index,
materialized view, or materialized view log but is not drawn from any particular
freelist group. Instead, Oracle uses the master freelist and allocates space as needed.
Note: If you are using automatic segment-space management, then
the INSTANCE parameter of the allocate_extent_clause may
not reserve the newly allocated space for the specified instance,
because automatic segment-space management does not maintain
rigid affinity between extents and instances.
constraint
8-4 Oracle Database SQL Language Reference
constraint
Purpose
Use a constraint to define an integrity constraint—a rule that restricts the values in
a database. Oracle Database lets you create six types of constraints and lets you declare
them in two ways.
The six types of integrity constraint are described briefly here and more fully in
"Semantics" on page 8-8:
■ A NOT NULL constraint prohibits a database value from being null.
■ A unique constraint prohibits multiple rows from having the same value in the
same column or combination of columns but allows some values to be null.
■ A primary key constraint combines a NOT NULL constraint and a unique
constraint in a single declaration. It prohibits multiple rows from having the same
value in the same column or combination of columns and prohibits values from
being null.
■ A foreign key constraint requires values in one table to match values in another
table.
■ A check constraint requires a value in the database to comply with a specified
condition.
■ A REF column by definition references an object in another object type or in a
relational table. A REF constraint lets you further describe the relationship
between the REF column and the object it references.
You can define constraints syntactically in two ways:
■ As part of the definition of an individual column or attribute. This is called inline
specification.
■ As part of the table definition. This is called out-of-line specification.
NOT NULL constraints must be declared inline. All other constraints can be declared
either inline or out of line.
Constraint clauses can appear in the following statements:
■ CREATE TABLE (see CREATE TABLE on page 16-6)
■ ALTER TABLE (see ALTER TABLE on page 12-2)
■ CREATE VIEW (see CREATE VIEW on page 17-14)
■ ALTER VIEW (see ALTER VIEW on page 13-12)
View Constraints Oracle Database does not enforce view constraints. However, you
can enforce constraints on views through constraints on base tables.
You can specify only unique, primary key, and foreign key constraints on views, and
they are supported only in DISABLE NOVALIDATE mode. You cannot define view
constraints on attributes of an object column.
See Also: "View Constraints" on page 8-18 for additional
information on view constraints and "DISABLE Clause" on page 8-16
for information on DISABLE NOVALIDATE mode
constraint
Common SQL DDL Clauses 8-5
Prerequisites
You must have the privileges necessary to issue the statement in which you are
defining the constraint.
To create a foreign key constraint, in addition, the parent table or view must be in your
own schema or you must have the REFERENCES privilege on the columns of the
referenced key in the parent table or view.
Syntax
constraint::=
(inline_constraint::= on page 8-5, out_of_line_constraint::= on page 8-5, inline_ref_
constraint::= on page 8-6, out_of_line_ref_constraint::= on page 8-6)
inline_constraint::=
(references_clause::= on page 8-6)
out_of_line_constraint::=
(references_clause::= on page 8-6, constraint_state::= on page 8-6)
inline_constraint
out_of_line_constraint
inline_ref_constraint
out_of_line_ref_constraint
CONSTRAINT constraint_name
NOT
NULL
UNIQUE
PRIMARY KEY
references_clause
CHECK ( condition )
constraint_state
CONSTRAINT constraint_name
UNIQUE ( column
,
)
PRIMARY KEY ( column
,
)
FOREIGN KEY ( column
,
) references_clause
CHECK ( condition )
constraint_state
constraint
8-6 Oracle Database SQL Language Reference
inline_ref_constraint::=
(references_clause::= on page 8-6, constraint_state::= on page 8-6)
out_of_line_ref_constraint::=
(references_clause::= on page 8-6, constraint_state::= on page 8-6)
references_clause::=
constraint_state::=
(using_index_clause::= on page 8-7, exceptions_clause::= on page 8-8)
SCOPE IS
schema .
scope_table
WITH ROWID
CONSTRAINT constraint_name
references_clause
constraint_state
SCOPE FOR (
ref_col
ref_attr
) IS
schema .
scope_table
REF (
ref_col
ref_attr
) WITH ROWID
CONSTRAINT constraint_name
FOREIGN KEY (
ref_col
ref_attr
) references_clause
constraint_state
REFERENCES
schema .
object
( column )
ON DELETE
CASCADE
SET NULL
NOT
DEFERRABLE
INITIALLY
IMMEDIATE
DEFERRED
RELY
NORELY
using_index_clause
ENABLE
DISABLE
VALIDATE
NOVALIDATE
exceptions_clause
constraint
Common SQL DDL Clauses 8-7
using_index_clause::=
(create_index::= on page 14-62, index_properties::= on page 8-7)
index_properties::=
(global_partitioned_index::= on page 14-65, local_partitioned_index::= on page 14-66--part
of CREATE INDEX, index_attributes::= on page 8-7. The INDEXTYPE IS ... clause is not
valid when defining a constraint.)
index_attributes::=
(physical_attributes_clause::= on page 14-3, logging_clause::= on page 8-38, key_
compression::= on page 14-64--all part of CREATE INDEX, parallel_clause: not
supported in using_index_clause)
USING INDEX
schema .
index
( create_index_statement )
index_properties
global_partitioned_index
local_partitioned_index
index_attributes
INDEXTYPE IS
domain_index_clause
XMLIndex_clause
physical_attributes_clause
logging_clause
ONLINE
TABLESPACE
tablespace
DEFAULT
key_compression
SORT
NOSORT
REVERSE
VISIBLE
INVISIBLE
parallel_clause
constraint
8-8 Oracle Database SQL Language Reference
exceptions_clause::=
Semantics
This section describes the semantics of constraint. For additional information, refer
to the SQL statement in which you define or redefine a constraint for a table or view.
Oracle Database does not support constraints on columns or attributes whose type is a
user-defined object, nested table, VARRAY, REF, or LOB, with two exceptions:
■ NOT NULL constraints are supported for a column or attribute whose type is
user-defined object, VARRAY, REF, or LOB.
■ NOT NULL, foreign key, and REF constraints are supported on a column of type
REF.
CONSTRAINT constraint_name Specify a name for the constraint. If you omit this
identifier, then Oracle Database generates a name with the form SYS_Cn. Oracle stores
the name and the definition of the integrity constraint in the USER_, ALL_, and DBA_
CONSTRAINTS data dictionary views (in the CONSTRAINT_NAME and SEARCH_
CONDITION columns, respectively).
NOT NULL Constraints
A NOT NULL constraint prohibits a column from containing nulls. The NULL keyword
by itself does not actually define an integrity constraint, but you can specify it to
explicitly permit a column to contain nulls. You must define NOT NULL and NULL
using inline specification. If you specify neither NOT NULL nor NULL, then the default
is NULL.
NOT NULL constraints are the only constraints you can specify inline on XMLType and
VARRAY columns.
To satisfy a NOT NULL constraint, every row in the table must contain a value for the
column.
Restrictions on NOT NULL Constraints NOT NULL constraints are subject to the
following restrictions:
■ You cannot specify NULL or NOT NULL in a view constraint.
■ You cannot specify NULL or NOT NULL for an attribute of an object. Instead, use a
CHECK constraint with the IS [NOT] NULL condition.
See Also: Oracle Database Reference for information on the data
dictionary views
Note: Oracle Database does not index table rows in which all key
columns are null except in the case of bitmap indexes. Therefore, if
you want an index on all rows of a table, then you must either specify
NOT NULL constraints for at least one of the index key columns or
create a bitmap index.
See Also: "Attribute-Level Constraints Example" on page 8-25 and
"NOT NULL Example" on page 8-21
EXCEPTIONS INTO
schema .
table
constraint
Common SQL DDL Clauses 8-9
Unique Constraints
A unique constraint designates a column as a unique key. A composite unique key
designates a combination of columns as the unique key. When you define a unique
constraint inline, you need only the UNIQUE keyword. When you define a unique
constraint out of line, you must also specify one or more columns. You must define a
composite unique key out of line.
To satisfy a unique constraint, no two rows in the table can have the same value for the
unique key. However, the unique key made up of a single column can contain nulls. To
satisfy a composite unique key, no two rows in the table or view can have the same
combination of values in the key columns. Any row that contains nulls in all key
columns automatically satisfies the constraint. However, two rows that contain nulls
for one or more key columns and the same combination of values for the other key
columns violate the constraint.
When you specify a unique constraint on one or more columns, Oracle implicitly
creates an index on the unique key. If you are defining uniqueness for purposes of
query performance, then Oracle recommends that you instead create the unique index
explicitly using a CREATE UNIQUE INDEX statement. You can also use the CREATE
UNIQUE INDEX statement to create a unique function-based index that defines a
conditional unique constraint. See "Using a Function-based Index to Define
Conditional Uniqueness: Example" on page 14-83 for more information.
Restrictions on Unique Constraints Unique constraints are subject to the following
restrictions:
■ None of the columns in the unique key can be of LOB, LONG, LONG RAW, VARRAY,
NESTED TABLE, OBJECT, REF, TIMESTAMP WITH TIME ZONE, or user-defined
type. However, the unique key can contain a column of TIMESTAMP WITH LOCAL
TIME ZONE.
■ A composite unique key cannot have more than 32 columns.
■ You cannot designate the same column or combination of columns as both a
primary key and a unique key.
■ You cannot specify a unique key when creating a subview in an inheritance
hierarchy. The unique key can be specified only for the top-level (root) view.
Primary Key Constraints
A primary key constraint designates a column as the primary key of a table or view. A
composite primary key designates a combination of columns as the primary key.
When you define a primary key constraint inline, you need only the PRIMARY KEY
keywords. When you define a primary key constraint out of line, you must also
specify one or more columns. You must define a composite primary key out of line.
To satisfy a primary key constraint:
■ No primary key value can appear in more than one row in the table.
■ No column that is part of the primary key can contain a null.
When you create a primary key constraint:
■ Oracle Database uses an existing index if it contains a unique set of values before
enforcing the primary key constraint. The existing index can be defined as unique
See Also: "Unique Key Example" on page 8-19 and Composite
Unique Key Example on page 8-20
constraint
8-10 Oracle Database SQL Language Reference
or nonunique. When a DML operation is performed, the primary key constraint is
enforced using this existing index.
■ If no existing index can be used, then Oracle Database generates a unique index.
When you drop a primary key constraint:
■ If the primary key was created using an existing index, then the index is not
dropped.
■ If the primary key was created using a system-generated index, then the index is
dropped.
Restrictions on Primary Key Constraints Primary constraints are subject to the
following restrictions:
■ A table or view can have only one primary key.
■ None of the columns in the primary key can be LOB, LONG, LONG RAW, VARRAY,
NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type.
However, the primary key can contain a column of TIMESTAMP WITH LOCAL
TIME ZONE.
■ The size of the primary key cannot exceed approximately one database block.
■ A composite primary key cannot have more than 32 columns.
■ You cannot designate the same column or combination of columns as both a
primary key and a unique key.
■ You cannot specify a primary key when creating a subview in an inheritance
hierarchy. The primary key can be specified only for the top-level (root) view.
Foreign Key Constraints
A foreign key constraint (also called a referential integrity constraint) designates a
column as the foreign key and establishes a relationship between that foreign key and
a specified primary or unique key, called the referenced key. A composite foreign key
designates a combination of columns as the foreign key.
The table or view containing the foreign key is called the child object, and the table or
view containing the referenced key is called the parent object. The foreign key and the
referenced key can be in the same table or view. In this case, the parent and child tables
are the same. If you identify only the parent table or view and omit the column name,
then the foreign key automatically references the primary key of the parent table or
view. The corresponding column or columns of the foreign key and the referenced key
must match in order and data type.
You can define a foreign key constraint on a single key column either inline or out of
line. You must specify a composite foreign key and a foreign key on an attribute out of
line.
To satisfy a composite foreign key constraint, the composite foreign key must refer to a
composite unique key or a composite primary key in the parent table or view, or the
value of at least one of the columns of the foreign key must be null.
You can designate the same column or combination of columns as both a foreign key
and a primary or unique key. You can also designate the same column or combination
of columns as both a foreign key and a cluster key.
See Also: "Primary Key Example" on page 8-20 and "Composite
Primary Key Example" on page 8-21
constraint
Common SQL DDL Clauses 8-11
You can define multiple foreign keys in a table or view. Also, a single column can be
part of more than one foreign key.
Restrictions on Foreign Key Constraints Foreign key constraints are subject to the
following restrictions:
■ None of the columns in the foreign key can be of LOB, LONG, LONG RAW, VARRAY,
NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type.
However, the primary key can contain a column of TIMESTAMP WITH LOCAL
TIME ZONE.
■ The referenced unique or primary key constraint on the parent table or view must
already be defined.
■ A composite foreign key cannot have more than 32 columns.
■ The child and parent tables must be on the same database. To enable referential
integrity constraints across nodes of a distributed database, you must use database
triggers. See CREATE TRIGGER on page 16-94.
■ If either the child or parent object is a view, then the constraint is subject to all
restrictions on view constraints. See "View Constraints" on page 8-18.
■ You cannot define a foreign key constraint in a CREATE TABLE statement that
contains an AS subquery clause. Instead, you must create the table without the
constraint and then add it later with an ALTER TABLE statement.
references_clause Foreign key constraints use the references_clause syntax.
When you specify a foreign key constraint inline, you need only the references_
clause. When you specify a foreign key constraint out of line, you must also specify
the FOREIGN KEY keywords and one or more columns.
ON DELETE Clause The ON DELETE clause lets you determine how Oracle Database
automatically maintains referential integrity if you remove a referenced primary or
unique key value. If you omit this clause, then Oracle does not allow you to delete
referenced key values in the parent table that have dependent rows in the child table.
■ Specify CASCADE if you want Oracle to remove dependent foreign key values.
■ Specify SET NULL if you want Oracle to convert dependent foreign key values to
NULL. You cannot specify this clause for a virtual column, because the values in a
virtual column cannot be updated directly. Rather, the values from which the
virtual column are derived must be updated.
Restriction on ON DELETE You cannot specify this clause for a view constraint.
Check Constraints
A check constraint lets you specify a condition that each row in the table must satisfy.
To satisfy the constraint, each row in the table must make the condition either TRUE or
unknown (due to a null). When Oracle evaluates a check constraint condition for a
See Also:
■ Oracle Database Advanced Application Developer's Guide for more
information on using constraints
■ "Foreign Key Constraint Example" on page 8-21 and "Composite
Foreign Key Constraint Example" on page 8-22
See Also: "ON DELETE Example" on page 8-22
constraint
8-12 Oracle Database SQL Language Reference
particular row, any column names in the condition refer to the column values in that
row.
The syntax for inline and out-of-line specification of check constraints is the same.
However, inline specification can refer only to the column (or the attributes of the
column if it is an object column) currently being defined, whereas out-of-line
specification can refer to multiple columns or attributes.
Oracle does not verify that conditions of check constraints are not mutually exclusive.
Therefore, if you create multiple check constraints for a column, design them carefully
so their purposes do not conflict. Do not assume any particular order of evaluation of
the conditions.
Restrictions on Check Constraints Check constraints are subject to the following
restrictions:
■ You cannot specify a check constraint for a view. However, you can define the
view using the WITH CHECK OPTION clause, which is equivalent to specifying a
check constraint for the view.
■ The condition of a check constraint can refer to any column in the table, but it
cannot refer to columns of other tables.
■ Conditions of check constraints cannot contain the following constructs:
– Subqueries and scalar subquery expressions
– Calls to the functions that are not deterministic (CURRENT_DATE, CURRENT_
TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE,
SYSDATE, SYSTIMESTAMP, UID, USER, and USERENV)
– Calls to user-defined functions
– Dereferencing of REF columns (for example, using the DEREF function)
– Nested table columns or attributes
– The pseudocolumns CURRVAL, NEXTVAL, LEVEL, or ROWNUM
– Date constants that are not fully specified
REF Constraints
REF constraints let you describe the relationship between a column of type REF and
the object it references.
ref_constraint REF constraints use the ref_constraint syntax. You define a REF
constraint either inline or out of line. Out-of-line specification requires you to specify
the REF column or attribute you are further describing.
■ For ref_column, specify the name of a REF column of an object or relational
table.
■ For ref_attribute, specify an embedded REF attribute within an object column
of a relational table.
See Also:
■ Chapter 7, "Conditions" for additional information and syntax
■ "Check Constraint Examples" on page 8-23 and "Attribute-Level
Constraints Example" on page 8-25
constraint
Common SQL DDL Clauses 8-13
Both inline and out-of-line specification let you define a scope constraint, a rowid
constraint, or a referential integrity constraint on a REF column.
If the scope table or referenced table of the REF column has a primary-key-based object
identifier, then the REF column is a user-defined REF column.
SCOPE REF Constraints
In a table with a REF column, each REF value in the column can conceivably reference
a row in a different object table. The SCOPE clause restricts the scope of references to a
single table, scope_table. The values in the REF column or attribute point to objects
in scope_table, in which object instances of the same type as the REF column are
stored.
Specify the SCOPE clause to restrict the scope of references in the REF column to a
single table. For you to specify this clause, scope_table must be in your own
schema or you must have SELECT privileges on scope_table or SELECT ANY TABLE
system privileges. You can specify only one scope table for each REF column.
Restrictions on Scope Constraints Scope constraints are subject to the following
restrictions:
■ You cannot add a scope constraint to an existing column unless the table is empty.
■ You cannot specify a scope constraint for the REF elements of a VARRAY column.
■ You must specify this clause if you specify AS subquery and the subquery returns
user-defined REF data types.
■ You cannot subsequently drop a scope constraint from a REF column.
Rowid REF Constraints
Specify WITH ROWID to store the rowid along with the REF value in ref_column or
ref_attribute. Storing the rowid with the REF value can improve the performance
of dereferencing operations, but will also use more space. Default storage of REF
values is without rowids.
Restrictions on Rowid Constraints Rowid constraints are subject to the following
restrictions:
■ You cannot define a rowid constraint for the REF elements of a VARRAY column.
■ You cannot subsequently drop a rowid constraint from a REF column.
■ If the REF column or attribute is scoped, then this clause is ignored and the rowid
is not stored with the REF value.
Referential Integrity Constraints on REF Columns
The references_clause of the ref_constraint syntax lets you define a foreign
key constraint on the REF column. This clause also implicitly restricts the scope of the
See Also:
■ Oracle Database Object-Relational Developer's Guide for more
information on REF data types
■ "Foreign Key Constraints" on page 8-10, and "REF Constraint
Examples" on page 8-25
See Also: The function DEREF on page 5-63 for an example of
dereferencing
constraint
8-14 Oracle Database SQL Language Reference
REF column or attribute to the referenced table. However, whereas a foreign key
constraint on a non-REF column references an actual column in the parent table, a
foreign key constraint on a REF column references the implicit object identifier column
of the parent table.
If you do not specify a constraint name, then Oracle generates a system name for the
constraint of the form SYS_Cn.
If you add a referential integrity constraint to an existing REF column that is already
scoped, then the referenced table must be the same as the scope table of the REF
column. If you later drop the referential integrity constraint, then the REF column will
remain scoped to the referenced table.
As is the case for foreign key constraints on other types of columns, you can use the
references_clause alone for inline declaration. For out-of-line declaration you
must also specify the FOREIGN KEY keywords plus one or more REF columns or
attributes.
Restrictions on Foreign Key Constraints on REF Columns Foreign key constraints
on REF columns have the following additional restrictions:
■ Oracle implicitly adds a scope constraint when you add a referential integrity
constraint to an existing unscoped REF column. Therefore, all the restrictions that
apply for scope constraints also apply in this case.
■ You cannot specify a column after the object name in the references_clause.
Specifying Constraint State
As part of constraint definition, you can specify how and when Oracle should enforce
the constraint.
constraint_state You can use the constraint_state with both inline and
out-of-line specification. Specify the clauses of constraint_state in the order
shown, from top to bottom, and do not specify any clause more than once.
DEFERRABLE Clause The DEFERRABLE and NOT DEFERRABLE parameters indicate
whether or not, in subsequent transactions, constraint checking can be deferred until
the end of the transaction using the SET CONSTRAINT(S) statement. If you omit this
clause, then the default is NOT DEFERRABLE.
■ Specify NOT DEFERRABLE to indicate that in subsequent transactions you cannot
use the SET CONSTRAINT[S] clause to defer checking of this constraint until the
transaction is committed. The checking of a NOT DEFERRABLE constraint can
never be deferred to the end of the transaction.
If you declare a new constraint NOT DEFERRABLE, then it must be valid at the time
the CREATE TABLE or ALTER TABLE statement is committed or the statement will
fail.
■ Specify DEFERRABLE to indicate that in subsequent transactions you can use the
SET CONSTRAINT[S] clause to defer checking of this constraint until a COMMIT
statement is submitted. If the constraint check fails, then the database returns an
error and the transaction is not committed. This setting in effect lets you disable
the constraint temporarily while making changes to the database that might
violate the constraint until all the changes are complete.
See Also: Oracle Database Object-Relational Developer's Guide for more
information on object identifiers
constraint
Common SQL DDL Clauses 8-15
You cannot alter the deferrability of a constraint. Whether you specify either of these
parameters, or make the constraint NOT DEFERRABLE implicitly by specifying neither
of them, you cannot specify this clause in an ALTER TABLE statement. You must drop
the constraint and r
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2
Sql reference11 gr2

More Related Content

What's hot (15)

PDF
Oracle® application server forms and reports services installation guide
FITSFSd
 
PDF
Oracle® Trading Community Architecture
Oracle Groups
 
PDF
Oracle database 12c client installation guide 6
bupbechanhgmail
 
PDF
E49462 01
Wilfred Mbithi Luvai
 
PDF
Oracle® business intelligence
George Heretis
 
PDF
Oracle demantra implementation guide part e22232 09
Amsa Krishnan Dhanapal
 
PDF
120posig
vinodchun
 
PDF
A85248
Anil Pandey
 
PDF
Shipping execution user guide r12
aruna777
 
PDF
120posig i spplr implmntn guide
Vikram Reddy
 
PDF
MALWARE THREAT ANALYSIS
Kumar Abhishek Shahi
 
PDF
Ascp
Maruthi k
 
PDF
I03402059063
theijes
 
Oracle® application server forms and reports services installation guide
FITSFSd
 
Oracle® Trading Community Architecture
Oracle Groups
 
Oracle database 12c client installation guide 6
bupbechanhgmail
 
Oracle® business intelligence
George Heretis
 
Oracle demantra implementation guide part e22232 09
Amsa Krishnan Dhanapal
 
120posig
vinodchun
 
A85248
Anil Pandey
 
Shipping execution user guide r12
aruna777
 
120posig i spplr implmntn guide
Vikram Reddy
 
MALWARE THREAT ANALYSIS
Kumar Abhishek Shahi
 
Ascp
Maruthi k
 
I03402059063
theijes
 

Viewers also liked (7)

PDF
Sgbd ud3 lenguaje_sql_para_examen
xarlydbz
 
DOCX
Examen de sql(inga pardave max)
maxtronic
 
DOC
Examen final de sql nadia
Carlitos Chancafe
 
PDF
Tutorial Teorico-Practico Sql server 2000 (233 paginas)
Martin Murciego
 
DOC
Ejercicios De Sql (actualizado)
capver digital
 
PDF
8.ejercicios SQL access
Marcelo Herrera
 
PDF
Ejercicios resueltos de sql
Julian Benavidez
 
Sgbd ud3 lenguaje_sql_para_examen
xarlydbz
 
Examen de sql(inga pardave max)
maxtronic
 
Examen final de sql nadia
Carlitos Chancafe
 
Tutorial Teorico-Practico Sql server 2000 (233 paginas)
Martin Murciego
 
Ejercicios De Sql (actualizado)
capver digital
 
8.ejercicios SQL access
Marcelo Herrera
 
Ejercicios resueltos de sql
Julian Benavidez
 
Ad

Similar to Sql reference11 gr2 (20)

PDF
Oracle 11g release 2
Adel Saleh
 
PDF
Libro de Oracle 11g
Guiro Lin
 
PDF
Oracle 11g
Kundan Kumar
 
PDF
ORACLE DATABASE - Programmers Guide to the Oracle Precompilers.pdf
Peter Asane
 
PDF
Oracle 11g concept
Battlecruiser Vodanh
 
PDF
Oracle 10g Reference
Edison
 
PDF
Oracle sql quick reference
maddy9055
 
PDF
Oracle_10g_PLSQL_Guia_Ref.pdf
Carlos Valente Albarracin
 
PDF
database-concepts for oracle aasdaasdasadsa
deyaamesh1
 
PDF
PL_SQL Oracle Reference.pdf
ARJUNMUKHERJEE27
 
PDF
Tai lieu-sql-plus-user-s-guide-and-reference
Le Thi
 
PDF
Oracle® database 2 days security guide e10575
imranshahid7861
 
PDF
Oracle database 12c 2 day developer's guide 123
bupbechanhgmail
 
PDF
database-reference-21cdatabasedataba.pdf
Aly Wade
 
PPT
Ep Cover
Sudharsan S
 
PPT
Csg 1
Sudharsan S
 
PDF
[Oracle数据库11 g初学者指南].oracle.database.11g,.a.beginner's.guide
gavin shaw
 
PDF
11g-sql-fundamentals-ppt.pdf
firasatsayyed1
 
PDF
Oracle database 12c client installation overview
bupbechanhgmail
 
Oracle 11g release 2
Adel Saleh
 
Libro de Oracle 11g
Guiro Lin
 
Oracle 11g
Kundan Kumar
 
ORACLE DATABASE - Programmers Guide to the Oracle Precompilers.pdf
Peter Asane
 
Oracle 11g concept
Battlecruiser Vodanh
 
Oracle 10g Reference
Edison
 
Oracle sql quick reference
maddy9055
 
Oracle_10g_PLSQL_Guia_Ref.pdf
Carlos Valente Albarracin
 
database-concepts for oracle aasdaasdasadsa
deyaamesh1
 
PL_SQL Oracle Reference.pdf
ARJUNMUKHERJEE27
 
Tai lieu-sql-plus-user-s-guide-and-reference
Le Thi
 
Oracle® database 2 days security guide e10575
imranshahid7861
 
Oracle database 12c 2 day developer's guide 123
bupbechanhgmail
 
database-reference-21cdatabasedataba.pdf
Aly Wade
 
Ep Cover
Sudharsan S
 
[Oracle数据库11 g初学者指南].oracle.database.11g,.a.beginner's.guide
gavin shaw
 
11g-sql-fundamentals-ppt.pdf
firasatsayyed1
 
Oracle database 12c client installation overview
bupbechanhgmail
 
Ad

Sql reference11 gr2

  • 1. Oracle® Database SQL Language Reference 11g Release 2 (11.2) E10592-03 September 2009
  • 2. Oracle Database SQL Language Reference, 11g Release 2 (11.2) E10592-03 Copyright © 1996, 2009, Oracle and/or its affiliates. All rights reserved. Primary Authors: Diana Lorentz, Mary Beth Roeser Contributors: Sundeep Abraham, Angela Amor, Geeta Arora, Vikas Arora, Lance Ashdown, Hermann Baer, Shrikanth Bellamkonda, Donna Carver, Dan Chiba, Timothy Chien, Alan Choi, Thierry Cruanes, George Eadon, Amit Ganesh, Barb Glover, Naveen Gopal, Mike Hallas, Min-Hank Ho, Chandrasekharan Iyer, Mark Jaeger, Vikram Kapoor, Peter Knaggs, Srinath Krishnaswamy, Andre Kruglikov, Paul Lane, Huagang Li, Yunrui Li, Vince Liang, Bryn Llewellyn, Rich Long, Scott Lynn, Vineet Marwah, Jun Matsuzawa, Robert McGuirk, Rahil Mir, Gopal Mulagund, Sujatha Muthulingam, Hanlin Qian, Ashish Ray, John Russell, Laurent Schneider, Vivian Schupmann, Jia Shi, Ajeet Singh, Wayne Smith, Shanshan Song, Vinay Srihari, Jim Stenoish, Sankar Subramanian, Seema Sundara, Mark van de Wiel, Badhri Varanasi, William Waddington, Peter Wahl, Charles Wetherell, Sergiusz Wolicki, Daniel Wong, Tsae-feng Yu, Mohamed Zait, Fred Zemke, Wei Zhang, Weiran Zhang This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065. This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.
  • 3. iii Contents Preface............................................................................................................................................................... xxi Audience..................................................................................................................................................... xxi Documentation Accessibility................................................................................................................... xxi Related Documents .................................................................................................................................. xxii Conventions .............................................................................................................................................. xxii What's New in the SQL Language Reference?....................................................................... xxiii Oracle Database 11g Release 2 New Features in the SQL Language Reference............................. xxiii Oracle Database 11g Release 1 New Features in the SQL Language Reference............................. xxv 1 Introduction to Oracle SQL History of SQL ......................................................................................................................................... 1-1 SQL Standards ......................................................................................................................................... 1-1 How SQL Works ............................................................................................................................... 1-2 Common Language for All Relational Databases ......................................................................... 1-2 Using Enterprise Manager ..................................................................................................................... 1-3 Lexical Conventions................................................................................................................................. 1-3 Tools Support ........................................................................................................................................... 1-3 2 Pseudocolumns Hierarchical Query Pseudocolumns .................................................................................................... 2-1 CONNECT_BY_ISCYCLE Pseudocolumn .................................................................................... 2-1 CONNECT_BY_ISLEAF Pseudocolumn ....................................................................................... 2-2 LEVEL Pseudocolumn ...................................................................................................................... 2-2 Sequence Pseudocolumns ..................................................................................................................... 2-3 Where to Use Sequence Values ....................................................................................................... 2-3 How to Use Sequence Values .......................................................................................................... 2-4 Version Query Pseudocolumns ............................................................................................................ 2-6 COLUMN_VALUE Pseudocolumn ...................................................................................................... 2-6 OBJECT_ID Pseudocolumn .................................................................................................................. 2-7 OBJECT_VALUE Pseudocolumn .......................................................................................................... 2-8
  • 4. iv ORA_ROWSCN Pseudocolumn ........................................................................................................... 2-8 ROWID Pseudocolumn .......................................................................................................................... 2-9 ROWNUM Pseudocolumn .................................................................................................................... 2-9 XMLDATA Pseudocolumn ................................................................................................................. 2-10 3 Basic Elements of Oracle SQL Data Types ................................................................................................................................................ 3-1 Oracle Built-in Data Types................................................................................................................ 3-6 CHAR Data Type ....................................................................................................................... 3-9 NCHAR Data Type .................................................................................................................... 3-9 NVARCHAR2 Data Type ......................................................................................................... 3-9 VARCHAR2 Data Type ......................................................................................................... 3-10 VARCHAR Data Type ........................................................................................................... 3-10 NUMBER Data Type .............................................................................................................. 3-10 FLOAT Data Type.................................................................................................................... 3-12 Floating-Point Numbers ........................................................................................................ 3-12 BINARY_FLOAT .............................................................................................................. 3-13 BINARY_DOUBLE........................................................................................................... 3-13 Numeric Precedence ............................................................................................................... 3-14 DATE Data Type ..................................................................................................................... 3-17 Using Julian Days ............................................................................................................. 3-17 TIMESTAMP Data Type ........................................................................................................ 3-18 TIMESTAMP WITH TIME ZONE Data Type .................................................................... 3-18 TIMESTAMP WITH LOCAL TIME ZONE Data Type ..................................................... 3-19 INTERVAL YEAR TO MONTH Data Type ........................................................................ 3-19 INTERVAL DAY TO SECOND Data Type ......................................................................... 3-20 Datetime/Interval Arithmetic ............................................................................................... 3-20 Support for Daylight Saving Times ...................................................................................... 3-22 Datetime and Interval Examples ........................................................................................... 3-23 RAW and LONG RAW Data Types ..................................................................................... 3-24 BFILE Data Type ..................................................................................................................... 3-26 BLOB Data Type ...................................................................................................................... 3-26 CLOB Data Type ..................................................................................................................... 3-26 NCLOB Data Type .................................................................................................................. 3-27 Rowid Data Types .......................................................................................................................... 3-27 ROWID Data Type .................................................................................................................. 3-27 UROWID Data Type ............................................................................................................... 3-28 ANSI, DB2, and SQL/DS Data Types ......................................................................................... 3-28 User-Defined Types ....................................................................................................................... 3-30 Object Types ............................................................................................................................ 3-30 REF Data Types ....................................................................................................................... 3-30 Varrays ...................................................................................................................................... 3-31 Nested Tables .......................................................................................................................... 3-31 Oracle-Supplied Types .................................................................................................................. 3-31 Any Types ....................................................................................................................................... 3-32 ANYTYPE ................................................................................................................................. 3-32 ANYDATA................................................................................................................................ 3-32
  • 5. v ANYDATASET......................................................................................................................... 3-32 XML Types ...................................................................................................................................... 3-32 XMLType .................................................................................................................................. 3-32 URI Data Types ....................................................................................................................... 3-33 URIFactory Package ................................................................................................................ 3-34 Spatial Types ................................................................................................................................... 3-34 SDO_GEOMETRY ................................................................................................................... 3-34 SDO_TOPO_GEOMETRY ..................................................................................................... 3-34 SDO_GEORASTER.................................................................................................................. 3-35 Media Types .................................................................................................................................... 3-35 ORDAudio ............................................................................................................................... 3-35 ORDImage ................................................................................................................................ 3-35 ORDVideo ................................................................................................................................ 3-35 ORDDoc ................................................................................................................................... 3-35 ORDDicom ............................................................................................................................... 3-36 SI_StillImage ............................................................................................................................ 3-36 SI_Color .................................................................................................................................... 3-36 SI_AverageColor ..................................................................................................................... 3-36 SI_ColorHistogram ................................................................................................................. 3-36 SI_PositionalColor .................................................................................................................. 3-36 SI_Texture ................................................................................................................................ 3-36 SI_FeatureList .......................................................................................................................... 3-36 ORDImageSignature ............................................................................................................... 3-36 Expression Filter Type.................................................................................................................... 3-36 Expression................................................................................................................................. 3-37 Data Type Comparison Rules ............................................................................................................ 3-37 Numeric Values .............................................................................................................................. 3-37 Date Values ..................................................................................................................................... 3-37 Character Values ............................................................................................................................ 3-37 Object Values .................................................................................................................................. 3-40 Varrays and Nested Tables ........................................................................................................... 3-40 Data Type Precedence .................................................................................................................... 3-40 Data Conversion ............................................................................................................................. 3-40 Implicit and Explicit Data Conversion ................................................................................ 3-40 Implicit Data Conversion ....................................................................................................... 3-40 Implicit Data Conversion Examples...................................................................................... 3-43 Explicit Data Conversion ....................................................................................................... 3-43 Security Considerations for Data Conversion ............................................................................ 3-44 Literals .................................................................................................................................................... 3-45 Text Literals ..................................................................................................................................... 3-46 Numeric Literals ............................................................................................................................. 3-47 Integer Literals ......................................................................................................................... 3-47 NUMBER and Floating-Point Literals .................................................................................. 3-48 Datetime Literals ............................................................................................................................ 3-50 Interval Literals................................................................................................................................ 3-52 INTERVAL YEAR TO MONTH ............................................................................................ 3-53 INTERVAL DAY TO SECOND ............................................................................................. 3-54
  • 6. vi Format Models ...................................................................................................................................... 3-55 Number Format Models ................................................................................................................ 3-56 Number Format Elements ..................................................................................................... 3-57 Datetime Format Models .............................................................................................................. 3-59 Datetime Format Elements .................................................................................................... 3-60 Uppercase Letters in Date Format Elements ............................................................... 3-60 Punctuation and Character Literals in Datetime Format Models ............................. 3-60 Datetime Format Elements and Globalization Support .................................................... 3-64 ISO Standard Date Format Elements ................................................................................... 3-64 The RR Datetime Format Element ........................................................................................ 3-64 RR Datetime Format Examples....................................................................................... 3-65 Datetime Format Element Suffixes ....................................................................................... 3-65 Format Model Modifiers ............................................................................................................... 3-66 Format Model Examples......................................................................................................... 3-67 String-to-Date Conversion Rules ................................................................................................. 3-68 XML Format Model ....................................................................................................................... 3-69 Nulls ........................................................................................................................................................ 3-70 Nulls in SQL Functions .................................................................................................................. 3-70 Nulls with Comparison Conditions ............................................................................................ 3-71 Nulls in Conditions ........................................................................................................................ 3-71 Comments .............................................................................................................................................. 3-71 Comments Within SQL Statements ............................................................................................. 3-72 Comments on Schema and Nonschema Objects ....................................................................... 3-72 Hints ................................................................................................................................................. 3-73 Alphabetical Listing of Hints ........................................................................................................ 3-77 ALL_ROWS Hint .................................................................................................................... 3-77 APPEND Hint .......................................................................................................................... 3-78 APPEND_VALUES Hint ....................................................................................................... 3-78 CACHE Hint ............................................................................................................................ 3-79 CHANGE_DUPKEY_ERROR_INDEX Hint ....................................................................... 3-79 CLUSTER Hint ........................................................................................................................ 3-80 CURSOR_SHARING_EXACT Hint ..................................................................................... 3-80 DRIVING_SITE Hint .............................................................................................................. 3-80 DYNAMIC_SAMPLING Hint ............................................................................................... 3-81 FACT Hint ................................................................................................................................ 3-81 FIRST_ROWS Hint .................................................................................................................. 3-81 FULL Hint ................................................................................................................................ 3-82 HASH Hint .............................................................................................................................. 3-82 IGNORE_ROW_ON_DUPKEY_INDEX Hint ..................................................................... 3-83 INDEX Hint ............................................................................................................................. 3-83 INDEX_ASC Hint ................................................................................................................... 3-84 INDEX_COMBINE Hint ........................................................................................................ 3-84 INDEX_DESC Hint ................................................................................................................. 3-85 INDEX_FFS Hint ..................................................................................................................... 3-85 INDEX_JOIN Hint .................................................................................................................. 3-85 INDEX_SS Hint ....................................................................................................................... 3-86 INDEX_SS_ASC Hint ............................................................................................................. 3-86
  • 7. vii INDEX_SS_DESC Hint ........................................................................................................... 3-87 LEADING Hint ........................................................................................................................ 3-87 MERGE Hint ............................................................................................................................ 3-87 MODEL_MIN_ANALYSIS Hint ........................................................................................... 3-88 MONITOR Hint ...................................................................................................................... 3-88 NATIVE_FULL_OUTER_JOIN Hint .................................................................................... 3-88 NOAPPEND Hint ................................................................................................................... 3-89 NOCACHE Hint ..................................................................................................................... 3-89 NO_EXPAND Hint ................................................................................................................. 3-89 NO_FACT Hint ....................................................................................................................... 3-89 NO_INDEX Hint ..................................................................................................................... 3-90 NO_INDEX_FFS Hint ............................................................................................................ 3-90 NO_INDEX_SS Hint ............................................................................................................... 3-90 NO_MERGE Hint ................................................................................................................... 3-91 NO_MONITOR Hint .............................................................................................................. 3-91 NO_NATIVE_FULL_OUTER_JOIN Hint ............................................................................ 3-91 NO_PARALLEL Hint ............................................................................................................. 3-91 NOPARALLEL Hint................................................................................................................ 3-92 NO_PARALLEL_INDEX Hint .............................................................................................. 3-92 NOPARALLEL_INDEX Hint................................................................................................. 3-92 NO_PUSH_PRED Hint .......................................................................................................... 3-92 NO_PUSH_SUBQ Hint .......................................................................................................... 3-93 NO_PX_JOIN_FILTER Hint .................................................................................................. 3-93 NO_QUERY_TRANSFORMATION Hint ........................................................................... 3-93 NO_RESULT_CACHE Hint .................................................................................................. 3-93 NO_REWRITE Hint ................................................................................................................ 3-93 NOREWRITE Hint................................................................................................................... 3-94 NO_STAR_TRANSFORMATION Hint ............................................................................... 3-94 NO_UNNEST Hint ................................................................................................................. 3-94 NO_USE_HASH Hint ............................................................................................................ 3-94 NO_USE_MERGE Hint .......................................................................................................... 3-94 NO_USE_NL Hint .................................................................................................................. 3-95 NO_XML_QUERY_REWRITE Hint...................................................................................... 3-95 NO_XMLINDEX_REWRITE Hint ........................................................................................ 3-95 OPT_PARAM Hint ................................................................................................................. 3-95 ORDERED Hint ....................................................................................................................... 3-96 PARALLEL Hint ..................................................................................................................... 3-96 PARALLEL_INDEX Hint ...................................................................................................... 3-98 PQ_DISTRIBUTE Hint ........................................................................................................... 3-98 PUSH_PRED Hint ................................................................................................................. 3-101 PUSH_SUBQ Hint ................................................................................................................. 3-101 PX_JOIN_FILTER Hint ......................................................................................................... 3-101 QB_NAME Hint .................................................................................................................... 3-101 RESULT_CACHE Hint ......................................................................................................... 3-102 RETRY_ON_ROW_CHANGE Hint ................................................................................... 3-102 REWRITE Hint ...................................................................................................................... 3-103 STAR_TRANSFORMATION Hint ..................................................................................... 3-103
  • 8. viii UNNEST Hint ........................................................................................................................ 3-104 USE_CONCAT Hint ............................................................................................................. 3-104 USE_HASH Hint ................................................................................................................... 3-104 USE_MERGE Hint ................................................................................................................ 3-105 USE_NL Hint ......................................................................................................................... 3-105 USE_NL_WITH_INDEX Hint ............................................................................................. 3-106 Database Objects................................................................................................................................. 3-106 Schema Objects ............................................................................................................................. 3-106 Nonschema Objects ...................................................................................................................... 3-107 Database Object Names and Qualifiers ......................................................................................... 3-107 Database Object Naming Rules .................................................................................................. 3-107 Schema Object Naming Examples ............................................................................................. 3-111 Schema Object Naming Guidelines ........................................................................................... 3-111 Syntax for Schema Objects and Parts in SQL Statements........................................................... 3-111 How Oracle Database Resolves Schema Object References ................................................... 3-112 References to Objects in Other Schemas ................................................................................... 3-113 References to Objects in Remote Databases ............................................................................. 3-113 Creating Database Links ...................................................................................................... 3-114 Database Link Names .................................................................................................... 3-114 Username and Password............................................................................................... 3-114 Database Connect String................................................................................................ 3-114 References to Database Links .............................................................................................. 3-115 References to Partitioned Tables and Indexes ......................................................................... 3-115 References to Object Type Attributes and Methods ................................................................ 3-117 4 Operators About SQL Operators.............................................................................................................................. 4-1 Unary and Binary Operators ........................................................................................................... 4-2 Operator Precedence ......................................................................................................................... 4-2 Arithmetic Operators .............................................................................................................................. 4-3 Concatenation Operator.......................................................................................................................... 4-4 Hierarchical Query Operators................................................................................................................ 4-5 PRIOR ................................................................................................................................................. 4-5 CONNECT_BY_ROOT ..................................................................................................................... 4-5 Set Operators ............................................................................................................................................ 4-5 Multiset Operators .................................................................................................................................. 4-6 MULTISET EXCEPT ......................................................................................................................... 4-6 MULTISET INTERSECT .................................................................................................................. 4-7 MULTISET UNION .......................................................................................................................... 4-8 User-Defined Operators ......................................................................................................................... 4-9 5 Functions About SQL Functions ............................................................................................................................. 5-2 Single-Row Functions ............................................................................................................................ 5-3 Numeric Functions ............................................................................................................................ 5-3 Character Functions Returning Character Values ........................................................................ 5-4 NLS Character Functions ................................................................................................................. 5-5
  • 9. ix Character Functions Returning Number Values .......................................................................... 5-5 Datetime Functions ........................................................................................................................... 5-5 General Comparison Functions ...................................................................................................... 5-6 Conversion Functions ....................................................................................................................... 5-6 Large Object Functions ..................................................................................................................... 5-7 Collection Functions ......................................................................................................................... 5-7 Hierarchical Function ....................................................................................................................... 5-7 Data Mining Functions ..................................................................................................................... 5-7 XML Functions .................................................................................................................................. 5-8 Encoding and Decoding Functions ................................................................................................ 5-9 NULL-Related Functions ................................................................................................................. 5-9 Environment and Identifier Functions ........................................................................................... 5-9 Aggregate Functions ............................................................................................................................... 5-9 Analytic Functions ............................................................................................................................... 5-11 Object Reference Functions ............................................................................................................... 5-16 Model Functions ................................................................................................................................... 5-16 Alphabetical Listing of SQL Functions ............................................................................................ 5-17 ABS .......................................................................................................................................................... 5-18 ACOS ...................................................................................................................................................... 5-18 ADD_MONTHS ................................................................................................................................... 5-19 APPENDCHILDXML .......................................................................................................................... 5-19 ASCII ...................................................................................................................................................... 5-20 ASCIISTR .............................................................................................................................................. 5-21 ASIN ....................................................................................................................................................... 5-21 ATAN ...................................................................................................................................................... 5-22 ATAN2 .................................................................................................................................................... 5-22 AVG ......................................................................................................................................................... 5-23 BFILENAME .......................................................................................................................................... 5-24 BIN_TO_NUM ...................................................................................................................................... 5-25 BITAND .................................................................................................................................................. 5-26 CARDINALITY .................................................................................................................................... 5-27 CAST ....................................................................................................................................................... 5-28 CEIL ......................................................................................................................................................... 5-31 CHARTOROWID ................................................................................................................................. 5-31 CHR ......................................................................................................................................................... 5-32 CLUSTER_ID ........................................................................................................................................ 5-33 CLUSTER_PROBABILITY ................................................................................................................. 5-34 CLUSTER_SET ..................................................................................................................................... 5-36 COALESCE ............................................................................................................................................ 5-38 COLLECT ............................................................................................................................................... 5-39 COMPOSE ............................................................................................................................................. 5-40 CONCAT ................................................................................................................................................ 5-40 CONVERT ............................................................................................................................................. 5-41 CORR ...................................................................................................................................................... 5-43 CORR_* .................................................................................................................................................. 5-44 CORR_S ........................................................................................................................................... 5-45 CORR_K .......................................................................................................................................... 5-46
  • 10. x COS ......................................................................................................................................................... 5-46 COSH ...................................................................................................................................................... 5-47 COUNT ................................................................................................................................................... 5-47 COVAR_POP ......................................................................................................................................... 5-49 COVAR_SAMP ..................................................................................................................................... 5-50 CUBE_TABLE......................................................................................................................................... 5-51 CUME_DIST ......................................................................................................................................... 5-53 CURRENT_DATE ................................................................................................................................ 5-54 CURRENT_TIMESTAMP ................................................................................................................... 5-55 CV............................................................................................................................................................. 5-56 DATAOBJ_TO_PARTITION .............................................................................................................. 5-57 DBTIMEZONE ..................................................................................................................................... 5-57 DECODE ................................................................................................................................................ 5-58 DECOMPOSE ....................................................................................................................................... 5-59 DELETEXML ......................................................................................................................................... 5-60 DENSE_RANK ..................................................................................................................................... 5-61 DEPTH .................................................................................................................................................... 5-63 DEREF ..................................................................................................................................................... 5-63 DUMP ..................................................................................................................................................... 5-64 EMPTY_BLOB, EMPTY_CLOB ......................................................................................................... 5-65 EXISTSNODE ....................................................................................................................................... 5-66 EXP .......................................................................................................................................................... 5-67 EXTRACT (datetime) ........................................................................................................................... 5-68 EXTRACT (XML) .................................................................................................................................. 5-70 EXTRACTVALUE ................................................................................................................................. 5-71 FEATURE_ID ........................................................................................................................................ 5-72 FEATURE_SET ...................................................................................................................................... 5-73 FEATURE_VALUE ................................................................................................................................ 5-75 FIRST ...................................................................................................................................................... 5-77 FIRST_VALUE ...................................................................................................................................... 5-79 FLOOR .................................................................................................................................................... 5-80 FROM_TZ .............................................................................................................................................. 5-81 GREATEST ............................................................................................................................................ 5-81 GROUP_ID ............................................................................................................................................ 5-82 GROUPING ........................................................................................................................................... 5-83 GROUPING_ID .................................................................................................................................... 5-84 HEXTORAW .......................................................................................................................................... 5-85 INITCAP ................................................................................................................................................ 5-85 INSERTCHILDXML ............................................................................................................................ 5-86 INSERTCHILDXMLAFTER ............................................................................................................... 5-87 INSERTCHILDXMLBEFORE ............................................................................................................ 5-88 INSERTXMLAFTER ............................................................................................................................. 5-89 INSERTXMLBEFORE .......................................................................................................................... 5-90 INSTR ..................................................................................................................................................... 5-91 ITERATION_NUMBER ...................................................................................................................... 5-92 LAG ......................................................................................................................................................... 5-94 LAST ....................................................................................................................................................... 5-95
  • 11. xi LAST_DAY ............................................................................................................................................. 5-95 LAST_VALUE ....................................................................................................................................... 5-96 LEAD ....................................................................................................................................................... 5-98 LEAST ..................................................................................................................................................... 5-99 LENGTH .............................................................................................................................................. 5-100 LISTAGG ............................................................................................................................................. 5-101 LN .......................................................................................................................................................... 5-102 LNNVL ................................................................................................................................................. 5-103 LOCALTIMESTAMP ......................................................................................................................... 5-104 LOG ....................................................................................................................................................... 5-105 LOWER ................................................................................................................................................. 5-105 LPAD...................................................................................................................................................... 5-106 LTRIM ................................................................................................................................................... 5-106 MAKE_REF .......................................................................................................................................... 5-107 MAX ...................................................................................................................................................... 5-108 MEDIAN .............................................................................................................................................. 5-109 MIN ....................................................................................................................................................... 5-111 MOD ..................................................................................................................................................... 5-112 MONTHS_BETWEEN ....................................................................................................................... 5-113 NANVL ................................................................................................................................................. 5-114 NCHR ................................................................................................................................................... 5-114 NEW_TIME ......................................................................................................................................... 5-115 NEXT_DAY .......................................................................................................................................... 5-116 NLS_CHARSET_DECL_LEN ........................................................................................................... 5-116 NLS_CHARSET_ID ........................................................................................................................... 5-117 NLS_CHARSET_NAME ................................................................................................................... 5-117 NLS_INITCAP .................................................................................................................................... 5-118 NLS_LOWER ....................................................................................................................................... 5-119 NLS_UPPER ........................................................................................................................................ 5-119 NLSSORT ............................................................................................................................................. 5-120 NTH_VALUE ....................................................................................................................................... 5-122 NTILE ................................................................................................................................................... 5-123 NULLIF ................................................................................................................................................. 5-124 NUMTODSINTERVAL ..................................................................................................................... 5-125 NUMTOYMINTERVAL .................................................................................................................... 5-126 NVL ....................................................................................................................................................... 5-126 NVL2 ..................................................................................................................................................... 5-127 ORA_DST_AFFECTED ..................................................................................................................... 5-128 ORA_DST_CONVERT ...................................................................................................................... 5-129 ORA_DST_ERROR ............................................................................................................................ 5-130 ORA_HASH ........................................................................................................................................ 5-130 PATH...................................................................................................................................................... 5-131 PERCENT_RANK .............................................................................................................................. 5-132 PERCENTILE_CONT ........................................................................................................................ 5-133 PERCENTILE_DISC .......................................................................................................................... 5-135 POWER ................................................................................................................................................. 5-137 POWERMULTISET ............................................................................................................................ 5-137
  • 12. xii POWERMULTISET_BY_CARDINALITY ..................................................................................... 5-138 PREDICTION ..................................................................................................................................... 5-139 PREDICTION_BOUNDS ................................................................................................................. 5-141 PREDICTION_COST ........................................................................................................................ 5-142 PREDICTION_DETAILS .................................................................................................................. 5-144 PREDICTION_PROBABILITY ....................................................................................................... 5-146 PREDICTION_SET ............................................................................................................................ 5-147 PRESENTNNV .................................................................................................................................... 5-150 PRESENTV ........................................................................................................................................... 5-151 PREVIOUS ........................................................................................................................................... 5-152 RANK ................................................................................................................................................... 5-153 RATIO_TO_REPORT ........................................................................................................................ 5-155 RAWTOHEX ........................................................................................................................................ 5-155 RAWTONHEX .................................................................................................................................... 5-156 REF ........................................................................................................................................................ 5-157 REFTOHEX .......................................................................................................................................... 5-157 REGEXP_COUNT .............................................................................................................................. 5-158 REGEXP_INSTR ................................................................................................................................. 5-160 REGEXP_REPLACE ........................................................................................................................... 5-162 REGEXP_SUBSTR ............................................................................................................................. 5-164 REGR_ (Linear Regression) Functions ........................................................................................... 5-166 REMAINDER ...................................................................................................................................... 5-171 REPLACE ............................................................................................................................................. 5-172 ROUND (date) .................................................................................................................................... 5-172 ROUND (number) .............................................................................................................................. 5-173 ROW_NUMBER ................................................................................................................................. 5-174 ROWIDTOCHAR ............................................................................................................................... 5-176 ROWIDTONCHAR ........................................................................................................................... 5-176 RPAD .................................................................................................................................................... 5-177 RTRIM .................................................................................................................................................. 5-178 SCN_TO_TIMESTAMP .................................................................................................................... 5-178 SESSIONTIMEZONE ....................................................................................................................... 5-180 SET ........................................................................................................................................................ 5-180 SIGN ..................................................................................................................................................... 5-181 SIN ......................................................................................................................................................... 5-181 SINH ..................................................................................................................................................... 5-182 SOUNDEX ........................................................................................................................................... 5-182 SQRT ..................................................................................................................................................... 5-183 STATS_BINOMIAL_TEST ............................................................................................................... 5-184 STATS_CROSSTAB ........................................................................................................................... 5-185 STATS_F_TEST ................................................................................................................................... 5-186 STATS_KS_TEST ................................................................................................................................ 5-187 STATS_MODE .................................................................................................................................... 5-188 STATS_MW_TEST ............................................................................................................................. 5-189 STATS_ONE_WAY_ANOVA ............................................................................................................ 5-190 STATS_T_TEST_* ............................................................................................................................... 5-191 STATS_T_TEST_ONE .................................................................................................................. 5-192
  • 13. xiii STATS_T_TEST_PAIRED ........................................................................................................... 5-193 STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU ....................................................... 5-193 STATS_WSR_TEST ............................................................................................................................ 5-194 STDDEV ............................................................................................................................................... 5-195 STDDEV_POP .................................................................................................................................... 5-196 STDDEV_SAMP ................................................................................................................................. 5-197 SUBSTR ................................................................................................................................................ 5-199 SUM ...................................................................................................................................................... 5-200 SYS_CONNECT_BY_PATH ............................................................................................................. 5-201 SYS_CONTEXT .................................................................................................................................. 5-202 SYS_DBURIGEN ................................................................................................................................ 5-208 SYS_EXTRACT_UTC ........................................................................................................................ 5-209 SYS_GUID ........................................................................................................................................... 5-209 SYS_TYPEID ....................................................................................................................................... 5-210 SYS_XMLAGG ................................................................................................................................... 5-211 SYS_XMLGEN .................................................................................................................................... 5-211 SYSDATE ............................................................................................................................................. 5-212 SYSTIMESTAMP ............................................................................................................................... 5-213 TAN ....................................................................................................................................................... 5-213 TANH .................................................................................................................................................... 5-214 TIMESTAMP_TO_SCN .................................................................................................................... 5-214 TO_BINARY_DOUBLE ..................................................................................................................... 5-215 TO_BINARY_FLOAT ........................................................................................................................ 5-216 TO_BLOB ............................................................................................................................................. 5-217 TO_CHAR (character) ........................................................................................................................ 5-218 TO_CHAR (datetime) ........................................................................................................................ 5-219 TO_CHAR (number) .......................................................................................................................... 5-221 TO_CLOB ............................................................................................................................................. 5-222 TO_DATE ............................................................................................................................................. 5-223 TO_DSINTERVAL ............................................................................................................................. 5-224 TO_LOB ............................................................................................................................................... 5-225 TO_MULTI_BYTE .............................................................................................................................. 5-226 TO_NCHAR (character) .................................................................................................................... 5-227 TO_NCHAR (datetime) ..................................................................................................................... 5-227 TO_NCHAR (number) ...................................................................................................................... 5-228 TO_NCLOB ......................................................................................................................................... 5-229 TO_NUMBER ..................................................................................................................................... 5-229 TO_SINGLE_BYTE ............................................................................................................................ 5-230 TO_TIMESTAMP ............................................................................................................................... 5-230 TO_TIMESTAMP_TZ ........................................................................................................................ 5-231 TO_YMINTERVAL ............................................................................................................................ 5-232 TRANSLATE ....................................................................................................................................... 5-233 TRANSLATE ... USING .................................................................................................................... 5-234 TREAT .................................................................................................................................................. 5-235 TRIM ..................................................................................................................................................... 5-236 TRUNC (date) ...................................................................................................................................... 5-237 TRUNC (number) ............................................................................................................................... 5-238
  • 14. xiv TZ_OFFSET ......................................................................................................................................... 5-238 UID ........................................................................................................................................................ 5-239 UNISTR ................................................................................................................................................ 5-239 UPDATEXML ...................................................................................................................................... 5-240 UPPER ................................................................................................................................................... 5-241 USER ..................................................................................................................................................... 5-242 USERENV ............................................................................................................................................ 5-242 VALUE .................................................................................................................................................. 5-243 VAR_POP ............................................................................................................................................. 5-244 VAR_SAMP ......................................................................................................................................... 5-245 VARIANCE .......................................................................................................................................... 5-246 VSIZE .................................................................................................................................................... 5-247 WIDTH_BUCKET .............................................................................................................................. 5-248 XMLAGG ............................................................................................................................................. 5-249 XMLCAST............................................................................................................................................. 5-250 XMLCDATA ........................................................................................................................................ 5-251 XMLCOLATTVAL............................................................................................................................... 5-252 XMLCOMMENT ................................................................................................................................ 5-252 XMLCONCAT ..................................................................................................................................... 5-253 XMLDIFF ............................................................................................................................................. 5-254 XMLELEMENT.................................................................................................................................... 5-255 XMLEXISTS ......................................................................................................................................... 5-257 XMLFOREST ....................................................................................................................................... 5-258 XMLISVALID ...................................................................................................................................... 5-259 XMLPARSE .......................................................................................................................................... 5-259 XMLPATCH ......................................................................................................................................... 5-260 XMLPI ................................................................................................................................................... 5-261 XMLQUERY ......................................................................................................................................... 5-262 XMLROOT ........................................................................................................................................... 5-263 XMLSEQUENCE ................................................................................................................................. 5-264 XMLSERIALIZE ................................................................................................................................. 5-266 XMLTABLE .......................................................................................................................................... 5-267 XMLTRANSFORM ............................................................................................................................. 5-269 ROUND and TRUNC Date Functions ............................................................................................ 5-270 About User-Defined Functions ........................................................................................................ 5-271 Prerequisites................................................................................................................................... 5-272 Name Precedence ......................................................................................................................... 5-272 Naming Conventions ........................................................................................................... 5-272 6 Expressions About SQL Expressions ......................................................................................................................... 6-1 Simple Expressions ................................................................................................................................. 6-3 Compound Expressions ......................................................................................................................... 6-4 CASE Expressions ................................................................................................................................... 6-5 Column Expressions ............................................................................................................................... 6-6 CURSOR Expressions.............................................................................................................................. 6-7 Datetime Expressions ............................................................................................................................. 6-8
  • 15. xv Function Expressions ........................................................................................................................... 6-10 Interval Expressions ............................................................................................................................. 6-10 Model Expressions ................................................................................................................................ 6-11 Object Access Expressions .................................................................................................................. 6-13 Placeholder Expressions ...................................................................................................................... 6-14 Scalar Subquery Expressions ............................................................................................................. 6-14 Type Constructor Expressions ............................................................................................................ 6-14 Expression Lists .................................................................................................................................... 6-16 7 Conditions About SQL Conditions............................................................................................................................ 7-1 Condition Precedence........................................................................................................................ 7-3 Comparison Conditions ......................................................................................................................... 7-4 Simple Comparison Conditions ...................................................................................................... 7-5 Group Comparison Conditions ...................................................................................................... 7-6 Floating-Point Conditions ..................................................................................................................... 7-7 Logical Conditions ................................................................................................................................... 7-7 Model Conditions ................................................................................................................................... 7-9 IS ANY Condition ............................................................................................................................. 7-9 IS PRESENT Condition ................................................................................................................. 7-10 Multiset Conditions ............................................................................................................................. 7-11 IS A SET Condition ........................................................................................................................ 7-11 IS EMPTY Condition ...................................................................................................................... 7-12 MEMBER Condition ...................................................................................................................... 7-12 SUBMULTISET Condition ............................................................................................................ 7-13 Pattern-matching Conditions ............................................................................................................. 7-14 LIKE Condition ............................................................................................................................... 7-14 REGEXP_LIKE Condition ............................................................................................................. 7-17 Null Conditions .................................................................................................................................... 7-19 XML Conditions ................................................................................................................................... 7-19 EQUALS_PATH Condition .......................................................................................................... 7-19 UNDER_PATH Condition ............................................................................................................ 7-20 Compound Conditions ........................................................................................................................ 7-20 BETWEEN Condition .......................................................................................................................... 7-21 EXISTS Condition ................................................................................................................................ 7-22 IN Condition ......................................................................................................................................... 7-22 IS OF type Condition ........................................................................................................................... 7-24 8 Common SQL DDL Clauses allocate_extent_clause ............................................................................................................................ 8-2 constraint ................................................................................................................................................... 8-4 deallocate_unused_clause .................................................................................................................... 8-27 file_specification ................................................................................................................................... 8-29 logging_clause ........................................................................................................................................ 8-38 parallel_clause ....................................................................................................................................... 8-41 physical_attributes_clause .................................................................................................................. 8-44
  • 16. xvi size_clause .............................................................................................................................................. 8-47 storage_clause ........................................................................................................................................ 8-48 9 SQL Queries and Subqueries About Queries and Subqueries ............................................................................................................ 9-1 Creating Simple Queries ........................................................................................................................ 9-2 Hierarchical Queries ............................................................................................................................... 9-3 Hierarchical Query Examples .......................................................................................................... 9-5 The UNION [ALL], INTERSECT, MINUS Operators....................................................................... 9-8 Sorting Query Results ......................................................................................................................... 9-10 Joins ......................................................................................................................................................... 9-11 Join Conditions ............................................................................................................................... 9-11 Equijoins .......................................................................................................................................... 9-11 Self Joins .......................................................................................................................................... 9-11 Cartesian Products ......................................................................................................................... 9-12 Inner Joins ....................................................................................................................................... 9-12 Outer Joins ....................................................................................................................................... 9-12 Antijoins .......................................................................................................................................... 9-13 Semijoins .......................................................................................................................................... 9-14 Using Subqueries ................................................................................................................................. 9-14 Unnesting of Nested Subqueries ...................................................................................................... 9-15 Selecting from the DUAL Table ........................................................................................................ 9-15 Distributed Queries ............................................................................................................................. 9-16 10 SQL Statements: ALTER CLUSTER to ALTER JAVA Types of SQL Statements .................................................................................................................... 10-1 Data Definition Language (DDL) Statements ............................................................................ 10-2 Data Manipulation Language (DML) Statements ..................................................................... 10-2 Transaction Control Statements ................................................................................................... 10-3 Session Control Statements ........................................................................................................... 10-3 System Control Statement ............................................................................................................. 10-3 Embedded SQL Statements .......................................................................................................... 10-3 How the SQL Statement Chapters are Organized ......................................................................... 10-4 ALTER CLUSTER ................................................................................................................................. 10-5 ALTER DATABASE ............................................................................................................................. 10-9 ALTER DATABASE LINK ................................................................................................................ 10-46 ALTER DIMENSION ........................................................................................................................ 10-48 ALTER DISKGROUP ........................................................................................................................ 10-51 ALTER FLASHBACK ARCHIVE .................................................................................................... 10-73 ALTER FUNCTION ........................................................................................................................... 10-76 ALTER INDEX .................................................................................................................................... 10-77 ALTER INDEXTYPE .......................................................................................................................... 10-96 ALTER JAVA ........................................................................................................................................ 10-99 11 SQL Statements: ALTER LIBRARY to ALTER SYSTEM ALTER LIBRARY................................................................................................................................... 11-2
  • 17. xvii ALTER MATERIALIZED VIEW ........................................................................................................ 11-3 ALTER MATERIALIZED VIEW LOG ............................................................................................ 11-18 ALTER OPERATOR ........................................................................................................................... 11-25 ALTER OUTLINE ............................................................................................................................... 11-28 ALTER PACKAGE ............................................................................................................................. 11-30 ALTER PROCEDURE ........................................................................................................................ 11-31 ALTER PROFILE ................................................................................................................................ 11-32 ALTER RESOURCE COST ............................................................................................................... 11-35 ALTER ROLE ....................................................................................................................................... 11-38 ALTER ROLLBACK SEGMENT ..................................................................................................... 11-40 ALTER SEQUENCE ........................................................................................................................... 11-43 ALTER SESSION ................................................................................................................................ 11-45 Initialization Parameters and ALTER SESSION....................................................................... 11-50 Session Parameters and ALTER SESSION ............................................................................... 11-51 ALTER SYSTEM ................................................................................................................................. 11-58 12 SQL Statements: ALTER TABLE to ALTER TABLESPACE ALTER TABLE ....................................................................................................................................... 12-2 ALTER TABLESPACE ........................................................................................................................ 12-89 13 SQL Statements: ALTER TRIGGER to COMMIT ALTER TRIGGER ................................................................................................................................. 13-2 ALTER TYPE ......................................................................................................................................... 13-4 ALTER USER ......................................................................................................................................... 13-5 ALTER VIEW ....................................................................................................................................... 13-12 ANALYZE ............................................................................................................................................ 13-15 ASSOCIATE STATISTICS ................................................................................................................ 13-23 AUDIT .................................................................................................................................................. 13-27 CALL ..................................................................................................................................................... 13-40 COMMENT ......................................................................................................................................... 13-44 COMMIT ............................................................................................................................................. 13-47 14 SQL Statements: CREATE CLUSTER to CREATE JAVA CREATE CLUSTER .............................................................................................................................. 14-2 CREATE CONTEXT ............................................................................................................................. 14-9 CREATE CONTROLFILE ................................................................................................................. 14-12 CREATE DATABASE ......................................................................................................................... 14-19 CREATE DATABASE LINK ............................................................................................................. 14-32 CREATE DIMENSION ..................................................................................................................... 14-37 CREATE DIRECTORY ...................................................................................................................... 14-42 CREATE DISKGROUP ..................................................................................................................... 14-44 CREATE EDITION ............................................................................................................................. 14-52 CREATE FLASHBACK ARCHIVE ................................................................................................. 14-56 CREATE FUNCTION ........................................................................................................................ 14-59 CREATE INDEX ................................................................................................................................. 14-61 CREATE INDEXTYPE ....................................................................................................................... 14-87
  • 18. xviii CREATE JAVA ..................................................................................................................................... 14-91 15 SQL Statements: CREATE LIBRARY to CREATE SPFILE CREATE LIBRARY ............................................................................................................................... 15-2 CREATE MATERIALIZED VIEW ..................................................................................................... 15-3 CREATE MATERIALIZED VIEW LOG ......................................................................................... 15-26 CREATE OPERATOR ........................................................................................................................ 15-34 CREATE OUTLINE ............................................................................................................................ 15-37 CREATE PACKAGE ........................................................................................................................... 15-41 CREATE PACKAGE BODY .............................................................................................................. 15-43 CREATE PFILE .................................................................................................................................... 15-45 CREATE PROCEDURE ..................................................................................................................... 15-47 CREATE PROFILE ............................................................................................................................. 15-49 CREATE RESTORE POINT ............................................................................................................. 15-55 CREATE ROLE .................................................................................................................................... 15-58 CREATE ROLLBACK SEGMENT .................................................................................................. 15-61 CREATE SCHEMA ............................................................................................................................. 15-64 CREATE SEQUENCE ........................................................................................................................ 15-66 CREATE SPFILE ................................................................................................................................. 15-70 16 SQL Statements: CREATE SYNONYM to CREATE TRIGGER CREATE SYNONYM ........................................................................................................................... 16-2 CREATE TABLE .................................................................................................................................... 16-6 CREATE TABLESPACE ..................................................................................................................... 16-80 CREATE TRIGGER ............................................................................................................................ 16-94 17 SQL Statements: CREATE TYPE to DROP ROLLBACK SEGMENT CREATE TYPE ....................................................................................................................................... 17-3 CREATE TYPE BODY .......................................................................................................................... 17-5 CREATE USER ...................................................................................................................................... 17-7 CREATE VIEW .................................................................................................................................... 17-14 DELETE ................................................................................................................................................ 17-26 DISASSOCIATE STATISTICS ........................................................................................................ 17-34 DROP CLUSTER ................................................................................................................................ 17-36 DROP CONTEXT ............................................................................................................................... 17-38 DROP DATABASE ............................................................................................................................. 17-39 DROP DATABASE LINK ................................................................................................................. 17-40 DROP DIMENSION .......................................................................................................................... 17-41 DROP DIRECTORY .......................................................................................................................... 17-42 DROP DISKGROUP ......................................................................................................................... 17-43 DROP EDITION ................................................................................................................................. 17-45 DROP FLASHBACK ARCHIVE ..................................................................................................... 17-46 DROP FUNCTION ............................................................................................................................ 17-47 DROP INDEX....................................................................................................................................... 17-49 DROP INDEXTYPE ........................................................................................................................... 17-51 DROP JAVA ......................................................................................................................................... 17-52
  • 19. xix DROP LIBRARY ................................................................................................................................. 17-53 DROP MATERIALIZED VIEW........................................................................................................ 17-54 DROP MATERIALIZED VIEW LOG ............................................................................................. 17-56 DROP OPERATOR ............................................................................................................................ 17-58 DROP OUTLINE ................................................................................................................................ 17-59 DROP PACKAGE ............................................................................................................................... 17-61 DROP PROCEDURE ......................................................................................................................... 17-63 DROP PROFILE .................................................................................................................................. 17-64 DROP RESTORE POINT ................................................................................................................. 17-65 DROP ROLE ........................................................................................................................................ 17-66 DROP ROLLBACK SEGMENT ...................................................................................................... 17-67 18 SQL Statements: DROP SEQUENCE to ROLLBACK DROP SEQUENCE .............................................................................................................................. 18-2 DROP SYNONYM ............................................................................................................................... 18-3 DROP TABLE ........................................................................................................................................ 18-5 DROP TABLESPACE ........................................................................................................................... 18-9 DROP TRIGGER................................................................................................................................. 18-12 DROP TYPE ......................................................................................................................................... 18-13 DROP TYPE BODY ............................................................................................................................ 18-15 DROP USER ........................................................................................................................................ 18-16 DROP VIEW ........................................................................................................................................ 18-18 EXPLAIN PLAN .................................................................................................................................. 18-20 FLASHBACK DATABASE ................................................................................................................ 18-24 FLASHBACK TABLE ......................................................................................................................... 18-27 GRANT ................................................................................................................................................. 18-33 INSERT ................................................................................................................................................. 18-54 LOCK TABLE ...................................................................................................................................... 18-72 MERGE ................................................................................................................................................. 18-75 NOAUDIT ............................................................................................................................................ 18-80 PURGE .................................................................................................................................................. 18-84 RENAME .............................................................................................................................................. 18-86 REVOKE ............................................................................................................................................... 18-88 ROLLBACK ......................................................................................................................................... 18-97 19 SQL Statements: SAVEPOINT to UPDATE SAVEPOINT .......................................................................................................................................... 19-2 SELECT ................................................................................................................................................... 19-4 SET CONSTRAINT[S] ...................................................................................................................... 19-58 SET ROLE ............................................................................................................................................ 19-60 SET TRANSACTION ........................................................................................................................ 19-62 TRUNCATE CLUSTER ..................................................................................................................... 19-65 TRUNCATE TABLE ........................................................................................................................... 19-67 UPDATE ............................................................................................................................................... 19-71
  • 20. xx A How to Read Syntax Diagrams Graphic Syntax Diagrams...................................................................................................................... A-1 Required Keywords and Parameters ............................................................................................ A-2 Optional Keywords and Parameters ............................................................................................. A-3 Syntax Loops...................................................................................................................................... A-3 Multipart Diagrams ......................................................................................................................... A-4 Database Objects .............................................................................................................................. A-4 B Automatic and Manual Locking Mechanisms During SQL Operations Automatic Locks in DML Operations ................................................................................................. B-1 Automatic Locks in DDL Operations.................................................................................................. B-4 Exclusive DDL Locks........................................................................................................................ B-4 Share DDL Locks............................................................................................................................... B-5 Breakable Parse Locks ...................................................................................................................... B-5 Manual Data Locking ............................................................................................................................. B-5 C Oracle and Standard SQL ANSI Standards ...................................................................................................................................... C-1 ISO Standards .......................................................................................................................................... C-2 Oracle Compliance To Core SQL:2008................................................................................................. C-3 Oracle Support for Optional Features of SQL/Foundation:2008.................................................... C-9 Oracle Compliance with SQL/CLI:2008 ............................................................................................ C-21 Oracle Compliance with SQL/PSM:2008 .......................................................................................... C-21 Oracle Compliance with SQL/MED:2008 ......................................................................................... C-21 Oracle Compliance with SQL/OLB:2008........................................................................................... C-21 Oracle Compliance with SQL/JRT:2008 ............................................................................................ C-21 Oracle Compliance with SQL/XML:2008.......................................................................................... C-22 Oracle Compliance with FIPS 127-2 ................................................................................................. C-27 Oracle Extensions to Standard SQL .................................................................................................. C-28 Oracle Compliance with Older Standards ....................................................................................... C-29 Character Set Support........................................................................................................................... C-29 D Oracle Regular Expression Support Multilingual Regular Expression Syntax .......................................................................................... D-1 Regular Expression Operator Multilingual Enhancements............................................................ D-2 Perl-influenced Extensions in Oracle Regular Expressions ........................................................... D-3 E Oracle SQL Reserved Words F Extended Examples Using Extensible Indexing ................................................................................................................... F-1 Using XML in SQL Statements ............................................................................................................ F-8 Index
  • 21. xxi Preface This reference contains a complete description of the Structured Query Language (SQL) used to manage information in an Oracle Database. Oracle SQL is a superset of the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO) SQL:1999 standard. This Preface contains these topics: ■ Audience ■ Documentation Accessibility ■ Related Documents ■ Conventions Audience The Oracle Database SQL Language Reference is intended for all users of Oracle SQL. Documentation Accessibility Our goal is to make Oracle products, services, and supporting documentation accessible to all users, including users that are disabled. To that end, our documentation includes features that make information available to users of assistive technology. This documentation is available in HTML format, and contains markup to facilitate access by the disabled community. Accessibility standards will continue to evolve over time, and Oracle is actively engaged with other market-leading technology vendors to address technical obstacles so that our documentation can be accessible to all of our customers. For more information, visit the Oracle Accessibility Program Web site at http://www.oracle.com/accessibility/. Accessibility of Code Examples in Documentation Screen readers may not always correctly read the code examples in this document. The conventions for writing code require that closing braces should appear on an otherwise empty line; however, some screen readers may not always read a line of text that consists solely of a bracket or brace. Accessibility of Links to External Web Sites in Documentation This documentation may contain links to Web sites of other companies or organizations that Oracle does not own or control. Oracle neither evaluates nor makes any representations regarding the accessibility of these Web sites.
  • 22. xxii Deaf/Hard of Hearing Access to Oracle Support Services To reach Oracle Support Services, use a telecommunications relay service (TRS) to call Oracle Support at 1.800.223.1711. An Oracle Support Services engineer will handle technical issues and provide customer support according to the Oracle service request process. Information about TRS is available at http://www.fcc.gov/cgb/consumerfacts/trs.html, and a list of phone numbers is available at http://www.fcc.gov/cgb/dro/trsphonebk.html. Related Documents For more information, see these Oracle resources: ■ Oracle Database PL/SQL Language Reference for information on PL/SQL, the procedural language extension to Oracle SQL ■ Pro*C/C++ Programmer's Guide, Oracle SQL*Module for Ada Programmer's Guide, and the Pro*COBOL Programmer's Guide for detailed descriptions of Oracle embedded SQL Many of the examples in this book use the sample schemas, which are installed by default when you select the Basic Installation option with an Oracle Database installation. Refer to Oracle Database Sample Schemas for information on how these schemas were created and how you can use them yourself. Conventions The following text conventions are used in this document: Convention Meaning boldface Boldface type indicates graphical user interface elements associated with an action, or terms defined in text or the glossary. italic Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values. monospace Monospace type indicates commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter.
  • 23. xxiii What's New in the SQL Language Reference? This section describes new features of Oracle Database 11g and provides pointers to additional information. For information on features that were new in earlier versions of Oracle Database, refer to the documentation for the earlier release. Oracle Database 11g Release 2 New Features in the SQL Language Reference Structural Changes in the SQL Language Reference A number of sections of this book that were make up primarily of PL/SQL were moved to Oracle Database PL/SQL Language Reference in Oracle Database 11g Release 1. Please refer to "Structural Changes in the SQL Language Reference" on page xxv for details on this migration of material. New Features in the SQL Language Reference The following top-level SQL statements are new or enhanced in this release: ■ A new top-level SQL statement ALTER DATABASE LINK on page 10-46 lets you update the fixed user password in a database link when the password of a connection or authentication user has changed. ■ The ALTER DISKGROUP statement has the following changes: – A new disk_region_clause on page 10-65 lets you determine the Intelligent Data Placement attribute of the disk group file. – New diskgroup_volume_clauses on page 10-67 let you manipulate logical Oracle Automatic Storage Management (Oracle ASM) volumes corresponding to physical volume devices. – Several new clauses let you control access to Oracle ASM files: usergroup_ clauses on page 10-68, user_clauses on page 10-69, file_permissions_clause on page 10-69, and file_owner_clause on page 10-69. ■ AUDIT and NOAUDIT contain a new clause ALL STATEMENTS on page 13-30 that lets you enable and disable auditing of all top-level SQL statements executed. In AUDIT only, a new clause IN SESSION CURRENT on page 13-31 allows you to limit auditing to the current session. ■ CREATE DISKGROUP and ALTER DISKGROUP have the following changes:
  • 24. xxiv – A new clause QUORUM | REGULAR on page 14-46 let you designate a disk or failure group as a quorum disk or failure group, which can contain the voting file for Cluster Synchronization Services (CSS). ■ Two new statements, CREATE EDITION on page 14-52 and DROP EDITION on page 17-45, let you use editions. An edition makes it possible to have two or more versions of the same editionable objects in the database. ■ CREATE INDEXTYPE on page 14-87 and ALTER INDEXTYPE on page 10-96 have a new clause WITH SYSTEM MANAGED STORAGE TABLES. This clause makes it possible to create domain indexes in both range- and list-partitioned tables. ■ ALTER SESSION contains a new clause SYNC WITH PRIMARY on page 11-48 that lets you synchronize the physical standby database with the primary database. A new session parameter STANDBY_MAX_DATA_DELAY on page 11-53 lets you specify a session-specific apply lag tolerance for queries to a physical standby database that is in real-time query mode. ■ CREATE MATERIALIZED VIEW LOG has a new clause COMMIT SCN on page 15-30 that instructs the database to use commit SCN data instead of timestamps to refresh the materialized view, which improves the speed of the refresh. ■ CREATE MATERIALIZED VIEW LOG and ALTER MATERIALIZED VIEW LOG have a new clause mv_log_purge_clause on page 15-32 that lets you specify the purge time for the materialized view log. ■ CREATE TABLE and ALTER TABLE are enhanced in the following ways: – A new clause deferred_segment_creation on page 16-32 lets you postpone creation of the table segment until the first row of data is inserted into the table. This clause is also applicable to materialized views. – The clause table_compression on page 16-34 has new syntax and terminology. Use COMPRESS FOR OLTP to specify OLTP table compression. (In earlier releases, the syntax was COMPRESS FOR ALL OPERATIONS.) Use COMPRESS BASIC to specify basic table compression. (In earlier releases, the syntax was COMPRESS FOR DIRECT_LOAD OPERATIONS and this type of compression was called DSS table compression.) – A new RESULT_CACHE Clause on page 16-61 lets you specify whether the results of queries that name the table are considered for result caching. – The nested_table_col_properties on page 16-48 provides a LOCAL keyword to equipartition a nested table with partitioned base table. This is the default behavior in this release. The default in earlier releases was not to equipartition the nested table with the partitioned base table. Now you must specify the GLOBAL keyword to store an unpartitioned nested table with a partitioned base table. ■ The CREATE VIEW has a new keyword EDITIONING on page 17-17 that lets you create an editioning view. ■ The statement GRANT on page 18-33 has a new EXECUTE object privilege on directory objects. The ORACLE_LOADER access driver for external tables references this privilege when deciding whether to execute a preprocessor program. The following built-in functions are new or enhanced in this release: ■ For a specified measure, the function LISTAGG on page 5-101 orders data within each group specified in an ORDER BY clause and then concatenates the values of the measure column.
  • 25. xxv ■ A new NTH_VALUE on page 5-122 function returns the value of a measure in a specified row of a window of data. ■ Three new functions are useful when you are changing the time zone data file for your database: ORA_DST_AFFECTED on page 5-128, ORA_DST_CONVERT on page 5-129, and ORA_DST_ERROR on page 5-130. The following miscellaneous features are new or enhanced in this release: ■ Hints, which were introduced in Oracle7, are now superseded by several Oracle tools, including the SQL Tuning Advisor, SQL plan management, and SQL Performance Analyzer. See "Hints" on page 3-73 for more information. ■ Beginning with Oracle Database 11g Release 2, the PARALLEL, PARALLEL_INDEX, NO_PARALLEL, and NO_PARALLEL_INDEX hints are statement-level hints and supersede the earlier object-level hints. See "Note on Parallel Hints" on page 3-96. ■ A new APPEND_VALUES Hint on page 3-78 lets you use direct-path INSERT with the VALUES clause. ■ When specifying a redo log file, you can use the new keyword BLOCKSIZE Clause on page 8-34 to override the operating system-dependent sector size. ■ The LOB_compression_clause on page 16-45 now has a new LOW setting, which results in significantly higher decompression and compression speeds, at the cost of a slightly lower compression ratio. ■ The subquery_factoring_clause on page 19-13 now supports recursive subquery factoring (recursive WITH), which lets you query hierarchical data. This feature is more powerful than CONNECT BY in that it provides depth-first search and breadth-first search, and supports multiple recursive branches. A new search_clause on page 19-14 and cycle_clause on page 19-14 let you specify an ordering for the rows and mark cycles in the recursion. Oracle Database 11g Release 1 New Features in the SQL Language Reference Structural Changes in the SQL Language Reference A number of SQL statements are constructed almost entirely of PL/SQL elements. Those statements continue to appear in this reference, but the bulk of their syntax and semantics has been moved to Oracle Database PL/SQL Language Reference. The following table contains links to both the abbreviated SQL syntax and semantics in this book and to the full syntax and semantics in Oracle Database PL/SQL Language Reference. Abbreviated SQL Section Full Syntax and Semantics CREATE FUNCTION on page 14-59 CREATE FUNCTION CREATE PACKAGE on page 15-41 CREATE PACKAGE CREATE PACKAGE BODY on page 15-43 CREATE PACKAGE BODY CREATE PROCEDURE on page 15-47 CREATE PROCEDURE CREATE TRIGGER on page 16-94 CREATE TRIGGER CREATE TYPE on page 17-3 CREATE TYPE CREATE TYPE BODY on page 17-5 CREATE TYPE BODY ALTER FUNCTION on page 10-76 ALTER FUNCTION
  • 26. xxvi New Features in the SQL Language Reference The following top-level SQL statements are new or enhanced in this release: ■ ALTER DATABASE on page 10-9 has been enhanced as follows: – The clause managed_standby_recovery on page 10-23 has been greatly simplified. A number of subclauses have been deprecated as the database now handles much of the recovery process automatically. – The supplemental_db_logging on page 10-32 contains new syntax that lets you enable or disable supplemental logging of PL/SQL calls. – The standby_database_clauses on page 10-34 have new syntax that lets you convert a physical standby database into a snapshot standby database or convert a snapshot standby database into a physical standby database. – The clause managed_standby_recovery on page 10-23 has new KEEP IDENTITY syntax that lets you use the rolling upgrade feature provided by a logical standby and also revert to the original configuration of a primary database and a physical standby. ■ ALTER DISKGROUP on page 10-51 has been enhanced as follows: – The check_diskgroup_clause on page 10-63 has simplified syntax for checking the consistency of disk groups, disks, and files in an Oracle ASM environment. – The clause diskgroup_availability on page 10-69 offers new options when mounting a disk group. – New clauses disk_offline_clause on page 10-61 and disk_online_clause on page 10-62 let you take a disk offline for repair and then bring it back online. ■ ALTER INDEX on page 10-77 has been enhanced as follows: – A new MIGRATE parameter lets you migrate a domain index from user-managed storage tables to system-managed storage tables. – A new INVISIBLE parameter lets you modify an index so that it is invisible to the optimizer. – The "PARAMETERS Clause" on page 10-88 now lets you rebuild an XMLIndex index as well as a domain index. ■ ALTER SYSTEM on page 11-58 has been enhanced as follows: – New syntax lets you kill a session on another instance in an Oracle Real Application Clusters (Oracle RAC) environment. – New rolling_migration_clauses on page 11-66 let you prepare an Oracle ASM cluster for migration and return it to normal operation after all nodes have migrated to the same software version. ■ ALTER TABLE on page 12-2 has been enhanced as follows: ALTER PACKAGE on page 11-30 ALTER PACKAGE ALTER PROCEDURE on page 11-31 ALTER PROCEDURE ALTER TRIGGER on page 13-2 ALTER TRIGGER ALTER TYPE on page 13-4 ALTER TYPE Abbreviated SQL Section Full Syntax and Semantics
  • 27. xxvii – The behavior of the add_column_clause on page 12-41 when you specify a DEFAULT value has been enhanced for improved performance. – The syntax for READ ONLY | READ WRITE on page 12-38 lets you put a table into read-only mode, to prevent DDL or DML changes during table maintenance, and then back into read/write mode. – The clause add_table_partition on page 12-63 has expanded syntax to let you add a system partition. – The flashback_archive_clause on page 12-38 lets you enable or disable historical tracking for the table. – The add_column_clause on page 12-41 now lets you add a virtual column to a table. – A new clause alter_interval_partitioning on page 12-57 lets you convert a range-partitioned table to an interval_partitioned table. – A new dependent_tables_clause on page 12-73 lets you instruct the database to cascade various partition maintenance operations on a table to reference-partitioned child tables. ■ ALTER TABLESPACE on page 12-89 has new syntax that lets you shrink the space taken by a temporary tablespace or an individual temp file. ■ ASSOCIATE STATISTICS on page 13-23 has syntax that lets you specify that the database should manage storage of statistics collected on a system-managed domain index. ■ AUDIT on page 13-27 has new syntax that lets you audit various activities on data mining models. ■ CALL on page 13-40 now permits positional, named, and mixed notation in the argument to the routine being called, if the routine takes any arguments. ■ COMMENT on page 13-44 has a new MINING MODEL clause lets you provide descriptive comments for a data mining model. ■ CREATE DISKGROUP on page 14-44 and ALTER DISKGROUP on page 10-51 have new syntax that lets you set various attributes of a disk group. ■ The new statements CREATE FLASHBACK ARCHIVE on page 14-56, ALTER FLASHBACK ARCHIVE on page 10-73, and DROP FLASHBACK ARCHIVE on page 17-46 let you create, modify, and drop flashback data archives, which in turn let you track historical changes to tables. ■ CREATE INDEX on page 14-61 has been enhanced as follows: – A new local_domain_index_clause on page 14-78 lets you create a locally partitioned domain index. – The index_attributes on page 14-72 have been modified to let you create an index that is invisible to the optimizer. – A new XMLIndex_clause on page 14-79 lets you create an XMLIndex index for XML data. ■ CREATE INDEXTYPE on page 14-87 and ALTER INDEXTYPE on page 10-96 let you specify that domain indexes built on the subject indextypes can be range partitioned, and will have their storage tables and partition maintenance operations managed by the database. ■ CREATE PFILE on page 15-45 has new syntax that lets you create a parameter file from current system-wide parameter settings.
  • 28. xxviii ■ CREATE RESTORE POINT on page 15-55 has new syntax that lets you create a restore point for a specified datetime or SCN in the past, and to preserve a flashback database. ■ CREATE SPFILE on page 15-70 has new syntax that lets you create a system parameter file from current system-wide parameter settings. ■ CREATE TABLE on page 16-6 has been enhanced as follows: – The flashback_archive_clause on page 16-64 lets you create the table with tracking of historical changes enabled – The clause system_partitioning on page 16-59 lets you partition the table BY SYSTEM – A new virtual_column_definition on page 16-28 lets you create a virtual column. – New syntax for XML storage lets you store XML data in binary XML format. – A new clause reference_partitioning on page 16-55 lets you partition a table by reference to another partitioned table. – The LOB_parameters on page 16-43 now include a SECUREFILE parameter, which lets you specify a new storage for LOBs that is faster, more efficient, and allows for new features such as LOB compression, encryption, and deduplication. – A new LOB_compression_clause on page 16-45 lets you enable or disable server-side LOB compression for LOBs using SecureFile storage. – A new LOB_deduplicate_clause on page 16-45 lets you coalesce duplicate data into a single shared repository, reducing storage consumption and simplifying storage management for LOBs using SecureFile storage. – The LOB_parameters on page 16-43 now include ENCRYPT and DECRYPT clauses to enable and disable encryption of LOB columns for LOBs using SecureFile storage. ■ CREATE TABLESPACE on page 16-80 has new syntax which, along with a new ENCRYPT keyword in the storage_clause on page 8-48, lets you encrypt an entire tablespace. ■ DROP DISKGROUP on page 17-43 has a new FORCE keyword that lets you drop a disk group that can no longer be mounted by an Oracle ASM instance. ■ GRANT on page 18-33 contains several new system and object privileges that enable the grantee to work with data mining models. ■ LOCK TABLE on page 18-72 has new syntax that lets you specify the maximum number of seconds the statement should wait to obtain a DML lock on the table. ■ MERGE on page 18-75 now supports operations on tables with domain indexes. ■ SELECT on page 19-4 has new PIVOT syntax that lets you rotate rows into columns. A new UNPIVOT operation lets you query data to rotate columns into rows. The following SQL built-in functions have been added or enhanced: ■ CUBE_TABLE on page 5-51 is a new built-in function that extracts data from a cube or dimension and returns it in the two-dimensional format of a relational table. ■ INSERTXMLAFTER on page 5-89 let you add one or more nodes of any kind immediately after a target node that is not an attribute node.
  • 29. xxix ■ REGEXP_INSTR on page 5-160 and REGEXP_SUBSTR on page 5-164 now have an optional subexpr parameter that lets you target a particular substring of the regular expression being evaluated. ■ REGEXP_COUNT on page 5-158 is a new built-in function that counts the number of occurrences of a specified regular expression pattern in a source string. ■ PREDICTION on page 5-139, PREDICTION_COST on page 5-142, and PREDICTION_SET on page 5-147 have been enhanced. New syntax let you specify that the stored cost matrix should be used only if it is available, or to specify a cost matrix inline. ■ PREDICTION_BOUNDS on page 5-141 is a new function that returns the lower and upper confidence bounds for a prediction. ■ XMLCAST on page 5-250 and XMLEXISTS on page 5-257 are two new functions that let you cast XML data to SQL scalar data types and determine whether an XQuery expression returns a nonempty XQuery sequence, respectively. ■ XMLDIFF on page 5-254 and XMLPATCH on page 5-260 are two new functions that provide SQL interfaces to the corresponding XMLDiff and XMLPatch C APIs. They let you compare two XMLType documents and use the diff file to patch an XMLType document. The following miscellaneous changes have been made: ■ In earlier releases, one form of expression in Chapter 6, "Expressions" was the variable expression. This form has been renamed to placeholder expression for consistency with other books in the documentation set. See "Placeholder Expressions" on page 6-14. ■ In earlier releases, the TRUNCATE statement was presented as a single statement with separate syntactic branches for TABLE and CLUSTER. That command has now been divided into TRUNCATE CLUSTER on page 19-65 and TRUNCATE TABLE on page 19-67 for consistency with other top-level SQL statements. No actual syntax or semantic changes have occurred. ■ Two new hints, "RESULT_CACHE Hint" on page 3-102 and "NO_RESULT_ CACHE Hint" on page 3-93, let you override settings of the RESULT_CACHE_MODE initialization parameter. ■ "Function Expressions" on page 6-10 now permit positional, named, and mixed notation in the argument to a user-defined function being used as an expression. ■ The index_partition_description syntax of ALTER TABLE on page 12-2 and ALTER INDEX on page 10-77 now lets you specify parameters for a partition of a domain index. ■ A new object type object type is supported with Oracle Multimedia. See ORDDicom on page 3-36
  • 30. xxx
  • 31. 1 Introduction to Oracle SQL 1-1 1 Introduction to Oracle SQL Structured Query Language (SQL) is the set of statements with which all programs and users access data in an Oracle Database. Application programs and Oracle tools often allow users access to the database without using SQL directly, but these applications in turn must use SQL when executing the user's request. This chapter provides background information on SQL as used by most database systems. This chapter contains these topics: ■ History of SQL ■ SQL Standards ■ Lexical Conventions ■ Tools Support History of SQL Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared Data Banks", in June 1970 in the Association of Computer Machinery (ACM) journal, Communications of the ACM. Codd's model is now accepted as the definitive model for relational database management systems (RDBMS). The language, Structured English Query Language (SEQUEL) was developed by IBM Corporation, Inc., to use Codd's model. SEQUEL later became SQL (still pronounced "sequel"). In 1979, Relational Software, Inc. (now Oracle) introduced the first commercially available implementation of SQL. Today, SQL is accepted as the standard RDBMS language. SQL Standards Oracle strives to comply with industry-accepted standards and participates actively in SQL standards committees. Industry-accepted committees are the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO), which is affiliated with the International Electrotechnical Commission (IEC). Both ANSI and the ISO/IEC have accepted SQL as the standard language for relational databases. When a new SQL standard is simultaneously published by these organizations, the names of the standards conform to conventions used by the organization, but the standards are technically identical. The latest SQL standard was adopted in July 2008 and is often called SQL:2008. The formal names of this standard are: ■ ANSI/ISO/IEC 9075:2008, "Database Language SQL", Parts 1 ("SQL/Framework"), 2 ("SQL/Foundation"), 3 ("SQL/CLI"), 4 ("SQL/PSM"), 9
  • 32. SQL Standards 1-2 Oracle Database SQL Language Reference ("SQL/MED"), 10 ("SQL/OLB"), 11("SQL/Schemata"), 13 ("SQL/JRT"), and ANSI/ISO/IEC 9075-14:2008, "Database Language SQL", Part 14 ("SQL/XML") ■ ISO/IEC 9075:2008, "Database Language SQL", Parts 1 ("SQL/Framework"), 2 ("SQL/Foundation"), 3 ("SQL/CLI"), 4 ("SQL/PSM"), 9 ("SQL/MED"), 10 ("SQL/OLB"), 11("SQL/Schemata"), 13 ("SQL/JRT"), and ISO/IEC 9075-14:2008, "Database Language SQL", Part 14 ("SQL/XML") How SQL Works The strengths of SQL provide benefits for all types of users, including application programmers, database administrators, managers, and end users. Technically speaking, SQL is a data sublanguage. The purpose of SQL is to provide an interface to a relational database such as Oracle Database, and all SQL statements are instructions to the database. In this SQL differs from general-purpose programming languages like C and BASIC. Among the features of SQL are the following: ■ It processes sets of data as groups rather than as individual units. ■ It provides automatic navigation to the data. ■ It uses statements that are complex and powerful individually, and that therefore stand alone. Flow-control statements were not part of SQL originally, but they are found in the recently accepted optional part of SQL, ISO/IEC 9075-5: 1996. Flow-control statements are commonly known as "persistent stored modules" (PSM), and the PL/SQL extension to Oracle SQL is similar to PSM. SQL lets you work with data at the logical level. You need to be concerned with the implementation details only when you want to manipulate the data. For example, to retrieve a set of rows from a table, you define a condition used to filter the rows. All rows satisfying the condition are retrieved in a single step and can be passed as a unit to the user, to another SQL statement, or to an application. You need not deal with the rows one by one, nor do you have to worry about how they are physically stored or retrieved. All SQL statements use the optimizer, a part of Oracle Database that determines the most efficient means of accessing the specified data. Oracle also provides techniques that you can use to make the optimizer perform its job better. SQL provides statements for a variety of tasks, including: ■ Querying data ■ Inserting, updating, and deleting rows in a table ■ Creating, replacing, altering, and dropping objects ■ Controlling access to the database and its objects ■ Guaranteeing database consistency and integrity SQL unifies all of the preceding tasks in one consistent language. Common Language for All Relational Databases All major relational database management systems support SQL, so you can transfer all skills you have gained with SQL from one database to another. In addition, all programs written in SQL are portable. They can often be moved from one database to another with very little modification. See Also: Appendix C, "Oracle and Standard SQL" for a detailed description of Oracle Database conformance to the SQL:2008 standards
  • 33. Tools Support Introduction to Oracle SQL 1-3 Using Enterprise Manager Many of the operations you can accomplish using SQL syntax can be done much more easily using Enterprise Manager. For more information, see the Oracle Enterprise Manager documentation set, Oracle Database 2 Day DBA, or any of the Oracle Database 2 Day + books. Lexical Conventions The following lexical conventions for issuing SQL statements apply specifically to the Oracle Database implementation of SQL, but are generally acceptable in other SQL implementations. When you issue a SQL statement, you can include one or more tabs, carriage returns, spaces, or comments anywhere a space occurs within the definition of the statement. Thus, Oracle Database evaluates the following two statements in the same manner: SELECT last_name,salary*12,MONTHS_BETWEEN(hire_date, SYSDATE) FROM employees WHERE department_id = 30 ORDER BY last_name; SELECT last_name, salary * 12, MONTHS_BETWEEN( hire_date, SYSDATE ) FROM employees WHERE department_id = 30 ORDER BY last_name; Case is insignificant in reserved words, keywords, identifiers and parameters. However, case is significant in text literals and quoted names. Refer to "Text Literals" on page 3-46 for a syntax description of text literals. Tools Support Oracle provides a number of utilities to facilitate your SQL development process: ■ Oracle SQL Developer is a graphical tool that lets you browse, create, edit, and delete (drop) database objects, edit and debug PL/SQL code, run SQL statements and scripts, manipulate and export data, and create and view reports. With SQL Developer, you can connect to any target Oracle Database schema using standard Oracle Database authentication. Once connected, you can perform operations on objects in the database. You can also connect to schemas for selected third-party (non-Oracle) databases, such as MySQL, Microsoft SQL Server, and Microsoft Access, view metadata and data in these databases, and migrate these databases to Oracle. ■ SQL*Plus is an interactive and batch query tool that is installed with every Oracle Database server or client installation. It has a command-line user interface and a web-based user interface called iSQL*Plus. ■ Oracle JDeveloper is a multiple-platform integrated development environment supporting the complete lifecycle of development for Java, Web services, and SQL. It provides a graphical interface for executing and tuning SQL statements and a Note: SQL statements are terminated differently in different programming environments. This documentation set uses the default SQL*Plus character, the semicolon (;).
  • 34. Tools Support 1-4 Oracle Database SQL Language Reference visual schema diagrammer (database modeler). It also supports editing, compiling, and debugging PL/SQL applications. ■ Oracle Application Express is a hosted environment for developing and deploying database-related Web applications. SQL Workshop is a component of Oracle Application Express that lets you view and manage database objects from a Web browser. SQL Workshop offers quick access to a SQL command processor and a SQL script repository. The Oracle Call Interface and Oracle precompilers let you embed standard SQL statements within a procedure programming language. ■ The Oracle Call Interface (OCI) lets you embed SQL statements in C programs. ■ The Oracle precompilers, Pro*C/C++ and Pro*COBOL, interpret embedded SQL statements and translate them into statements that can be understood by C/C++ and COBOL compilers, respectively. Most (but not all) Oracle tools also support all features of Oracle SQL. This reference describes the complete functionality of SQL. If the Oracle tool that you are using does not support this complete functionality, then you can find a discussion of the restrictions in the manual describing the tool, such as SQL*Plus User's Guide and Reference. See Also: SQL*Plus User's Guide and Reference and Oracle Application Express Application Builder User's Guide for more information on these products See Also: Oracle C++ Call Interface Programmer's Guide, Pro*COBOL Programmer's Guide, and Oracle Call Interface Programmer's Guide for additional information on the embedded SQL statements allowed in each product
  • 35. 2 Pseudocolumns 2-1 2 Pseudocolumns A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. A pseudocolumn is also similar to a function without arguments (refer to Chapter 5, "Functions"). However, functions without arguments typically return the same value for every row in the result set, whereas pseudocolumns typically return a different value for each row. This chapter contains the following sections: ■ Hierarchical Query Pseudocolumns ■ Sequence Pseudocolumns ■ Version Query Pseudocolumns ■ COLUMN_VALUE Pseudocolumn ■ OBJECT_ID Pseudocolumn ■ OBJECT_VALUE Pseudocolumn ■ ORA_ROWSCN Pseudocolumn ■ ROWID Pseudocolumn ■ ROWNUM Pseudocolumn ■ XMLDATA Pseudocolumn Hierarchical Query Pseudocolumns The hierarchical query pseudocolumns are valid only in hierarchical queries. The hierarchical query pseudocolumns are: ■ CONNECT_BY_ISCYCLE Pseudocolumn ■ CONNECT_BY_ISLEAF Pseudocolumn ■ LEVEL Pseudocolumn To define a hierarchical relationship in a query, you must use the CONNECT BY clause. CONNECT_BY_ISCYCLE Pseudocolumn The CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a child which is also its ancestor. Otherwise it returns 0.
  • 36. Hierarchical Query Pseudocolumns 2-2 Oracle Database SQL Language Reference You can specify CONNECT_BY_ISCYCLE only if you have specified the NOCYCLE parameter of the CONNECT BY clause. NOCYCLE enables Oracle to return the results of a query that would otherwise fail because of a CONNECT BY loop in the data. CONNECT_BY_ISLEAF Pseudocolumn The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a leaf of the tree defined by the CONNECT BY condition. Otherwise it returns 0. This information indicates whether a given row can be further expanded to show more of the hierarchy. CONNECT_BY_ISLEAF Example The following example shows the first three levels of the hr.employees table, indicating for each row whether it is a leaf row (indicated by 1 in the IsLeaf column) or whether it has child rows (indicated by 0 in the IsLeaf column): SELECT last_name "Employee", CONNECT_BY_ISLEAF "IsLeaf", LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path" FROM employees WHERE LEVEL <= 3 AND department_id = 80 START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id AND LEVEL <= 4; Employee IsLeaf LEVEL Path ------------------------- ---------- ---------- ------------------------- Abel 1 3 /King/Zlotkey/Abel Ande 1 3 /King/Errazuriz/Ande Banda 1 3 /King/Errazuriz/Banda Bates 1 3 /King/Cambrault/Bates Bernstein 1 3 /King/Russell/Bernstein Bloom 1 3 /King/Cambrault/Bloom Cambrault 0 2 /King/Cambrault Cambrault 1 3 /King/Russell/Cambrault Doran 1 3 /King/Partners/Doran Errazuriz 0 2 /King/Errazuriz Fox 1 3 /King/Cambrault/Fox . . . LEVEL Pseudocolumn For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root row, 2 for a child of a root, and so on. A root row is the highest row within an inverted tree. A child row is any nonroot row. A parent row is any row that has children. A leaf row is any row without children. Figure 2–1 shows the nodes of an inverted tree with their LEVEL values. See Also: "Hierarchical Queries" on page 9-3 for more information about the NOCYCLE parameter and "Hierarchical Query Examples" on page 9-5 for an example that uses the CONNECT_BY_ISCYCLE pseudocolumn See Also: "Hierarchical Queries" on page 9-3 and SYS_CONNECT_ BY_PATH on page 5-201
  • 37. Sequence Pseudocolumns Pseudocolumns 2-3 Figure 2–1 Hierarchical Tree Sequence Pseudocolumns A sequence is a schema object that can generate unique sequential values. These values are often used for primary and unique keys. You can refer to sequence values in SQL statements with these pseudocolumns: ■ CURRVAL: Returns the current value of a sequence ■ NEXTVAL: Increments the sequence and returns the next value You must qualify CURRVAL and NEXTVAL with the name of the sequence: sequence.CURRVAL sequence.NEXTVAL To refer to the current or next value of a sequence in the schema of another user, you must have been granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privilege, and you must qualify the sequence with the schema containing it: schema.sequence.CURRVAL schema.sequence.NEXTVAL To refer to the value of a sequence on a remote database, you must qualify the sequence with a complete or partial name of a database link: schema.sequence.CURRVAL@dblink schema.sequence.NEXTVAL@dblink A sequence can be accessed by many users concurrently with no waiting or locking. Where to Use Sequence Values You can use CURRVAL and NEXTVAL in the following locations: ■ The select list of a SELECT statement that is not contained in a subquery, materialized view, or view See Also: "Hierarchical Queries" on page 9-3 for information on hierarchical queries in general and "IN Condition" on page 7-22 for restrictions on using the LEVEL pseudocolumn See Also: "References to Objects in Remote Databases" on page 3-113 for more information on referring to database links Level 1 Level 2 Level 3 Level 4 child/ leaf parent/ child root/ parent parent/ child child/ leaf child/ leaf child/ leaf child/ leaf parent/ child parent/ child
  • 38. Sequence Pseudocolumns 2-4 Oracle Database SQL Language Reference ■ The select list of a subquery in an INSERT statement ■ The VALUES clause of an INSERT statement ■ The SET clause of an UPDATE statement Restrictions on Sequence Values You cannot use CURRVAL and NEXTVAL in the following constructs: ■ A subquery in a DELETE, SELECT, or UPDATE statement ■ A query of a view or of a materialized view ■ A SELECT statement with the DISTINCT operator ■ A SELECT statement with a GROUP BY clause or ORDER BY clause ■ A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator ■ The WHERE clause of a SELECT statement ■ The DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement ■ The condition of a CHECK constraint Within a single SQL statement that uses CURRVAL or NEXTVAL, all referenced LONG columns, updated tables, and locked tables must be located on the same database. How to Use Sequence Values When you create a sequence, you can define its initial value and the increment between its values. The first reference to NEXTVAL returns the initial value of the sequence. Subsequent references to NEXTVAL increment the sequence value by the defined increment and return the new value. Any reference to CURRVAL always returns the current value of the sequence, which is the value returned by the last reference to NEXTVAL. Before you use CURRVAL for a sequence in your session, you must first initialize the sequence with NEXTVAL. Refer to CREATE SEQUENCE on page 15-66 for information on sequences. Within a single SQL statement containing a reference to NEXTVAL, Oracle increments the sequence once: ■ For each row returned by the outer query block of a SELECT statement. Such a query block can appear in the following places: – A top-level SELECT statement – An INSERT ... SELECT statement (either single-table or multitable). For a multitable insert, the reference to NEXTVAL must appear in the VALUES clause, and the sequence is updated once for each row returned by the subquery, even though NEXTVAL may be referenced in multiple branches of the multitable insert. – A CREATE TABLE ... AS SELECT statement – A CREATE MATERIALIZED VIEW ... AS SELECT statement ■ For each row updated in an UPDATE statement ■ For each INSERT statement containing a VALUES clause ■ For each INSERT ... [ALL | FIRST] statement (multitable insert). A multitable insert is considered a single SQL statement. Therefore, a reference to the NEXTVAL
  • 39. Sequence Pseudocolumns Pseudocolumns 2-5 of a sequence will increase the sequence only once for each input record coming from the SELECT portion of the statement. If NEXTVAL is specified more than once in any part of the INSERT ... [ALL | FIRST ] statement, then the value will be the same for all insert branches, regardless of how often a given record might be inserted. ■ For each row merged by a MERGE statement. The reference to NEXTVAL can appear in the merge_insert_clause or the merge_update_clause or both. The NEXTVALUE value is incremented for each row updated and for each row inserted, even if the sequence number is not actually used in the update or insert operation. If NEXTVAL is specified more than once in any of these locations, then the sequence is incremented once for each row and returns the same value for all occurrences of NEXTVAL for that row. ■ For each input row in a multitable INSERT ALL statement. NEXTVAL is incremented once for each row returned by the subquery, regardless of how many occurrences of the insert_into_clause map to each row. If any of these locations contains more than one reference to NEXTVAL, then Oracle increments the sequence once and returns the same value for all occurrences of NEXTVAL. If any of these locations contains references to both CURRVAL and NEXTVAL, then Oracle increments the sequence and returns the same value for both CURRVAL and NEXTVAL. Finding the next value of a sequence: Example This example selects the next value of the employee sequence in the sample schema hr: SELECT employees_seq.nextval FROM DUAL; Inserting sequence values into a table: Example This example increments the employee sequence and uses its value for a new employee inserted into the sample table hr.employees: INSERT INTO employees VALUES (employees_seq.nextval, 'John', 'Doe', 'jdoe', '555-1212', TO_DATE(SYSDATE), 'PU_CLERK', 2500, null, null, 30); Reusing the current value of a sequence: Example This example adds a new order with the next order number to the master order table. It then adds suborders with this number to the detail order table: INSERT INTO orders (order_id, order_date, customer_id) VALUES (orders_seq.nextval, TO_DATE(SYSDATE), 106); INSERT INTO order_items (order_id, line_item_id, product_id) VALUES (orders_seq.currval, 1, 2359); INSERT INTO order_items (order_id, line_item_id, product_id) VALUES (orders_seq.currval, 2, 3290); INSERT INTO order_items (order_id, line_item_id, product_id) VALUES (orders_seq.currval, 3, 2381);
  • 40. Version Query Pseudocolumns 2-6 Oracle Database SQL Language Reference Version Query Pseudocolumns The version query pseudocolumns are valid only in Oracle Flashback Version Query, which is a form of Oracle Flashback Query. The version query pseudocolumns are: ■ VERSIONS_STARTSCN and VERSIONS_STARTTIME: Starting System Change Number (SCN) or TIMESTAMP when the row version was created. This pseudocolumn identifies the time when the data first had the values reflected in the row version. Use this pseudocolumn to identify the past target time for Oracle Flashback Table or Oracle Flashback Query. If this pseudocolumn is NULL, then the row version was created before start. ■ VERSIONS_ENDSCN and VERSIONS_ENDTIME: SCN or TIMESTAMP when the row version expired. If the pseudocolumn is NULL, then either the row version was current at the time of the query or the row corresponds to a DELETE operation. ■ VERSIONS_XID: Identifier (a RAW number) of the transaction that created the row version. ■ VERSIONS_OPERATION: Operation performed by the transaction: I for insertion, D for deletion, or U for update. The version is that of the row that was inserted, deleted, or updated; that is, the row after an INSERT operation, the row before a DELETE operation, or the row affected by an UPDATE operation. For user updates of an index key, Oracle Flashback Version Query might treat an UPDATE operation as two operations, DELETE plus INSERT, represented as two version rows with a D followed by an I VERSIONS_OPERATION. COLUMN_VALUE Pseudocolumn When you refer to an XMLTable construct without the COLUMNS clause, or when you use the TABLE collection expression to refer to a scalar nested table type, the database returns a virtual table with a single column. This name of this pseudocolumn is COLUMN_VALUE. In the context of XMLTable, the value returned is of data type XMLType. For example, the following two statements are equivalent, and the output for both shows COLUMN_ VALUE as the name of the column being returned: SELECT * FROM XMLTABLE('<a>123</a>'); COLUMN_VALUE --------------------------------------- <a>123</a> SELECT COLUMN_VALUE FROM (XMLTable('<a>123</a>')); COLUMN_VALUE ---------------------------------------- <a>123</a> In the context of a TABLE collection expression, the value returned is the data type of the collection element. The following statements create the two levels of nested tables See Also: ■ flashback_query_clause on page 19-17 for more information on version queries ■ Oracle Database Advanced Application Developer's Guide for more information on using Oracle Flashback Version Query
  • 41. OBJECT_ID Pseudocolumn Pseudocolumns 2-7 illustrated in "Creating a Table: Multilevel Collection Example" on page 16-71 to show the uses of COLUMN_VALUE in this context: CREATE TYPE phone AS TABLE OF NUMBER; / CREATE TYPE phone_list AS TABLE OF phone; / The next statement uses COLUMN_VALUE to select from the phone type: SELECT t.COLUMN_VALUE from table(phone(1,2,3)) t; COLUMN_VALUE ------------ 1 2 3 In a nested type, you can use the COLUMN_VALUE pseudocolumn in both the select list and the TABLE collection expression: SELECT t.COLUMN_VALUE FROM TABLE(phone_list(phone(1,2,3))) p, TABLE(p.COLUMN_VALUE) t; COLUMN_VALUE ------------ 1 2 3 The keyword COLUMN_VALUE is also the name that Oracle Database generates for the scalar value of an inner nested table without a column or attribute name, as shown in the example that follows. In this context, COLUMN_VALUE is not a pseudocolumn, but an actual column name. CREATE TABLE my_customers ( cust_id NUMBER, name VARCHAR2(25), phone_numbers phone_list, credit_limit NUMBER) NESTED TABLE phone_numbers STORE AS outer_ntab (NESTED TABLE COLUMN_VALUE STORE AS inner_ntab); OBJECT_ID Pseudocolumn The OBJECT_ID pseudocolumn returns the object identifier of a column of an object table or view. Oracle uses this pseudocolumn as the primary key of an object table. OBJECT_ID is useful in INSTEAD OF triggers on views and for identifying the ID of a substitutable row in an object table. See Also: ■ XMLTABLE on page 5-267 for information on that function ■ table_collection_expression::= on page 18-57 for information on the TABLE collection expression ■ ALTER TABLE examples in "Nested Tables: Examples" on page 12-87
  • 42. OBJECT_VALUE Pseudocolumn 2-8 Oracle Database SQL Language Reference OBJECT_VALUE Pseudocolumn The OBJECT_VALUE pseudocolumn returns system-generated names for the columns of an object table, XMLType table, object view, or XMLType view. This pseudocolumn is useful for identifying the value of a substitutable row in an object table and for creating object views with the WITH OBJECT IDENTIFIER clause. ORA_ROWSCN Pseudocolumn For each row, ORA_ROWSCN returns the conservative upper bound system change number (SCN) of the most recent change to the row in the current session. This pseudocolumn is useful for determining approximately when a row was last updated. It is not absolutely precise, because Oracle tracks SCNs by transaction committed for the block in which the row resides. You can obtain a more fine-grained approximation of the SCN by creating your tables with row-level dependency tracking. Refer to CREATE TABLE ... NOROWDEPENDENCIES | ROWDEPENDENCIES on page 16-62 for more information on row-level dependency tracking. You cannot use this pseudocolumn in a query to a view. However, you can use it to refer to the underlying table when creating a view. You can also use this pseudocolumn in the WHERE clause of an UPDATE or DELETE statement. ORA_ROWSCN is not supported for Flashback Query. Instead, use the version query pseudocolumns, which are provided explicitly for Flashback Query. Refer to the SELECT ... flashback_query_clause on page 19-17 for information on Flashback Query and "Version Query Pseudocolumns" on page 2-6 for additional information on those pseudocolumns. Restriction on ORA_ROWSCN: This pseudocolumn is not supported for external tables. Example The first statement below uses the ORA_ROWSCN pseudocolumn to get the system change number of the last operation on the employees table. The second Note: In earlier releases, this pseudocolumn was called SYS_NC_ OID$. That name is still supported for backward compatibility. However, Oracle recommends that you use the more intuitive name OBJECT_ID. See Also: Oracle Database Object-Relational Developer's Guide for examples of the use of this pseudocolumn Note: In earlier releases, this pseudocolumn was called SYS_NC_ ROWINFO$. That name is still supported for backward compatibility. However, Oracle recommends that you use the more intuitive name OBJECT_VALUE. See Also: ■ object_table on page 16-66 and object_view_clause on page 17-18 for more information on the use of this pseudocolumn ■ Oracle Database Object-Relational Developer's Guide for examples of the use of this pseudocolumn
  • 43. ROWNUM Pseudocolumn Pseudocolumns 2-9 statement uses the pseudocolumn with the SCN_TO_TIMESTAMP function to determine the timestamp of the operation: SELECT ORA_ROWSCN, last_name FROM employees WHERE employee_id = 188; SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN), last_name FROM employees WHERE employee_id = 188; ROWID Pseudocolumn For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row: ■ The data object number of the object ■ The data block in the data file in which the row resides ■ The position of the row in the data block (first row is 0) ■ The data file in which the row resides (first file is 1). The file number is relative to the tablespace. Usually, a rowid value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same rowid. Values of the ROWID pseudocolumn have the data type ROWID or UROWID. Refer to "Rowid Data Types" on page 3-27 and "UROWID Data Type" on page 3-28 for more information. Rowid values have several important uses: ■ They are the fastest way to access a single row. ■ They can show you how the rows in a table are stored. ■ They are unique identifiers for rows in a table. You should not use ROWID as the primary key of a table. If you delete and reinsert a row with the Import and Export utilities, for example, then its rowid may change. If you delete a row, then Oracle may reassign its rowid to a new row inserted later. Although you can use the ROWID pseudocolumn in the SELECT and WHERE clause of a query, these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete a value of the ROWID pseudocolumn. Example This statement selects the address of all rows that contain data for employees in department 20: SELECT ROWID, last_name FROM employees WHERE department_id = 20; ROWNUM Pseudocolumn See Also: SCN_TO_TIMESTAMP on page 5-178 Note: The ROW_NUMBER built-in SQL function provides superior support for ordering the results of a query. Refer to ROW_NUMBER on page 5-174 for more information.
  • 44. XMLDATA Pseudocolumn 2-10 Oracle Database SQL Language Reference For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on. You can use ROWNUM to limit the number of rows returned by a query, as in this example: SELECT * FROM employees WHERE ROWNUM < 11; If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed. For example, if the ORDER BY clause causes Oracle to use an index to access the data, then Oracle may retrieve the rows in a different order than without the index. Therefore, the following statement does not necessarily return the same rows as the preceding example: SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY last_name; If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query, then you can force the ROWNUM condition to be applied after the ordering of the rows. For example, the following query returns the employees with the 10 smallest employee numbers. This is sometimes referred to as top-N reporting: SELECT * FROM (SELECT * FROM employees ORDER BY employee_id) WHERE ROWNUM < 11; In the preceding example, the ROWNUM values are those of the top-level SELECT statement, so they are generated after the rows have already been ordered by employee_id in the subquery. Conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows: SELECT * FROM employees WHERE ROWNUM > 1; The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned. You can also use ROWNUM to assign unique values to each row of a table, as in this example: UPDATE my_table SET column1 = ROWNUM; Refer to the function ROW_NUMBER on page 5-174 for an alternative method of assigning unique numbers to rows. XMLDATA Pseudocolumn Oracle stores XMLType data either in LOB or object-relational columns, based on XMLSchema information and how you specify the storage clause. The XMLDATA pseudocolumn lets you access the underlying LOB or object relational column to specify additional storage clause parameters, constraints, indexes, and so forth. Note: Using ROWNUM in a query can affect view optimization.
  • 45. XMLDATA Pseudocolumn Pseudocolumns 2-11 Example The following statements illustrate the use of this pseudocolumn. Suppose you create a simple table of XMLType: CREATE TABLE xml_lob_tab of XMLTYPE; The default storage is in a CLOB column. To change the storage characteristics of the underlying LOB column, you can use the following statement: ALTER TABLE xml_lob_tab MODIFY LOB (XMLDATA) (STORAGE (MAXSIZE 2G) CACHE); Now suppose you have created an XMLSchema-based table like the xwarehouses table created in "Using XML in SQL Statements" on page F-8. You could then use the XMLDATA column to set the properties of the underlying columns, as shown in the following statement: ALTER TABLE xwarehouses ADD (UNIQUE(XMLDATA."WarehouseId"));
  • 46. XMLDATA Pseudocolumn 2-12 Oracle Database SQL Language Reference
  • 47. 3 Basic Elements of Oracle SQL 3-1 3 Basic Elements of Oracle SQL This chapter contains reference information on the basic elements of Oracle SQL. These elements are the simplest building blocks of SQL statements. Therefore, before using the statements described in Chapter 10 through Chapter 19, you should familiarize yourself with the concepts covered in this chapter. This chapter contains these sections: ■ Data Types ■ Data Type Comparison Rules ■ Literals ■ Format Models ■ Nulls ■ Comments ■ Database Objects ■ Database Object Names and Qualifiers ■ Syntax for Schema Objects and Parts in SQL Statements Data Types Each value manipulated by Oracle Database has a data type. The data type of a value associates a fixed set of properties with the value. These properties cause Oracle to treat values of one data type differently from values of another. For example, you can add values of NUMBER data type, but not values of RAW data type. When you create a table or cluster, you must specify a data type for each of its columns. When you create a procedure or stored function, you must specify a data type for each of its arguments. These data types define the domain of values that each column can contain or each argument can have. For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values 2 or 'SHOE'. Each value subsequently placed in a column assumes the data type of the column. For example, if you insert '01-JAN-98' into a DATE column, then Oracle treats the '01-JAN-98' character string as a DATE value after verifying that it translates to a valid date. Oracle Database provides a number of built-in data types as well as several categories for user-defined types that can be used as data types. The syntax of Oracle data types appears in the diagrams that follow. The text of this section is divided into the following sections: ■ Oracle Built-in Data Types
  • 48. Data Types 3-2 Oracle Database SQL Language Reference ■ ANSI, DB2, and SQL/DS Data Types ■ User-Defined Types ■ Oracle-Supplied Types ■ Data Type Comparison Rules ■ Data Conversion A data type is either scalar or nonscalar. A scalar type contains an atomic value, whereas a nonscalar (sometimes called a "collection") contains a set of values. A large object (LOB) is a special form of scalar data type representing a large scalar value of binary or character data. LOBs are subject to some restrictions that do not affect other scalar types because of their size. Those restrictions are documented in the context of the relevant SQL syntax. The Oracle precompilers recognize other data types in embedded SQL programs. These data types are called external data types and are associated with host variables. Do not confuse built-in data types and user-defined types with external data types. For information on external data types, including how Oracle converts between them and built-in data types or user-defined types, see Pro*COBOL Programmer's Guide, and Pro*C/C++ Programmer's Guide. datatypes::= Oracle_built_in_datatypes::= For descriptions of the Oracle built-in data types, refer to "Oracle Built-in Data Types" on page 3-6. See Also: "Restrictions on LOB Columns" on page 3-25 Oracle_built_in_datatypes ANSI_supported_datatypes user_defined_types Oracle_supplied_types character_datatypes number_datatypes long_and_raw_datatypes datetime_datatypes large_object_datatypes rowid_datatypes
  • 49. Data Types Basic Elements of Oracle SQL 3-3 character_datatypes::= number_datatypes::= long_and_raw_datatypes::= datetime_datatypes::= CHAR ( size BYTE CHAR ) VARCHAR2 ( size BYTE CHAR ) NCHAR ( size ) NVARCHAR2 ( size ) NUMBER ( precision , scale ) FLOAT ( precision ) BINARY_FLOAT BINARY_DOUBLE LONG LONG RAW RAW ( size ) DATE TIMESTAMP ( fractional_seconds_precision ) WITH LOCAL TIME ZONE INTERVAL YEAR ( year_precision ) TO MONTH INTERVAL DAY ( day_precision ) TO SECOND ( fractional_seconds_precision )
  • 50. Data Types 3-4 Oracle Database SQL Language Reference large_object_datatypes::= rowid_datatypes::= The ANSI-supported data types appear in the figure that follows. "ANSI, DB2, and SQL/DS Data Types" on page 3-28 discusses the mapping of ANSI-supported data types to Oracle built-in data types. ANSI_supported_datatypes::= BLOB CLOB NCLOB BFILE ROWID UROWID ( size ) CHARACTER VARYING ( size ) CHAR NCHAR VARYING ( size ) VARCHAR ( size ) NATIONAL CHARACTER CHAR VARYING ( size ) NUMERIC DECIMAL DEC ( precision , scale ) INTEGER INT SMALLINT FLOAT ( size ) DOUBLE PRECISION REAL
  • 51. Data Types Basic Elements of Oracle SQL 3-5 Oracle_supplied_types::= For a description of the expression_filter_type, refer to "Expression Filter Type" on page 3-36. Other Oracle-supplied types follow: any_types::= For descriptions of the Any types, refer to "Any Types" on page 3-32. XML_types::= For descriptions of the XML types, refer to "XML Types" on page 3-32. spatial_types::= For descriptions of the spatial types, refer to "Spatial Types" on page 3-34. media_types::= any_types XML_types spatial_types media_types expression_filter_type SYS.AnyData SYS.AnyType SYS.AnyDataSet XMLType URIType SDO_Geometry SDO_Topo_Geometry SDO_GeoRaster ORDAudio ORDImage ORDVideo ORDDoc ORDDicom still_image_object_types
  • 52. Data Types 3-6 Oracle Database SQL Language Reference still_image_object_types::= For descriptions of the media types, refer to "Media Types" on page 3-35. Oracle Built-in Data Types The table that follows summarizes Oracle built-in data types. Refer to the syntax in the preceding sections for the syntactic elements. The codes listed for the data types are used internally by Oracle Database. The data type code of a column or object attribute is returned by the DUMP function. Table 3–1 Built-in Data Type Summary Code Data Type Description 1 VARCHAR2(size [BYTE | CHAR]) Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics. CHAR indicates that the column will have character semantics. 1 NVARCHAR2(size) Variable-length Unicode character string having maximum length size characters. The number of bytes can be up to two times size for AL16UTF16 encoding and three times size for UTF8 encoding. Maximum size is determined by the national character set definition, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. 2 NUMBER [ (p [, s]) ] Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127. Both precision and scale are in decimal digits. A NUMBER value requires from 1 to 22 bytes. 2 FLOAT [(p)] A subtype of the NUMBER data type having precision p. A FLOAT value is represented internally as NUMBER. The precision p can range from 1 to 126 binary digits. A FLOAT value requires from 1 to 22 bytes. 8 LONG Character data of variable length up to 2 gigabytes, or 231 -1 bytes. Provided for backward compatibility. 12 DATE Valid date range from January 1, 4712 BC, to December 31, 9999 AD. The default format is determined explicitly by the NLS_ DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is fixed at 7 bytes. This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It does not have fractional seconds or a time zone. 21 BINARY_FLOAT 32-bit floating point number. This data type requires 4 bytes. SI_StillImage SI_AverageColor SI_PositionalColor SI_ColorHistogram SI_Texture SI_FeatureList SI_Color
  • 53. Data Types Basic Elements of Oracle SQL 3-7 22 BINARY_DOUBLE 64-bit floating point number. This data type requires 8 bytes. 180 TIMESTAMP [(fractional_ seconds_precision)] Year, month, and day values of date, as well as hour, minute, and second values of time, where fractional_seconds_ precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values of fractional_ seconds_precision are 0 to 9. The default is 6. The default format is determined explicitly by the NLS_DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is 7 or 11 bytes, depending on the precision. This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It contains fractional seconds but does not have a time zone. 181 TIMESTAMP [(fractional_ seconds)] WITH TIME ZONE All values of TIMESTAMP as well as time zone displacement value, where fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 0 to 9. The default is 6. The default format is determined explicitly by the NLS_DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is fixed at 13 bytes. This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_ HOUR, and TIMEZONE_MINUTE. It has fractional seconds and an explicit time zone. 231 TIMESTAMP [(fractional_ seconds)] WITH LOCAL TIME ZONE All values of TIMESTAMP WITH TIME ZONE, with the following exceptions: ■ Data is normalized to the database time zone when it is stored in the database. ■ When the data is retrieved, users see the data in the session time zone. The default format is determined explicitly by the NLS_DATE_ FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is 7 or 11 bytes, depending on the precision. 182 INTERVAL YEAR [(year_ precision)] TO MONTH Stores a period of time in years and months, where year_ precision is the number of digits in the YEAR datetime field. Accepted values are 0 to 9. The default is 2. The size is fixed at 5 bytes. 183 INTERVAL DAY [(day_precision)] TO SECOND [(fractional_ seconds)] Stores a period of time in days, hours, minutes, and seconds, where ■ day_precision is the maximum number of digits in the DAY datetime field. Accepted values are 0 to 9. The default is 2. ■ fractional_seconds_precision is the number of digits in the fractional part of the SECOND field. Accepted values are 0 to 9. The default is 6. The size is fixed at 11 bytes. 23 RAW(size) Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. 24 LONG RAW Raw binary data of variable length up to 2 gigabytes. 69 ROWID Base 64 string representing the unique address of a row in its table. This data type is primarily for values returned by the ROWID pseudocolumn. 208 UROWID [(size)] Base 64 string representing the logical address of a row of an index-organized table. The optional size is the size of a column of type UROWID. The maximum size and default is 4000 bytes. Table 3–1 (Cont.) Built-in Data Type Summary Code Data Type Description
  • 54. Data Types 3-8 Oracle Database SQL Language Reference The sections that follow describe the Oracle data types as they are stored in Oracle Database. For information on specifying these data types as literals, refer to "Literals" on page 3-45. Character Data Types Character data types store character (alphanumeric) data, which are words and free-form text, in the database character set or national character set. They are less restrictive than other data types and consequently have fewer properties. For example, character columns can store all alphanumeric values, but NUMBER columns can store only numeric values. Character data is stored in strings with byte values corresponding to one of the character sets, such as 7-bit ASCII or EBCDIC, specified when the database was created. Oracle Database supports both single-byte and multibyte character sets. These data types are used for character data: ■ CHAR Data Type ■ NCHAR Data Type ■ NVARCHAR2 Data Type ■ VARCHAR2 Data Type For information on specifying character data types as literals, refer to "Text Literals" on page 3-46. 96 CHAR [(size [BYTE | CHAR])] Fixed-length character data of length size bytes or characters. Maximum size is 2000 bytes or characters. Default and minimum size is 1 byte. BYTE and CHAR have the same semantics as for VARCHAR2. 96 NCHAR[(size)] Fixed-length character data of length size characters. The number of bytes can be up to two times size for AL16UTF16 encoding and three times size for UTF8 encoding. Maximum size is determined by the national character set definition, with an upper limit of 2000 bytes. Default and minimum size is 1 character. 112 CLOB A character large object containing single-byte or multibyte characters. Both fixed-width and variable-width character sets are supported, both using the database character set. Maximum size is (4 gigabytes - 1) * (database block size). 112 NCLOB A character large object containing Unicode characters. Both fixed-width and variable-width character sets are supported, both using the database national character set. Maximum size is (4 gigabytes - 1) * (database block size). Stores national character set data. 113 BLOB A binary large object. Maximum size is (4 gigabytes - 1) * (database block size). 114 BFILE Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes. Table 3–1 (Cont.) Built-in Data Type Summary Code Data Type Description
  • 55. Data Types Basic Elements of Oracle SQL 3-9 CHAR Data Type The CHAR data type specifies a fixed-length character string. Oracle ensures that all values stored in a CHAR column have the length specified by size. If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length. If you try to insert a value that is too long for the column, then Oracle returns an error. The default length for a CHAR column is 1 byte and the maximum allowed is 2000 bytes. A 1-byte string can be inserted into a CHAR(10) column, but the string is blank-padded to 10 bytes before it is stored. When you create a table with a CHAR column, by default you supply the column length in bytes. The BYTE qualifier is the same as the default. If you use the CHAR qualifier, for example CHAR(10 CHAR), then you supply the column length in characters. A character is technically a code point of the database character set. Its size can range from 1 byte to 4 bytes, depending on the database character set. The BYTE and CHAR qualifiers override the semantics specified by the NLS_LENGTH_ SEMANTICS parameter, which has a default of byte semantics. For performance reasons, Oracle recommends that you use the NLS_LENGTH_SEMANTICS parameter to set length semantics and that you use the BYTE and CHAR qualifiers only when necessary to override the parameter. To ensure proper data conversion between databases with different character sets, you must ensure that CHAR data consists of well-formed strings. NCHAR Data Type The NCHAR data type is a Unicode-only data type. When you create a table with an NCHAR column, you define the column length in characters. You define the national character set when you create your database. The maximum length of a column is determined by the national character set definition. Width specifications of character data type NCHAR refer to the number of characters. The maximum column size allowed is 2000 bytes. If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length. You cannot insert a CHAR value into an NCHAR column, nor can you insert an NCHAR value into a CHAR column. The following example compares the translated_description column of the pm.product_descriptions table with a national character set string: SELECT translated_description FROM product_descriptions WHERE translated_name = N'LCD Monitor 11/PM'; NVARCHAR2 Data Type The NVARCHAR2 data type is a Unicode-only data type. When you create a table with an NVARCHAR2 column, you supply the maximum number of characters it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the maximum length of the column. See Also: Oracle Database Globalization Support Guide for more information on character set support and "Data Type Comparison Rules" on page 3-37 for information on comparison semantics See Also: Oracle Database Globalization Support Guide for information on Unicode data type support
  • 56. Data Types 3-10 Oracle Database SQL Language Reference The maximum length of the column is determined by the national character set definition. Width specifications of character data type NVARCHAR2 refer to the number of characters. The maximum column size allowed is 4000 bytes. VARCHAR2 Data Type The VARCHAR2 data type specifies a variable-length character string. When you create a VARCHAR2 column, you supply the maximum number of bytes or characters of data that it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the column's maximum length of the column. If you try to insert a value that exceeds the specified length, then Oracle returns an error. You must specify a maximum length for a VARCHAR2 column. This maximum must be at least 1 byte, although the actual string stored is permitted to be a zero-length string (''). You can use the CHAR qualifier, for example VARCHAR2(10 CHAR), to give the maximum length in characters instead of bytes. A character is technically a code point of the database character set. You can use the BYTE qualifier, for example VARCHAR2(10 BYTE), to explicitly give the maximum length in bytes. If no explicit qualifier is included in a column or attribute definition when a database object with this column or attribute is created, then the length semantics are determined by the value of the NLS_LENGTH_SEMANTICS parameter of the session creating the object. Independently of the maximum length in characters, the length of VARCHAR2 data cannot exceed 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics. To ensure proper data conversion between databases with different character sets, you must ensure that VARCHAR2 data consists of well-formed strings. See Oracle Database Globalization Support Guide for more information on character set support. VARCHAR Data Type Do not use the VARCHAR data type. Use the VARCHAR2 data type instead. Although the VARCHAR data type is currently synonymous with VARCHAR2, the VARCHAR data type is scheduled to be redefined as a separate data type used for variable-length character strings compared with different comparison semantics. Numeric Data Types The Oracle Database numeric data types store positive and negative fixed and floating-point numbers, zero, infinity, and values that are the undefined result of an operation—"not a number" or NAN. For information on specifying numeric data types as literals, refer to "Numeric Literals" on page 3-47. NUMBER Data Type The NUMBER data type stores zero as well as positive and negative fixed numbers with absolute values from 1.0 x 10-130 to but not including 1.0 x 10126 . If you specify an arithmetic expression whose value has an absolute value greater than or equal to 1.0 x 10126 , then Oracle returns an error. Each NUMBER value requires from 1 to 22 bytes. Specify a fixed-point number using the following form: NUMBER(p,s) See Also: Oracle Database Globalization Support Guide for information on Unicode data type support. See Also: "Data Type Comparison Rules" on page 3-37 for information on comparison semantics
  • 57. Data Types Basic Elements of Oracle SQL 3-11 where: ■ p is the precision, or the maximum number of significant decimal digits, where the most significant digit is the left-most nonzero digit, and the least significant digit is the right-most known digit. Oracle guarantees the portability of numbers with precision of up to 20 base-100 digits, which is equivalent to 39 or 40 decimal digits depending on the position of the decimal point. ■ s is the scale, or the number of digits from the decimal point to the least significant digit. The scale can range from -84 to 127. – Positive scale is the number of significant digits to the right of the decimal point to and including the least significant digit. – Negative scale is the number of significant digits to the left of the decimal point, to but not including the least significant digit. For negative scale the least significant digit is on the left side of the decimal point, because the actual data is rounded to the specified number of places to the left of the decimal point. For example, a specification of (10,-2) means to round to hundreds. Scale can be greater than precision, most commonly when e notation is used. When scale is greater than precision, the precision specifies the maximum number of significant digits to the right of the decimal point. For example, a column defined as NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all values past the fifth digit after the decimal point. It is good practice to specify the scale and precision of a fixed-point number column for extra integrity checking on input. Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision, then Oracle returns an error. If a value exceeds the scale, then Oracle rounds it. Specify an integer using the following form: NUMBER(p) This represents a fixed-point number with precision p and scale 0 and is equivalent to NUMBER(p,0). Specify a floating-point number using the following form: NUMBER The absence of precision and scale designators specifies the maximum range and precision for an Oracle number. Table 3–2 show how Oracle stores data using different precisions and scales. See Also: "Floating-Point Numbers" on page 3-12 Table 3–2 Storage of Scale and Precision Actual Data Specified As Stored As 123.89 NUMBER 123.89 123.89 NUMBER(3) 124 123.89 NUMBER(3,2) exceeds precision 123.89 NUMBER(4,2) exceeds precision 123.89 NUMBER(5,2) 123.89 123.89 NUMBER(6,1) 123.9
  • 58. Data Types 3-12 Oracle Database SQL Language Reference FLOAT Data Type The FLOAT data type is a subtype of NUMBER. It can be specified with or without precision, which has the same definition it has for NUMBER and can range from 1 to 126. Scale cannot be specified, but is interpreted from the data. Each FLOAT value requires from 1 to 22 bytes. To convert from binary to decimal precision, multiply n by 0.30103. To convert from decimal to binary precision, multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision. The difference between NUMBER and FLOAT is best illustrated by example. In the following example the same values are inserted into NUMBER and FLOAT columns: CREATE TABLE test (col1 NUMBER(5,2), col2 FLOAT(5)); INSERT INTO test VALUES (1.23, 1.23); INSERT INTO test VALUES (7.89, 7.89); INSERT INTO test VALUES (12.79, 12.79); INSERT INTO test VALUES (123.45, 123.45); SELECT * FROM test; COL1 COL2 ---------- ---------- 1.23 1.2 7.89 7.9 12.79 13 123.45 120 In this example, the FLOAT value returned cannot exceed 5 binary digits. The largest decimal number that can be represented by 5 binary digits is 31. The last row contains decimal values that exceed 31. Therefore, the FLOAT value must be truncated so that its significant digits do not require more than 5 binary digits. Thus 123.45 is rounded to 120, which has only two significant decimal digits, requiring only 4 binary digits. Oracle Database uses the Oracle FLOAT data type internally when converting ANSI FLOAT data. Oracle FLOAT is available for you to use, but Oracle recommends that you use the BINARY_FLOAT and BINARY_DOUBLE data types instead, as they are more robust. Refer to "Floating-Point Numbers" on page 3-12 for more information. Floating-Point Numbers Floating-point numbers can have a decimal point anywhere from the first to the last digit or can have no decimal point at all. An exponent may optionally be used 123.89 NUMBER(6,-2) 100 .01234 NUMBER(4,5) .01234 .00012 NUMBER(4,5) .00012 .000127 NUMBER(4,5) .00013 .0000012 NUMBER(2,7) .0000012 .00000123 NUMBER(2,7) .0000012 1.2e-4 NUMBER(2,5) 0.00012 1.2e-5 NUMBER(2,5) 0.00001 Table 3–2 (Cont.) Storage of Scale and Precision Actual Data Specified As Stored As
  • 59. Data Types Basic Elements of Oracle SQL 3-13 following the number to increase the range, for example, 1.777 e-20 . A scale value is not applicable to floating-point numbers, because the number of digits that can appear after the decimal point is not restricted. Binary floating-point numbers differ from NUMBER in the way the values are stored internally by Oracle Database. Values are stored using decimal precision for NUMBER. All literals that are within the range and precision supported by NUMBER are stored exactly as NUMBER. Literals are stored exactly because literals are expressed using decimal precision (the digits 0 through 9). Binary floating-point numbers are stored using binary precision (the digits 0 and 1). Such a storage scheme cannot represent all values using decimal precision exactly. Frequently, the error that occurs when converting a value from decimal to binary precision is undone when the value is converted back from binary to decimal precision. The literal 0.1 is such an example. Oracle Database provides two numeric data types exclusively for floating-point numbers: BINARY_FLOAT BINARY_FLOAT is a 32-bit, single-precision floating-point number data type. Each BINARY_FLOAT value requires 4 bytes. BINARY_DOUBLE BINARY_DOUBLE is a 64-bit, double-precision floating-point number data type. Each BINARY_DOUBLE value requires 8 bytes. In a NUMBER column, floating point numbers have decimal precision. In a BINARY_ FLOAT or BINARY_DOUBLE column, floating-point numbers have binary precision. The binary floating-point numbers support the special values infinity and NaN (not a number). You can specify floating-point numbers within the limits listed in Table 3–3 on page 3-13. The format for specifying floating-point numbers is defined in "Numeric Literals" on page 3-47. IEEE754 Conformance The Oracle implementation of floating-point data types conforms substantially with the Institute of Electrical and Electronics Engineers (IEEE) Standard for Binary Floating-Point Arithmetic, IEEE Standard 754-1985 (IEEE754). The floating-point data types conform to IEEE754 in the following areas: ■ The SQL function SQRT implements square root. See SQRT on page 5-183. ■ The SQL function REMAINDER implements remainder. See REMAINDER on page 5-171. ■ Arithmetic operators conform. See "Arithmetic Operators" on page 4-3. ■ Comparison operators conform, except for comparisons with NaN. Oracle orders NaN greatest with respect to all other values, and evaluates NaN equal to NaN. See "Floating-Point Conditions" on page 7-7. ■ Conversion operators conform. See "Conversion Functions" on page 5-6. ■ The default rounding mode is supported. ■ The default exception handling mode is supported. Table 3–3 Floating Point Number Limits Value BINARY_FLOAT BINARY_DOUBLE Maximum positive finite value 3.40282E+38F 1.79769313486231E+308 Minimum positive finite value 1.17549E-38F 2.22507485850720E-308
  • 60. Data Types 3-14 Oracle Database SQL Language Reference ■ The special values INF, -INF, and NaN are supported. See "Floating-Point Conditions" on page 7-7. ■ Rounding of BINARY_FLOAT and BINARY_DOUBLE values to integer-valued BINARY_FLOAT and BINARY_DOUBLE values is provided by the SQL functions ROUND, TRUNC, CEIL, and FLOOR. ■ Rounding of BINARY_FLOAT/BINARY_DOUBLE to decimal and decimal to BINARY_FLOAT/BINARY_DOUBLE is provided by the SQL functions TO_CHAR, TO_NUMBER, TO_NCHAR, TO_BINARY_FLOAT, TO_BINARY_DOUBLE, and CAST. The floating-point data types do not conform to IEEE754 in the following areas: ■ -0 is coerced to +0. ■ Comparison with NaN is not supported. ■ All NaN values are coerced to either BINARY_FLOAT_NAN or BINARY_DOUBLE_ NAN. ■ Non-default rounding modes are not supported. ■ Non-default exception handling mode are not supported. Numeric Precedence Numeric precedence determines, for operations that support numeric data types, the data type Oracle uses if the arguments to the operation have different data types. BINARY_DOUBLE has the highest numeric precedence, followed by BINARY_FLOAT, and finally by NUMBER. Therefore, in any operation on multiple numeric values: ■ If any of the operands is BINARY_DOUBLE, then Oracle attempts to convert all the operands implicitly to BINARY_DOUBLE before performing the operation. ■ If none of the operands is BINARY_DOUBLE but any of the operands is BINARY_ FLOAT, then Oracle attempts to convert all the operands implicitly to BINARY_ FLOAT before performing the operation. ■ Otherwise, Oracle attempts to convert all the operands to NUMBER before performing the operation. If any implicit conversion is needed and fails, then the operation fails. Refer to Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion. In the context of other data types, numeric data types have lower precedence than the datetime/interval data types and higher precedence than character and all other data types. LONG Data Type Do not create tables with LONG columns. Use LOB columns (CLOB, NCLOB, BLOB) instead. LONG columns are supported only for backward compatibility. LONG columns store variable-length character strings containing up to 2 gigabytes -1, or 231 -1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. The length of LONG values may be limited by the memory available on your computer. LONG literals are formed as described for "Text Literals" on page 3-46. Oracle also recommends that you convert existing LONG columns to LOB columns. LOB columns are subject to far fewer restrictions than LONG columns. Further, LOB functionality is enhanced in every release, whereas LONG functionality has been static for several releases. See the modify_col_properties clause of ALTER TABLE on
  • 61. Data Types Basic Elements of Oracle SQL 3-15 page 12-2 and TO_LOB on page 5-225 for more information on converting LONG columns to LOB. You can reference LONG columns in SQL statements in these places: ■ SELECT lists ■ SET clauses of UPDATE statements ■ VALUES clauses of INSERT statements The use of LONG values is subject to these restrictions: ■ A table can contain only one LONG column. ■ You cannot create an object type with a LONG attribute. ■ LONG columns cannot appear in WHERE clauses or in integrity constraints (except that they can appear in NULL and NOT NULL constraints). ■ LONG columns cannot be indexed. ■ LONG data cannot be specified in regular expressions. ■ A stored function cannot return a LONG value. ■ You can declare a variable or argument of a PL/SQL program unit using the LONG data type. However, you cannot then call the program unit from SQL. ■ Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database. ■ LONG and LONG RAW columns cannot be used in distributed SQL statements and cannot be replicated. ■ If a table has both LONG and LOB columns, then you cannot bind more than 4000 bytes of data to both the LONG and LOB columns in the same SQL statement. However, you can bind more than 4000 bytes of data to either the LONG or the LOB column. In addition, LONG columns cannot appear in these parts of SQL statements: ■ GROUP BY clauses, ORDER BY clauses, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements ■ The UNIQUE operator of a SELECT statement ■ The column list of a CREATE CLUSTER statement ■ The CLUSTER clause of a CREATE MATERIALIZED VIEW statement ■ SQL built-in functions, expressions, or conditions ■ SELECT lists of queries containing GROUP BY clauses ■ SELECT lists of subqueries or queries combined by the UNION, INTERSECT, or MINUS set operators ■ SELECT lists of CREATE TABLE ... AS SELECT statements ■ ALTER TABLE ... MOVE statements ■ SELECT lists in subqueries in INSERT statements Triggers can use the LONG data type in the following manner: ■ A SQL statement within a trigger can insert data into a LONG column.
  • 62. Data Types 3-16 Oracle Database SQL Language Reference ■ If data from a LONG column can be converted to a constrained data type (such as CHAR and VARCHAR2), then a LONG column can be referenced in a SQL statement within a trigger. ■ Variables in triggers cannot be declared using the LONG data type. ■ :NEW and :OLD cannot be used with LONG columns. You can use Oracle Call Interface functions to retrieve a portion of a LONG value from the database. Datetime and Interval Data Types The datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE. Values of datetime data types are sometimes called datetimes. The interval data types are INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND. Values of interval data types are sometimes called intervals. For information on expressing datetime and interval values as literals, refer to "Datetime Literals" on page 3-50 and "Interval Literals" on page 3-52. Both datetimes and intervals are made up of fields. The values of these fields determine the value of the data type. Table 3–4 lists the datetime fields and their possible values for datetimes and intervals. To avoid unexpected results in your DML operations on datetime data, you can verify the database and session time zones by querying the built-in SQL functions DBTIMEZONE and SESSIONTIMEZONE. If the time zones have not been set manually, then Oracle Database uses the operating system time zone by default. If the operating system time zone is not a valid Oracle time zone, then Oracle uses UTC as the default value. See Also: Oracle Call Interface Programmer's Guide Table 3–4 Datetime Fields and Values Datetime Field Valid Values for Datetime Valid Values for INTERVAL YEAR -4712 to 9999 (excluding year 0) Any positive or negative integer MONTH 01 to 12 0 to 11 DAY 01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the current NLS calendar parameter) Any positive or negative integer HOUR 00 to 23 0 to 23 MINUTE 00 to 59 0 to 59 SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional seconds. The 9(n) portion is not applicable for DATE. 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds TIMEZONE_HOUR -12 to 14 (This range accommodates daylight saving time changes.) Not applicable for DATE or TIMESTAMP. Not applicable
  • 63. Data Types Basic Elements of Oracle SQL 3-17 DATE Data Type The DATE data type stores date and time information. Although date and time information can be represented in both character and number data types, the DATE data type has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, date, hour, minute, and second. You can specify a DATE value as a literal, or you can convert a character or numeric value to a date value with the TO_DATE function. For examples of expressing DATE values in both these ways, refer to "Datetime Literals" on page 3-50. Using Julian Days A Julian day number is the number of days since January 1, 4712 BC. Julian days allow continuous dating from a common reference. You can use the date format model "J" with date functions TO_DATE and TO_CHAR to convert between Oracle DATE values and their Julian equivalents. The default date values are determined as follows: ■ The year is the current year, as returned by SYSDATE. ■ The month is the current month, as returned by SYSDATE. ■ The day is 01 (the first day of the month). ■ The hour, minute, and second are all 0. These default values are used in a query that requests date values where the date itself is not specified, as in the following example, which is issued in the month of May: TIMEZONE_MINUTE (See note at end of table) 00 to 59. Not applicable for DATE or TIMESTAMP. Not applicable TIMEZONE_REGION Query the TZNAME column of the V$TIMEZONE_ NAMES data dictionary view. Not applicable for DATE or TIMESTAMP. For a complete listing of all time zone region names, refer to Oracle Database Globalization Support Guide. Not applicable TIMEZONE_ABBR Query the TZABBREV column of the V$TIMEZONE_ NAMES data dictionary view. Not applicable for DATE or TIMESTAMP. Not applicable Note: TIMEZONE_HOUR and TIMEZONE_MINUTE are specified together and interpreted as an entity in the format +|- hh:mm, with values ranging from -12:59 to +14:00. Refer to Oracle Data Provider for .NET Developer's Guide for information on specifying time zone values for that API. Note: Oracle Database uses the astronomical system of calculating Julian days, in which the year 4713 BC is specified as -4712. The historical system of calculating Julian days, in contrast, specifies 4713 BC as -4713. If you are comparing Oracle Julian days with values calculated using the historical system, then take care to allow for the 365-day difference in BC dates. For more information, see http://aa.usno.navy.mil/faq/docs/millennium.php. Table 3–4 (Cont.) Datetime Fields and Values Datetime Field Valid Values for Datetime Valid Values for INTERVAL
  • 64. Data Types 3-18 Oracle Database SQL Language Reference SELECT TO_DATE('2005', 'YYYY') FROM DUAL; TO_DATE(' --------- 01-MAY-05 Example This statement returns the Julian equivalent of January 1, 1997: SELECT TO_CHAR(TO_DATE('01-01-1997', 'MM-DD-YYYY'),'J') FROM DUAL; TO_CHAR -------- 2450450 TIMESTAMP Data Type The TIMESTAMP data type is an extension of the DATE data type. It stores the year, month, and day of the DATE data type, plus hour, minute, and second values. This data type is useful for storing precise time values and for collecting and evaluating date information across geographic regions. Specify the TIMESTAMP data type as follows: TIMESTAMP [(fractional_seconds_precision)] where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this data type, the value can be a number in the range 0 to 9. The default is 6. TIMESTAMP WITH TIME ZONE Data Type TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time zone region name or a a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time—formerly Greenwich Mean Time). This data type is useful for preserving local time zone information. Specify the TIMESTAMP WITH TIME ZONE data type as follows: TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this data type, the value can be a number in the range 0 to 9. The default is 6. Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site. See Also: "Selecting from the DUAL Table" for a description of the DUAL table See Also: TO_TIMESTAMP on page 5-230 for information on converting character data to TIMESTAMP data
  • 65. Data Types Basic Elements of Oracle SQL 3-19 TIMESTAMP WITH LOCAL TIME ZONE Data Type TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP that includes a time zone offset in its value. It differs from TIMESTAMP WITH TIME ZONE in that data stored in the database is normalized to the database time zone, and the time zone offset is not stored as part of the column data. When a user retrieves the data, Oracle returns it in the user's local session time zone. The time zone offset is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time—formerly Greenwich Mean Time). This data type is useful for displaying date information in the time zone of the client system in a two-tier application. Specify the TIMESTAMP WITH LOCAL TIME ZONE data type as follows: TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this data type, the value can be a number in the range 0 to 9. The default is 6. Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site. INTERVAL YEAR TO MONTH Data Type INTERVAL YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime fields. This data type is useful for representing the difference between two datetime values when only the year and month values are significant. Specify INTERVAL YEAR TO MONTH as follows: INTERVAL YEAR [(year_precision)] TO MONTH where year_precision is the number of digits in the YEAR datetime field. The default value of year_precision is 2. See Also: ■ Oracle Database Globalization Support Guide for more information on Oracle time zone data ■ "Support for Daylight Saving Times" on page 3-22 and Table 3–17, " Matching Character Data and Format Models with the FX Format Model Modifier" on page 3-67 for information on daylight saving support ■ TO_TIMESTAMP_TZ on page 5-231 for information on converting character data to TIMESTAMP WITH TIME ZONE data ■ ALTER SESSION on page 11-45 for information on the ERROR_ ON_OVERLAP_TIME session parameter See Also: ■ Oracle Database Globalization Support Guide for more information on Oracle time zone data ■ Oracle Database Advanced Application Developer's Guide for examples of using this data type and CAST on page 5-28 for information on converting character data to TIMESTAMP WITH LOCAL TIME ZONE
  • 66. Data Types 3-20 Oracle Database SQL Language Reference You have a great deal of flexibility when specifying interval values as literals. Refer to "Interval Literals" on page 3-52 for detailed information on specifying interval values as literals. Also see "Datetime and Interval Examples" on page 3-23 for an example using intervals. INTERVAL DAY TO SECOND Data Type INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and seconds. This data type is useful for representing the precise difference between two datetime values. Specify this data type as follows: INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)] where ■ day_precision is the number of digits in the DAY datetime field. Accepted values are 0 to 9. The default is 2. ■ fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 0 to 9. The default is 6. You have a great deal of flexibility when specifying interval values as literals. Refer to "Interval Literals" on page 3-52 for detailed information on specify interval values as literals. Also see "Datetime and Interval Examples" on page 3-23 for an example using intervals. Datetime/Interval Arithmetic You can perform a number of arithmetic operations on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE) and interval (INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH) data. Oracle calculates the results based on the following rules: ■ You can use NUMBER constants in arithmetic operations on date and timestamp values, but not interval values. Oracle internally converts timestamp values to date values and interprets NUMBER constants in arithmetic datetime and interval expressions as numbers of days. For example, SYSDATE + 1 is tomorrow. SYSDATE - 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting the hire_date column of the sample table employees from SYSDATE returns the number of days since each employee was hired. You cannot multiply or divide date or timestamp values. ■ Oracle implicitly converts BINARY_FLOAT and BINARY_DOUBLE operands to NUMBER. ■ Each DATE value contains a time component, and the result of many date operations include a fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours. These fractions are also returned by Oracle built-in functions for common operations on DATE data. For example, the MONTHS_ BETWEEN function returns the number of months between two dates. The fractional portion of the result represents that portion of a 31-day month. ■ If one operand is a DATE value or a numeric value, neither of which contains time zone or fractional seconds components, then: – Oracle implicitly converts the other operand to DATE data. The exception is multiplication of a numeric value times an interval, which returns an interval.
  • 67. Data Types Basic Elements of Oracle SQL 3-21 – If the other operand has a time zone value, then Oracle uses the session time zone in the returned value. – If the other operand has a fractional seconds value, then the fractional seconds value is lost. ■ When you pass a timestamp, interval, or numeric value to a built-in function that was designed only for the DATE data type, Oracle implicitly converts the non-DATE value to a DATE value. Refer to "Datetime Functions" on page 5-5 for information on which functions cause implicit conversion to DATE. ■ When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error. For example, the next two statements return errors: SELECT TO_DATE('31-AUG-2004','DD-MON-YYYY') + TO_YMINTERVAL('0-1') FROM DUAL; SELECT TO_DATE('29-FEB-2004','DD-MON-YYYY') + TO_YMINTERVAL('1-0') FROM DUAL; The first fails because adding one month to a 31-day month would result in September 31, which is not a valid date. The second fails because adding one year to a date that exists only every four years is not valid. However, the next statement succeeds, because adding four years to a February 29 date is valid: SELECT TO_DATE('29-FEB-2004', 'DD-MON-YYYY') + TO_YMINTERVAL('4-0') FROM DUAL; TO_DATE(' --------- 29-FEB-08 ■ Oracle performs all timestamp arithmetic in UTC time. For TIMESTAMP WITH LOCAL TIME ZONE, Oracle converts the datetime value from the database time zone to UTC and converts back to the database time zone after performing the arithmetic. For TIMESTAMP WITH TIME ZONE, the datetime value is always in UTC, so no conversion is necessary. Table 3–5 is a matrix of datetime arithmetic operations. Dashes represent operations that are not supported. Table 3–5 Matrix of Datetime Arithmetic Operand & Operator DATE TIMESTAMP INTERVAL Numeric DATE + — — DATE DATE - NUMBER INTERVAL DATE DATE * — — — — / — — — — TIMESTAMP + — — TIMESTAMP DATE - INTERVAL INTERVAL TIMESTAMP DATE * — — — — / — — — — INTERVAL + DATE TIMESTAMP INTERVAL —
  • 68. Data Types 3-22 Oracle Database SQL Language Reference Examples You can add an interval value expression to a start time. Consider the sample table oe.orders with a column order_date. The following statement adds 30 days to the value of the order_date column: SELECT order_id, order_date + INTERVAL '30' DAY FROM orders ORDER BY order_id, "Due Date"; Support for Daylight Saving Times Oracle Database automatically determines, for any given time zone region, whether daylight saving is in effect and returns local time values accordingly. The datetime value is sufficient for Oracle to determine whether daylight saving time is in effect for a given region in all cases except boundary cases. A boundary case occurs during the period when daylight saving goes into or comes out of effect. For example, in the US-Pacific region, when daylight saving goes into effect, the time changes from 2:00 a.m. to 3:00 a.m. The one hour interval between 2 and 3 a.m. does not exist. When daylight saving goes out of effect, the time changes from 2:00 a.m. back to 1:00 a.m., and the one-hour interval between 1 and 2 a.m. is repeated. To resolve these boundary cases, Oracle uses the TZR and TZD format elements, as described in Table 3–17. TZR represents the time zone region name in datetime input strings. Examples are 'Australia/North', 'UTC', and 'Singapore'. TZD represents an abbreviated form of the time zone region name with daylight saving information. Examples are 'PST' for US/Pacific standard time and 'PDT' for US/Pacific daylight time. To see a listing of valid values for the TZR and TZD format elements, query the TZNAME and TZABBREV columns of the V$TIMEZONE_NAMES dynamic performance view. For a complete listing of the time zone region names in both files, refer to Oracle Database Globalization Support Guide. - — — INTERVAL — * — — — INTERVAL / — — — INTERVAL Numeric + DATE DATE — NA - — — — NA * — — INTERVAL NA / — — — NA Note: Time zone region names are needed by the daylight saving feature. These names are stored in two types of time zone files: one large and one small. One of these files is the default file, depending on your environment and the release of Oracle Database you are using. For more information regarding time zone files and names, see Oracle Database Globalization Support Guide. Table 3–5 (Cont.) Matrix of Datetime Arithmetic Operand & Operator DATE TIMESTAMP INTERVAL Numeric
  • 69. Data Types Basic Elements of Oracle SQL 3-23 Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site. Datetime and Interval Examples The following example shows how to specify some datetime and interval data types. CREATE TABLE time_table ( start_time TIMESTAMP, duration_1 INTERVAL DAY (6) TO SECOND (5), duration_2 INTERVAL YEAR TO MONTH); The start_time column is of type TIMESTAMP. The implicit fractional seconds precision of TIMESTAMP is 6. The duration_1 column is of type INTERVAL DAY TO SECOND. The maximum number of digits in field DAY is 6 and the maximum number of digits in the fractional second is 5. The maximum number of digits in all other datetime fields is 2. The duration_2 column is of type INTERVAL YEAR TO MONTH. The maximum number of digits of the value in each field (YEAR and MONTH) is 2. Interval data types do not have format models. Therefore, to adjust their presentation, you must combine character functions such as EXTRACT and concatenate the components. For example, the following examples query the hr.employees and oe.orders tables, respectively, and change interval output from the form "yy-mm" to "yy years mm months" and from "dd-hh" to "dddd days hh hours": SELECT last_name, EXTRACT(YEAR FROM (SYSDATE - hire_date) YEAR TO MONTH ) || ' years ' || EXTRACT(MONTH FROM (SYSDATE - hire_date) YEAR TO MONTH ) || ' months' "Interval" FROM employees ; LAST_NAME Interval ------------------------- -------------------- King 6 years 1 months Kochhar 3 years 9 months De Haan 8 years 6 months Hunold 3 years 6 months Ernst 2 years 1 months Austin 4 years 0 months Pataballa 3 years 5 months Lorentz 2 years 5 months Greenberg 6 years 11 months . . . SELECT order_id, EXTRACT(DAY FROM (SYSDATE - order_date) DAY TO SECOND ) See Also: ■ "Datetime Format Models" on page 3-59 for information on the format elements and the session parameter ERROR_ON_ OVERLAP_TIME on page 11-51. ■ Oracle Database Globalization Support Guide for more information on Oracle time zone data ■ Oracle Database Reference for information on the dynamic performance views
  • 70. Data Types 3-24 Oracle Database SQL Language Reference || ' days ' || EXTRACT(HOUR FROM (SYSDATE - order_date) DAY TO SECOND ) || ' hours' "Interval" FROM orders; ORDER_ID Interval ---------- -------------------- 2458 2095 days 18 hours 2397 2000 days 17 hours 2454 2048 days 16 hours 2354 1762 days 16 hours 2358 1950 days 15 hours 2381 1823 days 13 hours 2440 2080 days 12 hours 2357 2680 days 11 hours 2394 1917 days 10 hours 2435 2078 days 10 hours . . . RAW and LONG RAW Data Types The RAW and LONG RAW data types store data that is not to be explicitly converted by Oracle Database when moving data between different systems. These data types are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use. Oracle strongly recommends that you convert LONG RAW columns to binary LOB (BLOB) columns. LOB columns are subject to far fewer restrictions than LONG columns. See TO_LOB on page 5-225 for more information. RAW is a variable-length data type like VARCHAR2, except that Oracle Net (which connects user sessions to the instance) and the Oracle import and export utilities do not perform character conversion when transmitting RAW or LONG RAW data. In contrast, Oracle Net and the Oracle import and export utilities automatically convert CHAR, VARCHAR2, and LONG data from the database character set to the user session character set. If the two character sets are different, you can set the user session character set with the NLS_LANGUAGE parameter of the ALTER SESSION statement. When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary data is represented in hexadecimal form, with one hexadecimal character representing every four bits of RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as CB. Large Object (LOB) Data Types The built-in LOB data types BLOB, CLOB, and NCLOB (stored internally) and BFILE (stored externally) can store large and unstructured data such as text, image, video, and spatial data. The size of BLOB, CLOB, and NCLOB data can be up to (232 -1 bytes) * (the value of the CHUNK parameter of LOB storage). If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (232 -1 bytes) * (database block size). BFILE data can be up to 264 -1 bytes, although your operating system may impose restrictions on this maximum. When creating a table, you can optionally specify different tablespace and storage characteristics for LOB columns or LOB object attributes from those specified for the table.
  • 71. Data Types Basic Elements of Oracle SQL 3-25 CLOB, NCLOB, and BLOB values up to approximately 4000 bytes are stored inline if you enable storage in row at the time the LOB column is created. LOBs greater than 4000 bytes are always stored externally. Refer to ENABLE STORAGE IN ROW on page 16-43 for more information. LOB columns contain LOB locators that can refer to internal (in the database) or external (outside the database) LOB values. Selecting a LOB from a table actually returns the LOB locator and not the entire LOB value. The DBMS_LOB package and Oracle Call Interface (OCI) operations on LOBs are performed through these locators. LOBs are similar to LONG and LONG RAW types, but differ in the following ways: ■ LOBs can be attributes of an object type (user-defined data type). ■ The LOB locator is stored in the table column, either with or without the actual LOB value. BLOB, NCLOB, and CLOB values can be stored in separate tablespaces. BFILE data is stored in an external file on the server. ■ When you access a LOB column, the locator is returned. ■ A LOB can be up to (232 -1 bytes)*(database block size) in size. BFILE data can be up to 264 -1 bytes, although your operating system may impose restrictions on this maximum. ■ LOBs permit efficient, random, piece-wise access to and manipulation of data. ■ You can define more than one LOB column in a table. ■ With the exception of NCLOB, you can define one or more LOB attributes in an object. ■ You can declare LOB bind variables. ■ You can select LOB columns and LOB attributes. ■ You can insert a new row or update an existing row that contains one or more LOB columns or an object with one or more LOB attributes. In update operations, you can set the internal LOB value to NULL, empty, or replace the entire LOB with data. You can set the BFILE to NULL or make it point to a different file. ■ You can update a LOB row-column intersection or a LOB attribute with another LOB row-column intersection or LOB attribute. ■ You can delete a row containing a LOB column or LOB attribute and thereby also delete the LOB value. For BFILEs, the actual operating system file is not deleted. You can access and populate rows of an inline LOB column (a LOB column stored in the database) or a LOB attribute (an attribute of an object type column stored in the database) simply by issuing an INSERT or UPDATE statement. Restrictions on LOB Columns LOB columns are subject to a number of rules and restrictions. See Oracle Database SecureFiles and Large Objects Developer's Guide for a complete listing. See Also: ■ Oracle Database PL/SQL Packages and Types Reference and Oracle Call Interface Programmer's Guide for more information about these interfaces and LOBs ■ the modify_col_properties clause of ALTER TABLE on page 12-2 and TO_LOB on page 5-225 for more information on converting LONG columns to LOB columns
  • 72. Data Types 3-26 Oracle Database SQL Language Reference BFILE Data Type The BFILE data type enables access to binary file LOBs that are stored in file systems outside Oracle Database. A BFILE column or attribute stores a BFILE locator, which serves as a pointer to a binary file on the server file system. The locator maintains the directory name and the filename. You can change the filename and path of a BFILE without affecting the base table by using the BFILENAME function. Refer to BFILENAME on page 5-24 for more information on this built-in SQL function. Binary file LOBs do not participate in transactions and are not recoverable. Rather, the underlying operating system provides file integrity and durability. BFILE data can be up to 264 -1 bytes, although your operating system may impose restrictions on this maximum. The database administrator must ensure that the external file exists and that Oracle processes have operating system read permissions on the file. The BFILE data type enables read-only support of large binary files. You cannot modify or replicate such a file. Oracle provides APIs to access file data. The primary interfaces that you use to access file data are the DBMS_LOB package and Oracle Call Interface (OCI). BLOB Data Type The BLOB data type stores unstructured binary large objects. BLOB objects can be thought of as bitstreams with no character set semantics. BLOB objects can store binary data up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage). If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes - 1) * (database block size). BLOB objects have full transactional support. Changes made through SQL, the DBMS_ LOB package, or Oracle Call Interface (OCI) participate fully in the transaction. BLOB value manipulations can be committed and rolled back. However, you cannot save a BLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session. CLOB Data Type The CLOB data type stores single-byte and multibyte character data. Both fixed-width and variable-width character sets are supported, and both use the database character set. CLOB objects can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage) of character data. If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes - 1) * (database block size). CLOB objects have full transactional support. Changes made through SQL, the DBMS_ LOB package, or Oracle Call Interface (OCI) participate fully in the transaction. CLOB value manipulations can be committed and rolled back. However, you cannot save a CLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session. See Also: Oracle Database SecureFiles and Large Objects Developer's Guide and Oracle Call Interface Programmer's Guide for more information about LOBs and CREATE DIRECTORY on page 14-42
  • 73. Data Types Basic Elements of Oracle SQL 3-27 NCLOB Data Type The NCLOB data type stores Unicode data. Both fixed-width and variable-width character sets are supported, and both use the national character set. NCLOB objects can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage) of character text data. If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes - 1) * (database block size). NCLOB objects have full transactional support. Changes made through SQL, the DBMS_ LOB package, or OCI participate fully in the transaction. NCLOB value manipulations can be committed and rolled back. However, you cannot save an NCLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session. Rowid Data Types Each row in the database has an address. The sections that follow describe the two forms of row address in an Oracle Database. ROWID Data Type The rows in heap-organized tables that are native to Oracle Database have row addresses called rowids. You can examine a rowid row address by querying the pseudocolumn ROWID. Values of this pseudocolumn are strings representing the address of each row. These strings have the data type ROWID. You can also create tables and clusters that contain actual columns having the ROWID data type. Oracle Database does not guarantee that the values of such columns are valid rowids. Refer to Chapter 2, "Pseudocolumns" for more information on the ROWID pseudocolumn. Rowids contain the following information: ■ The data block of the data file containing the row. The length of this string depends on your operating system. ■ The row in the data block. ■ The database file containing the row. The first data file has the number 1. The length of this string depends on your operating system. ■ The data object number, which is an identification number assigned to every database segment. You can retrieve the data object number from the data dictionary views USER_OBJECTS, DBA_OBJECTS, and ALL_OBJECTS. Objects that share the same segment (clustered tables in the same cluster, for example) have the same object number. See Also: Oracle Database Globalization Support Guide for information on Unicode data type support Note: Beginning with Oracle8, Oracle SQL incorporated an extended format for rowids to efficiently support partitioned tables and indexes and tablespace-relative data block addresses without ambiguity. If you are running Version 7 of the database and you intend to upgrade, use the DBMS_ROWID package to migrate rowids in your data to the extended format. Refer to Oracle Database PL/SQL Packages and Types Reference for information on DBMS_ROWID and to Oracle Database Upgrade Guide for information on upgrading from Oracle7.
  • 74. Data Types 3-28 Oracle Database SQL Language Reference Rowids are stored as base 64 values that can contain the characters A-Z, a-z, 0-9, and the plus sign (+) and forward slash (/). Rowids are not available directly. You can use the supplied package DBMS_ROWID to interpret rowid contents. The package functions extract and provide information on the four rowid elements listed above. UROWID Data Type The rows of some tables have addresses that are not physical or permanent or were not generated by Oracle Database. For example, the row addresses of index-organized tables are stored in index leaves, which can move. Rowids of foreign tables (such as DB2 tables accessed through a gateway) are not standard Oracle rowids. Oracle uses universal rowids (urowids) to store the addresses of index-organized and foreign tables. Index-organized tables have logical urowids and foreign tables have foreign urowids. Both types of urowid are stored in the ROWID pseudocolumn (as are the physical rowids of heap-organized tables). Oracle creates logical rowids based on the primary key of the table. The logical rowids do not change as long as the primary key does not change. The ROWID pseudocolumn of an index-organized table has a data type of UROWID. You can access this pseudocolumn as you would the ROWID pseudocolumn of a heap-organized table (using a SELECT ... ROWID statement). If you want to store the rowids of an index-organized table, then you can define a column of type UROWID for the table and retrieve the value of the ROWID pseudocolumn into that column. ANSI, DB2, and SQL/DS Data Types SQL statements that create tables and clusters can also use ANSI data types and data types from the IBM products SQL/DS and DB2. Oracle recognizes the ANSI or IBM data type name that differs from the Oracle Database data type name. It converts the data type to the equivalent Oracle data type, records the Oracle data type as the name of the column data type, and stores the column data in the Oracle data type based on the conversions shown in the tables that follow. See Also: Oracle Database PL/SQL Packages and Types Reference for information on the functions available with the DBMS_ROWID package and how to use them Note: Heap-organized tables have physical rowids. Oracle does not recommend that you specify a column of data type UROWID for a heap-organized table. Table 3–6 ANSI Data Types Converted to Oracle Data Types ANSI SQL Data Type Oracle Data Type CHARACTER(n) CHAR(n) CHAR(n) CHARACTER VARYING(n) CHAR VARYING(n) VARCHAR2(n) NATIONAL CHARACTER(n) NATIONAL CHAR(n) NCHAR(n) NCHAR(n)
  • 75. Data Types Basic Elements of Oracle SQL 3-29 Notes: a. The NUMERIC and DECIMAL data types can specify only fixed-point numbers. For those data types, the scale (s) defaults to 0. b. The FLOAT data type is a floating-point number with a binary precision b. The default precision for this data type is 126 binary, or 38 decimal. c. The DOUBLE PRECISION data type is a floating-point number with binary precision 126. d. The REAL data type is a floating-point number with a binary precision of 63, or 18 decimal. Do not define columns with the following SQL/DS and DB2 data types, because they have no corresponding Oracle data type: ■ GRAPHIC ■ LONG VARGRAPHIC ■ VARGRAPHIC ■ TIME Note that data of type TIME can also be expressed as Oracle datetime data. NATIONAL CHARACTER VARYING(n) NATIONAL CHAR VARYING(n) NCHAR VARYING(n) NVARCHAR2(n) NUMERIC[(p,s)] DECIMAL[(p,s)] (Note a) NUMBER(p,s) INTEGER INT SMALLINT NUMBER(38) FLOAT (Note b) DOUBLE PRECISION (Note c) REAL (Note d) FLOAT(126) FLOAT(126) FLOAT(63) See Also: Data Types in Oracle Database SQL Language Reference Table 3–7 SQL/DS and DB2 Data Types Converted to Oracle Data Types SQL/DS or DB2 Data Type Oracle Data Type CHARACTER(n) CHAR(n) VARCHAR(n) VARCHAR(n) LONG VARCHAR LONG DECIMAL(p,s) (a) NUMBER(p,s) INTEGER SMALLINT NUMBER(38) FLOAT (b) NUMBER Table 3–6 (Cont.) ANSI Data Types Converted to Oracle Data Types ANSI SQL Data Type Oracle Data Type
  • 76. Data Types 3-30 Oracle Database SQL Language Reference Notes: a. The DECIMAL data type can specify only fixed-point numbers. For this data type, s defaults to 0. b. The FLOAT data type is a floating-point number with a binary precision b. The default precision for this data type is 126 binary or 38 decimal. User-Defined Types User-defined data types use Oracle built-in data types and other user-defined data types as the building blocks of object types that model the structure and behavior of data in applications. The sections that follow describe the various categories of user-defined types. Object Types Object types are abstractions of the real-world entities, such as purchase orders, that application programs deal with. An object type is a schema object with three kinds of components: ■ A name, which identifies the object type uniquely within that schema. ■ Attributes, which are built-in types or other user-defined types. Attributes model the structure of the real-world entity. ■ Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C or Java and stored externally. Methods implement operations the application can perform on the real-world entity. REF Data Types An object identifier (represented by the keyword OID) uniquely identifies an object and enables you to reference the object from other objects or from relational tables. A data type category called REF represents such references. A REF data type is a container for an object identifier. REF values are pointers to objects. When a REF value points to a nonexistent object, the REF is said to be "dangling". A dangling REF is different from a null REF. To determine whether a REF is dangling or not, use the condition IS [NOT] DANGLING. For example, given object view oc_ orders in the sample schema oe, the column customer_ref is of type REF to type customer_typ, which has an attribute cust_email: SELECT o.customer_ref.cust_email FROM oc_orders o WHERE o.customer_ref IS NOT DANGLING; See Also: ■ Oracle Database Concepts for information about Oracle built-in data types ■ CREATE TYPE on page 17-3 and the CREATE TYPE BODY on page 17-5 for information about creating user-defined types ■ Oracle Database Object-Relational Developer's Guide for information about using user-defined types
  • 77. Data Types Basic Elements of Oracle SQL 3-31 Varrays An array is an ordered set of data elements. All elements of a given array are of the same data type. Each element has an index, which is a number corresponding to the position of the element in the array. The number of elements in an array is the size of the array. Oracle arrays are of variable size, which is why they are called varrays. You must specify a maximum size when you declare the varray. When you declare a varray, it does not allocate space. It defines a type, which you can use as: ■ The data type of a column of a relational table ■ An object type attribute ■ A PL/SQL variable, parameter, or function return type Oracle normally stores an array object either in line (as part of the row data) or out of line (in a LOB), depending on its size. However, if you specify separate storage characteristics for a varray, then Oracle stores it out of line, regardless of its size. Refer to the varray_col_properties of CREATE TABLE on page 16-47 for more information about varray storage. Nested Tables A nested table type models an unordered set of elements. The elements may be built-in types or user-defined types. You can view a nested table as a single-column table or, if the nested table is an object type, as a multicolumn table, with a column for each attribute of the object type. A nested table definition does not allocate space. It defines a type, which you can use to declare: ■ The data type of a column of a relational table ■ An object type attribute ■ A PL/SQL variable, parameter, or function return type When a nested table appears as the type of a column in a relational table or as an attribute of the underlying object type of an object table, Oracle stores all of the nested table data in a single table, which it associates with the enclosing relational or object table. Oracle-Supplied Types Oracle provides SQL-based interfaces for defining new types when the built-in or ANSI-supported types are not sufficient. The behavior for these types can be implemented in C/C++, Java, or PL/ SQL. Oracle Database automatically provides the low-level infrastructure services needed for input-output, heterogeneous client-side access for new data types, and optimizations for data transfers between the application and the database. These interfaces can be used to build user-defined (or object) types and are also used by Oracle to create some commonly useful data types. Several such data types are supplied with the server, and they serve both broad horizontal application areas (for example, the Any types) and specific vertical ones (for example, the spatial types). The Oracle-supplied types, along with cross-references to the documentation of their implementation and use, are described in the following sections:
  • 78. Data Types 3-32 Oracle Database SQL Language Reference ■ Any Types ■ XML Types ■ Spatial Types ■ Media Types Any Types The Any types provide highly flexible modeling of procedure parameters and table columns where the actual type is not known. These data types let you dynamically encapsulate and access type descriptions, data instances, and sets of data instances of any other SQL type. These types have OCI and PL/SQL interfaces for construction and access. ANYTYPE This type can contain a type description of any named SQL type or unnamed transient type. ANYDATA This type contains an instance of a given type, with data, plus a description of the type. ANYDATA can be used as a table column data type and lets you store heterogeneous values in a single column. The values can be of SQL built-in types as well as user-defined types. ANYDATASET This type contains a description of a given type plus a set of data instances of that type. ANYDATASET can be used as a procedure parameter data type where such flexibility is needed. The values of the data instances can be of SQL built-in types as well as user-defined types. XML Types Extensible Markup Language (XML) is a standard format developed by the World Wide Web Consortium (W3C) for representing structured and unstructured data on the World Wide Web. Universal resource identifiers (URIs) identify resources such as Web pages anywhere on the Web. Oracle provides types to handle XML and URI data, as well as a class of URIs called DBURIRef types to access data stored within the database itself. It also provides a set of types to store and access both external and internal URIs from within the database. XMLType This Oracle-supplied type can be used to store and query XML data in the database. XMLType has member functions you can use to access, extract, and query the XML data using XPath expressions. XPath is another standard developed by the W3C committee to traverse XML documents. Oracle XMLType functions support many W3C XPath expressions. Oracle also provides a set of SQL functions and PL/SQL packages to create XMLType values from existing relational or object-relational data. XMLType is a system-defined type, so you can use it as an argument of a function or as the data type of a table or view column. You can also create tables and views of See Also: Oracle Database PL/SQL Packages and Types Reference for information on the ANYTYPE, ANYDATA, and ANYDATASET types
  • 79. Data Types Basic Elements of Oracle SQL 3-33 XMLType. When you create an XMLType column in a table, you can choose to store the XML data in a CLOB column, as binary XML (stored internally as a CLOB), or object relationally. You can also register the schema (using the DBMS_XMLSCHEMA package) and create a table or column conforming to the registered schema. In this case Oracle stores the XML data in underlying object-relational columns by default, but you can specify storage in a CLOB or binary XML column even for schema-based data. Queries and DML on XMLType columns operate the same regardless of the storage mechanism. URI Data Types Oracle supplies a family of URI types—URIType, DBURIType, XDBURIType, and HTTPURIType—which are related by an inheritance hierarchy. URIType is an object type and the others are subtypes of URIType. Since URIType is the supertype, you can create columns of this type and store DBURIType or HTTPURIType type instances in this column. HTTPURIType You can use HTTPURIType to store URLs to external Web pages or to files. Oracle accesses these files using HTTP (Hypertext Transfer Protocol). XDBURIType You can use XDBURIType to expose documents in the XML database hierarchy as URIs that can be embedded in any URIType column in a table. The XDBURIType consists of a URL, which comprises the hierarchical name of the XML document to which it refers and an optional fragment representing the XPath syntax. The fragment is separated from the URL part by a pound sign (#). The following lines are examples of XDBURIType: /home/oe/doc1.xml /home/oe/doc1.xml#/orders/order_item DBURIType DBURIType can be used to store DBURIRef values, which reference data inside the database. Storing DBURIRef values lets you reference data stored inside or outside the database and access the data consistently. DBURIRef values use an XPath-like representation to reference data inside the database. If you imagine the database as an XML tree, then you would see the tables, rows, and columns as elements in the XML document. For example, the sample human resources user hr would see the following XML tree: <HR> <EMPLOYEES> <ROW> <EMPLOYEE_ID>205</EMPLOYEE_ID> <LAST_NAME>Higgins</LAST_NAME> <SALARY>12000</SALARY> .. <!-- other columns --> </ROW> ... <!-- other rows --> </EMPLOYEES> <!-- other tables..--> </HR> <!-- other user schemas on which you have some privilege on..--> See Also: Oracle XML DB Developer's Guide for information about using XMLType columns
  • 80. Data Types 3-34 Oracle Database SQL Language Reference The DBURIRef is an XPath expression over this virtual XML document. So to reference the SALARY value in the EMPLOYEES table for the employee with employee number 205, you can write a DBURIRef as, /HR/EMPLOYEES/ROW[EMPLOYEE_ID=205]/SALARY Using this model, you can reference data stored in CLOB columns or other columns and expose them as URLs to the external world. URIFactory Package Oracle also provides the URIFactory package, which can create and return instances of the various subtypes of the URITypes. The package analyzes the URL string, identifies the type of URL (HTTP, DBURI, and so on), and creates an instance of the subtype. To create a DBURI instance, the URL must start with the prefix /oradb. For example, URIFactory.getURI('/oradb/HR/EMPLOYEES') would create a DBURIType instance and URIFactory.getUri('/sys/schema') would create an XDBURIType instance. Spatial Types Oracle Spatial is designed to make spatial data management easier and more natural to users of location-enabled applications, geographic information system (GIS) applications, and geoimaging applications. After the spatial data is stored in an Oracle Database, you can easily manipulate, retrieve, and relate it to all the other data stored in the database. The following data types are available only if you have installed Oracle Spatial. SDO_GEOMETRY The geometric description of a spatial object is stored in a single row, in a single column of object type SDO_GEOMETRY in a user-defined table. Any table that has a column of type SDO_GEOMETRY must have another column, or set of columns, that defines a unique primary key for that table. Tables of this sort are sometimes called geometry tables. The SDO_GEOMETRY object type has the following definition: CREATE TYPE SDO_GEOMETRY AS OBJECT ( sgo_gtype NUMBER, sdo_srid NUMBER, sdo_point SDO_POINT_TYPE, sdo_elem_info SDO_ELEM_INFO_ARRAY, sdo_ordinates SDO_ORDINATE_ARRAY) / SDO_TOPO_GEOMETRY This type describes a topology geometry, which is stored in a single row, in a single column of object type SDO_TOPO_GEOMETRY in a user-defined table. See Also: ■ Oracle Database Object-Relational Developer's Guide for general information on object types and type inheritance ■ Oracle XML DB Developer's Guide for more information about these supplied types and their implementation ■ Oracle Streams Advanced Queuing User's Guide for information about using XMLType with Oracle Advanced Queuing
  • 81. Data Types Basic Elements of Oracle SQL 3-35 The SDO_TOPO_GEOMETRY object type has the following definition: CREATE TYPE SDO_TOPO_GEOMETRY AS OBJECT ( tg_type NUMBER, tg_id NUMBER, tg_layer_id NUMBER, topology_id NUMBER) / SDO_GEORASTER In the GeoRaster object-relational model, a raster grid or image object is stored in a single row, in a single column of object type SDO_GEORASTER in a user-defined table. Tables of this sort are called GeoRaster tables. The SDO_GEORASTER object type has the following definition: CREATE TYPE SDO_GEORASTER AS OBJECT ( rasterType NUMBER, spatialExtent SDO_GEOMETRY, rasterDataTable VARCHAR2(32), rasterID NUMBER, metadata XMLType) / Media Types Oracle Multimedia uses object types, similar to Java or C++ classes, to describe multimedia data. An instance of these object types consists of attributes, including metadata and the media data, and methods. The Multimedia data types are created in the ORDSYS schema. Public synonyms exist for all the data types, so you can access them without specifying the schema name. ORDAudio The ORDAudio object type supports the storage and management of audio data. ORDImage The ORDImage object type supports the storage and management of image data. ORDVideo The ORDVideo object type supports the storage and management of video data. ORDDoc The ORDDoc object type supports storage and management of any type of media data, including audio, image and video data. Use this type when you want all media to be stored in a single column. See Also: Oracle Spatial Developer's Guide, Oracle Spatial Topology and Network Data Models Developer's Guide, and Oracle Spatial GeoRaster Developer's Guide for information on the full implementation of the spatial data types and guidelines for using them See Also: Oracle Multimedia Reference for information on the implementation of these types and guidelines for using them
  • 82. Data Types 3-36 Oracle Database SQL Language Reference ORDDicom The ORDDicom object type supports the storage and management of Digital Imaging and Communications in Medicine (DICOM), the format universally recognized as the standard for medical imaging. The following data types provide compliance with the ISO-IEC 13249-5 Still Image standard, commonly referred to as SQL/MM StillImage. SI_StillImage The SI_StillImage object type represents digital images with inherent image characteristics such as height, width, and format. SI_Color The SI_Color object type encapsulates color values. SI_AverageColor The SI_AverageColor object type represents a feature that characterizes an image by its average color. SI_ColorHistogram The SI_ColorHistogram object type represents a feature that characterizes an image by the relative frequencies of the colors exhibited by samples of the raw image. SI_PositionalColor Given an image divided into n by m rectangles, the SI_PositionalColor object type represents the feature that characterizes an image by the n by m most significant colors of the rectangles. SI_Texture The SI_Texture object type represents a feature that characterizes an image by the size of repeating items (coarseness), brightness variations (contrast), and predominant direction (directionality). SI_FeatureList The SI_FeatureList object type is a list containing up to four of the image features represented by the preceding object types (SI_AverageColor, SI_ ColorHistogram, SI_PositionalColor, and SI_Texture), where each feature is associated with a feature weight. ORDImageSignature The ORDImageSignature object type has been deprecated and should no longer be introduced into your code. Existing occurrences of this object type will continue to function as in the past. Expression Filter Type The Oracle Expression Filter allows application developers to manage and evaluate conditional expressions that describe users' interests in data. The Expression Filter includes the following data type:
  • 83. Data Type Comparison Rules Basic Elements of Oracle SQL 3-37 Expression Expression Filter uses a virtual data type called Expression to manage and evaluate conditional expressions as data in database tables. The Expression Filter creates a column of Expression data type from a VARCHAR2 column by assigning an attribute set to the column. This assignment enables a data constraint that ensures the validity of expressions stored in the column. You can define conditions using the EVALUATE operator on an Expression data type to evaluate the expressions stored in a column for some data. If you are using Enterprise Edition, then you can also define an Expression Filter index on a column of Expression data type to process queries using the EVALUATE operator. Data Type Comparison Rules This section describes how Oracle Database compares values of each data type. Numeric Values A larger value is considered greater than a smaller one. All negative numbers are less than zero and all positive numbers. Thus, -1 is less than 100; -100 is less than -1. The floating-point value NaN (not a number) is greater than any other numeric value and is equal to itself. Date Values A later date is considered greater than an earlier one. For example, the date equivalent of '29-MAR-2005' is less than that of '05-JAN-2006' and '05-JAN-2006 1:35pm' is greater than '05-JAN-2005 10:09am'. Character Values Character values are compared on the basis of two measures: ■ Binary or linguistic sorting ■ Blank-padded or nonpadded comparison semantics The following subsections describe the two measures. Binary and Linguistic Comparisons In binary comparison, which is the default, Oracle compares character strings according to the concatenated value of the numeric codes of the characters in the database character set. One character is greater than another if it has a greater numeric value than the other in the character set. Oracle considers blanks to be less than any character, which is true in most character sets. These are some common character sets: ■ 7-bit ASCII (American Standard Code for Information Interchange) ■ EBCDIC Code (Extended Binary Coded Decimal Interchange Code) See Also: Oracle Database Rules Manager and Expression Filter Developer's Guide for more information on the Expression Filter See Also: "Numeric Precedence" on page 3-14 and "Floating-Point Numbers" on page 3-12 for more information on comparison semantics
  • 84. Data Type Comparison Rules 3-38 Oracle Database SQL Language Reference ■ ISO 8859/1 (International Organization for Standardization) ■ JEUC Japan Extended UNIX Linguistic comparison is useful if the binary sequence of numeric codes does not match the linguistic sequence of the characters you are comparing. Linguistic comparison is used if the NLS_SORT parameter has a setting other than BINARY and the NLS_COMP parameter is set to LINGUISTIC. In linguistic sorting, all SQL sorting and comparison are based on the linguistic rule specified by NLS_SORT. Blank-Padded and Nonpadded Comparison Semantics With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. Oracle then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of data type CHAR, NCHAR, text literals, or values returned by the USER function. With nonpadded semantics, Oracle compares two values character by character up to the first character that differs. The value with the greater character in that position is considered greater. If two values of different length are identical up to the end of the shorter one, then the longer value is considered greater. If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the data type VARCHAR2 or NVARCHAR2. The results of comparing two character values using different comparison semantics may vary. The table that follows shows the results of comparing five pairs of character values using each comparison semantic. Usually, the results of blank-padded and nonpadded comparisons are the same. The last comparison in the table illustrates the differences between the blank-padded and nonpadded comparison semantics. Portions of the ASCII and EBCDIC character sets appear in Table 3–8 and Table 3–9. Uppercase and lowercase letters are not equivalent. The numeric values for the characters of a character set may not match the linguistic sequence for a particular language. See Also: Oracle Database Globalization Support Guide for more information about linguistic sorting Blank-Padded Nonpadded 'ac' > 'ab' 'ac' > 'ab' 'ab' > 'a ' 'ab' > 'a ' 'ab' > 'a' 'ab' > 'a' 'ab' = 'ab' 'ab' = 'ab' 'a ' = 'a' 'a ' > 'a' Table 3–8 ASCII Character Set Symbol Decimal value Symbol Decimal value blank 32 ; 59
  • 85. Data Type Comparison Rules Basic Elements of Oracle SQL 3-39 ! 33 < 60 " 34 = 61 # 35 > 62 $ 36 ? 63 % 37 @ 64 & 38 A-Z 65-90 ' 39 [ 91 ( 40 92 ) 41 ] 93 * 42 ^ 94 + 43 _ 95 , 44 ' 96 - 45 a-z 97-122 . 46 { 123 / 47 | 124 0-9 48-57 } 125 : 58 ~ 126 Table 3–9 EBCDIC Character Set Symbol Decimal value Symbol Decimal value blank 64 % 108 ¢ 74 _ 109 . 75 > 110 < 76 ? 111 ( 77 : 122 + 78 # 123 | 79 @ 124 & 80 ' 125 ! 90 = 126 $ 91 " 127 * 92 a-i 129-137 ) 93 j-r 145-153 ; 94 s-z 162-169 ÿ 95 A-I 193-201 - 96 J-R 209-217 / 97 S-Z 226-233 Table 3–8 (Cont.) ASCII Character Set Symbol Decimal value Symbol Decimal value
  • 86. Data Type Comparison Rules 3-40 Oracle Database SQL Language Reference Object Values Object values are compared using one of two comparison functions: MAP and ORDER. Both functions compare object type instances, but they are quite different from one another. These functions must be specified as part of any object type that will be compared with other object types. Varrays and Nested Tables Comparison of nested tables is described in "Comparison Conditions" on page 7-4. Data Type Precedence Oracle uses data type precedence to determine implicit data type conversion, which is discussed in the section that follows. Oracle data types take the following precedence: ■ Datetime and interval data types ■ BINARY_DOUBLE ■ BINARY_FLOAT ■ NUMBER ■ Character data types ■ All other built-in data types Data Conversion Generally an expression cannot contain values of different data types. For example, an expression cannot multiply 5 by 10 and then add 'JAMES'. However, Oracle supports both implicit and explicit conversion of values from one data type to another. Implicit and Explicit Data Conversion Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons: ■ SQL statements are easier to understand when you use explicit data type conversion functions. ■ Implicit data type conversion can have a negative impact on performance, especially if the data type of a column value is converted to that of a constant rather than the other way around. ■ Implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a VARCHAR2 value may return an unexpected year depending on the value of the NLS_DATE_FORMAT parameter. ■ Algorithms for implicit conversion are subject to change across software releases and among Oracle products. Behavior of explicit conversions is more predictable. Implicit Data Conversion Oracle Database automatically converts a value from one data type to another when such a conversion makes sense. Implicit conversion to character data types follows these rules: See Also: CREATE TYPE on page 17-3 for a description of MAP and ORDER methods and the values they return
  • 87. Data Type Comparison Rules Basic Elements of Oracle SQL 3-41 Table 3–10 is a matrix of Oracle implicit conversions. The table shows all possible conversions, without regard to the direction of the conversion or the context in which it is made. The rules governing these details follow the table. The following rules govern implicit data type conversions: ■ During INSERT and UPDATE operations, Oracle converts the value to the data type of the affected column. ■ During SELECT FROM operations, Oracle converts the data from the column to the type of the target variable. ■ When manipulating numeric values, Oracle usually adjusts precision and scale to allow for maximum capacity. In such cases, the numeric data type resulting from such operations can differ from the numeric data type found in the underlying tables. ■ When comparing a character value with a numeric value, Oracle converts the character data to a numeric value. ■ Conversions between character values or NUMBER values and floating-point number values can be inexact, because the character types and NUMBER use decimal precision to represent the numeric value, and the floating-point numbers use binary precision. Table 3–10 Implicit Type Conversion Matrix CHAR VARCHAR2 NCHAR NVARCHAR2 DATE DATETIME/ INTERVAL NUMBER BINARY_FLOAT BINARY_DOUBLE LONG RAW ROWID CLOB BLOB NCLOB CHAR -- X X X X X X X X X X -- X X X VARCHAR2 X -- X X X X X X X X X X X -- X NCHAR X X -- X X X X X X X X X X -- X NVARCHAR2 X X X -- X X X X X X X X X -- X DATE X X X X -- -- -- -- -- -- -- -- -- -- -- DATETIME/ INTERVAL X X X X -- -- -- -- -- X -- -- -- -- -- NUMBER X X X X -- -- -- X X -- -- -- -- -- -- BINARY_ FLOAT X X X X -- -- X -- X -- -- -- -- -- -- BINARY_ DOUBLE X X X X -- -- X X -- -- -- -- -- -- -- LONG X X X X -- X1 -- -- -- -- X -- X -- X RAW X X X X -- -- -- -- -- X -- -- -- X -- ROWID -- X X X -- -- -- -- -- -- -- -- -- -- -- CLOB X X X X -- -- -- -- -- X -- -- -- -- X BLOB -- -- -- -- -- -- -- -- -- -- X -- -- -- -- NCLOB X X X X -- -- -- -- -- X -- -- X -- -- Note 1: You cannot convert LONG to INTERVAL directly, but you can convert LONG to VARCHAR2 using TO_CHAR(interval), and then convert the resulting VARCHAR2 value to INTERVAL.
  • 88. Data Type Comparison Rules 3-42 Oracle Database SQL Language Reference ■ When converting a CLOB value into a character data type such as VARCHAR2, or converting BLOB to RAW data, if the data to be converted is larger than the target data type, then the database returns an error. ■ During conversion from a timestamp value to a DATE value, the fractional seconds portion of the timestamp value is truncated. This behavior differs from earlier releases of Oracle Database, when the fractional seconds portion of the timestamp value was rounded. ■ Conversions from BINARY_FLOAT to BINARY_DOUBLE are exact. ■ Conversions from BINARY_DOUBLE to BINARY_FLOAT are inexact if the BINARY_ DOUBLE value uses more bits of precision that supported by the BINARY_FLOAT. ■ When comparing a character value with a DATE value, Oracle converts the character data to DATE. ■ When you use a SQL function or operator with an argument of a data type other than the one it accepts, Oracle converts the argument to the accepted data type. ■ When making assignments, Oracle converts the value on the right side of the equal sign (=) to the data type of the target of the assignment on the left side. ■ During concatenation operations, Oracle converts from noncharacter data types to CHAR or NCHAR. ■ During arithmetic operations on and comparisons between character and noncharacter data types, Oracle converts from any character data type to a numeric, date, or rowid, as appropriate. In arithmetic operations between CHAR/VARCHAR2 and NCHAR/NVARCHAR2, Oracle converts to a NUMBER. ■ Comparisons between CHAR and VARCHAR2 and between NCHAR and NVARCHAR2 types may entail different character sets. The default direction of conversion in such cases is from the database character set to the national character set. Table 3–11 shows the direction of implicit conversions between different character types. ■ Most SQL character functions are enabled to accept CLOBs as parameters, and Oracle performs implicit conversions between CLOB and character types. Therefore, functions that are not yet enabled for CLOBs can accept CLOBs through implicit conversion. In such cases, Oracle converts the CLOBs to CHAR or VARCHAR2 before the function is invoked. If the CLOB is larger than 4000 bytes, then Oracle converts only the first 4000 bytes to CHAR. User-defined types such as collections cannot be implicitly converted, but must be explicitly converted using CAST ... MULTISET. Table 3–11 Conversion Direction of Different Character Types to CHAR to VARCHAR2 to NCHAR to NVARCHAR2 from CHAR -- VARCHAR2 NCHAR NVARCHAR2 from VARCHAR2 VARCHAR2 -- NVARCHAR2 NVARCHAR2 from NCHAR NCHAR NCHAR -- NVARCHAR2 from NVARCHAR2 NVARCHAR2 NVARCHAR2 NVARCHAR2 --
  • 89. Data Type Comparison Rules Basic Elements of Oracle SQL 3-43 Implicit Data Conversion Examples Text Literal Example The text literal '10' has data type CHAR. Oracle implicitly converts it to the NUMBER data type if it appears in a numeric expression as in the following statement: SELECT salary + '10' FROM employees; Character and Number Values Example When a condition compares a character value and a NUMBER value, Oracle implicitly converts the character value to a NUMBER value, rather than converting the NUMBER value to a character value. In the following statement, Oracle implicitly converts '200' to 200: SELECT last_name FROM employees WHERE employee_id = '200'; Date Example In the following statement, Oracle implicitly converts '24-JUN-06' to a DATE value using the default date format 'DD-MON-YY': SELECT last_name FROM employees WHERE hire_date = '24-JUN-06'; Explicit Data Conversion You can explicitly specify data type conversions using SQL conversion functions. Table 3–12 shows SQL functions that explicitly convert a value from one data type to another. You cannot specify LONG and LONG RAW values in cases in which Oracle can perform implicit data type conversion. For example, LONG and LONG RAW values cannot appear in expressions with functions or operators. Refer to "LONG Data Type" on page 3-14 for information on the limitations on LONG and LONG RAW data types.
  • 90. Data Type Comparison Rules 3-44 Oracle Database SQL Language Reference Security Considerations for Data Conversion When a datetime value is converted to text, either by implicit conversion or by explicit conversion that does not specify a format model, the format model is defined by one of the globalization session parameters. Depending on the source data type, the parameter name is NLS_DATE_FORMAT, NLS_TIMESTAMP_FORMAT, or NLS_ TIMESTAMP_TZ_FORMAT. The values of these parameters can be specified in the client environment or in an ALTER SESSION statement. Table 3–12 Explicit Type Conversions toCHAR, VARCHAR2, NCHAR, NVARCHAR2 toNUMBER toDatetime/ Interval toRAW toROWID toLONG, LONGRAW toCLOB,NCLOB, BLOB toBINARY_FLOAT toBINARY_DOUBLE from CHAR, VARCHAR2, NCHAR, NVARCHAR2 TO_CHAR (char.) TO_NCHAR (char.) TO_ NUMBER TO_DATE TO_TIMESTAMP TO_ TIMESTAMP_TZ TO_ YMINTERVAL TO_ DSINTERVAL HEXTORAW CHARTO= ROWID -- TO_CLOB TO_NCLOB TO_ BINARY_ FLOAT TO_ BINARY_ DOUBLE from NUMBER TO_CHAR (number) TO_NCHAR (number) -- TO_DATE NUMTOYM- INTERVAL NUMTODS- INTERVAL -- -- -- -- TO_ BINARY_ FLOAT TO_ BINARY_ DOUBLE from Datetime/ Interval TO_CHAR (date) TO_NCHAR (datetime) -- -- -- -- -- -- -- -- from RAW RAWTOHEX RAWTONHEX -- -- -- -- -- TO_BLOB -- -- from ROWID ROWIDTOCHAR -- -- -- -- -- -- -- -- from LONG / LONG RAW -- -- -- -- -- -- TO_LOB -- -- from CLOB, NCLOB, BLOB TO_CHAR TO_NCHAR -- -- -- -- -- TO_CLOB TO_NCLOB -- -- from CLOB, NCLOB, BLOB TO_CHAR TO_NCHAR -- -- -- -- -- TO_CLOB TO_NCLOB -- -- from BINARY_ FLOAT TO_CHAR (char.) TO_NCHAR (char.) TO_ NUMBER -- -- -- -- -- TO_ BINARY_ FLOAT TO_ BINARY_ DOUBLE from BINARY_ DOUBLE TO_CHAR (char.) TO_NCHAR (char.) TO_ NUMBER -- -- -- -- -- TO_ BINARY_ FLOAT TO_ BINARY_ DOUBLE See Also: "Conversion Functions" on page 5-6 for details on all of the explicit conversion functions
  • 91. Literals Basic Elements of Oracle SQL 3-45 The dependency of format models on session parameters can have a negative impact on database security when conversion without an explicit format model is applied to a datetime value that is being concatenated to text of a dynamic SQL statement. Dynamic SQL statements are those statements whose text is concatenated from fragments before being passed to a database for execution. Dynamic SQL is frequently associated with the built-in PL/SQL package DBMS_SQL or with the PL/SQL statement EXECUTE IMMEDIATE, but these are not the only places where dynamically constructed SQL text may be passed as argument. For example: EXECUTE IMMEDIATE 'SELECT name FROM employee WHERE hiredate > ''' || start_date || ''''; where start_date has the data type DATE. In the above example, the value of start_date is converted to text using a format model specified in the session parameter NLS_DATE_FORMAT. The result is concatenated into SQL text. A datetime format model can consist simply of literal text enclosed in double quotation marks. Therefore, any user who can explicitly set globalization parameters for a session can decide what text is produced by the above conversion. If the SQL statement is executed by a PL/SQL procedure, the procedure becomes vulnerable to SQL injection through the session parameter. If the procedure runs with definer's rights, with higher privileges than the session itself, the user can gain unauthorized access to sensitive data. Implicit and explicit conversion for numeric values may also suffer from the analogous problem, as the conversion result may depend on the session parameter NLS_ NUMERIC_CHARACTERS. This parameter defines the decimal and group separator characters. If the decimal separator is defined to be the quotation mark or the double quotation mark, some potential for SQL injection emerges. Literals The terms literal and constant value are synonymous and refer to a fixed data value. For example, 'JACK', 'BLUE ISLAND', and '101' are all character literals; 5001 is a numeric literal. Character literals are enclosed in single quotation marks so that Oracle can distinguish them from schema object names. This section contains these topics: ■ Text Literals See Also: Oracle Database PL/SQL Language Reference for further examples and for recommendations on avoiding this security risk Note: This security risk also applies to middle-tier applications that construct SQL text from datetime values converted to text by the database or by OCI datetime functions. Those applications are vulnerable if session globalization parameters are obtained from a user preference. See Also: ■ Oracle Database Globalization Support Guide for detailed descriptions of the session globalization parameters ■ "Format Models" on page 3-55 for information on the format models
  • 92. Literals 3-46 Oracle Database SQL Language Reference ■ Numeric Literals ■ Datetime Literals ■ Interval Literals Many SQL statements and functions require you to specify character and numeric literal values. You can also specify literals as part of expressions and conditions. You can specify character literals with the 'text' notation, national character literals with the N'text' notation, and numeric literals with the integer, or number notation, depending on the context of the literal. The syntactic forms of these notations appear in the sections that follow. To specify a datetime or interval data type as a literal, you must take into account any optional precisions included in the data types. Examples of specifying datetime and interval data types as literals are provided in the relevant sections of "Data Types" on page 3-1. Text Literals Use the text literal notation to specify values whenever 'string' appears in the syntax of expressions, conditions, SQL functions, and SQL statements in other parts of this reference. This reference uses the terms text literal, character literal, and string interchangeably. Text, character, and string literals are always surrounded by single quotation marks. If the syntax uses the term char, then you can specify either a text literal or another expression that resolves to character data — for example, the last_ name column of the hr.employees table. When char appears in the syntax, the single quotation marks are not used. The syntax of text literals or strings follows: string::= where N or n specifies the literal using the national character set (NCHAR or NVARCHAR2 data). By default, text entered using this notation is translated into the national character set by way of the database character set when used by the server. To avoid potential loss of data during the text literal conversion to the database character set, set the environment variable ORA_NCHAR_LITERAL_REPLACE to TRUE. Doing so transparently replaces the n' internally and preserves the text literal for SQL processing. In the top branch of the syntax: ■ c is any member of the user's character set. A single quotation mark (') within the literal must be preceded by an escape character. To represent one single quotation mark within a literal, enter two single quotation marks. ■ ' ' are two single quotation marks that begin and end text literals. In the bottom branch of the syntax: See Also: Oracle Database Globalization Support Guide for more information about N-quoted literals N n ’ c ’ Q q ’ quote_delimiter c quote_delimiter ’
  • 93. Literals Basic Elements of Oracle SQL 3-47 ■ Q or q indicates that the alternative quoting mechanism will be used. This mechanism allows a wide range of delimiters for the text string. ■ The outermost ' ' are two single quotation marks that precede and follow, respectively, the opening and closing quote_delimiter. ■ c is any member of the user's character set. You can include quotation marks (") in the text literal made up of c characters. You can also include the quote_ delimiter, as long as it is not immediately followed by a single quotation mark. ■ quote_delimiter is any single- or multibyte character except space, tab, and return. The quote_delimiter can be a single quotation mark. However, if the quote_delimiter appears in the text literal itself, ensure that it is not immediately followed by a single quotation mark. If the opening quote_delimiter is one of [, {, <, or (, then the closing quote_ delimiter must be the corresponding ], }, >, or ). In all other cases, the opening and closing quote_delimiter must be the same character. Text literals have properties of both the CHAR and VARCHAR2 data types: ■ Within expressions and conditions, Oracle treats text literals as though they have the data type CHAR by comparing them using blank-padded comparison semantics. ■ A text literal can have a maximum length of 4000 bytes. Here are some valid text literals: 'Hello' 'ORACLE.dbs' 'Jackie''s raincoat' '09-MAR-98' N'nchar literal' Here are some valid text literals using the alternative quoting mechanism: q'!name LIKE '%DBMS_%%'!' q'<'So,' she said, 'It's finished.'>' q'{SELECT * FROM employees WHERE last_name = 'Smith';}' nq'ï Ÿ1234 ï' q'"name like '['"' Numeric Literals Use numeric literal notation to specify fixed and floating-point numbers. Integer Literals You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference. The syntax of integer follows: See Also: "Blank-Padded and Nonpadded Comparison Semantics" on page 3-38
  • 94. Literals 3-48 Oracle Database SQL Language Reference integer::= where digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. An integer can store a maximum of 38 digits of precision. Here are some valid integers: 7 +255 NUMBER and Floating-Point Literals You must use the number or floating-point notation to specify values whenever number or n appears in expressions, conditions, SQL functions, and SQL statements in other parts of this reference. The syntax of number follows: number::= where ■ + or - indicates a positive or negative value. If you omit the sign, then a positive value is the default. ■ digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9. ■ e or E indicates that the number is specified in scientific notation. The digits after the E specify the exponent. The exponent can range from -130 to 125. ■ f or F indicates that the number is a 32-bit binary floating point number of type BINARY_FLOAT. ■ d or D indicates that the number is a 64-bit binary floating point number of type BINARY_DOUBLE. If you omit f or F and d or D, then the number is of type NUMBER. The suffixes f (F) and d (D) are supported only in floating-point number literals, not in character strings that are to be converted to NUMBER. For example, if Oracle is expecting a NUMBER and it encounters the string '9', then it converts the string to the number 9. However, if Oracle encounters the string '9f', then conversion fails and an error is returned. + – digit + – digit . digit . digit e + – digit f d
  • 95. Literals Basic Elements of Oracle SQL 3-49 A number of type NUMBER can store a maximum of 38 digits of precision. If the literal requires more precision than provided by NUMBER, BINARY_FLOAT, or BINARY_ DOUBLE, then Oracle truncates the value. If the range of the literal exceeds the range supported by NUMBER, BINARY_FLOAT, or BINARY_DOUBLE, then Oracle raises an error. If you have established a decimal character other than a period (.) with the initialization parameter NLS_NUMERIC_CHARACTERS, then you must specify numeric literals with 'text' notation. In these cases, Oracle automatically converts the text literal to a numeric value. For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character of comma, specify the number 5.123 as follows: '5,123' Here are some valid NUMBER literals: 25 +6.34 0.5 25e-03 -1 Here are some valid floating-point number literals: 25f +6.34F 0.5d -1D You can also use the following supplied floating-point literals in situations where a value cannot be expressed as a numeric literal: Note: You cannot use this notation for floating-point number literals. See Also: ALTER SESSION on page 11-45 and Oracle Database Reference Literal Meaning Example binary_float_nan A value of type BINARY_FLOAT for which the condition IS NAN is true SELECT COUNT(*) FROM employees WHERE TO_BINARY_FLOAT(commission_pct) != BINARY_FLOAT_NAN; binary_float_ infinity Single-precision positive infinity SELECT COUNT(*) FROM employees WHERE salary < BINARY_FLOAT_INFINITY; binary_double_nan A value of type BINARY_DOUBLE for which the condition IS NAN is true SELECT COUNT(*) FROM employees WHERE TO_BINARY_FLOAT(commission_pct) != BINARY_FLOAT_NAN; binary_double_ infinity Double-precision positive infinity SELECT COUNT(*) FROM employees WHERE salary < BINARY_FLOAT_INFINITY;
  • 96. Literals 3-50 Oracle Database SQL Language Reference Datetime Literals Oracle Database supports four datetime data types: DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE. Date Literals You can specify a DATE value as a string literal, or you can convert a character or numeric value to a date value with the TO_DATE function. DATE literals are the only case in which Oracle Database accepts a TO_DATE expression in place of a string literal. To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example: DATE '1998-12-25' The ANSI date literal contains no time portion, and must be specified in the format 'YYYY-MM-DD'. Alternatively you can specify an Oracle date value, as in the following example: TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI') The default date format for an Oracle DATE value is specified by the initialization parameter NLS_DATE_FORMAT. This example date format includes a two-digit number for the day of the month, an abbreviation of the month name, the last two digits of the year, and a 24-hour time designation. Oracle automatically converts character values that are in the default date format into date values when they are used in date expressions. If you specify a date value without a time component, then the default time is midnight (00:00:00 or 12:00:00 for 24-hour and 12-hour clock time, respectively). If you specify a date value without a date, then the default date is the first day of the current month. Oracle DATE columns always contain both the date and time fields. Therefore, if you query a DATE column, then you must either specify the time field in your query or ensure that the time fields in the DATE column are set to midnight. Otherwise, Oracle may not return the query results you expect. You can use the TRUNC date function to set the time field to midnight, or you can include a greater-than or less-than condition in the query instead of an equality or inequality condition. Here are some examples that assume a table my_table with a number column row_ num and a DATE column datecol: INSERT INTO my_table VALUES (1, SYSDATE); INSERT INTO my_table VALUES (2, TRUNC(SYSDATE)); SELECT * FROM my_table; ROW_NUM DATECOL ---------- --------- 1 03-OCT-02 2 03-OCT-02 SELECT * FROM my_table WHERE datecol = TO_DATE('03-OCT-02','DD-MON-YY'); ROW_NUM DATECOL ---------- --------- 2 03-OCT-02
  • 97. Literals Basic Elements of Oracle SQL 3-51 SELECT * FROM my_table WHERE datecol > TO_DATE('02-OCT-02', 'DD-MON-YY'); ROW_NUM DATECOL ---------- --------- 1 03-OCT-02 2 03-OCT-02 If you know that the time fields of your DATE column are set to midnight, then you can query your DATE column as shown in the immediately preceding example, or by using the DATE literal: SELECT * FROM my_table WHERE datecol = DATE '2002-10-03'; However, if the DATE column contains values other than midnight, then you must filter out the time fields in the query to get the correct result. For example: SELECT * FROM my_table WHERE TRUNC(datecol) = DATE '2002-10-03'; Oracle applies the TRUNC function to each row in the query, so performance is better if you ensure the midnight value of the time fields in your data. To ensure that the time fields are set to midnight, use one of the following methods during inserts and updates: ■ Use the TO_DATE function to mask out the time fields: INSERT INTO my_table VALUES (3, TO_DATE('3-OCT-2002','DD-MON-YYYY')); ■ Use the DATE literal: INSERT INTO my_table VALUES (4, '03-OCT-02'); ■ Use the TRUNC function: INSERT INTO my_table VALUES (5, TRUNC(SYSDATE)); The date function SYSDATE returns the current system date and time. The function CURRENT_DATE returns the current session date. For information on SYSDATE, the TO_* datetime functions, and the default date format, see "Datetime Functions" on page 5-5. TIMESTAMP Literals The TIMESTAMP data type stores year, month, day, hour, minute, and second, and fractional second values. When you specify TIMESTAMP as a literal, the fractional_seconds_precision value can be any number of digits up to 9, as follows: TIMESTAMP '1997-01-31 09:26:50.124' TIMESTAMP WITH TIME ZONE Literals The TIMESTAMP WITH TIME ZONE data type is a variant of TIMESTAMP that includes a time zone region name or time zone offset. When you specify TIMESTAMP WITH TIME ZONE as a literal, the fractional_seconds_precision value can be any number of digits up to 9. For example: TIMESTAMP '1997-01-31 09:26:56.66 +02:00' Two TIMESTAMP WITH TIME ZONE values are considered identical if they represent the same instant in UTC, regardless of the TIME ZONE offsets stored in the data. For example, TIMESTAMP '1999-04-15 8:00:00 -8:00'
  • 98. Literals 3-52 Oracle Database SQL Language Reference is the same as TIMESTAMP '1999-04-15 11:00:00 -5:00' 8:00 a.m. Pacific Standard Time is the same as 11:00 a.m. Eastern Standard Time. You can replace the UTC offset with the TZR (time zone region name) format element. For example, the following example has the same value as the preceding example: TIMESTAMP '1999-04-15 8:00:00 US/Pacific' To eliminate the ambiguity of boundary cases when the daylight saving time switches, use both the TZR and a corresponding TZD format element. The following example ensures that the preceding example will return a daylight saving time value: TIMESTAMP '1999-10-29 01:30:00 US/Pacific PDT' You can also express the time zone offset using a datetime expression: SELECT TIMESTAMP '1999-10-29 01:30:00' AT TIME ZONE 'US/Pacific' FROM DUAL; If you do not add the TZD format element, and the datetime value is ambiguous, then Oracle returns an error if you have the ERROR_ON_OVERLAP_TIME session parameter set to TRUE. If that parameter is set to FALSE, then Oracle interprets the ambiguous datetime as standard time in the specified region. TIMESTAMP WITH LOCAL TIME ZONE Literals The TIMESTAMP WITH LOCAL TIME ZONE data type differs from TIMESTAMP WITH TIME ZONE in that data stored in the database is normalized to the database time zone. The time zone offset is not stored as part of the column data. There is no literal for TIMESTAMP WITH LOCAL TIME ZONE. Rather, you represent values of this data type using any of the other valid datetime literals. The table that follows shows some of the formats you can use to insert a value into a TIMESTAMP WITH LOCAL TIME ZONE column, along with the corresponding value returned by a query. Notice that if the value specified does not include a time component (either explicitly or implicitly, then the value returned defaults to midnight. Interval Literals An interval literal specifies a period of time. You can specify these differences in terms of years and months, or in terms of days, hours, minutes, and seconds. Oracle Database supports two types of interval literals, YEAR TO MONTH and DAY TO SECOND. See Also: "Datetime Expressions" on page 6-8 for more information Value Specified in INSERT Statement Value Returned by Query '19-FEB-2004' 19-FEB-2004.00.00.000000 AM SYSTIMESTAMP 19-FEB-04 02.54.36.497659 PM TO_TIMESTAMP('19-FEB-2004', 'DD-MON-YYYY')); 19-FEB-04 12.00.00.000000 AM SYSDATE 19-FEB-04 02.55.29.000000 PM TO_DATE('19-FEB-2004', 'DD-MON-YYYY')); 19-FEB-04 12.00.00.000000 AM TIMESTAMP'2004-02-19 8:00:00 US/Pacific'); 19-FEB-04 08.00.00.000000 AM
  • 99. Literals Basic Elements of Oracle SQL 3-53 Each type contains a leading field and may contain a trailing field. The leading field defines the basic unit of date or time being measured. The trailing field defines the smallest increment of the basic unit being considered. For example, a YEAR TO MONTH interval considers an interval of years to the nearest month. A DAY TO MINUTE interval considers an interval of days to the nearest minute. If you have date data in numeric form, then you can use the NUMTOYMINTERVAL or NUMTODSINTERVAL conversion function to convert the numeric data into interval values. Interval literals are used primarily with analytic functions. INTERVAL YEAR TO MONTH Specify YEAR TO MONTH interval literals using the following syntax: interval_year_to_month::= where ■ 'integer [-integer]' specifies integer values for the leading and optional trailing field of the literal. If the leading field is YEAR and the trailing field is MONTH, then the range of integer values for the month field is 0 to 11. ■ precision is the maximum number of digits in the leading field. The valid range of the leading field precision is 0 to 9 and its default value is 2. Restriction on the Leading Field If you specify a trailing field, then it must be less significant than the leading field. For example, INTERVAL '0-1' MONTH TO YEAR is not valid. The following INTERVAL YEAR TO MONTH literal indicates an interval of 123 years, 2 months: INTERVAL '123-2' YEAR(3) TO MONTH Examples of the other forms of the literal follow, including some abbreviated versions: See Also: "Analytic Functions" on page 5-11, NUMTODSINTERVAL on page 5-125, NUMTOYMINTERVAL on page 5-126, and Oracle Database Data Warehousing Guide Form of Interval Literal Interpretation INTERVAL '123-2' YEAR(3) TO MONTH An interval of 123 years, 2 months. You must specify the leading field precision if it is greater than the default of 2 digits. INTERVAL '123' YEAR(3) An interval of 123 years 0 months. INTERVAL '300' MONTH(3) An interval of 300 months. INTERVAL ’ integer – integer ’ YEAR MONTH ( precision ) TO YEAR MONTH
  • 100. Literals 3-54 Oracle Database SQL Language Reference You can add or subtract one INTERVAL YEAR TO MONTH literal to or from another to yield another INTERVAL YEAR TO MONTH literal. For example: INTERVAL '5-3' YEAR TO MONTH + INTERVAL'20' MONTH = INTERVAL '6-11' YEAR TO MONTH INTERVAL DAY TO SECOND Specify DAY TO SECOND interval literals using the following syntax: interval_day_to_second::= where ■ integer specifies the number of days. If this value contains more digits than the number specified by the leading precision, then Oracle returns an error. ■ time_expr specifies a time in the format HH[:MI[:SS[.n]]] or MI[:SS[.n]] or SS[.n], where n specifies the fractional part of a second. If n contains more digits than the number specified by fractional_seconds_precision, then n is rounded to the number of digits specified by the fractional_seconds_ precision value. You can specify time_expr following an integer and a space only if the leading field is DAY. INTERVAL '4' YEAR Maps to INTERVAL '4-0' YEAR TO MONTH and indicates 4 years. INTERVAL '50' MONTH Maps to INTERVAL '4-2' YEAR TO MONTH and indicates 50 months or 4 years 2 months. INTERVAL '123' YEAR Returns an error, because the default precision is 2, and '123' has 3 digits. Form of Interval Literal Interpretation INTERVAL ’ integer integer time_expr time_expr ’ DAY HOUR MINUTE ( leading_precision ) SECOND ( leading_precision , fractional_seconds_precision ) TO DAY HOUR MINUTE SECOND ( fractional_seconds_precision )
  • 101. Format Models Basic Elements of Oracle SQL 3-55 ■ leading_precision is the number of digits in the leading field. Accepted values are 0 to 9. The default is 2. ■ fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 1 to 9. The default is 6. Restriction on the Leading Field: If you specify a trailing field, then it must be less significant than the leading field. For example, INTERVAL MINUTE TO DAY is not valid. As a result of this restriction, if SECOND is the leading field, the interval literal cannot have any trailing field. The valid range of values for the trailing field are as follows: ■ HOUR: 0 to 23 ■ MINUTE: 0 to 59 ■ SECOND: 0 to 59.999999999 Examples of the various forms of INTERVAL DAY TO SECOND literals follow, including some abbreviated versions: You can add or subtract one DAY TO SECOND interval literal from another DAY TO SECOND literal. For example. INTERVAL'20' DAY - INTERVAL'240' HOUR = INTERVAL'10-0' DAY TO SECOND Format Models A format model is a character literal that describes the format of datetime or numeric data stored in a character string. A format model does not change the internal representation of the value in the database. When you convert a character string into a date or number, a format model determines how Oracle Database interprets the string. Form of Interval Literal Interpretation INTERVAL '4 5:12:10.222' DAY TO SECOND(3) 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second. INTERVAL '4 5:12' DAY TO MINUTE 4 days, 5 hours and 12 minutes. INTERVAL '400 5' DAY(3) TO HOUR 400 days 5 hours. INTERVAL '400' DAY(3) 400 days. INTERVAL '11:12:10.2222222' HOUR TO SECOND(7) 11 hours, 12 minutes, and 10.2222222 seconds. INTERVAL '11:20' HOUR TO MINUTE 11 hours and 20 minutes. INTERVAL '10' HOUR 10 hours. INTERVAL '10:22' MINUTE TO SECOND 10 minutes 22 seconds. INTERVAL '10' MINUTE 10 minutes. INTERVAL '4' DAY 4 days. INTERVAL '25' HOUR 25 hours. INTERVAL '40' MINUTE 40 minutes. INTERVAL '120' HOUR(3) 120 hours. INTERVAL '30.12345' SECOND(2,4) 30.1235 seconds. The fractional second '12345' is rounded to '1235' because the precision is 4.
  • 102. Format Models 3-56 Oracle Database SQL Language Reference In SQL statements, you can use a format model as an argument of the TO_CHAR and TO_DATE functions to specify: ■ The format for Oracle to use to return a value from the database ■ The format for a value you have specified for Oracle to store in the database For example: ■ The datetime format model for the string '17:45:29' is 'HH24:MI:SS'. ■ The datetime format model for the string '11-Nov-1999' is 'DD-Mon-YYYY'. ■ The number format model for the string '$2,304.25' is '$9,999.99'. For lists of number and datetime format model elements, see Table 3–13, " Number Format Elements" on page 3-57 and Table 3–15, " Datetime Format Elements" on page 3-60. The values of some formats are determined by the value of initialization parameters. For such formats, you can specify the characters returned by these format elements implicitly using the initialization parameter NLS_TERRITORY. You can change the default date format for your session with the ALTER SESSION statement. This remainder of this section describes how to use the following format models: ■ Number Format Models ■ Datetime Format Models ■ Format Model Modifiers Number Format Models You can use number format models in the following functions: ■ In the TO_CHAR function to translate a value of NUMBER, BINARY_FLOAT, or BINARY_DOUBLE data type to VARCHAR2 data type ■ In the TO_NUMBER function to translate a value of CHAR or VARCHAR2 data type to NUMBER data type ■ In the TO_BINARY_FLOAT and TO_BINARY_DOUBLE functions to translate CHAR and VARCHAR2 expressions to BINARY_FLOAT or BINARY_DOUBLE values All number format models cause the number to be rounded to the specified number of significant digits. If a value has more significant digits to the left of the decimal place than are specified in the format, then pound signs (#) replace the value. This event typically occurs when you are using TO_CHAR with a restrictive number format string, causing a rounding operation. ■ If a positive NUMBER value is extremely large and cannot be represented in the specified format, then the infinity sign (~) replaces the value. Likewise, if a See Also: ■ ALTER SESSION on page 11-45 for information on changing the values of these parameters and Format Model Examples on page 3-67 for examples of using format models ■ TO_CHAR (datetime) on page 5-219, TO_CHAR (number) on page 5-221, and TO_DATE on page 5-223 ■ Oracle Database Reference and Oracle Database Globalization Support Guide for information on these parameters
  • 103. Format Models Basic Elements of Oracle SQL 3-57 negative NUMBER value is extremely small and cannot be represented by the specified format, then the negative infinity sign replaces the value (-~). ■ If a BINARY_FLOAT or BINARY_DOUBLE value is converted to CHAR or NCHAR, and the input is either infinity or NaN (not a number), then Oracle always returns the pound signs to replace the value. However, if you omit the format model, then Oracle returns either Inf or Nan as a string. Number Format Elements A number format model is composed of one or more number format elements. The tables that follow list the elements of a number format model and provide some examples. Negative return values automatically contain a leading negative sign and positive values automatically contain a leading space unless the format model contains the MI, S, or PR format element. Table 3–13 Number Format Elements Element Example Description , (comma) 9,999 Returns a comma in the specified position. You can specify multiple commas in a number format model. Restrictions: ■ A comma element cannot begin a number format model. ■ A comma cannot appear to the right of a decimal character or period in a number format model. . (period) 99.99 Returns a decimal point, which is a period (.) in the specified position. Restriction: You can specify only one period in a number format model. $ $9999 Returns value with a leading dollar sign. 0 0999 9990 Returns leading zeros. Returns trailing zeros. 9 9999 Returns value with the specified number of digits with a leading space if positive or with a leading minus if negative. Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the fixed-point number. B B9999 Returns blanks for the integer part of a fixed-point number when the integer part is zero (regardless of zeros in the format model). C C999 Returns in the specified position the ISO currency symbol (the current value of the NLS_ISO_CURRENCY parameter). D 99D99 Returns in the specified position the decimal character, which is the current value of the NLS_NUMERIC_CHARACTER parameter. The default is a period (.). Restriction: You can specify only one decimal character in a number format model. EEEE 9.9EEEE Returns a value using in scientific notation. G 9G999 Returns in the specified position the group separator (the current value of the NLS_NUMERIC_CHARACTER parameter). You can specify multiple group separators in a number format model. Restriction: A group separator cannot appear to the right of a decimal character or period in a number format model. L L999 Returns in the specified position the local currency symbol (the current value of the NLS_CURRENCY parameter).
  • 104. Format Models 3-58 Oracle Database SQL Language Reference Table 3–14 shows the results of the following query for different values of number and 'fmt': SELECT TO_CHAR(number, 'fmt') FROM DUAL; MI 9999MI Returns negative value with a trailing minus sign (-). Returns positive value with a trailing blank. Restriction: The MI format element can appear only in the last position of a number format model. PR 9999PR Returns negative value in <angle brackets>. Returns positive value with a leading and trailing blank. Restriction: The PR format element can appear only in the last position of a number format model. RN rn RN rn Returns a value as Roman numerals in uppercase. Returns a value as Roman numerals in lowercase. Value can be an integer between 1 and 3999. S S9999 9999S Returns negative value with a leading minus sign (-). Returns positive value with a leading plus sign (+). Returns negative value with a trailing minus sign (-). Returns positive value with a trailing plus sign (+). Restriction: The S format element can appear only in the first or last position of a number format model. TM TM The text minimum number format model returns (in decimal output) the smallest number of characters possible. This element is case insensitive. The default is TM9, which returns the number in fixed notation unless the output exceeds 64 characters. If the output exceeds 64 characters, then Oracle Database automatically returns the number in scientific notation. Restrictions: ■ You cannot precede this element with any other element. ■ You can follow this element only with one 9 or one E (or e), but not with any combination of these. The following statement returns an error: SELECT TO_CHAR(1234, 'TM9e') FROM DUAL; U U9999 Returns in the specified position the Euro (or other) dual currency symbol, determined by the current value of the NLS_DUAL_CURRENCY parameter. V 999V99 Returns a value multiplied by 10n (and if necessary, round it up), where n is the number of 9's after the V. X XXXX xxxx Returns the hexadecimal value of the specified number of digits. If the specified number is not an integer, then Oracle Database rounds it to an integer. Restrictions: ■ This element accepts only positive values or 0. Negative values return an error. ■ You can precede this element only with 0 (which returns leading zeroes) or FM. Any other elements return an error. If you specify neither 0 nor FM with X, then the return always has one leading blank. Table 3–13 (Cont.) Number Format Elements Element Example Description
  • 105. Format Models Basic Elements of Oracle SQL 3-59 Datetime Format Models You can use datetime format models in the following functions: ■ In the TO_* datetime functions to translate a character value that is in a format other than the default format into a datetime value. (The TO_* datetime functions are TO_DATE, TO_TIMESTAMP, and TO_TIMESTAMP_TZ.) ■ In the TO_CHAR function to translate a datetime value into a character value that is in a format other than the default format (for example, to print the date from an application) The total length of a datetime format model cannot exceed 22 characters. The default datetime formats are specified either explicitly with the NLS session parameters NLS_DATE_FORMAT, NLS_TIMESTAMP_FORMAT, and NLS_TIMESTAMP_ TZ_FORMAT, or implicitly with the NLS session parameter NLS_TERRITORY. You can change the default datetime formats for your session with the ALTER SESSION statement. Table 3–14 Results of Number Conversions number 'fmt' Result -1234567890 9999999999S '1234567890-' 0 99.99 ' .00' +0.1 99.99 ' .10' -0.2 99.99 ' -.20' 0 90.99 ' 0.00' +0.1 90.99 ' 0.10' -0.2 90.99 ' -0.20' 0 9999 ' 0' 1 9999 ' 1' 0 B9999 ' ' 1 B9999 ' 1' 0 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.2E+02' +123.45 FM999.009 '123.45' +123.0 FM999.009 '123.00' +123.45 L999.99 ' $123.45' +123.45 FML999.99 '$123.45' +1234567890 9999999999S '1234567890+'
  • 106. Format Models 3-60 Oracle Database SQL Language Reference Datetime Format Elements A datetime format model is composed of one or more datetime format elements as listed in Table 3–15, " Datetime Format Elements" on page 3-60. ■ For input format models, format items cannot appear twice, and format items that represent similar information cannot be combined. For example, you cannot use 'SYYYY' and 'BC' in the same format string. ■ The second column indicates whether the format element can be used in the TO_* datetime functions. All format elements can be used in the TO_CHAR function. ■ The following datetime format elements can be used in timestamp and interval format models, but not in the original DATE format model: FF, TZD, TZH, TZM, and TZR. ■ Many datetime format elements are padded with blanks or leading zeroes to a specific length. Refer to the format model modifier FM on page 3-66 for more information. Uppercase Letters in Date Format Elements Capitalization in a spelled-out word, abbreviation, or Roman numeral follows capitalization in the corresponding format element. For example, the date format model 'DAY' produces capitalized words like 'MONDAY'; 'Day' produces 'Monday'; and 'day' produces 'monday'. Punctuation and Character Literals in Datetime Format Models You can include these characters in a date format model: ■ Punctuation such as hyphens, slashes, commas, periods, and colons ■ Character literals, enclosed in double quotation marks These characters appear in the return value in the same location as they appear in the format model. See Also: ALTER SESSION on page 11-45 and Oracle Database Globalization Support Guide for information on the NLS parameters Table 3–15 Datetime Format Elements Element TO_* datetime functions? Description - / , . ; : "text" Yes Punctuation and quoted text is reproduced in the result. AD A.D. Yes AD indicator with or without periods. AM A.M. Yes Meridian indicator with or without periods. BC B.C. Yes BC indicator with or without periods.
  • 107. Format Models Basic Elements of Oracle SQL 3-61 CC SCC Century. ■ If the last 2 digits of a 4-digit year are between 01 and 99 (inclusive), then the century is one greater than the first 2 digits of that year. ■ If the last 2 digits of a 4-digit year are 00, then the century is the same as the first 2 digits of that year. For example, 2002 returns 21; 2000 returns 20. D Yes Day of week (1-7). This element depends on the NLS territory of the session. DAY Yes Name of day. DD Yes Day of month (1-31). DDD Yes Day of year (1-366). DL Yes Returns a value in the long date format, which is an extension of the Oracle Database DATE format, determined by the current value of the NLS_DATE_FORMAT parameter. Makes the appearance of the date components (day name, month number, and so forth) depend on the NLS_TERRITORY and NLS_LANGUAGE parameters. For example, in the AMERICAN_AMERICA locale, this is equivalent to specifying the format 'fmDay, Month dd, yyyy'. In the GERMAN_GERMANY locale, it is equivalent to specifying the format 'fmDay, dd. Month yyyy'. Restriction: You can specify this format only with the TS element, separated by white space. DS Yes Returns a value in the short date format. Makes the appearance of the date components (day name, month number, and so forth) depend on the NLS_ TERRITORY and NLS_LANGUAGE parameters. For example, in the AMERICAN_ AMERICA locale, this is equivalent to specifying the format 'MM/DD/RRRR'. In the ENGLISH_UNITED_KINGDOM locale, it is equivalent to specifying the format 'DD/MM/RRRR'. Restriction: You can specify this format only with the TS element, separated by white space. DY Yes Abbreviated name of day. E Yes Abbreviated era name (Japanese Imperial, ROC Official, and Thai Buddha calendars). EE Yes Full era name (Japanese Imperial, ROC Official, and Thai Buddha calendars). FF [1..9] Yes Fractional seconds; no radix character is printed. Use the X format element to add the radix character. Use the numbers 1 to 9 after FF to specify the number of digits in the fractional second portion of the datetime value returned. If you do not specify a digit, then Oracle Database uses the precision specified for the datetime data type or the data type's default precision. Valid in timestamp and interval formats, but not in DATE formats. Examples: 'HH:MI:SS.FF' SELECT TO_CHAR(SYSTIMESTAMP, 'SS.FF3') from dual; FM Yes Returns a value with no leading or trailing blanks. See Also: Additional discussion on this format model modifier in the Oracle Database SQL Language Reference FX Yes Requires exact matching between the character data and the format model. See Also: Additional discussion on this format model modifier in the Oracle Database SQL Language Reference HH HH12 Yes Hour of day (1-12). Table 3–15 (Cont.) Datetime Format Elements Element TO_* datetime functions? Description
  • 108. Format Models 3-62 Oracle Database SQL Language Reference HH24 Yes Hour of day (0-23). IW Week of year (1-52 or 1-53) based on the ISO standard. IYY IY I Last 3, 2, or 1 digit(s) of ISO year. IYYY 4-digit year based on the ISO standard. J Yes Julian day; the number of days since January 1, 4712 BC. Number specified with J must be integers. MI Yes Minute (0-59). MM Yes Month (01-12; January = 01). MON Yes Abbreviated name of month. MONTH Yes Name of month. PM P.M. Yes Meridian indicator with or without periods. Q Quarter of year (1, 2, 3, 4; January - March = 1). RM Yes Roman numeral month (I-XII; January = I). RR Yes Lets you store 20th century dates in the 21st century using only two digits. See Also: Additional discussion on RR datetime format element in the Oracle Database SQL Language Reference RRRR Yes Round year. Accepts either 4-digit or 2-digit input. If 2-digit, provides the same return as RR. If you do not want this functionality, then enter the 4-digit year. SS Yes Second (0-59). SSSSS Yes Seconds past midnight (0-86399). TS Yes Returns a value in the short time format. Makes the appearance of the time components (hour, minutes, and so forth) depend on the NLS_TERRITORY and NLS_LANGUAGE initialization parameters. Restriction: You can specify this format only with the DL or DS element, separated by white space. TZD Yes Daylight saving information. The TZD value is an abbreviated time zone string with daylight saving information. It must correspond with the region specified in TZR. Valid in timestamp and interval formats, but not in DATE formats. Example: PST (for US/Pacific standard time); PDT (for US/Pacific daylight time). TZH Yes Time zone hour. (See TZM format element.) Valid in timestamp and interval formats, but not in DATE formats. Example: 'HH:MI:SS.FFTZH:TZM'. TZM Yes Time zone minute. (See TZH format element.) Valid in timestamp and interval formats, but not in DATE formats. Example: 'HH:MI:SS.FFTZH:TZM'. TZR Yes Time zone region information. The value must be one of the time zone region names supported in the database. Valid in timestamp and interval formats, but not in DATE formats. Example: US/Pacific Table 3–15 (Cont.) Datetime Format Elements Element TO_* datetime functions? Description
  • 109. Format Models Basic Elements of Oracle SQL 3-63 Oracle Database converts strings to dates with some flexibility. For example, when the TO_DATE function is used, a format model containing punctuation characters matches an input string lacking some or all of these characters, provided each numerical element in the input string contains the maximum allowed number of digits—for example, two digits '05' for 'MM' or four digits '2007' for 'YYYY'. The following statement does not return an error: SELECT TO_CHAR (TO_DATE('0207','MM/YY'), 'MM/YY') FROM DUAL; TO_CH ----- 02/07 However, the following format string does return an error, because the FX (format exact) format modifier requires an exact match of the expression and the format string: SELECT TO_CHAR(TO_DATE('0207', 'fxmm/yy'), 'mm/yy') FROM DUAL; SELECT TO_CHAR(TO_DATE('0207', 'fxmm/yy'), 'mm/yy') FROM DUAL * ERROR at line 1: ORA-01861: literal does not match format string Any non-alphanumeric character is allowed to match the punctuation characters in the format model. For example, the following statement does not return an error: SELECT TO_CHAR (TO_DATE('02#07','MM/YY'), 'MM/YY') FROM DUAL; TO_CH ----- 02/07 WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year. W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. X Yes Local radix character. Example: 'HH:MI:SSXFF'. Y,YYY Yes Year with comma in this position. YEAR SYEAR Year, spelled out; S prefixes BC dates with a minus sign (-). YYYY SYYYY Yes 4-digit year; S prefixes BC dates with a minus sign. YYY YY Y Yes Last 3, 2, or 1 digit(s) of year. See Also: "Format Model Modifiers" on page 3-66 and "String-to-Date Conversion Rules" on page 3-68 for more information Table 3–15 (Cont.) Datetime Format Elements Element TO_* datetime functions? Description
  • 110. Format Models 3-64 Oracle Database SQL Language Reference Datetime Format Elements and Globalization Support The functionality of some datetime format elements depends on the country and language in which you are using Oracle Database. For example, these datetime format elements return spelled values: ■ MONTH ■ MON ■ DAY ■ DY ■ BC or AD or B.C. or A.D. ■ AM or PM or A.M or P.M. The language in which these values are returned is specified either explicitly with the initialization parameter NLS_DATE_LANGUAGE or implicitly with the initialization parameter NLS_LANGUAGE. The values returned by the YEAR and SYEAR datetime format elements are always in English. The datetime format element D returns the number of the day of the week (1-7). The day of the week that is numbered 1 is specified implicitly by the initialization parameter NLS_TERRITORY. ISO Standard Date Format Elements Oracle calculates the values returned by the datetime format elements IYYY, IYY, IY, I, and IW according to the ISO standard. For information on the differences between these values and those returned by the datetime format elements YYYY, YYY, YY, Y, and WW, see the discussion of globalization support in Oracle Database Globalization Support Guide. The RR Datetime Format Element The RR datetime format element is similar to the YY datetime format element, but it provides additional flexibility for storing date values in other centuries. The RR datetime format element lets you store 20th century dates in the 21st century by specifying only the last two digits of the year. If you use the TO_DATE function with the YY datetime format element, then the year returned always has the same first 2 digits as the current year. If you use the RR datetime format element instead, then the century of the return value varies according to the specified two-digit year and the last two digits of the current year. That is: ■ If the specified two-digit year is 00 to 49, then – If the last two digits of the current year are 00 to 49, then the returned year has the same first two digits as the current year. – If the last two digits of the current year are 50 to 99, then the first 2 digits of the returned year are 1 greater than the first 2 digits of the current year. ■ If the specified two-digit year is 50 to 99, then – If the last two digits of the current year are 00 to 49, then the first 2 digits of the returned year are 1 less than the first 2 digits of the current year. See Also: Oracle Database Reference and Oracle Database Globalization Support Guide for information on globalization support initialization parameters
  • 111. Format Models Basic Elements of Oracle SQL 3-65 – If the last two digits of the current year are 50 to 99, then the returned year has the same first two digits as the current year. The following examples demonstrate the behavior of the RR datetime format element. RR Datetime Format Examples Assume these queries are issued between 1950 and 1999: SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---- 1998 SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---- 2017 Now assume these queries are issued between 2000 and 2049: SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---- 1998 SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---- 2017 Note that the queries return the same values regardless of whether they are issued before or after the year 2000. The RR datetime format element lets you write SQL statements that will return the same values from years whose first two digits are different. Datetime Format Element Suffixes Table 3–16 lists suffixes that can be added to datetime format elements: Notes on date format element suffixes: ■ When you add one of these suffixes to a datetime format element, the return value is always in English. Table 3–16 Date Format Element Suffixes Suffix Meaning Example Element Example Value TH Ordinal Number DDTH 4TH SP Spelled Number DDSP FOUR SPTH or THSP Spelled, ordinal number DDSPTH FOURTH
  • 112. Format Models 3-66 Oracle Database SQL Language Reference ■ Datetime suffixes are valid only to format output. You cannot use them to insert a date into the database. Format Model Modifiers The FM and FX modifiers, used in format models in the TO_CHAR function, control blank padding and exact format checking. A modifier can appear in a format model more than once. In such a case, each subsequent occurrence toggles the effects of the modifier. Its effects are enabled for the portion of the model following its first occurrence, and then disabled for the portion following its second, and then reenabled for the portion following its third, and so on. FM Fill mode. Oracle uses trailing blank characters and leading zeroes to fill format elements to a constant width. The width is equal to the display width of the largest element for the relevant format model: ■ Numeric elements are padded with leading zeros to the width of the maximum value allowed for the element. For example, the YYYY element is padded to four digits (the length of '9999'), HH24 to two digits (the length of '23'), and DDD to three digits (the length of '366'). ■ The character elements MONTH, MON, DAY, and DY are padded with trailing blanks to the width of the longest full month name, the longest abbreviated month name, the longest full date name, or the longest abbreviated day name, respectively, among valid names determined by the values of NLS_DATE_LANGUAGE and NLS_ CALENDAR parameters. For example, when NLS_DATE_LANGUAGE is AMERICAN and NLS_CALENDAR is GREGORIAN (the default), the largest element for MONTH is SEPTEMBER, so all values of the MONTH format element are padded to nine display characters. The values of the NLS_DATE_LANGUAGE and NLS_CALENDAR parameters are specified in the third argument to TO_CHAR and TO_* datetime functions or they are retrieved from the NLS environment of the current session. ■ The character element RM is padded with trailing blanks to the length of 4, which is the length of 'viii'. ■ Other character elements and spelled-out numbers (SP, SPTH, and THSP suffixes) are not padded. The FM modifier suppresses the above padding in the return value of the TO_CHAR function. FX Format exact. This modifier specifies exact matching for the character argument and datetime format model of a TO_DATE function: ■ Punctuation and quoted text in the character argument must exactly match (except for case) the corresponding parts of the format model. ■ The character argument cannot have extra blanks. Without FX, Oracle ignores extra blanks. ■ Numeric data in the character argument must have the same number of digits as the corresponding element in the format model. Without FX, numbers in the character argument can omit leading zeros. When FX is enabled, you can disable this check for leading zeros by using the FM modifier as well. If any portion of the character argument violates any of these conditions, then Oracle returns an error message.
  • 113. Format Models Basic Elements of Oracle SQL 3-67 Format Model Examples The following statement uses a date format model to return a character expression: SELECT TO_CHAR(SYSDATE, 'fmDDTH')||' of '||TO_CHAR (SYSDATE, 'fmMonth')||', '||TO_CHAR(SYSDATE, 'YYYY') "Ides" FROM DUAL; Ides ------------------ 3RD of April, 1998 The preceding statement also uses the FM modifier. If FM is omitted, then the month is blank-padded to nine characters: SELECT TO_CHAR(SYSDATE, 'DDTH')||' of '|| TO_CHAR(SYSDATE, 'Month')||', '|| TO_CHAR(SYSDATE, 'YYYY') "Ides" FROM DUAL; Ides ----------------------- 03RD of April , 1998 The following statement places a single quotation mark in the return value by using a date format model that includes two consecutive single quotation marks: SELECT TO_CHAR(SYSDATE, 'fmDay')||'''s Special' "Menu" FROM DUAL; Menu ----------------- Tuesday's Special Two consecutive single quotation marks can be used for the same purpose within a character literal in a format model. Table 3–17 shows whether the following statement meets the matching conditions for different values of char and 'fmt' using FX (the table named table has a column date_column of data type DATE): UPDATE table SET date_column = TO_DATE(char, 'fmt'); Format of Return Values: Examples You can use a format model to specify the format for Oracle to use to return values from the database to you. Table 3–17 Matching Character Data and Format Models with the FX Format Model Modifier char 'fmt' Match or Error? '15/ JAN /1998' 'DD-MON-YYYY' Match ' 15! JAN % /1998' 'DD-MON-YYYY' Error '15/JAN/1998' 'FXDD-MON-YYYY' Error '15-JAN-1998' 'FXDD-MON-YYYY' Match '1-JAN-1998' 'FXDD-MON-YYYY' Error '01-JAN-1998' 'FXDD-MON-YYYY' Match '1-JAN-1998' 'FXFMDD-MON-YYYY' Match
  • 114. Format Models 3-68 Oracle Database SQL Language Reference The following statement selects the salaries of the employees in Department 80 and uses the TO_CHAR function to convert these salaries into character values with the format specified by the number format model '$99,990.99': SELECT last_name employee, TO_CHAR(salary, '$99,990.99') FROM employees WHERE department_id = 80; Because of this format model, Oracle returns salaries with leading dollar signs, commas every three digits, and two decimal places. The following statement selects the date on which each employee from Department 20 was hired and uses the TO_CHAR function to convert these dates to character strings with the format specified by the date format model 'fmMonth DD, YYYY': SELECT last_name employee, TO_CHAR(hire_date,'fmMonth DD, YYYY') hiredate FROM employees WHERE department_id = 20; With this format model, Oracle returns the hire dates without blank padding (as specified by fm), two digits for the day, and the century included in the year. Supplying the Correct Format Model: Examples When you insert or update a column value, the data type of the value that you specify must correspond to the column data type of the column. You can use format models to specify the format of a value that you are converting from one data type to another data type required for a column. For example, a value that you insert into a DATE column must be a value of the DATE data type or a character string in the default date format (Oracle implicitly converts character strings in the default date format to the DATE data type). If the value is in another format, then you must use the TO_DATE function to convert the value to the DATE data type. You must also use a format model to specify the format of the character string. The following statement updates Hunold's hire date using the TO_DATE function with the format mask 'YYYY MM DD' to convert the character string '2008 05 20' to a DATE value: UPDATE employees SET hire_date = TO_DATE('2008 05 20','YYYY MM DD') WHERE last_name = 'Hunold'; String-to-Date Conversion Rules The following additional formatting rules apply when converting string values to date values (unless you have used the FX or FXFM modifiers in the format model to control exact format checking): ■ You can omit punctuation included in the format string from the date string if all the digits of the numerical format elements, including leading zeros, are specified. For example, specify 02 and not 2 for two-digit format elements such as MM, DD, and YY. ■ You can omit time fields found at the end of a format string from the date string. See Also: "Format Model Modifiers" on page 3-66 for a description of the fm format element
  • 115. Format Models Basic Elements of Oracle SQL 3-69 ■ You can use any non-alphanumeric character in the date string to match the punctuation symbol in the format string. ■ If a match fails between a datetime format element and the corresponding characters in the date string, then Oracle attempts alternative format elements, as shown in Table 3–18. XML Format Model The SYS_XMLGEN function returns an instance of type XMLType containing an XML document. Oracle provides the XMLFormat object, which lets you format the output of the SYS_XMLGEN function. Table 3–19 lists and describes the attributes of the XMLFormat object. The function that implements this type follows the table. Table 3–18 Oracle Format Matching Original Format Element Additional Format Elements to Try in Place of the Original 'MM' 'MON' and 'MONTH' 'MON 'MONTH' 'MONTH' 'MON' 'YY' 'YYYY' 'RR' 'RRRR' See Also: ■ SYS_XMLGEN on page 5-211 for information on the SYS_XMLGEN function ■ Oracle XML Developer's Kit Programmer's Guide for more information on the implementation of the XMLFormat object and its use Table 3–19 Attributes of the XMLFormat Object Attribute Data Type Purpose enclTag VARCHAR2(4000) The name of the enclosing tag for the result of the SYS_XMLGEN function. If the input to the function is a column name, then the default is the column name. Otherwise the default is ROW. When schemaType is set to USE_GIVEN_SCHEMA, this attribute also gives the name of the XMLSchema element. schemaType VARCHAR2(100) The type of schema generation for the output document. Valid values are 'NO_SCHEMA' and 'USE_GIVEN_SCHEMA'. The default is 'NO_ SCHEMA'. schemaName VARCHAR2(4000) The name of the target schema Oracle uses if the value of the schemaType is 'USE_GIVEN_SCHEMA'. If you specify schemaName, then Oracle uses the enclosing tag as the element name. targetNameSpace VARCHAR2(4000) The target namespace if the schema is specified (that is, schemaType is GEN_SCHEMA_*, or USE_GIVEN_SCHEMA) dburlPrefix VARCHAR2(4000) The URL to the database to use if WITH_SCHEMA is specified. If this attribute is not specified, then Oracle declares the URL to the types as a relative URL reference. processingIns VARCHAR2(4000) User-provided processing instructions, which are appended to the top of the function output before the element.
  • 116. Nulls 3-70 Oracle Database SQL Language Reference The function that implements the XMLFormat object follows: STATIC FUNCTION createFormat( enclTag IN varchar2 := 'ROWSET', schemaType IN varchar2 := 'NO_SCHEMA', schemaName IN varchar2 := null, targetNameSpace IN varchar2 := null, dburlPrefix IN varchar2 := null, processingIns IN varchar2 := null) RETURN XMLGenFormatType deterministic parallel_enable, MEMBER PROCEDURE genSchema (spec IN varchar2), MEMBER PROCEDURE setSchemaName(schemaName IN varchar2), MEMBER PROCEDURE setTargetNameSpace(targetNameSpace IN varchar2), MEMBER PROCEDURE setEnclosingElementName(enclTag IN varchar2), MEMBER PROCEDURE setDbUrlPrefix(prefix IN varchar2), MEMBER PROCEDURE setProcessingIns(pi IN varchar2), CONSTRUCTOR FUNCTION XMLGenFormatType ( enclTag IN varchar2 := 'ROWSET', schemaType IN varchar2 := 'NO_SCHEMA', schemaName IN varchar2 := null, targetNameSpace IN varchar2 := null, dbUrlPrefix IN varchar2 := null, processingIns IN varchar2 := null) RETURN SELF AS RESULT deterministic parallel_enable, STATIC function createFormat2( enclTag in varchar2 := 'ROWSET', flags in raw) return sys.xmlgenformattype deterministic parallel_enable ); Nulls If a column in a row has no value, then the column is said to be null, or to contain null. Nulls can appear in columns of any data type that are not restricted by NOT NULL or PRIMARY KEY integrity constraints. Use a null when the actual value is not known or when a value would not be meaningful. Oracle Database treats a character value with a length of zero as null. However, do not use null to represent a numeric value of zero, because they are not equivalent. Any arithmetic expression containing a null always evaluates to null. For example, null added to 10 is null. In fact, all operators (except concatenation) return null when given a null operand. Nulls in SQL Functions For information on null handling in SQL functions, see "Nulls in SQL Functions" on page 5-2. Note: Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.
  • 117. Comments Basic Elements of Oracle SQL 3-71 Nulls with Comparison Conditions To test for nulls, use only the comparison conditions IS NULL and IS NOT NULL. If you use any other condition with nulls and the result depends on the value of the null, then the result is UNKNOWN. Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, Oracle considers two nulls to be equal when evaluating a DECODE function. Refer to DECODE on page 5-58 for syntax and additional information. Oracle also considers two nulls to be equal if they appear in compound keys. That is, Oracle considers identical two compound keys containing nulls if all the non-null components of the keys are equal. Nulls in Conditions A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN. Table 3–20 shows examples of various evaluations involving nulls in conditions. If the conditions evaluating to UNKNOWN were used in a WHERE clause of a SELECT statement, then no rows would be returned for that query. For the truth tables showing the results of logical conditions containing nulls, see Table 7–5 on page 7-8, Table 7–6 on page 7-8, and Table 7–7 on page 7-8. Comments You can create two types of comments: ■ Comments within SQL statements are stored as part of the application code that executes the SQL statements. ■ Comments associated with individual schema or nonschema objects are stored in the data dictionary along with metadata on the objects themselves. Table 3–20 Conditions Containing Nulls Condition Value of A Evaluation a IS NULL 10 FALSE a IS NOT NULL 10 TRUE a IS NULL NULL TRUE a IS NOT NULL NULL FALSE a = NULL 10 UNKNOWN a != NULL 10 UNKNOWN a = NULL NULL UNKNOWN a != NULL NULL UNKNOWN a = 10 NULL UNKNOWN a != 10 NULL UNKNOWN
  • 118. Comments 3-72 Oracle Database SQL Language Reference Comments Within SQL Statements Comments can make your application easier for you to read and maintain. For example, you can include a comment in a statement that describes the purpose of the statement within your application. With the exception of hints, comments within SQL statements do not affect the statement execution. Refer to "Hints" on page 3-73 on using this particular form of comment. A comment can appear between any keywords, parameters, or punctuation marks in a statement. You can include a comment in a statement in two ways: ■ Begin the comment with a slash and an asterisk (/*). Proceed with the text of the comment. This text can span multiple lines. End the comment with an asterisk and a slash (*/). The opening and terminating characters need not be separated from the text by a space or a line break. ■ Begin the comment with -- (two hyphens). Proceed with the text of the comment. This text cannot extend to a new line. End the comment with a line break. Some of the tools used to enter SQL have additional restrictions. For example, if you are using SQL*Plus, by default you cannot have a blank line inside a multiline comment. For more information, refer to the documentation for the tool you use as an interface to the database. A SQL statement can contain multiple comments of both styles. The text of a comment can contain any printable characters in your database character set. Example These statements contain many comments: SELECT last_name, salary + NVL(commission_pct, 0), job_id, e.department_id /* Select all employees whose compensation is greater than that of Pataballa.*/ FROM employees e, departments d /*The DEPARTMENTS table is used to get the department name.*/ WHERE e.department_id = d.department_id AND salary + NVL(commission_pct,0) > /* Subquery: */ (SELECT salary + NVL(commission_pct,0) /* total compensation is salar + commission_pct */ FROM employees WHERE last_name = 'Pataballa'); SELECT last_name, -- select the name salary + NVL(commission_pct, 0),-- total compensation job_id, -- job e.department_id -- and department FROM employees e, -- of all employees departments d WHERE e.department_id = d.department_id AND salary + NVL(commission_pct, 0) > -- whose compensation -- is greater than (SELECT salary + NVL(commission_pct,0) -- the compensation FROM employees WHERE last_name = 'Pataballa') -- of Pataballa. ; Comments on Schema and Nonschema Objects You can use the COMMENT command to associate a comment with a schema object (table, view, materialized view, operator, indextype, mining model) or a nonschema object (edition) using the COMMENT command. You can also create a comment on a
  • 119. Comments Basic Elements of Oracle SQL 3-73 column, which is part of a table schema object. Comments associated with schema and nonschema objects are stored in the data dictionary. Refer to COMMENT on page 13-44 for a description of this form of comment. Hints Hints are comments in a SQL statement that pass instructions to the Oracle Database optimizer. The optimizer uses these hints to choose an execution plan for the statement, unless some condition exists that prevents the optimizer from doing so. Hints were introduced in Oracle7, when users had little recourse if the optimizer generated suboptimal plans. Now Oracle provides a number of tools, including the SQL Tuning Advisor, SQL plan management, and SQL Performance Analyzer, to help you address performance problems that are not solved by the optimizer. Oracle strongly recommends that you use those tools rather than hints. The tools are far superior to hints, because when used on an ongoing basis, they provide fresh solutions as your data and database environment change. Hints should be used sparingly, and only after you have collected statistics on the relevant tables and evaluated the optimizer plan without hints using the EXPLAIN PLAN statement. Changing database conditions as well as query performance enhancements in subsequent releases can have significant impact on how hints in your code affect performance. The remainder of this section provides information on some commonly used hints. If you decide to use hints rather than the more advanced tuning tools, be aware that any short-term benefit resulting from the use of hints may not continue to result in improved performance over the long term. Using Hints A statement block can have only one comment containing hints, and that comment must follow the SELECT, UPDATE, INSERT, MERGE, or DELETE keyword. The following syntax diagram shows hints contained in both styles of comments that Oracle supports within a statement block. The hint syntax must follow immediately after an INSERT, UPDATE, DELETE, SELECT, or MERGE keyword that begins the statement block. hint::= where: ■ The plus sign (+) causes Oracle to interpret the comment as a list of hints. The plus sign must follow immediately after the comment delimiter. No space is permitted. ■ hint is one of the hints discussed in this section. The space between the plus sign and the hint is optional. If the comment contains multiple hints, then separate the hints by at least one space. ■ string is other commenting text that can be interspersed with the hints. The --+ syntax requires that the entire comment be on a single line. /*+ hint string */ – – + hint string
  • 120. Comments 3-74 Oracle Database SQL Language Reference Oracle Database ignores hints and does not return an error under the following circumstances: ■ The hint contains misspellings or syntax errors. However, the database does consider other correctly specified hints in the same comment. ■ The comment containing the hint does not follow a DELETE, INSERT, MERGE, SELECT, or UPDATE keyword. ■ A combination of hints conflict with each other. However, the database does consider other hints in the same comment. ■ The database environment uses PL/SQL version 1, such as Forms version 3 triggers, Oracle Forms 4.5, and Oracle Reports 2.5. Many hints can apply both to specific tables or indexes and more globally to tables within a view or to columns that are part of indexes. The syntactic elements tablespec and indexspec define these global hints. tablespec::= You must specify the table to be accessed exactly as it appears in the statement. If the statement uses an alias for the table, then use the alias rather than the table name in the hint. However, do not include the schema name with the table name within the hint, even if the schema name appears in the statement. indexspec::= When tablespec is followed by indexspec in the specification of a hint, a comma separating the table name and index name is permitted but not required. Commas are also permitted, but not required, to separate multiple occurrences of indexspec. See Also: Oracle Database Performance Tuning Guide for information on the following topics: ■ When to use global hints and how Oracle interprets them ■ Using EXPLAIN PLAN to learn how the optimizer is executing a query ■ References in hints to tables within views view . table index ( table . column )
  • 121. Comments Basic Elements of Oracle SQL 3-75 Specifying a Query Block in a Hint You can specify an optional query block name in many hints to specify the query block to which the hint applies. This syntax lets you specify in the outer query a hint that applies to an inline view. The syntax of the query block argument is of the form @queryblock, where queryblock is an identifier that specifies a query block in the query. The queryblock identifier can either be system-generated or user-specified. When you specify a hint in the query block itself to which the hint applies, you omit the @queryblock syntax. ■ The system-generated identifier can be obtained by using EXPLAIN PLAN for the query. Pretransformation query block names can be determined by running EXPLAIN PLAN for the query using the NO_QUERY_TRANSFORMATION hint. See "NO_QUERY_TRANSFORMATION Hint" on page 3-93. ■ The user-specified name can be set with the QB_NAME hint. See "QB_NAME Hint" on page 3-101. Table 3–21 lists the hints by functional category and contains cross-references to the syntax and semantics for each hint. An alphabetical reference of the hints follows the table. Note: Oracle Database ignores global hints that refer to multiple query blocks. For example, the LEADING hint is ignored in the following query because it refers to the main query block containing table a and view query block v: SELECT /*+ LEADING(v.b a v.c) */ * FROM a,v WHERE a.id = v.id; To avoid this issue, Oracle recommends that you specify a query block in the hint: SELECT /*+ LEADING(A@SEL$1 B@SEL$2 C@SEL$2) */ FROM a a, v v WHERE a.id = v.id; Refer to Oracle Database Performance Tuning Guide for more information on specifying hints. See Also: Oracle Database Performance Tuning Guide for information on: ■ Using hints to optimize SQL statements and on detailed information about using the tablespec and indexspec syntax ■ Specifying a query block in a hint ■ Descriptions of hint categories and when to use them Table 3–21 Hints by Functional Category Hint Link to Syntax and Semantics Optimization Goals and Approaches ALL_ROWS Hint on page 3-77 FIRST_ROWS Hint on page 3-81
  • 122. Comments 3-76 Oracle Database SQL Language Reference Access Path Hints CLUSTER Hint on page 3-80 -- FULL Hint on page 3-82 -- HASH Hint on page 3-82 -- INDEX Hint on page 3-83 NO_INDEX Hint on page 3-90 -- INDEX_ASC Hint on page 3-84 INDEX_DESC Hint on page 3-85 -- INDEX_COMBINE Hint on page 3-84 -- INDEX_JOIN Hint on page 3-85 -- INDEX_FFS Hint on page 3-85 -- INDEX_SS Hint on page 3-86 -- INDEX_SS_ASC Hint on page 3-86 -- INDEX_SS_DESC Hint on page 3-87 -- NATIVE_FULL_OUTER_JOIN Hint on page 3-88 NO_NATIVE_FULL_OUTER_JOIN Hint on page 3-91 -- NO_INDEX_FFS Hint on page 3-90 -- NO_INDEX_SS Hint on page 3-90 Join Order Hints ORDERED Hint on page 3-96 -- LEADING Hint on page 3-87 Join Operation Hints USE_HASH Hint on page 3-104 NO_USE_HASH Hint on page 3-94 -- USE_MERGE Hint on page 3-105 NO_USE_MERGE Hint on page 3-94 -- USE_NL Hint on page 3-105 USE_NL_WITH_INDEX Hint on page 3-106 NO_USE_NL Hint on page 3-95 Parallel Execution Hints PARALLEL Hint on page 3-96 NO_PARALLEL Hint on page 3-91 -- PARALLEL_INDEX Hint on page 3-98 NO_PARALLEL_INDEX Hint on page 3-92 -- PQ_DISTRIBUTE Hint on page 3-98 Online Application Upgrade Hints CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79 IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83 RETRY_ON_ROW_CHANGE Hint on page 3-102 Query Transformation Hints FACT Hint on page 3-81 NO_FACT Hint on page 3-89 -- MERGE Hint on page 3-87 NO_MERGE Hint on page 3-91 Table 3–21 (Cont.) Hints by Functional Category Hint Link to Syntax and Semantics
  • 123. Comments Basic Elements of Oracle SQL 3-77 Alphabetical Listing of Hints This section provides syntax and semantics for all hints in alphabetical order. ALL_ROWS Hint -- NO_EXPAND Hint on page 3-89 USE_CONCAT Hint on page 3-104 -- REWRITE Hint on page 3-103 NO_REWRITE Hint on page 3-93 -- UNNEST Hint on page 3-104 NO_UNNEST Hint on page 3-94 -- STAR_TRANSFORMATION Hint on page 3-103 NO_STAR_TRANSFORMATION Hint on page 3-94 -- NO_QUERY_TRANSFORMATION Hint on page 3-93 XML Hints NO_XMLINDEX_REWRITE Hint on page 3-95 -- NO_XML_QUERY_REWRITE Hint on page 3-95 Other Hints APPEND Hint on page 3-78 APPEND_VALUES Hint on page 3-78 NOAPPEND Hint on page 3-89 -- CACHE Hint on page 3-79 NOCACHE Hint on page 3-89 -- CURSOR_SHARING_EXACT Hint on page 3-80 -- DRIVING_SITE Hint on page 3-80 -- DYNAMIC_SAMPLING Hint on page 3-81 -- MODEL_MIN_ANALYSIS Hint on page 3-88 -- MONITOR Hint on page 3-88 -- NO_MONITOR Hint on page 3-91 -- OPT_PARAM Hint on page 3-95 -- PUSH_PRED Hint on page 3-101 NO_PUSH_PRED Hint on page 3-92 -- PUSH_SUBQ Hint on page 3-101 NO_PUSH_SUBQ Hint on page 3-93 -- PX_JOIN_FILTER Hint on page 3-101 NO_PX_JOIN_FILTER Hint on page 3-93 -- QB_NAME Hint on page 3-101 -- RESULT_CACHE Hint on page 3-102 NO_RESULT_CACHE Hint on page 3-93 Table 3–21 (Cont.) Hints by Functional Category Hint Link to Syntax and Semantics /*+ ALL_ROWS */
  • 124. Comments 3-78 Oracle Database SQL Language Reference The ALL_ROWS hint instructs the optimizer to optimize a statement block with a goal of best throughput, which is minimum total resource consumption. For example, the optimizer uses the query optimization approach to optimize this statement for best throughput: SELECT /*+ ALL_ROWS */ employee_id, last_name, salary, job_id FROM employees WHERE employee_id = 7566; If you specify either the ALL_ROWS or the FIRST_ROWS hint in a SQL statement, and if the data dictionary does not have statistics about tables accessed by the statement, then the optimizer uses default statistical values, such as allocated storage for such tables, to estimate the missing statistics and to subsequently choose an execution plan. These estimates might not be as accurate as those gathered by the DBMS_STATS package, so you should use the DBMS_STATS package to gather statistics. If you specify hints for access paths or join operations along with either the ALL_ROWS or FIRST_ROWS hint, then the optimizer gives precedence to the access paths and join operations specified by the hints. APPEND Hint The APPEND hint instructs the optimizer to use direct-path INSERT with the subquery syntax of the INSERT statement. ■ Conventional INSERT is the default in serial mode. In serial mode, direct path can be used only if you include the APPEND hint. ■ Direct-path INSERT is the default in parallel mode. In parallel mode, conventional insert can be used only if you specify the NOAPPEND hint. The decision whether the INSERT will go parallel or not is independent of the APPEND hint. In direct-path INSERT, data is appended to the end of the table, rather than using existing space currently allocated to the table. As a result, direct-path INSERT can be considerably faster than conventional INSERT. The APPEND hint is only supported with the subquery syntax of the INSERT statement, not the VALUES clause. If you specify the APPEND hint with the VALUES clause, it is ignored and conventional insert will be used. To use direct-path INSERT with the VALUES clause, refer to "APPEND_VALUES Hint" on page 3-78. APPEND_VALUES Hint The APPEND_VALUES hint instructs the optimizer to use direct-path INSERT with the VALUES clause. If you do not specify this hint, then conventional INSERT is used. In direct-path INSERT, data is appended to the end of the table, rather than using existing space currently allocated to the table. As a result, direct-path INSERT can be considerably faster than conventional INSERT. See Also: "NOAPPEND Hint" on page 3-89 for information on that hint and Oracle Database Administrator's Guide for information on direct-path inserts /*+ APPEND */ /*+ APPEND_VALUES */
  • 125. Comments Basic Elements of Oracle SQL 3-79 The APPEND_VALUES hint can be used to greatly enhance performance. Some examples of its uses are: ■ In an Oracle Call Interface (OCI) program, when using large array binds or array binds with row callbacks ■ In PL/SQL, when loading a large number of rows with a FORALL loop that has an INSERT statement with a VALUES clause The APPEND_VALUES hint is only supported with the VALUES clause of the INSERT statement. If you specify the APPEND_VALUES hint with the subquery syntax of the INSERT statement, it is ignored and conventional insert will be used. To use direct-path INSERT with a subquery, refer to "APPEND Hint" on page 3-78. CACHE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The CACHE hint instructs the optimizer to place the blocks retrieved for the table at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This hint is useful for small lookup tables. In the following example, the CACHE hint overrides the default caching specification of the table: SELECT /*+ FULL (hr_emp) CACHE(hr_emp) */ last_name FROM employees hr_emp; The CACHE and NOCACHE hints affect system statistics table scans (long tables) and table scans (short tables), as shown in the V$SYSSTAT data dictionary view. CHANGE_DUPKEY_ERROR_INDEX Hint The CHANGE_DUPKEY_ERROR_INDEX hint provides a mechanism to unambiguously identify a unique key violation for a specified set of columns or for a specified index. When a unique key violation occurs for the specified index, an ORA-38911 error is reported instead of an ORA-001. This hint applies to INSERT, UPDATE operations. If you specify an index, then the index must exist and be unique. If you specify a column list instead of an index, then a See Also: Oracle Database Administrator's Guide for information on direct-path inserts Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_ DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other hints in that they have a semantic effect. The general philosophy explained in "Hints" on page 3-73 does not apply for these three hints. /*+ CACHE ( @ queryblock tablespec ) */ /*+ CHANGE_DUPKEY_ERROR_INDEX ( table , index table ( column , ) ) */
  • 126. Comments 3-80 Oracle Database SQL Language Reference unique index whose columns match the specified columns in number and order must exist. This use of this hint results in error messages if specific rules are violated. Refer to IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83 for details. CLUSTER Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The CLUSTER hint instructs the optimizer to use a cluster scan to access the specified table. This hint applies only to tables in an index cluster. CURSOR_SHARING_EXACT Hint Oracle can replace literals in SQL statements with bind variables, when it is safe to do so. This replacement is controlled with the CURSOR_SHARING initialization parameter. The CURSOR_SHARING_EXACT hint instructs the optimizer to switch this behavior off. When you specify this hint, Oracle executes the SQL statement without any attempt to replace literals with bind variables. DRIVING_SITE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The DRIVING_SITE hint instructs the optimizer to execute the query at a different site than that selected by the database. This hint is useful if you are using distributed query optimization. For example: SELECT /*+ DRIVING_SITE(departments) */ * FROM employees, departments@rsite WHERE employees.department_id = departments.department_id; If this query is executed without the hint, then rows from departments are sent to the local site, and the join is executed there. With the hint, the rows from employees are sent to the remote site, and the query is executed there and the result set is returned to the local site. Note: This hint disables both APPEND mode and parallel DML. See Also: IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83 for information on that hint and Oracle Database Performance Tuning Guide for more information on using the online application upgrade related hints /*+ CLUSTER ( @ queryblock tablespec ) */ /*+ CURSOR_SHARING_EXACT */ /*+ DRIVING_SITE ( @ queryblock tablespec ) */
  • 127. Comments Basic Elements of Oracle SQL 3-81 DYNAMIC_SAMPLING Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The DYNAMIC_SAMPLING hint instructs the optimizer how to control dynamic sampling to improve server performance by determining more accurate predicate selectivity and statistics for tables and indexes. You can set the value of DYNAMIC_SAMPLING to a value from 0 to 10. The higher the level, the more effort the compiler puts into dynamic sampling and the more broadly it is applied. Sampling defaults to cursor level unless you specify tablespec. The integer value is 0 to 10, indicating the degree of sampling. If a cardinality statistic already exists for the table, then the optimizer uses it. Otherwise, the optimizer enables dynamic sampling to estimate the cardinality statistic. If you specify tablespec and the cardinality statistic already exists, then: ■ If there is no single-table predicate (a WHERE clause that evaluates only one table), then the optimizer trusts the existing statistics and ignores this hint. For example, the following query will not result in any dynamic sampling if employees is analyzed: SELECT /*+ dynamic_sampling(e 1) */ count(*) FROM employees e; ■ If there is a single-table predicate, then the optimizer uses the existing cardinality statistic and estimates the selectivity of the predicate using the existing statistics. To apply dynamic sampling to a specific table, use the following form of the hint: SELECT /*+ dynamic_sampling(employees 1) */ * FROM employees WHERE ... FACT Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The FACT hint is used in the context of the star transformation. It instructs the optimizer that the table specified in tablespec should be considered as a fact table. FIRST_ROWS Hint See Also: Oracle Database Performance Tuning Guide for information about dynamic sampling and the sampling levels that you can set /*+ DYNAMIC_SAMPLING ( @ queryblock tablespec integer ) */ /*+ FACT ( @ queryblock tablespec ) */ /*+ FIRST_ROWS ( integer ) */
  • 128. Comments 3-82 Oracle Database SQL Language Reference The FIRST_ROWS hint instructs Oracle to optimize an individual SQL statement for fast response, choosing the plan that returns the first n rows most efficiently. For integer, specify the number of rows to return. For example, the optimizer uses the query optimization approach to optimize the following statement for best response time: SELECT /*+ FIRST_ROWS(10) */ employee_id, last_name, salary, job_id FROM employees WHERE department_id = 20; In this example each department contains many employees. The user wants the first 10 employees of department 20 to be displayed as quickly as possible. The optimizer ignores this hint in DELETE and UPDATE statement blocks and in SELECT statement blocks that include any blocking operations, such as sorts or groupings. Such statements cannot be optimized for best response time, because Oracle Database must retrieve all rows accessed by the statement before returning the first row. If you specify this hint in any such statement, then the database optimizes for best throughput. FULL Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The FULL hint instructs the optimizer to perform a full table scan for the specified table. For example: SELECT /*+ FULL(e) */ employee_id, last_name FROM hr.employees e WHERE last_name LIKE :b1; Oracle Database performs a full table scan on the employees table to execute this statement, even if there is an index on the last_name column that is made available by the condition in the WHERE clause. The employees table has alias e in the FROM clause, so the hint must refer to the table by its alias rather than by its name. Do not specify schema names in the hint even if they are specified in the FROM clause. HASH Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The HASH hint instructs the optimizer to use a hash scan to access the specified table. This hint applies only to tables in a hash cluster. See Also: "ALL_ROWS Hint" on page 3-77 for additional information on the FIRST_ROWS hint and statistics /*+ FULL ( @ queryblock tablespec ) */ /*+ HASH ( @ queryblock tablespec ) */
  • 129. Comments Basic Elements of Oracle SQL 3-83 IGNORE_ROW_ON_DUPKEY_INDEX Hint The IGNORE_ROW_ON_DUPKEY_INDEX hint applies only to single-table INSERT operations. It is not supported for UPDATE, DELETE, MERGE, or multitable insert operations. IGNORE_ROW_ON_DUPKEY_INDEX causes the statement to ignore a unique key violation for a specified set of columns or for a specified index. When a unique key violation is encountered, a row-level rollback occurs and execution resumes with the next input row. If you specify this hint when inserting data with DML error logging enabled, then the unique key violation is not logged and does not cause statement termination. The semantic effect of this hint results in error messages if specific rules are violated: ■ If you specify index, then the index must exist and be unique. Otherwise, the statement causes ORA-38913. ■ You must specify exactly one index. If you specify no index, then the statement causes ORA-38912. If you specify more than one index, then the statement causes ORA-38915. ■ You can specify either a CHANGE_DUPKEY_ERROR_INDEX or IGNORE_ROW_ON_ DUPKEY_INDEX hint in an INSERT statement, but not both. If you specify both, then the statement causes ORA-38915. As with all hints, a syntax error in the hint causes it to be silently ignored. The result will be that ORA-00001 will be caused, just as if no hint were used. INDEX Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_ DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other hints in that they have a semantic effect. The general philosophy explained in "Hints" on page 3-73 does not apply for these three hints. Note: This hint disables both APPEND mode and parallel DML. See Also: CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79 for information on that hint and Oracle Database Performance Tuning Guide for more information on using the online application upgrade related hints /*+ IGNORE_ROW_ON_DUPKEY_INDEX ( table , index table ( column , ) ) */ /*+ INDEX ( @ queryblock tablespec indexspec ) */
  • 130. Comments 3-84 Oracle Database SQL Language Reference The INDEX hint instructs the optimizer to use an index scan for the specified table. You can use the INDEX hint for function-based, domain, B-tree, bitmap, and bitmap join indexes. The behavior of the hint depends on the indexspec specification: ■ If the INDEX hint specifies a single available index, then the database performs a scan on this index. The optimizer does not consider a full table scan or a scan of another index on the table. ■ For a hint on a combination of multiple indexes, Oracle recommends using INDEX_COMBINE rather than INDEX, because it is a more versatile hint. If the INDEX hint specifies a list of available indexes, then the optimizer considers the cost of a scan on each index in the list and then performs the index scan with the lowest cost. The database can also choose to scan multiple indexes from this list and merge the results, if such an access path has the lowest cost. The database does not consider a full table scan or a scan on an index not listed in the hint. ■ If the INDEX hint specifies no indexes, then the optimizer considers the cost of a scan on each available index on the table and then performs the index scan with the lowest cost. The database can also choose to scan multiple indexes and merge the results, if such an access path has the lowest cost. The optimizer does not consider a full table scan. For example: SELECT /*+ INDEX (employees emp_department_ix)*/ employee_id, department_id FROM employees WHERE department_id > 50; INDEX_ASC Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_ASC hint instructs the optimizer to use an index scan for the specified table. If the statement uses an index range scan, then Oracle Database scans the index entries in ascending order of their indexed values. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. The default behavior for a range scan is to scan index entries in ascending order of their indexed values, or in descending order for a descending index. This hint does not change the default order of the index, and therefore does not specify anything more than the INDEX hint. However, you can use the INDEX_ASC hint to specify ascending range scans explicitly should the default behavior change. INDEX_COMBINE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) /*+ INDEX_ASC ( @ queryblock tablespec indexspec ) */ /*+ INDEX_COMBINE ( @ queryblock tablespec indexspec ) */
  • 131. Comments Basic Elements of Oracle SQL 3-85 The INDEX_COMBINE hint instructs the optimizer to use a bitmap access path for the table. If indexspec is omitted from the INDEX_COMBINE hint, then the optimizer uses whatever Boolean combination of indexes has the best cost estimate for the table. If you specify indexspec, then the optimizer tries to use some Boolean combination of the specified indexes. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For example: SELECT /*+ INDEX_COMBINE(e emp_manager_ix emp_department_ix) */ * FROM employees e WHERE manager_id = 108 OR department_id = 110; INDEX_DESC Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_DESC hint instructs the optimizer to use a descending index scan for the specified table. If the statement uses an index range scan and the index is ascending, then Oracle scans the index entries in descending order of their indexed values. In a partitioned index, the results are in descending order within each partition. For a descending index, this hint effectively cancels out the descending order, resulting in a scan of the index entries in ascending order. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For example: SELECT /*+ INDEX_DESC(e emp_name_ix) */ * FROM employees e; INDEX_FFS Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_FFS hint instructs the optimizer to perform a fast full index scan rather than a full table scan. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For example: SELECT /*+ INDEX_FFS(e emp_name_ix) */ first_name FROM employees e; INDEX_JOIN Hint See Also: Oracle Database Performance Tuning Guide for information on full scans /*+ INDEX_DESC ( @ queryblock tablespec indexspec ) */ /*+ INDEX_FFS ( @ queryblock tablespec indexspec ) */ /*+ INDEX_JOIN ( @ queryblock tablespec indexspec ) */
  • 132. Comments 3-86 Oracle Database SQL Language Reference (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_JOIN hint instructs the optimizer to use an index join as an access path. For the hint to have a positive effect, a sufficiently small number of indexes must exist that contain all the columns required to resolve the query. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For example, the following query uses an index join to access the manager_id and department_id columns, both of which are indexed in the employees table. SELECT /*+ INDEX_JOIN(e emp_manager_ix emp_department_ix) */ department_id FROM employees e WHERE manager_id < 110 AND department_id < 50; INDEX_SS Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_SS hint instructs the optimizer to perform an index skip scan for the specified table. If the statement uses an index range scan, then Oracle scans the index entries in ascending order of their indexed values. In a partitioned index, the results are in ascending order within each partition. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. For example: SELECT /*+ INDEX_SS(e emp_name_ix) */ last_name FROM employees e WHERE first_name = 'Steven'; INDEX_SS_ASC Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_SS_ASC hint instructs the optimizer to perform an index skip scan for the specified table. If the statement uses an index range scan, then Oracle Database scans the index entries in ascending order of their indexed values. In a partitioned index, the results are in ascending order within each partition. Each parameter serves the same purpose as in "INDEX Hint" on page 3-83. The default behavior for a range scan is to scan index entries in ascending order of their indexed values, or in descending order for a descending index. This hint does not change the default order of the index, and therefore does not specify anything more than the INDEX_SS hint. However, you can use the INDEX_SS_ASC hint to specify ascending range scans explicitly should the default behavior change. See Also: Oracle Database Performance Tuning Guide for information on index skip scans /*+ INDEX_SS ( @ queryblock tablespec indexspec ) */ /*+ INDEX_SS_ASC ( @ queryblock tablespec indexspec ) */
  • 133. Comments Basic Elements of Oracle SQL 3-87 INDEX_SS_DESC Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The INDEX_SS_DESC hint instructs the optimizer to perform an index skip scan for the specified table. If the statement uses an index range scan and the index is ascending, then Oracle scans the index entries in descending order of their indexed values. In a partitioned index, the results are in descending order within each partition. For a descending index, this hint effectively cancels out the descending order, resulting in a scan of the index entries in ascending order. Each parameter serves the same purpose as in the "INDEX Hint" on page 3-83. For example: SELECT /*+ INDEX_SS_DESC(e emp_name_ix) */ last_name FROM employees e WHERE first_name = 'Steven'; LEADING Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The LEADING hint instructs the optimizer to use the specified set of tables as the prefix in the execution plan. This hint is more versatile than the ORDERED hint. For example: SELECT /*+ LEADING(e j) */ * FROM employees e, departments d, job_history j WHERE e.department_id = d.department_id AND e.hire_date = j.start_date; The LEADING hint is ignored if the tables specified cannot be joined first in the order specified because of dependencies in the join graph. If you specify two or more conflicting LEADING hints, then all of them are ignored. If you specify the ORDERED hint, it overrides all LEADING hints. MERGE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) See Also: Oracle Database Performance Tuning Guide for information on index skip scans See Also: Oracle Database Performance Tuning Guide for information on index skip scans /*+ INDEX_SS_DESC ( @ queryblock tablespec indexspec ) */ /*+ LEADING ( @ queryblock tablespec ) */ /*+ MERGE ( @ queryblock @ queryblock tablespec ) */
  • 134. Comments 3-88 Oracle Database SQL Language Reference The MERGE hint lets you merge views in a query. If a view's query block contains a GROUP BY clause or DISTINCT operator in the SELECT list, then the optimizer can merge the view into the accessing statement only if complex view merging is enabled. Complex merging can also be used to merge an IN subquery into the accessing statement if the subquery is uncorrelated. For example: SELECT /*+ MERGE(v) */ e1.last_name, e1.salary, v.avg_salary FROM employees e1, (SELECT department_id, avg(salary) avg_salary FROM employees e2 GROUP BY department_id) v WHERE e1.department_id = v.department_id AND e1.salary > v.avg_salary; When the MERGE hint is used without an argument, it should be placed in the view query block. When MERGE is used with the view name as an argument, it should be placed in the surrounding query. MODEL_MIN_ANALYSIS Hint The MODEL_MIN_ANALYSIS hint instructs the optimizer to omit some compile-time optimizations of spreadsheet rules—primarily detailed dependency graph analysis. Other spreadsheet optimizations, such as creating filters to selectively populate spreadsheet access structures and limited rule pruning, are still used by the optimizer. This hint reduces compilation time because spreadsheet analysis can be lengthy if the number of spreadsheet rules is more than several hundreds. MONITOR Hint The MONITOR hint forces real-time SQL monitoring for the query, even if the statement is not long running. This hint is valid only when the parameter CONTROL_ MANAGEMENT_PACK_ACCESS is set to DIAGNOSTIC+TUNING. NATIVE_FULL_OUTER_JOIN Hint The NATIVE_FULL_OUTER_JOIN hint instructs the optimizer to use native full outer join, which is a native execution method based on a hash join. See Also: Oracle Database Performance Tuning Guide for more information about real-time SQL monitoring See Also: ■ NO_NATIVE_FULL_OUTER_JOIN Hint on page 3-91 ■ Oracle Database Performance Tuning Guide for more information about native full outer joins /*+ MODEL_MIN_ANALYSIS */ /*+ MONITOR */ /*+ NATIVE_FULL_OUTER_JOIN */
  • 135. Comments Basic Elements of Oracle SQL 3-89 NOAPPEND Hint The NOAPPEND hint instructs the optimizer to use conventional INSERT by disabling parallel mode for the duration of the INSERT statement. Conventional INSERT is the default in serial mode, and direct-path INSERT is the default in parallel mode. NOCACHE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NOCACHE hint instructs the optimizer to place the blocks retrieved for the table at the least recently used end of the LRU list in the buffer cache when a full table scan is performed. This is the normal behavior of blocks in the buffer cache. For example: SELECT /*+ FULL(hr_emp) NOCACHE(hr_emp) */ last_name FROM employees hr_emp; The CACHE and NOCACHE hints affect system statistics table scans(long tables) and table scans(short tables), as shown in the V$SYSSTAT view. NO_EXPAND Hint (See "Specifying a Query Block in a Hint" on page 3-75) The NO_EXPAND hint instructs the optimizer not to consider OR-expansion for queries having OR conditions or IN-lists in the WHERE clause. Usually, the optimizer considers using OR expansion and uses this method if it decides that the cost is lower than not using it. For example: SELECT /*+ NO_EXPAND */ * FROM employees e, departments d WHERE e.manager_id = 108 OR d.department_id = 110; NO_FACT Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_FACT hint is used in the context of the star transformation. It instruct the optimizer that the queried table should not be considered as a fact table. See Also: Oracle Database Performance Tuning Guide for information on automatic caching of tables, depending on their size See Also: The "USE_CONCAT Hint" on page 3-104, which is the opposite of this hint /*+ NOAPPEND */ /*+ NOCACHE ( @ queryblock tablespec ) */ /*+ NO_EXPAND ( @ queryblock ) */ /*+ NO_FACT ( @ queryblock tablespec ) */
  • 136. Comments 3-90 Oracle Database SQL Language Reference NO_INDEX Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The NO_INDEX hint instructs the optimizer not to use one or more indexes for the specified table. For example: SELECT /*+ NO_INDEX(employees emp_empid) */ employee_id FROM employees WHERE employee_id > 200; Each parameter serves the same purpose as in "INDEX Hint" on page 3-83 with the following modifications: ■ If this hint specifies a single available index, then the optimizer does not consider a scan on this index. Other indexes not specified are still considered. ■ If this hint specifies a list of available indexes, then the optimizer does not consider a scan on any of the specified indexes. Other indexes not specified in the list are still considered. ■ If this hint specifies no indexes, then the optimizer does not consider a scan on any index on the table. This behavior is the same as a NO_INDEX hint that specifies a list of all available indexes for the table. The NO_INDEX hint applies to function-based, B-tree, bitmap, cluster, or domain indexes. If a NO_INDEX hint and an index hint (INDEX, INDEX_ASC, INDEX_DESC, INDEX_COMBINE, or INDEX_FFS) both specify the same indexes, then the database ignores both the NO_INDEX hint and the index hint for the specified indexes and considers those indexes for use during execution of the statement. NO_INDEX_FFS Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The NO_INDEX_FFS hint instructs the optimizer to exclude a fast full index scan of the specified indexes on the specified table. Each parameter serves the same purpose as in the "INDEX Hint" on page 3-83. For example: SELECT /*+ NO_INDEX_FFS(items item_order_ix) */ order_id FROM order_items items; NO_INDEX_SS Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) /*+ NO_INDEX ( @ queryblock tablespec indexspec ) */ /*+ NO_INDEX_FFS ( @ queryblock tablespec indexspec ) */ /*+ NO_INDEX_SS ( @ queryblock tablespec indexspec ) */
  • 137. Comments Basic Elements of Oracle SQL 3-91 The NO_INDEX_SS hint instructs the optimizer to exclude a skip scan of the specified indexes on the specified table. Each parameter serves the same purpose as in the "INDEX Hint" on page 3-83. NO_MERGE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_MERGE hint instructs the optimizer not to combine the outer query and any inline view queries into a single query. This hint lets you have more influence over the way in which the view is accessed. For example, the following statement causes view seattle_dept not to be merged: SELECT /*+NO_MERGE(seattle_dept)*/ e1.last_name, seattle_dept.department_name FROM employees e1, (SELECT location_id, department_id, department_name FROM departments WHERE location_id = 1700) seattle_dept WHERE e1.department_id = seattle_dept.department_id; When you use the NO_MERGE hint in the view query block, specify it without an argument. When you specify NO_MERGE in the surrounding query, specify it with the view name as an argument. NO_MONITOR Hint The NO_MONITOR hint disables real-time SQL monitoring for the query, even if the query is long running. NO_NATIVE_FULL_OUTER_JOIN Hint The NO_NATIVE_FULL_OUTER_JOIN hint instructs the optimizer to exclude the native execution method when joining each specified table. Instead, the full outer join is executed as a union of left outer join and anti-join. NO_PARALLEL Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) See Also: Oracle Database Performance Tuning Guide for information on index skip scans See Also: NATIVE_FULL_OUTER_JOIN Hint on page 3-88 /*+ NO_MERGE ( @ queryblock @ queryblock tablespec ) */ /*+ NO_MONITOR */ /*+ NO_NATIVE_FULL_OUTER_JOIN */ /*+ NO_PARALLEL ( @ queryblock tablespec ) */
  • 138. Comments 3-92 Oracle Database SQL Language Reference The NO_PARALLEL hint overrides a PARALLEL parameter in the DDL that created or altered the table. For example: ALTER TABLE employees PARALLEL 8; SELECT /*+ NO_PARALLEL(hr_emp) */ last_name FROM employees hr_emp; NOPARALLEL Hint The NOPARALLEL hint has been deprecated. Use the NO_PARALLEL hint instead. NO_PARALLEL_INDEX Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The NO_PARALLEL_INDEX hint overrides a PARALLEL parameter in the DDL that created or altered the index, thus avoiding a parallel index scan operation. NOPARALLEL_INDEX Hint The NOPARALLEL_INDEX hint has been deprecated. Use the NO_PARALLEL_INDEX hint instead. NO_PUSH_PRED Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_PUSH_PRED hint instructs the optimizer not to push a join predicate into the view. For example: SELECT /*+ NO_MERGE(v) NO_PUSH_PRED(v) */ * FROM employees e, (SELECT manager_id FROM employees ) v WHERE e.manager_id = v.manager_id(+) AND e.employee_id = 100; See Also: "Note on Parallel Hints" on page 3-96 for more information on the parallel hints See Also: "Note on Parallel Hints" on page 3-96 for more information on the parallel hints /*+ NO_PARALLEL_INDEX ( @ queryblock tablespec indexspec ) */ /*+ NO_PUSH_PRED ( @ queryblock @ queryblock tablespec ) */
  • 139. Comments Basic Elements of Oracle SQL 3-93 NO_PUSH_SUBQ Hint (See "Specifying a Query Block in a Hint" on page 3-75) The NO_PUSH_SUBQ hint instructs the optimizer to evaluate nonmerged subqueries as the last step in the execution plan. Doing so can improve performance if the subquery is relatively expensive or does not reduce the number of rows significantly. NO_PX_JOIN_FILTER Hint This hint prevents the optimizer from using parallel join bitmap filtering. NO_QUERY_TRANSFORMATION Hint The NO_QUERY_TRANSFORMATION hint instructs the optimizer to skip all query transformations, including but not limited to OR-expansion, view merging, subquery unnesting, star transformation, and materialized view rewrite. For example: SELECT /*+ NO_QUERY_TRANSFORMATION */ employee_id, last_name FROM (SELECT * FROM employees e) v WHERE v.last_name = 'Smith'; NO_RESULT_CACHE Hint The optimizer caches query results in the result cache if the RESULT_CACHE_MODE initialization parameter is set to FORCE. In this case, the NO_RESULT_CACHE hint disables such caching for the current query. If the query is executed from OCI client and OCI client result cache is enabled, then the NO_RESULT_CACHE hint disables caching for the current query. NO_REWRITE Hint (See "Specifying a Query Block in a Hint" on page 3-75) The NO_REWRITE hint instructs the optimizer to disable query rewrite for the query block, overriding the setting of the parameter QUERY_REWRITE_ENABLED. For example: SELECT /*+ NO_REWRITE */ sum(s.amount_sold) AS dollars FROM sales s, times t WHERE s.time_id = t.time_id GROUP BY t.calendar_month_desc; /*+ NO_PUSH_SUBQ ( @ queryblock ) */ /*+ NO_PX_JOIN_FILTER ( tablespec ) */ /*+ NO_QUERY_TRANSFORMATION */ /*+ NO_RESULT_CACHE */ /*+ NO_REWRITE ( @ queryblock ) */
  • 140. Comments 3-94 Oracle Database SQL Language Reference NOREWRITE Hint The NOREWRITE hint has been deprecated. Use the NO_REWRITE hint instead. NO_STAR_TRANSFORMATION Hint (See "Specifying a Query Block in a Hint" on page 3-75) The NO_STAR_TRANSFORMATION hint instructs the optimizer not to perform star query transformation. NO_UNNEST Hint (See "Specifying a Query Block in a Hint" on page 3-75) Use of the NO_UNNEST hint turns off unnesting . NO_USE_HASH Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_USE_HASH hint instructs the optimizer to exclude hash joins when joining each specified table to another row source using the specified table as the inner table. For example: SELECT /*+ NO_USE_HASH(e d) */ * FROM employees e, departments d WHERE e.department_id = d.department_id; NO_USE_MERGE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_USE_MERGE hint instructs the optimizer to exclude sort-merge joins when joining each specified table to another row source using the specified table as the inner table. For example: SELECT /*+ NO_USE_MERGE(e d) */ * FROM employees e, departments d WHERE e.department_id = d.department_id ORDER BY d.department_id; /*+ NO_STAR_TRANSFORMATION ( @ queryblock ) */ /*+ NO_UNNEST ( @ queryblock ) */ /*+ NO_USE_HASH ( @ queryblock tablespec ) */ /*+ NO_USE_MERGE ( @ queryblock tablespec ) */
  • 141. Comments Basic Elements of Oracle SQL 3-95 NO_USE_NL Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The NO_USE_NL hint instructs the optimizer to exclude nested loops joins when joining each specified table to another row source using the specified table as the inner table. For example: SELECT /*+ NO_USE_NL(l h) */ * FROM orders h, order_items l WHERE l.order_id = h.order_id AND l.order_id > 3500; When this hint is specified, only hash join and sort-merge joins are considered for the specified tables. However, in some cases tables can be joined only by using nested loops. In such cases, the optimizer ignores the hint for those tables. NO_XML_QUERY_REWRITE Hint The NO_XML_QUERY_REWRITE hint instructs the optimizer to prohibit the rewriting of XPath expressions in SQL statements. By prohibiting the rewriting of XPath expressions, this hint also prohibits the use of any XMLIndexes for the current query. For example: SELECT /*+NO_XML_QUERY_REWRITE*/ XMLQUERY('<A/>') FROM dual; NO_XMLINDEX_REWRITE Hint The NO_XMLINDEX_REWRITE hint instructs the optimizer not to use any XMLIndex indexes for the current query. For example: SELECT /*+NO_XMLINDEX_REWRITE*/ count(*) FROM table WHERE existsNode(OBJECT_VALUE, '/*') = 1; OPT_PARAM Hint The OPT_PARAM hint lets you set an initialization parameter for the duration of the current query only. This hint is valid only for the following parameters: OPTIMIZER_ DYNAMIC_SAMPLING, OPTIMIZER_INDEX_CACHING, OPTIMIZER_INDEX_COST_ ADJ, OPTIMIZER_SECURE_VIEW_MERGING, and STAR_TRANSFORMATION_ See Also: "NO_XMLINDEX_REWRITE Hint" on page 3-95 See Also: "NO_XML_QUERY_REWRITE Hint" on page 3-95 for another way to disable the use of XMLIndexes /*+ NO_USE_NL ( @ queryblock tablespec ) */ /*+ NO_XML_QUERY_REWRITE */ /*+ NO_XMLINDEX_REWRITE */ /*+ OPT_PARAM ( parameter_name , parameter_value ) */
  • 142. Comments 3-96 Oracle Database SQL Language Reference ENABLED. For example, the following hint sets the parameter STAR_ TRANSFORMATION_ENABLED to TRUE for the statement to which it is added: SELECT /*+ OPT_PARAM('star_transformation_enabled' 'true') */ * FROM ... ; Parameter values that are strings are enclosed in single quotation marks. Numeric parameter values are specified without quotation marks. ORDERED Hint The ORDERED hint instructs Oracle to join tables in the order in which they appear in the FROM clause. Oracle recommends that you use the LEADING hint, which is more versatile than the ORDERED hint. When you omit the ORDERED hint from a SQL statement requiring a join, the optimizer chooses the order in which to join the tables. You might want to use the ORDERED hint to specify a join order if you know something that the optimizer does not know about the number of rows selected from each table. Such information lets you choose an inner and outer table better than the optimizer could. The following query is an example of the use of the ORDERED hint: SELECT /*+ORDERED */ o.order_id, c.customer_id, l.unit_price * l.quantity FROM customers c, order_items l, orders o WHERE c.cust_last_name = :b1 AND o.customer_id = c.customer_id AND o.order_id = l.order_id; PARALLEL Hint Note on Parallel Hints Beginning with Oracle Database 11g Release 2, the PARALLEL and NO_PARALLEL hints are statement-level hints and supersede the earlier object-level hints: PARALLEL_INDEX, NO_PARALLEL_INDEX, and previously specified PARALLEL and NO_PARALLEL hints. For PARALLEL, if you specify integer, then that degree of parallelism will be used for the statement. If you omit integer, then the database computes the degree of parallelism. All the access paths that can use parallelism will use the specified or computed degree of parallelism. In the syntax diagrams below, parallel_hint_statement shows the syntax for statement-level hints, and parallel_hint_object shows the syntax for object-level hints. Object-level hints are supported for backward compatibility, and are superseded by statement-level hints. parallel_hint_statement::= /*+ ORDERED */ /*+ PARALLEL ( DEFAULT AUTO MANUAL integer ) */
  • 143. Comments Basic Elements of Oracle SQL 3-97 parallel_hint_object::= (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The PARALLEL hint instructs the optimizer to use the specified number of concurrent servers for a parallel operation. The hint applies to the SELECT, INSERT, MERGE, UPDATE, and DELETE portions of a statement, as well as to the table scan portion. If any parallel restrictions are violated, then the hint is ignored. For a statement-level PARALLEL hint: ■ PARALLEL: The statement always is run parallel, and the database computes the degree of parallelism, which can be 2 or greater. ■ PARALLEL DEFAULT: The same as PARALLEL. The DEFAULT keyword is included for completeness. ■ PARALLEL AUTO: The database computes the degree of parallelism, which can be 1 or greater. If the computed degree of parallelism is 1, then the statement runs serially. ■ PARALLEL MANUAL: The optimizer is forced to use the parallel settings of the objects in the statement. ■ PARALLEL (integer): The optimizer uses the degree of parallelism specified by integer. In the following example, the optimizer calculates the degree of parallelism. The statement always runs in parallel. SELECT /*+ PARALLEL */ last_name FROM employees; In the following example, the optimizer calculates the degree of parallelism, but that degree may be 1, in which case the statement will run serially. SELECT /*+ PARALLEL (AUTO) */ last_name from employees; In the following example, the PARALLEL hint advises the optimizer to use the degree of parallelization currently in effect for the table itself, which is 5: CREATE TABLE parallel_table (col1 number, col2 VARCHAR2(10)) PARALLEL 5; SELECT /*+ PARALLEL (MANUAL) */ col2 FROM parallel_table; For an object-level PARALLEL hint, the integer value specifies the degree of parallelism for the specified table. Specifying DEFAULT or no value signifies that the query coordinator should examine the settings of the initialization parameters to determine the default degree of parallelism. In the following example, the PARALLEL hint overrides the degree of parallelism specified in the employees table definition: SELECT /*+ FULL(hr_emp) PARALLEL(hr_emp, 5) */ last_name FROM employees hr_emp; Note: The number of servers that can be used is twice the value in the PARALLEL hint, if sorting or grouping operations also take place. /*+ PARALLEL ( @ queryblock tablespec integer DEFAULT ) */
  • 144. Comments 3-98 Oracle Database SQL Language Reference In the next example, the PARALLEL hint overrides the degree of parallelism specified in the employees table definition and instructs the optimizer to use the default degree of parallelism determined by the initialization parameters. SELECT /*+ FULL(hr_emp) PARALLEL(hr_emp, DEFAULT) */ last_name FROM employees hr_emp; Oracle ignores parallel hints on temporary tables. Refer to CREATE TABLE on page 16-6 and Oracle Database Concepts for more information on parallel execution. PARALLEL_INDEX Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The PARALLEL_INDEX hint instructs the optimizer to use the specified number of concurrent servers to parallelize index range scans, full scans, and fast full scans for partitioned indexes. The integer value indicates the degree of parallelism for the specified index. Specifying DEFAULT or no value signifies that the query coordinator should examine the settings of the initialization parameters to determine the default degree of parallelism. For example, the following hint indicates three parallel execution processes are to be used: SELECT /*+ PARALLEL_INDEX(table1, index1, 3) */ PQ_DISTRIBUTE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) See Also: ■ CREATE TABLE on page 16-6 and Oracle Database Concepts for more information on parallel execution. ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_PARALLEL_EXECUTE package, which provides methods to apply table changes in chunks of rows. Changes to each chunk are independently committed when there are no errors. See Also: "Note on Parallel Hints" on page 3-96 for more information on the parallel hints /*+ PARALLEL_INDEX ( @ queryblock tablespec indexspec integer DEFAULT ) */ /*+ PQ_DISTRIBUTE ( @ queryblock tablespec distribution outer_distribution inner_distribution ) */
  • 145. Comments Basic Elements of Oracle SQL 3-99 The PQ_DISTRIBUTE hint instructs the optimizer how to distribute rows among producer and consumer query servers. You can control the distribution of rows for either joins or for load. Control of Distribution for Load You can control the distribution of rows for parallel INSERT ... SELECT and parallel CREATE TABLE ... AS SELECT statements to direct how rows should be distributed between the producer (query) and the consumer (load) servers. Use the upper branch of the syntax by specifying a single distribution method. The values of the distribution methods and their semantics are described in Table 3–22 on page 3-99. For example, in the following direct-load insert operation, the query and load portions of the operation are combined into each query server: INSERT /*+ APPEND PARALLEL(target_table, 16) PQ_DISTRIBUTE(target_table, NONE) */ INTO target_table SELECT * FROM source_table; In the following table creation example, the optimizer uses the partitioning of target_ table to distribute the rows: CREATE /*+ PQ_DISTRIBUTE(target_table, PARTITION) */ TABLE target_table NOLOGGING PARALLEL 16 PARTITION BY HASH (l_orderkey) PARTITIONS 512 AS SELECT * FROM source_table; Table 3–22 Distribution Values for Load Distribution Description NONE No distribution. That is the query and load operation are combined into each query server. All servers will load all partitions. This lack of distribution is useful to avoid the overhead of distributing rows where there is no skew. Skew can occur due to empty segments or to a predicate in the statement that filters out all rows evaluated by the query. If skew occurs due to using this method, then use either RANDOM or RANDOM_ LOCAL distribution instead. Note: Use this distribution with care. Each partition loaded requires a minimum of 512 KB per process of PGA memory. If you also use compression, then approximately 1.5 MB of PGA memory is consumer per server. PARTITION This method uses the partitioning information of tablespec) to distribute the rows from the query servers to the load servers. Use this distribution method when it is not possible or desirable to combine the query and load operations, when the number of partitions being loaded is greater than or equal to the number of load servers, and the input data will be evenly distributed across the partitions being loaded—that is, there is no skew. RANDOM This method distributes the rows from the producers in a round-robin fashion to the consumers. Use this distribution method when the input data is highly skewed. RANDOM_LOCAL This method distributes the rows from the producers to a set of servers that are responsible for maintaining a given set of partitions. Two or more servers can be loading the same partition, but no servers are loading all partitions. Use this distribution method when the input data is skewed and combining query and load operations is not possible due to memory constraints.
  • 146. Comments 3-100 Oracle Database SQL Language Reference Control of Distribution for Joins You control the distribution method for joins by specifying two distribution methods, as shown in the lower branch of the syntax diagram, one distribution for the outer table and one distribution for the inner table. ■ outer_distribution is the distribution for the outer table. ■ inner_distribution is the distribution for the inner table. The values of the distributions are HASH, BROADCAST, PARTITION, and NONE. Only six combinations table distributions are valid, as described in Table 3–23: For example, given two tables r and s that are joined using a hash join, the following query contains a hint to use hash distribution: SELECT /*+ORDERED PQ_DISTRIBUTE(s HASH, HASH) USE_HASH (s)*/ column_list FROM r,s WHERE r.c=s.c; To broadcast the outer table r, the query is: Table 3–23 Distribution Values for Joins Distribution Description HASH, HASH The rows of each table are mapped to consumer query servers, using a hash function on the join keys. When mapping is complete, each query server performs the join between a pair of resulting partitions. This distribution is recommended when the tables are comparable in size and the join operation is implemented by hash-join or sort merge join. BROADCAST, NONE All rows of the outer table are broadcast to each query server. The inner table rows are randomly partitioned. This distribution is recommended when the outer table is very small compared with the inner table. As a general rule, use this distribution when the inner table size multiplied by the number of query servers is greater than the outer table size. NONE, BROADCAST All rows of the inner table are broadcast to each consumer query server. The outer table rows are randomly partitioned. This distribution is recommended when the inner table is very small compared with the outer table. As a general rule, use this distribution when the inner table size multiplied by the number of query servers is less than the outer table size. PARTITION, NONE The rows of the outer table are mapped using the partitioning of the inner table. The inner table must be partitioned on the join keys. This distribution is recommended when the number of partitions of the outer table is equal to or nearly equal to a multiple of the number of query servers; for example, 14 partitions and 15 query servers. Note: The optimizer ignores this hint if the inner table is not partitioned or not equijoined on the partitioning key. NONE, PARTITION The rows of the inner table are mapped using the partitioning of the outer table. The outer table must be partitioned on the join keys. This distribution is recommended when the number of partitions of the outer table is equal to or nearly equal to a multiple of the number of query servers; for example, 14 partitions and 15 query servers. Note: The optimizer ignores this hint if the outer table is not partitioned or not equijoined on the partitioning key. NONE, NONE Each query server performs the join operation between a pair of matching partitions, one from each table. Both tables must be equipartitioned on the join keys.
  • 147. Comments Basic Elements of Oracle SQL 3-101 SELECT /*+ORDERED PQ_DISTRIBUTE(s BROADCAST, NONE) USE_HASH (s) */ column_list FROM r,s WHERE r.c=s.c; PUSH_PRED Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The PUSH_PRED hint instructs the optimizer to push a join predicate into the view. For example: SELECT /*+ NO_MERGE(v) PUSH_PRED(v) */ * FROM employees e, (SELECT manager_id FROM employees ) v WHERE e.manager_id = v.manager_id(+) AND e.employee_id = 100; PUSH_SUBQ Hint (See "Specifying a Query Block in a Hint" on page 3-75) The PUSH_SUBQ hint instructs the optimizer to evaluate nonmerged subqueries at the earliest possible step in the execution plan. Generally, subqueries that are not merged are executed as the last step in the execution plan. If the subquery is relatively inexpensive and reduces the number of rows significantly, then evaluating the subquery earlier can improve performance. This hint has no effect if the subquery is applied to a remote table or one that is joined using a merge join. PX_JOIN_FILTER Hint This hint forces the optimizer to use parallel join bitmap filtering. QB_NAME Hint (See "Specifying a Query Block in a Hint" on page 3-75) See Also: Oracle Database Concepts for more information on how Oracle parallelizes join operations /*+ PUSH_PRED ( @ queryblock @ queryblock tablespec ) */ /*+ PUSH_SUBQ ( @ queryblock ) */ /*+ PX_JOIN_FILTER ( tablespec ) */ /*+ QB_NAME ( queryblock ) */
  • 148. Comments 3-102 Oracle Database SQL Language Reference Use the QB_NAME hint to define a name for a query block. This name can then be used in a hint in the outer query or even in a hint in an inline view to affect query execution on the tables appearing in the named query block. If two or more query blocks have the same name, or if the same query block is hinted twice with different names, then the optimizer ignores all the names and the hints referencing that query block. Query blocks that are not named using this hint have unique system-generated names. These names can be displayed in the plan table and can also be used in hints within the query block, or in query block hints. For example: SELECT /*+ QB_NAME(qb) FULL(@qb e) */ employee_id, last_name FROM employees e WHERE last_name = 'Smith'; RESULT_CACHE Hint The RESULT_CACHE hint instructs the database to cache the results of the current query or query fragment in memory and then to use the cached results in future executions of the query or query fragment. The hint is recognized in the top-level query, the subquery_factoring_clause, or FROM clause inline view. The cached results reside in the result cache memory portion of the shared pool. A cached result is automatically invalidated whenever a database object used in its creation is successfully modified. This hint takes precedence over settings of the RESULT_CACHE_MODE initialization parameter. The query is eligible for result caching only if all functions entailed in the query—for example, built-in or user-defined functions or virtual columns—are deterministic. If the query is executed from OCI client and OCI client result cache is enabled, then RESULT_CACHE hint enables client caching for the current query. RETRY_ON_ROW_CHANGE Hint This hint is valid only for UPDATE and DELETE operations. It is not supported for INSERT or MERGE operations. When you specify this hint, the operation is retried when the ORA_ROWSCN for one or more rows in the set has changed from the time the set of rows to be modified is determined to the time the block is actually modified. See Also: Oracle Database Performance Tuning Guide for information about using this hint, Oracle Database Reference for information about the RESULT_CACHE_MODE initialization parameter, and Oracle Call Interface Programmer's Guide for more information about the OCI result cache and usage guidelines Note: The CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_ DUPKEY_INDEX, and RETRY_ON_ROW_CHANGE hints are unlike other hints in that they have a semantic effect. The general philosophy explained in "Hints" on page 3-73 does not apply for these three hints. /*+ RESULT_CACHE */ /*+ RETRY_ON_ROW_CHANGE */
  • 149. Comments Basic Elements of Oracle SQL 3-103 REWRITE Hint (See "Specifying a Query Block in a Hint" on page 3-75) The REWRITE hint instructs the optimizer to rewrite a query in terms of materialized views, when possible, without cost consideration. Use the REWRITE hint with or without a view list. If you use REWRITE with a view list and the list contains an eligible materialized view, then Oracle uses that view regardless of its cost. Oracle does not consider views outside of the list. If you do not specify a view list, then Oracle searches for an eligible materialized view and always uses it regardless of the cost of the final plan. STAR_TRANSFORMATION Hint (See "Specifying a Query Block in a Hint" on page 3-75) The STAR_TRANSFORMATION hint instructs the optimizer to use the best plan in which the transformation has been used. Without the hint, the optimizer could make a query optimization decision to use the best plan generated without the transformation, instead of the best plan for the transformed query. For example: SELECT /*+ STAR_TRANSFORMATION */ s.time_id, s.prod_id, s.channel_id FROM sales s, times t, products p, channels c WHERE s.time_id = t.time_id AND s.prod_id = p.prod_id AND s.channel_id = c.channel_id AND c.channel_desc = 'Direct Sales'; Even if the hint is specified, there is no guarantee that the transformation will take place. The optimizer generates the subqueries only if it seems reasonable to do so. If no subqueries are generated, then there is no transformed query, and the best plan for the untransformed query is used, regardless of the hint. See Also: IGNORE_ROW_ON_DUPKEY_INDEX Hint on page 3-83 and CHANGE_DUPKEY_ERROR_INDEX Hint on page 3-79 for information on those hints and Oracle Database Performance Tuning Guide for more information on using the online application upgrade related hints See Also: ■ Oracle Database Concepts and Oracle Database Advanced Replication for more information on materialized views ■ Oracle Database Data Warehousing Guide for more information on using REWRITE with materialized views /*+ REWRITE ( @ queryblock view ) */ /*+ STAR_TRANSFORMATION ( @ queryblock ) */
  • 150. Comments 3-104 Oracle Database SQL Language Reference UNNEST Hint (See "Specifying a Query Block in a Hint" on page 3-75) The UNNEST hint instructs the optimizer to unnest and merge the body of the subquery into the body of the query block that contains it, allowing the optimizer to consider them together when evaluating access paths and joins. Before a subquery is unnested, the optimizer first verifies whether the statement is valid. The statement must then must pass heuristic and query optimization tests. The UNNEST hint instructs the optimizer to check the subquery block for validity only. If the subquery block is valid, then subquery unnesting is enabled without checking the heuristics or costs. USE_CONCAT Hint (See "Specifying a Query Block in a Hint" on page 3-75) The USE_CONCAT hint instructs the optimizer to transform combined OR-conditions in the WHERE clause of a query into a compound query using the UNION ALL set operator. Without this hint, this transformation occurs only if the cost of the query using the concatenations is cheaper than the cost without them. The USE_CONCAT hint overrides the cost consideration. For example: SELECT /*+ USE_CONCAT */ * FROM employees e WHERE manager_id = 108 OR department_id = 110; USE_HASH Hint See Also: ■ Oracle Database Data Warehousing Guide for a full discussion of star transformation. ■ Oracle Database Reference for more information on the STAR_ TRANSFORMATION_ENABLED initialization parameter. See Also: ■ "Collection Unnesting: Examples" on page 19-54 for more information on unnesting nested subqueries and the conditions that make a subquery block valid ■ Oracle Database Performance Tuning Guide for additional information on subquery unnesting See Also: The "NO_EXPAND Hint" on page 3-89, which is the opposite of this hint /*+ UNNEST ( @ queryblock ) */ /*+ USE_CONCAT ( @ queryblock ) */ /*+ USE_HASH ( @ queryblock tablespec ) */
  • 151. Comments Basic Elements of Oracle SQL 3-105 (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The USE_HASH hint instructs the optimizer to join each specified table with another row source using a hash join. For example: SELECT /*+ USE_HASH(l h) */ * FROM orders h, order_items l WHERE l.order_id = h.order_id AND l.order_id > 3500; USE_MERGE Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The USE_MERGE hint instructs the optimizer to join each specified table with another row source using a sort-merge join. For example: SELECT /*+ USE_MERGE(employees departments) */ * FROM employees, departments WHERE employees.department_id = departments.department_id; Use of the USE_NL and USE_MERGE hints is recommended with the LEADING and ORDERED hints. The optimizer uses those hints when the referenced table is forced to be the inner table of a join. The hints are ignored if the referenced table is the outer table. USE_NL Hint The USE_NL hint instructs the optimizer to join each specified table to another row source with a nested loops join, using the specified table as the inner table. (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74) The USE_NL hint instructs the optimizer to join each specified table to another row source with a nested loops join, using the specified table as the inner table. Use of the USE_NL and USE_MERGE hints is recommended with the LEADING and ORDERED hints. The optimizer uses those hints when the referenced table is forced to be the inner table of a join. The hints are ignored if the referenced table is the outer table. In the following example, where a nested loop is forced through a hint, orders is accessed through a full table scan and the filter condition l.order_id = h.order_ id is applied to every row. For every row that meets the filter condition, order_ items is accessed through the index order_id. SELECT /*+ USE_NL(l h) */ h.customer_id, l.unit_price * l.quantity FROM orders h ,order_items l WHERE l.order_id = h.order_id; Adding an INDEX hint to the query could avoid the full table scan on orders, resulting in an execution plan similar to one used on larger systems, even though it might not be particularly efficient here. /*+ USE_MERGE ( @ queryblock tablespec ) */ /*+ USE_NL ( @ queryblock tablespec ) */
  • 152. Database Objects 3-106 Oracle Database SQL Language Reference USE_NL_WITH_INDEX Hint (See "Specifying a Query Block in a Hint" on page 3-75, tablespec::= on page 3-74, indexspec::= on page 3-74) The USE_NL_WITH_INDEX hint instructs the optimizer to join the specified table to another row source with a nested loops join using the specified table as the inner table. For example: SELECT /*+ USE_NL_WITH_INDEX(l item_product_ix) */ * FROM orders h, order_items l WHERE l.order_id = h.order_id AND l.order_id > 3500; The following conditions apply: ■ If no index is specified, then the optimizer must be able to use some index with at least one join predicate as the index key. ■ If an index is specified, then the optimizer must be able to use that index with at least one join predicate as the index key. Database Objects Oracle Database recognizes objects that are associated with a particular schema and objects that are not associated with any particular schema, as described in the sections that follow. Schema Objects A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of objects: Clusters Constraints Database links Database triggers Dimensions External procedure libraries Index-organized tables Indexes Indextypes Java classes, Java resources, Java sources Materialized views Materialized view logs Mining models Object tables Object types Object views Operators Packages Sequences /*+ USE_NL_WITH_INDEX ( @ queryblock tablespec indexspec ) */
  • 153. Database Object Names and Qualifiers Basic Elements of Oracle SQL 3-107 Stored functions, stored procedures Synonyms Tables Views Nonschema Objects Other types of objects are also stored in the database and can be created and manipulated with SQL but are not contained in a schema: Contexts Directories Editions Restore points Roles Rollback segments Tablespaces Users In this reference, each type of object is described in Chapter 10 through Chapter 19, in the section devoted to the statement that creates the database object. These statements begin with the keyword CREATE. For example, for the definition of a cluster, see CREATE CLUSTER on page 14-2. You must provide names for most types of database objects when you create them. These names must follow the rules listed in the sections that follow. Database Object Names and Qualifiers Some database objects are made up of parts that you can or must name, such as the columns in a table or view, index and table partitions and subpartitions, integrity constraints on a table, and objects that are stored within a package, including procedures and stored functions. This section provides: ■ Rules for naming database objects and database object location qualifiers ■ Guidelines for naming database objects and qualifiers Database Object Naming Rules Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier. ■ A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks whenever you refer to that object. See Also: Oracle Database Concepts for an overview of database objects Note: Oracle uses system-generated names beginning with "SYS_" for implicitly generated database objects and subobjects, and names beginning with "ORA_" for some Oracle-supplied objects. Oracle discourages you from using these prefixes in the names you explicitly provide to your database objects and subobjects to avoid possible conflict in name resolution.
  • 154. Database Object Names and Qualifiers 3-108 Oracle Database SQL Language Reference ■ A nonquoted identifier is not surrounded by any punctuation. You can use either quoted or nonquoted identifiers to name any database object. However, database names, global database names, and database link names are always case insensitive and are stored as uppercase. If you specify such names as quoted identifiers, then the quotation marks are silently ignored. Refer to CREATE USER on page 17-7 for additional rules for naming users and passwords. The following list of rules applies to both quoted and nonquoted identifiers unless otherwise indicated: 1. Names must be from 1 to 30 bytes long with these exceptions: ■ Names of databases are limited to 8 bytes. ■ Names of database links can be as long as 128 bytes. If an identifier includes multiple parts separated by periods, then each attribute can be up to 30 bytes long. Each period separator, as well as any surrounding double quotation marks, counts as one byte. For example, suppose you identify a column like this: "schema"."table"."column" The schema name can be 30 bytes, the table name can by 30 bytes, and the column name can be 30 bytes. Each of the quotation marks and periods is a single-byte character, so the total length of the identifier in this example can be up to 98 bytes. 2. Nonquoted identifiers cannot be Oracle Database reserved words. Quoted identifiers can be reserved words, although this is not recommended. Depending on the Oracle product you plan to use to access a database object, names might be further restricted by other product-specific reserved words. 3. The Oracle SQL language contains other words that have special meanings. These words include data types, schema names, function names, the dummy system table DUAL, and keywords (the uppercase words in SQL statements, such as Note: Oracle does not recommend using quoted identifiers for database object names. These quoted identifiers are accepted by SQL*Plus, but they may not be valid when using other tools that manage database objects. Note: The reserved word ROWID is an exception to this rule. You cannot use the uppercase word ROWID, either quoted or nonquoted, as a column name. However, you can use the uppercase word as a quoted identifier that is not a column name, and you can use the word with one or more lowercase letters (for example, "Rowid" or "rowid") as any quoted identifier, including a column name. See Also: ■ Appendix E, "Oracle SQL Reserved Words" for a listing of all Oracle Database reserved words ■ The manual for a specific product, such as Oracle Database PL/SQL Language Reference, for a list of the reserved words of that product
  • 155. Database Object Names and Qualifiers Basic Elements of Oracle SQL 3-109 DIMENSION, SEGMENT, ALLOCATE, DISABLE, and so forth). These words are not reserved. However, Oracle uses them internally in specific ways. Therefore, if you use these words as names for objects and object parts, then your SQL statements may be more difficult to read and may lead to unpredictable results. In particular, do not use words beginning with SYS_ or ORA_ as schema object names, and do not use the names of SQL built-in functions for the names of schema objects or user-defined functions. 4. You should use ASCII characters in database names, global database names, and database link names, because ASCII characters provide optimal compatibility across different platforms and operating systems. 5. You can include multibyte characters in passwords. 6. Nonquoted identifiers must begin with an alphabetic character from your database character set. Quoted identifiers can begin with any character. 7. Nonquoted identifiers can contain only alphanumeric characters from your database character set and the underscore (_), dollar sign ($), and pound sign (#). Database links can also contain periods (.) and "at" signs (@). Oracle strongly discourages you from using $ and # in nonquoted identifiers. Quoted identifiers can contain any characters and punctuations marks as well as spaces. However, neither quoted nor nonquoted identifiers can contain double quotation marks or the null character (0). 8. Within a namespace, no two objects can have the same name. The following schema objects share one namespace: ■ Tables ■ Views ■ Sequences ■ Private synonyms ■ Stand-alone procedures ■ Stand-alone stored functions ■ Packages ■ Materialized views ■ User-defined types Each of the following schema objects has its own namespace: ■ Indexes ■ Constraints ■ Clusters ■ Database triggers ■ Private database links ■ Dimensions See Also: "Data Types" on page 3-1, About SQL Functions on page 5-2, and "Selecting from the DUAL Table" on page 9-15
  • 156. Database Object Names and Qualifiers 3-110 Oracle Database SQL Language Reference Because tables and views are in the same namespace, a table and a view in the same schema cannot have the same name. However, tables and indexes are in different namespaces. Therefore, a table and an index in the same schema can have the same name. Each schema in the database has its own namespaces for the objects it contains. This means, for example, that two tables in different schemas are in different namespaces and can have the same name. Each of the following nonschema objects also has its own namespace: ■ User roles ■ Public synonyms ■ Public database links ■ Tablespaces ■ Profiles ■ Parameter files (PFILEs) and server parameter files (SPFILEs) ■ Editions Because the objects in these namespaces are not contained in schemas, these namespaces span the entire database. 9. Nonquoted identifiers are not case sensitive. Oracle interprets them as uppercase. Quoted identifiers are case sensitive. By enclosing names in double quotation marks, you can give the following names to different objects in the same namespace: employees "employees" "Employees" "EMPLOYEES" Note that Oracle interprets the following names the same, so they cannot be used for different objects in the same namespace: employees EMPLOYEES "EMPLOYEES" 10. When Oracle stores or compares identifiers in uppercase, the uppercase form of each character in the identifiers is determined by applying the uppercasing rules of the database character set. Language-specific rules determined by the session setting NLS_SORT are not considered. This behavior corresponds to applying the SQL function UPPER to the identifier rather than the function NLS_UPPER. The database character set uppercasing rules can yield results that are incorrect when viewed as being in a certain natural language. For example, small letter sharp s ("ß"), used in German, does not have an uppercase form according to the database character set uppercasing rules. It is not modified when an identifier is converted into uppercase, while the expected uppercase form in German is the sequence of two characters capital letter S ("SS"). Similarly, the uppercase form of small letter i, according to the database character set uppercasing rules, is capital letter I. However, the expected uppercase form in Turkish and Azerbaijani is capital letter I with dot above. The database character set uppercasing rules ensure that identifiers are interpreted the same in any linguistic configuration of a session. If you want an identifier to
  • 157. Syntax for Schema Objects and Parts in SQL Statements Basic Elements of Oracle SQL 3-111 look correctly in a certain natural language, then you can quote it to preserve the lowercase form or you can use the linguistically correct uppercase form whenever you use that identifier. 11. Columns in the same table or view cannot have the same name. However, columns in different tables or views can have the same name. 12. Procedures or functions contained in the same package can have the same name, if their arguments are not of the same number and data types. Creating multiple procedures or functions with the same name in the same package with different arguments is called overloading the procedure or function. Schema Object Naming Examples The following examples are valid schema object names: last_name horse hr.hire_date "EVEN THIS & THAT!" a_very_long_and_valid_name All of these examples adhere to the rules listed in "Database Object Naming Rules" on page 3-107. The following example is not valid, because it exceeds 30 characters: a_very_very_long_and_valid_name Although column aliases, table aliases, usernames, and passwords are not objects or parts of objects, they must also follow these naming rules unless otherwise specified in the rules themselves. Schema Object Naming Guidelines Here are several helpful guidelines for naming objects and their parts: ■ Use full, descriptive, pronounceable names (or well-known abbreviations). ■ Use consistent naming rules. ■ Use the same name to describe the same entity or attribute across tables. When naming objects, balance the objective of keeping names short and easy to use with the objective of making names as descriptive as possible. When in doubt, choose the more descriptive name, because the objects in the database may be used by many people over a period of time. Your counterpart ten years from now may have difficulty understanding a table column with a name like pmdd instead of payment_due_date. Using consistent naming rules helps users understand the part that each table plays in your application. One such rule might be to begin the names of all tables belonging to the FINANCE application with fin_. Use the same names to describe the same things across tables. For example, the department number columns of the sample employees and departments tables are both named department_id. Syntax for Schema Objects and Parts in SQL Statements This section tells you how to refer to schema objects and their parts in the context of a SQL statement. This section shows you: ■ The general syntax for referring to an object
  • 158. Syntax for Schema Objects and Parts in SQL Statements 3-112 Oracle Database SQL Language Reference ■ How Oracle resolves a reference to an object ■ How to refer to objects in schemas other than your own ■ How to refer to objects in remote databases ■ How to refer to table and index partitions and subpartitions The following diagram shows the general syntax for referring to an object or a part: database_object_or_part::= where: ■ object is the name of the object. ■ schema is the schema containing the object. The schema qualifier lets you refer to an object in a schema other than your own. You must be granted privileges to refer to objects in other schemas. If you omit schema, then Oracle assumes that you are referring to an object in your own schema. Only schema objects can be qualified with schema. Schema objects are shown with list item 8 on page 3-109. Nonschema objects, also shown with list item 8, cannot be qualified with schema because they are not schema objects. An exception is public synonyms, which can optionally be qualified with "PUBLIC". The quotation marks are required. ■ part is a part of the object. This identifier lets you refer to a part of a schema object, such as a column or a partition of a table. Not all types of objects have parts. ■ dblink applies only when you are using the Oracle Database distributed functionality. This is the name of the database containing the object. The dblink qualifier lets you refer to an object in a database other than your local database. If you omit dblink, then Oracle assumes that you are referring to an object in your local database. Not all SQL statements allow you to access objects on remote databases. You can include spaces around the periods separating the components of the reference to the object, but it is conventional to omit them. How Oracle Database Resolves Schema Object References When you refer to an object in a SQL statement, Oracle considers the context of the SQL statement and locates the object in the appropriate namespace. After locating the object, Oracle performs the operation specified by the statement on the object. If the named object cannot be found in the appropriate namespace, then Oracle returns an error. The following example illustrates how Oracle resolves references to objects within SQL statements. Consider this statement that adds a row of data to a table identified by the name departments: INSERT INTO departments VALUES ( 280, 'ENTERTAINMENT_CLERK', 206, 1700); Based on the context of the statement, Oracle determines that departments can be: ■ A table in your own schema schema . object . part @ dblink
  • 159. Syntax for Schema Objects and Parts in SQL Statements Basic Elements of Oracle SQL 3-113 ■ A view in your own schema ■ A private synonym for a table or view ■ A public synonym Oracle always attempts to resolve an object reference within the namespaces in your own schema before considering namespaces outside your schema. In this example, Oracle attempts to resolve the name departments as follows: 1. First, Oracle attempts to locate the object in the namespace in your own schema containing tables, views, and private synonyms. If the object is a private synonym, then Oracle locates the object for which the synonym stands. This object could be in your own schema, another schema, or on another database. The object could also be another synonym, in which case Oracle locates the object for which this synonym stands. 2. If the object is in the namespace, then Oracle attempts to perform the statement on the object. In this example, Oracle attempts to add the row of data to departments. If the object is not of the correct type for the statement, then Oracle returns an error. In this example, departments must be a table, view, or a private synonym resolving to a table or view. If departments is a sequence, then Oracle returns an error. 3. If the object is not in any namespace searched in thus far, then Oracle searches the namespace containing public synonyms. If the object is in that namespace, then Oracle attempts to perform the statement on it. If the object is not of the correct type for the statement, then Oracle returns an error. In this example, if departments is a public synonym for a sequence, then Oracle returns an error. If a public synonym has any dependent tables or user-defined types, then you cannot create an object with the same name as the synonym in the same schema as the dependent objects. If a synonym does not have any dependent tables or user-defined types, then you can create an object with the same name in the same schema as the dependent objects. Oracle invalidates any dependent objects and attempts to revalidate them when they are next accessed. References to Objects in Other Schemas To refer to objects in schemas other than your own, prefix the object name with the schema name: schema.object For example, this statement drops the employees table in the sample schema hr: DROP TABLE hr.employees; References to Objects in Remote Databases To refer to objects in databases other than your local database, follow the object name with the name of the database link to that database. A database link is a schema object that causes Oracle to connect to a remote database to access an object there. This section tells you: ■ How to create database links See Also: Oracle Database PL/SQL Language Reference for information about how PL/SQL resolves identifier names
  • 160. Syntax for Schema Objects and Parts in SQL Statements 3-114 Oracle Database SQL Language Reference ■ How to use database links in your SQL statements Creating Database Links You create a database link with the statement CREATE DATABASE LINK on page 14-32. The statement lets you specify this information about the database link: ■ The name of the database link ■ The database connect string to access the remote database ■ The username and password to connect to the remote database Oracle stores this information in the data dictionary. Database Link Names When you create a database link, you must specify its name. Database link names are different from names of other types of objects. They can be as long as 128 bytes and can contain periods (.) and the "at" sign (@). The name that you give to a database link must correspond to the name of the database to which the database link refers and the location of that database in the hierarchy of database names. The following syntax diagram shows the form of the name of a database link: dblink::= where: ■ database should specify the name portion of the global name of the remote database to which the database link connects. This global name is stored in the data dictionary of the remote database. You can see this name in the GLOBAL_ NAME data dictionary view. ■ domain should specify the domain portion of the global name of the remote database to which the database link connects. If you omit domain from the name of a database link, then Oracle qualifies the database link name with the domain of your local database as it currently exists in the data dictionary. ■ connection_qualifier lets you further qualify a database link. Using connection qualifiers, you can create multiple database links to the same database. For example, you can use connection qualifiers to create multiple database links to different instances of the Oracle Real Application Clusters that access the same database. The combination database.domain is sometimes called the service name. Username and Password Oracle uses the username and password to connect to the remote database. The username and password for a database link are optional. Database Connect String The database connect string is the specification used by Oracle Net to access the remote database. For information on writing database connect See Also: Oracle Database Administrator's Guide and Oracle Database Advanced Replication for more information on connection qualifiers See Also: Oracle Database Net Services Administrator's Guide database . domain @ connection_qualifier
  • 161. Syntax for Schema Objects and Parts in SQL Statements Basic Elements of Oracle SQL 3-115 strings, see the Oracle Net documentation for your specific network protocol. The database string for a database link is optional. References to Database Links Database links are available only if you are using Oracle distributed functionality. When you issue a SQL statement that contains a database link, you can specify the database link name in one of these forms: ■ The complete database link name as stored in the data dictionary, including the database, domain, and optional connection_qualifier components. ■ The partial database link name is the database and optional connection_ qualifier components, but not the domain component. Oracle performs these tasks before connecting to the remote database: 1. If the database link name specified in the statement is partial, then Oracle expands the name to contain the domain of the local database as found in the global database name stored in the data dictionary. (You can see the current global database name in the GLOBAL_NAME data dictionary view.) 2. Oracle first searches for a private database link in your own schema with the same name as the database link in the statement. Then, if necessary, it searches for a public database link with the same name. ■ Oracle always determines the username and password from the first matching database link (either private or public). If the first matching database link has an associated username and password, then Oracle uses it. If it does not have an associated username and password, then Oracle uses your current username and password. ■ If the first matching database link has an associated database string, then Oracle uses it. Otherwise Oracle searches for the next matching (public) database link. If no matching database link is found, or if no matching link has an associated database string, then Oracle returns an error. 3. Oracle uses the database string to access the remote database. After accessing the remote database, if the value of the GLOBAL_NAMES parameter is true, then Oracle verifies that the database.domain portion of the database link name matches the complete global name of the remote database. If this condition is true, then Oracle proceeds with the connection, using the username and password chosen in Step 2. If not, Oracle returns an error. 4. If the connection using the database string, username, and password is successful, then Oracle attempts to access the specified object on the remote database using the rules for resolving object references and referring to objects in other schemas discussed earlier in this section. You can disable the requirement that the database.domain portion of the database link name must match the complete global name of the remote database by setting to FALSE the initialization parameter GLOBAL_NAMES or the GLOBAL_NAMES parameter of the ALTER SYSTEM or ALTER SESSION statement. References to Partitioned Tables and Indexes Tables and indexes can be partitioned. When partitioned, these schema objects consist of a number of parts called partitions, all of which have the same logical attributes. See Also: Oracle Database Administrator's Guide for more information on remote name resolution
  • 162. Syntax for Schema Objects and Parts in SQL Statements 3-116 Oracle Database SQL Language Reference For example, all partitions in a table share the same column and constraint definitions, and all partitions in an index share the same index columns. Partition-extended and subpartition-extended names let you perform some partition-level and subpartition-level operations, such as deleting all rows from a partition or subpartition, on only one partition or subpartition. Without extended names, such operations would require that you specify a predicate (WHERE clause). For range- and list-partitioned tables, trying to phrase a partition-level operation with a predicate can be cumbersome, especially when the range partitioning key uses more than one column. For hash partitions and subpartitions, using a predicate is more difficult still, because these partitions and subpartitions are based on a system-defined hash function. Partition-extended names let you use partitions as if they were tables. An advantage of this method, which is most useful for range-partitioned tables, is that you can build partition-level access control mechanisms by granting (or revoking) privileges on these views to (or from) other users or roles. To use a partition as a table, create a view by selecting data from a single partition, and then use the view as a table. Syntax You can specify partition-extended or subpartition-extended table names in any SQL statements in which the partition_extended_name or subpartition_ extended_name element appears in the syntax. partition_extended_name::= subpartition_extended_name::= The DML statements INSERT, UPDATE, and DELETE and the ANALYZE statement requires parentheses around the partition or subpartition name. This small distinction is reflected in the partition_extension_clause: partition_extension_clause::= In partition_extended_name, subpartition_extended_name, and partition_extension_clause, the PARTITION FOR and SUBPARTITION FOR clauses let you refer to a partition without using its name. They are valid with any PARTITION partition PARTITION FOR ( partition_key_value , ) SUBPARTITION subpartition SUBPARTITION FOR ( subpartition_key_value , ) PARTITION ( partition ) FOR ( partition_key_value , ) SUBPARTITION ( subpartition ) FOR ( subpartition_key_value , )
  • 163. Syntax for Schema Objects and Parts in SQL Statements Basic Elements of Oracle SQL 3-117 type of partitioning and are especially useful for interval partitions. Interval partitions are created automatically as needed when data is inserted into a table. For the respective partition_key_value or subpartition_key_value, specify one value for each partitioning key column. For multicolumn partitioning keys, specify one value for each partitioning key. For composite partitions, specify one value for each partitioning key, followed by one value for each subpartitioning key. All partitioning key values are comma separated. For interval partitions, you can specify only one partition_key_value, and it must be a valid NUMBER or datetime value. Your SQL statement will operate on the partition or subpartitions that contain the values you specify. Restrictions on Extended Names Currently, the use of partition-extended and subpartition-extended table names has the following restrictions: ■ No remote tables: A partition-extended or subpartition-extended table name cannot contain a database link (dblink) or a synonym that translates to a table with a dblink. To use remote partitions and subpartitions, create a view at the remote site that uses the extended table name syntax and then refer to the remote view. ■ No synonyms: A partition or subpartition extension must be specified with a base table. You cannot use synonyms, views, or any other objects. ■ The PARTITION FOR and SUBPARTITION FOR clauses are not valid for DDL operations on views. ■ In the PARTITION FOR and SUBPARTITION FOR clauses, you cannot specify the keywords DEFAULT or MAXVALUE or a bind variable for the partition_key_ value or subpartition_key_value. Example In the following statement, sales is a partitioned table with partition sales_q1_2000. You can create a view of the single partition sales_q1_2000, and then use it as if it were a table. This example deletes rows from the partition. CREATE VIEW Q1_2000_sales AS SELECT * FROM sales PARTITION (SALES_Q1_2000); DELETE FROM Q1_2000_sales WHERE amount_sold < 0; References to Object Type Attributes and Methods To refer to object type attributes or methods in a SQL statement, you must fully qualify the reference with a table alias. Consider the following example from the sample schema oe, which contains a type cust_address_typ and a table customers with a cust_address column based on the cust_address_typ: CREATE TYPE cust_address_typ OID '82A4AF6A4CD1656DE034080020E0EE3D' AS OBJECT ( street_address VARCHAR2(40) , postal_code VARCHAR2(10) , city VARCHAR2(30) , state_province VARCHAR2(10) , country_id CHAR(2) ); / CREATE TABLE customers See Also: The CREATE TABLE "INTERVAL Clause" on page 16-51 for more information on interval partitions
  • 164. Syntax for Schema Objects and Parts in SQL Statements 3-118 Oracle Database SQL Language Reference ( customer_id NUMBER(6) , cust_first_name VARCHAR2(20) CONSTRAINT cust_fname_nn NOT NULL , cust_last_name VARCHAR2(20) CONSTRAINT cust_lname_nn NOT NULL , cust_address cust_address_typ . . . In a SQL statement, reference to the postal_code attribute must be fully qualified using a table alias, as illustrated in the following example: SELECT c.cust_address.postal_code FROM customers c; UPDATE customers c SET c.cust_address.postal_code = 'GU13 BE5' WHERE c.cust_address.city = 'Fleet'; To reference a member method that does not accept arguments, you must provide empty parentheses. For example, the sample schema oe contains an object table categories_tab, based on catalog_typ, which contains the member function getCatalogName. In order to call this method in a SQL statement, you must provide empty parentheses as shown in this example: SELECT TREAT(VALUE(c) AS catalog_typ).getCatalogName() "Catalog Type" FROM categories_tab c WHERE category_id = 90; Catalog Type ------------------------------------ online catalog
  • 165. 4 Operators 4-1 4 Operators An operator manipulates data items and returns a result. Syntactically, an operator appears before or after an operand or between two operands. This chapter contains these sections: ■ About SQL Operators ■ Arithmetic Operators ■ Concatenation Operator ■ Hierarchical Query Operators ■ Set Operators ■ Multiset Operators ■ User-Defined Operators This chapter discusses nonlogical (non-Boolean) operators. These operators cannot by themselves serve as the condition of a WHERE or HAVING clause in queries or subqueries. For information on logical operators, which serve as conditions, refer to Chapter 7, "Conditions". About SQL Operators Operators manipulate individual data items called operands or arguments. Operators are represented by special characters or by keywords. For example, the multiplication operator is represented by an asterisk (*). If you have installed Oracle Text, then you can use the SCORE operator, which is part of that product, in Oracle Text queries. You can also create conditions with the built-in Text operators, including CONTAINS, CATSEARCH, and MATCHES. For more information on these Oracle Text elements, refer to Oracle Text Reference. If you are using Oracle Expression Filter, then you can create conditions with the built-in EVALUATE operator that is part of that product. For more information, refer to Oracle Database Rules Manager and Expression Filter Developer's Guide.
  • 166. About SQL Operators 4-2 Oracle Database SQL Language Reference Unary and Binary Operators The two general classes of operators are: ■ unary: A unary operator operates on only one operand. A unary operator typically appears with its operand in this format: operator operand ■ binary: A binary operator operates on two operands. A binary operator appears with its operands in this format: operand1 operator operand2 Other operators with special formats accept more than two operands. If an operator is given a null operand, then the result is always null. The only operator that does not follow this rule is concatenation (||). Operator Precedence Precedence is the order in which Oracle Database evaluates different operators in the same expression. When evaluating an expression containing multiple operators, Oracle evaluates operators with higher precedence before evaluating those with lower precedence. Oracle evaluates operators with equal precedence from left to right within an expression. Table 4–1 lists the levels of precedence among SQL operators from high to low. Operators listed on the same line have the same precedence. Precedence Example In the following expression, multiplication has a higher precedence than addition, so Oracle first multiplies 2 by 3 and then adds the result to 1. 1+2*3 Note: The combined values of the NLS_COMP and NLS_SORT settings determine the rules by which characters are sorted and compared. If NLS_COMP is set to LINGUISTIC for your database, then all entities in this chapter will be interpreted according to the rules specified by the NLS_SORT parameter. If NLS_COMP is not set to LINGUISTIC, then the functions are interpreted without regard to the NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle Database Globalization Support Guide for more information on these settings. Table 4–1 SQL Operator Precedence Operator Operation +, - (as unary operators), PRIOR, CONNECT_ BY_ROOT Identity, negation, location in hierarchy *, / Multiplication, division +, - (as binary operators), || Addition, subtraction, concatenation SQL conditions are evaluated after SQL operators See "Condition Precedence" on page 7-3
  • 167. Arithmetic Operators Operators 4-3 You can use parentheses in an expression to override operator precedence. Oracle evaluates expressions inside parentheses before evaluating those outside. SQL also supports set operators (UNION, UNION ALL, INTERSECT, and MINUS), which combine sets of rows returned by queries, rather than individual data items. All set operators have equal precedence. Arithmetic Operators You can use an arithmetic operator with one or two arguments to negate, add, subtract, multiply, and divide numeric values. Some of these operators are also used in datetime and interval arithmetic. The arguments to the operator must resolve to numeric data types or to any data type that can be implicitly converted to a numeric data type. Unary arithmetic operators return the same data type as the numeric data type of the argument. For binary arithmetic operators, Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Table 4–2 lists arithmetic operators. Do not use two consecutive minus signs (--) in arithmetic expressions to indicate double negation or the subtraction of a negative value. The characters -- are used to begin comments within SQL statements. You should separate consecutive minus signs with a space or parentheses. Refer to "Comments" on page 3-71 for more information on comments within SQL statements. See Also: "Hierarchical Query Operators" on page 4-5 and "Hierarchical Queries" on page 9-3 for information on the PRIOR operator, which is used only in hierarchical queries See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion, "Numeric Precedence" on page 3-14 for information on numeric precedence, and "Datetime/Interval Arithmetic" on page 3-20 Table 4–2 Arithmetic Operators Operator Purpose Example + - When these denote a positive or negative expression, they are unary operators. SELECT * FROM order_items WHERE quantity = -1 ORDER BY order_id, line_item_id, product_id; SELECT * FROM employees WHERE -salary < 0 ORDER BY employee_id; + - When they add or subtract, they are binary operators. SELECT hire_date FROM employees WHERE SYSDATE - hire_date > 365 ORDER BY hire_date; * / Multiply, divide. These are binary operators. UPDATE employees SET salary = salary * 1.1;
  • 168. Concatenation Operator 4-4 Oracle Database SQL Language Reference Concatenation Operator The concatenation operator manipulates character strings and CLOB data. Table 4–3 describes the concatenation operator. The result of concatenating two character strings is another character string. If both character strings are of data type CHAR, then the result has data type CHAR and is limited to 2000 characters. If either string is of data type VARCHAR2, the result has data type VARCHAR2 and is limited to 4000 characters. If either argument is a CLOB, the result is a temporary CLOB. Trailing blanks in character strings are preserved by concatenation, regardless of the data types of the string or CLOB. On most platforms, the concatenation operator is two solid vertical bars, as shown in Table 4–3. However, some IBM platforms use broken vertical bars for this operator. When moving SQL script files between systems having different character sets, such as between ASCII and EBCDIC, vertical bars might not be translated into the vertical bar required by the target Oracle Database environment. Oracle provides the CONCAT character function as an alternative to the vertical bar operator for cases when it is difficult or impossible to control translation performed by operating system or network utilities. Use this function in applications that will be moved between environments with differing character sets. Although Oracle treats zero-length character strings as nulls, concatenating a zero-length character string with another operand always results in the other operand, so null can result only from the concatenation of two null strings. However, this may not continue to be true in future versions of Oracle Database. To concatenate an expression that might be null, use the NVL function to explicitly convert the expression to a zero-length string. Concatenation Example This example creates a table with both CHAR and VARCHAR2 columns, inserts values both with and without trailing blanks, and then selects these values and concatenates them. Note that for both CHAR and VARCHAR2 columns, the trailing blanks are preserved. CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6), col3 VARCHAR2(6), col4 CHAR(6) ); INSERT INTO tab1 (col1, col2, col3, col4) VALUES ('abc', 'def ', 'ghi ', 'jkl'); SELECT col1||col2||col3||col4 "Concatenation" FROM tab1; Table 4–3 Concatenation Operator Operator Purpose Example || Concatenates character strings and CLOB data. SELECT 'Name is ' || last_name FROM employees ORDER BY last_name; See Also: ■ "Character Data Types" on page 3-8 for more information on the differences between the CHAR and VARCHAR2 data types ■ The functions CONCAT on page 5-40 and NVL on page 5-126 ■ Oracle Database SecureFiles and Large Objects Developer's Guide for more information about CLOBs
  • 169. Set Operators Operators 4-5 Concatenation ------------------------ abcdef ghi jkl Hierarchical Query Operators Two operators, PRIOR and CONNECT_BY_ROOT, are valid only in hierarchical queries. PRIOR In a hierarchical query, one expression in the CONNECT BY condition must be qualified by the PRIOR operator. If the CONNECT BY condition is compound, then only one condition requires the PRIOR operator, although you can have multiple PRIOR conditions. PRIOR evaluates the immediately following expression for the parent row of the current row in a hierarchical query. PRIOR is most commonly used when comparing column values with the equality operator. (The PRIOR keyword can be on either side of the operator.) PRIOR causes Oracle to use the value of the parent row in the column. Operators other than the equal sign (=) are theoretically possible in CONNECT BY clauses. However, the conditions created by these other operators can result in an infinite loop through the possible combinations. In this case Oracle detects the loop at run time and returns an error. Refer to "Hierarchical Queries" on page 9-3 for more information on this operator, including examples. CONNECT_BY_ROOT CONNECT_BY_ROOT is a unary operator that is valid only in hierarchical queries. When you qualify a column with this operator, Oracle returns the column value using data from the root row. This operator extends the functionality of the CONNECT BY [PRIOR] condition of hierarchical queries. Restriction on CONNECT_BY_ROOT You cannot specify this operator in the START WITH condition or the CONNECT BY condition. Set Operators Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. Table 4–4 lists SQL set operators. They are fully described, including examples and restrictions on these operators, in "The UNION [ALL], INTERSECT, MINUS Operators" on page 9-8. See Also: "CONNECT_BY_ROOT Examples" on page 9-7 Table 4–4 Set Operators Operator Returns UNION All distinct rows selected by either query UNION ALL All rows selected by either query, including all duplicates INTERSECT All distinct rows selected by both queries MINUS All distinct rows selected by the first query but not the second
  • 170. Multiset Operators 4-6 Oracle Database SQL Language Reference Multiset Operators Multiset operators combine the results of two nested tables into a single nested table. The examples related to multiset operators require that two nested tables be created and loaded with data as follows: First, make a copy of the oe.customers table called customers_demo: CREATE TABLE customers_demo AS SELECT * FROM customers; Next, create a table type called cust_address_tab_typ. This type will be used when creating the nested table columns. CREATE TYPE cust_address_tab_typ AS TABLE OF cust_address_typ / Now, create two nested table columns in the customers_demo table: ALTER TABLE customers_demo ADD (cust_address_ntab cust_address_tab_typ, cust_address2_ntab cust_address_tab_typ) NESTED TABLE cust_address_ntab STORE AS cust_address_ntab_store NESTED TABLE cust_address2_ntab STORE AS cust_address2_ntab_store; Finally, load data into the two new nested table columns using data from the cust_ address column of the oe.customers table: UPDATE CUSTOMERS_DEMO cd SET cust_address_ntab = CAST(MULTISET(SELECT cust_address FROM customers c WHERE c.customer_id = cd.customer_id) as cust_address_tab_typ); UPDATE CUSTOMERS_DEMO cd SET cust_address2_ntab = CAST(MULTISET(SELECT cust_address FROM customers c WHERE c.customer_id = cd.customer_id) as cust_address_tab_typ); MULTISET EXCEPT MULTISET EXCEPT takes as arguments two nested tables and returns a nested table whose elements are in the first nested table but not in the second nested table. The two input nested tables must be of the same type, and the returned nested table is of the same type as well. ■ The ALL keyword instructs Oracle to return all elements in nested_table1 that are not in nested_table2. For example, if a particular element occurs m times in nested_table1 and n times in nested_table2, then the result will have (m-n) occurrences of the element if m >n and 0 occurrences if m<=n. ALL is the default. nested_table1 MULTISET EXCEPT ALL DISTINCT nested_table2
  • 171. Multiset Operators Operators 4-7 ■ The DISTINCT keyword instructs Oracle to eliminate any element in nested_ table1 which is also in nested_table2, regardless of the number of occurrences. ■ The element types of the nested tables must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example compares two nested tables and returns a nested table of those elements found in the first nested table but not in the second nested table: SELECT customer_id, cust_address_ntab MULTISET EXCEPT DISTINCT cust_address2_ntab multiset_except FROM customers_demo; CUSTOMER_ID MULTISET_EXCEPT(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ----------- -------------------------------------------------------------------------------- 101 CUST_ADDRESS_TAB_TYP() 102 CUST_ADDRESS_TAB_TYP() 103 CUST_ADDRESS_TAB_TYP() 104 CUST_ADDRESS_TAB_TYP() 105 CUST_ADDRESS_TAB_TYP() . . . The preceding example requires the table customers_demo and two nested table columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. MULTISET INTERSECT MULTISET INTERSECT takes as arguments two nested tables and returns a nested table whose values are common in the two input nested tables. The two input nested tables must be of the same type, and the returned nested table is of the same type as well. ■ The ALL keyword instructs Oracle to return all common occurrences of elements that are in the two input nested tables, including duplicate common values and duplicate common NULL occurrences. For example, if a particular value occurs m times in nested_table1 and n times in nested_table2, then the result would contain the element min(m,n) times. ALL is the default. ■ The DISTINCT keyword instructs Oracle to eliminate duplicates from the returned nested table, including duplicates of NULL, if they exist. ■ The element types of the nested tables must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example compares two nested tables and returns a nested table of those elements found in both input nested tables: SELECT customer_id, cust_address_ntab MULTISET INTERSECT DISTINCT cust_address2_ntab multiset_intersect FROM customers_demo ORDER BY customer_id; nested_table1 MULTISET INTERSECT ALL DISTINCT nested_table2
  • 172. Multiset Operators 4-8 Oracle Database SQL Language Reference CUSTOMER_ID MULTISET_INTERSECT(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID ----------- ----------------------------------------------------------------------------------- 101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')) 102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US')) 103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')) 104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US')) 105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US')) . . . The preceding example requires the table customers_demo and two nested table columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. MULTISET UNION MULTISET UNION takes as arguments two nested tables and returns a nested table whose values are those of the two input nested tables. The two input nested tables must be of the same type, and the returned nested table is of the same type as well. ■ The ALL keyword instructs Oracle to return all elements that are in the two input nested tables, including duplicate values and duplicate NULL occurrences. This is the default. ■ The DISTINCT keyword instructs Oracle to eliminate duplicates from the returned nested table, including duplicates of NULL, if they exist. ■ The element types of the nested tables must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example compares two nested tables and returns a nested table of elements from both input nested tables: SELECT customer_id, cust_address_ntab MULTISET UNION cust_address2_ntab multiset_union FROM customers_demo ORDER BY customer_id; CUSTOMER_ID MULTISET_UNION(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ----------- ------------------------------------------------------------------------------- 101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'), CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')) 102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'), CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN','US')) 103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'), CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')) 104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'), CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US')) 105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US'), CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US')) . . . The preceding example requires the table customers_demo and two nested table columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. nested_table1 MULTISET UNION ALL DISTINCT nested_table2
  • 173. User-Defined Operators Operators 4-9 User-Defined Operators Like built-in operators, user-defined operators take a set of operands as input and return a result. However, you create them with the CREATE OPERATOR statement, and they are identified by user-defined names. They reside in the same namespace as tables, views, types, and standalone functions. After you have defined a new operator, you can use it in SQL statements like any other built-in operator. For example, you can use user-defined operators in the select list of a SELECT statement, the condition of a WHERE clause, or in ORDER BY clauses and GROUP BY clauses. However, you must have EXECUTE privilege on the operator to do so, because it is a user-defined object. See Also: CREATE OPERATOR on page 15-34 for an example of creating an operator and Oracle Database Data Cartridge Developer's Guide for more information on user-defined operators
  • 174. User-Defined Operators 4-10 Oracle Database SQL Language Reference
  • 175. 5 Functions 5-1 5Functions Functions are similar to operators in that they manipulate data items and return a result. Functions differ from operators in the format of their arguments. This format enables them to operate on zero, one, two, or more arguments: function(argument, argument, ...) A function without any arguments is similar to a pseudocolumn (refer to Chapter 2, "Pseudocolumns"). However, a pseudocolumn typically returns a different value for each row in the result set, whereas a function without any arguments typically returns the same value for each row. This chapter contains these sections: ■ About SQL Functions ■ Single-Row Functions – Numeric Functions – Character Functions Returning Character Values – NLS Character Functions – Character Functions Returning Number Values – Datetime Functions – General Comparison Functions – Conversion Functions – Large Object Functions – Collection Functions – Hierarchical Function – Data Mining Functions – XML Functions – Encoding and Decoding Functions – NULL-Related Functions – Environment and Identifier Functions ■ Aggregate Functions ■ Analytic Functions ■ Object Reference Functions
  • 176. About SQL Functions 5-2 Oracle Database SQL Language Reference ■ Model Functions ■ About User-Defined Functions About SQL Functions SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL. If you call a SQL function with an argument of a data type other than the data type expected by the SQL function, then Oracle attempts to convert the argument to the expected data type before performing the SQL function. Nulls in SQL Functions Most scalar functions return null when given a null argument. You can use the NVL function to return a value when a null occurs. For example, the expression NVL(commission_pct,0) returns 0 if commission_pct is null or the value of commission_pct if it is not null. For information on how aggregate functions handle nulls, see "Aggregate Functions" on page 5-9. Syntax for SQL Functions In the syntax diagrams for SQL functions, arguments are indicated by their data types. When the parameter function appears in SQL syntax, replace it with one of the functions described in this section. Functions are grouped by the data types of their arguments and their return values. Note: The combined values of the NLS_COMP and NLS_SORT settings determine the rules by which characters are sorted and compared. If NLS_COMP is set to LINGUISTIC for your database, then all entities in this chapter will be interpreted according to the rules specified by the NLS_SORT parameter. If NLS_COMP is not set to LINGUISTIC, then the functions are interpreted without regard to the NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle Database Globalization Support Guide for more information on these settings. Note: When you apply SQL functions to LOB columns, Oracle Database creates temporary LOBs during SQL and PL/SQL processing. You should ensure that temporary tablespace quota is sufficient for storing these temporary LOBs for your application. See Also: ■ "About User-Defined Functions" on page 5-271 for information on user functions and "Data Conversion" on page 3-40 for implicit conversion of data types ■ Oracle Text Reference for information on functions used with Oracle Text ■ Oracle Data Mining Application Developer's Guide for information on frequent itemset functions used with Oracle Data Mining
  • 177. Single-Row Functions Functions 5-3 The syntax showing the categories of functions follows: function::= single_row_function::= The sections that follow list the built-in SQL functions in each of the groups illustrated in the preceding diagrams except user-defined functions. All of the built-in SQL functions are then described in alphabetical order. Single-Row Functions Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses. Numeric Functions Numeric functions accept numeric input and return numeric values. Most numeric functions that return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are: ABS ACOS ASIN ATAN ATAN2 BITAND See Also: "About User-Defined Functions" on page 5-271 and CREATE FUNCTION on page 14-59 single_row_function aggregate_function analytic_function object_reference_function model_function user_defined_function numeric_function character_function data_mining_function datetime_function conversion_function collection_function XML_function miscellaneous_single_row_function
  • 178. Single-Row Functions 5-4 Oracle Database SQL Language Reference CEIL COS COSH EXP FLOOR LN LOG MOD NANVL POWER REMAINDER ROUND (number) SIGN SIN SINH SQRT TAN TANH TRUNC (number) WIDTH_BUCKET Character Functions Returning Character Values Character functions that return character values return values of the following data types unless otherwise documented: ■ If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2. ■ If the input argument is NCHAR or NVARCHAR2, then the value returned is NVARCHAR2. The length of the value returned by the function is limited by the maximum length of the data type returned. ■ For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit, then Oracle Database truncates it and returns the result without an error message. ■ For functions that return CLOB values, if the length of the return values exceeds the limit, then Oracle raises an error and returns no data. The character functions that return character values are: CHR CONCAT INITCAP LOWER LPAD LTRIM NLS_INITCAP NLS_LOWER NLSSORT NLS_UPPER REGEXP_REPLACE REGEXP_SUBSTR REPLACE RPAD RTRIM SOUNDEX
  • 179. Single-Row Functions Functions 5-5 SUBSTR TRANSLATE TREAT TRIM UPPER NLS Character Functions The NLS character functions return information about the character set. The NLS character functions are: NLS_CHARSET_DECL_LEN NLS_CHARSET_ID NLS_CHARSET_NAME Character Functions Returning Number Values Character functions that return number values can take as their argument any character data type. The character functions that return number values are: ASCII INSTR LENGTH REGEXP_INSTR Datetime Functions Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL DAY TO SECOND, INTERVAL YEAR TO MONTH) values. Some of the datetime functions were designed for the Oracle DATE data type (ADD_ MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you provide a timestamp value as their argument, then Oracle Database internally converts the input type to a DATE value and returns a DATE value. The exceptions are the MONTHS_ BETWEEN function, which returns a number, and the ROUND and TRUNC functions, which do not accept timestamp or interval values at all. The remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and interval) and to return a value of one of these types. All of the datetime functions that return current system datetime information, such as SYSDATE, SYSTIMESTAMP, CURRENT_TIMESTAMP, and so forth, are evaluated once for each SQL statement, regardless how many times they are referenced in that statement. The datetime functions are: ADD_MONTHS CURRENT_DATE CURRENT_TIMESTAMP DBTIMEZONE EXTRACT (datetime) FROM_TZ LAST_DAY LOCALTIMESTAMP MONTHS_BETWEEN
  • 180. Single-Row Functions 5-6 Oracle Database SQL Language Reference NEW_TIME NEXT_DAY NUMTODSINTERVAL NUMTOYMINTERVAL ROUND (date) SESSIONTIMEZONE SYS_EXTRACT_UTC SYSDATE SYSTIMESTAMP TO_CHAR (datetime) TO_TIMESTAMP TO_TIMESTAMP_TZ TO_DSINTERVAL TO_YMINTERVAL TRUNC (date) TZ_OFFSET General Comparison Functions The general comparison functions determine the greatest and or least value from a set of values. The general comparison functions are: GREATEST LEAST Conversion Functions Conversion functions convert a value from one data type to another. Generally, the form of the function names follows the convention datatype TO datatype. The first data type is the input data type. The second data type is the output data type. The SQL conversion functions are: ASCIISTR BIN_TO_NUM CAST CHARTOROWID COMPOSE CONVERT DECOMPOSE HEXTORAW NUMTODSINTERVAL NUMTOYMINTERVAL RAWTOHEX RAWTONHEX ROWIDTOCHAR ROWIDTONCHAR SCN_TO_TIMESTAMP TIMESTAMP_TO_SCN TO_BINARY_DOUBLE TO_BINARY_FLOAT TO_CHAR (character) TO_CHAR (datetime) TO_CHAR (number) TO_CLOB TO_DATE TO_DSINTERVAL
  • 181. Single-Row Functions Functions 5-7 TO_LOB TO_MULTI_BYTE TO_NCHAR (character) TO_NCHAR (datetime) TO_NCHAR (number) TO_NCLOB TO_NUMBER TO_DSINTERVAL TO_SINGLE_BYTE TO_TIMESTAMP TO_TIMESTAMP_TZ TO_YMINTERVAL TO_YMINTERVAL TRANSLATE ... USING UNISTR Large Object Functions The large object functions operate on LOBs. The large object functions are: BFILENAME EMPTY_BLOB, EMPTY_CLOB Collection Functions The collection functions operate on nested tables and varrays. The SQL collection functions are: CARDINALITY COLLECT POWERMULTISET POWERMULTISET_BY_CARDINALITY SET Hierarchical Function The hierarchical function applies hierarchical path information to a result set. SYS_CONNECT_BY_PATH Data Mining Functions The data mining functions operate on models that have been built using the DBMS_ DATA_MINING package or the Oracle Data Mining Java API. The SQL data mining functions are: CLUSTER_ID CLUSTER_PROBABILITY CLUSTER_SET FEATURE_ID FEATURE_SET FEATURE_VALUE PREDICTION PREDICTION_BOUNDS PREDICTION_COST PREDICTION_DETAILS PREDICTION_PROBABILITY
  • 182. Single-Row Functions 5-8 Oracle Database SQL Language Reference PREDICTION_SET XML Functions The XML functions operate on or return XML documents or fragments. These functions use arguments that are not defined as part of the ANSI/ISO/IEC SQL Standard but are defined as part of the World Wide Web Consortium (W3C) standards. The processing and operations that the functions perform are defined by the relevant W3C standards. The table below provides a link to the appropriate section of the W3C standard for the rules and guidelines that apply to each of these XML-related arguments. A SQL statement that uses one of these XML functions, where any of the arguments does not conform to the relevant W3C syntax, will result in an error. In particular, of special note is the fact that not every character that is allowed in the value of a database column is considered legal in XML. For more information about selecting and querying XML data using these functions, including information on formatting output, refer to Oracle XML DB Developer's Guide. The SQL XML functions are: APPENDCHILDXML DELETEXML DEPTH EXTRACT (XML) EXISTSNODE EXTRACTVALUE INSERTCHILDXML INSERTCHILDXMLAFTER INSERTCHILDXMLBEFORE INSERTXMLAFTER INSERTXMLBEFORE PATH SYS_DBURIGEN SYS_XMLAGG SYS_XMLGEN UPDATEXML XMLAGG XMLCAST XMLCDATA XMLCOLATTVAL XMLCOMMENT XMLCONCAT XMLDIFF XMLELEMENT XMLEXISTS XMLFOREST XMLISVALID Syntax Element W3C Standard URL value_expr http://www.w3.org/TR/2006/REC-xml-20060816 Xpath_string http://www.w3.org/TR/1999/REC-xpath-19991116 XQuery_string http://www.w3.org/TR/2007/REC-xquery-semantics-20070123/ namespace_string http://www.w3.org/TR/2006/REC-xml-names-20060816/ identifier http://www.w3.org/TR/2006/REC-xml-20060816/#NT-Nmtoken
  • 183. Aggregate Functions Functions 5-9 XMLPARSE XMLPATCH XMLPI XMLQUERY XMLROOT XMLSEQUENCE XMLSERIALIZE XMLTABLE XMLTRANSFORM Encoding and Decoding Functions The encoding and decoding functions let you inspect and decode data in the database. DECODE DUMP ORA_HASH VSIZE NULL-Related Functions The NULL-related functions facilitate null handling. The NULL-related functions are: COALESCE LNNVL NANVL NULLIF NVL NVL2 Environment and Identifier Functions The environment and identifier functions provide information about the instance and session. These functions are: SYS_CONTEXT SYS_GUID SYS_TYPEID UID USER USERENV Aggregate Functions Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group. If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the
  • 184. Aggregate Functions 5-10 Oracle Database SQL Language Reference aggregate functions, rather than on the values of the individual rows of the queried table or view. Many (but not all) aggregate functions that take a single argument accept these clauses: ■ DISTINCT and UNIQUE, which are synonymous, cause an aggregate function to consider only distinct values of the argument expression. The syntax diagrams for aggregate functions in this chapter use the keyword DISTINCT for simplicity. ■ ALL causes an aggregate function to consider all values, including all duplicates. For example, the DISTINCT average of 1, 1, 1, and 3 is 2. The ALL average is 1.5. If you specify neither, then the default is ALL. Some aggregate functions allow the windowing_clause, which is part of the syntax of analytic functions. Refer to windowing_clause on page 5-14 for information about this clause. In the listing of aggregate functions at the end of this section, the functions that allow the windowing_clause are followed by an asterisk (*) All aggregate functions except COUNT(*), GROUPING, and GROUPING_ID ignore nulls. You can use the NVL function in the argument to an aggregate function to substitute a value for a null. COUNT and REGR_COUNT never return null, but return either a number or zero. For all the remaining aggregate functions, if the data set contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the function returns null. The aggregate functions MIN, MAX, SUM, AVG, COUNT, VARIANCE, and STDDEV, when followed by the KEEP keyword, can be used in conjunction with the FIRST or LAST function to operate on a set of values from a set of rows that rank as the FIRST or LAST with respect to a given sorting specification. Refer to FIRST on page 5-77 for more information. You can nest aggregate functions. For example, the following example calculates the average of the maximum salaries of all the departments in the sample schema hr: SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id; AVG(MAX(SALARY)) ---------------- 10925 This calculation evaluates the inner aggregate (MAX(salary)) for each group defined by the GROUP BY clause (department_id), and aggregates the results again. The aggregate functions are: AVG COLLECT CORR CORR_* COUNT COVAR_POP COVAR_SAMP CUME_DIST DENSE_RANK FIRST See Also: "Using the GROUP BY Clause: Examples" on page 19-42 and the "HAVING Clause" on page 19-28 for more information on the GROUP BY clause and HAVING clauses in queries and subqueries
  • 185. Analytic Functions Functions 5-11 GROUP_ID GROUPING GROUPING_ID LAST MAX MEDIAN MIN PERCENTILE_CONT PERCENTILE_DISC PERCENT_RANK RANK REGR_ (Linear Regression) Functions STATS_BINOMIAL_TEST STATS_CROSSTAB STATS_F_TEST STATS_KS_TEST STATS_MODE STATS_MW_TEST STATS_ONE_WAY_ANOVA STATS_T_TEST_* STATS_WSR_TEST STDDEV STDDEV_POP STDDEV_SAMP SUM SYS_XMLAGG VAR_POP VAR_SAMP VARIANCE XMLAGG Analytic Functions Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time. Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause. Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates. analytic_function::= analytic_function ( arguments ) OVER ( analytic_clause )
  • 186. Analytic Functions 5-12 Oracle Database SQL Language Reference analytic_clause::= query_partition_clause::= order_by_clause::= windowing_clause::= The semantics of this syntax are discussed in the sections that follow. analytic_function Specify the name of an analytic function (see the listing of analytic functions following this discussion of semantics). arguments Analytic functions take 0 to 3 arguments. The arguments can be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence and implicitly converts the remaining arguments to that data type. The return type is also that data type, unless otherwise noted for an individual function. See Also: "Numeric Precedence" on page 3-14 for information on numeric precedence and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion query_partition_clause order_by_clause windowing_clause PARTITION BY expr , ( expr , ) ORDER SIBLINGS BY expr position c_alias ASC DESC NULLS FIRST NULLS LAST , ROWS RANGE BETWEEN UNBOUNDED PRECEDING CURRENT ROW value_expr PRECEDING FOLLOWING AND UNBOUNDED FOLLOWING CURRENT ROW value_expr PRECEDING FOLLOWING UNBOUNDED PRECEDING CURRENT ROW value_expr PRECEDING
  • 187. Analytic Functions Functions 5-13 analytic_clause Use OVER analytic_clause to indicate that the function operates on a query result set. This clause is computed after the FROM, WHERE, GROUP BY, and HAVING clauses. You can specify analytic functions with this clause in the select list or ORDER BY clause. To filter the results of a query based on an analytic function, nest these functions within the parent query, and then filter the results of the nested subquery. Notes on the analytic_clause: The following notes apply to the analytic_clause: ■ You cannot nest analytic functions by specifying any analytic function in any part of the analytic_clause. However, you can specify an analytic function in a subquery and compute another analytic function over it. ■ You can specify OVER analytic_clause with user-defined analytic functions as well as built-in analytic functions. See CREATE FUNCTION on page 14-59. query_partition_clause Use the PARTITION BY clause to partition the query result set into groups based on one or more value_expr. If you omit this clause, then the function treats all rows of the query result set as a single group. To use the query_partition_clause in an analytic function, use the upper branch of the syntax (without parentheses). To use this clause in a model query (in the model_column_clauses) or a partitioned outer join (in the outer_join_clause), use the lower branch of the syntax (with parentheses). You can specify multiple analytic functions in the same query, each with the same or different PARTITION BY keys. If the objects being queried have the parallel attribute, and if you specify an analytic function with the query_partition_clause, then the function computations are parallelized as well. Valid values of value_expr are constants, columns, nonanalytic functions, function expressions, or expressions involving any of these. order_by_clause Use the order_by_clause to specify how data is ordered within a partition. For all analytic functions except PERCENTILE_CONT and PERCENTILE_DISC (which take only a single key), you can order the values in a partition on multiple keys, each defined by a value_expr and each qualified by an ordering sequence. Within each function, you can specify multiple ordering expressions. Doing so is especially useful when using functions that rank values, because the second expression can resolve ties between identical values for the first expression. Whenever the order_by_clause results in identical values for multiple rows, the function returns the same result for each of those rows. Refer to the analytic example for SUM on page 5-200 for an illustration of this behavior. Restrictions on the ORDER BY Clause The following restrictions apply to the ORDER BY clause: ■ When used in an analytic function, the order_by_clause must take an expression (expr). The SIBLINGS keyword is not valid (it is relevant only in hierarchical queries). Position (position) and column aliases (c_alias) are also invalid. Otherwise this order_by_clause is the same as that used to order the overall query or subquery.
  • 188. Analytic Functions 5-14 Oracle Database SQL Language Reference ■ An analytic function that uses the RANGE keyword can use multiple sort keys in its ORDER BY clause if it specifies either of these two windows: – RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The short form of this is RANGE UNBOUNDED PRECEDING. – RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. Window boundaries other than these two can have only one sort key in the ORDER BY clause of the analytic function. This restriction does not apply to window boundaries specified by the ROW keyword. ASC | DESC Specify the ordering sequence (ascending or descending). ASC is the default. NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls should appear first or last in the ordering sequence. NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending order. Analytic functions always operate on rows in the order specified in the order_by_ clause of the function. However, the order_by_clause of the function does not guarantee the order of the result. Use the order_by_clause of the query to guarantee the final result ordering. windowing_clause Some analytic functions allow the windowing_clause. In the listing of analytic functions at the end of this section, the functions that allow the windowing_clause are followed by an asterisk (*). ROWS | RANGE These keywords define for each row a window (a physical or logical set of rows) used for calculating the function result. The function is then applied to all the rows in the window. The window moves through the query result set or partition from top to bottom. ■ ROWS specifies the window in physical units (rows). ■ RANGE specifies the window as a logical offset. You cannot specify this clause unless you have specified the order_by_clause. Some window boundaries defined by the RANGE clause let you specify only one expression in the order_by_clause. Refer to "Restrictions on the ORDER BY Clause" on page 5-13. The value returned by an analytic function with a logical offset is always deterministic. However, the value returned by an analytic function with a physical offset may produce nondeterministic results unless the ordering expression results in a unique ordering. You may have to specify multiple columns in the order_by_clause to achieve this unique ordering. BETWEEN ... AND Use the BETWEEN ... AND clause to specify a start point and end point for the window. The first expression (before AND) defines the start point and the second expression (after AND) defines the end point. If you omit BETWEEN and specify only one end point, then Oracle considers it the start point, and the end point defaults to the current row. See Also: order_by_clause of SELECT on page 19-33 for more information on this clause
  • 189. Analytic Functions Functions 5-15 UNBOUNDED PRECEDING Specify UNBOUNDED PRECEDING to indicate that the window starts at the first row of the partition. This is the start point specification and cannot be used as an end point specification. UNBOUNDED FOLLOWING Specify UNBOUNDED FOLLOWING to indicate that the window ends at the last row of the partition. This is the end point specification and cannot be used as a start point specification. CURRENT ROW As a start point, CURRENT ROW specifies that the window begins at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the end point cannot be value_expr PRECEDING. As an end point, CURRENT ROW specifies that the window ends at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the start point cannot be value_expr FOLLOWING. value_expr PRECEDING or value_expr FOLLOWING For RANGE or ROW: ■ If value_expr FOLLOWING is the start point, then the end point must be value_ expr FOLLOWING. ■ If value_expr PRECEDING is the end point, then the start point must be value_ expr PRECEDING. If you are defining a logical window defined by an interval of time in numeric format, then you may need to use conversion functions. If you specified ROWS: ■ value_expr is a physical offset. It must be a constant or expression and must evaluate to a positive numeric value. ■ If value_expr is part of the start point, then it must evaluate to a row before the end point. If you specified RANGE: ■ value_expr is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal. Refer to "Literals" on page 3-45 for information on interval literals. ■ You can specify only one expression in the order_by_clause ■ If value_expr evaluates to a numeric value, then the ORDER BY expr must be a numeric or DATE data type. ■ If value_expr evaluates to an interval value, then the ORDER BY expr must be a DATE data type. If you omit the windowing_clause entirely, then the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Analytic functions are commonly used in data warehousing environments. In the list of analytic functions that follows, functions followed by an asterisk (*) allow the full syntax, including the windowing_clause. AVG * CORR * See Also: NUMTOYMINTERVAL on page 5-126 and NUMTODSINTERVAL on page 5-125 for information on converting numeric times into intervals
  • 190. Object Reference Functions 5-16 Oracle Database SQL Language Reference COVAR_POP * COVAR_SAMP * COUNT * CUME_DIST DENSE_RANK FIRST FIRST_VALUE * LAG LAST LAST_VALUE * LEAD MAX * MIN * NTH_VALUE* NTILE PERCENT_RANK PERCENTILE_CONT PERCENTILE_DISC RANK RATIO_TO_REPORT REGR_ (Linear Regression) Functions * ROW_NUMBER STDDEV * STDDEV_POP * STDDEV_SAMP * SUM * VAR_POP * VAR_SAMP * VARIANCE * Object Reference Functions Object reference functions manipulate REF values, which are references to objects of specified object types. The object reference functions are: DEREF MAKE_REF REF REFTOHEX VALUE Model Functions Model functions can be used only in the model_clause of the SELECT statement. The model functions are: CV ITERATION_NUMBER PRESENTNNV PRESENTV See Also: Oracle Database Data Warehousing Guide for more information on these functions and for scenarios illustrating their use See Also: Oracle Database Object-Relational Developer's Guide for more information about REF data types
  • 191. Alphabetical Listing of SQL Functions Functions 5-17 PREVIOUS Alphabetical Listing of SQL Functions The SQL functions are described in alphabetical order.
  • 192. ABS 5-18 Oracle Database SQL Language Reference ABS Syntax Purpose ABS returns the absolute value of n. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. Examples The following example returns the absolute value of -15: SELECT ABS(-15) "Absolute" FROM DUAL; Absolute ---------- 15 ACOS Syntax Purpose ACOS returns the arc cosine of n. The argument n must be in the range of -1 to 1, and the function returns a value in the range of 0 to pi, expressed in radians. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the arc cosine of .3: SELECT ACOS(.3)"Arc_Cosine" FROM DUAL; Arc_Cosine ---------- 1.26610367 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ABS ( n ) ACOS ( n )
  • 193. APPENDCHILDXML Functions 5-19 ADD_MONTHS Syntax Purpose ADD_MONTHS returns the date date plus integer months. A month is defined by the session parameter NLS_CALENDAR. The date argument can be a datetime value or any value that can be implicitly converted to DATE. The integer argument can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE, regardless of the data type of date. If date is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as date. Examples The following example returns the month after the hire_date in the sample table employees: SELECT TO_CHAR( ADD_MONTHS(hire_date,1), 'DD-MON-YYYY') "Next month" FROM employees WHERE last_name = 'Baer'; Next Month ----------- 07-JUL-2002 APPENDCHILDXML Syntax Purpose APPENDCHILDXML appends a user-supplied value onto the target XML as the child of the node indicated by an XPath expression. ■ XMLType_instance is an instance of XMLType. ■ The XPath_string is an Xpath expression indicating one or more nodes onto which one or more child nodes are to be appended. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative path defaults to the root node. ■ The value_expr specifies one or more nodes of XMLType. It must resolve to a string. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ADD_MONTHS ( date , integer ) APPENDCHILDXML ( XMLType_instance , XPath_string , value_expr , namespace_string )
  • 194. ASCII 5-20 Oracle Database SQL Language Reference ■ The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type VARCHAR2. Examples The following example adds an /Owner node to the /Warehouse/Building node of warehouse_spec in the oe.warehouses table if the value of the /Building node is "Rented": UPDATE warehouses SET warehouse_spec = APPENDCHILDXML(warehouse_spec, 'Warehouse/Building', XMLType('<Owner>Grandco</Owner>')) WHERE EXTRACTVALUE(warehouse_spec, '/Warehouse/Building') = 'Rented'; SELECT warehouse_id, warehouse_name, EXTRACTVALUE(warehouse_spec, '/Warehouse/Building/Owner') "Prop.Owner" FROM warehouses WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Building/Owner') = 1; WAREHOUSE_ID WAREHOUSE_NAME Prop.Owner ------------ --------------- ---------- 2 San Francisco Grandco 3 New Jersey Grandco ASCII Syntax Purpose ASCII returns the decimal representation in the database character set of the first character of char. char can be of data type CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned is of data type NUMBER. If your database character set is 7-bit ASCII, then this function returns an ASCII value. If your database character set is EBCDIC Code, then this function returns an EBCDIC value. There is no corresponding EBCDIC character function. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example returns employees whose last names begin with the letter L, whose ASCII equivalent is 76: SELECT last_name FROM employees WHERE ASCII(SUBSTR(last_name, 1, 1,)) = 76; LAST_NAME See Also: Oracle XML DB Developer's Guide for more information about this function See Also: "Data Type Comparison Rules" on page 3-37 for more information ASCII ( char )
  • 195. ASIN Functions 5-21 ------------------------- Ladwig Landry Lee Livingston ASCIISTR Syntax Purpose ASCIISTR takes as its argument a string, or an expression that resolves to a string, in any character set and returns an ASCII version of the string in the database character set. Non-ASCII characters are converted to the form xxxx, where xxxx represents a UTF-16 code unit. Examples The following example returns the ASCII string equivalent of the text string "ABÄCDE": SELECT ASCIISTR('ABÄCDE') FROM DUAL; ASCIISTR(' ---------- AB00C4CDE ASIN Syntax Purpose ASIN returns the arc sine of n. The argument n must be in the range of -1 to 1, and the function returns a value in the range of -pi/2 to pi/2, expressed in radians. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the arc sine of .3: SELECT ASIN(.3) "Arc_Sine" FROM DUAL; Arc_Sine See Also: Oracle Database Globalization Support Guide for information on Unicode character sets and character semantics See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ASCIISTR ( char ) ASIN ( n )
  • 196. ATAN 5-22 Oracle Database SQL Language Reference ---------- .304692654 ATAN Syntax Purpose ATAN returns the arc tangent of n. The argument n can be in an unbounded range and returns a value in the range of -pi/2 to pi/2, expressed in radians. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the arc tangent of .3: SELECT ATAN(.3) "Arc_Tangent" FROM DUAL; Arc_Tangent ---------- .291456794 ATAN2 Syntax Purpose ATAN2 returns the arc tangent of n1 and n2. The argument n1 can be in an unbounded range and returns a value in the range of -pi to pi, depending on the signs of n1 and n2, expressed in radians. ATAN2(n1,n2) is the same as ATAN(n1/n2). This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If any argument is BINARY_ FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise the function returns NUMBER. Examples The following example returns the arc tangent of .3 and .2: See Also: ATAN2 on page 5-22 for information about the ATAN2 function and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: ATAN on page 5-22 for information on the ATAN function and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ATAN ( n ) ATAN2 ( n1 , n2 )
  • 197. AVG Functions 5-23 SELECT ATAN2(.3, .2) "Arc_Tangent2" FROM DUAL; Arc_Tangent2 ------------ .982793723 AVG Syntax Purpose AVG returns average value of expr. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed. Aggregate Example The following example calculates the average salary of all employees in the hr.employees table: SELECT AVG(salary) "Average" FROM employees; Average -------------- 6461.68224 Analytic Example The following example calculates, for each employee in the employees table, the average salary of the employees reporting to the same manager who were hired in the range just before through just after the employee: SELECT manager_id, last_name, hire_date, salary, AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS c_mavg FROM employees ORDER BY manager_id, hire_date, salary, c_mavg; See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 AVG ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 198. BFILENAME 5-24 Oracle Database SQL Language Reference MANAGER_ID LAST_NAME HIRE_DATE SALARY C_MAVG ---------- ------------------------- --------- ---------- ---------- 100 De Haan 13-JAN-01 17000 14000 100 Raphaely 07-DEC-02 11000 11966.6667 100 Kaufling 01-MAY-03 7900 10633.3333 100 Hartstein 17-FEB-04 13000 9633.33333 100 Weiss 18-JUL-04 8000 11666.6667 100 Russell 01-OCT-04 14000 11833.3333 100 Partners 05-JAN-05 13500 13166.6667 100 Errazuriz 10-MAR-05 12000 11233.3333 . . . BFILENAME Syntax Purpose BFILENAME returns a BFILE locator that is associated with a physical LOB binary file on the server file system. ■ 'directory' is a database object that serves as an alias for a full path name on the server file system where the files are actually located. ■ 'filename' is the name of the file in the server file system. You must create the directory object and associate a BFILE value with a physical file before you can use them as arguments to BFILENAME in a SQL or PL/SQL statement, DBMS_LOB package, or OCI operation. You can use this function in two ways: ■ In a DML statement to initialize a BFILE column ■ In a programmatic interface to access BFILE data by assigning a value to the BFILE locator. The directory argument is case sensitive. You must ensure that you specify the directory object name exactly as it exists in the data dictionary. For example, if an "Admin" directory object was created using mixed case and a quoted identifier in the CREATE DIRECTORY statement, then when using the BFILENAME function you must refer to the directory object as 'Admin'. You must specify the filename argument according to the case and punctuation conventions for your operating system. Examples The following example inserts a row into the sample table pm.print_media. The example uses the BFILENAME function to identify a binary file on the server file system in the directory /demo/schema/product_media. The example shows how the directory database object media_dir was created in the PM schema. See Also: ■ Oracle Database SecureFiles and Large Objects Developer's Guide and Oracle Call Interface Programmer's Guide for more information on LOBs and for examples of retrieving BFILE data ■ CREATE DIRECTORY on page 14-42 BFILENAME ( ’ directory ’ , ’ filename ’ )
  • 199. BIN_TO_NUM Functions 5-25 CREATE DIRECTORY media_dir AS '/demo/schema/product_media'; INSERT INTO print_media (product_id, ad_id, ad_graphic) VALUES (3000, 31001, BFILENAME('MEDIA_DIR', 'modem_comp_ad.gif')); BIN_TO_NUM Syntax Purpose BIN_TO_NUM converts a bit vector to its equivalent number. Each argument to this function represents a bit in the bit vector. This function takes as arguments any numeric data type, or any nonnumeric data type that can be implicitly converted to NUMBER. Each expr must evaluate to 0 or 1. This function returns Oracle NUMBER. BIN_TO_NUM is useful in data warehousing applications for selecting groups of interest from a materialized view using grouping sets. Examples The following example converts a binary value to a number: SELECT BIN_TO_NUM(1,0,1,0) FROM DUAL; BIN_TO_NUM(1,0,1,0) ------------------- 10 The next example converts three values into a single binary value and uses BIN_TO_ NUM to convert that binary into a number. The example uses a PL/SQL declaration to specify the original values. These would normally be derived from actual data sources. SELECT order_status FROM orders WHERE order_id = 2441; ORDER_STATUS ------------ 5 DECLARE warehouse NUMBER := 1; ground NUMBER := 1; insured NUMBER := 1; result NUMBER; BEGIN SELECT BIN_TO_NUM(warehouse, ground, insured) INTO result FROM DUAL; See Also: ■ group_by_clause on page 19-27 for information on GROUPING SETS syntax ■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ■ Oracle Database Data Warehousing Guide for information on data aggregation in general BIN_TO_NUM ( expr , )
  • 200. BITAND 5-26 Oracle Database SQL Language Reference UPDATE orders SET order_status = result WHERE order_id = 2441; end; / PL/SQL procedure successfully completed. SELECT order_status FROM orders WHERE order_id = 2441; ORDER_STATUS ------------ 7 Refer to the examples for BITAND on page 5-26 for information on reversing this process, extracting multiple values from a single column value. BITAND Syntax Purpose The BITAND function treats its inputs and its output as vectors of bits; the output is the bitwise AND of the inputs. The types of expr1 and expr2 are NUMBER, and the result is of type NUMBER. If either argument to BITAND is NULL, the result is NULL. The arguments must be in the range -(2(n-1) ) .. ((2(n-1) )-1). If an argument is out of this range, the result is undefined. The result is computed in several steps. First, each argument A is replaced with the value SIGN(A)*FLOOR(ABS(A)). This conversion has the effect of truncating each argument towards zero. Next, each argument A (which must now be an integer value) is converted to an n-bit two's complement binary integer value. The two bit values are combined using a bitwise AND operation. Finally, the resulting n-bit two's complement value is converted back to NUMBER. Notes on the BITAND Function ■ The current implementation of BITAND defines n = 128. ■ PL/SQL supports an overload of BITAND for which the types of the inputs and of the result are all BINARY_INTEGER and for which n = 32. Examples The following example performs an AND operation on the numbers 6 (binary 1,1,0) and 3 (binary 0,1,1): SELECT BITAND(6,3) FROM DUAL; BITAND(6,3) ----------- 2 This is the same as the following example, which shows the binary values of 6 and 3. The BITAND function operates only on the significant digits of the binary values: SELECT BITAND( BIN_TO_NUM(1,1,0), BITAND ( expr1 , expr2 )
  • 201. CARDINALITY Functions 5-27 BIN_TO_NUM(0,1,1)) "Binary" FROM DUAL; Binary ---------- 2 Refer to the example for BIN_TO_NUM on page 5-25 for information on encoding multiple values in a single column value. The following example supposes that the order_status column of the sample table oe.orders encodes several choices as individual bits within a single numeric value. For example, an order still in the warehouse is represented by a binary value 001 (decimal 1). An order being sent by ground transportation is represented by a binary value 010 (decimal 2). An insured package is represented by a binary value 100 (decimal 4). The example uses the DECODE function to provide two values for each of the three bits in the order_status value, one value if the bit is turned on and one if it is turned off. SELECT order_id, customer_id, order_status, DECODE(BITAND(order_status, 1), 1, 'Warehouse', 'PostOffice') "Location", DECODE(BITAND(order_status, 2), 2, 'Ground', 'Air') "Method", DECODE(BITAND(order_status, 4), 4, 'Insured', 'Certified') "Receipt" FROM orders WHERE sales_rep_id = 160 ORDER BY order_id; ORDER_ID CUSTOMER_ID ORDER_STATUS Location Method Receipt ---------- ----------- ------------ ---------- ------ --------- 2455 145 7 Warehouse Ground Insured 2416 104 6 PostOffice Ground Insured 2419 107 3 Warehouse Ground Certified 2420 108 2 PostOffice Ground Certified 2423 145 3 Warehouse Ground Certified 2441 106 5 Warehouse Air Insured For the Location column, BITAND first compares order_status with 1 (binary 001). Only significant bit values are compared, so any binary value with a 1 in its rightmost bit (any odd number) will evaluate positively and return 1. Even numbers will return 0. The DECODE function compares the value returned by BITAND with 1. If they are both 1, then the location is "Warehouse". If they are different, then the location is "PostOffice". The Method and Receipt columns are calculated similarly. For Method, BITAND performs the AND operation on order_status and 2 (binary 010). For Receipt, BITAND performs the AND operation on order_status and 4 (binary 100). CARDINALITY Syntax CARDINALITY ( nested_table )
  • 202. CAST 5-28 Oracle Database SQL Language Reference Purpose CARDINALITY returns the number of elements in a nested table. The return type is NUMBER. If the nested table is empty, or is a null collection, then CARDINALITY returns NULL. Examples The following example shows the number of elements in the nested table column ad_ textdocs_ntab of the sample table pm.print_media: SELECT product_id, CARDINALITY(ad_textdocs_ntab) Cardinality FROM print_media ORDER BY product_id, cardinality; PRODUCT_ID CARDINALITY ---------- ----------- 2056 3 2268 3 3060 3 3106 3 CAST Syntax Purpose CAST converts one built-in data type or collection-typed value into another built-in data type or collection-typed value. CAST lets you convert built-in data types or collection-typed values of one type into another built-in data type or collection type. You can cast an unnamed operand (such as a date or the result set of a subquery) or a named collection (such as a varray or a nested table) into a type-compatible data type or named collection. The type_name must be the name of a built-in data type or collection type and the operand must be a built-in data type or must evaluate to a collection value. For the operand, expr can be either a built-in data type, a collection type, or an instance of an ANYDATA type. If expr is an instance of an ANYDATA type, then CAST tries to extract the value of the ANYDATA instance and return it if it matches the cast target type, otherwise, null will be returned. MULTISET informs Oracle Database to take the result set of the subquery and return a collection value. Table 5–1 shows which built-in data types can be cast into which other built-in data types. (CAST does not support LONG, LONG RAW, or the Oracle-supplied types.) CAST does not directly support any of the LOB data types. When you use CAST to convert a CLOB value into a character data type or a BLOB value into the RAW data type, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target data type. If the resulting value is larger than the target type, then the database returns an error. When you use CAST ... MULTISET to get a collection value, each select list item in the query passed to the CAST function is converted to the corresponding attribute type of the target collection element type. CAST ( expr MULTISET ( subquery ) AS type_name )
  • 203. CAST Functions 5-29 Note 1: Datetime/interval includes DATE, TIMESTAMP, TIMESTAMP WITH TIMEZONE, INTERVAL DAY TO SECOND, and INTERVAL YEAR TO MONTH. Note 2: You cannot cast a UROWID to a ROWID if the UROWID contains the value of a ROWID of an index-organized table. If you want to cast a named collection type into another named collection type, then the elements of both collections must be of the same type. If the result set of subquery can evaluate to multiple rows, then you must specify the MULTISET keyword. The rows resulting from the subquery form the elements of the collection value into which they are cast. Without the MULTISET keyword, the subquery is treated as a scalar subquery. Built-In Data Type Examples The following examples use the CAST function with scalar data types. The first example converts text to a timestamp value by applying the format model provided in the session parameter NLS_TIMESTAMP_FORMAT. If you want to avoid dependency on this NLS parameter, then you can use the TO_DATE as shown in the second example. SELECT CAST('22-OCT-1997' AS TIMESTAMP WITH LOCAL TIME ZONE) FROM dual; SELECT CAST(TO_DATE('22-Oct-1997', 'DD-Mon-YYYY') AS TIMESTAMP WITH LOCAL TIME ZONE) FROM dual; In the preceding example, TO_DATE converts from text to DATE, and CAST converts from DATE to TIMESTAMP WITH LOCAL TIME ZONE, interpreting the date in the session time zone (SESSIONTIMEZONE) SELECT product_id, CAST(ad_sourcetext AS VARCHAR2(30)) Text FROM print_media Table 5–1 Casting Built-In Data Types from BINARY_ FLOAT, BINARY_ DOUBLE from CHAR, VARCHAR2 from NUMBER from DATETIME / INTERVAL (Note 1) from RAW from ROWID, UROWID (Note 2) from NCHAR, NVARCHAR2 to BINARY_FLOAT, BINARY_DOUBLE X X X -- -- -- X to CHAR, VARCHAR2 X X X X X X -- to NUMBER X X X -- -- -- X to DATE, TIMESTAMP, INTERVAL -- X -- X -- -- -- to RAW -- X -- -- X -- -- to ROWID, UROWID -- X -- -- -- Xa -- to NCHAR, NVARCHAR2 X -- X X X X X See Also: "Implicit Data Conversion" on page 3-40 for information on how Oracle Database implicitly converts collection type data into character data and "Security Considerations for Data Conversion" on page 3-44
  • 204. CAST 5-30 Oracle Database SQL Language Reference ORDER BY product_id, text; Collection Examples The CAST examples that follow build on the cust_address_typ found in the sample order entry schema, oe. CREATE TYPE address_book_t AS TABLE OF cust_address_typ; / CREATE TYPE address_array_t AS VARRAY(3) OF cust_address_typ; / CREATE TABLE cust_address ( custno NUMBER, street_address VARCHAR2(40), postal_code VARCHAR2(10), city VARCHAR2(30), state_province VARCHAR2(10), country_id CHAR(2)); CREATE TABLE cust_short (custno NUMBER, name VARCHAR2(31)); CREATE TABLE states (state_id NUMBER, addresses address_array_t); This example casts a subquery: SELECT s.custno, s.name, CAST(MULTISET(SELECT ca.street_address, ca.postal_code, ca.city, ca.state_province, ca.country_id FROM cust_address ca WHERE s.custno = ca.custno) AS address_book_t) FROM cust_short s ORDER BY s.custno, s.name; CAST converts a varray type column into a nested table: SELECT CAST(s.addresses AS address_book_t) FROM states s WHERE s.state_id = 111; The following objects create the basis of the example that follows: CREATE TABLE projects (employee_id NUMBER, project_name VARCHAR2(10)); CREATE TABLE emps_short (employee_id NUMBER, last_name VARCHAR2(10)); CREATE TYPE project_table_typ AS TABLE OF VARCHAR2(10); / The following example of a MULTISET expression uses these objects: SELECT e.last_name, CAST(MULTISET(SELECT p.project_name FROM projects p WHERE p.employee_id = e.employee_id ORDER BY p.project_name) AS project_table_typ) FROM emps_short e
  • 205. CHARTOROWID Functions 5-31 ORDER BY e.last_name; CEIL Syntax Purpose CEIL returns smallest integer greater than or equal to n. The number n can always be written as the difference of an integer k and a positive fraction f such that 0 <= f < 1 and n = k - f. The value of CEIL is the integer k. Thus, the value of CEIL is n itself if and only if n is precisely an integer. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. Examples The following example returns the smallest integer greater than or equal to the order total of a specified order: SELECT order_total, CEIL(order_total) FROM orders WHERE order_id = 2434; ORDER_TOTAL CEIL(ORDER_TOTAL) ----------- ----------------- 268651.8 268652 CHARTOROWID Syntax Purpose CHARTOROWID converts a value from CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to ROWID data type. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example converts a character rowid representation to a rowid. (The actual rowid is different for each database instance.) SELECT last_name FROM employees See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and FLOOR on page 5-80 See Also: "Data Type Comparison Rules" on page 3-37 for more information. CEIL ( n ) CHARTOROWID ( char )
  • 206. CHR 5-32 Oracle Database SQL Language Reference WHERE ROWID = CHARTOROWID('AAAFd1AAFAAAABSAA/'); LAST_NAME ------------------------- Greene CHR Syntax Purpose CHR returns the character having the binary equivalent to n as a VARCHAR2 value in either the database character set or, if you specify USING NCHAR_CS, the national character set. For single-byte character sets, if n > 256, then Oracle Database returns the binary equivalent of n mod 256. For multibyte character sets, n must resolve to one entire code point. Invalid code points are not validated, and the result of specifying invalid code points is indeterminate. This function takes as an argument a NUMBER value, or any value that can be implicitly converted to NUMBER, and returns a character. Examples The following example is run on an ASCII-based machine with the database character set defined as WE8ISO8859P1: SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL; Dog --- CAT To produce the same results on an EBCDIC-based machine with the WE8EBCDIC1047 character set, the preceding example would have to be modified as follows: SELECT CHR(195)||CHR(193)||CHR(227) "Dog" FROM DUAL; Dog --- CAT Note: Use of the CHR function (either with or without the optional USING NCHAR_CS clause) results in code that is not portable between ASCII- and EBCDIC-based machine architectures. See Also: NCHR on page 5-114 and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion CHR ( n USING NCHAR_CS )
  • 207. CLUSTER_ID Functions 5-33 For multibyte character sets, this sort of concatenation gives different results. For example, given a multibyte character whose hexadecimal value is a1a2 (a1 representing the first byte and a2 the second byte), you must specify for n the decimal equivalent of 'a1a2', or 41378: SELECT CHR(41378) FROM DUAL; You cannot specify the decimal equivalent of a1 concatenated with the decimal equivalent of a2, as in the following example: SELECT CHR(161)||CHR(162) FROM DUAL; However, you can concatenate whole multibyte code points, as in the following example, which concatenates the multibyte characters whose hexadecimal values are a1a2 and a1a3: SELECT CHR(41378)||CHR(41379) FROM DUAL; The following example assumes that the national character set is UTF16: SELECT CHR (196 USING NCHAR_CS) FROM DUAL; CH -- Ä CLUSTER_ID Syntax mining_attribute_clause::= Purpose This function is for use with clustering models that have been created using the DBMS_ DATA_MINING package or with the Oracle Data Mining Java API. It returns the cluster identifier of the predicted cluster with the highest probability for the set of predictors specified in the mining_attribute_clause. The value returned is an Oracle NUMBER. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. CLUSTER_ID ( schema . model mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 208. CLUSTER_PROBABILITY 5-34 Oracle Database SQL Language Reference Examples The following example lists the clusters into which customers of a given dataset have been grouped. This example, and the prerequisite data mining operations, including the creation of the dm_sh_clus_sample model and the dm_sh_sample_apply_prepared view, can be found in the demo file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT CLUSTER_ID(km_sh_clus_sample USING *) AS clus, COUNT(*) AS cnt FROM km_sh_sample_apply_prepared GROUP BY CLUSTER_ID(km_sh_clus_sample USING *) ORDER BY cnt DESC; CLUS CNT ---------- ---------- 2 580 10 199 6 185 8 115 12 98 16 82 19 81 15 68 18 65 14 27 10 rows selected. CLUSTER_PROBABILITY Syntax See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ PREDICTION on page 5-139 CLUSTER_PROBABILITY ( schema . model , cluster_id mining_attribute_clause )
  • 209. CLUSTER_PROBABILITY Functions 5-35 mining_attribute_clause::= Purpose This function is for use with clustering models that have been created with the DBMS_ DATA_MINING package or with the Oracle Data Mining Java API. It returns a measure of the degree of confidence of membership of an input row in a cluster associated with the specified model. ■ For cluster_id, specify the identifier of the cluster in the model. The function returns the probability for the specified cluster. If you omit this clause, then the function returns the probability associated with the best predicted cluster. You can use the form without cluster_id in conjunction with the CLUSTER_ID function to obtain the best predicted pair of cluster ID and probability. ■ The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140 Examples The following example determines the ten most representative customers, based on likelihood, in cluster 2. This example, and the prerequisite data mining operations, including the creation of the dm_sh_clus_sample model and the dm_sh_sample_apply_prepared view, can be found in the demo file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT * FROM (SELECT cust_id, CLUSTER_PROBABILITY(km_sh_clus_sample, 2 USING *) prob FROM km_sh_sample_apply_prepared ORDER BY prob DESC) WHERE ROWNUM < 11; CUST_ID PROB See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ CLUSTER_ID on page 5-33 and PREDICTION on page 5-139 for information on related data mining functions USING * schema . table . * expr AS alias ,
  • 210. CLUSTER_SET 5-36 Oracle Database SQL Language Reference ---------- ------ 100052 .9993 100962 .9993 101208 .9993 100281 .9993 100012 .9993 101009 .9992 100173 .9992 101176 .9991 100672 .9991 101420 .9991 10 rows selected. CLUSTER_SET Syntax mining_attribute_clause::= Purpose This function is for use with clustering models that have been created with the DBMS_ DATA_MINING package or with the Oracle Data Mining Java API. It returns a varray of objects containing all possible clusters that a given row belongs to. Each object in the varray is a pair of scalar values containing the cluster ID and the cluster probability. The object fields are named CLUSTER_ID and PROBABILITY, and both are Oracle NUMBER. ■ For the optional topN argument, specify a positive integer. Doing so restricts the set of predicted clusters to those that have one of the top N probability values. If you omit topN or set it to NULL, then all clusters are returned in the collection. If multiple clusters are tied for the Nth value, the database still returns only N values. ■ For the optional cutoff argument, specify a positive integer to restrict the returned clusters to those with a probability greater than or equal to the specified cutoff. You can filter only by cutoff by specifying NULL for topN and the desired cutoff value for cutoff. You can specify topN and cutoff together to restrict the returned clusters to those that are in the top N and have a probability that passes the threshold. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. CLUSTER_SET ( schema . model , topN , cutoff mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 211. CLUSTER_SET Functions 5-37 Examples The following example lists the most relevant attributes (with confidence > 55%) of each cluster to which customer 101362 belongs with > 20% likelihood. This example, and the prerequisite data mining operations, including the creation of the dm_sh_clus_sample model and the views and type, can be found in the demo file $ORACLE_HOME/rdbms/demo/dmkmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. WITH clus_tab AS ( SELECT id, A.attribute_name aname, A.conditional_operator op, NVL(A.attribute_str_value, ROUND(DECODE(A.attribute_name, N.col, A.attribute_num_value * N.scale + N.shift, A.attribute_num_value),4)) val, A.attribute_support support, A.attribute_confidence confidence FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_KM('km_sh_clus_sample')) T, TABLE(T.rule.antecedent) A, km_sh_sample_norm N WHERE A.attribute_name = N.col (+) AND A.attribute_confidence > 0.55 ), clust AS ( SELECT id, CAST(COLLECT(Cattr(aname, op, TO_CHAR(val), support, confidence)) AS Cattrs) cl_attrs FROM clus_tab GROUP BY id ), custclus AS ( SELECT T.cust_id, S.cluster_id, S.probability FROM (SELECT cust_id, CLUSTER_SET(km_sh_clus_sample, NULL, 0.2 USING *) pset FROM km_sh_sample_apply_prepared WHERE cust_id = 101362) T, TABLE(T.pset) S ) SELECT A.probability prob, A.cluster_id cl_id, B.attr, B.op, B.val, B.supp, B.conf FROM custclus A, (SELECT T.id, C.* FROM clust T, TABLE(T.cl_attrs) C) B WHERE A.cluster_id = B.id ORDER BY prob DESC, cl_id ASC, conf DESC, attr ASC, val ASC; See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions
  • 212. COALESCE 5-38 Oracle Database SQL Language Reference PROB CL_ID ATTR OP VAL SUPP CONF ------- ---------- --------------- --- --------------- ---------- ------- .7873 8 HOUSEHOLD_SIZE IN 9+ 126 .7500 .7873 8 CUST_MARITAL_ST IN Divorc. 118 .6000 ATUS .7873 8 CUST_MARITAL_ST IN NeverM 118 .6000 ATUS .7873 8 CUST_MARITAL_ST IN Separ. 118 .6000 ATUS .7873 8 CUST_MARITAL_ST IN Widowed 118 .6000 ATUS .2016 6 AGE >= 17 152 .6667 .2016 6 AGE <= 31.6 152 .6667 .2016 6 CUST_MARITAL_ST IN NeverM 168 .6667 ATUS 8 rows selected. COALESCE Syntax Purpose COALESCE returns the first non-null expr in the expression list. You must specify at least two expressions. If all occurrences of expr evaluate to null, then the function returns null. Oracle Database uses short-circuit evaluation. The database evaluates each expr value and determines whether it is NULL, rather than evaluating all of the expr values before determining whether any of them is NULL. If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. This function is a generalization of the NVL function. You can also use COALESCE as a variety of the CASE expression. For example, COALESCE (expr1, expr2) is equivalent to: CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence COALESCE ( expr , )
  • 213. COLLECT Functions 5-39 Similarly, COALESCE (expr1, expr2, ..., exprn), for n>=3 is equivalent to: CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE COALESCE (expr2, ..., exprn) END Examples The following example uses the sample oe.product_information table to organize a clearance sale of products. It gives a 10% discount to all products with a list price. If there is no list price, then the sale price is the minimum price. If there is no minimum price, then the sale price is "5": SELECT product_id, list_price, min_price, COALESCE(0.9*list_price, min_price, 5) "Sale" FROM product_information WHERE supplier_id = 102050 ORDER BY product_id; PRODUCT_ID LIST_PRICE MIN_PRICE Sale ---------- ---------- ---------- ---------- 1769 48 43.2 1770 73 73 2378 305 247 274.5 2382 850 731 765 3355 5 COLLECT Syntax Purpose COLLECT is an aggregate function that takes as its argument a column of any type and creates a nested table of the input type out of the rows selected. To get accurate results from this function you must use it within a CAST function. If column is itself a collection, then the output of COLLECT is a nested table of collections. If column is of a user-defined type, then column must have a MAP or ORDER method defined on it in order for you to use the optional DISTINCT, UNIQUE and ORDER BY clauses. Examples The following example creates a nested table from the varray column of phone numbers in the sample table oe.customers: CREATE TYPE phone_book_t AS TABLE OF phone_list_typ; See Also: NVL on page 5-126 and "CASE Expressions" on page 6-5 See Also: CAST on page 5-28 and "Aggregate Functions" on page 5-9 COLLECT ( DISTINCT UNIQUE column ORDER BY expr )
  • 214. COMPOSE 5-40 Oracle Database SQL Language Reference / SELECT CAST(COLLECT(phone_numbers) AS phone_book_t) Phone_Book FROM customers ORDER BY phone_book; COMPOSE Syntax Purpose COMPOSE takes as its argument a string, or an expression that resolves to a string, in any data type, and returns a Unicode string in the same character set as the input. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. For example, an o code point qualified by an umlaut code point will be returned as the o-umlaut code point. COMPOSE returns the string in NFC normal form. For a more exclusive setting, you can first call DECOMPOSE with the CANONICAL setting and then COMPOSE. This combination returns the string in NFKC normal form. CLOB and NCLOB values are supported through implicit conversion. If char is a character LOB value, then it is converted to a VARCHAR value before the COMPOSE operation. The operation will fail if the size of the LOB value exceeds the supported length of the VARCHAR in the particular development environment. Examples The following example returns the o-umlaut code point: SELECT COMPOSE ( 'o' || UNISTR('0308') ) FROM DUAL; CO -- ö CONCAT Syntax Purpose CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string See Also: ■ Oracle Database Globalization Support Guide for information on Unicode character sets and character semantics ■ DECOMPOSE on page 5-59 See Also: UNISTR on page 5-239 COMPOSE ( char ) CONCAT ( char1 , char2 )
  • 215. CONVERT Functions 5-41 returned is in the same character set as char1. Its data type depends on the data types of the arguments. In concatenations of two different data types, Oracle Database returns the data type that results in a lossless conversion. Therefore, if one of the arguments is a LOB, then the returned value is a LOB. If one of the arguments is a national data type, then the returned value is a national data type. For example: ■ CONCAT(CLOB, NCLOB) returns NCLOB ■ CONCAT(NCLOB, NCHAR) returns NCLOB ■ CONCAT(NCLOB, CHAR) returns NCLOB ■ CONCAT(NCHAR, CLOB) returns NCLOB This function is equivalent to the concatenation operator (||). Examples This example uses nesting to concatenate three character strings: SELECT CONCAT(CONCAT(last_name, '''s job category is '), job_id) "Job" FROM employees WHERE employee_id = 152 ORDER BY "Job"; Job ------------------------------------------------------ Hall's job category is SA_REP CONVERT Syntax Purpose CONVERT converts a character string from one character set to another. ■ The char argument is the value to be converted. It can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ The dest_char_set argument is the name of the character set to which char is converted. ■ The source_char_set argument is the name of the character set in which char is stored in the database. The default value is the database character set. The return value for CHAR and VARCHAR2 is VARCHAR2. For NCHAR and NVARCHAR2, it is NVARCHAR2. For CLOB, it is CLOB, and for NCLOB, it is NCLOB. Both the destination and source character set arguments can be either literals or columns containing the name of the character set. For complete correspondence in character conversion, it is essential that the destination character set contains a representation of all the characters defined in the See Also: "Concatenation Operator" on page 4-4 for information on the CONCAT operator CONVERT ( char , dest_char_set , source_char_set )
  • 216. CONVERT 5-42 Oracle Database SQL Language Reference source character set. Where a character does not exist in the destination character set, a replacement character appears. Replacement characters can be defined as part of a character set definition. Examples The following example illustrates character set conversion by converting a Latin-1 string to ASCII. The result is the same as importing the same string from a WE8ISO8859P1 database to a US7ASCII database. SELECT CONVERT('Ä Ê Í Õ Ø A B C D E ', 'US7ASCII', 'WE8ISO8859P1') FROM DUAL; CONVERT('ÄÊÍÕØABCDE' --------------------- A E I ? ? A B C D E ? Common character sets include: ■ US7ASCII: US 7-bit ASCII character set ■ WE8ISO8859P1: ISO 8859-1 West European 8-bit character set ■ EE8MSWIN1250: Microsoft Windows East European Code Page 1250 ■ WE8MSWIN1252: Microsoft Windows West European Code Page 1252 ■ WE8EBCDIC1047: IBM West European EBCDIC Code Page 1047 ■ JA16SJISTILDE: Japanese Shift-JIS Character Set, compatible with MS Code Page 932 ■ ZHT16MSWIN950: Microsoft Windows Traditional Chinese Code Page 950 ■ UTF8: Unicode 3.0 Universal character set CESU-8 encoding form ■ AL32UTF8: Unicode 5.0 Universal character set UTF-8 encoding form You can query the V$NLS_VALID_VALUES view to get a listing of valid character sets, as follows: SELECT * FROM V$NLS_VALID_VALUES WHERE parameter = 'CHARACTERSET' Note: Oracle discourages the use of the CONVERT function in the current Oracle Database release. The return value of CONVERT has a character data type, so it should be either in the database character set or in the national character set, depending on the data type. Any dest_char_set that is not one of these two character sets is unsupported. The char argument and the source_char_set have the same requirements. Therefore, the only practical use of the function is to correct data that has been stored in a wrong character set. Values that are in neither the database nor the national character set should be processed and stored as RAW or BLOB. Procedures in the PL/SQL packages UTL_RAW and UTL_I18N—for example, UTL_ RAW.CONVERT—allow limited processing of such values. Procedures accepting RAW argument in the packages UTL_FILE, UTL_TCP, UTL_ HTTP, and UTL_SMTP can be used to output the processed data.
  • 217. CORR Functions 5-43 CORR Syntax Purpose CORR returns the coefficient of correlation of a set of number pairs. You can use it as an aggregate or analytic function. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Oracle Database applies the function to the set of (expr1, expr2) after eliminating the pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation: COVAR_POP(expr1, expr2) / (STDDEV_POP(expr1) * STDDEV_POP(expr2)) The function returns a value of type NUMBER. If the function is applied to an empty set, then it returns null. Aggregate Example The following example calculates the coefficient of correlation between the list prices and minimum prices of products by weight class in the sample table oe.product_ information: SELECT weight_class, CORR(list_price, min_price) "Correlation" See Also: Oracle Database Globalization Support Guide for information on supported character sets and Oracle Database Reference for information on the V$NLS_VALID_VALUES view See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence Note: The CORR function calculates the Pearson's correlation coefficient, which requires numeric expressions as arguments. Oracle also provides the CORR_S (Spearman's rho coefficient) and CORR_K (Kendall's tau-b coefficient) to support nonparametric or rank correlation. See Also: "Aggregate Functions" on page 5-9, "About SQL Expressions" on page 6-1 for information on valid forms of expr, and CORR_* on page 5-44 and CORR_S on page 5-45 CORR ( expr1 , expr2 ) OVER ( analytic_clause )
  • 218. CORR_* 5-44 Oracle Database SQL Language Reference FROM product_information GROUP BY weight_class ORDER BY weight_class, "Correlation"; WEIGHT_CLASS Correlation ------------ ----------- 1 .999149795 2 .999022941 3 .998484472 4 .999359909 5 .999536087 Analytic Example The following example shows the correlation between duration at the company and salary by the employee's position. The result set shows the same correlation for each employee in a given job: SELECT employee_id, job_id, TO_CHAR((SYSDATE - hire_date) YEAR TO MONTH ) "Yrs-Mns", salary, CORR(SYSDATE-hire_date, salary) OVER(PARTITION BY job_id) AS "Correlation" FROM employees WHERE department_id in (50, 80) ORDER BY job_id, employee_id; EMPLOYEE_ID JOB_ID Yrs-Mns SALARY Correlation ----------- ---------- ------- ---------- ----------- 145 SA_MAN +04-09 14000 .912385598 146 SA_MAN +04-06 13500 .912385598 147 SA_MAN +04-04 12000 .912385598 148 SA_MAN +01-08 11000 .912385598 149 SA_MAN +01-05 10500 .912385598 150 SA_REP +04-05 10000 .80436755 151 SA_REP +04-03 9500 .80436755 152 SA_REP +03-10 9000 .80436755 153 SA_REP +03-03 8000 .80436755 154 SA_REP +02-07 7500 .80436755 155 SA_REP +01-07 7000 .80436755 ... CORR_* The CORR_* functions are: ■ CORR_S ■ CORR_K
  • 219. CORR_* Functions 5-45 Syntax correlation::= Purpose The CORR function (see CORR on page 5-43) calculates the Pearson's correlation coefficient and requires numeric expressions as input. The CORR_* functions support nonparametric or rank correlation. They let you find correlations between expressions that are ordinal scaled (where ranking of the values is possible). Correlation coefficients take on a value ranging from -1 to 1, where 1 indicates a perfect relationship, -1 a perfect inverse relationship (when one variable increases as the other decreases), and a value close to 0 means no relationship. These functions takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, makes the calculation, and returns NUMBER. expr1 and expr2 are the two variables being analyzed. The third argument is a return value of type VARCHAR2. If you omit the third argument, then the default is COEFFICIENT. The meaning of the return values is shown in the table that follows: CORR_S CORR_S calculates the Spearman's rho correlation coefficient. The input expressions should be a set of (xi, yi) pairs of observations. The function first replaces each value with a rank. Each value of xi is replaced with its rank among all the other xis in the sample, and each value of yi is replaced with its rank among all the other yis. Thus, each xi and yi take on a value from 1 to n, where n is the total number of pairs of See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence Table 5–2 CORR_* Return Values Return Value Meaning COEFFICIENT Coefficient of correlation ONE_SIDED_SIG Positive one-tailed significance of the correlation ONE_SIDED_SIG_POS Same as ONE_SIDED_SIG ONE_SIDED_SIG_NEG Negative one-tailed significance of the correlation TWO_SIDED_SIG Two-tailed significance of the correlation CORR_K CORR_S ( expr1 , expr2 , COEFFICIENT ONE_SIDED_SIG ONE_SIDED_SIG_POS ONE_SIDED_SIG_NEG TWO_SIDED_SIG )
  • 220. CORR_K 5-46 Oracle Database SQL Language Reference values. Ties are assigned the average of the ranks they would have had if their values had been slightly different. Then the function calculates the linear correlation coefficient of the ranks. CORR_S Example Using Spearman's rho correlation coefficient, the following example derives a coefficient of correlation for each of two different comparisons -- salary and commission_pct, and salary and employee_id: SELECT COUNT(*) count, CORR_S(salary, commission_pct) commission, CORR_S(salary, employee_id) empid FROM employees; COUNT COMMISSION EMPID ---------- ---------- ---------- 107 .735837022 -.04482358 CORR_K CORR_K calculates the Kendall's tau-b correlation coefficient. As for CORR_S, the input expressions are a set of (xi, yi) pairs of observations. To calculate the coefficient, the function counts the number of concordant and discordant pairs. A pair of observations is concordant if the observation with the larger x also has a larger value of y. A pair of observations is discordant if the observation with the larger x has a smaller y. The significance of tau-b is the probability that the correlation indicated by tau-b was due to chance—a value of 0 to 1. A small value indicates a significant correlation for positive values of tau-b (or anticorrelation for negative values of tau-b). CORR_K Example Using Kendall's tau-b correlation coefficient, the following example determines whether a correlation exists between an employee's salary and commission percent: SELECT CORR_K(salary, commission_pct, 'COEFFICIENT') coefficient, CORR_K(salary, commission_pct, 'TWO_SIDED_SIG') two_sided_p_value FROM hr.employees; COEFFICIENT TWO_SIDED_P_VALUE ----------- ----------------- .603079768 3.4702E-07 COS Syntax Purpose COS returns the cosine of n (an angle expressed in radians). This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion COS ( n )
  • 221. COUNT Functions 5-47 Examples The following example returns the cosine of 180 degrees: SELECT COS(180 * 3.14159265359/180) "Cosine of 180 degrees" FROM DUAL; Cosine of 180 degrees --------------------- -1 COSH Syntax Purpose COSH returns the hyperbolic cosine of n. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the hyperbolic cosine of zero: SELECT COSH(0) "Hyperbolic cosine of 0" FROM DUAL; Hyperbolic cosine of 0 ---------------------- 1 COUNT Syntax Purpose COUNT returns the number of rows returned by the query. You can use it as an aggregate or analytic function. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions COSH ( n ) COUNT ( * DISTINCT ALL expr ) OVER ( analytic_clause )
  • 222. COUNT 5-48 Oracle Database SQL Language Reference If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed. If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr. If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls. COUNT never returns null. Aggregate Examples The following examples use COUNT as an aggregate function: SELECT COUNT(*) "Total" FROM employees; Total ---------- 107 SELECT COUNT(*) "Allstars" FROM employees WHERE commission_pct > 0; Allstars --------- 35 SELECT COUNT(commission_pct) "Count" FROM employees; Count ---------- 35 SELECT COUNT(DISTINCT manager_id) "Managers" FROM employees; Managers ---------- 18 Analytic Example The following example calculates, for each employee in the employees table, the moving count of employees earning salaries in the range 50 less than through 150 greater than the employee's salary. SELECT last_name, salary, COUNT(*) OVER (ORDER BY salary RANGE BETWEEN 50 PRECEDING AND 150 FOLLOWING) AS mov_count FROM employees ORDER BY last_name, salary, COUNT(*); LAST_NAME SALARY MOV_COUNT ------------------------- ---------- ---------- Olson 2100 3 Markle 2200 2 Philtanker 2200 2 Landry 2400 8 Gee 2400 8 Colmenares 2500 10 Marlow 2500 10 See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9
  • 223. COVAR_POP Functions 5-49 Patel 2500 10 . . . COVAR_POP Syntax Purpose COVAR_POP returns the population covariance of a set of number pairs. You can use it as an aggregate or analytic function. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Oracle Database applies the function to the set of (expr1, expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation: (SUM(expr1 * expr2) - SUM(expr2) * SUM(expr1) / n) / n where n is the number of (expr1, expr2) pairs where neither expr1 nor expr2 is null. The function returns a value of type NUMBER. If the function is applied to an empty set, then it returns null. Aggregate Example The following example calculates the population covariance and sample covariance for time employed (SYSDATE - hire_date) and salary using the sample table hr.employees: SELECT job_id, COVAR_POP(SYSDATE-hire_date, salary) AS covar_pop, COVAR_SAMP(SYSDATE-hire_date, salary) AS covar_samp FROM employees WHERE department_id in (50, 80) GROUP BY job_id ORDER BY job_id, covar_pop, covar_samp; JOB_ID COVAR_POP COVAR_SAMP ---------- ----------- ----------- SA_MAN 660700 825875 See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 COVAR_POP ( expr1 , expr2 ) OVER ( analytic_clause )
  • 224. COVAR_SAMP 5-50 Oracle Database SQL Language Reference SA_REP 579988.466 600702.34 SH_CLERK 212432.5 223613.158 ST_CLERK 176577.25 185870.789 ST_MAN 436092 545115 Analytic Example The following example calculates cumulative sample covariance of the list price and minimum price of the products in the sample schema oe: SELECT product_id, supplier_id, COVAR_POP(list_price, min_price) OVER (ORDER BY product_id, supplier_id) AS CUM_COVP, COVAR_SAMP(list_price, min_price) OVER (ORDER BY product_id, supplier_id) AS CUM_COVS FROM product_information p WHERE category_id = 29 ORDER BY product_id, supplier_id; PRODUCT_ID SUPPLIER_ID CUM_COVP CUM_COVS ---------- ----------- ---------- ---------- 1774 103088 0 1775 103087 1473.25 2946.5 1794 103096 1702.77778 2554.16667 1825 103093 1926.25 2568.33333 2004 103086 1591.4 1989.25 2005 103086 1512.5 1815 2416 103088 1475.97959 1721.97619 . . . COVAR_SAMP Syntax Purpose COVAR_SAMP returns the sample covariance of a set of number pairs. You can use it as an aggregate or analytic function. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence COVAR_SAMP ( expr1 , expr2 ) OVER ( analytic_clause )
  • 225. CUBE_TABLE Functions 5-51 Oracle Database applies the function to the set of (expr1, expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation: (SUM(expr1 * expr2) - SUM(expr1) * SUM(expr2) / n) / (n-1) where n is the number of (expr1, expr2) pairs where neither expr1 nor expr2 is null. The function returns a value of type NUMBER. If the function is applied to an empty set, then it returns null. Aggregate Example Refer to the aggregate example for COVAR_POP on page 5-49. Analytic Example Refer to the analytic example for COVAR_POP on page 5-49. CUBE_TABLE Syntax Purpose CUBE_TABLE extracts data from a cube or dimension and returns it in the two-dimensional format of a relational table, which can be used by SQL-based applications. The function takes a single VARCHAR2 argument. The optional hierarchy clause enables you to specify a dimension hierarchy. A cube can have multiple hierarchy clauses, one for each dimension. You can generate these different types of tables: ■ A cube table contains a key column for each dimension and a column for each measure and calculated measure in the cube. To create a cube table, you can specify the cube with or without a cube hierarchy clause. For a dimension with multiple hierarchies, this clause limits the return values to the dimension members and levels in the specified hierarchy. Without a hierarchy clause, all dimension members and all levels are included. See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 CUBE_TABLE ( ’ schema . cube HIERARCHY HRR dimension hierarchy schema . dimension HIERARCHY HRR dimension hierarchy ’ )
  • 226. CUBE_TABLE 5-52 Oracle Database SQL Language Reference ■ A dimension table contains a key column, and a column for each level and each attribute. All dimension members and all levels are included in the table. To create a dimension table, specify the dimension without a dimension hierarchy clause. ■ A hierarchy table contains all the columns of a dimension table plus a column for the parent member and a column for each source level. Any dimension members and levels that are not part of the named hierarchy are excluded from the table. To create a hierarchy table, specify the dimension with a dimension hierarchy clause. CUBE_TABLE is a table function and is always used in the context of a SELECT statement with this syntax: SELECT ... FROM TABLE(CUBE_TABLE('arg')); Examples The following SELECT statement generates a dimension table of CHANNEL in the GLOBAL schema. SELECT * FROM TABLE(CUBE_TABLE('global.channel')); DIM_KEY LEVEL_NAME LONG_DESCRIP SHORT_DESCRI TOTAL_CHANNEL_ID CHANNEL_ID -------- --------------- ------------ ------------ ---------------- ---------- 1 TOTAL_CHANNEL All Channels All Channels 1 2 CHANNEL Direct Sales Direct Sales 1 2 3 CHANNEL Catalog Catalog 1 3 4 CHANNEL Internet Internet 1 4 The next statement generates a cube table of UNITS_CUBE. It restricts the table to the MARKET_ROLLUP and CALENDAR hierarchies. SELECT * FROM TABLE(CUBE_TABLE( 'global.units_cube HIERARCHY customer market_rollup HIERARCHY time calendar')); SALES UNITS COST TIME CUSTOMER PRODUCT CHANNEL ---------- ---------- ---------- -------- -------- -------- -------- 134109248 330425 124918967 2 7 1 1 32275009.5 77425 30255208 10 7 1 1 10768750.7 25780 10058324.5 36 7 1 1 109261.64 278 101798.32 36 5 1 1 22371.47 53 20887.54 36 36 1 1 . . . See Also: Oracle OLAP User's Guide for information about dimensional objects and about the tables generated by CUBE_TABLE.
  • 227. CUME_DIST Functions 5-53 CUME_DIST Aggregate Syntax cume_dist_aggregate::= Analytic Syntax cume_dist_analytic::= Purpose CUME_DIST calculates the cumulative distribution of a value in a group of values. The range of values returned by CUME_DIST is >0 to <=1. Tie values always evaluate to the same cumulative distribution value. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, makes the calculation, and returns NUMBER. ■ As an aggregate function, CUME_DIST calculates, for a hypothetical row r identified by the arguments of the function and a corresponding sort specification, the relative position of row r among the rows in the aggregation group. Oracle makes this calculation as if the hypothetical row r were inserted into the group of rows to be aggregated over. The arguments of the function identify a single hypothetical row within each aggregate group. Therefore, they must all evaluate to constant expressions within each aggregate group. The constant argument expressions and the expressions in the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments must be the same and their types must be compatible. ■ As an analytic function, CUME_DIST computes the relative position of a specified value in a group of values. For a row r, assuming ascending ordering, the CUME_ See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence CUME_DIST ( expr , ) WITHIN GROUP ( ORDER BY expr DESC ASC NULLS FIRST LAST , ) CUME_DIST ( ) OVER ( query_partition_clause order_by_clause )
  • 228. CURRENT_DATE 5-54 Oracle Database SQL Language Reference DIST of r is the number of rows with values lower than or equal to the value of r, divided by the number of rows being evaluated (the entire query result set or a partition). Aggregate Example The following example calculates the cumulative distribution of a hypothetical employee with a salary of $15,500 and commission rate of 5% among the employees in the sample table oe.employees: SELECT CUME_DIST(15500, .05) WITHIN GROUP (ORDER BY salary, commission_pct) "Cume-Dist of 15500" FROM employees; Cume-Dist of 15500 ------------------ .972222222 Analytic Example The following example calculates the salary percentile for each employee in the purchasing division. For example, 40% of clerks have salaries less than or equal to Himuro. SELECT job_id, last_name, salary, CUME_DIST() OVER (PARTITION BY job_id ORDER BY salary) AS cume_dist FROM employees WHERE job_id LIKE 'PU%' ORDER BY job_id, last_name, salary, cume_dist; JOB_ID LAST_NAME SALARY CUME_DIST ---------- ------------------------- ---------- ---------- PU_CLERK Baida 2900 .8 PU_CLERK Colmenares 2500 .2 PU_CLERK Himuro 2600 .4 PU_CLERK Khoo 3100 1 PU_CLERK Tobias 2800 .6 PU_MAN Raphaely 11000 1 CURRENT_DATE Syntax Purpose CURRENT_DATE returns the current date in the session time zone, in a value in the Gregorian calendar of data type DATE. Examples The following example illustrates that CURRENT_DATE is sensitive to the session time zone: ALTER SESSION SET TIME_ZONE = '-5:0'; ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL; SESSIONTIMEZONE CURRENT_DATE CURRENT_DATE
  • 229. CURRENT_TIMESTAMP Functions 5-55 --------------- -------------------- -05:00 29-MAY-2000 13:14:03 ALTER SESSION SET TIME_ZONE = '-8:0'; SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL; SESSIONTIMEZONE CURRENT_DATE --------------- -------------------- -08:00 29-MAY-2000 10:14:33 CURRENT_TIMESTAMP Syntax Purpose CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of data type TIMESTAMP WITH TIME ZONE. The time zone offset reflects the current local time of the SQL session. If you omit precision, then the default is 6. The difference between this function and LOCALTIMESTAMP is that CURRENT_TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value while LOCALTIMESTAMP returns a TIMESTAMP value. In the optional argument, precision specifies the fractional second precision of the time value returned. Examples The following example illustrates that CURRENT_TIMESTAMP is sensitive to the session time zone: ALTER SESSION SET TIME_ZONE = '-5:0'; ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL; SESSIONTIMEZONE CURRENT_TIMESTAMP --------------- --------------------------------------------------- -05:00 04-APR-00 01.17.56.917550 PM -05:00 ALTER SESSION SET TIME_ZONE = '-8:0'; SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL; SESSIONTIMEZONE CURRENT_TIMESTAMP --------------- ---------------------------------------------------- -08:00 04-APR-00 10.18.21.366065 AM -08:00 When you use the CURRENT_TIMESTAMP with a format mask, take care that the format mask matches the value returned by the function. For example, consider the following table: CREATE TABLE current_test (col1 TIMESTAMP WITH TIME ZONE); The following statement fails because the mask does not include the TIME ZONE portion of the type returned by the function: See Also: LOCALTIMESTAMP on page 5-104 CURRENT_TIMESTAMP ( precision )
  • 230. CV 5-56 Oracle Database SQL Language Reference INSERT INTO current_test VALUES (TO_TIMESTAMP_TZ(CURRENT_TIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM')); The following statement uses the correct format mask to match the return type of CURRENT_TIMESTAMP: INSERT INTO current_test VALUES (TO_TIMESTAMP_TZ (CURRENT_TIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM TZH:TZM')); CV Syntax Purpose The CV function can be used only in the model_clause of a SELECT statement and then only on the right-hand side of a model rule. It returns the current value of a dimension column or a partitioning column carried from the left-hand side to the right-hand side of a rule. This function is used in the model_clause to provide relative indexing with respect to the dimension column. The return type is that of the data type of the dimension column. If you omit the argument, then it defaults to the dimension column associated with the relative position of the function within the cell reference. The CV function can be used outside a cell reference. In this case, dimension_column is required. Example The following example assigns the sum of the sales of the product represented by the current value of the dimension column (Mouse Pad or Standard Mouse) for years 1999 and 2000 to the sales of that product for year 2001: SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s[FOR prod IN ('Mouse Pad', 'Standard Mouse'), 2001] = s[CV( ), 1999] + s[CV( ), 2000] ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 3000.72 See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for the syntax and semantics CV ( dimension_column )
  • 231. DBTIMEZONE Functions 5-57 France Mouse Pad 2001 6679.41 France Standard Mouse 1998 2390.83 France Standard Mouse 1999 2280.45 France Standard Mouse 2000 1274.31 France Standard Mouse 2001 3554.76 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 7375.46 Germany Mouse Pad 2001 15721.9 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 2637.31 Germany Standard Mouse 2001 8900.45 16 rows selected. The preceding example requires the view sales_view_ref. Refer to "The MODEL clause: Examples" on page 19-45 to create this view. DATAOBJ_TO_PARTITION Syntax Purpose DATAOBJ_TO_PARTITION is useful only to Data Cartridge developers who are performing data maintenance or query operations on system-partitioned tables that are used to store domain index data. The DML or query operations are triggered by corresponding operations on the base table of the domain index. This function takes as arguments the name of the base table and the partition ID of the base table partition, both of which are passed to the function by the appropriate ODCIIndex method. The function returns the partition ID of the corresponding system-partitioned table, which can be used to perform the operation (DML or query) on that partition of the system-partitioned table. DBTIMEZONE Syntax Purpose DBTIMEZONE returns the value of the database time zone. The return type is a time zone offset (a character type in the format '[+|-]TZH:TZM') or a time zone region name, depending on how the user specified the database time zone value in the most recent CREATE DATABASE or ALTER DATABASE statement. See Also: Oracle Database Data Cartridge Developer's Guide for information on the use of this function, including examples DATAOBJ_TO_PARTITION ( table , partition_id ) DBTIMEZONE
  • 232. DECODE 5-58 Oracle Database SQL Language Reference Examples The following example assumes that the database time zone is set to UTC time zone: SELECT DBTIMEZONE FROM DUAL; DBTIME ------ +00:00 DECODE Syntax Purpose DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null. The arguments can be any of the numeric types (NUMBER, BINARY_FLOAT, or BINARY_DOUBLE) or character types. ■ If expr and search are character data, then Oracle compares them using nonpadded comparison semantics. expr, search, and result can be any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of VARCHAR2 data type and is in the same character set as the first result parameter. ■ If the first search-result pair are numeric, then Oracle compares all search-result expressions and the first expr to determine the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. The search, result, and default values can be derived from expressions. Oracle Database uses short-circuit evaluation. The database evaluates each search value only before comparing it to expr, rather than evaluating all search values before comparing any of them with expr. Consequently, Oracle never evaluates a search if a previous search is equal to expr. Oracle automatically converts expr and each search value to the data type of the first search value before comparing. Oracle automatically converts the return value to the same data type as the first result. If the first result has the data type CHAR or if the first result is null, then Oracle converts the return value to the data type VARCHAR2. In a DECODE function, Oracle considers two nulls to be equivalent. If expr is null, then Oracle returns the result of the first search that is also null. The maximum number of components in the DECODE function, including expr, searches, results, and default, is 255. DECODE ( expr , search , result , , default )
  • 233. DECOMPOSE Functions 5-59 Examples This example decodes the value warehouse_id. If warehouse_id is 1, then the function returns 'Southlake'; if warehouse_id is 2, then it returns 'San Francisco'; and so forth. If warehouse_id is not 1, 2, 3, or 4, then the function returns 'Non domestic'. SELECT product_id, DECODE (warehouse_id, 1, 'Southlake', 2, 'San Francisco', 3, 'New Jersey', 4, 'Seattle', 'Non domestic') "Location" FROM inventories WHERE product_id < 1775 ORDER BY product_id, "Location"; DECOMPOSE Syntax Purpose DECOMPOSE is valid only for Unicode characters. DECOMPOSE takes as its argument a string in any data type and returns a Unicode string after decomposition in the same character set as the input. For example, an o-umlaut code point will be returned as the "o" code point followed by an umlaut code point. ■ string can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ CANONICAL causes canonical decomposition, which allows recomposition (for example, with the COMPOSE function) to the original string. This is the default and returns the string in NFD normal form. ■ COMPATIBILITY causes decomposition in compatibility mode. In this mode, recomposition is not possible. This mode is useful, for example, when decomposing half-width and full-width katakana characters, where recomposition might not be desirable without external formatting or style information. It returns the string in NFKD normal form. See Also: ■ "Data Type Comparison Rules" on page 3-37 for information on comparison semantics ■ "Data Conversion" on page 3-40 for information on data type conversion in general ■ "Floating-Point Numbers" on page 3-12 for information on floating-point comparison semantics ■ "Implicit and Explicit Data Conversion" on page 3-40 for information on the drawbacks of implicit conversion DECOMPOSE ( string CANONICAL COMPATIBILITY )
  • 234. DELETEXML 5-60 Oracle Database SQL Language Reference CLOB and NCLOB values are supported through implicit conversion. If char is a character LOB value, then it is converted to a VARCHAR value before the COMPOSE operation. The operation will fail if the size of the LOB value exceeds the supported length of the VARCHAR in the particular development environment. Examples The following example decomposes the string "Châteaux" into its component code points: SELECT DECOMPOSE ('Châteaux') FROM DUAL; DECOMPOSE --------- Cha^teaux DELETEXML Syntax Purpose DELETEXML deletes the node or nodes matched by the XPath expression in the target XML. ■ XMLType_instance is an instance of XMLType. ■ The XPath_string is an Xpath expression indicating one or more nodes that are to be deleted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative path defaults to the root node. Any child nodes of the nodes specified by XPath_string are also deleted. ■ The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type VARCHAR2. Examples The following example removes the /Owner node from the warehouse_spec of one of the warehouses modified in the example for APPENDCHILDXML on page 5-19: UPDATE warehouses SET warehouse_spec = See Also: ■ Oracle Database Globalization Support Guide for information on Unicode character sets and character semantics ■ COMPOSE on page 5-40 Note: The results of this example can vary depending on the character set of your operating system. See Also: Oracle XML DB Developer's Guide for more information about this function DELETEXML ( XMLType_instance , XPath_string , namespace_string )
  • 235. DENSE_RANK Functions 5-61 DELETEXML(warehouse_spec, '/Warehouse/Building/Owner') WHERE warehouse_id = 2; SELECT warehouse_id, warehouse_spec FROM warehouses WHERE warehouse_id in (2,3); ID WAREHOUSE_SPEC ---------- ----------------------------------- 2 <?xml version="1.0"?> <Warehouse> <Building>Rented</Building> <Area>50000</Area> <Docks>1</Docks> <DockType>Side load</DockType> <WaterAccess>Y</WaterAccess> <RailAccess>N</RailAccess> <Parking>Lot</Parking> <VClearance>12 ft</VClearance> </Warehouse> 3 <?xml version="1.0"?> <Warehouse> <Building>Rented <Owner>Grandco</Owner> <Owner>ThirdOwner</Owner> <Owner>LesserCo</Owner> </Building> <Area>85700</Area> <DockType/> <WaterAccess>N</WaterAccess> <RailAccess>N</RailAccess> <Parking>Street</Parking> <VClearance>11.5 ft</VClearance> </Warehouse> DENSE_RANK Aggregate Syntax dense_rank_aggregate::= DENSE_RANK ( expr , ) WITHIN GROUP ( ORDER BY expr DESC ASC NULLS FIRST LAST , )
  • 236. DENSE_RANK 5-62 Oracle Database SQL Language Reference Analytic Syntax dense_rank_analytic::= Purpose DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1. The largest rank value is the number of unique values returned by the query. Rank values are not skipped in the event of ties. Rows with equal values for the ranking criteria receive the same rank. This function is useful for top-N and bottom-N reporting. This function accepts as arguments any numeric data type and returns NUMBER. ■ As an aggregate function, DENSE_RANK calculates the dense rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the order_by_clause of the aggregate match by position. Therefore, the number of arguments must be the same and types must be compatible. ■ As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_ exprs in the order_by_clause. Aggregate Example The following example computes the ranking of a hypothetical employee with the salary $15,500 and a commission of 5% in the sample table oe.employees: SELECT DENSE_RANK(15500, .05) WITHIN GROUP (ORDER BY salary DESC, commission_pct) "Dense Rank" FROM employees; Dense Rank ------------------- 3 Analytic Example The following statement selects the department name, employee name, and salary of all employees who work in the human resources or purchasing department, and then computes a rank for each unique salary in each of the two departments. The salaries that are equal receive the same rank. Compare this example with the example for RANK on page 5-153. SELECT d.department_name, e.last_name, e.salary, DENSE_RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary) AS drank FROM employees e, departments d WHERE e.department_id = d.department_id AND d.department_id IN ('30', '40') ORDER BY e.last_name, e.salary, d.department_name, drank; See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions DENSE_RANK ( ) OVER ( query_partition_clause order_by_clause )
  • 237. DEREF Functions 5-63 DEPARTMENT_NAME LAST_NAME SALARY DRANK c------------------------------ ------------------------- ---------- ---------- Purchasing Baida 2900 4 Purchasing Colmenares 2500 1 Purchasing Himuro 2600 2 Purchasing Khoo 3100 5 Human Resources Mavris 6500 1 Purchasing Raphaely 11000 6 Purchasing Tobias 2800 3 DEPTH Syntax Purpose DEPTH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the number of levels in the path specified by the UNDER_PATH condition with the same correlation variable. The correlation_integer can be any NUMBER integer. Use it to correlate this ancillary function with its primary condition if the statement contains multiple primary conditions. Values less than 1 are treated as 1. Examples The EQUALS_PATH and UNDER_PATH conditions can take two ancillary functions, DEPTH and PATH. The following example shows the use of both ancillary functions. The example assumes the existence of the XMLSchema warehouses.xsd (created in "Using XML in SQL Statements" on page F-8). SELECT PATH(1), DEPTH(2) FROM RESOURCE_VIEW WHERE UNDER_PATH(res, '/sys/schemas/OE', 1)=1 AND UNDER_PATH(res, '/sys/schemas/OE', 2)=1; PATH(1) DEPTH(2) -------------------------------- -------- /www.example.com 1 /www.example.com/xwarehouses.xsd 2 DEREF Syntax Purpose DEREF returns the object reference of argument expr, where expr must return a REF to an object. If you do not use this function in a query, then Oracle Database returns the object ID of the REF instead, as shown in the example that follows. See Also: EQUALS_PATH Condition on page 7-19, UNDER_PATH Condition on page 7-20, and the related function PATH on page 5-131 DEPTH ( correlation_integer ) DEREF ( expr )
  • 238. DUMP 5-64 Oracle Database SQL Language Reference Examples The sample schema oe contains an object type cust_address_typ. The "REF Constraint Examples" on page 8-25 create a similar type, cust_address_typ_new, and a table with one column that is a REF to the type. The following example shows how to insert into such a column and how to use DEREF to extract information from the column: INSERT INTO address_table VALUES ('1 First', 'G45 EU8', 'Paris', 'CA', 'US'); INSERT INTO customer_addresses SELECT 999, REF(a) FROM address_table a; SELECT address FROM customer_addresses ORDER BY address; ADDRESS -------------------------------------------------------------------------------- 000022020876B2245DBE325C5FE03400400B40DCB176B2245DBE305C5FE03400400B40DCB1 SELECT DEREF(address) FROM customer_addresses; DEREF(ADDRESS)(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) -------------------------------------------------------------------------------- CUST_ADDRESS_TYP('1 First', 'G45 EU8', 'Paris', 'CA', 'US') DUMP Syntax Purpose DUMP returns a VARCHAR2 value containing the data type code, length in bytes, and internal representation of expr. The returned result is always in the database character set. For the data type corresponding to each code, see Table 3–1, " Built-in Data Type Summary" on page 3-6. The argument return_fmt specifies the format of the return value and can have any of the following values: ■ 8 returns result in octal notation. ■ 10 returns result in decimal notation. ■ 16 returns result in hexadecimal notation. ■ 17 returns each byte printed as a character if and only if it can be interpreted as a printable character in the character set of the compiler—typically ASCII or EBCDIC. Some ASCII control characters may be printed in the form ^X as well. Otherwise the character is printed in hexidecimal notation. All NLS parameters are ignored. Do not depend on any particular output format for DUMP with return_fmt 17. See Also: MAKE_REF on page 5-107 DUMP ( expr , return_fmt , start_position , length )
  • 239. EMPTY_BLOB, EMPTY_CLOB Functions 5-65 By default, the return value contains no character set information. To retrieve the character set name of expr, add 1000 to any of the preceding format values. For example, a return_fmt of 1008 returns the result in octal and provides the character set name of expr. The arguments start_position and length combine to determine which portion of the internal representation to return. The default is to return the entire internal representation in decimal notation. If expr is null, then this function returns NULL. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following examples show how to extract dump information from a string expression and a column: SELECT DUMP('abc', 1016) FROM DUAL; DUMP('ABC',1016) ------------------------------------------ Typ=96 Len=3 CharacterSet=WE8DEC: 61,62,63 SELECT DUMP(last_name, 8, 3, 2) "OCTAL" FROM employees WHERE last_name = 'Hunold' ORDER BY employee_id; OCTAL ------------------------------------------------------------------- Typ=1 Len=6: 156,157 SELECT DUMP(last_name, 10, 3, 2) "ASCII" FROM employees WHERE last_name = 'Hunold' ORDER BY employee_id; ASCII -------------------------------------------------------------------- Typ=1 Len=6: 110,111 EMPTY_BLOB, EMPTY_CLOB Syntax empty_LOB::= See Also: "Data Type Comparison Rules" on page 3-37 for more information EMPTY_BLOB EMPTY_CLOB ( )
  • 240. EXISTSNODE 5-66 Oracle Database SQL Language Reference Purpose EMPTY_BLOB and EMPTY_CLOB return an empty LOB locator that can be used to initialize a LOB variable or, in an INSERT or UPDATE statement, to initialize a LOB column or attribute to EMPTY. EMPTY means that the LOB is initialized, but not populated with data. Restriction on LOB Locators You cannot use the locator returned from this function as a parameter to the DBMS_LOB package or the OCI. Examples The following example initializes the ad_photo column of the sample pm.print_ media table to EMPTY: UPDATE print_media SET ad_photo = EMPTY_BLOB(); EXISTSNODE Syntax Purpose EXISTSNODE determines whether traversal of an XML document using a specified path results in any nodes. It takes as arguments the XMLType instance containing an XML document and a VARCHAR2 XPath string designating a path. The optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath expression(s). The namespace_string argument defaults to the namespace of the root element. If you refer to any subelement in Xpath_string, then you must specify namespace_ string, and you must specify the "who" prefix in both of these arguments. The return value is NUMBER: ■ 0 if no nodes remain after applying the XPath traversal on the document ■ 1 if any nodes remain Note: An empty LOB is not the same as a null LOB, and an empty CLOB is not the same as a LOB containing a string of 0 length. For more information, see Oracle Database SecureFiles and Large Objects Developer's Guide. Note: The EXISTSNODE function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLEXISTS function instead. See XMLEXISTS on page 5-257 for more information. See Also: "Using XML in SQL Statements" on page F-8 for examples that specify namespace_string and use the "who" prefix. EXISTSNODE ( XMLType_instance , XPath_string , namespace_string )
  • 241. EXP Functions 5-67 Examples The following example tests for the existence of the /Warehouse/Dock node in the XML path of the warehouse_spec column of the sample table oe.warehouses: SELECT warehouse_id, warehouse_name FROM warehouses WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Docks') = 1 ORDER BY warehouse_id, warehouse_name; WAREHOUSE_ID WAREHOUSE_NAME ------------ ----------------------------------- 1 Southlake, Texas 2 San Francisco 4 Seattle, Washington EXP Syntax Purpose EXP returns e raised to the nth power, where e = 2.71828183 ... The function returns a value of the same type as the argument. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns e to the 4th power: SELECT EXP(4) "e to the 4th power" FROM DUAL; e to the 4th power ------------------ 54.59815 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion EXP ( n )
  • 242. EXTRACT (datetime) 5-68 Oracle Database SQL Language Reference EXTRACT (datetime) Syntax extract_datetime::= Purpose EXTRACT extracts and returns the value of a specified datetime field from a datetime or interval expression. The expr can be any expression that evaluates to a datetime or interval data type compatible with the requested field: ■ If YEAR or MONTH is requested, then expr must evaluate to an expression of data type DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, or INTERVAL YEAR TO MONTH. ■ If DAY is requested, then expr must evaluate to an expression of data type DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, or INTERVAL DAY TO SECOND. ■ If HOUR, MINUTE, or SECOND is requested, then expr must evaluate to an expression of data type TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, or INTERVAL DAY TO SECOND. DATE is not valid here, because Oracle Database treats it as ANSI DATE data type, which has no time fields. ■ If TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_ABBR, TIMEZONE_REGION, or TIMEZONE_OFFSET is requested, then expr must evaluate to an expression of data type TIMESTAMP WITH TIME ZONE or TIMESTAMP WITH LOCAL TIME ZONE. EXTRACT interprets expr as an ANSI datetime data type. For example, EXTRACT treats DATE not as legacy Oracle DATE but as ANSI DATE, without time elements. Therefore, you can extract only YEAR, MONTH, and DAY from a DATE value. Likewise, you can extract TIMEZONE_HOUR and TIMEZONE_MINUTE only from the TIMESTAMP WITH TIME ZONE data type. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value returned is a string containing the appropriate time zone region name or abbreviation. When you extract any of the other values, the value returned is an integer representing the datetime value in the Gregorian calendar. When extracting from a datetime with a time zone value, the value returned is in UTC. For a listing of time zone region names EXTRACT ( YEAR MONTH DAY HOUR MINUTE SECOND TIMEZONE_HOUR TIMEZONE_MINUTE TIMEZONE_REGION TIMEZONE_ABBR FROM expr )
  • 243. EXTRACT (datetime) Functions 5-69 and their corresponding abbreviations, query the V$TIMEZONE_NAMES dynamic performance view. This function can be very useful for manipulating datetime field values in very large tables, as shown in the first example below. Some combinations of datetime field and datetime or interval value expression result in ambiguity. In these cases, Oracle Database returns UNKNOWN (see the examples that follow for additional information). Examples The following example returns from the oe.orders table the number of orders placed in each month: SELECT EXTRACT(month FROM order_date) "Month", COUNT(order_date) "No. of Orders" FROM orders GROUP BY EXTRACT(month FROM order_date) ORDER BY "No. of Orders" DESC; Month No. of Orders ---------- ------------- 11 15 7 14 6 14 3 11 5 10 9 9 2 9 8 7 10 6 1 5 12 4 4 1 12 rows selected. The following example returns the year 1998. SELECT EXTRACT(YEAR FROM DATE '1998-03-07') FROM DUAL; Note: Time zone region names are needed by the daylight saving feature. These names are stored in two types of time zone files: one large and one small. One of these files is the default file, depending on your environment and the release of Oracle Database you are using. For more information regarding time zone files and names, see Oracle Database Globalization Support Guide. See Also: ■ Oracle Database Globalization Support Guide for a complete listing of the time zone region names in both files ■ "Datetime/Interval Arithmetic" on page 3-20 for a description of datetime_value_expr and interval_value_expr ■ Oracle Database Reference for information on the dynamic performance views
  • 244. EXTRACT (XML) 5-70 Oracle Database SQL Language Reference EXTRACT(YEARFROMDATE'1998-03-07') --------------------------------- 1998 The following example selects from the sample table hr.employees all employees who were hired after 2007: SELECT last_name, employee_id, hire_date FROM employees WHERE EXTRACT(YEAR FROM TO_DATE(hire_date, 'DD-MON-RR')) > 2007 ORDER BY hire_date; LAST_NAME EMPLOYEE_ID HIRE_DATE ------------------------- ----------- --------- Johnson 179 04-JAN-08 Grant 199 13-JAN-08 Marvins 164 24-JAN-08 . . . The following example results in ambiguity, so Oracle returns UNKNOWN: SELECT EXTRACT(TIMEZONE_REGION FROM TIMESTAMP '1999-01-01 10:00:00 -08:00') FROM DUAL; EXTRACT(TIMEZONE_REGIONFROMTIMESTAMP'1999-01-0110:00:00-08:00') ---------------------------------------------------------------- UNKNOWN The ambiguity arises because the time zone numerical offset is provided in the expression, and that numerical offset may map to more than one time zone region name. EXTRACT (XML) Syntax extract_xml::= Purpose EXTRACT (XML) is similar to the EXISTSNODE function. It applies a VARCHAR2 XPath string and returns an XMLType instance containing an XML fragment. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative Note: The EXTRACT (XML) function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLQUERY function instead. See XMLQUERY on page 5-262 for more information. EXTRACT ( XMLType_instance , XPath_string , namespace_string )
  • 245. EXTRACTVALUE Functions 5-71 path defaults to the root node. The optional namespace_string is required if the XML you are handling uses a namespace prefix. This argument must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath expression(s). Examples The following example extracts the value of the /Warehouse/Dock node of the XML path of the warehouse_spec column in the sample table oe.warehouses: SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks" FROM warehouses WHERE warehouse_spec IS NOT NULL ORDER BY warehouse_name, "Number of Docks"; WAREHOUSE_NAME Number of Docks ------------------------- ------------------------- New Jersey San Francisco <Docks>1</Docks> Seattle, Washington <Docks>3</Docks> Southlake, Texas <Docks>2</Docks> Compare this example with the example for EXTRACTVALUE on page 5-71, which returns the scalar value of the XML fragment. EXTRACTVALUE Syntax The EXTRACTVALUE function takes as arguments an XMLType instance and an XPath expression and returns a scalar value of the resultant node. The result must be a single node and be either a text node, attribute, or element. If the result is an element, then the element must have a single text node as its child, and it is this value that the function returns. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, the context of the relative path defaults to the root node. If the specified XPath points to a node with more than one child, or if the node pointed to has a non-text node child, then Oracle returns an error. The optional namespace_ string must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping for prefixes, which Oracle uses when evaluating the XPath expression(s). For documents based on XML schemas, if Oracle can infer the type of the return value, then a scalar value of the appropriate type is returned. Otherwise, the result is of type Note: The EXTRACTVALUE function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLTABLE function, or the XMLCAST and XMLQUERY functions instead. See XMLTABLE on page 5-267, XMLCAST on page 5-250, and XMLQUERY on page 5-262 for more information. EXTRACTVALUE ( XMLType_instance , XPath_string , namespace_string )
  • 246. FEATURE_ID 5-72 Oracle Database SQL Language Reference VARCHAR2. For documents that are not based on XML schemas, the return type is always VARCHAR2. Examples The following example takes as input the same arguments as the example for EXTRACT (XML) on page 5-70. Instead of returning an XML fragment, as does the EXTRACT function, it returns the scalar value of the XML fragment: SELECT warehouse_name, EXTRACTVALUE(e.warehouse_spec, '/Warehouse/Docks') "Docks" FROM warehouses e WHERE warehouse_spec IS NOT NULL; WAREHOUSE_NAME Docks -------------------- ------------ Southlake, Texas 2 San Francisco 1 New Jersey Seattle, Washington 3 FEATURE_ID Syntax mining_attribute_clause:= Purpose This function is for use with feature extraction models that have been created using the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns an Oracle NUMBER that is the identifier of the feature with the highest value in the row. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. FEATURE_ID ( schema . model mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 247. FEATURE_SET Functions 5-73 Examples The following example lists the features and corresponding count of customers in a dataset. This example and the prerequisite data mining operations, including creation of the nmf_sh_sample model and nmf_sh_sample_apply_prepared view, can be found in the demo file $ORACLE_HOME/rdbms/demo/dmnmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT FEATURE_ID(nmf_sh_sample USING *) AS feat, COUNT(*) AS cnt FROM nmf_sh_sample_apply_prepared GROUP BY FEATURE_ID(nmf_sh_sample USING *) ORDER BY cnt DESC; FEAT CNT ---------- ---------- 7 1443 2 49 3 6 1 1 6 1 FEATURE_SET Syntax mining_attribute_clause:= Purpose This function is for use with feature extraction models that have been created using the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns a See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions FEATURE_SET ( schema . model , topN , cutoff mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 248. FEATURE_SET 5-74 Oracle Database SQL Language Reference varray of objects containing all possible features. Each object in the varray is a pair of scalar values containing the feature ID and the feature value. The object fields are named FEATURE_ID and VALUE, and both are Oracle NUMBER. The optional topN argument is a positive integer that restricts the set of features to those that have one of the top N values. If there is a tie at the Nth value, then the database still returns only N values. If you omit this argument, then the function returns all features. The optional cutoff argument restricts the returned features to only those that have a feature value greater than or equal to the specified cutoff. To filter only by cutoff, specify NULL for topN and the desired cutoff for cutoff. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. Examples The following example lists the top features corresponding to a given customer record (based on match quality), and determines the top attributes for each feature (based on coefficient > 0.25). This example and the prerequisite data mining operations, including the creation of the model, views, and type, can be found in the demo file $ORACLE_ HOME/rdbms/demo/dmnmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. WITH feat_tab AS ( SELECT F.feature_id fid, A.attribute_name attr, TO_CHAR(A.attribute_value) val, A.coefficient coeff FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_NMF('nmf_sh_sample')) F, TABLE(F.attribute_set) A WHERE A.coefficient > 0.25 ), feat AS ( SELECT fid, CAST(COLLECT(Featattr(attr, val, coeff)) AS Featattrs) f_attrs FROM feat_tab GROUP BY fid ), cust_10_features AS ( SELECT T.cust_id, S.feature_id, S.value FROM (SELECT cust_id, FEATURE_SET(nmf_sh_sample, 10 USING *) pset FROM nmf_sh_sample_apply_prepared WHERE cust_id = 100002) T, See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions
  • 249. FEATURE_VALUE Functions 5-75 TABLE(T.pset) S ) SELECT A.value, A.feature_id fid, B.attr, B.val, B.coeff FROM cust_10_features A, (SELECT T.fid, F.* FROM feat T, TABLE(T.f_attrs) F) B WHERE A.feature_id = B.fid ORDER BY A.value DESC, A.feature_id ASC, coeff DESC, attr ASC, val ASC; VALUE FID ATTR VAL COEFF -------- ---- ------------------------- -------------------- ------- 6.8409 7 YRS_RESIDENCE 1.3879 6.8409 7 BOOKKEEPING_APPLICATION .4388 6.8409 7 CUST_GENDER M .2956 6.8409 7 COUNTRY_NAME United States of Ame .2848 rica 6.4975 3 YRS_RESIDENCE 1.2668 6.4975 3 BOOKKEEPING_APPLICATION .3465 6.4975 3 COUNTRY_NAME United States of Ame .2927 rica 6.4886 2 YRS_RESIDENCE 1.3285 6.4886 2 CUST_GENDER M .2819 6.4886 2 PRINTER_SUPPLIES .2704 6.3953 4 YRS_RESIDENCE 1.2931 5.9640 6 YRS_RESIDENCE 1.1585 5.9640 6 HOME_THEATER_PACKAGE .2576 5.2424 5 YRS_RESIDENCE 1.0067 2.4714 8 YRS_RESIDENCE .3297 2.3559 1 YRS_RESIDENCE .2768 2.3559 1 FLAT_PANEL_MONITOR .2593 17 rows selected. FEATURE_VALUE Syntax mining_attribute_clause:= FEATURE_VALUE ( schema . model , feature_id mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 250. FEATURE_VALUE 5-76 Oracle Database SQL Language Reference Purpose This function is for use with feature extraction models that have been created using the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns the value of a given feature. If you omit the feature_id argument, then the function returns the highest feature value. You can use this form in conjunction with the FEATURE_ID function to obtain the largest feature/value combination. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. Examples The following example lists the customers that correspond to feature 3, ordered by match quality. This example and the prerequisite data mining operations, including the creation of the model and view, can be found in the demo file $ORACLE_ HOME/rdbms/demo/dmnmdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT * FROM (SELECT cust_id, FEATURE_VALUE(nmf_sh_sample, 3 USING *) match_quality FROM nmf_sh_sample_apply_prepared ORDER BY match_quality DESC) WHERE ROWNUM < 11; CUST_ID MATCH_QUALITY ---------- ------------- 100210 19.4101627 100962 15.2482251 101151 14.5685197 101499 14.4186292 100363 14.4037396 100372 14.3335148 100982 14.1716545 101039 14.1079914 100759 14.0913761 100953 14.0799737 10 rows selected. See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions
  • 251. FIRST Functions 5-77 FIRST Syntax first::= Purpose FIRST and LAST are very similar functions. Both are aggregate and analytic functions that operate on a set of values from a set of rows that rank as the FIRST or LAST with respect to a given sorting specification. If only one row ranks as FIRST or LAST, then the aggregate operates on the set with only one element. If you omit the OVER clause, then the FIRST and LAST functions are treated as aggregate functions. You can use these functions as analytic functions by specifying the OVER clause. The query_partition_clause is the only part of the OVER clause valid with these functions. If you include the OVER clause but omit the query_ partition_clause, then the function is treated as an analytic function, but the window defined for analysis is the entire table. These functions take as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. When you need a value from the first or last row of a sorted group, but the needed value is not the sort key, the FIRST and LAST functions eliminate the need for self-joins or views and enable better performance. ■ The aggregate_function argument is any one of the MIN, MAX, SUM, AVG, COUNT, VARIANCE, or STDDEV functions. It operates on values from the rows that rank either FIRST or LAST. If only one row ranks as FIRST or LAST, then the aggregate operates on a singleton (nonaggregate) set. ■ The KEEP keyword is for semantic clarity. It qualifies aggregate_function, indicating that only the FIRST or LAST values of aggregate_function will be returned. ■ DENSE_RANK FIRST or DENSE_RANK LAST indicates that Oracle Database will aggregate over only those rows with the minimum (FIRST) or the maximum (LAST) dense rank (also called olympic rank). See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the ORDER BY clause and OVER clause aggregate_function KEEP ( DENSE_RANK FIRST ORDER BY expr DESC ASC NULLS FIRST LAST , ) OVER ( query_partition_clause )
  • 252. FIRST 5-78 Oracle Database SQL Language Reference Aggregate Example The following example returns, within each department of the sample table hr.employees, the minimum salary among the employees who make the lowest commission and the maximum salary among the employees who make the highest commission: SELECT department_id, MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) "Worst", MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) "Best" FROM employees GROUP BY department_id ORDER BY department_id, "Worst", "Best"; DEPARTMENT_ID Worst Best ------------- ---------- ---------- 10 4400 4400 20 6000 13000 30 2500 11000 40 6500 6500 50 2100 8200 60 4200 9000 70 10000 10000 80 6100 14000 90 17000 24000 100 6900 12000 110 8300 12000 7000 7000 Analytic Example The next example makes the same calculation as the previous example but returns the result for each employee within the department: SELECT last_name, department_id, salary, MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) OVER (PARTITION BY department_id) "Worst", MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) OVER (PARTITION BY department_id) "Best" FROM employees ORDER BY department_id, salary; LAST_NAME DEPARTMENT_ID SALARY Worst Best ------------------- ------------- ---------- ---------- ---------- Whalen 10 4400 4400 4400 Fay 20 6000 6000 13000 Hartstein 20 13000 6000 13000 . . . Gietz 110 8300 8300 12000 Higgins 110 12000 8300 12000 Grant 7000 7000 7000 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and LAST on page 5-95
  • 253. FIRST_VALUE Functions 5-79 FIRST_VALUE Syntax Purpose FIRST_VALUE is an analytic function. It returns the first value in an ordered set of values. If the first value in the set is null, then the function returns NULL unless you specify IGNORE NULLS. This setting is useful for data densification. {RESPECT | IGNORE} NULLS determines whether null values of expr are included in or eliminated from the calculation. The default is RESPECT NULLS. If you specify IGNORE NULLS, then FIRST_VALUE returns the first non-null value in the set, or NULL if all values are null. {RESPECT | IGNORE} NULLS determines whether null values of expr are included in or eliminated from the calculation. The default is RESPECT NULLS. Refer to "Using Partitioned Outer Joins: Examples" on page 19-52 for an example of data densification. You cannot nest analytic functions by using FIRST_VALUE or any other analytic function for expr. However, you can use other built-in function expressions for expr. Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr. Examples The following example selects, for each employee in Department 90, the name of the employee with the lowest salary. SELECT department_id, last_name, salary, FIRST_VALUE(last_name) OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS lowest_sal FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY employee_id) ORDER BY department_id, last_name, salary, lowest_sal; DEPARTMENT_ID LAST_NAME SALARY LOWEST_SAL ------------- ------------------------- ---------- ------------------------- 90 De Haan 17000 Kochhar 90 King 24000 Kochhar See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of expr Note: The two forms of this syntax have the same behavior. The top branch is the ANSI format, which Oracle recommends. The bottom branch is deprecated but is supported for backward compatibility. FIRST_VALUE ( expr ) RESPECT IGNORE NULLS ( expr RESPECT IGNORE NULLS ) OVER ( analytic_clause )
  • 254. FLOOR 5-80 Oracle Database SQL Language Reference 90 Kochhar 17000 Kochhar The example illustrates the nondeterministic nature of the FIRST_VALUE function. Kochhar and DeHaan have the same salary, so are in adjacent rows. Kochhar appears first because the rows returned by the subquery are ordered by employee_id. However, if the rows returned by the subquery are ordered by employee_id in descending order, as in the next example, then the function returns a different value: SELECT department_id, last_name, salary, FIRST_VALUE(last_name) OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) as fv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER by employee_id DESC) ORDER BY department_id, last_name, salary, fv; DEPARTMENT_ID LAST_NAME SALARY FV ------------- ------------------------- ---------- ------------------------- 90 De Haan 17000 De Haan 90 King 24000 De Haan 90 Kochhar 17000 De Haan The following example shows how to make the FIRST_VALUE function deterministic by ordering on a unique key. SELECT department_id, last_name, salary, hire_date, FIRST_VALUE(last_name) OVER (ORDER BY salary ASC, hire_date ROWS UNBOUNDED PRECEDING) AS fv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY employee_id DESC) ORDER BY department_id, last_name, salary, hire_date; DEPARTMENT_ID LAST_NAME SALARY HIRE_DATE FV ------------- --------------- ---------- --------- ------------------------- 90 De Haan 17000 13-JAN-01 De Haan 90 King 24000 17-JUN-03 De Haan 90 Kochhar 17000 21-SEP-05 De Haan When you use a logical offset (RANGE instead of ROWS), the function is deterministic. When duplicates are found for the ORDER BY expression, the FIRST_VALUE is the lowest value of expr: SELECT department_id, last_name, salary, FIRST_VALUE(last_name) OVER (ORDER BY salary ASC RANGE UNBOUNDED PRECEDING) AS lowest_sal FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY employee_id); DEPARTMENT_ID LAST_NAME SALARY LOWEST_SAL ------------- ------------------------- ---------- ------------------------- 90 De Haan 17000 De Haan 90 Kochhar 17000 De Haan 90 King 24000 De Haan 3 rows selected. FLOOR Syntax FLOOR ( n )
  • 255. GREATEST Functions 5-81 Purpose FLOOR returns the largest integer equal to or less than n. The number n can always be written as the sum of an integer k and a positive fraction f such that 0 <= f < 1 and n = k + f. The value of FLOOR is the integer k. Thus, the value of FLOOR is n itself if and only if n is precisely an integer. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. Examples The following example returns the largest integer equal to or less than 15.7: SELECT FLOOR(15.7) "Floor" FROM DUAL; Floor ---------- 15 FROM_TZ Syntax Purpose FROM_TZ converts a timestamp value and a time zone to a TIMESTAMP WITH TIME ZONE value. time_zone_value is a character string in the format 'TZH:TZM' or a character expression that returns a string in TZR with optional TZD format. Examples The following example returns a timestamp value to TIMESTAMP WITH TIME ZONE: SELECT FROM_TZ(TIMESTAMP '2000-03-28 08:00:00', '3:00') FROM DUAL; FROM_TZ(TIMESTAMP'2000-03-2808:00:00','3:00') --------------------------------------------------------------- 28-MAR-00 08.00.00 AM +03:00 GREATEST Syntax See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and CEIL on page 5-31 FROM_TZ ( timestamp_value , time_zone_value ) GREATEST ( expr , )
  • 256. GROUP_ID 5-82 Oracle Database SQL Language Reference Purpose GREATEST returns the greatest of the list of one or more expressions. Oracle Database uses the first expr to determine the return type. If the first expr is numeric, then Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type before the comparison, and returns that data type. If the first expr is not numeric, then each expr after the first is implicitly converted to the data type of the first expr before the comparison. Oracle Database compares each expr using nonpadded comparison semantics. The comparison is binary by default and is linguistic if the NLS_COMP parameter is set to LINGUISTIC and the NLS_SORT parameter has a setting other than BINARY. Character comparison is based on the numerical codes of the characters in the database character set and is performed on whole strings treated as one sequence of bytes, rather than character by character. If the value returned by this function is character data, then its data type is VARCHAR2 if the first expr is a character data type and NVARCHAR2 if the first expr is a national character data type. Examples The following statement selects the string with the greatest value: SELECT GREATEST ('HARRY', 'HARRIOT', 'HAROLD') "Greatest" FROM DUAL; Greatest -------- HARRY GROUP_ID Syntax Purpose GROUP_ID distinguishes duplicate groups resulting from a GROUP BY specification. It is useful in filtering out duplicate groupings from the query result. It returns an Oracle NUMBER to uniquely identify duplicate groups. This function is applicable only in a SELECT statement that contains a GROUP BY clause. If n duplicates exist for a particular grouping, then GROUP_ID returns numbers in the range 0 to n-1. Examples The following example assigns the value 1 to the duplicate co.country_region grouping from a query on the sample tables sh.countries and sh.sales: See Also: ■ "Data Type Comparison Rules" on page 3-37 for more information on character comparison ■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Floating-Point Numbers" on page 3-12 for information on binary-float comparison semantics GROUP_ID ( )
  • 257. GROUPING Functions 5-83 SELECT co.country_region, co.country_subregion, SUM(s.amount_sold) "Revenue", GROUP_ID() g FROM sales s, customers c, countries co WHERE s.cust_id = c.cust_id AND c.country_id = co.country_id AND s.time_id = '1-JAN-00' AND co.country_region IN ('Americas', 'Europe') GROUP BY GROUPING SETS ( (co.country_region, co.country_subregion), (co.country_ region, co.country_subregion) ) ORDER BY co.country_region, co.country_subregion, "Revenue", g; COUNTRY_REGION COUNTRY_SUBREGION Revenue G -------------------- ------------------------------ ---------- ---------- Americas Northern America 944.6 0 Americas 944.6 1 Europe Western Europe 566.39 0 Europe 566.39 1 To ensure that only rows with GROUP_ID < 1 are returned, add the following HAVING clause to the end of the statement : HAVING GROUP_ID() < 1 GROUPING Syntax Purpose GROUPING distinguishes superaggregate rows from regular grouped rows. GROUP BY extensions such as ROLLUP and CUBE produce superaggregate rows where the set of all values is represented by null. Using the GROUPING function, you can distinguish a null representing the set of all values in a superaggregate row from a null in a regular row. The expr in the GROUPING function must match one of the expressions in the GROUP BY clause. The function returns a value of 1 if the value of expr in the row is a null representing the set of all values. Otherwise, it returns zero. The data type of the value returned by the GROUPING function is Oracle NUMBER. Refer to the SELECT group_by_ clause on page 19-27 for a discussion of these terms. Examples In the following example, which uses the sample tables hr.departments and hr.employees, if the GROUPING function returns 1 (indicating a superaggregate row rather than a regular row from the table), then the string "All Jobs" appears in the "JOB" column instead of the null that would otherwise appear: SELECT DECODE(GROUPING(department_name), 1, 'All Departments', department_name) AS department, DECODE(GROUPING(job_id), 1, 'All Jobs', job_id) AS job, COUNT(*) "Total Empl", AVG(salary) * 12 "Average Sal" FROM employees e, departments d WHERE d.department_id = e.department_id GROUP BY ROLLUP (department_name, job_id) GROUPING ( expr )
  • 258. GROUPING_ID 5-84 Oracle Database SQL Language Reference ORDER BY department, job, "Total Empl", "Average Sal"; DEPARTMENT JOB Total Empl Average Sal ------------------------------ ---------- ---------- ----------- Accounting AC_ACCOUNT 1 99600 Accounting AC_MGR 1 144000 Accounting All Jobs 2 121800 Administration AD_ASST 1 52800 Administration All Jobs 1 52800 All Departments All Jobs 106 77479.2453 Executive AD_PRES 1 288000 Executive AD_VP 2 204000 Executive All Jobs 3 232000 Finance All Jobs 6 103200 Finance FI_ACCOUNT 5 95040 . . . GROUPING_ID Syntax Purpose GROUPING_ID returns a number corresponding to the GROUPING bit vector associated with a row. GROUPING_ID is applicable only in a SELECT statement that contains a GROUP BY extension, such as ROLLUP or CUBE, and a GROUPING function. In queries with many GROUP BY expressions, determining the GROUP BY level of a particular row requires many GROUPING functions, which leads to cumbersome SQL. GROUPING_ID is useful in these cases. GROUPING_ID is functionally equivalent to taking the results of multiple GROUPING functions and concatenating them into a bit vector (a string of ones and zeros). By using GROUPING_ID you can avoid the need for multiple GROUPING functions and make row filtering conditions easier to express. Row filtering is easier with GROUPING_ID because the desired rows can be identified with a single condition of GROUPING_ID = n. The function is especially useful when storing multiple levels of aggregation in a single table. Examples The following example shows how to extract grouping IDs from a query of the sample table sh.sales: SELECT channel_id, promo_id, sum(amount_sold) s_sales, GROUPING(channel_id) gc, GROUPING(promo_id) gp, GROUPING_ID(channel_id, promo_id) gcp, GROUPING_ID(promo_id, channel_id) gpc FROM sales WHERE promo_id > 496 GROUP BY CUBE(channel_id, promo_id) ORDER BY channel_id, promo_id, s_sales, gc; CHANNEL_ID PROMO_ID S_SALES GC GP GCP GPC ---------- ---------- ---------- ---------- ---------- ---------- ---------- GROUPING_ID ( expr , )
  • 259. INITCAP Functions 5-85 2 999 25797563.2 0 0 0 0 2 25797563.2 0 1 1 2 3 999 55336945.1 0 0 0 0 3 55336945.1 0 1 1 2 4 999 13370012.5 0 0 0 0 4 13370012.5 0 1 1 2 999 94504520.8 1 0 2 1 94504520.8 1 1 3 3 HEXTORAW Syntax Purpose HEXTORAW converts char containing hexadecimal digits in the CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to a raw value. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example creates a simple table with a raw column, and inserts a hexadecimal value that has been converted to RAW: CREATE TABLE test (raw_col RAW(10)); INSERT INTO test VALUES (HEXTORAW('7D')); The following example converts hexadecimal digits to a raw value and casts the raw value to VARCHAR2: SELECT UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW('4041424344')) FROM DUAL; UTL_RAW.CAST_TO_VARCHAR2(HEXTORAW('4041424344')) ------------------------------------------------ @ABCD INITCAP Syntax See Also: "Data Type Comparison Rules" on page 3-37 for more information. See Also: "RAW and LONG RAW Data Types" on page 3-24 and RAWTOHEX on page 5-155 HEXTORAW ( char ) INITCAP ( char )
  • 260. INSERTCHILDXML 5-86 Oracle Database SQL Language Reference Purpose INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric. char can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same data type as char. The database sets the case of the initial characters based on the binary mapping defined for the underlying character set. For linguistic-sensitive uppercase and lowercase, refer to NLS_INITCAP on page 5-118. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example capitalizes each word in the string: SELECT INITCAP('the soap') "Capitals" FROM DUAL; Capitals --------- The Soap INSERTCHILDXML Syntax Purpose INSERTCHILDXML inserts a user-supplied value into the target XML at the node indicated by the XPath expression. Compare this function with INSERTXMLBEFORE on page 5-90. ■ XMLType_instance is an instance of XMLType. ■ The XPath_string is an Xpath expression indicating one or more nodes into which the one or more child nodes are to be inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative path defaults to the root node. ■ The child_expr specifies the one or more element or attribute nodes to be inserted. ■ The value_expr is an fragment of XMLType that specifies one or more notes being inserted. It must resolve to a string. See Also: "Data Type Comparison Rules" on page 3-37 for more information. See Also: Oracle XML DB Developer's Guide for more information about this function INSERTCHILDXML ( XMLType_instance , XPath_string , child_expr , value_expr , namespace_string )
  • 261. INSERTCHILDXMLAFTER Functions 5-87 ■ The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type VARCHAR2. Examples The following example adds a second /Owner node to the warehouse_spec of one of the warehouses updated in the example for APPENDCHILDXML on page 5-19: UPDATE warehouses SET warehouse_spec = INSERTCHILDXML(warehouse_spec, '/Warehouse/Building', 'Owner', XMLType('<Owner>LesserCo</Owner>')) WHERE warehouse_id = 3; SELECT warehouse_spec FROM warehouses WHERE warehouse_id = 3; WAREHOUSE_SPEC ---------------------------------------------------------------------------- <?xml version="1.0"?> <Warehouse> <Building>Rented <Owner>Grandco</Owner> <Owner>LesserCo</Owner> </Building> <Area>85700</Area> <DockType/> <WaterAccess>N</WaterAccess> <RailAccess>N</RailAccess> <Parking>Street</Parking> <VClearance>11.5 ft</VClearance> </Warehouse> INSERTCHILDXMLAFTER Syntax Purpose INSERTXMLCHILDAFTER inserts one or more collection elements as children of target parent elements. The insertion for each target occurs immediately after a specified existing collection element. The existing XML document that is the target of the insertion can be schema-based or non-schema-based. ■ The XMLType_instance identifies the XML data that is the target of the insertion. ■ The XPath_string locates the parent elements within target-data; child-data is inserted under each parent element. ■ The child_expr is a relative XPath 1.0 expression that locates the existing child that will precede the inserted child-data. It must name a child element of the element indicated by parent-xpath, and it can include a predicate. INSERTCHILDXMLAFTER ( XMLType_instance , XPath_string , child_expr , value_expr , namespace_string )
  • 262. INSERTCHILDXMLBEFORE 5-88 Oracle Database SQL Language Reference ■ The value_expr is the XMLType child element data to insert. Each top-level element node in this argument must have the same data type as the element indicated by child_expr. ■ The optional namespace_string specifies the namespace for the parent elements, existing child element, and child element XML data to be inserted. For more information about this function and its uses, including examples, see Oracle XML DB Developer's Guide. Examples The following example is similar to that for INSERTCHILDXML, but it adds a third /Owner node after the /Owner node added in the other example. The output of the query has been formatted for readability. UPDATE warehouses SET warehouse_spec = INSERTCHILDXMLAFTER(warehouse_spec, '/Warehouse/Building','Owner[2]', XMLType('<Owner>ThirdOwner</Owner>')) WHERE warehouse_id = 3; SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Building/Owner') "Owners" FROM warehouses WHERE warehouse_id = 3; WAREHOUSE_NAME Owners ----------------------------------- ------------------------------ New Jersey <Owner>LesserCo</Owner> <Owner>GrandCo</Owner> <Owner>ThirdOwner</Owner> INSERTCHILDXMLBEFORE Syntax Purpose INSERTXMLCHILDBEFORE inserts one or more collection elements as children of target parent elements. The insertion for each target occurs immediately before a specified existing collection element. The existing XML document that is the target of the insertion can be schema-based or non-schema-based. ■ The XMLType_instance identifies the XML data that is the target of the insertion. ■ The XPath_string locates the parent elements within target-data; child-data is inserted under each parent element. ■ The child_expr is a relative XPath 1.0 expression that locates the existing child that will follow the inserted child-data. It must name a child element of the element indicated by parent-xpath, and it can include a predicate. INSERTCHILDXMLBEFORE ( XMLType_instance , XPath_string , child_expr , value_expr , namespace_string )
  • 263. INSERTXMLAFTER Functions 5-89 ■ The value_expr is the XMLType child element data to insert. Each top-level element node in this argument must have the same data type as the element indicated by child_expr. ■ The optional namespace_string specifies the namespace for the parent elements, existing child element, and child element XML data to be inserted. For more information about this function and its uses, including examples, see Oracle XML DB Developer's Guide. Examples The following example is similar to that for INSERTCHILDXML, but it adds a third /Owner node before the /Owner node added in the other example. The output of the query has been formatted for readability. UPDATE warehouses SET warehouse_spec = INSERTCHILDXMLBEFORE(warehouse_spec, '/Warehouse/Building','Owner[2]', XMLType('<Owner>ThirdOwner</Owner>')) WHERE warehouse_id = 3; SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Building/Owner') "Owners" FROM warehouses WHERE warehouse_id = 3; WAREHOUSE_NAME Owners ----------------------------------- ------------------------------ New Jersey <Owner>LesserCo</Owner> <Owner>ThirdOwner</Owner> <Owner>GrandCo</Owner> INSERTXMLAFTER Syntax Purpose INSERTXMLAFTER inserts one or more nodes of any kind immediately after a target node that is not an attribute node. The XML document that is the target of the insertion can be schema-based or non-schema-based. This function is similar to insertXMLbefore, but it inserts after, not before, the target node. ■ XMLType_instance specifies the target node of the of the insertion. ■ XPath_string is an XPath 1.0 expression that locates in the target node zero or more nodes of any kind except attribute nodes. XML-data is inserted immediately after each of these nodes; that is, each node specified becomes the preceding sibling node of a node specified in value_expr. ■ value_expr is the XML data to be inserted. You can specify one or more nodes of any kind. The order of the nodes is preserved after the insertion. ■ namespace_string is the namespace for the target node. For more information about this function and its uses, including examples, see Oracle XML DB Developer's Guide. INSERTXMLAFTER ( XMLType_instance , XPath_string , value_expr , namespace_string )
  • 264. INSERTXMLBEFORE 5-90 Oracle Database SQL Language Reference Examples The following example is similar to that for INSERTCHILDXML, but it adds a third /Owner node after the /Owner node added in the other example. The output of the query has been formatted for readability. UPDATE warehouses SET warehouse_spec = INSERTXMLAFTER(warehouse_spec, '/Warehouse/Building/Owner[1]', XMLType('<Owner>SecondOwner</Owner>')) WHERE warehouse_id = 3; SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Building/Owner') "Owners" FROM warehouses WHERE warehouse_id = 3; INSERTXMLBEFORE Syntax Purpose INSERTXMLBEFORE inserts a user-supplied value into the target XML before the node indicated by the XPath expression. This function is similar to INSERTXMLAFTER, but it inserts before, not after, the target node. Compare this function with INSERTCHILDXML on page 5-86. ■ XMLType_instance is an instance of XMLType. ■ The XPath_string is an Xpath expression indicating one or more nodes into which one or more child nodes are to be inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative path defaults to the root node. ■ The value_expr is a fragment of XMLType that defines one or more nodes being inserted and their position within the parent node. It must resolve to a string. ■ The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type VARCHAR2. Examples The following example is similar to that for INSERTCHILDXML on page 5-86, but it adds a third /Owner node before the /Owner node added in the other example. The output of the query has been formatted for readability. UPDATE warehouses SET warehouse_spec = INSERTXMLBEFORE(warehouse_spec, '/Warehouse/Building/Owner[2]', XMLType('<Owner>ThirdOwner</Owner>')) WHERE warehouse_id = 3; SELECT warehouse_name, EXTRACT(warehouse_spec, See Also: Oracle XML DB Developer's Guide for more information about this function INSERTXMLBEFORE ( XMLType_instance , XPath_string , value_expr , namespace_string )
  • 265. INSTR Functions 5-91 '/Warehouse/Building/Owner') "Owners" FROM warehouses WHERE warehouse_id = 3; Name Owners ------------ -------------------------------------------------------------------- New Jersey <Owner>Grandco</Owner> <Owner>ThirdOwner</Owner> <Owner>LesserCo</Owner> INSTR Syntax Purpose The INSTR functions search string for substring. The search operation is defined as comparing the substring argument with substrings of string of the same length for equality until a match is found or there are no more substrings left. Each consecutive compared substring of string begins one character to the right (for forward searches) or one character to the left (for backward searches) from the first character of the previous compared substring. If a substring that is equal to substring is found, then the function returns an integer indicating the position of the first character of this substring. If no such substring is found, then the function returns zero. ■ position is an nonzero integer indicating the character of string where Oracle Database begins the search—that is, the position of the first character of the first substring to compare with substring. If position is negative, then Oracle counts backward from the end of string and then searches backward from the resulting position. ■ occurrence is an integer indicating which occurrence of substring in string Oracle should search for. The value of occurrence must be positive. If occurrence is greater than 1, then the database does not return on the first match but continues comparing consecutive substrings of string, as described above, until match number occurrence has been found. INSTR accepts and returns positions in characters as defined by the input character set, with the first character of string having position 1. INSTRB uses bytes instead of characters. INSTRC uses Unicode complete characters. INSTR2 uses UCS2 code points. INSTR4 uses UCS4 code points. Both string and substring can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The value returned is of NUMBER data type. Both position and occurrence must be of data type NUMBER, or any data type that can be implicitly converted to NUMBER, and must resolve to an integer. The default values of both position and occurrence are 1, meaning Oracle begins searching at INSTR INSTRB INSTRC INSTR2 INSTR4 ( string , substring , position , occurrence )
  • 266. ITERATION_NUMBER 5-92 Oracle Database SQL Language Reference the first character of string for the first occurrence of substring. The return value is relative to the beginning of string, regardless of the value of position. Examples The following example searches the string CORPORATE FLOOR, beginning with the third character, for the string "OR". It returns the position in CORPORATE FLOOR at which the second occurrence of "OR" begins: SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL; Instring ---------- 14 In the next example, Oracle counts backward from the last character to the third character from the end, which is the first O in FLOOR. Oracle then searches backward for the second occurrence of OR, and finds that this second occurrence begins with the second character in the search string : SELECT INSTR('CORPORATE FLOOR','OR', -3, 2) "Reversed Instring" FROM DUAL; Reversed Instring ----------------- 2 The next example assumes a double-byte database character set. SELECT INSTRB('CORPORATE FLOOR','OR',5,2) "Instring in bytes" FROM DUAL; Instring in bytes ----------------- 27 ITERATION_NUMBER Syntax Purpose The ITERATION_NUMBER function can be used only in the model_clause of the SELECT statement and then only when ITERATE(number) is specified in the model_ rules_clause. It returns an integer representing the completed iteration through the model rules. The ITERATION_NUMBER function returns 0 during the first iteration. For each subsequent iteration, the ITERATION_NUMBER function returns the equivalent of iteration_number plus one. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for the syntax and semantics ITERATION_NUMBER
  • 267. ITERATION_NUMBER Functions 5-93 Examples The following example assigns the sales of the Mouse Pad for the years 1998 and 1999 to the sales of the Mouse Pad for the years 2001 and 2002 respectively: SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ITERATE(2) ( s['Mouse Pad', 2001 + ITERATION_NUMBER] = s['Mouse Pad', 1998 + ITERATION_NUMBER] ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 3000.72 France Mouse Pad 2001 2509.42 France Mouse Pad 2002 3678.69 France Standard Mouse 1998 2390.83 France Standard Mouse 1999 2280.45 France Standard Mouse 2000 1274.31 France Standard Mouse 2001 2164.54 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 7375.46 Germany Mouse Pad 2001 5827.87 Germany Mouse Pad 2002 8346.44 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 2637.31 Germany Standard Mouse 2001 6456.13 18 rows selected. The preceding example requires the view sales_view_ref. Refer to "The MODEL clause: Examples" on page 19-45 to create this view.
  • 268. LAG 5-94 Oracle Database SQL Language Reference LAG Syntax Purpose LAG is an analytic function. It provides access to more than one row of a table at the same time without a self join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position. If you do not specify offset, then its default is 1. The optional default value is returned if the offset goes beyond the scope of the window. If you do not specify default, then its default is null. {RESPECT | IGNORE} NULLS determines whether null values of value_expr are included in or eliminated from the calculation. The default is RESPECT NULLS. You cannot nest analytic functions by using LAG or any other analytic function for value_expr. However, you can use other built-in function expressions for value_ expr. Examples The following example provides, for each salesperson in the employees table, the salary of the employee hired just before: SELECT last_name, hire_date, salary, LAG(salary, 1, 0) OVER (ORDER BY hire_date) AS prev_sal FROM employees WHERE job_id = 'PU_CLERK' ORDER BY last_name, hire_date, salary, prev_sal; LAST_NAME HIRE_DATE SALARY PREV_SAL ------------------------- --------- ---------- ---------- Baida 24-DEC-05 2900 2800 Colmenares 10-AUG-07 2500 2600 Himuro 15-NOV-06 2600 2900 See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of value_ expr See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and LEAD on page 5-98 LAG ( value_expr , offset , default ) RESPECT IGNORE NULLS ( value_expr RESPECT IGNORE NULLS , offset , default ) OVER ( query_partition_clause order_by_clause )
  • 269. LAST_DAY Functions 5-95 Khoo 18-MAY-03 3100 0 Tobias 24-JUL-05 2800 3100 LAST Syntax last::= Purpose FIRST and LAST are very similar functions. Both are aggregate and analytic functions that operate on a set of values from a set of rows that rank as the FIRST or LAST with respect to a given sorting specification. If only one row ranks as FIRST or LAST, then the aggregate operates on the set with only one element. Refer to FIRST on page 5-77 for complete information on this function and for examples of its use. LAST_DAY Syntax Purpose LAST_DAY returns the date of the last day of the month that contains date. The last day of the month is defined by the session parameter NLS_CALENDAR. The return type is always DATE, regardless of the data type of date. Examples The following statement determines how many days are left in the current month. SELECT SYSDATE, LAST_DAY(SYSDATE) "Last", LAST_DAY(SYSDATE) - SYSDATE "Days Left" FROM DUAL; See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the query_partitioning_ clause aggregate_function KEEP ( DENSE_RANK LAST ORDER BY expr DESC ASC NULLS FIRST LAST , ) OVER ( query_partition_clause ) LAST_DAY ( date )
  • 270. LAST_VALUE 5-96 Oracle Database SQL Language Reference SYSDATE Last Days Left --------- --------- ---------- 30-MAY-01 31-MAY-01 1 The following example adds 5 months to the hire date of each employee to give an evaluation date: SELECT last_name, hire_date, TO_CHAR( ADD_MONTHS(LAST_DAY(hire_date), 5)) "Eval Date" FROM employees; LAST_NAME HIRE_DATE Eval Date ------------------------- --------- --------- King 17-JUN-03 30-NOV-03 Kochhar 21-SEP-05 28-FEB-05 De Haan 13-JAN-01 30-JUN-01 Hunold 20-MAY-08 31-OCT-08 Ernst 21-MAY-07 31-OCT-07 Austin 25-JUN-05 30-NOV-05 Pataballa 05-FEB-06 31-JUL-06 Lorentz 07-FEB-07 31-JUL-07 . . . LAST_VALUE Syntax Purpose LAST_VALUE is an analytic function that is useful for data densification. It returns the last value in an ordered set of values. {RESPECT | IGNORE} NULLS determines whether null values of expr are included in or eliminated from the calculation. The default is RESPECT NULLS. If the last value in the set is null, then the function returns NULL unless you specify IGNORE NULLS. If you specify IGNORE NULLS, then LAST_VALUE returns the fist non-null value in the set, or NULL if all values are null. Refer to "Using Partitioned Outer Joins: Examples" on page 19-52 for an example of data densification. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of expr Note: The two forms of this syntax have the same behavior. The top branch is the ANSI format, which Oracle recommends. The bottom branch is deprecated but is supported for backward compatibility. LAST_VALUE ( expr ) RESPECT IGNORE NULLS ( expr RESPECT IGNORE NULLS ) OVER ( analytic_clause )
  • 271. LAST_VALUE Functions 5-97 You cannot nest analytic functions by using LAST_VALUE or any other analytic function for expr. However, you can use other built-in function expressions for expr. Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr. If you omit the windowing_clause of the analytic_clause, it defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This default sometimes returns an unexpected value, because the last value in the window is at the bottom of the window, which is not fixed. It keeps changing as the current row changes. For expected results, specify the windowing_clause as RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Alternatively, you can specify the windowing_clause as RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. Examples The following example returns, for each row, the hire date of the employee earning the highest salary: SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date) ORDER BY last_name, salary, hire_date, lv; LAST_NAME SALARY HIRE_DATE LV --------------- ---------- --------- --------- De Haan 17000 13-JAN-01 17-JUN-03 King 24000 17-JUN-03 17-JUN-03 Kochhar 17000 21-SEP-05 17-JUN-03 This example illustrates the nondeterministic nature of the LAST_VALUE function. Kochhar and De Haan have the same salary, so they are in adjacent rows. Kochhar appears first because the rows in the subquery are ordered by hire_date. However, if the rows are ordered by hire_date in descending order, as in the next example, then the function returns a different value: SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date DESC) ORDER BY last_name, salary, hire_datea, lv; LAST_NAME SALARY HIRE_DATE LV --------------- ---------- --------- --------- De Haan 17000 13-JAN-01 17-JUN-03 King 24000 17-JUN-03 17-JUN-03 Kochhar 17000 21-SEP-05 17-JUN-03 The following two examples show how to make the LAST_VALUE function deterministic by ordering on a unique key. By ordering within the function by both salary and hire_date, you can ensure the same result regardless of the ordering in the subquery. SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER (ORDER BY salary, hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date)
  • 272. LEAD 5-98 Oracle Database SQL Language Reference ORDER BY last_name, salary, hire_date, lv; LAST_NAME SALARY HIRE_DATE LV --------------- ---------- --------- --------- De Haan 17000 13-JAN-01 17-JUN-03 King 24000 17-JUN-03 17-JUN-03 Kochhar 17000 21-SEP-05 17-JUN-03 SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER (ORDER BY salary, hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date DESC) ORDER BY last_name, salary, hire_date, lv; LAST_NAME SALARY HIRE_DATE LV --------------- ---------- --------- --------- De Haan 17000 13-JAN-01 17-JUN-03 King 24000 17-JUN-03 17-JUN-03 Kochhar 17000 21-SEP-05 17-JUN-03 When you use a logical offset (RANGE instead of ROWS), the function is deterministic. When duplicates are found for the ORDER BY expression, the LAST_VALUE is the highest value of expr: SELECT last_name, salary, hire_date, LAST_VALUE(hire_date) OVER (ORDER BY salary RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date DESC); LAST_NAME SALARY HIRE_DATE LV ------------------------- ---------- --------- --------- De Haan 17000 13-JAN-01 17-JUN-03 Kochhar 17000 21-SEP-05 17-JUN-03 King 24000 17-JUN-03 17-JUN-03 LEAD Syntax See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of value_ expr LEAD ( value_expr , offset , default ) RESPECT IGNORE NULLS ( value_expr RESPECT IGNORE NULLS , offset , default ) OVER ( query_partition_clause order_by_clause )
  • 273. LEAST Functions 5-99 Purpose LEAD is an analytic function. It provides access to more than one row of a table at the same time without a self join. Given a series of rows returned from a query and a position of the cursor, LEAD provides access to a row at a given physical offset beyond that position. If you do not specify offset, then its default is 1. The optional default value is returned if the offset goes beyond the scope of the table. If you do not specify default, then its default value is null. {RESPECT | IGNORE} NULLS determines whether null values of value_expr are included in or eliminated from the calculation. The default is RESPECT NULLS. You cannot nest analytic functions by using LEAD or any other analytic function for value_expr. However, you can use other built-in function expressions for value_ expr. Examples The following example provides, for each employee in the employees table, the hire date of the employee hired just after: SELECT last_name, hire_date, LEAD(hire_date, 1) OVER (ORDER BY hire_date) AS "NextHired" FROM employees WHERE department_id = 30 ORDER BY last_name, hire_date, "NextHired"; LAST_NAME HIRE_DATE NextHired ------------------------- --------- --------- Baida 24-DEC-05 15-NOV-06 Colmenares 10-AUG-07 Himuro 15-NOV-06 10-AUG-07 Khoo 18-MAY-03 24-JUL-05 Raphaely 07-DEC-02 18-MAY-03 Tobias 24-JUL-05 24-DEC-05 LEAST Syntax Purpose LEAST returns the least of the list of exprs. All exprs after the first are implicitly converted to the data type of the first expr before the comparison. Oracle Database compares the exprs using nonpadded comparison semantics. If the value returned by this function is character data, then its data type is always VARCHAR2. See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and LAG on page 5-94 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion, "Floating-Point Numbers" on page 3-12 for information on binary-float comparison semantics, and "Data Type Comparison Rules" on page 3-37 LEAST ( expr , )
  • 274. LENGTH 5-100 Oracle Database SQL Language Reference Examples The following statement selects the string with the least value: SELECT LEAST('HARRY','HARRIOT','HAROLD') "LEAST" FROM DUAL; LEAST ------ HAROLD LENGTH Syntax length::= Purpose The LENGTH functions return the length of char. LENGTH calculates length using characters as defined by the input character set. LENGTHB uses bytes instead of characters. LENGTHC uses Unicode complete characters. LENGTH2 uses UCS2 code points. LENGTH4 uses UCS4 code points. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is of data type NUMBER. If char has data type CHAR, then the length includes all trailing blanks. If char is null, then this function returns null. Restriction on LENGTHB The LENGTHB function is supported for single-byte LOBs only. It cannot be used with CLOB and NCLOB data in a multibyte character set. Examples The following example uses the LENGTH function using a single-byte database character set: SELECT LENGTH('CANDIDE') "Length in characters" FROM DUAL; Length in characters -------------------- 7 The next example assumes a double-byte database character set. SELECT LENGTHB ('CANDIDE') "Length in bytes" FROM DUAL; Length in bytes --------------- 14 LENGTH LENGTHB LENGTHC LENGTH2 LENGTH4 ( char )
  • 275. LISTAGG Functions 5-101 LISTAGG Syntax Purpose For a specified measure, LISTAGG orders data within each group specified in the ORDER BY clause and then concatenates the values of the <measure> column. ■ As a single-set aggregate function, LISTAGG operates on all rows and returns a single output row. ■ As a group-set aggregate, the function operates on and returns an output row for each group defined by the GROUP BY clause. ■ As an analytic function, LISTAGG partitions the query result set into groups based on one or more expression in the query_partition_clause. The arguments to the function are subject to the following rules: ■ The measure_expr can be any expression. Null values in the measure column are ignored. ■ The delimiter_expr designates the string that is to separate the measure values. This clause is optional and defaults to NULL. ■ The order_by_clause determines the order in which the concatenated values are returned. The function is deterministic only if the ORDER BY column list achieved unique ordering. The return data type is RAW if the measure column is RAW; otherwise the return value is VARCHAR2. Examples The following single-set aggregate example lists all of the employees in Department 30 in the hr.employees table, ordered by hire date and last name: SELECT LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date, last_name) "Emp_ list", MIN(hire_date) "Earliest" FROM employees WHERE department_id = 30; Emp_list Earliest ------------------------------------------------------------ --------- Raphaely; Khoo; Tobias; Baida; Himuro; Colmenares 07-DEC-02 See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the ORDER BY clause and OVER clause LISTAGG ( measure_expr , ’ delimiter ’ ) WITHIN GROUP ( order_by_clause ) OVER query_partition_clause
  • 276. LN 5-102 Oracle Database SQL Language Reference The following group-set aggregate example lists, for each department ID in the hr.employees table, the employees in that department in order of their hire date: SELECT department_id "Dept.", LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date) "Employees" FROM employees GROUP BY department_id; Dept. Employees ------ ------------------------------------------------------------ 10 Whalen 20 Hartstein; Fay 30 Raphaely; Khoo; Tobias; Baida; Himuro; Colmenares 40 Mavris 50 Kaufling; Ladwig; Rajs; Sarchand; Bell; Mallin; Weiss; Davie s; Marlow; Bull; Everett; Fripp; Chung; Nayer; Dilly; Bissot ; Vollman; Stiles; Atkinson; Taylor; Seo; Fleaur; Matos; Pat el; Walsh; Feeney; Dellinger; McCain; Vargas; Gates; Rogers; Mikkilineni; Landry; Cabrio; Jones; Olson; OConnell; Sulliv an; Mourgos; Gee; Perkins; Grant; Geoni; Philtanker; Markle 60 Austin; Pataballa; Lorentz; Ernst; Hunold 70 Baer ... The following analytic example shows, for each employee hired earlier than September 1, 2003, the employee's department, hire date, and all other employees in that department also hired before September 1, 2003: SELECT department_id "Dept", hire_date "Date", last_name "Name", LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date, last_name) OVER (PARTITION BY department_id) as "Emp_list" FROM employees WHERE hire_date < '01-SEP-2003'; Dept Date Name Emp_list ----- --------- --------------- --------------------------------------------- 30 07-DEC-02 Raphaely Raphaely; Khoo 30 18-MAY-03 Khoo Raphaely; Khoo 40 07-JUN-02 Mavris Mavris 50 01-MAY-03 Kaufling Kaufling; Ladwig 50 14-JUL-03 Ladwig Kaufling; Ladwig 70 07-JUN-02 Baer Baer 90 13-JAN-01 De Haan De Haan; King 90 17-JUN-03 King De Haan; King 100 16-AUG-02 Faviet Faviet; Greenberg 100 17-AUG-02 Greenberg Faviet; Greenberg 110 07-JUN-02 Gietz Gietz; Higgins 110 07-JUN-02 Higgins Gietz; Higgins LN Syntax Purpose LN returns the natural logarithm of n, where n is greater than 0. LN ( n )
  • 277. LNNVL Functions 5-103 This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the natural logarithm of 95: SELECT LN(95) "Natural log of 95" FROM DUAL; Natural log of 95 ----------------- 4.55387689 LNNVL Syntax Purpose LNNVL provides a concise way to evaluate a condition when one or both operands of the condition may be null. The function can be used only in the WHERE clause of a query. It takes as an argument a condition and returns TRUE if the condition is FALSE or UNKNOWN and FALSE if the condition is TRUE. LNNVL can be used anywhere a scalar expression can appear, even in contexts where the IS [NOT] NULL, AND, or OR conditions are not valid but would otherwise be required to account for potential nulls. Oracle Database sometimes uses the LNNVL function internally in this way to rewrite NOT IN conditions as NOT EXISTS conditions. In such cases, output from EXPLAIN PLAN shows this operation in the plan table output. The condition can evaluate any scalar values but cannot be a compound condition containing AND, OR, or BETWEEN. The table that follows shows what LNNVL returns given that a = 2 and b is null. Examples Suppose that you want to know the number of employees with commission rates of less than 20%, including employees who do not receive commissions. The following query returns only employees who actually receive a commission of less than 20%: See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion Condition Truth of Condition LNNVL Return Value a = 1 FALSE TRUE a = 2 TRUE FALSE a IS NULL FALSE TRUE b = 1 UNKNOWN TRUE b IS NULL TRUE FALSE a = b UNKNOWN TRUE LNNVL ( condition )
  • 278. LOCALTIMESTAMP 5-104 Oracle Database SQL Language Reference SELECT COUNT(*) FROM employees WHERE commission_pct < .2; COUNT(*) ---------- 11 To include the 72 employees who receive no commission at all, you could rewrite the query using the LNNVL function as follows: SELECT COUNT(*) FROM employees WHERE LNNVL(commission_pct >= .2); COUNT(*) ---------- 83 LOCALTIMESTAMP Syntax Purpose LOCALTIMESTAMP returns the current date and time in the session time zone in a value of data type TIMESTAMP. The difference between this function and CURRENT_ TIMESTAMP is that LOCALTIMESTAMP returns a TIMESTAMP value while CURRENT_ TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value. The optional argument timestamp_precision specifies the fractional second precision of the time value returned. Examples This example illustrates the difference between LOCALTIMESTAMP and CURRENT_ TIMESTAMP: ALTER SESSION SET TIME_ZONE = '-5:00'; SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL; CURRENT_TIMESTAMP LOCALTIMESTAMP ------------------------------------------------------------------- 04-APR-00 01.27.18.999220 PM -05:00 04-APR-00 01.27.19 PM ALTER SESSION SET TIME_ZONE = '-8:00'; SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL; CURRENT_TIMESTAMP LOCALTIMESTAMP ----------------------------------- ------------------------------ 04-APR-00 10.27.45.132474 AM -08:00 04-APR-00 10.27.451 AM When you use the LOCALTIMESTAMP with a format mask, take care that the format mask matches the value returned by the function. For example, consider the following table: CREATE TABLE local_test (col1 TIMESTAMP WITH LOCAL TIME ZONE); See Also: CURRENT_TIMESTAMP on page 5-55, "TIMESTAMP Data Type" on page 3-18, and "TIMESTAMP WITH TIME ZONE Data Type" on page 3-18 LOCALTIMESTAMP ( timestamp_precision )
  • 279. LOWER Functions 5-105 The following statement fails because the mask does not include the TIME ZONE portion of the return type of the function: INSERT INTO local_test VALUES (TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF')); The following statement uses the correct format mask to match the return type of LOCALTIMESTAMP: INSERT INTO local_test VALUES (TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM')); LOG Syntax Purpose LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other than 0 or 1 and n2 can be any positive value. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If any argument is BINARY_ FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise the function returns NUMBER. Examples The following example returns the log of 100: SELECT LOG(10,100) "Log base 10 of 100" FROM DUAL; Log base 10 of 100 ------------------ 2 LOWER Syntax Purpose LOWER returns char, with all letters lowercase. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same data type as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set. For linguistic-sensitive lowercase, refer to NLS_LOWER on page 5-119. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion LOG ( n2 , n1 ) LOWER ( char )
  • 280. LPAD 5-106 Oracle Database SQL Language Reference Examples The following example returns a string in lowercase: SELECT LOWER('MR. SCOTT MCMILLAN') "Lowercase" FROM DUAL; Lowercase -------------------- mr. scott mcmillan LPAD Syntax Purpose LPAD returns expr1, left-padded to length n characters with the sequence of characters in expr2. This function is useful for formatting the output of a query. Both expr1 and expr2 can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if expr1 is a character data type, NVARCHAR2 if expr1 is a national character data type, and a LOB if expr1 is a LOB data type. The string returned is in the same character set as expr1. The argument n must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify expr2, then the default is a single blank. If expr1 is longer than n, then this function returns the portion of expr1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multibyte character sets, the display length of a character string can differ from the number of characters in the string. Examples The following example left-pads a string with the asterisk (*) and period (.) characters: SELECT LPAD('Page 1',15,'*.') "LPAD example" FROM DUAL; LPAD example --------------- *.*.*.*.*Page 1 LTRIM Syntax LPAD ( expr1 , n , expr2 ) LTRIM ( char , set )
  • 281. MAKE_REF Functions 5-107 Purpose LTRIM removes from the left end of char all of the characters contained in set. If you do not specify set, then it defaults to a single blank. If char is a character literal, then you must enclose it in single quotation marks. Oracle Database begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result. Both char and set can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is a character data type, NVARCHAR2 if char is a national character data type, and a LOB if char is a LOB data type. Examples The following example trims the redundant first word from a group of product names in the oe.products table: SELECT product_name, LTRIM(product_name, 'Monitor ') "Short Name" FROM products WHERE product_name LIKE 'Monitor%'; PRODUCT_NAME Short Name -------------------- --------------- Monitor 17/HR 17/HR Monitor 17/HR/F 17/HR/F Monitor 17/SD 17/SD Monitor 19/SD 19/SD Monitor 19/SD/M 19/SD/M Monitor 21/D 21/D Monitor 21/HR 21/HR Monitor 21/HR/M 21/HR/M Monitor 21/SD 21/SD Monitor Hinge - HD Hinge - HD Monitor Hinge - STD Hinge - STD MAKE_REF Syntax Purpose MAKE_REF creates a REF to a row of an object view or a row in an object table whose object identifier is primary key based. This function is useful, for example, if you are creating an object view See Also: RTRIM on page 5-178 See Also: Oracle Database Object-Relational Developer's Guide for more information about object views and DEREF on page 5-63 MAKE_REF ( table view , key , )
  • 282. MAX 5-108 Oracle Database SQL Language Reference Examples The sample schema oe contains an object view oc_inventories based on inventory_typ. The object identifier is product_id. The following example creates a REF to the row in the oc_inventories object view with a product_id of 3003: SELECT MAKE_REF (oc_inventories, 3003) FROM DUAL; MAKE_REF(OC_INVENTORIES,3003) ------------------------------------------------------------------ 00004A038A0046857C14617141109EE03408002082543600000014260100010001 00290090606002A00078401FE0000000B03C21F040000000000000000000000000 0000000000 MAX Syntax Purpose MAX returns maximum value of expr. You can use it as an aggregate or analytic function. Aggregate Example The following example determines the highest salary in the hr.employees table: SELECT MAX(salary) "Maximum" FROM employees; Maximum ---------- 24000 Analytic Example The following example calculates, for each employee, the highest salary of the employees reporting to the same manager as the employee. SELECT manager_id, last_name, salary, MAX(salary) OVER (PARTITION BY manager_id) AS mgr_max FROM employees ORDER BY manager_id, last_name, salary, mgr_max; MANAGER_ID LAST_NAME SALARY MGR_MAX ---------- ------------------------- ---------- ---------- 100 Cambrault 11000 17000 100 De Haan 17000 17000 100 Errazuriz 12000 17000 See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr, "Floating-Point Numbers" on page 3-12 for information on binary-float comparison semantics, and "Aggregate Functions" on page 5-9 MAX ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 283. MEDIAN Functions 5-109 100 Fripp 8200 17000 100 Hartstein 13000 17000 100 Kaufling 7900 17000 100 Kochhar 17000 17000 . . . If you enclose this query in the parent query with a predicate, then you can determine the employee who makes the highest salary in each department: SELECT manager_id, last_name, salary FROM (SELECT manager_id, last_name, salary, MAX(salary) OVER (PARTITION BY manager_id) AS rmax_sal FROM employees) WHERE salary = rmax_sal ORDER BY manager_id, last_name, salary; MANAGER_ID LAST_NAME SALARY ---------- ------------------------- ---------- 100 De Haan 17000 100 Kochhar 17000 101 Greenberg 12000 101 Higgins 12000 102 Hunold 9000 103 Ernst 6000 108 Faviet 9000 114 Khoo 3100 120 Nayer 3200 120 Taylor 3200 121 Sarchand 4200 122 Chung 3800 123 Bell 4000 124 Rajs 3500 145 Tucker 10000 146 King 10000 147 Vishney 10500 148 Ozer 11500 149 Abel 11000 201 Fay 6000 205 Gietz 8300 King 24000 22 rows selected. MEDIAN Syntax Purpose MEDIAN is an inverse distribution function that assumes a continuous distribution model. It takes a numeric or datetime value and returns the middle value or an interpolated value that would be the middle value once the values are sorted. Nulls are ignored in the calculation. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions MEDIAN ( expr ) OVER ( query_partition_clause )
  • 284. MEDIAN 5-110 Oracle Database SQL Language Reference This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If you specify only expr, then the function returns the same data type as the numeric data type of the argument. if you specify the OVER clause, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. The result of MEDIAN is computed by first ordering the rows. Using N as the number of rows in the group, Oracle calculates the row number (RN) of interest with the formula RN = (1 + (0.5*(N-1)). The final result of the aggregate function is computed by linear interpolation between the values from rows at row numbers CRN = CEILING(RN) and FRN = FLOOR(RN). The final result will be: if (CRN = FRN = RN) then (value of expression from row at RN) else (CRN - RN) * (value of expression for row at FRN) + (RN - FRN) * (value of expression for row at CRN) You can use MEDIAN as an analytic function. You can specify only the query_ partition_clause in its OVER clause. It returns, for each row, the value that would fall in the middle among a set of values within each partition. Compare this function with these functions: ■ PERCENTILE_CONT on page 5-133, which returns, for a given percentile, the value that corresponds to that percentile by way of interpolation. MEDIAN is the specific case of PERCENTILE_CONT where the percentile value defaults to 0.5. ■ PERCENTILE_DISC on page 5-135, which is useful for finding values for a given percentile without interpolation. Aggregate Example The following query returns the median salary for each department in the hr.employees table: SELECT department_id, MEDIAN(salary) FROM employees GROUP BY department_id ORDER BY department_id, median(salary); DEPARTMENT_ID MEDIAN(SALARY) ------------- -------------- 10 4400 20 9500 30 2850 40 6500 50 3100 60 4800 70 10000 80 8900 90 17000 100 8000 110 10150 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence
  • 285. MIN Functions 5-111 7000 Analytic Example The following query returns the median salary for each manager in a subset of departments in the hr.employees table: SELECT manager_id, employee_id, salary, MEDIAN(salary) OVER (PARTITION BY manager_id) "Median by Mgr" FROM employees WHERE department_id > 60 ORDER BY manager_id, employee_id, salary, "Median by Mgr"; MANAGER_ID EMPLOYEE_ID SALARY Median by Mgr ---------- ----------- ---------- ------------- 100 101 17000 13500 100 102 17000 13500 100 145 14000 13500 100 146 13500 13500 100 147 12000 13500 100 148 11000 13500 100 149 10500 13500 101 108 12000 12000 101 204 10000 12000 101 205 12000 12000 108 109 9000 7800 108 110 8200 7800 108 111 7700 7800 108 112 7800 7800 108 113 6900 7800 145 150 10000 8500 145 151 9500 8500 145 152 9000 8500 . . . MIN Syntax Purpose MIN returns minimum value of expr. You can use it as an aggregate or analytic function. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr, "Floating-Point Numbers" on page 3-12 for information on binary-float comparison semantics, and "Aggregate Functions" on page 5-9 MIN ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 286. MOD 5-112 Oracle Database SQL Language Reference Aggregate Example The following statement returns the earliest hire date in the hr.employees table: SELECT MIN(hire_date) "Earliest" FROM employees; Earliest --------- 13-JAN-01 Analytic Example The following example determines, for each employee, the employees who were hired on or before the same date as the employee. It then determines the subset of employees reporting to the same manager as the employee, and returns the lowest salary in that subset. SELECT manager_id, last_name, hire_date, salary, MIN(salary) OVER(PARTITION BY manager_id ORDER BY hire_date RANGE UNBOUNDED PRECEDING) AS p_cmin FROM employees ORDER BY manager_id, last_name, hire_date, salary, p_cmin; MANAGER_ID LAST_NAME HIRE_DATE SALARY P_CMIN ---------- ------------------------- --------- ---------- ---------- 100 Cambrault 15-OCT-07 11000 6500 100 De Haan 13-JAN-01 17000 17000 100 Errazuriz 10-MAR-05 12000 7900 100 Fripp 10-APR-05 8200 7900 100 Hartstein 17-FEB-04 13000 7900 100 Kaufling 01-MAY-03 7900 7900 100 Kochhar 21-SEP-05 17000 7900 100 Mourgos 16-NOV-07 5800 5800 100 Partners 05-JAN-05 13500 7900 100 Raphaely 07-DEC-02 11000 11000 100 Russell 01-OCT-04 14000 7900 . . . MOD Syntax Purpose MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Examples The following example returns the remainder of 11 divided by 4: See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence MOD ( n2 , n1 )
  • 287. MONTHS_BETWEEN Functions 5-113 SELECT MOD(11,4) "Modulus" FROM DUAL; Modulus ---------- 3 This function behaves differently from the classical mathematical modulus function when m is negative. The classical modulus can be expressed using the MOD function with this formula: n2 - n1 * FLOOR(n2/n1) The following table illustrates the difference between the MOD function and the classical modulus: MONTHS_BETWEEN Syntax Purpose MONTHS_BETWEEN returns number of months between dates date1 and date2. The month and the last day of the month are defined by the parameter NLS_CALENDAR. If date1 is later than date2, then the result is positive. If date1 is earlier than date2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2. Examples The following example calculates the months between two dates: SELECT MONTHS_BETWEEN (TO_DATE('02-02-1995','MM-DD-YYYY'), TO_DATE('01-01-1995','MM-DD-YYYY') ) "Months" FROM DUAL; Months ---------- 1.03225806 n2 n1 MOD(n2,n1) Classical Modulus 11 4 3 3 11 -4 3 -1 -11 4 -3 1 -11 -4 -3 -3 See Also: FLOOR on page 5-80 and REMAINDER on page 5-171, which is similar to MOD, but uses ROUND in its formula instead of FLOOR MONTHS_BETWEEN ( date1 , date2 )
  • 288. NANVL 5-114 Oracle Database SQL Language Reference NANVL Syntax Purpose The NANVL function is useful only for floating-point numbers of type BINARY_FLOAT or BINARY_DOUBLE. It instructs Oracle Database to return an alternative value n1 if the input value n2 is NaN (not a number). If n2 is not NaN, then Oracle returns n2. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Examples Using table float_point_demo created for TO_BINARY_DOUBLE on page 5-215, insert a second entry into the table: Insert INTO float_point_demo VALUES (0,'NaN','NaN'); SELECT * FROM float_point_demo; DEC_NUM BIN_DOUBLE BIN_FLOAT ---------- ---------- ---------- 1234.56 1.235E+003 1.235E+003 0 Nan Nan The following example returns bin_float if it is a number. Otherwise, 0 is returned. SELECT bin_float, NANVL(bin_float,0) FROM float_point_demo; BIN_FLOAT NANVL(BIN_FLOAT,0) ---------- ------------------ 1.235E+003 1.235E+003 Nan 0 NCHR Syntax See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion, "Floating-Point Numbers" on page 3-12 for information on binary-float comparison semantics, and "Numeric Precedence" on page 3-14 for information on numeric precedence NANVL ( n2 , n1 ) NCHR ( number )
  • 289. NEW_TIME Functions 5-115 Purpose NCHR returns the character having the binary equivalent to number in the national character set. The value returned is always NVARCHAR2. This function is equivalent to using the CHR function with the USING NCHAR_CS clause. This function takes as an argument a NUMBER value, or any value that can be implicitly converted to NUMBER, and returns a character. Examples The following examples return the nchar character 187: SELECT NCHR(187) FROM DUAL; NC -- > SELECT CHR(187 USING NCHAR_CS) FROM DUAL; CH -- > NEW_TIME Syntax Purpose NEW_TIME returns the date and time in time zone timezone2 when date and time in time zone timezone1 are date. Before using this function, you must set the NLS_ DATE_FORMAT parameter to display 24-hour time. The return type is always DATE, regardless of the data type of date. The arguments timezone1 and timezone2 can be any of these text strings: ■ AST, ADT: Atlantic Standard or Daylight Time ■ BST, BDT: Bering Standard or Daylight Time ■ CST, CDT: Central Standard or Daylight Time ■ EST, EDT: Eastern Standard or Daylight Time ■ GMT: Greenwich Mean Time ■ HST, HDT: Alaska-Hawaii Standard Time or Daylight Time. See Also: CHR on page 5-32 Note: This function takes as input only a limited number of time zones. You can have access to a much greater number of time zones by combining the FROM_TZ function and the datetime expression. See FROM_TZ on page 5-81 and the example for "Datetime Expressions" on page 6-8. NEW_TIME ( date , timezone1 , timezone2 )
  • 290. NEXT_DAY 5-116 Oracle Database SQL Language Reference ■ MST, MDT: Mountain Standard or Daylight Time ■ NST: Newfoundland Standard Time ■ PST, PDT: Pacific Standard or Daylight Time ■ YST, YDT: Yukon Standard or Daylight Time Examples The following example returns an Atlantic Standard time, given the Pacific Standard time equivalent: ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; SELECT NEW_TIME(TO_DATE( '11-10-99 01:23:45', 'MM-DD-YY HH24:MI:SS'), 'AST', 'PST') "New Date and Time" FROM DUAL; New Date and Time -------------------- 09-NOV-1999 21:23:45 NEXT_DAY Syntax Purpose NEXT_DAY returns the date of the first weekday named by char that is later than the date date. The return type is always DATE, regardless of the data type of date. The argument char must be a day of the week in the date language of your session, either the full name or the abbreviation. The minimum number of letters required is the number of letters in the abbreviated version. Any characters immediately following the valid abbreviation are ignored. The return value has the same hours, minutes, and seconds component as the argument date. Examples This example returns the date of the next Tuesday after February 2, 2001: SELECT NEXT_DAY('02-FEB-2001','TUESDAY') "NEXT DAY" FROM DUAL; NEXT DAY ----------- 06-FEB-2001 NLS_CHARSET_DECL_LEN Syntax NEXT_DAY ( date , char ) NLS_CHARSET_DECL_LEN ( byte_count , ’ char_set_id ’ )
  • 291. NLS_CHARSET_NAME Functions 5-117 Purpose NLS_CHARSET_DECL_LEN returns the declaration length (in number of characters) of an NCHAR column. The byte_count argument is the width of the column. The char_ set_id argument is the character set ID of the column. Examples The following example returns the number of characters that are in a 200-byte column when you are using a multibyte character set: SELECT NLS_CHARSET_DECL_LEN (200, nls_charset_id('ja16eucfixed')) FROM DUAL; NLS_CHARSET_DECL_LEN(200,NLS_CHARSET_ID('JA16EUCFIXED')) -------------------------------------------------------- 100 NLS_CHARSET_ID Syntax Purpose NLS_CHARSET_ID returns the character set ID number corresponding to character set name string. The string argument is a run-time VARCHAR2 value. The string value 'CHAR_CS' returns the database character set ID number of the server. The string value 'NCHAR_CS' returns the national character set ID number of the server. Invalid character set names return null. Examples The following example returns the character set ID of a character set: SELECT NLS_CHARSET_ID('ja16euc') FROM DUAL; NLS_CHARSET_ID('JA16EUC') ------------------------- 830 NLS_CHARSET_NAME Syntax See Also: Oracle Database Globalization Support Guide for a list of character set names NLS_CHARSET_ID ( string ) NLS_CHARSET_NAME ( number )
  • 292. NLS_INITCAP 5-118 Oracle Database SQL Language Reference Purpose NLS_CHARSET_NAME returns the name of the character set corresponding to ID number number. The character set name is returned as a VARCHAR2 value in the database character set. If number is not recognized as a valid character set ID, then this function returns null. Examples The following example returns the character set corresponding to character set ID number 2: SELECT NLS_CHARSET_NAME(2) FROM DUAL; NLS_CH ------ WE8DEC NLS_INITCAP Syntax Purpose NLS_INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric. Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of VARCHAR2 data type and is in the same character set as char. The value of 'nlsparam' can have this form: 'NLS_SORT = sort' where sort is either a linguistic sort sequence or BINARY. The linguistic sort sequence handles special linguistic requirements for case conversions. These requirements can result in a return value of a different length than the char. If you omit 'nlsparam', then this function uses the default sort sequence for your session. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following examples show how the linguistic sort sequence results in a different return value from the function: See Also: Oracle Database Globalization Support Guide for a list of character set IDs See Also: "Data Type Comparison Rules" on page 3-37 for more information. NLS_INITCAP ( char , ’ nlsparam ’ )
  • 293. NLS_UPPER Functions 5-119 SELECT NLS_INITCAP ('ijsland') "InitCap" FROM DUAL; InitCap ------- Ijsland SELECT NLS_INITCAP ('ijsland', 'NLS_SORT = XDutch') "InitCap" FROM DUAL; InitCap ------- IJsland NLS_LOWER Syntax Purpose NLS_LOWER returns char, with all letters lowercase. Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is a character data type and a LOB if char is a LOB data type. The return string is in the same character set as char. The 'nlsparam' can have the same form and serve the same purpose as in the NLS_ INITCAP function. Examples The following statement returns the lowercase form of the character string 'NOKTASINDA' using the XTurkish linguistic sort sequence. The Turkish uppercase I becoming a small, dotless i. SELECT NLS_LOWER ('NOKTASINDA', 'NLS_SORT = XTurkish') "Lowercase" FROM DUAL; NLS_UPPER Syntax Purpose NLS_UPPER returns char, with all letters uppercase. See Also: Oracle Database Globalization Support Guide for information on sort sequences NLS_LOWER ( char , ’ nlsparam ’ ) NLS_UPPER ( char , ’ nlsparam ’ )
  • 294. NLSSORT 5-120 Oracle Database SQL Language Reference Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is a character data type and a LOB if char is a LOB data type. The return string is in the same character set as char. The 'nlsparam' can have the same form and serve the same purpose as in the NLS_ INITCAP function. Examples The following example returns a string with all the letters converted to uppercase: SELECT NLS_UPPER ('große') "Uppercase" FROM DUAL; Upper ----- GROßE SELECT NLS_UPPER ('große', 'NLS_SORT = XGerman') "Uppercase" FROM DUAL; Upperc ------ GROSSE NLSSORT Syntax Purpose NLSSORT returns the string of bytes used to sort char. Both char and 'nlsparam' can be any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of RAW data type. The value of 'nlsparam' can have the form 'NLS_SORT = sort' where sort is a linguistic sort sequence or BINARY. If you omit 'nlsparam', then this function uses the default sort sequence for your session. If you specify BINARY, then this function returns char. If you specify 'nlsparam', then you can append to the linguistic sort name the suffix _ai to request an accent-insensitive sort or _ci to request a case-insensitive sort. Refer to Oracle Database Globalization Support Guide for more information on accent- and case-insensitive sorting. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. See Also: NLS_INITCAP on page 5-118 NLSSORT ( char , ’ nlsparam ’ )
  • 295. NLSSORT Functions 5-121 Examples This function can be used to specify sorting and comparison operations based on a linguistic sort sequence rather than on the binary value of a string. The following example creates a test table containing two values and shows how the values returned can be ordered by the NLSSORT function: CREATE TABLE test (name VARCHAR2(15)); INSERT INTO test VALUES ('Gaardiner'); INSERT INTO test VALUES ('Gaberd'); INSERT INTO test VALUES ('Gaasten'); SELECT * FROM test ORDER BY name; NAME --------------- Gaardiner Gaasten Gaberd SELECT * FROM test ORDER BY NLSSORT(name, 'NLS_SORT = XDanish'); NAME --------------- Gaberd Gaardiner Gaasten The following example shows how to use the NLSSORT function in comparison operations: SELECT * FROM test WHERE name > 'Gaberd' ORDER BY name; no rows selected SELECT * FROM test WHERE NLSSORT(name, 'NLS_SORT = XDanish') > NLSSORT('Gaberd', 'NLS_SORT = XDanish') ORDER BY name; NAME --------------- Gaardiner Gaasten If you frequently use NLSSORT in comparison operations with the same linguistic sort sequence, then consider this more efficient alternative: Set the NLS_COMP parameter (either for the database or for the current session) to LINGUISTIC, and set the NLS_ SORT parameter for the session to the desired sort sequence. Oracle Database will use that sort sequence by default for all sorting and comparison operations during the current session: ALTER SESSION SET NLS_COMP = 'LINGUISTIC'; ALTER SESSION SET NLS_SORT = 'XDanish'; SELECT * FROM test WHERE name > 'Gaberd' ORDER BY name; See Also: "Data Type Comparison Rules" on page 3-37 for more information.
  • 296. NTH_VALUE 5-122 Oracle Database SQL Language Reference NAME --------------- Gaardiner Gaasten NTH_VALUE Syntax Purpose NTH_VALUE returns the measure_expr value of the nth row in the window defined by the analytic_clause. The returned value has the data type of the measure_ expr. ■ {RESPECT | IGNORE} NULLS determines whether null values of measure_expr are included in or eliminated from the calculation. The default is RESPECT NULLS. ■ n determines the nth row for which the measure value is to be returned. n can be a constant, bind variable, column, or an expression involving them, as long as it resolves to a positive integer. The function returns NULL if the data source window has fewer than n rows. If n is null, then the function returns an error. ■ FROM {FIRST | LAST} determines whether the calculation begins at the first or last row of the window. The default is FROM FIRST. Examples The following example shows the minimum amount_sold value for the second channel_id in ascending order for each prod_id between 13 and 16: SELECT prod_id, channel_id, MIN(amount_sold), NTH_VALUE(MIN(amount_sold), 2) OVER (PARTITION BY prod_id ORDER BY channel_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) NV FROM sales WHERE prod_id BETWEEN 13 and 16 GROUP BY prod_id, channel_id; PROD_ID CHANNEL_ID MIN(AMOUNT_SOLD) NV ---------- ---------- ---------------- ---------- 13 2 907.34 906.2 13 3 906.2 906.2 13 4 842.21 906.2 See Also: Oracle Database Globalization Support Guide for information on sort sequences See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the analytic_clause See Also: Oracle Database Data Warehousing Guide for more information on the use of this function NTH_VALUE ( measure_expr , n ) FROM FIRST LAST RESPECT IGNORE NULLS OVER ( analytic_clause )
  • 297. NTILE Functions 5-123 14 2 1015.94 1036.72 14 3 1036.72 1036.72 14 4 935.79 1036.72 15 2 871.19 871.19 15 3 871.19 871.19 15 4 871.19 871.19 16 2 266.84 266.84 16 3 266.84 266.84 16 4 266.84 266.84 16 9 11.99 266.84 13 rows selected. NTILE Syntax Purpose NTILE is an analytic function. It divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr. The expr value must resolve to a positive constant for each partition. Oracle Database expects an integer, and if expr is a noninteger constant, then Oracle truncates the value to an integer. The return value is NUMBER. The number of rows in the buckets can differ by at most 1. The remainder values (the remainder of number of rows divided by buckets) are distributed one for each bucket, starting with bucket 1. If expr is greater than the number of rows, then a number of buckets equal to the number of rows will be filled, and the remaining buckets will be empty. You cannot nest analytic functions by using NTILE or any other analytic function for expr. However, you can use other built-in function expressions for expr. Examples The following example divides into 4 buckets the values in the salary column of the oe.employees table from Department 100. The salary column has 6 values in this department, so the two extra values (the remainder of 6 / 4) are allocated to buckets 1 and 2, which therefore have one more value than buckets 3 or 4. SELECT last_name, salary, NTILE(4) OVER (ORDER BY salary DESC) AS quartile FROM employees WHERE department_id = 100 ORDER BY last_name, salary, quartile; LAST_NAME SALARY QUARTILE See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of expr See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion NTILE ( expr ) OVER ( query_partition_clause order_by_clause )
  • 298. NULLIF 5-124 Oracle Database SQL Language Reference ------------------------- ---------- ---------- Chen 8200 2 Faviet 9000 1 Greenberg 12000 1 Popp 6900 4 Sciarra 7700 3 Urman 7800 2 NULLIF Syntax Purpose NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1. If both arguments are numeric data types, then Oracle Database determines the argument with the higher numeric precedence, implicitly converts the other argument to that data type, and returns that data type. If the arguments are not numeric, then they must be of the same data type, or Oracle returns an error. The NULLIF function is logically equivalent to the following CASE expression: CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END Examples The following example selects those employees from the sample schema hr who have changed jobs since they were hired, as indicated by a job_id in the job_history table different from the current job_id in the employees table: SELECT e.last_name, NULLIF(e.job_id, j.job_id) "Old Job ID" FROM employees e, job_history j WHERE e.employee_id = j.employee_id ORDER BY last_name, "Old Job ID"; LAST_NAME Old Job ID ------------------------- ---------- De Haan AD_VP Hartstein MK_MAN Kaufling ST_MAN Kochhar AD_VP Kochhar AD_VP Raphaely PU_MAN Taylor SA_REP Taylor Whalen AD_ASST Whalen See Also: "CASE Expressions" on page 6-5 NULLIF ( expr1 , expr2 )
  • 299. NUMTODSINTERVAL Functions 5-125 NUMTODSINTERVAL Syntax Purpose NUMTODSINTERVAL converts n to an INTERVAL DAY TO SECOND literal. The argument n can be any NUMBER value or an expression that can be implicitly converted to a NUMBER value. The argument interval_unit can be of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type. The value for interval_unit specifies the unit of n and must resolve to one of the following string values: ■ 'DAY' ■ 'HOUR' ■ 'MINUTE' ■ 'SECOND' interval_unit is case insensitive. Leading and trailing values within the parentheses are ignored. By default, the precision of the return is 9. Examples The following example uses NUMTODSINTERVAL in a COUNT analytic function to calculate, for each employee, the number of employees hired by the same manager within the past 100 days from his or her hire date. Refer to "Analytic Functions" on page 5-11 for more information on the syntax of the analytic functions. SELECT manager_id, last_name, hire_date, COUNT(*) OVER (PARTITION BY manager_id ORDER BY hire_date RANGE NUMTODSINTERVAL(100, 'day') PRECEDING) AS t_count FROM employees; MANAGER_ID LAST_NAME HIRE_DATE T_COUNT ---------- ------------------------- --------- ---------- 100 De Haan 13-JAN-01 1 100 Raphaely 07-DEC-02 1 100 Kaufling 01-MAY-03 1 100 Hartstein 17-FEB-04 1 100 Weiss 18-JUL-04 1 . . . 149 Grant 24-MAY-07 1 149 Johnson 04-JAN-08 1 201 Fay 17-AUG-05 1 205 Gietz 07-JUN-02 1 King 17-JUN-03 1 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion NUMTODSINTERVAL ( n , ’ interval_unit ’ )
  • 300. NUMTOYMINTERVAL 5-126 Oracle Database SQL Language Reference NUMTOYMINTERVAL Syntax Purpose NUMTOYMINTERVAL converts number n to an INTERVAL YEAR TO MONTH literal. The argument n can be any NUMBER value or an expression that can be implicitly converted to a NUMBER value. The argument interval_unit can be of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type. The value for interval_unit specifies the unit of n and must resolve to one of the following string values: ■ 'YEAR' ■ 'MONTH' interval_unit is case insensitive. Leading and trailing values within the parentheses are ignored. By default, the precision of the return is 9. Examples The following example uses NUMTOYMINTERVAL in a SUM analytic function to calculate, for each employee, the total salary of employees hired in the past one year from his or her hire date. Refer to "Analytic Functions" on page 5-11 for more information on the syntax of the analytic functions. SELECT last_name, hire_date, salary, SUM(salary) OVER (ORDER BY hire_date RANGE NUMTOYMINTERVAL(1,'year') PRECEDING) AS t_sal FROM employees ORDER BY last_name, hire_date; LAST_NAME HIRE_DATE SALARY T_SAL ------------------------- --------- ---------- ---------- Abel 11-MAY-04 11000 90300 Ande 24-MAR-08 6400 112500 Atkinson 30-OCT-05 2800 177000 . . . Walsh 24-APR-06 3100 177200 Weiss 18-JUL-04 8000 70900 Whalen 17-SEP-03 4400 54000 Zlotkey 29-JAN-08 10500 119000 NVL Syntax See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion NUMTOYMINTERVAL ( n , ’ interval_unit ’ ) NVL ( expr1 , expr2 )
  • 301. NVL2 Functions 5-127 Purpose NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1. The arguments expr1 and expr2 can have any data type. If their data types are different, then Oracle Database implicitly converts one to the other. If they are cannot be converted implicitly, the database returns an error. The implicit conversion is implemented as follows: ■ If expr1 is character data, then Oracle Database converts expr2 to the data type of expr1 before comparing them and returns VARCHAR2 in the character set of expr1. ■ If expr1 is numeric, then Oracle determines which argument has the highest numeric precedence, implicitly converts the other argument to that data type, and returns that data type. Examples The following example returns a list of employee names and commissions, substituting "Not Applicable" if the employee receives no commission: SELECT last_name, NVL(TO_CHAR(commission_pct), 'Not Applicable') "COMMISSION" FROM employees WHERE last_name LIKE 'B%' ORDER BY last_name; LAST_NAME COMMISSION ------------------------- ---------------------------------------- Baer Not Applicable Baida Not Applicable Banda .1 Bates .15 Bell Not Applicable Bernstein .25 Bissot Not Applicable Bloom .2 Bull Not Applicable NVL2 Syntax Purpose NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3. The argument expr1 can have any data type. The arguments expr2 and expr3 can have any data types except LONG. If the data types of expr2 and expr3 are different: See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence NVL2 ( expr1 , expr2 , expr3 )
  • 302. ORA_DST_AFFECTED 5-128 Oracle Database SQL Language Reference ■ If expr2 is character data, then Oracle Database converts expr3 to the data type of expr2 before comparing them unless expr3 is a null constant. In that case, a data type conversion is not necessary. Oracle returns VARCHAR2 in the character set of expr2. ■ If expr2 is character data, then Oracle Database converts expr3 to the data type of expr2 before returning a value unless expr3 is a null constant. In that case, a data type conversion is not necessary, and the database returns VARCHAR2 in the character set of expr2. Examples The following example shows whether the income of some employees is made up of salary plus commission, or just salary, depending on whether the commission_pct column of employees is null or not. SELECT last_name, salary, NVL2(commission_pct, salary + (salary * commission_pct), salary) income FROM employees WHERE last_name like 'B%' ORDER BY last_name; LAST_NAME SALARY INCOME ------------------------- ---------- ---------- Baer 10000 10000 Baida 2900 2900 Banda 6200 6882 Bates 7300 8468 Bell 4000 4000 Bernstein 9500 11970 Bissot 3300 3300 Bloom 10000 12100 Bull 4100 4100 ORA_DST_AFFECTED Syntax Purpose ORA_DST_AFFECTED is useful when you are changing the time zone data file for your database. The function takes as an argument a datetime expression that resolves to a TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP WITH TIME ZONE values. The function returns 1 if the datetime value is affected by or will result in a "nonexisting time" or "duplicate time" error with the new time zone data. Otherwise, it returns 0. This function can be issued only when changing the time zone data file of the database and upgrading the timestamp with the time zone data, and only between the execution of the DBMS_DST.BEGIN_PREPARE and the DBMS_DST.END_PREPARE procedures or between the execution of the DBMS_DST.BEGIN_UPGRADE and the DBMS_DST.END_UPGRADE procedures. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence ORA_DST_AFFECTED ( datetime_expr )
  • 303. ORA_DST_CONVERT Functions 5-129 ORA_DST_CONVERT Syntax Purpose ORA_DST_CONVERT is useful when you are changing the time zone data file for your database. The function lets you specify error handling for a specified datetime expression. ■ For datetime_expr, specify a datetime expression that resolves to a TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP WITH TIME ZONE values. ■ The optional second argument specifies handling of "duplicate time" errors. Specify 0 (false) to suppress the error by returning the source datetime value. This is the default. Specify 1 (true) to allow the database to return the duplicate time error. ■ The optional third argument specifies handling of "nonexisting time" errors. Specify 0 (false) to suppress the error by returning the source datetime value. This is the default. Specify 1 (true) to allow the database to return the nonexisting time error. If no error occurs, this function returns a value of the same data type as datetime_ expr (a TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP WITH TIME ZONE values). The returned datetime value when interpreted with the new time zone file corresponds to datetime_expr interpreted with the old time zone file. This function can be issued only when changing the time zone data file of the database and upgrading the timestamp with the time zone data, and only between the execution of the DBMS_DST.BEGIN_UPGRADE and the DBMS_DST.END_UPGRADE procedures. See Also: Oracle Database Globalization Support Guide for more information on time zone datafiles and on how Oracle Database handles daylight saving time, and Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DST package See Also: Oracle Database Globalization Support Guide for more information on time zone datafiles and on how Oracle Database handles daylight saving time, and Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DST package ORA_DST_CONVERT ( datetime_expr , integer , integer )
  • 304. ORA_DST_ERROR 5-130 Oracle Database SQL Language Reference ORA_DST_ERROR Syntax Purpose ORA_DST_ERROR is useful when you are changing the time zone data file for your database. The function takes as an argument a datetime expression that resolves to a TIMESTAMP WITH TIME ZONE value or a VARRAY object that contains TIMESTAMP WITH TIME ZONE values, and indicates whether the datetime value will result in an error with the new time zone data. The return values are: ■ 0: the datetime value does not result in an error with the new time zone data. ■ 1878: the datetime value results in a "nonexisting time" error. ■ 1883: the datetime value results in a "duplicate time" error. This function can be issued only when changing the time zone data file of the database and upgrading the timestamp with the time zone data, and only between the execution of the DBMS_DST.BEGIN_PREPARE and the DBMS_DST.END_PREPARE procedures or between the execution of the DBMS_DST.BEGIN_UPGRADE and the DBMS_DST.END_UPGRADE procedures. ORA_HASH Syntax Purpose ORA_HASH is a function that computes a hash value for a given expression. This function is useful for operations such as analyzing a subset of data and generating a random sample. ■ The expr argument determines the data for which you want Oracle Database to compute a hash value. There are no restrictions on the length of data represented by expr, which commonly resolves to a column name. The expr cannot be a LONG or LOB type. It cannot be a user-defined object type unless it is a nested table type. The hash value for nested table types does not depend on the order of elements in the collection. All other data types are supported for expr. ■ The optional max_bucket argument determines the maximum bucket value returned by the hash function. You can specify any value between 0 and 4294967295. The default is 4294967295. See Also: Oracle Database Globalization Support Guide for more information on time zone datafiles and on how Oracle Database handles daylight saving time, and Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DST package ORA_DST_ERROR ( datetime_expr ) ORA_HASH ( expr , max_bucket , seed_value )
  • 305. PATH Functions 5-131 ■ The optional seed_value argument enables Oracle to produce many different results for the same set of data. Oracle applies the hash function to the combination of expr and seed_value. You can specify any value between 0 and 4294967295. The default is 0. The function returns a NUMBER value. Examples The following example creates a hash value for each combination of customer ID and product ID in the sh.sales table, divides the hash values into a maximum of 100 buckets, and returns the sum of the amount_sold values in the first bucket (bucket 0). The third argument (5) provides a seed value for the hash function. You can obtain different hash results for the same query by changing the seed value. SELECT SUM(amount_sold) FROM sales WHERE ORA_HASH(CONCAT(cust_id, prod_id), 99, 5) = 0; SUM(AMOUNT_SOLD) ---------------- 989431.14 PATH Syntax Purpose PATH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the relative path that leads to the resource specified in the parent condition. The correlation_integer can be any NUMBER integer and is used to correlate this ancillary function with its primary condition. Values less than 1 are treated as 1. Example Refer to the related function DEPTH on page 5-63 for an example using both of these ancillary functions of the EQUALS_PATH and UNDER_PATH conditions. See Also: EQUALS_PATH Condition on page 7-19 and UNDER_ PATH Condition on page 7-20 PATH ( correlation_integer )
  • 306. PERCENT_RANK 5-132 Oracle Database SQL Language Reference PERCENT_RANK Aggregate Syntax percent_rank_aggregate::= Analytic Syntax percent_rank_analytic::= Purpose PERCENT_RANK is similar to the CUME_DIST (cumulative distribution) function. The range of values returned by PERCENT_RANK is 0 to 1, inclusive. The first row in any set has a PERCENT_RANK of 0. The return value is NUMBER. ■ As an aggregate function, PERCENT_RANK calculates, for a hypothetical row r identified by the arguments of the function and a corresponding sort specification, the rank of row r minus 1 divided by the number of rows in the aggregate group. This calculation is made as if the hypothetical row r were inserted into the group of rows over which Oracle Database is to aggregate. The arguments of the function identify a single hypothetical row within each aggregate group. Therefore, they must all evaluate to constant expressions within each aggregate group. The constant argument expressions and the expressions in the ORDER BY clause of the aggregate match by position. Therefore the number of arguments must be the same and their types must be compatible. ■ As an analytic function, for a row r, PERCENT_RANK calculates the rank of r minus 1, divided by 1 less than the number of rows being evaluated (the entire query result set or a partition). See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion PERCENT_RANK ( expr , ) WITHIN GROUP ( ORDER BY expr DESC ASC NULLS FIRST LAST , ) PERCENT_RANK ( ) OVER ( query_partition_clause order_by_clause )
  • 307. PERCENTILE_CONT Functions 5-133 Aggregate Example The following example calculates the percent rank of a hypothetical employee in the sample table hr.employees with a salary of $15,500 and a commission of 5%: SELECT PERCENT_RANK(15000, .05) WITHIN GROUP (ORDER BY salary, commission_pct) "Percent-Rank" FROM employees; Percent-Rank ------------ .971962617 Analytic Example The following example calculates, for each employee, the percent rank of the employee's salary within the department: SELECT department_id, last_name, salary, PERCENT_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS pr FROM employees ORDER BY pr, salary; DEPARTMENT_ID LAST_NAME SALARY PR ------------- ------------------------- ---------- ---------- 10 Whalen 4400 0 40 Marvis 6500 0 . . . 80 Vishney 10500 .176470588 50 Everett 3900 .181818182 30 Khoo 3100 .2 . . . 80 Johnson 6200 .941176471 50 Markle 2200 .954545455 50 Philtanker 2200 .954545455 50 Olson 2100 1 . . . PERCENTILE_CONT Syntax Purpose PERCENTILE_CONT is an inverse distribution function that assumes a continuous distribution model. It takes a percentile value and a sort specification, and returns an interpolated value that would fall into that percentile value with respect to the sort specification. Nulls are ignored in the calculation. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the OVER clause PERCENTILE_CONT ( expr ) WITHIN GROUP ( ORDER BY expr DESC ASC ) OVER ( query_partition_clause )
  • 308. PERCENTILE_CONT 5-134 Oracle Database SQL Language Reference This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. The first expr must evaluate to a numeric value between 0 and 1, because it is a percentile value. This expr must be constant within each aggregation group. The ORDER BY clause takes a single expression that must be a numeric or datetime value, as these are the types over which Oracle can perform interpolation. The result of PERCENTILE_CONT is computed by linear interpolation between values after ordering them. Using the percentile value (P) and the number of rows (N) in the aggregation group, you can compute the row number you are interested in after ordering the rows with respect to the sort specification. This row number (RN) is computed according to the formula RN = (1+ (P*(N-1)). The final result of the aggregate function is computed by linear interpolation between the values from rows at row numbers CRN = CEILING(RN) and FRN = FLOOR(RN). The final result will be: If (CRN = FRN = RN) then the result is (value of expression from row at RN) Otherwise the result is (CRN - RN) * (value of expression for row at FRN) + (RN - FRN) * (value of expression for row at CRN) You can use the PERCENTILE_CONT function as an analytic function. You can specify only the query_partitioning_clause in its OVER clause. It returns, for each row, the value that would fall into the specified percentile among a set of values within each partition. The MEDIAN function is a specific case of PERCENTILE_CONT where the percentile value defaults to 0.5. For more information, refer to MEDIAN on page 5-109. Aggregate Example The following example computes the median salary in each department: SELECT department_id, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary DESC) "Median cont", PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC) "Median disc" FROM employees GROUP BY department_id ORDER BY department_id, "Median cont", "Median disc; DEPARTMENT_ID Median cont Median disc ------------- ----------- ----------- 10 4400 4400 20 9500 13000 30 2850 2900 40 6500 6500 50 3100 3100 60 4800 4800 70 10000 10000 80 8900 9000 90 17000 17000 100 8000 8200 110 10150 12000 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion
  • 309. PERCENTILE_DISC Functions 5-135 7000 7000 PERCENTILE_CONT and PERCENTILE_DISC may return different results. PERCENTILE_CONT returns a computed result after doing linear interpolation. PERCENTILE_DISC simply returns a value from the set of values that are aggregated over. When the percentile value is 0.5, as in this example, PERCENTILE_CONT returns the average of the two middle values for groups with even number of elements, whereas PERCENTILE_DISC returns the value of the first one among the two middle values. For aggregate groups with an odd number of elements, both functions return the value of the middle element. Analytic Example In the following example, the median for Department 60 is 4800, which has a corresponding percentile (Percent_Rank) of 0.5. None of the salaries in Department 30 have a percentile of 0.5, so the median value must be interpolated between 2900 (percentile 0.4) and 2800 (percentile 0.6), which evaluates to 2850. SELECT last_name, salary, department_id, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary DESC) OVER (PARTITION BY department_id) "Percentile_Cont", PERCENT_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) "Percent_Rank" FROM employees WHERE department_id IN (30, 60) ORDER BY last_name, salary, department_id, "Percentile_Cont", "Percent_Rank"; LAST_NAME SALARY DEPARTMENT_ID Percentile_Cont Percent_Rank ------------------------- ---------- ------------- --------------- ------------ Austin 4800 60 4800 .5 Baida 2900 30 2850 .4 Colmenares 2500 30 2850 1 Ernst 6000 60 4800 .25 Himuro 2600 30 2850 .8 Hunold 9000 60 4800 0 Khoo 3100 30 2850 .2 Lorentz 4200 60 4800 1 Pataballa 4800 60 4800 .5 Raphaely 11000 30 2850 0 Tobias 2800 30 2850 .6 PERCENTILE_DISC Syntax See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions of the OVER clause PERCENTILE_DISC ( expr ) WITHIN GROUP ( ORDER BY expr DESC ASC ) OVER ( query_partition_clause )
  • 310. PERCENTILE_DISC 5-136 Oracle Database SQL Language Reference Purpose PERCENTILE_DISC is an inverse distribution function that assumes a discrete distribution model. It takes a percentile value and a sort specification and returns an element from the set. Nulls are ignored in the calculation. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. The first expr must evaluate to a numeric value between 0 and 1, because it is a percentile value. This expression must be constant within each aggregate group. The ORDER BY clause takes a single expression that can be of any type that can be sorted. For a given percentile value P, PERCENTILE_DISC sorts the values of the expression in the ORDER BY clause and returns the value with the smallest CUME_DIST value (with respect to the same sort specification) that is greater than or equal to P. Aggregate Example See aggregate example for PERCENTILE_CONT on page 5-133. Analytic Example The following example calculates the median discrete percentile of the salary of each employee in the sample table hr.employees: SELECT last_name, salary, department_id, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC) OVER (PARTITION BY department_id) "Percentile_Disc", CUME_DIST() OVER (PARTITION BY department_id ORDER BY salary DESC) "Cume_Dist" FROM employees where department_id in (30, 60) ORDER BY last_name, salary, department_id, "Percentile_Disc", "Cume_Dist"; LAST_NAME SALARY DEPARTMENT_ID Percentile_Disc Cume_Dist ------------------------- ---------- ------------- --------------- ---------- Austin 4800 60 4800 .8 Baida 2900 30 2900 .5 Colmenares 2500 30 2900 1 Ernst 6000 60 4800 .4 Himuro 2600 30 2900 .833333333 Hunold 9000 60 4800 .2 Khoo 3100 30 2900 .333333333 Lorentz 4200 60 4800 1 Pataballa 4800 60 4800 .8 Raphaely 11000 30 2900 .166666667 Tobias 2800 30 2900 .666666667 The median value for Department 30 is 2900, which is the value whose corresponding percentile (Cume_Dist) is the smallest value greater than or equal to 0.5. The median value for Department 60 is 4800, which is the value whose corresponding percentile is the smallest value greater than or equal to 0.5. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion
  • 311. POWERMULTISET Functions 5-137 POWER Syntax Purpose POWER returns n2 raised to the n1 power. The base n2 and the exponent n1 can be any numbers, but if n2 is negative, then n1 must be an integer. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If any argument is BINARY_ FLOAT or BINARY_DOUBLE, then the function returns BINARY_DOUBLE. Otherwise the function returns NUMBER. Examples The following example returns 3 squared: SELECT POWER(3,2) "Raised" FROM DUAL; Raised ---------- 9 POWERMULTISET Syntax Purpose POWERMULTISET takes as input a nested table and returns a nested table of nested tables containing all nonempty subsets (called submultisets) of the input nested table. ■ expr can be any expression that evaluates to a nested table. ■ If expr resolves to null, then Oracle Database returns NULL. ■ If expr resolves to a nested table that is empty, then Oracle returns an error. ■ The element types of the nested table must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Examples First, create a data type that is a nested table of the cust_address_tab_type data type: CREATE TYPE cust_address_tab_tab_typ AS TABLE OF cust_address_tab_typ; See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion Note: This function is not supported in PL/SQL. POWER ( n2 , n1 ) POWERMULTISET ( expr )
  • 312. POWERMULTISET_BY_CARDINALITY 5-138 Oracle Database SQL Language Reference Now, select the nested table column cust_address_ntab from the customers_ demo table using the POWERMULTISET function: SELECT CAST(POWERMULTISET(cust_address_ntab) AS cust_address_tab_tab_typ) FROM customers_demo; CAST(POWERMULTISET(CUST_ADDRESS_NTAB) AS CUST_ADDRESS_TAB_TAB_TYP) (STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ------------------------------------------------------------------ CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP ('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))) CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP ('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'))) CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP ('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))) CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP ('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US'))) . . . The preceding example requires the customers_demo table and a nested table column containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. POWERMULTISET_BY_CARDINALITY Syntax Purpose POWERMULTISET_BY_CARDINALITY takes as input a nested table and a cardinality and returns a nested table of nested tables containing all nonempty subsets (called submultisets) of the nested table of the specified cardinality. ■ expr can be any expression that evaluates to a nested table. ■ cardinality can be any positive integer. ■ If expr resolves to null, then Oracle Database returns NULL. ■ If expr resolves to a nested table that is empty, then Oracle returns an error. ■ The element types of the nested table must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Examples First, duplicate the elements in all the nested table rows to increase the cardinality of the nested table rows to 2: UPDATE customers_demo SET cust_address_ntab = cust_address_ntab MULTISET UNION cust_address_ntab; Note: This function is not supported in PL/SQL. POWERMULTISET_BY_CARDINALITY ( expr , cardinality )
  • 313. PREDICTION Functions 5-139 Now, select the nested table column cust_address_ntab from the customers_ demo table using the POWERMULTISET_BY_CARDINALITY function: SELECT CAST(POWERMULTISET_BY_CARDINALITY(cust_address_ntab, 2) AS cust_address_tab_tab_typ) FROM customers_demo; CAST(POWERMULTISET_BY_CARDINALITY(CUST_ADDRESS_NTAB,2) AS CUST_ADDRESS_TAB_TAB_TYP) (STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ---------------------------------------------------------------------------------------- CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP (CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'), CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US'))) CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP (CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'), CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US'))) CUST_ADDRESS_TAB_TAB_TYP(CUST_ADDRESS_TAB_TYP (CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'), CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US'))) . . . The preceding example requires the customers_demo table and a nested table column containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. PREDICTION Syntax cost_matrix_clause::= mining_attribute_clause::= Purpose This function is for use with models created by the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns the best prediction for the model. The PREDICTION ( schema . model cost_matrix_clause mining_attribute_clause ) COST MODEL AUTO ( class_value , ) VALUES ( ( cost_value , ) , ) USING * schema . table . * expr AS alias ,
  • 314. PREDICTION 5-140 Oracle Database SQL Language Reference data type returned depends on the target value type used during the build of the model. For regression models, this function returns the expected value. cost_matrix_clause The COST clause is relevant for all classification models. ■ Specify COST MODEL to indicate that the scoring should be performed by taking into account the scoring cost matrix associated with the model. If no such scoring cost matrix exists, then the database returns an error. ■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this case the function returns the lowest cost prediction using the stored cost matrix if it exists. If no stored cost matrix exists, then the function returns the highest probability prediction. ■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to specify an inline cost matrix. You can use an inline cost matrix regardless of whether the model has an associated scoring cost matrix. If you omit the cost_matrix_clause clause, then the best prediction is the target class with the highest probability. If two or more classes are tied with the highest probability, the database chooses one class. mining_attribute_clause This maps the predictors that were provided when the model was built. Specifying USING * maps to all to the columns and expressions that can be retrieved from the underlying inputs (tables, views, and so on). ■ If you specify more predictors in the mining_attribute_clause than there are predictors used by the model, then the extra expressions are silently ignored. ■ If you specify fewer predictors than are used during the build, then the operation proceeds with the subset of predictors you specify and returns information on a best-effort basis. All types of models will return a result regardless of the number of predictors you specify in this clause. ■ If you specify a predictor with the same name as was used during the build but a different data type, then the database implicitly converts to produce a predictor value of the same type as the original build. Example The following example returns by gender the average age of customers who are likely to use an affinity card. The PREDICTION function takes into account only the cust_ marital_status, education, and household_size predictors. This example, and the prerequisite data mining operations, including the creation of the view, can be found in the demo file $ORACLE_ HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DATA_MINING package
  • 315. PREDICTION_BOUNDS Functions 5-141 is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT cust_gender, COUNT(*) AS cnt, ROUND(AVG(age)) AS avg_age FROM mining_data_apply_v WHERE PREDICTION(DT_SH_Clas_sample COST MODEL USING cust_marital_status, education, household_size) = 1 GROUP BY cust_gender ORDER BY cust_gender; C CNT AVG_AGE - ---------- ---------- F 170 38 M 685 42 PREDICTION_BOUNDS Syntax mining_attribute_clause::= Purpose The PREDICTION_BOUNDS function is for use only with generalized linear models (GLM). It returns an object with two NUMBER fields LOWER and UPPER. For a regression mining function, the bounds apply to value of the prediction. For a classification mining function, the bounds apply to the probability value. If the GLM was built using ridge regression, or if the covariance matrix is found to be singular during the build, then this function returns NULL for both fields. ■ For confidence_level, specify a number in the range (0,1). If you omit this clause, then the default value is 0.95. ■ The class_value argument is valid for classification models but not for regression models. By default, the function returns the bounds for the prediction with the highest probability. You can use the class_value argument to filter out the bounds value specific to a target value. You can specify class_value while leaving confidence_level at its default by specifying NULL for confidence_level. PREDICTION_BOUNDS ( schema . model , confidence_level , class_value mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 316. PREDICTION_COST 5-142 Oracle Database SQL Language Reference ■ The mining_attribute_clause has the same behavior for PREDICTION_ BOUNDS that it has for PREDICTION. Refer to mining_attribute_clause on page 5-140. Example The following example returns the distribution of customers whose ages are predicted to be between 25 and 45 years with 98% confidence. This example and the prerequisite data mining operations can be found in the demo file $ORACLE_HOME/rdbms/demo/dmglcdem.sql. The example is presented here to illustrate the syntactic use of the function. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. SELECT count(cust_id) cust_count, cust_marital_status FROM (SELECT cust_id, cust_marital_status FROM mining_data_apply_v WHERE PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).LOWER > 24 AND PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).UPPER < 46) GROUP BY cust_marital_status; CUST_COUNT CUST_MARITAL_STATUS -------------- -------------------- 46 NeverM 7 Mabsent 5 Separ. 35 Divorc. 72 Married PREDICTION_COST Syntax See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining and about generalized linear models ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DATA_MINING package PREDICTION_COST ( schema . model , class cost_matrix_clause mining_attribute_clause )
  • 317. PREDICTION_COST Functions 5-143 cost_matrix_clause::= mining_attribute_clause::= Purpose This function is for use with any classification model created by the DBMS_DATA_ MINING package or with the Oracle Data Mining Java API. It returns a measure of cost for a given prediction as an Oracle NUMBER. If you specify the optional class parameter, then the function returns the cost for the specified class. If you omit the class parameter, then the function returns the cost associated with the best prediction. You can use this form in conjunction with the PREDICTION function to obtain the best pair of prediction value and cost. The COST clause is relevant for all classification models. ■ Specify COST MODEL to indicate that the scoring should be performed by taking into account the scoring cost matrix associated with the model. If no such scoring cost matrix exists, then the database returns an error. ■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this case the function returns the cost using the stored cost matrix if it exists. If no stored cost matrix exists, then the function applies the unit cost matrix (0's on the diagonal and 1's everywhere else). This is equivalent to one minus probability for the given class.. ■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to specify an inline cost matrix. You can use an inline cost matrix regardless of whether the model has an associated scoring cost matrix. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. COST MODEL AUTO ( class_value , ) VALUES ( ( cost_value , ) , ) USING * schema . table . * expr AS alias ,
  • 318. PREDICTION_DETAILS 5-144 Oracle Database SQL Language Reference Example The following example finds the ten customers living in Italy who are least expensive to convince to use an affinity card. This example and the prerequisite data mining operations can be found in the demo file $ORACLE_HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. WITH cust_italy AS ( SELECT cust_id FROM mining_data_apply_v WHERE country_name = 'Italy' ORDER BY PREDICTION_COST(DT_SH_Clas_sample, 1 COST MODEL USING *) ASC, 1 ) SELECT cust_id FROM cust_italy WHERE rownum < 11; CUST_ID ---------- 100081 100179 100185 100324 100344 100554 100662 100733 101250 101306 10 rows selected. PREDICTION_DETAILS Syntax See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining in general and about costs in particular ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DATA_MINING package PREDICTION_DETAILS ( schema . model mining_attribute_clause )
  • 319. PREDICTION_DETAILS Functions 5-145 mining_attribute_clause::= Purpose This function is for use with decision tree models created by the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It returns an XML string containing model-specific information related to the scoring of the input row. In this release, the return value takes the following form: <Node id= "integer"/> where integer is the identifier of a data mining tree node. The form of the output is subject to change. It may be enhanced to provide additional prediction information in future releases. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. Example The following example uses all attributes from the mining_data_apply_v view that are relevant predictors for the DT_SH_Clas_sample decision tree model. For customers who work in technical support and are under age 25, it returns the tree node that results from scoring those records with the DT_SH_Clas_sample model. This example, and the prerequisite data mining operations, including the creation of the view, can be found in the demo files $ORACLE_ HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT cust_id, education, PREDICTION_DETAILS(DT_SH_Clas_sample using *) treenode FROM mining_data_apply_v WHERE occupation = 'TechSup' AND age < 25 ORDER BY cust_id; CUST_ID EDUCATION TREENODE ---------- --------------------- ------------------------- 100234 < Bach. <Node id="21"/> See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions USING * schema . table . * expr AS alias ,
  • 320. PREDICTION_PROBABILITY 5-146 Oracle Database SQL Language Reference 100320 < Bach. <Node id="21"/> 100349 < Bach. <Node id="21"/> 100419 < Bach. <Node id="21"/> 100583 < Bach. <Node id="13"/> 100657 HS-grad <Node id="21"/> 101171 < Bach. <Node id="21"/> 101225 < Bach. <Node id="21"/> 101338 < Bach. <Node id="21"/> 9 rows selected. PREDICTION_PROBABILITY Syntax mining_attribute_clause::= Purpose This function is for use with classification models created by the DBMS_DATA_MINING package or with the Oracle Data Mining Java API. It is not valid with other types of models. It returns the probability for a given prediction as an Oracle NUMBER. If you specify the optional class parameter, then the function returns the probability for the specified class. This is equivalent to the probability associated with choosing the given target class value. If you omit the class parameter, then the function returns the probability associated with the best prediction. You can use this form in conjunction with the PREDICTION function to obtain the best pair of prediction value and probability. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions PREDICTION_PROBABILITY ( schema . model , class mining_attribute_clause ) USING * schema . table . * expr AS alias ,
  • 321. PREDICTION_SET Functions 5-147 Example The following example returns the 10 customers living in Italy who are most likely to use an affinity card. This example, and the prerequisite data mining operations, including the creation of the view, can be found in the demo files $ORACLE_ HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT cust_id FROM ( SELECT cust_id FROM mining_data_apply_v WHERE country_name = 'Italy' ORDER BY PREDICTION_PROBABILITY(DT_SH_Clas_sample, 1 USING *) DESC, cust_id) WHERE rownum < 11; CUST_ID ---------- 100081 100179 100185 100324 100344 100554 100662 100733 101250 101306 10 rows selected. PREDICTION_SET Syntax cost_matrix_clause::= PREDICTION_SET ( schema . model , bestN , cutoff cost_matrix_clause mining_attribute_clause ) COST MODEL AUTO ( class_value , ) VALUES ( ( cost_value , ) , )
  • 322. PREDICTION_SET 5-148 Oracle Database SQL Language Reference mining_attribute_clause::= Purpose This function is for use with classification models created using the DBMS_DATA_ MINING package or with the Oracle Data Mining Java API. It is not valid with other types of models. It returns a varray of objects containing all classes in a multiclass classification scenario. The object fields are named PREDICTION, PROBABILITY, and COST. The data type of the PREDICTION field depends on the target value type used during the build of the model. The other two fields are both Oracle NUMBER. The elements are returned in the order of best prediction to worst prediction. ■ For bestN, specify a positive integer to restrict the returned target classes to the N having the highest probability, or lowest cost if cost matrix clause is specified. If multiple classes are tied in the Nth value, then the database still returns only N values. If you want to filter only by cutoff, specify NULL for this parameter. ■ For cutoff, specify a NUMBER value to restrict the returned target classes to those with a probability greater than or equal to (or a cost less than or equal to if cost matrix clause is specified) to the specified cutoff value. You can filter solely by cutoff by specifying NULL for bestN. When you specify values for both bestN and cutoff, you restrict the returned predictions to only those that are the bestN and have a probability (or cost when the cost_matrix_clause is specified) surpassing the threshold. The cost_matrix_clause clause is relevant for all classification models. When you specify this clause, both bestN and cutoff are treated with respect to the prediction cost, not the prediction probability. The value of bestN restricts the result to the target classes having the N best (lowest) costs, and cutoff restricts the target classes to those with a cost less than or equal to the specified cutoff. When you specify this clause, each object in the collection is a triplet of scalar values containing the prediction value (the data type of which depends on the target value type used during model build), the prediction probability, and the prediction cost (both Oracle NUMBER). If you omit this clause, then each object in the varray is a pair of scalars containing the prediction value and prediction probability. The data types returned are as described in the preceding paragraph. ■ Specify COST MODEL to indicate that the scoring should be performed by taking into account the scoring cost matrix associated with the model. If no such cost matrix exists, then the database returns an error. ■ Specify COST MODEL AUTO if the existence of a cost matrix is unknown. In this case: – If the stored cost matrix exists, then the result is the same as with COST MODEL. – If no stored cost matrix exists, then the result is almost the same as without the cost_matrix_clause, except the object in the collection is a triplet and the USING * schema . table . * expr AS alias ,
  • 323. PREDICTION_SET Functions 5-149 cost value is computed based on the unit cost matrix (0's on the diagonal and 1's everywhere else). This is equivalent to one minus probability for the given class. The cutoff parameter is ignored if no stored cost matrix exists. ■ Use the VALUES clause (the bottom branch of the cost_matrix_clause) to specify an inline cost matrix. You can use an inline cost matrix regardless of whether the model has an associated scoring cost matrix. The mining_attribute_clause behaves as described for the PREDICTION function. Refer to mining_attribute_clause on page 5-140. Example The following example lists, for ten customers, the likelihood and cost of using or rejecting an affinity card. This example has a binary target, but such a query is also useful in multiclass classification such as Low, Med, and High. This example and the prerequisite data mining operations can be found in the demo file $ORACLE_HOME/rdbms/demo/dmdtdemo.sql. General information on data mining demo files is available in Oracle Data Mining Administrator's Guide. The example is presented here to illustrate the syntactic use of the function. SELECT T.cust_id, S.prediction, S.probability, S.cost FROM (SELECT cust_id, PREDICTION_SET(dt_sh_clas_sample COST MODEL USING *) pset FROM mining_data_apply_v WHERE cust_id < 100011) T, TABLE(T.pset) S ORDER BY cust_id, S.prediction; CUST_ID PREDICTION PROBABILITY COST ---------- ---------- ----------- ----- 100001 0 .96682 .27 100001 1 .03318 .97 100002 0 .74038 2.08 100002 1 .25962 .74 100003 0 .90909 .73 100003 1 .09091 .91 100004 0 .90909 .73 100004 1 .09091 .91 100005 0 .27236 5.82 100005 1 .72764 .27 100006 0 1.00000 .00 100006 1 .00000 1.00 100007 0 .90909 .73 100007 1 .09091 .91 100008 0 .90909 .73 See Also: ■ Oracle Data Mining Concepts for detailed information about Oracle Data Mining ■ Oracle Data Mining Administrator's Guide for information on the demo programs available in the code ■ Oracle Data Mining Application Developer's Guide for detailed information about real-time scoring with the Data Mining SQL functions ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_DATA_MINING package
  • 324. PRESENTNNV 5-150 Oracle Database SQL Language Reference 100008 1 .09091 .91 100009 0 .27236 5.82 100009 1 .72764 .27 100010 0 .80808 1.54 100010 1 .19192 .81 20 rows selected. PRESENTNNV Syntax Purpose The PRESENTNNV function can be used only in the model_clause of the SELECT statement and then only on the right-hand side of a model rule. It returns expr1 when cell_reference exists prior to the execution of the model_clause and is not null when PRESENTNNV is evaluated. Otherwise it returns expr2. This function differs from NVL2 in that NVL2 evaluates the data at the time it is executed, rather than evaluating the data as it was prior to the execution of the model_clause. Examples In the following example, if a row containing sales for the Mouse Pad for the year 2002 exists, and the sales value is not null, then the sales value remains unchanged. If the row exists and the sales value is null, then the sales value is set to 10. If the row does not exist, then the row is created with the sales value set to 10. SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s['Mouse Pad', 2002] = PRESENTNNV(s['Mouse Pad', 2002], s['Mouse Pad', 2002], 10) ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 3000.72 France Mouse Pad 2001 3269.09 France Mouse Pad 2002 10 France Standard Mouse 1998 2390.83 See Also: ■ model_clause on page 19-28 and "Model Expressions" on page 6-11 for the syntax and semantics ■ NVL2 on page 5-127 for comparison PRESENTNNV ( cell_reference , expr1 , expr2 )
  • 325. PRESENTV Functions 5-151 France Standard Mouse 1999 2280.45 France Standard Mouse 2000 1274.31 France Standard Mouse 2001 2164.54 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 7375.46 Germany Mouse Pad 2001 9535.08 Germany Mouse Pad 2002 10 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 2637.31 Germany Standard Mouse 2001 6456.13 18 rows selected. The preceding example requires the view sales_view_ref. Refer to "Examples" on page 19-36 to create this view. PRESENTV Syntax Purpose The PRESENTV function can be used only within the model_clause of the SELECT statement and then only on the right-hand side of a model rule. It returns expr1 when, prior to the execution of the model_clause, cell_reference exists. Otherwise it returns expr2. Examples In the following example, if a row containing sales for the Mouse Pad for the year 2000 exists, then the sales value for the Mouse Pad for the year 2001 is set to the sales value for the Mouse Pad for the year 2000. If the row does not exist, then a row is created with the sales value for the Mouse Pad for year 20001 set to 0. SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s['Mouse Pad', 2001] = PRESENTV(s['Mouse Pad', 2000], s['Mouse Pad', 2000], 0) ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for the syntax and semantics PRESENTV ( cell_reference , expr1 , expr2 )
  • 326. PREVIOUS 5-152 Oracle Database SQL Language Reference France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 3000.72 France Mouse Pad 2001 3000.72 France Standard Mouse 1998 2390.83 France Standard Mouse 1999 2280.45 France Standard Mouse 2000 1274.31 France Standard Mouse 2001 2164.54 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 7375.46 Germany Mouse Pad 2001 7375.46 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 2637.31 Germany Standard Mouse 2001 6456.13 16 rows selected. The preceding example requires the view sales_view_ref. Refer to "The MODEL clause: Examples" on page 19-45 to create this view. PREVIOUS Syntax Purpose The PREVIOUS function can be used only in the model_clause of the SELECT statement and then only in the ITERATE ... [ UNTIL ] clause of the model_rules_ clause. It returns the value of cell_reference at the beginning of each iteration. Examples The following example repeats the rules, up to 1000 times, until the difference between the values of cur_val at the beginning and at the end of an iteration is less than one: SELECT dim_col, cur_val, num_of_iterations FROM (SELECT 1 AS dim_col, 10 AS cur_val FROM dual) MODEL DIMENSION BY (dim_col) MEASURES (cur_val, 0 num_of_iterations) IGNORE NAV UNIQUE DIMENSION RULES ITERATE (1000) UNTIL (PREVIOUS(cur_val[1]) - cur_val[1] < 1) ( cur_val[1] = cur_val[1]/2, num_of_iterations[1] = num_of_iterations[1] + 1 ); DIM_COL CUR_VAL NUM_OF_ITERATIONS ---------- ---------- ----------------- 1 .625 4 See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for the syntax and semantics PREVIOUS ( cell_reference )
  • 327. RANK Functions 5-153 RANK Aggregate Syntax rank_aggregate::= Analytic Syntax rank_analytic::= Purpose RANK calculates the rank of a value in a group of values. The return type is NUMBER. Rows with equal values for the ranking criteria receive the same rank. Oracle Database then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers. This function is useful for top-N and bottom-N reporting. ■ As an aggregate function, RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments must be the same and their types must be compatible. ■ As an analytic function, RANK computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the order_by_clause. See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence RANK ( expr , ) WITHIN GROUP ( ORDER BY expr DESC ASC NULLS FIRST LAST , ) RANK ( ) OVER ( query_partition_clause order_by_clause )
  • 328. RANK 5-154 Oracle Database SQL Language Reference Aggregate Example The following example calculates the rank of a hypothetical employee in the sample table hr.employees with a salary of $15,500 and a commission of 5%: SELECT RANK(15500, .05) WITHIN GROUP (ORDER BY salary, commission_pct) "Rank" FROM employees; Rank ---------- 105 Similarly, the following query returns the rank for a $15,500 salary among the employee salaries: SELECT RANK(15500) WITHIN GROUP (ORDER BY salary DESC) "Rank of 15500" FROM employees; Rank of 15500 -------------- 4 Analytic Example The following statement ranks the employees in the sample hr schema in department 80 based on their salary and commission. Identical salary values receive the same rank and cause nonconsecutive ranks. Compare this example with the example for DENSE_ RANK on page 5-61. SELECT department_id, last_name, salary, commission_pct, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC, commission_pct) "Rank" FROM employees WHERE department_id = 80 ORDER BY department_id, last_name, salary, commission_pct, "Rank"; DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank ------------- ------------------------- ---------- -------------- ---------- 80 Abel 11000 .3 5 80 Ande 6400 .1 31 80 Banda 6200 .1 32 80 Bates 7300 .15 26 80 Bernstein 9500 .25 14 80 Bloom 10000 .2 9 80 Cambrault 7500 .2 23 80 Cambrault 11000 .3 5 80 Doran 7500 .3 24 80 Errazuriz 12000 .3 3 80 Fox 9600 .2 12 80 Greene 9500 .15 13 80 Hall 9000 .25 16 80 Hutton 8800 .25 18 80 Johnson 6200 .1 32 80 King 10000 .35 11 80 Kumar 6100 .1 34 80 Lee 6800 .1 30 80 Livingston 8400 .2 20 80 Marvins 7200 .1 27 80 McEwen 9000 .35 17 80 Olsen 8000 .2 21 80 Ozer 11500 .25 4
  • 329. RAWTOHEX Functions 5-155 80 Partners 13500 .3 2 80 Russell 14000 .4 1 80 Sewall 7000 .25 29 80 Smith 7400 .15 25 80 Smith 8000 .3 22 80 Sully 9500 .35 15 80 Taylor 8600 .2 19 80 Tucker 10000 .3 10 80 Tuvault 7000 .15 28 80 Vishney 10500 .25 8 80 Zlotkey 10500 .2 7 RATIO_TO_REPORT Syntax Purpose RATIO_TO_REPORT is an analytic function. It computes the ratio of a value to the sum of a set of values. If expr evaluates to null, then the ratio-to-report value also evaluates to null. The set of values is determined by the query_partition_clause. If you omit that clause, then the ratio-to-report is computed over all rows returned by the query. You cannot nest analytic functions by using RATIO_TO_REPORT or any other analytic function for expr. However, you can use other built-in function expressions for expr. Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr. Examples The following example calculates the ratio-to-report value of each purchasing clerk's salary to the total of all purchasing clerks' salaries: SELECT last_name, salary, RATIO_TO_REPORT(salary) OVER () AS rr FROM employees WHERE job_id = 'PU_CLERK' ORDER BY last_name, salary, rr; LAST_NAME SALARY RR ------------------------- ---------- ---------- Baida 2900 .208633094 Colmenares 2500 .179856115 Himuro 2600 .18705036 Khoo 3100 .223021583 Tobias 2800 .201438849 RAWTOHEX Syntax See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions, including valid forms of expr RATIO_TO_REPORT ( expr ) OVER ( query_partition_clause ) RAWTOHEX ( raw )
  • 330. RAWTONHEX 5-156 Oracle Database SQL Language Reference Purpose RAWTOHEX converts raw to a character value containing its hexadecimal representation. As a SQL built-in function, RAWTOHEX accepts an argument of any scalar data type other than LONG, LONG RAW, CLOB, BLOB, or BFILE. It returns a VARCHAR2 value with the hexadecimal representation of bytes that make up the value of raw. Each byte is represented by two hexadecimal digits. Examples The following hypothetical example returns the hexadecimal equivalent of a RAW column value: SELECT RAWTOHEX(raw_column) "Graphics" FROM graphics; Graphics -------- 7D RAWTONHEX Syntax Purpose RAWTONHEX converts raw to a character value containing its hexadecimal representation. RAWTONHEX (raw) is equivalent to TO_NCHAR(RAWTOHEX(raw)). The value returned is always in the national character set. Examples The following hypothetical example returns the hexadecimal equivalent of a RAW column value: SELECT RAWTONHEX(raw_column), DUMP ( RAWTONHEX (raw_column) ) "DUMP" FROM graphics; RAWTONHEX(RA) DUMP ----------------------- ------------------------------ 7D Typ=1 Len=4: 0,55,0,68 Note: RAWTOHEX functions differently when used as a PL/SQL built-in function. Refer to Oracle Database Advanced Application Developer's Guide for more information. See Also: "RAW and LONG RAW Data Types" on page 3-24 and HEXTORAW on page 5-85 RAWTONHEX ( raw )
  • 331. REFTOHEX Functions 5-157 REF Syntax Purpose REF takes as its argument a correlation variable (table alias) associated with a row of an object table or an object view. A REF value is returned for the object instance that is bound to the variable or row. Examples The sample schema oe contains a type called cust_address_typ, described as follows: Attribute Type ----------------------------- ---------------- STREET_ADDRESS VARCHAR2(40) POSTAL_CODE VARCHAR2(10) CITY VARCHAR2(30) STATE_PROVINCE VARCHAR2(10) COUNTRY_ID CHAR(2) The following example creates a table based on the sample type oe.cust_address_ typ, inserts a row into the table, and retrieves a REF value for the object instance of the type in the addresses table: CREATE TABLE addresses OF cust_address_typ; INSERT INTO addresses VALUES ( '123 First Street', '4GF H1J', 'Our Town', 'Ourcounty', 'US'); SELECT REF(e) FROM addresses e; REF(E) ----------------------------------------------------------------------------------- 00002802097CD1261E51925B60E0340800208254367CD1261E51905B60E034080020825436010101820000 REFTOHEX Syntax Purpose REFTOHEX converts argument expr to a character value containing its hexadecimal equivalent. expr must return a REF. See Also: Oracle Database Object-Relational Developer's Guide for information on REFs REF ( correlation_variable ) REFTOHEX ( expr )
  • 332. REGEXP_COUNT 5-158 Oracle Database SQL Language Reference Examples The sample schema oe contains a warehouse_typ. The following example builds on that type to illustrate how to convert the REF value of a column to a character value containing its hexadecimal equivalent: CREATE TABLE warehouse_table OF warehouse_typ (PRIMARY KEY (warehouse_id)); CREATE TABLE location_table (location_number NUMBER, building REF warehouse_typ SCOPE IS warehouse_table); INSERT INTO warehouse_table VALUES (1, 'Downtown', 99); INSERT INTO location_table SELECT 10, REF(w) FROM warehouse_table w; SELECT REFTOHEX(building) FROM location_table; REFTOHEX(BUILDING) -------------------------------------------------------------------------- 0000220208859B5E9255C31760E034080020825436859B5E9255C21760E034080020825436 REGEXP_COUNT Syntax Purpose REGEXP_COUNT complements the functionality of the REGEXP_INSTR function by returning the number of times a pattern occurs in a source string. The function evaluates strings using characters as defined by the input character set. It returns an integer indicating the number of occurrences of pattern. If no match is found, then the function returns 0. ■ source_char is a character expression that serves as the search value. It is commonly a character column and can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ pattern is the regular expression. It is usually a text literal and can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512 bytes. If the data type of pattern is different from the data type of source_ char, then Oracle Database converts pattern to the data type of source_char. REGEXP_COUNT ignores subexpression parentheses in pattern. For example, the pattern '(123(45))' is equivalent to '12345'. For a listing of the operators you can specify in pattern, refer to Appendix D, "Oracle Regular Expression Support". ■ position is a positive integer indicating the character of source_char where Oracle should begin the search. The default is 1, meaning that Oracle begins the search at the first character of source_char. After finding the first occurrence of pattern, the database searches for a second occurrence beginning with the first character following the first occurrence. REGEXP_COUNT ( source_char , pattern , position , match_param )
  • 333. REGEXP_COUNT Functions 5-159 ■ match_param is a text literal that lets you change the default matching behavior of the function. You can specify one or more of the following values for match_ param: – 'i' specifies case-insensitive matching. – 'c' specifies case-sensitive matching. – 'n' allows the period (.), which is the match-any-character character, to match the newline character. If you omit this parameter, then the period does not match the newline character. – 'm' treats the source string as multiple lines. Oracle interprets the caret (^) and dollar sign ($) as the start and end, respectively, of any line anywhere in the source string, rather than only at the start or end of the entire source string. If you omit this parameter, then Oracle treats the source string as a single line. – 'x' ignores whitespace characters. By default, whitespace characters match themselves. If you specify multiple contradictory values, then Oracle uses the last value. For example, if you specify 'ic', then Oracle uses case-sensitive matching. If you specify a character other than those shown above, then Oracle returns an error. If you omit match_param, then: – The default case sensitivity is determined by the value of the NLS_SORT parameter. – A period (.) does not match the newline character. – The source string is treated as a single line. Examples The following example shows that subexpressions parentheses in pattern are ignored: SELECT REGEXP_COUNT('123123123123123', '(12)3', 1, 'i') REGEXP_COUNT FROM DUAL; REGEXP_COUNT ------------ 5 In the following example, the function begins to evaluate the source string at the third character, so skips over the first occurrence of pattern: SELECT REGEXP_COUNT('123123123123', '123', 3, 'i') COUNT FROM DUAL; COUNT ---------- 3
  • 334. REGEXP_INSTR 5-160 Oracle Database SQL Language Reference REGEXP_INSTR Syntax Purpose REGEXP_INSTR extends the functionality of the INSTR function by letting you search a string for a regular expression pattern. The function evaluates strings using characters as defined by the input character set. It returns an integer indicating the beginning or ending position of the matched substring, depending on the value of the return_option argument. If no match is found, then the function returns 0. This function complies with the POSIX regular expression standard and the Unicode Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle Regular Expression Support". ■ source_char is a character expression that serves as the search value. It is commonly a character column and can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ pattern is the regular expression. It is usually a text literal and can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512 bytes. If the data type of pattern is different from the data type of source_ char, then Oracle Database converts pattern to the data type of source_char. For a listing of the operators you can specify in pattern, refer to Appendix D, "Oracle Regular Expression Support". ■ position is a positive integer indicating the character of source_char where Oracle should begin the search. The default is 1, meaning that Oracle begins the search at the first character of source_char. ■ occurrence is a positive integer indicating which occurrence of pattern in source_char Oracle should search for. The default is 1, meaning that Oracle searches for the first occurrence of pattern. If occurrence is greater than 1, then the database searches for the second occurrence beginning with the first character following the first occurrence of pattern, and so forth. This behavior is different from the INSTR function, which begins its search for the second occurrence at the second character of the first occurrence. ■ return_option lets you specify what Oracle should return in relation to the occurrence: – If you specify 0, then Oracle returns the position of the first character of the occurrence. This is the default. – If you specify 1, then Oracle returns the position of the character following the occurrence. REGEXP_INSTR ( source_char , pattern , position , occurrence , return_opt , match_param , subexpr )
  • 335. REGEXP_INSTR Functions 5-161 ■ match_parameter is a text literal that lets you change the default matching behavior of the function. The behavior of this parameter is the same for this function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for detailed information. ■ For a pattern with subexpressions, subexpr is an integer from 0 to 9 indicating which subexpression in pattern is the target of the function. The subexpr is a fragment of pattern enclosed in parentheses. Subexpressions can be nested. Subexpressions are numbered in order in which their left parentheses appear in pattern. For example, consider the following expression: 0123(((abc)(de)f)ghi)45(678) This expression has five subexpressions in the following order: "abcdefghi" followed by "abcdef", "abc", "de" and "678". If subexpr is zero, then the position of the entire substring that matches the pattern is returned. If subexpr is greater than zero, then the position of the substring fragment that corresponds to subexpression number subexpr in the matched substring is returned. If pattern does not have at least subexpr subexpressions, the function returns zero. A null subexpr value returns NULL. The default value for subexpr is zero. Examples The following example examines the string, looking for occurrences of one or more non-blank characters. Oracle begins searching at the first character in the string and returns the starting position (default) of the sixth occurrence of one or more non-blank characters. SELECT REGEXP_INSTR('500 Oracle Parkway, Redwood Shores, CA', '[^ ]+', 1, 6) "REGEXP_INSTR" FROM DUAL; REGEXP_INSTR ------------ 37 The following example examines the string, looking for occurrences of words beginning with s, r, or p, regardless of case, followed by any six alphabetic characters. Oracle begins searching at the third character in the string and returns the position in the string of the character following the second occurrence of a seven-letter word beginning with s, r, or p, regardless of case. SELECT REGEXP_INSTR('500 Oracle Parkway, Redwood Shores, CA', '[s|r|p][[:alpha:]]{6}', 3, 2, 1, 'i') "REGEXP_INSTR" FROM DUAL; REGEXP_INSTR ------------ 28 See Also: ■ INSTR on page 5-91 and REGEXP_SUBSTR on page 5-164 ■ REGEXP_REPLACE on page 5-162 and REGEXP_LIKE Condition on page 7-17
  • 336. REGEXP_REPLACE 5-162 Oracle Database SQL Language Reference The following examples use the subexpr argument to search for a particular subexpression in pattern. The first statement returns the position in the source string of the first character in the first subexpression, which is '123': SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 1) "REGEXP_INSTR" FROM DUAL; REGEXP_INSTR ------------------- 1 The next statement returns the position in the source string of the first character in the second subexpression, which is '45678': SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 2) "REGEXP_INSTR" FROM DUAL; REGEXP_INSTR ------------------- 4 The next statement returns the position in the source string of the first character in the fourth subexpression, which is '78': SELECT REGEXP_INSTR('1234567890', '(123)(4(56)(78))', 1, 1, 0, 'i', 4) "REGEXP_INSTR" FROM DUAL; REGEXP_INSTR ------------------- 7 REGEXP_REPLACE Syntax Purpose REGEXP_REPLACE extends the functionality of the REPLACE function by letting you search a string for a regular expression pattern. By default, the function returns source_char with every occurrence of the regular expression pattern replaced with replace_string. The string returned is in the same character set as source_char. The function returns VARCHAR2 if the first argument is not a LOB and returns CLOB if the first argument is a LOB. This function complies with the POSIX regular expression standard and the Unicode Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle Regular Expression Support". REGEXP_REPLACE ( source_char , pattern , replace_string , position , occurrence , match_param )
  • 337. REGEXP_REPLACE Functions 5-163 ■ source_char is a character expression that serves as the search value. It is commonly a character column and can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB. ■ pattern is the regular expression. It is usually a text literal and can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512 bytes. If the data type of pattern is different from the data type of source_ char, then Oracle Database converts pattern to the data type of source_char. For a listing of the operators you can specify in pattern, refer to Appendix D, "Oracle Regular Expression Support". ■ replace_string can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. If replace_string is a CLOB or NCLOB, then Oracle truncates replace_string to 32K. The replace_string can contain up to 500 backreferences to subexpressions in the form n, where n is a number from 1 to 9. If n is the backslash character in replace_string, then you must precede it with the escape character (). For more information on backreference expressions, refer to the notes to "Oracle Regular Expression Support", Table D–1 on page D-1. ■ position is a positive integer indicating the character of source_char where Oracle should begin the search. The default is 1, meaning that Oracle begins the search at the first character of source_char. ■ occurrence is a nonnegative integer indicating the occurrence of the replace operation: – If you specify 0, then Oracle replaces all occurrences of the match. – If you specify a positive integer n, then Oracle replaces the nth occurrence. If occurrence is greater than 1, then the database searches for the second occurrence beginning with the first character following the first occurrence of pattern, and so forth. This behavior is different from the INSTR function, which begins its search for the second occurrence at the second character of the first occurrence. ■ match_parameter is a text literal that lets you change the default matching behavior of the function. The behavior of this parameter is the same for this function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for detailed information. Examples The following example examines phone_number, looking for the pattern xxx.xxx.xxxx. Oracle reformats this pattern with (xxx) xxx-xxxx. SELECT REGEXP_REPLACE(phone_number, '([[:digit:]]{3}).([[:digit:]]{3}).([[:digit:]]{4})', '(1) 2-3') "REGEXP_REPLACE" FROM employees ORDER BY "REGEXP_REPLACE"; REGEXP_REPLACE See Also: ■ REPLACE on page 5-172 ■ REGEXP_INSTR on page 5-160, REGEXP_SUBSTR on page 5-164, and REGEXP_LIKE Condition on page 7-17
  • 338. REGEXP_SUBSTR 5-164 Oracle Database SQL Language Reference -------------------------------------------------------------------------------- (515) 123-4444 (515) 123-4567 (515) 123-4568 (515) 123-4569 (515) 123-5555 . . . The following example examines country_name. Oracle puts a space after each non-null character in the string. SELECT REGEXP_REPLACE(country_name, '(.)', '1 ') "REGEXP_REPLACE" FROM countries; REGEXP_REPLACE -------------------------------------------------------------------------------- A r g e n t i n a A u s t r a l i a B e l g i u m B r a z i l C a n a d a . . . The following example examines the string, looking for two or more spaces. Oracle replaces each occurrence of two or more spaces with a single space. SELECT REGEXP_REPLACE('500 Oracle Parkway, Redwood Shores, CA', '( ){2,}', ' ') "REGEXP_REPLACE" FROM DUAL; REGEXP_REPLACE -------------------------------------- 500 Oracle Parkway, Redwood Shores, CA REGEXP_SUBSTR Syntax Purpose REGEXP_SUBSTR extends the functionality of the SUBSTR function by letting you search a string for a regular expression pattern. It is also similar to REGEXP_INSTR, but instead of returning the position of the substring, it returns the substring itself. This function is useful if you need the contents of a match string but not its position in the source string. The function returns the string as VARCHAR2 or CLOB data in the same character set as source_char. REGEXP_SUBSTR ( source_char , pattern , position , occurrence , match_param subexpr )
  • 339. REGEXP_SUBSTR Functions 5-165 This function complies with the POSIX regular expression standard and the Unicode Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle Regular Expression Support". ■ source_char is a character expression that serves as the search value. It is commonly a character column and can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ pattern is the regular expression. It is usually a text literal and can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512 bytes. If the data type of pattern is different from the data type of source_ char, then Oracle Database converts pattern to the data type of source_char. For a listing of the operators you can specify in pattern, refer to Appendix D, "Oracle Regular Expression Support". ■ position is a positive integer indicating the character of source_char where Oracle should begin the search. The default is 1, meaning that Oracle begins the search at the first character of source_char. ■ occurrence is a positive integer indicating which occurrence of pattern in source_char Oracle should search for. The default is 1, meaning that Oracle searches for the first occurrence of pattern. If occurrence is greater than 1, then the database searches for the second occurrence beginning with the first character following the first occurrence of pattern, and so forth. This behavior is different from the SUBSTR function, which begins its search for the second occurrence at the second character of the first occurrence. ■ match_parameter is a text literal that lets you change the default matching behavior of the function. The behavior of this parameter is the same for this function as for REGEXP_COUNT. Refer to REGEXP_COUNT on page 5-158 for detailed information. ■ For a pattern with subexpressions, subexpr is a nonnegative integer from 0 to 9 indicating which subexpression in pattern is to be returned by the function. This parameter has the same semantics that it has for the REGEXP_INSTR function. Refer to REGEXP_INSTR on page 5-160 for more information. Examples The following example examines the string, looking for the first substring bounded by commas. Oracle Database searches for a comma followed by one or more occurrences of non-comma characters followed by a comma. Oracle returns the substring, including the leading and trailing commas. SELECT REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA', ',[^,]+,') "REGEXPR_SUBSTR" FROM DUAL; REGEXPR_SUBSTR ----------------- , Redwood Shores, See Also: ■ SUBSTR on page 5-199 and REGEXP_INSTR on page 5-160 ■ REGEXP_REPLACE on page 5-162, and REGEXP_LIKE Condition on page 7-17
  • 340. REGR_ (Linear Regression) Functions 5-166 Oracle Database SQL Language Reference The following example examines the string, looking for http:// followed by a substring of one or more alphanumeric characters and optionally, a period (.). Oracle searches for a minimum of three and a maximum of four occurrences of this substring between http:// and either a slash (/) or the end of the string. SELECT REGEXP_SUBSTR('http://www.example.com/products', 'http://([[:alnum:]]+.?){3,4}/?') "REGEXP_SUBSTR" FROM DUAL; REGEXP_SUBSTR ---------------------- http://www.example.com/ The next two examples use the subexpr argument to return a specific subexpression of pattern. The first statement returns the first subexpression in pattern: SELECT REGEXP_SUBSTR('1234567890', '(123)(4(56)(78))', 1, 1, 'i', 1) "REGEXP_SUBSTR" FROM DUAL; REGEXP_SUBSTR ------------------- 123 The next statement returns the fourth subexpression in pattern: SELECT REGEXP_SUBSTR('1234567890', '(123)(4(56)(78))', 1, 1, 'i', 4) "REGEXP_SUBSTR" FROM DUAL; REGEXP_SUBSTR ------------------- 78 REGR_ (Linear Regression) Functions The linear regression functions are: ■ REGR_SLOPE ■ REGR_INTERCEPT ■ REGR_COUNT ■ REGR_R2 ■ REGR_AVGX ■ REGR_AVGY ■ REGR_SXX ■ REGR_SYY ■ REGR_SXY
  • 341. REGR_ (Linear Regression) Functions Functions 5-167 Syntax linear_regr::= Purpose The linear regression functions fit an ordinary-least-squares regression line to a set of number pairs. You can use them as both aggregate and analytic functions. These functions take as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. Oracle applies the function to the set of (expr1, expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Oracle computes all the regression functions simultaneously during a single pass through the data. expr1 is interpreted as a value of the dependent variable (a y value), and expr2 is interpreted as a value of the independent variable (an x value). ■ REGR_SLOPE returns the slope of the line. The return value is a numeric data type and can be null. After the elimination of null (expr1, expr2) pairs, it makes the following computation: COVAR_POP(expr1, expr2) / VAR_POP(expr2) ■ REGR_INTERCEPT returns the y-intercept of the regression line. The return value is a numeric data type and can be null. After the elimination of null (expr1, expr2) pairs, it makes the following computation: AVG(expr1) - REGR_SLOPE(expr1, expr2) * AVG(expr2) See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: "Aggregate Functions" on page 5-9 and "About SQL Expressions" on page 6-1 for information on valid forms of expr See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence REGR_SLOPE REGR_INTERCEPT REGR_COUNT REGR_R2 REGR_AVGX REGR_AVGY REGR_SXX REGR_SYY REGR_SXY ( expr1 , expr2 ) OVER ( analytic_clause )
  • 342. REGR_ (Linear Regression) Functions 5-168 Oracle Database SQL Language Reference ■ REGR_COUNT returns an integer that is the number of non-null number pairs used to fit the regression line. ■ REGR_R2 returns the coefficient of determination (also called R-squared or goodness of fit) for the regression. The return value is a numeric data type and can be null. VAR_POP(expr1) and VAR_POP(expr2) are evaluated after the elimination of null pairs. The return values are: NULL if VAR_POP(expr2) = 0 1 if VAR_POP(expr1) = 0 and VAR_POP(expr2) != 0 POWER(CORR(expr1,expr),2) if VAR_POP(expr1) > 0 and VAR_POP(expr2 != 0 All of the remaining regression functions return a numeric data type and can be null: ■ REGR_AVGX evaluates the average of the independent variable (expr2) of the regression line. It makes the following computation after the elimination of null (expr1, expr2) pairs: AVG(expr2) ■ REGR_AVGY evaluates the average of the dependent variable (expr1) of the regression line. It makes the following computation after the elimination of null (expr1, expr2) pairs: AVG(expr1) REGR_SXY, REGR_SXX, REGR_SYY are auxiliary functions that are used to compute various diagnostic statistics. ■ REGR_SXX makes the following computation after the elimination of null (expr1, expr2) pairs: REGR_COUNT(expr1, expr2) * VAR_POP(expr2) ■ REGR_SYY makes the following computation after the elimination of null (expr1, expr2) pairs: REGR_COUNT(expr1, expr2) * VAR_POP(expr1) ■ REGR_SXY makes the following computation after the elimination of null (expr1, expr2) pairs: REGR_COUNT(expr1, expr2) * COVAR_POP(expr1, expr2) The following examples are based on the sample tables sh.sales and sh.products. General Linear Regression Example The following example provides a comparison of the various linear regression functions used in their analytic form. The analytic form of these functions can be useful when you want to use regression statistics for calculations such as finding the salary predicted for each employee by the model. The sections that follow on the individual linear regression functions contain examples of the aggregate form of these functions. SELECT job_id, employee_id ID, salary, REGR_SLOPE(SYSDATE-hire_date, salary) OVER (PARTITION BY job_id) slope, REGR_INTERCEPT(SYSDATE-hire_date, salary)
  • 343. REGR_ (Linear Regression) Functions Functions 5-169 OVER (PARTITION BY job_id) intcpt, REGR_R2(SYSDATE-hire_date, salary) OVER (PARTITION BY job_id) rsqr, REGR_COUNT(SYSDATE-hire_date, salary) OVER (PARTITION BY job_id) count, REGR_AVGX(SYSDATE-hire_date, salary) OVER (PARTITION BY job_id) avgx, REGR_AVGY(SYSDATE-hire_date, salary) OVER (PARTITION BY job_id) avgy FROM employees WHERE department_id in (50, 80) ORDER BY job_id, employee_id; JOB_ID ID SALARY SLOPE INTCPT RSQR COUNT AVGX AVGY ---------- ----- ---------- ----- --------- ----- ------ ---------- --------- SA_MAN 145 14000 .355 -1707.035 .832 5 12200.000 2626.589 SA_MAN 146 13500 .355 -1707.035 .832 5 12200.000 2626.589 SA_MAN 147 12000 .355 -1707.035 .832 5 12200.000 2626.589 SA_MAN 148 11000 .355 -1707.035 .832 5 12200.000 2626.589 SA_MAN 149 10500 .355 -1707.035 .832 5 12200.000 2626.589 SA_REP 150 10000 .257 404.763 .647 29 8396.552 2561.244 SA_REP 151 9500 .257 404.763 .647 29 8396.552 2561.244 SA_REP 152 9000 .257 404.763 .647 29 8396.552 2561.244 SA_REP 153 8000 .257 404.763 .647 29 8396.552 2561.244 SA_REP 154 7500 .257 404.763 .647 29 8396.552 2561.244 SA_REP 155 7000 .257 404.763 .647 29 8396.552 2561.244 SA_REP 156 10000 .257 404.763 .647 29 8396.552 2561.244 ... REGR_SLOPE and REGR_INTERCEPT Examples The following example calculates the slope and regression of the linear regression model for time employed (SYSDATE - hire_date) and salary using the sample table hr.employees. Results are grouped by job_id. SELECT job_id, REGR_SLOPE(SYSDATE-hire_date, salary) slope, REGR_INTERCEPT(SYSDATE-hire_date, salary) intercept FROM employees WHERE department_id in (50,80) GROUP BY job_id ORDER BY job_id; JOB_ID SLOPE INTERCEPT ---------- ----- ------------ SA_MAN .355 -1707.030762 SA_REP .257 404.767151 SH_CLERK .745 159.015293 ST_CLERK .904 134.409050 ST_MAN .479 -570.077291 REGR_COUNT Examples The following example calculates the count of by job_id for time employed (SYSDATE - hire_date) and salary using the sample table hr.employees. Results are grouped by job_id. SELECT job_id, REGR_COUNT(SYSDATE-hire_date, salary) count FROM employees WHERE department_id in (30, 50)
  • 344. REGR_ (Linear Regression) Functions 5-170 Oracle Database SQL Language Reference GROUP BY job_id ORDER BY job_id, count; JOB_ID COUNT ---------- ---------- PU_CLERK 5 PU_MAN 1 SH_CLERK 20 ST_CLERK 20 ST_MAN 5 REGR_R2 Examples The following example calculates the coefficient of determination the linear regression of time employed (SYSDATE - hire_date) and salary using the sample table hr.employees: SELECT job_id, REGR_R2(SYSDATE-hire_date, salary) Regr_R2 FROM employees WHERE department_id in (80, 50) GROUP by job_id ORDER BY job_id, Regr_R2; JOB_ID REGR_R2 ---------- ---------- SA_MAN .83244748 SA_REP .647007156 SH_CLERK .879799698 ST_CLERK .742808493 ST_MAN .69418508 REGR_AVGY and REGR_AVGX Examples The following example calculates the average values for time employed (SYSDATE - hire_date) and salary using the sample table hr.employees. Results are grouped by job_id: SELECT job_id, REGR_AVGY(SYSDATE-hire_date, salary) avgy, REGR_AVGX(SYSDATE-hire_date, salary) avgx FROM employees WHERE department_id in (30,50) GROUP BY job_id ORDER BY job_id, avgy, avgx; JOB_ID AVGY AVGX ---------- ---------- ---------- PU_CLERK 2950.3778 2780 PU_MAN 4026.5778 11000 SH_CLERK 2773.0778 3215 ST_CLERK 2872.7278 2785 ST_MAN 3140.1778 7280 REGR_SXY, REGR_SXX, and REGR_SYY Examples The following example calculates three types of diagnostic statistics for the linear regression of time employed (SYSDATE - hire_date) and salary using the sample table hr.employees: SELECT job_id, REGR_SXY(SYSDATE-hire_date, salary) regr_sxy,
  • 345. REMAINDER Functions 5-171 REGR_SXX(SYSDATE-hire_date, salary) regr_sxx, REGR_SYY(SYSDATE-hire_date, salary) regr_syy FROM employees WHERE department_id in (80, 50) GROUP BY job_id ORDER BY job_id; JOB_ID REGR_SXY REGR_SXX REGR_SYY ---------- ---------- ----------- ---------- SA_MAN 3303500 9300000.0 1409642 SA_REP 16819665.5 65489655.2 6676562.55 SH_CLERK 4248650 5705500.0 3596039 ST_CLERK 3531545 3905500.0 4299084.55 ST_MAN 2180460 4548000.0 1505915.2 REMAINDER Syntax Purpose REMAINDER returns the remainder of n2 divided by n1. This function takes as arguments any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. The MOD function is similar to REMAINDER except that it uses FLOOR in its formula, whereas REMAINDER uses ROUND. Refer to MOD on page 5-112. ■ If n1 = 0 or m2 = infinity, then Oracle returns – An error if the arguments are of type NUMBER – NaN if the arguments are BINARY_FLOAT or BINARY_DOUBLE. ■ If n1 != 0, then the remainder is n2 - (n1*N) where N is the integer nearest n2/n1. If n2/n1 equals x.5, then N is the nearest even integer. ■ If n2 is a floating-point number, and if the remainder is 0, then the sign of the remainder is the sign of n2. Remainders of 0 are unsigned for NUMBER values. Examples Using table float_point_demo, created for the TO_BINARY_DOUBLE "Examples" on page 5-216, the following example divides two floating-point numbers and returns the remainder of that operation: SELECT bin_float, bin_double, REMAINDER(bin_float, bin_double) FROM float_point_demo; BIN_FLOAT BIN_DOUBLE REMAINDER(BIN_FLOAT,BIN_DOUBLE) ---------- ---------- ------------------------------- See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion and "Numeric Precedence" on page 3-14 for information on numeric precedence REMAINDER ( n2 , n1 )
  • 346. REPLACE 5-172 Oracle Database SQL Language Reference 1.235E+003 1.235E+003 5.859E-005 REPLACE Syntax Purpose REPLACE returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, then all occurrences of search_string are removed. If search_string is null, then char is returned. Both search_string and replacement_string, as well as char, can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is in the same character set as char. The function returns VARCHAR2 if the first argument is not a LOB and returns CLOB if the first argument is a LOB. REPLACE provides functionality related to that provided by the TRANSLATE function. TRANSLATE provides single-character, one-to-one substitution. REPLACE lets you substitute one string for another as well as to remove character strings. Examples The following example replaces occurrences of J with BL: SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL; Changes -------------- BLACK and BLUE ROUND (date) Syntax round_date::= Purpose ROUND returns date rounded to the unit specified by the format model fmt. This function is not sensitive to the NLS_CALENDAR session parameter. It operates according to the rules of the Gregorian calendar. The value returned is always of data type DATE, even if you specify a different datetime data type for date. If you omit fmt, then date is rounded to the nearest day. The date expression must resolve to a DATE value. See Also: TRANSLATE on page 5-233 REPLACE ( char , search_string , replacement_string ) ROUND ( date , fmt )
  • 347. ROUND (number) Functions 5-173 Examples The following example rounds a date to the first day of the following year: SELECT ROUND (TO_DATE ('27-OCT-00'),'YEAR') "New Year" FROM DUAL; New Year --------- 01-JAN-01 ROUND (number) Syntax round_number::= Purpose ROUND returns n rounded to integer places to the right of the decimal point. If you omit integer, then n is rounded to zero places. If integer is negative, then n is rounded off to the left of the decimal point. n can be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If you omit integer, then the function returns the value ROUND(n, 0) in the same data type as the numeric data type of n. If you include integer, then the function returns NUMBER. ROUND is implemented using the following rules: 1. If n is 0, then ROUND always returns 0 regardless of integer. 2. If n is negative, then ROUND(n, integer) returns -ROUND(-n, integer). 3. If n is positive, then ROUND(n, integer) = FLOOR(n * POWER(10, integer) + 0.5) * POWER(10, -integer) ROUND applied to a NUMBER value may give a slightly different result from ROUND applied to the same value expressed in floating-point. The different results arise from differences in internal representations of NUMBER and floating point values. The difference will be 1 in the rounded digit if a difference occurs. See Also: "ROUND and TRUNC Date Functions" on page 5-270 for the permitted format models to use in fmt ROUND ( n , integer )
  • 348. ROW_NUMBER 5-174 Oracle Database SQL Language Reference Examples The following example rounds a number to one decimal point: SELECT ROUND(15.193,1) "Round" FROM DUAL; Round ---------- 15.2 The following example rounds a number one digit to the left of the decimal point: SELECT ROUND(15.193,-1) "Round" FROM DUAL; Round ---------- 20 ROW_NUMBER Syntax Purpose ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1. By nesting a subquery using ROW_NUMBER inside a query that retrieves the ROW_ NUMBER values for a specified range, you can find a precise subset of rows from the results of the inner query. This use of the function lets you implement top-N, bottom-N, and inner-N reporting. For consistent results, the query must ensure a deterministic sort order. You cannot nest analytic functions by using ROW_NUMBER or any other analytic function for expr. However, you can use other built-in function expressions for expr. Refer to "About SQL Expressions" on page 6-1 for information on valid forms of expr. See Also: ■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ■ "Floating-Point Numbers" on page 3-12 for more information on how Oracle Database handles BINARY_FLOAT and BINARY_ DOUBLE values ■ FLOOR on page 5-80 and CEIL on page 5-31, TRUNC (number) on page 5-238 and MOD on page 5-112 for information on functions that perform related operations See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions ROW_NUMBER ( ) OVER ( query_partition_clause order_by_clause )
  • 349. ROW_NUMBER Functions 5-175 Examples The following example finds the three highest paid employees in each department in the hr.employees table. Fewer then three rows are returned for departments with fewer than three employees. SELECT department_id, first_name, last_name, salary FROM ( SELECT department_id, first_name, last_name, salary, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary desc) rn FROM employees ) WHERE rn <= 3 ORDER BY department_id, salary DESC, last_name; The following example is a join query on the sh.sales table. It finds the sales amounts in 2000 of the five top-selling products in 1999 and compares the difference between 2000 and 1999. The ten top-selling products are calculated within each distribution channel. SELECT sales_2000.channel_desc, sales_2000.prod_name, sales_2000.amt amt_2000, top_5_prods_1999_year.amt amt_1999, sales_2000.amt - top_5_prods_1999_year.amt amt_diff FROM /* The first subquery finds the 5 top-selling products per channel in year 1999. */ (SELECT channel_desc, prod_name, amt FROM ( SELECT channel_desc, prod_name, sum(amount_sold) amt, ROW_NUMBER () OVER (PARTITION BY channel_desc ORDER BY SUM(amount_sold) DESC) rn FROM sales, times, channels, products WHERE sales.time_id = times.time_id AND times.calendar_year = 1999 AND channels.channel_id = sales.channel_id AND products.prod_id = sales.prod_id GROUP BY channel_desc, prod_name ) WHERE rn <= 5 ) top_5_prods_1999_year, /* The next subquery finds sales per product and per channel in 2000. */ (SELECT channel_desc, prod_name, sum(amount_sold) amt FROM sales, times, channels, products WHERE sales.time_id = times.time_id AND times.calendar_year = 2000 AND channels.channel_id = sales.channel_id AND products.prod_id = sales.prod_id GROUP BY channel_desc, prod_name ) sales_2000 WHERE sales_2000.channel_desc = top_5_prods_1999_year.channel_desc AND sales_2000.prod_name = top_5_prods_1999_year.prod_name ORDER BY sales_2000.channel_desc, sales_2000.prod_name ; CHANNEL_DESC PROD_NAME AMT_2000 AMT_1999 AMT_DIFF --------------- --------------==-------------------------------- ---------- ---------- ---------- Direct Sales 17" LCD w/built-in HDTV Tuner 628855.7 1163645.78 -534790.08 Direct Sales Envoy 256MB - 40GB 502938.54 843377.88 -340439.34 Direct Sales Envoy Ambassador 2259566.96 1770349.25 489217.71 Direct Sales Home Theatre Package with DVD-Audio/Video Play 1235674.15 1260791.44 -25117.29
  • 350. ROWIDTOCHAR 5-176 Oracle Database SQL Language Reference Direct Sales Mini DV Camcorder with 3.5" Swivel LCD 775851.87 1326302.51 -550450.64 Internet 17" LCD w/built-in HDTV Tuner 31707.48 160974.7 -129267.22 Internet 8.3 Minitower Speaker 404090.32 155235.25 248855.07 Internet Envoy 256MB - 40GB 28293.87 154072.02 -125778.15 Internet Home Theatre Package with DVD-Audio/Video Play 155405.54 153175.04 2230.5 Internet Mini DV Camcorder with 3.5" Swivel LCD 39726.23 189921.97 -150195.74 Partners 17" LCD w/built-in HDTV Tuner 269973.97 325504.75 -55530.78 Partners Envoy Ambassador 1213063.59 614857.93 598205.66 Partners Home Theatre Package with DVD-Audio/Video Play 700266.58 520166.26 180100.32 Partners Mini DV Camcorder with 3.5" Swivel LCD 404265.85 520544.11 -116278.26 Partners Unix/Windows 1-user pack 374002.51 340123.02 33879.49 15 rows selected. ROWIDTOCHAR Syntax Purpose ROWIDTOCHAR converts a rowid value to VARCHAR2 data type. The result of this conversion is always 18 characters long. Examples The following example converts a rowid value in the employees table to a character value. (Results vary for each build of the sample database.) SELECT ROWID FROM employees WHERE ROWIDTOCHAR(ROWID) LIKE '%JAAB%' ORDER BY ROWID; ROWID ------------------ AAAFfIAAFAAAABSAAb ROWIDTONCHAR Syntax Purpose ROWIDTONCHAR converts a rowid value to NVARCHAR2 data type. The result of this conversion is always in the national character set and is 18 characters long. Examples The following example converts a rowid value to an NVARCHAR2 string: SELECT LENGTHB( ROWIDTONCHAR(ROWID) ) Length, ROWIDTONCHAR(ROWID) FROM employees ORDER BY length; LENGTH ROWIDTONCHAR(ROWID ---------- ------------------ ROWIDTOCHAR ( rowid ) ROWIDTONCHAR ( rowid )
  • 351. RPAD Functions 5-177 36 AAAL52AAFAAAABSABD 36 AAAL52AAFAAAABSABV . . . RPAD Syntax Purpose RPAD returns expr1, right-padded to length n characters with expr2, replicated as many times as necessary. This function is useful for formatting the output of a query. Both expr1 and expr2 can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if expr1 is a character data type, NVARCHAR2 if expr1 is a national character data type, and a LOB if expr1 is a LOB data type. The string returned is in the same character set as expr1. The argument n must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. expr1 cannot be null. If you do not specify expr2, then it defaults to a single blank. If expr1 is longer than n, then this function returns the portion of expr1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multibyte character sets, the display length of a character string can differ from the number of characters in the string. Examples The following example creates a simple chart of salary amounts by padding a single space with asterisks: SELECT last_name, RPAD(' ', salary/1000/1, '*') "Salary" FROM employees WHERE department_id = 80 ORDER BY last_name, "Salary"; LAST_NAME Salary ------------------------- --------------- Abel ********** Ande ***** Banda ***** Bates ****** Bernstein ******** Bloom ********* Cambrault ********** Cambrault ****** Doran ****** Errazuriz *********** Fox ******** Greene ******** Hall ******** Hutton ******* Johnson ***** King ********* . . . RPAD ( expr1 , n , expr2 )
  • 352. RTRIM 5-178 Oracle Database SQL Language Reference RTRIM Syntax Purpose RTRIM removes from the right end of char all of the characters that appear in set. This function is useful for formatting the output of a query. If you do not specify set, then it defaults to a single blank. If char is a character literal, then you must enclose it in single quotation marks. RTRIM works similarly to LTRIM. Both char and set can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 data type if char is a character data type, NVARCHAR2 if expr1 is a national character data type, and a LOB if char is a LOB data type. Examples The following example trims all the right-most occurrences of period, slash, and equal sign from a string: SELECT RTRIM('BROWNING: ./=./=./=./=./=.=','/=.') "RTRIM example" FROM DUAL; RTRIM exam ---------- BROWNING: SCN_TO_TIMESTAMP Syntax Purpose SCN_TO_TIMESTAMP takes as an argument a number that evaluates to a system change number (SCN), and returns the approximate timestamp associated with that SCN. The returned value is of TIMESTAMP data type. This function is useful any time you want to know the timestamp associated with an SCN. For example, it can be used in conjunction with the ORA_ROWSCN pseudocolumn to associate a timestamp with the most recent change to a row. See Also: LTRIM on page 5-106 RTRIM ( char , set ) SCN_TO_TIMESTAMP ( number )
  • 353. SCN_TO_TIMESTAMP Functions 5-179 Examples The following example uses the ORA_ROWSCN pseudocolumn to determine the system change number of the last update to a row and uses SCN_TO_TIMESTAMP to convert that SCN to a timestamp: SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) FROM employees WHERE employee_id = 188; You could use such a query to convert a system change number to a timestamp for use in an Oracle Flashback Query: SELECT salary FROM employees WHERE employee_id = 188; SALARY ---------- 3800 UPDATE employees SET salary = salary*10 WHERE employee_id = 188; COMMIT; SELECT salary FROM employees WHERE employee_id = 188; SALARY ---------- 38000 SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) FROM employees WHERE employee_id = 188; SCN_TO_TIMESTAMP(ORA_ROWSCN) --------------------------------------------------------------------------- 28-AUG-03 01.58.01.000000000 PM FLASHBACK TABLE employees TO TIMESTAMP TO_TIMESTAMP('28-AUG-03 01.00.00.000000000 PM'); SELECT salary FROM employees WHERE employee_id = 188; SALARY ---------- 3800 Notes: ■ The usual precision of the result value is 3 seconds. ■ The association between an SCN and a timestamp when the SCN is generated is remembered by the database for a limited period of time. This period is the maximum of the auto-tuned undo retention period, if the database runs in the Automatic Undo Management mode, and the retention times of all flashback archives in the database, but no less than 120 hours. The time for the association to become obsolete elapses only when the database is open. An error is returned if the SCN specified for the argument to SCN_TO_TIMESTAMP is too old. See Also: ORA_ROWSCN Pseudocolumn on page 2-8 and TIMESTAMP_TO_SCN on page 5-214
  • 354. SESSIONTIMEZONE 5-180 Oracle Database SQL Language Reference SESSIONTIMEZONE Syntax Purpose SESSIONTIMEZONE returns the time zone of the current session. The return type is a time zone offset (a character type in the format '[+|]TZH:TZM') or a time zone region name, depending on how the user specified the session time zone value in the most recent ALTER SESSION statement. Examples The following example returns the time zone of the current session: SELECT SESSIONTIMEZONE FROM DUAL; SESSION ------- -08:00 SET Syntax Purpose SET converts a nested table into a set by eliminating duplicates. The function returns a nested table whose elements are distinct from one another. The returned nested table is of the same type as the input nested table. The element types of the nested table must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example selects from the customers_demo table the unique elements of the cust_address_ntab nested table column: SELECT customer_id, SET(cust_address_ntab) address FROM customers_demo ORDER BY customer_id; CUSTOMER_ID ADDRESS(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ----------- ------------------------------------------------------------------------ Note: The default client session time zone is an offset even if the client operating system uses a named time zone. If you want the default session time zone to use a named time zone, then set the ORA_ SDTZ variable in the client environment to an Oracle time zone region name. Refer to Oracle Database Globalization Support Guide for more information on this variable. SESSIONTIMEZONE SET ( nested_table )
  • 355. SIN Functions 5-181 101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')) 102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US')) 103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')) 104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US')) 105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US')) . . . The preceding example requires the table customers_demo and a nested table column containing data. Refer to "Multiset Operators" on page 4-1 to create this table and nested table column. SIGN Syntax Purpose SIGN returns the sign of n. This function takes as an argument any numeric data type, or any nonnumeric data type that can be implicitly converted to NUMBER, and returns NUMBER. For value of NUMBER type, the sign is: ■ -1 if n<0 ■ 0 if n=0 ■ 1 if n>0 For binary floating-point numbers (BINARY_FLOAT and BINARY_DOUBLE), this function returns the sign bit of the number. The sign bit is: ■ -1 if n<0 ■ +1 if n>=0 or n=NaN Examples The following example indicates that the argument of the function (-15) is <0: SELECT SIGN(-15) "Sign" FROM DUAL; Sign ---------- -1 SIN Syntax Purpose SIN returns the sine of n (an angle expressed in radians). This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is SIGN ( n ) SIN ( n )
  • 356. SINH 5-182 Oracle Database SQL Language Reference BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the sine of 30 degrees: SELECT SIN(30 * 3.14159265359/180) "Sine of 30 degrees" FROM DUAL; Sine of 30 degrees ------------------ .5 SINH Syntax Purpose SINH returns the hyperbolic sine of n. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the hyperbolic sine of 1: SELECT SINH(1) "Hyperbolic sine of 1" FROM DUAL; Hyperbolic sine of 1 -------------------- 1.17520119 SOUNDEX Syntax Purpose SOUNDEX returns a character string containing the phonetic representation of char. This function lets you compare words that are spelled differently, but sound alike in English. The phonetic representation is defined in The Art of Computer Programming, Volume 3: Sorting and Searching, by Donald E. Knuth, as follows: See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion SINH ( n ) SOUNDEX ( char )
  • 357. SQRT Functions 5-183 1. Retain the first letter of the string and remove all other occurrences of the following letters: a, e, h, i, o, u, w, y. 2. Assign numbers to the remaining letters (after the first) as follows: b, f, p, v = 1 c, g, j, k, q, s, x, z = 2 d, t = 3 l = 4 m, n = 5 r = 6 3. If two or more letters with the same number were adjacent in the original name (before step 1), or adjacent except for any intervening h and w, then retain the first letter and omit rest of all the adjacent letters with same number. 4. Return the first four bytes padded with 0. char can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is the same data type as char. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example returns the employees whose last names are a phonetic representation of "Smyth": SELECT last_name, first_name FROM hr.employees WHERE SOUNDEX(last_name) = SOUNDEX('SMYTHE') ORDER BY last_name, first_name; LAST_NAME FIRST_NAME ---------- ---------- Smith Lindsey Smith William SQRT Syntax Purpose SQRT returns the square root of n. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. See Also: "Data Type Comparison Rules" on page 3-37 for more information. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion SQRT ( n )
  • 358. STATS_BINOMIAL_TEST 5-184 Oracle Database SQL Language Reference ■ If n resolves to a NUMBER, then the value n cannot be negative. SQRT returns a real number. ■ If n resolves to a binary floating-point number (BINARY_FLOAT or BINARY_ DOUBLE): – If n >= 0, then the result is positive. – If n = -0, then the result is -0. – If n < 0, then the result is NaN. Examples The following example returns the square root of 26: SELECT SQRT(26) "Square root" FROM DUAL; Square root ----------- 5.09901951 STATS_BINOMIAL_TEST Syntax Purpose STATS_BINOMIAL_TEST is an exact probability test used for dichotomous variables, where only two possible values exist. It tests the difference between a sample proportion and a given proportion. The sample size in such tests is usually small. This function takes four arguments: expr1 is the sample being examined. expr2 contains the values for which the proportion is expected to be, and p is a proportion to test against. The fourth argument is a return value of type VARCHAR2. If you omit the fourth argument, then the default is TWO_SIDED_PROB. The meaning of the return values is shown in Table 5–3. Table 5–3 STATS_BINOMIAL Return Values Return Value Meaning TWO_SIDED_PROB The probability that the given population proportion, p, could result in the observed proportion or a more extreme one. EXACT_PROB The probability that the given population proportion, p, could result in exactly the observed proportion. ONE_SIDED_PROB_OR_MORE The probability that the given population proportion, p, could result in the observed proportion or a larger one. ONE_SIDED_PROB_OR_LESS The probability that the given population proportion, p, could result in the observed proportion or a smaller one. STATS_BINOMIAL_TEST ( expr1 , expr2 , p , TWO_SIDED_PROB EXACT_PROB ONE_SIDED_PROB_OR_MORE ONE_SIDED_PROB_OR_LESS )
  • 359. STATS_CROSSTAB Functions 5-185 EXACT_PROB gives the probability of getting exactly proportion p. In cases where you want to test whether the proportion found in the sample is significantly different from a 50-50 split, p would normally be 0.50. If you want to test only whether the proportion is different, then use the return value TWO_SIDED_PROB. If your test is whether the proportion is more than the value of expr2, then use the return value ONE_SIDED_PROB_OR_MORE. If the test is to determine whether the proportion of expr2 is less, then use the return value ONE_SIDED_PROB_OR_LESS. STATS_BINOMIAL_TEST Example The following example determines the probability that reality exactly matches the number of men observed under the assumption that 69% of the population is composed of men: SELECT AVG(DECODE(cust_gender, 'M', 1, 0)) real_proportion, STATS_BINOMIAL_TEST (cust_gender, 'M', 0.68, 'EXACT_PROB') exact, STATS_BINOMIAL_TEST (cust_gender, 'M', 0.68, 'ONE_SIDED_PROB_OR_LESS') prob_or_less FROM sh.customers; STATS_CROSSTAB Syntax Purpose Crosstabulation (commonly called crosstab) is a method used to analyze two nominal variables. The STATS_CROSSTAB function takes three arguments: two expressions and a return value of type VARCHAR2. expr1 and expr2 are the two variables being analyzed. The function returns one number, determined by the value of the third argument. If you omit the third argument, then the default is CHISQ_SIG. The meaning of the return values is shown in Table 5–4. Table 5–4 STATS_CROSSTAB Return Values Return Value Meaning CHISQ_OBS Observed value of chi-squared CHISQ_SIG Significance of observed chi-squared CHISQ_DF Degree of freedom for chi-squared PHI_COEFFICIENT Phi coefficient CRAMERS_V Cramer's V statistic CONT_COEFFICIENT Contingency coefficient STATS_CROSSTAB ( expr1 , expr2 , CHISQ_OBS CHISQ_SIG CHISQ_DF PHI_COEFFICIENT CRAMERS_V CONT_COEFFICIENT COHENS_K )
  • 360. STATS_F_TEST 5-186 Oracle Database SQL Language Reference STATS_CROSSTAB Example The following example determines the strength of the association between gender and income level: SELECT STATS_CROSSTAB (cust_gender, cust_income_level, 'CHISQ_OBS') chi_squared, STATS_CROSSTAB (cust_gender, cust_income_level, 'CHISQ_SIG') p_value, STATS_CROSSTAB (cust_gender, cust_income_level, 'PHI_COEFFICIENT') phi_coefficient FROM sh.customers; CHI_SQUARED P_VALUE PHI_COEFFICIENT ----------- ---------- --------------- 251.690705 1.2364E-47 .067367056 STATS_F_TEST Syntax Purpose STATS_F_TEST tests whether two variances are significantly different. The observed value of f is the ratio of one variance to the other, so values very different from 1 usually indicate significant differences. This function takes three arguments: expr1 is the grouping or independent variable and expr2 is the sample of values. The function returns one number, determined by the value of the third argument. If you omit the third argument, then the default is TWO_SIDED_SIG. The meaning of the return values is shown in Table 5–5. COHENS_K Cohen's kappa Table 5–5 STATS_F_TEST Return Values Return Value Meaning STATISTIC The observed value of f DF_NUM Degree of freedom for the numerator DF_DEN Degree of freedom for the denominator ONE_SIDED_SIG One-tailed significance of f TWO_SIDED_SIG Two-tailed significance of f Table 5–4 (Cont.) STATS_CROSSTAB Return Values Return Value Meaning STATS_F_TEST ( expr1 , expr2 , STATISTIC DF_NUM DF_DEN ONE_SIDED_SIG , expr3 TWO_SIDED_SIG )
  • 361. STATS_KS_TEST Functions 5-187 The one-tailed significance is always in relation to the upper tail. The final argument, expr3, indicates which of the two groups specified by expr1 is the high value or numerator (the value whose rejection region is the upper tail). The observed value of f is the ratio of the variance of one group to the variance of the second group. The significance of the observed value of f is the probability that the variances are different just by chance—a number between 0 and 1. A small value for the significance indicates that the variances are significantly different. The degree of freedom for each of the variances is the number of observations in the sample minus 1. STATS_F_TEST Example The following example determines whether the variance in credit limit between men and women is significantly different. The results, a p_value not close to zero, and an f_statistic close to 1, indicate that the difference between credit limits for men and women are not significant. SELECT VARIANCE(DECODE(cust_gender, 'M', cust_credit_limit, null)) var_men, VARIANCE(DECODE(cust_gender, 'F', cust_credit_limit, null)) var_women, STATS_F_TEST(cust_gender, cust_credit_limit, 'STATISTIC', 'F') f_statistic, STATS_F_TEST(cust_gender, cust_credit_limit) two_sided_p_value FROM sh.customers; VAR_MEN VAR_WOMEN F_STATISTIC TWO_SIDED_P_VALUE ---------- ---------- ----------- ----------------- 12879896.7 13046865 1.01296348 .311928071 STATS_KS_TEST Syntax Purpose STATS_KS_TEST is a Kolmogorov-Smirnov function that compares two samples to test whether they are from the same population or from populations that have the same distribution. It does not assume that the population from which the samples were taken is normally distributed. This function takes three arguments: two expressions and a return value of type VARCHAR2. expr1 classifies the data into the two samples. expr2 contains the values for each of the samples. If expr1 classifies the rows into only one sample or into more than two samples, then an error is raised.The function returns one value determined by the third argument. If you omit the third argument, then the default is SIG. The meaning of the return values is shown in Table 5–6. STATS_KS_TEST Example Using the Kolmogorov Smirnov test, the following example determines whether the distribution of sales between men and women is due to chance: Table 5–6 STATS_KS_TEST Return Values Return Value Meaning STATISTIC Observed value of D SIG Significance of D STATS_KS_TEST ( expr1 , expr2 , STATISTIC SIG )
  • 362. STATS_MODE 5-188 Oracle Database SQL Language Reference SELECT stats_ks_test(cust_gender, amount_sold, 'STATISTIC') ks_statistic, stats_ks_test(cust_gender, amount_sold) p_value FROM sh.customers c, sh.sales s WHERE c.cust_id = s.cust_id; KS_STATISTIC P_VALUE ------------ ---------- .003841396 .004080006 STATS_MODE Syntax Purpose STATS_MODE takes as its argument a set of values and returns the value that occurs with the greatest frequency. If more than one mode exists, then Oracle Database chooses one and returns only that one value. To obtain multiple modes (if multiple modes exist), you must use a combination of other functions, as shown in the hypothetical query: SELECT x FROM (SELECT x, COUNT(x) AS cnt1 FROM t GROUP BY x) WHERE cnt1 = (SELECT MAX(cnt2) FROM (SELECT COUNT(x) AS cnt2 FROM t GROUP BY x)); Examples The following example returns the mode of salary per department in the hr.employees table: SELECT department_id, STATS_MODE(salary) FROM employees GROUP BY department_id ORDER BY department_id, stats_mode(salary); DEPARTMENT_ID STATS_MODE(SALARY) ------------- ------------------ 10 4400 20 6000 30 2500 40 6500 50 2500 60 4800 70 10000 80 9500 90 17000 100 6900 110 8300 7000 If you need to retrieve all of the modes (in cases with multiple modes), you can do so using a combination of other functions, as shown in the next example: SELECT commission_pct FROM (SELECT commission_pct, COUNT(commission_pct) AS cnt1 FROM employees GROUP BY commission_pct) WHERE cnt1 = STATS_MODE ( expr )
  • 363. STATS_MW_TEST Functions 5-189 (SELECT MAX (cnt2) FROM (SELECT COUNT(commission_pct) AS cnt2 FROM employees GROUP BY commission_pct)) ORDER BY commission_pct; COMMISSION_PCT -------------- .2 .3 STATS_MW_TEST Syntax Purpose A Mann Whitney test compares two independent samples to test the null hypothesis that two populations have the same distribution function against the alternative hypothesis that the two distribution functions are different. The STATS_MW_TEST does not assume that the differences between the samples are normally distributed, as do the STATS_T_TEST_* functions. This function takes three arguments and a return value of type VARCHAR2. expr1 classifies the data into groups. expr2 contains the values for each of the groups. The function returns one value, determined by the third argument. If you omit the third argument, then the default is TWO_SIDED_SIG. The meaning of the return values is shown in the table that follows. The significance of the observed value of Z or U is the probability that the variances are different just by chance—a number between 0 and 1. A small value for the significance indicates that the variances are significantly different. The degree of freedom for each of the variances is the number of observations in the sample minus 1. The one-tailed significance is always in relation to the upper tail. The final argument, expr3, indicates which of the two groups specified by expr1 is the high value (the value whose rejection region is the upper tail). STATS_MW_TEST computes the probability that the samples are from the same distribution by checking the differences in the sums of the ranks of the values. If the samples come from the same distribution, then the sums should be close in value. Table 5–7 STATS_MW_TEST Return Values Return Value Meaning STATISTIC The observed value of Z U_STATISTIC The observed value of U ONE_SIDED_SIG One-tailed significance of Z TWO_SIDED_SIG Two-tailed significance of Z STATS_MW_TEST ( expr1 , expr2 , STATISTIC U_STATISTIC ONE_SIDED_SIG , expr3 TWO_SIDED_SIG )
  • 364. STATS_ONE_WAY_ANOVA 5-190 Oracle Database SQL Language Reference STATS_MW_TEST Example Using the Mann Whitney test, the following example determines whether the distribution of sales between men and women is due to chance: SELECT STATS_MW_TEST (cust_gender, amount_sold, 'STATISTIC') z_statistic, STATS_MW_TEST (cust_gender, amount_sold, 'ONE_SIDED_SIG', 'F') one_sided_p_value FROM sh.customers c, sh.sales s WHERE c.cust_id = s.cust_id; Z_STATISTIC ONE_SIDED_P_VALUE ----------- ----------------- -1.4011509 .080584471 STATS_ONE_WAY_ANOVA Syntax Purpose The one-way analysis of variance function (STATS_ONE_WAY_ANOVA) tests differences in means (for groups or variables) for statistical significance by comparing two different estimates of variance. One estimate is based on the variances within each group or category. This is known as the mean squares within or mean square error. The other estimate is based on the variances among the means of the groups. This is known as the mean squares between. If the means of the groups are significantly different, then the mean squares between will be larger than expected and will not match the mean squares within. If the mean squares of the groups are consistent, then the two variance estimates will be about the same. STATS_ONE_WAY_ANOVA takes three arguments: two expressions and a return value of type VARCHAR2. expr1 is an independent or grouping variable that divides the data into a set of groups. expr2 is a dependent variable (a numeric expression) containing the values corresponding to each member of a group. The function returns one number, determined by the value of the third argument. If you omit the third argument, then the default is SIG. The meaning of the return values is shown in Table 5–8. Table 5–8 STATS_ONE_WAY_ANOVA Return Values Return Value Meaning SUM_SQUARES_BETEEN Sum of squares between groups STATS_ONE_WAY_ANOVA ( expr1 , expr2 , SUM_SQUARES_BETWEEN SUM_SQUARES_WITHIN DF_BETWEEN DF_WITHIN MEAN_SQUARES_BETWEEN MEAN_SQUARES_WITHIN F_RATIO SIG )
  • 365. STATS_T_TEST_* Functions 5-191 The significance of one-way analysis of variance is determined by obtaining the one-tailed significance of an f-test on the ratio of the mean squares between and the mean squares within. The f-test should use one-tailed significance, because the mean squares between can be only equal to or larger than the mean squares within. Therefore, the significance returned by STATS_ONE_WAY_ANOVA is the probability that the differences between the groups happened by chance—a number between 0 and 1. The smaller the number, the greater the significance of the difference between the groups. Refer to the STATS_F_TEST on page 5-186 for information on performing an f-test. STATS_ONE_WAY_ANOVA Example The following example determines the significance of the differences in mean sales within an income level and differences in mean sales between income levels. The results, p_values close to zero, indicate that, for both men and women, the difference in the amount of goods sold across different income levels is significant. SELECT cust_gender, STATS_ONE_WAY_ANOVA(cust_income_level, amount_sold, 'F_RATIO') f_ratio, STATS_ONE_WAY_ANOVA(cust_income_level, amount_sold, 'SIG') p_value FROM sh.customers c, sh.sales s WHERE c.cust_id = s.cust_id GROUP BY cust_gender ORDER BY cust_gender; C F_RATIO P_VALUE - ---------- ---------- F 5.59536943 4.7840E-09 M 9.2865001 6.7139E-17 STATS_T_TEST_* The t-test functions are: ■ STATS_T_TEST_ONE: A one-sample t-test ■ STATS_T_TEST_PAIRED: A two-sample, paired t-test (also known as a crossed t-test) ■ STATS_T_TEST_INDEP: A t-test of two independent groups with the same variance (pooled variances) ■ STATS_T_TEST_INDEPU: A t-test of two independent groups with unequal variance (unpooled variances) SUM_SQUARES_WITHIN Sum of squares within groups DF_BETWEEN Degree of freedom between groups DF_WITHIN Degree of freedom within groups MEAN_SQUARES_BETWEEN Mean squares between groups MEAN_SQUARES_WITHIN Mean squares within groups F_RATIO Ratio of the mean squares between to the mean squares within (MSB/MSW) SIG Significance Table 5–8 (Cont.) STATS_ONE_WAY_ANOVA Return Values Return Value Meaning
  • 366. STATS_T_TEST_ONE 5-192 Oracle Database SQL Language Reference Syntax stats_t_test::= Purpose The t-test measures the significance of a difference of means. You can use it to compare the means of two groups or the means of one group with a constant. The one-sample and two-sample STATS_T_TEST_* functions take three arguments: two expressions and a return value of type VARCHAR2. The functions return one number, determined by the value of the third argument. If you omit the third argument, then the default is TWO_SIDED_SIG. The meaning of the return values is shown in Table 5–9. The two independent STATS_T_TEST_* functions can take a fourth argument (expr3) if the third argument is specified as STATISTIC or ONE_SIDED_SIG. In this case, expr3 indicates which value of expr1 is the high value, or the value whose rejection region is the upper tail. The significance of the observed value of t is the probability that the value of t would have been obtained by chance—a number between 0 and 1. The smaller the value, the more significant the difference between the means. One-sided significance is always respect to the upper tail. For one-sample and paired t-test, the high value is the first expression. For independent t-test, the high value is the one specified by expr3. The degree of freedom depends on the type of t-test that resulted in the observed value of t. For example, for a one-sample t-test (STATS_T_TEST_ONE), the degree of freedom is the number of observations in the sample minus 1. STATS_T_TEST_ONE In the STATS_T_TEST_ONE function, expr1 is the sample and expr2 is the constant mean against which the sample mean is compared. For this t-test only, expr2 is optional; the constant mean defaults to 0. This function obtains the value of t by dividing the difference between the sample mean and the known mean by the standard error of the mean (rather than the standard error of the difference of the means, as for STATS_T_TEST_PAIRED). Table 5–9 STATS_T_TEST_* Return Values Return Value Meaning STATISTIC The observed value of t DF Degree of freedom ONE_SIDED_SIG One-tailed significance of t TWO_SIDED_SIG Two-tailed significance of t STATS_T_TEST_INDEP STATS_T_TEST_INDEPU STATS_T_TEST_ONE STATS_T_TEST_PAIRED ( expr1 , expr2 , STATISTIC ONE_SIDED_SIG , expr3 TWO_SIDED_SIG DF )
  • 367. STATS_T_TEST_* Functions 5-193 STATS_T_TEST_ONE Example The following example determines the significance of the difference between the average list price and the constant value 60: SELECT AVG(prod_list_price) group_mean, STATS_T_TEST_ONE(prod_list_price, 60, 'STATISTIC') t_observed, STATS_T_TEST_ONE(prod_list_price, 60) two_sided_p_value FROM sh.products; GROUP_MEAN T_OBSERVED TWO_SIDED_P_VALUE ---------- ---------- ----------------- 139.545556 2.32107746 .023158537 STATS_T_TEST_PAIRED In the STATS_T_TEST_PAIRED function, expr1 and expr2 are the two samples whose means are being compared. This function obtains the value of t by dividing the difference between the sample means by the standard error of the difference of the means (rather than the standard error of the mean, as for STATS_T_TEST_ONE). STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU In the STATS_T_TEST_INDEP and STATS_T_TEST_INDEPU functions, expr1 is the grouping column and expr2 is the sample of values. The pooled variances version (STATS_T_TEST_INDEP) tests whether the means are the same or different for two distributions that have similar variances. The unpooled variances version (STATS_T_ TEST_INDEPU) tests whether the means are the same or different even if the two distributions are known to have significantly different variances. Before using these functions, it is advisable to determine whether the variances of the samples are significantly different. If they are, then the data may come from distributions with different shapes, and the difference of the means may not be very useful. You can perform an f-test to determine the difference of the variances. If they are not significantly different, use STATS_T_TEST_INDEP. If they are significantly different, use STATS_T_TEST_INDEPU. Refer to STATS_F_TEST on page 5-186 for information on performing an f-test. STATS_T_TEST_INDEP Example The following example determines the significance of the difference between the average sales to men and women where the distributions are assumed to have similar (pooled) variances: SELECT SUBSTR(cust_income_level, 1, 22) income_level, AVG(DECODE(cust_gender, 'M', amount_sold, null)) sold_to_men, AVG(DECODE(cust_gender, 'F', amount_sold, null)) sold_to_women, STATS_T_TEST_INDEP(cust_gender, amount_sold, 'STATISTIC', 'F') t_observed, STATS_T_TEST_INDEP(cust_gender, amount_sold) two_sided_p_value FROM sh.customers c, sh.sales s WHERE c.cust_id = s.cust_id GROUP BY ROLLUP(cust_income_level) ORDER BY income_level, sold_to_men, sold_to_women, t_observed; INCOME_LEVEL SOLD_TO_MEN SOLD_TO_WOMEN T_OBSERVED TWO_SIDED_P_VALUE ---------------------- ----------- ------------- ---------- ----------------- A: Below 30,000 105.28349 99.4281447 -1.9880629 .046811482 B: 30,000 - 49,999 102.59651 109.829642 3.04330875 .002341053 C: 50,000 - 69,999 105.627588 110.127931 2.36148671 .018204221 D: 70,000 - 89,999 106.630299 110.47287 2.28496443 .022316997 E: 90,000 - 109,999 103.396741 101.610416 -1.2544577 .209677823 F: 110,000 - 129,999 106.76476 105.981312 -.60444998 .545545304
  • 368. STATS_WSR_TEST 5-194 Oracle Database SQL Language Reference G: 130,000 - 149,999 108.877532 107.31377 -.85298245 .393671218 H: 150,000 - 169,999 110.987258 107.152191 -1.9062363 .056622983 I: 170,000 - 189,999 102.808238 107.43556 2.18477851 .028908566 J: 190,000 - 249,999 108.040564 115.343356 2.58313425 .009794516 K: 250,000 - 299,999 112.377993 108.196097 -1.4107871 .158316973 L: 300,000 and above 120.970235 112.216342 -2.0642868 .039003862 107.121845 113.80441 .686144393 .492670059 106.663769 107.276386 1.08013499 .280082357 14 rows selected. STATS_T_TEST_INDEPU Example The following example determines the significance of the difference between the average sales to men and women where the distributions are known to have significantly different (unpooled) variances: SELECT SUBSTR(cust_income_level, 1, 22) income_level, AVG(DECODE(cust_gender, 'M', amount_sold, null)) sold_to_men, AVG(DECODE(cust_gender, 'F', amount_sold, null)) sold_to_women, STATS_T_TEST_INDEPU(cust_gender, amount_sold, 'STATISTIC', 'F') t_observed, STATS_T_TEST_INDEPU(cust_gender, amount_sold) two_sided_p_value FROM sh.customers c, sh.sales s WHERE c.cust_id = s.cust_id GROUP BY ROLLUP(cust_income_level) ORDER BY income_level, sold_to_men, sold_to_women, t_observed; INCOME_LEVEL SOLD_TO_MEN SOLD_TO_WOMEN T_OBSERVED TWO_SIDED_P_VALUE ---------------------- ----------- ------------- ---------- ----------------- A: Below 30,000 105.28349 99.4281447 -2.0542592 .039964704 B: 30,000 - 49,999 102.59651 109.829642 2.96922332 .002987742 C: 50,000 - 69,999 105.627588 110.127931 2.3496854 .018792277 D: 70,000 - 89,999 106.630299 110.47287 2.26839281 .023307831 E: 90,000 - 109,999 103.396741 101.610416 -1.2603509 .207545662 F: 110,000 - 129,999 106.76476 105.981312 -.60580011 .544648553 G: 130,000 - 149,999 108.877532 107.31377 -.85219781 .394107755 H: 150,000 - 169,999 110.987258 107.152191 -1.9451486 .051762624 I: 170,000 - 189,999 102.808238 107.43556 2.14966921 .031587875 J: 190,000 - 249,999 108.040564 115.343356 2.54749867 .010854966 K: 250,000 - 299,999 112.377993 108.196097 -1.4115514 .158091676 L: 300,000 and above 120.970235 112.216342 -2.0726194 .038225611 107.121845 113.80441 .689462437 .490595765 106.663769 107.276386 1.07853782 .280794207 14 rows selected. STATS_WSR_TEST Syntax Purpose STATS_WSR_TEST is a Wilcoxon Signed Ranks test of paired samples to determine whether the median of the differences between the samples is significantly different from zero. The absolute values of the differences are ordered and assigned ranks. Then STATS_WSR_TEST ( expr1 , expr2 , STATISTIC ONE_SIDED_SIG TWO_SIDED_SIG )
  • 369. STDDEV Functions 5-195 the null hypothesis states that the sum of the ranks of the positive differences is equal to the sum of the ranks of the negative differences. This function takes three arguments: expr1 and expr2 are the two samples being analyzed, and the third argument is a return value of type VARCHAR2. If you omit the third argument, then the default is TWO_SIDED_SIG. The meaning of the return values is shown in Table 5–10. One-sided significance is always with respect to the upper tail. The high value (the value whose rejection region is the upper tail) is expr1. STDDEV Syntax Purpose STDDEV returns the sample standard deviation of expr, a set of numbers. You can use it as both an aggregate and analytic function. It differs from STDDEV_SAMP in that STDDEV returns zero when it has only 1 row of input data, whereas STDDEV_SAMP returns null. Oracle Database calculates the standard deviation as the square root of the variance defined for the VARIANCE aggregate function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed. Table 5–10 STATS_WSR_TEST_* Return Values Return Value Meaning STATISTIC The observed value of Z ONE_SIDED_SIG One-tailed significance of Z TWO_SIDED_SIG Two-tailed significance of Z See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion STDDEV ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 370. STDDEV_POP 5-196 Oracle Database SQL Language Reference Aggregate Examples The following example returns the standard deviation of the salaries in the sample hr.employees table: SELECT STDDEV(salary) "Deviation" FROM employees; Deviation ---------- 3909.36575 Analytic Examples The query in the following example returns the cumulative standard deviation of the salaries in Department 80 in the sample table hr.employees, ordered by hire_ date: SELECT last_name, salary, STDDEV(salary) OVER (ORDER BY hire_date) "StdDev" FROM employees WHERE department_id = 30 ORDER BY last_name, salary, "StdDev"; LAST_NAME SALARY StdDev ------------------------- ---------- ---------- Baida 2900 4035.26125 Colmenares 2500 3362.58829 Himuro 2600 3649.2465 Khoo 3100 5586.14357 Raphaely 11000 0 Tobias 2800 4650.0896 STDDEV_POP Syntax Purpose STDDEV_POP computes the population standard deviation and returns the square root of the population variance. You can use it as both an aggregate and analytic function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. See Also: ■ "Aggregate Functions" on page 5-9, VARIANCE on page 5-246, and STDDEV_SAMP on page 5-197 ■ "About SQL Expressions" on page 6-1 for information on valid forms of expr See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions STDDEV_POP ( expr ) OVER ( analytic_clause )
  • 371. STDDEV_SAMP Functions 5-197 This function is the same as the square root of the VAR_POP function. When VAR_POP returns null, this function returns null. Aggregate Example The following example returns the population and sample standard deviations of the amount of sales in the sample table sh.sales: SELECT STDDEV_POP(amount_sold) "Pop", STDDEV_SAMP(amount_sold) "Samp" FROM sales; Pop Samp ---------- ---------- 896.355151 896.355592 Analytic Example The following example returns the population standard deviations of salaries in the sample hr.employees table by department: SELECT department_id, last_name, salary, STDDEV_POP(salary) OVER (PARTITION BY department_id) AS pop_std FROM employees ORDER BY department_id, last_name, salary, pop_std; DEPARTMENT_ID LAST_NAME SALARY POP_STD ------------- ------------------------- ---------- ---------- 10 Whalen 4400 0 20 Fay 6000 3500 20 Hartstein 13000 3500 30 Baida 2900 3069.6091 . . . 100 Urman 7800 1644.18166 110 Gietz 8300 1850 110 Higgins 12000 1850 Grant 7000 0 STDDEV_SAMP Syntax See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: ■ "Aggregate Functions" on page 5-9 and VAR_POP on page 5-244 ■ "About SQL Expressions" on page 6-1 for information on valid forms of expr See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions STDDEV_SAMP ( expr ) OVER ( analytic_clause )
  • 372. STDDEV_SAMP 5-198 Oracle Database SQL Language Reference Purpose STDDEV_SAMP computes the cumulative sample standard deviation and returns the square root of the sample variance. You can use it as both an aggregate and analytic function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. This function is same as the square root of the VAR_SAMP function. When VAR_SAMP returns null, this function returns null. Aggregate Example Refer to the aggregate example for STDDEV_POP on page 5-196. Analytic Example The following example returns the sample standard deviation of salaries in the employees table by department: SELECT department_id, last_name, hire_date, salary, STDDEV_SAMP(salary) OVER (PARTITION BY department_id ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sdev FROM employees ORDER BY department_id, last_name, hire_date, salary, cum_sdev; DEPARTMENT_ID LAST_NAME HIRE_DATE SALARY CUM_SDEV ------------- --------------- --------- ---------- ---------- 10 Whalen 17-SEP-03 4400 20 Fay 17-AUG-05 6000 4949.74747 20 Hartstein 17-FEB-04 13000 30 Baida 24-DEC-05 2900 4035.26125 30 Colmenares 10-AUG-07 2500 3362.58829 30 Himuro 15-NOV-06 2600 3649.2465 30 Khoo 18-MAY-03 3100 5586.14357 30 Raphaely 07-DEC-02 11000 . . . 100 Greenberg 17-AUG-02 12008 2126.9772 100 Popp 07-DEC-07 6900 1804.13155 100 Sciarra 30-SEP-05 7700 1929.76233 100 Urman 07-MAR-06 7800 1788.92504 110 Gietz 07-JUN-02 8300 2621.95194 110 Higgins 07-JUN-02 12008 Grant 24-MAY-07 7000 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: ■ "Aggregate Functions" on page 5-9 and VAR_SAMP on page 5-245 ■ "About SQL Expressions" on page 6-1 for information on valid forms of expr
  • 373. SUBSTR Functions 5-199 SUBSTR Syntax substr::= Purpose The SUBSTR functions return a portion of char, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC uses Unicode complete characters. SUBSTR2 uses UCS2 code points. SUBSTR4 uses UCS4 code points. ■ If position is 0, then it is treated as 1. ■ If position is positive, then Oracle Database counts from the beginning of char to find the first character. ■ If position is negative, then Oracle counts backward from the end of char. ■ If substring_length is omitted, then Oracle returns all characters to the end of char. If substring_length is less than 1, then Oracle returns null. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Both position and substring_length must be of data type NUMBER, or any data type that can be implicitly converted to NUMBER, and must resolve to an integer. The return value is the same data type as char. Floating-point numbers passed as arguments to SUBSTR are automatically converted to integers. Examples The following example returns several specified substrings of "ABCDEFG": SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL; Substring --------- CDEF SELECT SUBSTR('ABCDEFG',-5,4) "Substring" FROM DUAL; Substring --------- See Also: Oracle Database Globalization Support Guide for more information about SUBSTR functions and length semantics in different locales SUBSTR SUBSTRB SUBSTRC SUBSTR2 SUBSTR4 ( char , position , substring_length )
  • 374. SUM 5-200 Oracle Database SQL Language Reference CDEF Assume a double-byte database character set: SELECT SUBSTRB('ABCDEFG',5,4.2) "Substring with bytes" FROM DUAL; Substring with bytes -------------------- CD SUM Syntax Purpose SUM returns the sum of values of expr. You can use it as an aggregate or analytic function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed. Aggregate Example The following example calculates the sum of all salaries in the sample hr.employees table: SELECT SUM(salary) "Total" FROM employees; Total ---------- 691400 Analytic Example The following example calculates, for each manager in the sample table hr.employees, a cumulative total of salaries of employees who answer to that manager that are equal to or less than the current salary. You can see that Raphaely See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 SUM ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 375. SYS_CONNECT_BY_PATH Functions 5-201 and Cambrault have the same cumulative total. This is because Raphaely and Cambrault have the identical salaries, so Oracle Database adds together their salary values and applies the same cumulative total to both rows. SELECT manager_id, last_name, salary, SUM(salary) OVER (PARTITION BY manager_id ORDER BY salary RANGE UNBOUNDED PRECEDING) l_csum FROM employees ORDER BY manager_id, last_name, salary, l_csum; MANAGER_ID LAST_NAME SALARY L_CSUM ---------- --------------- ---------- ---------- MANAGER_ID LAST_NAME SALARY L_CSUM ---------- ------------------------- ---------- ---------- 100 Cambrault 11000 68900 100 De Haan 17000 155400 100 Errazuriz 12000 80900 100 Fripp 8200 36400 100 Hartstein 13000 93900 100 Kaufling 7900 20200 100 Kochhar 17000 155400 100 Mourgos 5800 5800 100 Partners 13500 107400 100 Raphaely 11000 68900 100 Russell 14000 121400 . . . 149 Hutton 8800 39000 149 Johnson 6200 6200 149 Livingston 8400 21600 149 Taylor 8600 30200 201 Fay 6000 6000 205 Gietz 8300 8300 King 24000 24000 SYS_CONNECT_BY_PATH Syntax Purpose SYS_CONNECT_BY_PATH is valid only in hierarchical queries. It returns the path of a column value from root to node, with column values separated by char for each row returned by CONNECT BY condition. Both column and char can be any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The string returned is of VARCHAR2 data type and is in the same character set as column. Examples The following example returns the path of employee names from employee Kochhar to all employees of Kochhar (and their employees): SELECT LPAD(' ', 2*level-1)||SYS_CONNECT_BY_PATH(last_name, '/') "Path" FROM employees See Also: "Hierarchical Queries" on page 9-3 for more information about hierarchical queries and CONNECT BY conditions SYS_CONNECT_BY_PATH ( column , char )
  • 376. SYS_CONTEXT 5-202 Oracle Database SQL Language Reference START WITH last_name = 'Kochhar' CONNECT BY PRIOR employee_id = manager_id; Path ------------------------------ /Kochhar/Greenberg/Chen /Kochhar/Greenberg/Faviet /Kochhar/Greenberg/Popp /Kochhar/Greenberg/Sciarra /Kochhar/Greenberg/Urman /Kochhar/Higgins/Gietz /Kochhar/Baer /Kochhar/Greenberg /Kochhar/Higgins /Kochhar/Mavris /Kochhar/Whalen /Kochhar SYS_CONTEXT Syntax Purpose SYS_CONTEXT returns the value of parameter associated with the context namespace at the current instant. You can use this function in both SQL and PL/SQL statements. For namespace and parameter, you can specify either a string or an expression that resolves to a string designating a namespace or an attribute. If you specify literal arguments for namespace and parameter, and you are using SYS_CONTEXT explicitly in a SQL statement—rather than in a PL/SQL function that in turn is in mentioned in a SQL statement—then Oracle Database evaluates SYS_CONTEXT only once per SQL statement execution for each call site that invokes the SYS_CONTEXT function. The context namespace must already have been created, and the associated parameter and its value must also have been set using the DBMS_SESSION.set_ context procedure. The namespace must be a valid SQL identifier. The parameter name can be any string. It is not case sensitive, but it cannot exceed 30 bytes in length. The data type of the return value is VARCHAR2. The default maximum size of the return value is 256 bytes. You can override this default by specifying the optional length parameter, which must be a NUMBER or a value that can be implicitly converted to NUMBER. The valid range of values is 1 to 4000 bytes. If you specify an invalid value, then Oracle Database ignores it and uses the default. Oracle provides a built-in namespace called USERENV, which describes the current session. The predefined parameters of namespace USERENV are listed in Table 5–11 on page 5-203. SYS_CONTEXT ( ’ namespace ’ , ’ parameter ’ , length )
  • 377. SYS_CONTEXT Functions 5-203 Examples The following statement returns the name of the user who logged onto the database: CONNECT OE/password SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') FROM DUAL; SYS_CONTEXT ('USERENV', 'SESSION_USER') ------------------------------------------------------ OE The following hypothetical example returns the group number that was set as the value for the attribute group_no in the PL/SQL package that was associated with the context hr_apps when hr_apps was created: SELECT SYS_CONTEXT ('hr_apps', 'group_no') "User Group" FROM DUAL; See Also: ■ Oracle Database Security Guide for information on using the application context feature in your application development ■ CREATE CONTEXT on page 14-9 for information on creating user-defined context namespaces ■ Oracle Database PL/SQL Packages and Types Reference for information on the DBMS_SESSION.set_context procedure Note: For simplicity in demonstrating this feature, this example does not perform the password management techniques that a deployed system normally uses. In a production environment, follow the Oracle Database password management guidelines, and disable any sample accounts. See Oracle Database Security Guide for password management guidelines and other security recommendations. Table 5–11 Predefined Parameters of Namespace USERENV Parameter Return Value ACTION Identifies the position in the module (application name) and is set through the DBMS_APPLICATION_INFO package or OCI. AUDITED_CURSORID Returns the cursor ID of the SQL that triggered the audit. This parameter is not valid in a fine-grained auditing environment. If you specify it in such an environment, then Oracle Database always returns NULL.
  • 378. SYS_CONTEXT 5-204 Oracle Database SQL Language Reference AUTHENTICATED_IDENTITY Returns the identity used in authentication. In the list that follows, the type of user is followed by the value returned: ■ Kerberos-authenticated enterprise user: kerberos principal name ■ Kerberos-authenticated external user : kerberos principal name; same as the schema name ■ SSL-authenticated enterprise user: the DN in the user's PKI certificate ■ SSL-authenticated external user: the DN in the user's PKI certificate ■ Password-authenticated enterprise user: nickname; same as the login name ■ Password-authenticated database user: the database username; same as the schema name ■ OS-authenticated external user: the external operating system user name ■ Radius/DCE-authenticated external user: the schema name ■ Proxy with DN : Oracle Internet Directory DN of the client ■ Proxy with certificate: certificate DN of the client ■ Proxy with username: database user name if client is a local database user; nickname if client is an enterprise user. ■ SYSDBA/SYSOPER using Password File: login name ■ SYSDBA/SYSOPER using OS authentication: operating system user name AUTHENTICATION_DATA Data being used to authenticate the login user. For X.503 certificate authenticated sessions, this field returns the context of the certificate in HEX2 format. Note: You can change the return value of the AUTHENTICATION_DATA attribute using the length parameter of the syntax. Values of up to 4000 are accepted. This is the only attribute of USERENV for which Oracle Database implements such a change. AUTHENTICATION_METHOD Returns the method of authentication. In the list that follows, the type of user is followed by the method returned: ■ Password-authenticated enterprise user, local database user, or SYSDBA/SYSOPER using Password File; proxy with username using password: PASSWORD ■ Kerberos-authenticated enterprise or external user: KERBEROS ■ SSL-authenticated enterprise or external user: SSL ■ Radius-authenticated external user: RADIUS ■ OS-authenticated external user or SYSDBA/SYSOPER: OS ■ DCE-authenticated external user: DCE ■ Proxy with certificate, DN, or username without using password: NONE ■ Background process (job queue slave process): JOB You can use IDENTIFICATION_TYPE to distinguish between external and enterprise users when the authentication method is Password, Kerberos, or SSL. BG_JOB_ID Job ID of the current session if it was established by an Oracle Database background process. Null if the session was not established by a background process. CLIENT_IDENTIFIER Returns an identifier that is set by the application through the DBMS_ SESSION.SET_IDENTIFIER procedure, the OCI attribute OCI_ATTR_CLIENT_ IDENTIFIER, or the Java class Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is used by various database components to identify lightweight application users who authenticate as the same database user. Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV Parameter Return Value
  • 379. SYS_CONTEXT Functions 5-205 CLIENT_INFO Returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package. CURRENT_BIND The bind variables for fine-grained auditing. CURRENT_EDITION_ID The identifier of the current edition. CURRENT_EDITION_NAME The name of the current edition. CURRENT_SCHEMA The name of the currently active default schema. This value may change during the duration of a session through use of an ALTER SESSION SET CURRENT_ SCHEMA statement. This may also change during the duration of a session to reflect the owner of any active definer's rights object. When used directly in the body of a view definition, this returns the default schema used when executing the cursor that is using the view; it does not respect views used in the cursor as being definer's rights. Note: Oracle recommends against issuing the SQL statement ALTER SESSION SET CURRENT_SCHEMA from within a stored PL/SQL unit. CURRENT_SCHEMAID Identifier of the currently active default schema. CURRENT_SQL CURRENT_SQLn CURRENT_SQL returns the first 4K bytes of the current SQL that triggered the fine-grained auditing event. The CURRENT_SQLn attributes return subsequent 4K-byte increments, where n can be an integer from 1 to 7, inclusive. CURRENT_ SQL1 returns bytes 4K to 8K; CURRENT_SQL2 returns bytes 8K to 12K, and so forth. You can specify these attributes only inside the event handler for the fine-grained auditing feature. CURRENT_SQL_LENGTH The length of the current SQL statement that triggers fine-grained audit or row-level security (RLS) policy functions or event handlers. Valid only inside the function or event handler. CURRENT_USER The name of the database user whose privileges are currently active. This may change during the duration of a session to reflect the owner of any active definer's rights object. When no definer's rights object is active, CURRENT_USER returns the same value as SESSION_USER. When used directly in the body of a view definition, this returns the user that is executing the cursor that is using the view; it does not respect views used in the cursor as being definer's rights. CURRENT_USERID The identifier of the database user whose privileges are currently active. DATABASE_ROLE The database role using the SYS_CONTEXT function with the USERENV namespace. The role is one of the following: PRIMARY, PHYSICAL STANDBY, LOGICAL STANDBY, SNAPSHOT STANDBY. DB_DOMAIN Domain of the database as specified in the DB_DOMAIN initialization parameter. DB_NAME Name of the database as specified in the DB_NAME initialization parameter. DB_UNIQUE_NAME Name of the database as specified in the DB_UNIQUE_NAME initialization parameter. ENTRYID The current audit entry number. The audit entryid sequence is shared between fine-grained audit records and regular audit records. You cannot use this attribute in distributed SQL statements. The correct auditing entry identifier can be seen only through an audit handler for standard or fine-grained audit. Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV Parameter Return Value
  • 380. SYS_CONTEXT 5-206 Oracle Database SQL Language Reference ENTERPRISE_IDENTITY Returns the user's enterprise-wide identity: ■ For enterprise users: the Oracle Internet Directory DN. ■ For external users: the external identity (Kerberos principal name, Radius and DCE schema names, OS user name, Certificate DN). ■ For local users and SYSDBA/SYSOPER logins: NULL. The value of the attribute differs by proxy method: ■ For a proxy with DN: the Oracle Internet Directory DN of the client ■ For a proxy with certificate: the certificate DN of the client for external users; the Oracle Internet Directory DN for global users ■ For a proxy with username: the Oracle Internet Directory DN if the client is an enterprise users; NULL if the client is a local database user. FG_JOB_ID Job ID of the current session if it was established by a client foreground process. Null if the session was not established by a foreground process. GLOBAL_CONTEXT_MEMORY Returns the number being used in the System Global Area by the globally accessed context. GLOBAL_UID Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) logins; returns null for all other logins. HOST Name of the host machine from which the client has connected. IDENTIFICATION_TYPE Returns the way the user's schema was created in the database. Specifically, it reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that follows, the syntax used during schema creation is followed by the identification type returned: ■ IDENTIFIED BY password: LOCAL ■ IDENTIFIED EXTERNALLY: EXTERNAL ■ IDENTIFIED GLOBALLY: GLOBAL SHARED ■ IDENTIFIED GLOBALLY AS DN: GLOBAL PRIVATE INSTANCE The instance identification number of the current instance. INSTANCE_NAME The name of the instance. IP_ADDRESS IP address of the machine from which the client is connected. If the client and server are on the same machine and the connection uses IPv6 addressing, then ::1 is returned. ISDBA Returns TRUE if the user has been authenticated as having DBA privileges either through the operating system or through a password file. LANG The abbreviated name for the language, a shorter form than the existing 'LANGUAGE' parameter. LANGUAGE The language and territory currently used by your session, along with the database character set, in this form: language_territory.characterset MODULE The application name (module) set through the DBMS_APPLICATION_INFO package or OCI. NETWORK_PROTOCOL Network protocol being used for communication, as specified in the 'PROTOCOL=protocol' portion of the connect string. NLS_CALENDAR The current calendar of the current session. NLS_CURRENCY The currency of the current session. NLS_DATE_FORMAT The date format for the session. Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV Parameter Return Value
  • 381. SYS_CONTEXT Functions 5-207 Table 5–12 lists the parameters of namespace USERENV that have been deprecated. Do not specify any of these parameters. Instead use the alternatives suggested in the Comments column. NLS_DATE_LANGUAGE The language used for expressing dates. NLS_SORT BINARY or the linguistic sort basis. NLS_TERRITORY The territory of the current session. OS_USER Operating system user name of the client process that initiated the database session. POLICY_INVOKER The invoker of row-level security (RLS) policy functions. PROXY_ENTERPRISE_ IDENTITY Returns the Oracle Internet Directory DN when the proxy user is an enterprise user. PROXY_GLOBAL_UID Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) proxy users; returns NULL for all other proxy users. PROXY_USER Name of the database user who opened the current session on behalf of SESSION_ USER. PROXY_USERID Identifier of the database user who opened the current session on behalf of SESSION_USER. SERVER_HOST The host name of the machine on which the instance is running. SERVICE_NAME The name of the service to which a given session is connected. SESSION_EDITION_ID The identifier of the session edition. SESSION_EDITION_NAME The name of the session edition. SESSION_USER The name of the database user at logon. For enterprise users, returns the schema. For other users, returns the database user name. This value remains the same throughout the duration of the session. SESSION_USERID The identifier of the database user at logon. SESSIONID The auditing session identifier. You cannot use this attribute in distributed SQL statements. SID The session ID. STATEMENTID The auditing statement identifier. STATEMENTID represents the number of SQL statements audited in a given session. You cannot use this attribute in distributed SQL statements. The correct auditing statement identifier can be seen only through an audit handler for standard or fine-grained audit. TERMINAL The operating system identifier for the client of the current session. In distributed SQL statements, this attribute returns the identifier for your local session. In a distributed environment, this is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations. (The return length of this parameter may vary by operating system.) Table 5–11 (Cont.) Predefined Parameters of Namespace USERENV Parameter Return Value
  • 382. SYS_DBURIGEN 5-208 Oracle Database SQL Language Reference SYS_DBURIGEN Syntax Purpose SYS_DBURIGen takes as its argument one or more columns or attributes, and optionally a rowid, and generates a URL of data type DBURIType to a particular column or row object. You can then use the URL to retrieve an XML document from the database. All columns or attributes referenced must reside in the same table. They must perform the function of a primary key. They need not actually match the primary key of the table, but they must reference a unique value. If you specify multiple columns, then all but the final column identify the row in the database, and the last column specified identifies the column within the row. By default the URL points to a formatted XML document. If you want the URL to point only to the text of the document, then specify the optional 'text()'. If the table or view containing the columns or attributes does not have a schema specified in the context of the query, then Oracle Database interprets the table or view name as a public synonym. Examples The following example uses the SYS_DBURIGen function to generate a URL of data type DBURIType to the email column of the row in the sample table hr.employees where the employee_id = 206: SELECT SYS_DBURIGEN(employee_id, email) FROM employees Table 5–12 Deprecated Parameters of Namespace USERENV Parameter Comments AUTHENTICATION_TYPE This parameter returned a value indicating how the user was authenticated. The same information is now available from the new AUTHENTICATION_METHOD parameter combined with IDENTIFICATION_TYPE. EXTERNAL_NAME This parameter returned the external name of the user. More complete information can now be obtained from the AUTHENTICATED_IDENTITY and ENTERPRISE_ IDENTITY parameter. Note: In this XML context, the lowercase text is a keyword, not a syntactic placeholder. See Also: Oracle XML Developer's Kit Programmer's Guide for information on the URIType data type and XML documents in the database SYS_DBURIGEN ( column attribute rowid , , ’ text ( ) ’ )
  • 383. SYS_GUID Functions 5-209 WHERE employee_id = 206; SYS_DBURIGEN(EMPLOYEE_ID,EMAIL)(URL, SPARE) -------------------------------------------------------------------- DBURITYPE('/PUBLIC/EMPLOYEES/ROW[EMPLOYEE_ID=''206'']/EMAIL', NULL) SYS_EXTRACT_UTC Syntax Purpose SYS_EXTRACT_UTC extracts the UTC (Coordinated Universal Time—formerly Greenwich Mean Time) from a datetime value with time zone offset or time zone region name. If a time zone is not specified, the time is associated with the database time zone. Examples The following example extracts the UTC from a specified datetime: SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -08:00') FROM DUAL; SYS_EXTRACT_UTC(TIMESTAMP'2000-03-2811:30:00.00-08:00') ----------------------------------------------------------------- 28-MAR-00 07.30.00 PM SYS_GUID Syntax Purpose SYS_GUID generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier, a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread. Examples The following example adds a column to the sample table hr.locations, inserts unique identifiers into each row, and returns the 32-character hexadecimal representation of the 16-byte RAW value of the global unique identifier: ALTER TABLE locations ADD (uid_col RAW(16)); UPDATE locations SET uid_col = SYS_GUID(); SELECT location_id, uid_col FROM locations ORDER BY location_id, uid_col; LOCATION_ID UID_COL ----------- ---------------------------------------------------------------- SYS_EXTRACT_UTC ( datetime_with_timezone ) SYS_GUID ( )
  • 384. SYS_TYPEID 5-210 Oracle Database SQL Language Reference 1000 09F686761827CF8AE040578CB20B7491 1100 09F686761828CF8AE040578CB20B7491 1200 09F686761829CF8AE040578CB20B7491 1300 09F68676182ACF8AE040578CB20B7491 1400 09F68676182BCF8AE040578CB20B7491 1500 09F68676182CCF8AE040578CB20B7491 . . . SYS_TYPEID Syntax Purpose SYS_TYPEID returns the typeid of the most specific type of the operand. This value is used primarily to identify the type-discriminant column underlying a substitutable column. For example, you can use the value returned by SYS_TYPEID to build an index on the type-discriminant column. You can use this function only on object type operands. All final root object types—final types not belonging to a type hierarchy—have a null typeid. Oracle Database assigns to all types belonging to a type hierarchy a unique non-null typeid. Examples The following examples use the tables persons and books, which are created in "Substitutable Table and Column Examples" on page 16-69. The first query returns the most specific types of the object instances stored in the persons table. SELECT name, SYS_TYPEID(VALUE(p)) "Type_id" FROM persons p; NAME Type_id ------------------------- -------------------------------- Bob 01 Joe 02 Tim 03 The next query returns the most specific types of authors stored in the table books: SELECT b.title, b.author.name, SYS_TYPEID(author) "Type_ID" FROM books b; TITLE AUTHOR.NAME Type_ID ------------------------- -------------------- ------------------- An Autobiography Bob 01 Business Rules Joe 02 Mixing School and Work Tim 03 You can use the SYS_TYPEID function to create an index on the type-discriminant column of a table. For an example, see "Indexing on Substitutable Columns: Examples" on page 14-86. See Also: Oracle Database Object-Relational Developer's Guide for more information on typeids SYS_TYPEID ( object_type_value )
  • 385. SYS_XMLGEN Functions 5-211 SYS_XMLAGG Syntax Purpose SYS_XMLAgg aggregates all of the XML documents or fragments represented by expr and produces a single XML document. It adds a new enclosing element with a default name ROWSET. If you want to format the XML document differently, then specify fmt, which is an instance of the XMLFormat object. Examples The following example uses the SYS_XMLGen function to generate an XML document for each row of the sample table employees where the employee's last name begins with the letter R, and then aggregates all of the rows into a single XML document in the default enclosing element ROWSET: SELECT SYS_XMLAGG(SYS_XMLGEN(last_name)) XMLAGG FROM employees WHERE last_name LIKE 'R%' ORDER BY xmlagg; XMLAGG -------------------------------------------------------------------------------- <?xml version="1.0"?> <ROWSET> <LAST_NAME>Rajs</LAST_NAME> <LAST_NAME>Raphaely</LAST_NAME> <LAST_NAME>Rogers</LAST_NAME> <LAST_NAME>Russell</LAST_NAME> </ROWSET> SYS_XMLGEN Syntax Purpose SYS_XMLGen takes an expression that evaluates to a particular row and column of the database, and returns an instance of type XMLType containing an XML document. The expr can be a scalar value, a user-defined type, or an XMLType instance. ■ If expr is a scalar value, then the function returns an XML element containing the scalar value. See Also: SYS_XMLGEN on page 5-211 and "XML Format Model" on page 3-69 for using the attributes of the XMLFormat type to format SYS_XMLAgg results SYS_XMLAGG ( expr , fmt ) SYS_XMLGEN ( expr , fmt )
  • 386. SYSDATE 5-212 Oracle Database SQL Language Reference ■ If expr is a type, then the function maps the user-defined type attributes to XML elements. ■ If expr is an XMLType instance, then the function encloses the document in an XML element whose default tag name is ROW. By default the elements of the XML document match the elements of expr. For example, if expr resolves to a column name, then the enclosing XML element will be the same column name. If you want to format the XML document differently, then specify fmt, which is an instance of the XMLFormat object. Examples The following example retrieves the employee email ID from the sample table oe.employees where the employee_id value is 205, and generates an instance of an XMLType containing an XML document with an EMAIL element. SELECT SYS_XMLGEN(email) FROM employees WHERE employee_id = 205; SYS_XMLGEN(EMAIL) ------------------------------------------------------------------- <?xml version="1.0"?> <EMAIL>SHIGGINS</EMAIL> SYSDATE Syntax Purpose SYSDATE returns the current date and time set for the operating system on which the database server resides. The data type of the returned value is DATE, and the format returned depends on the value of the NLS_DATE_FORMAT initialization parameter. The function requires no arguments. In distributed SQL statements, this function returns the date and time set for the operating system of your local database. You cannot use this function in the condition of a CHECK constraint. Examples The following example returns the current operating system date and time: SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW" FROM DUAL; NOW ------------------- 04-13-2001 09:45:51 See Also: "XML Format Model" on page 3-69 for a description of the XMLFormat type and how to use its attributes to format SYS_XMLGen results SYSDATE
  • 387. TAN Functions 5-213 SYSTIMESTAMP Syntax Purpose SYSTIMESTAMP returns the system date, including fractional seconds and time zone, of the system on which the database resides. The return type is TIMESTAMP WITH TIME ZONE. Examples The following example returns the system timestamp: SELECT SYSTIMESTAMP FROM DUAL; SYSTIMESTAMP ------------------------------------------------------------------ 28-MAR-00 12.38.55.538741 PM -08:00 The following example shows how to explicitly specify fractional seconds: SELECT TO_CHAR(SYSTIMESTAMP, 'SSSSS.FF') FROM DUAL; TO_CHAR(SYSTIME --------------- 55615.449255 The following example returns the current timestamp in a specified time zone: SELECT SYSTIMESTAMP AT TIME ZONE 'UTC' FROM dual; SYSTIMESTAMPATTIMEZONE'UTC' --------------------------------------------------------------------------- 08-07-21 20:39:52,743557 UTC The output format in this example depends on the NLS_TIMESTAMP_TZ_FORMAT for the session. TAN Syntax Purpose TAN returns the tangent of n (an angle expressed in radians). This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. SYSTIMESTAMP TAN ( n )
  • 388. TANH 5-214 Oracle Database SQL Language Reference Examples The following example returns the tangent of 135 degrees: SELECT TAN(135 * 3.14159265359/180) "Tangent of 135 degrees" FROM DUAL; Tangent of 135 degrees ---------------------- - 1 TANH Syntax Purpose TANH returns the hyperbolic tangent of n. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument. Examples The following example returns the hyperbolic tangent of .5: SELECT TANH(.5) "Hyperbolic tangent of .5" FROM DUAL; Hyperbolic tangent of .5 ------------------------ .462117157 TIMESTAMP_TO_SCN Syntax Purpose TIMESTAMP_TO_SCN takes as an argument a timestamp value and returns the approximate system change number (SCN) associated with that timestamp. The returned value is of data type NUMBER. This function is useful any time you want to know the SCN associated with a particular timestamp. See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion TANH ( n ) TIMESTAMP_TO_SCN ( timestamp )
  • 389. TO_BINARY_DOUBLE Functions 5-215 Examples The following example inserts a row into the oe.orders table and then uses TIMESTAMP_TO_SCN to determine the system change number of the insert operation. (The actual SCN returned will differ on each system.) INSERT INTO orders (order_id, order_date, customer_id, order_total) VALUES (5000, SYSTIMESTAMP, 188, 2345); 1 row created. COMMIT; Commit complete. SELECT TIMESTAMP_TO_SCN(order_date) FROM orders WHERE order_id = 5000; TIMESTAMP_TO_SCN(ORDER_DATE) ---------------------------- 574100 TO_BINARY_DOUBLE Syntax Purpose TO_BINARY_DOUBLE returns a double-precision floating-point number. ■ expr can be a character string or a numeric value of type NUMBER, BINARY_ FLOAT, or BINARY_DOUBLE. If expr is BINARY_DOUBLE, then the function returns expr. ■ The optional 'fmt' and 'nlsparam' arguments are valid only if expr is a character string. They serve the same purpose as for the TO_CHAR (number) function. – The case-insensitive string 'INF' is converted to positive infinity. – The case-insensitive string '-INF' is converted to negative identity. – The case-insensitive string 'NaN' is converted to NaN (not a number). Note: The association between an SCN and a timestamp when the SCN is generated is remembered by the database for a limited period of time. This period is the maximum of the auto-tuned undo retention period, if the database runs in the Automatic Undo Management mode, and the retention times of all flashback archives in the database, but no less than 120 hours. The time for the association to become obsolete elapses only when the database is open. An error is returned if the timestamp specified for the argument to TIMESTAMP_TO_SCN is too old. See Also: SCN_TO_TIMESTAMP on page 5-178 for information on converting SCNs to timestamp TO_BINARY_DOUBLE ( expr , fmt , ’ nlsparam ’ )
  • 390. TO_BINARY_FLOAT 5-216 Oracle Database SQL Language Reference You cannot use a floating-point number format element (F, f, D, or d) in a character string expr. Conversions from character strings or NUMBER to BINARY_DOUBLE can be inexact, because the NUMBER and character types use decimal precision to represent the numeric value, and BINARY_DOUBLE uses binary precision. Conversions from BINARY_FLOAT to BINARY_DOUBLE are exact. Examples The examples that follow are based on a table with three columns, each with a different numeric data type: CREATE TABLE float_point_demo (dec_num NUMBER(10,2), bin_double BINARY_DOUBLE, bin_float BINARY_FLOAT); INSERT INTO float_point_demo VALUES (1234.56,1234.56,1234.56); SELECT * FROM float_point_demo; DEC_NUM BIN_DOUBLE BIN_FLOAT ---------- ---------- ---------- 1234.56 1.235E+003 1.235E+003 The following example converts a value of data type NUMBER to a value of data type BINARY_DOUBLE: SELECT dec_num, TO_BINARY_DOUBLE(dec_num) FROM float_point_demo; DEC_NUM TO_BINARY_DOUBLE(DEC_NUM) ---------- ------------------------- 1234.56 1.235E+003 The following example compares extracted dump information from the dec_num and bin_double columns: SELECT DUMP(dec_num) "Decimal", DUMP(bin_double) "Double" FROM float_point_demo; Decimal Double --------------------------- --------------------------------------------- Typ=2 Len=4: 194,13,35,57 Typ=101 Len=8: 192,147,74,61,112,163,215,10 TO_BINARY_FLOAT Syntax See Also: TO_CHAR (number) on page 5-221 and "Floating-Point Numbers" on page 3-12 TO_BINARY_FLOAT ( expr , fmt , ’ nlsparam ’ )
  • 391. TO_BLOB Functions 5-217 Purpose TO_BINARY_FLOAT returns a single-precision floating-point number. ■ expr can be a character string or a numeric value of type NUMBER, BINARY_ FLOAT, or BINARY_DOUBLE. If expr is BINARY_FLOAT, then the function returns expr. ■ The optional 'fmt' and 'nlsparam' arguments are valid only if expr is a character string. They serve the same purpose as for the TO_CHAR (number) function. – The incase-sensitive string 'INF' is converted to positive infinity. – The incase-sensitive string '-INF' is converted to negative identity. – The incase-sensitive string 'NaN' is converted to NaN (not a number). You cannot use a floating-point number format element (F, f, D, or d) in a character string expr. Conversions from character strings or NUMBER to BINARY_FLOAT can be inexact, because the NUMBER and character types use decimal precision to represent the numeric value and BINARY_FLOAT uses binary precision. Conversions from BINARY_DOUBLE to BINARY_FLOAT are inexact if the BINARY_ DOUBLE value uses more bits of precision than supported by the BINARY_FLOAT. Examples Using table float_point_demo created for TO_BINARY_DOUBLE on page 5-215, the following example converts a value of data type NUMBER to a value of data type BINARY_FLOAT: SELECT dec_num, TO_BINARY_FLOAT(dec_num) FROM float_point_demo; DEC_NUM TO_BINARY_FLOAT(DEC_NUM) ---------- ------------------------ 1234.56 1.235E+003 TO_BLOB Syntax to_blob::= Purpose TO_BLOB converts LONG RAW and RAW values to BLOB values. From within a PL/SQL package, you can use TO_BLOB to convert RAW and BLOB values to BLOB. Example The following hypothetical example returns the BLOB of a RAW column value: SELECT TO_BLOB(raw_column) blob FROM raw_table; See Also: TO_CHAR (number) on page 5-221 and "Floating-Point Numbers" on page 3-12 TO_BLOB ( raw_value )
  • 392. TO_CHAR (character) 5-218 Oracle Database SQL Language Reference BLOB ----------------------- 00AADD343CDBBD TO_CHAR (character) Syntax to_char_char::= Purpose TO_CHAR (character) converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. The value returned is always VARCHAR2. When you use this function to convert a character LOB into the database character set, if the LOB value to be converted is larger than the target type, then the database returns an error. You can use this function in conjunction with any of the XML functions to generate a date in the database format rather than the XML Schema standard format. Examples The following example interprets a simple string as character data: SELECT TO_CHAR('01110') FROM DUAL; TO_CH ----- 01110 Compare this example with the first example for TO_CHAR (number) on page 5-221. The following example converts some CLOB data from the pm.print_media table to the database character set: SELECT TO_CHAR(ad_sourcetext) FROM print_media WHERE product_id = 2268; TO_CHAR(AD_SOURCETEXT) -------------------------------------------------------------------- ****************************** TIGER2 2268...Standard Hayes Compatible Modem Product ID: 2268 The #1 selling modem in the universe! Tiger2's modem includes call management and Internet voicing. Make real-time full duplex phone calls at the same time See Also: ■ Oracle XML DB Developer's Guide for information about formatting of XML dates and timestamps, including examples ■ "XML Functions" on page 5-8 for a listing of the XML function TO_CHAR ( nchar clob nclob )
  • 393. TO_CHAR (datetime) Functions 5-219 you're online. ********************************** TO_CHAR (datetime) Syntax to_char_date::= Purpose TO_CHAR (datetime) converts a datetime or interval value of DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL DAY TO SECOND, or INTERVAL YEAR TO MONTH data type to a value of VARCHAR2 data type in the format specified by the date format fmt. If you omit fmt, then date is converted to a VARCHAR2 value as follows: ■ DATE values are converted to values in the default date format. ■ TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONE values are converted to values in the default timestamp format. ■ TIMESTAMP WITH TIME ZONE values are converted to values in the default timestamp with time zone format. ■ Interval values are converted to the numeric representation of the interval literal. Refer to "Format Models" on page 3-55 for information on datetime formats. The 'nlsparam' argument specifies the language in which month and day names and abbreviations are returned. This argument can have this form: 'NLS_DATE_LANGUAGE = language' If you omit 'nlsparam', then this function uses the default date language for your session. Examples The following example uses this table: CREATE TABLE date_tab ( ts_col TIMESTAMP, tsltz_col TIMESTAMP WITH LOCAL TIME ZONE, tstz_col TIMESTAMP WITH TIME ZONE); The example shows the results of applying TO_CHAR to different TIMESTAMP data types. The result for a TIMESTAMP WITH LOCAL TIME ZONE column is sensitive to session time zone, whereas the results for the TIMESTAMP and TIMESTAMP WITH TIME ZONE columns are not sensitive to session time zone: ALTER SESSION SET TIME_ZONE = '-8:00'; INSERT INTO date_tab VALUES ( See Also: "Security Considerations for Data Conversion" on page 3-44 TO_CHAR ( datetime interval , fmt , ’ nlsparam ’ )
  • 394. TO_CHAR (datetime) 5-220 Oracle Database SQL Language Reference TIMESTAMP'1999-12-01 10:00:00', TIMESTAMP'1999-12-01 10:00:00', TIMESTAMP'1999-12-01 10:00:00'); INSERT INTO date_tab VALUES ( TIMESTAMP'1999-12-02 10:00:00 -8:00', TIMESTAMP'1999-12-02 10:00:00 -8:00', TIMESTAMP'1999-12-02 10:00:00 -8:00'); SELECT TO_CHAR(ts_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS ts_date, TO_CHAR(tstz_col, 'DD-MON-YYYY HH24:MI:SSxFF TZH:TZM') AS tstz_date FROM date_tab ORDER BY ts_date, tstz_date; TS_DATE TSTZ_DATE ------------------------------ ------------------------------------- 01-DEC-1999 10:00:00.000000 01-DEC-1999 10:00:00.000000 -08:00 02-DEC-1999 10:00:00.000000 02-DEC-1999 10:00:00.000000 -08:00 SELECT SESSIONTIMEZONE, TO_CHAR(tsltz_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS tsltz FROM date_tab ORDER BY sessiontimezone, tsltz; SESSIONTIM TSLTZ ---------- ------------------------------ -08:00 01-DEC-1999 10:00:00.000000 -08:00 02-DEC-1999 10:00:00.000000 ALTER SESSION SET TIME_ZONE = '-5:00'; SELECT TO_CHAR(ts_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS ts_col, TO_CHAR(tstz_col, 'DD-MON-YYYY HH24:MI:SSxFF TZH:TZM') AS tstz_col FROM date_tab ORDER BY ts_col, tstz_col; TS_COL TSTZ_COL ------------------------------ ------------------------------------- 01-DEC-1999 10:00:00.000000 01-DEC-1999 10:00:00.000000 -08:00 02-DEC-1999 10:00:00.000000 02-DEC-1999 10:00:00.000000 -08:00 SELECT SESSIONTIMEZONE, TO_CHAR(tsltz_col, 'DD-MON-YYYY HH24:MI:SSxFF') AS tsltz_col FROM date_tab ORDER BY sessiontimezone, tsltz_col; 2 3 4 SESSIONTIM TSLTZ_COL ---------- ------------------------------ -05:00 01-DEC-1999 13:00:00.000000 -05:00 02-DEC-1999 13:00:00.000000 The following example converts an interval literal into a text literal: SELECT TO_CHAR(INTERVAL '123-2' YEAR(3) TO MONTH) FROM DUAL; TO_CHAR ------- +123-02
  • 395. TO_CHAR (number) Functions 5-221 TO_CHAR (number) Syntax to_char_number::= Purpose TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or BINARY_ DOUBLE. If you omit fmt, then n is converted to a VARCHAR2 value exactly long enough to hold its significant digits. If n is negative, then the sign is applied after the format is applied. Thus TO_ CHAR(-1, '$9') returns -$1, rather than $-1. Refer to "Format Models" on page 3-55 for information on number formats. The 'nlsparam' argument specifies these characters that are returned by number format elements: ■ Decimal character ■ Group separator ■ Local currency symbol ■ International currency symbol This argument can have this form: 'NLS_NUMERIC_CHARACTERS = ''dg'' NLS_CURRENCY = ''text'' NLS_ISO_CURRENCY = territory ' The characters d and g represent the decimal character and group separator, respectively. They must be different single-byte characters. Within the quoted string, you must use two single quotation marks around the parameter values. Ten characters are available for the currency symbol. If you omit 'nlsparam' or any one of the parameters, then this function uses the default parameter values for your session. Examples The following statement uses implicit conversion to combine a string and a number into a number: SELECT TO_CHAR('01110' + 1) FROM dual; TO_C ---- 1111 See Also: "Security Considerations for Data Conversion" on page 3-44 TO_CHAR ( n , fmt , ’ nlsparam ’ )
  • 396. TO_CLOB 5-222 Oracle Database SQL Language Reference Compare this example with the first example for TO_CHAR (character) on page 5-218. In the next example, the output is blank padded to the left of the currency symbol. SELECT TO_CHAR(-10000,'L99G999D99MI') "Amount" FROM DUAL; Amount -------------- $10,000.00- SELECT TO_CHAR(-10000,'L99G999D99MI', 'NLS_NUMERIC_CHARACTERS = '',.'' NLS_CURRENCY = ''AusDollars'' ') "Amount" FROM DUAL; Amount ------------------- AusDollars10.000,00- In the optional number format fmt, L designates local currency symbol and MI designates a trailing minus sign. See Table 3–17, " Matching Character Data and Format Models with the FX Format Model Modifier" on page 3-67 for a complete listing of number format elements. TO_CLOB Syntax Purpose TO_CLOB converts NCLOB values in a LOB column or other character strings to CLOB values. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Oracle Database executes this function by converting the underlying LOB data from the national character set to the database character set. From within a PL/SQL package, you can use the TO_CLOB function to convert RAW, CHAR, VARCHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB values to CLOB or NCLOB values. Examples The following statement converts NCLOB data from the sample pm.print_media table to CLOB and inserts it into a CLOB column, replacing existing data in that column. UPDATE PRINT_MEDIA SET AD_FINALTEXT = TO_CLOB (AD_FLTEXTN); TO_CLOB ( lob_column char )
  • 397. TO_DATE Functions 5-223 TO_DATE Syntax Purpose TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to a value of DATE data type. The fmt is a datetime model format specifying the format of char. If you omit fmt, then char must be in the default date format. The default date format is determined implicitly by the NLS_TERRITORY initialization parameter or can be set explicitly by the NLS_DATE_FORMAT parameter. If fmt is J, for Julian, then char must be an integer. The 'nlsparam' argument specifies the language of the text string that is being converted to a date. This argument can have this form: 'NLS_DATE_LANGUAGE = language' Do not use the TO_DATE function with a DATE value for the char argument. The first two digits of the returned DATE value can differ from the original char, depending on fmt or the default date format. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example converts a character string into a date: SELECT TO_DATE( 'January 15, 1989, 11:00 A.M.', Note: This function does not convert data to any of the other datetime data types. For information on other datetime conversions, refer to TO_TIMESTAMP on page 5-230, TO_TIMESTAMP_TZ on page 5-231, TO_DSINTERVAL on page 5-224, and TO_YMINTERVAL on page 5-232. Caution: It is good practice always to specify a format mask (fmt) with TO_DATE, as shown in the examples in the section that follows. When it is used without a format mask, the function is valid only if char uses the same format as is determined by the NLS_TERRITORY or NLS_DATE_FORMAT parameters. Furthermore, the function may not be stable across databases unless the explicit format mask is specified to avoid dependencies. See Also: "Datetime Format Models" on page 3-59 and "Data Type Comparison Rules" on page 3-37 for more information TO_DATE ( char , fmt , ’ nlsparam ’ )
  • 398. TO_DSINTERVAL 5-224 Oracle Database SQL Language Reference 'Month dd, YYYY, HH:MI A.M.', 'NLS_DATE_LANGUAGE = American') FROM DUAL; TO_DATE(' --------- 15-JAN-89 The value returned reflects the default date format if the NLS_TERRITORY parameter is set to 'AMERICA'. Different NLS_TERRITORY values result in different default date formats: ALTER SESSION SET NLS_TERRITORY = 'KOREAN'; SELECT TO_DATE( 'January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.', 'NLS_DATE_LANGUAGE = American') FROM DUAL; TO_DATE( -------- 89/01/15 TO_DSINTERVAL Syntax sql_format::= ds_iso_format::= Purpose TO_DSINTERVAL converts a character string of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to an INTERVAL DAY TO SECOND type. TO_DSINTERVAL accepts argument in one of the two formats: ■ SQL interval format compatible with the SQL standard (ISO/IEC 9075:2003) ■ ISO duration format compatible with the ISO 8601:2004 standard TO_DSINTERVAL ( ’ sql_format ds_iso_format ’ ) + – days hours : minutes : seconds . frac_secs – P days D T hours H minutes M seconds . frac_secs S
  • 399. TO_LOB Functions 5-225 In the SQL format, days is an integer between 0 and 999999999, hours is an integer between 0 and 23, and minutes and seconds are integers between 0 and 59. frac_ secs is the fractional part of seconds between .0 and .999999999. One or more blanks separate days from hours. Additional blanks are allowed between format elements. In the ISO format, days, hours, minutes and seconds are integers between 0 and 999999999. frac_secs is the fractional part of seconds between .0 and .999999999. No blanks are allowed in the value. Examples The following example uses the SQL format to select from the hr.employees table the employees who had worked for the company for at least 100 days on November 1, 2002: SELECT employee_id, last_name FROM employees WHERE hire_date + TO_DSINTERVAL('100 00:00:00') <= DATE '2002-11-01' ORDER BY employee_id; EMPLOYEE_ID LAST_NAME ----------- --------------- 102 De Haan 203 Mavris 204 Baer 205 Higgins 206 Giet The following example uses the ISO format to display the timestamp 100 days and 5 hours after the beginning of the year 2009: SELECT TO_CHAR(TIMESTAMP '2009-01-01 00:00:00' + TO_DSINTERVAL('P100DT05H'), 'YYYY-MM-DD HH24:MI:SS') "Time Stamp" FROM DUAL; Time Stamp ------------------- 2009-04-11 05:00:00 TO_LOB Syntax Purpose TO_LOB converts LONG or LONG RAW values in the column long_column to LOB values. You can apply this function only to a LONG or LONG RAW column, and only in the select list of a subquery in an INSERT statement. Before using this function, you must create a LOB column to receive the converted LONG values. To convert LONG values, create a CLOB column. To convert LONG RAW values, create a BLOB column. You cannot use the TO_LOB function to convert a LONG column to a LOB column in the subquery of a CREATE TABLE ... AS SELECT statement if you are creating an index-organized table. Instead, create the index-organized table without the LONG column, and then use the TO_LOB function in an INSERT ... AS SELECT statement. TO_LOB ( long_column )
  • 400. TO_MULTI_BYTE 5-226 Oracle Database SQL Language Reference You cannot use this function within a PL/SQL package. Instead use the TO_CLOB or TO_BLOB functions. Example The following syntax shows how to use the TO_LOB function on your LONG data in a hypothetical table old_table: CREATE TABLE new_table (col1, col2, ... lob_col CLOB); INSERT INTO new_table (select o.col1, o.col2, ... TO_LOB(o.old_long_col) FROM old_table o; TO_MULTI_BYTE Syntax Purpose TO_MULTI_BYTE returns char with all of its single-byte characters converted to their corresponding multibyte characters. char can be of data type CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned is in the same data type as char. Any single-byte characters in char that have no multibyte equivalents appear in the output string as single-byte characters. This function is useful only if your database character set contains both single-byte and multibyte characters. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example illustrates converting from a single byte A to a multibyte A in UTF8: SELECT dump(TO_MULTI_BYTE( 'A')) FROM DUAL; DUMP(TO_MULTI_BYTE('A')) ------------------------ Typ=1 Len=3: 239,188,161 See Also: ■ the modify_col_properties clause of ALTER TABLE on page 12-2 for an alternative method of converting LONG columns to LOB ■ INSERT on page 18-54 for information on the subquery of an INSERT statement See Also: "Data Type Comparison Rules" on page 3-37 for more information. TO_MULTI_BYTE ( char )
  • 401. TO_NCHAR (datetime) Functions 5-227 TO_NCHAR (character) Syntax to_nchar_char::= Purpose TO_NCHAR (character) converts a character string, CHAR, VARCHAR2, CLOB, or NCLOB value to the national character set. The value returned is always NVARCHAR2. This function is equivalent to the TRANSLATE ... USING function with a USING clause in the national character set. Examples The following example converts VARCHAR2 data from the oe.customers table to the national character set: SELECT TO_NCHAR(cust_last_name) FROM customers WHERE customer_id=103; TO_NCHAR(CUST_LAST_NAME) -------------------------------------------------- Taylor TO_NCHAR (datetime) Syntax to_nchar_date::= Purpose TO_NCHAR (datetime) converts a datetime or interval value of DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL MONTH TO YEAR, or INTERVAL DAY TO SECOND data type from the database character set to the national character set. See Also: "Data Conversion" on page 3-40 and TRANSLATE ... USING on page 5-234 See Also: "Security Considerations for Data Conversion" on page 3-44 TO_NCHAR ( char clob nclob ) TO_NCHAR ( datetime interval , fmt , ’ nlsparam ’ )
  • 402. TO_NCHAR (number) 5-228 Oracle Database SQL Language Reference Examples The following example converts the order_date of all orders whose status is 9 to the national character set: SELECT TO_NCHAR(ORDER_DATE) AS order_date FROM ORDERS WHERE ORDER_STATUS > 9 ORDER BY order_date; ORDER_DATE -------------------------------------------------------------------------- 06-DEC-99 02.22.34.225609 PM 13-SEP-99 10.19.00.654279 AM 14-SEP-99 09.53.40.223345 AM 26-JUN-00 10.19.43.190089 PM 27-JUN-00 09.53.32.335522 PM TO_NCHAR (number) Syntax to_nchar_number::= Purpose TO_NCHAR (number) converts n to a string in the national character set. The value n can be of type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE. The function returns a value of the same type as the argument. The optional fmt and 'nlsparam' corresponding to n can be of DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL MONTH TO YEAR, or INTERVAL DAY TO SECOND data type. Examples The following example converts the customer_id values from the sample table oe.orders to the national character set: SELECT TO_NCHAR(customer_id) "NCHAR_Customer_ID" FROM orders WHERE order_status > 9 ORDER BY "NCHAR_Customer_ID"; NCHAR_Customer_ID ---------------------------------------- 102 103 148 148 149 See Also: "Security Considerations for Data Conversion" on page 3-44 TO_NCHAR ( n , fmt , ’ nlsparam ’ )
  • 403. TO_NUMBER Functions 5-229 TO_NCLOB Syntax Purpose TO_NCLOB converts CLOB values in a LOB column or other character strings to NCLOB values. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Oracle Database implements this function by converting the character set of char from the database character set to the national character set. Examples The following example inserts some character data into an NCLOB column of the pm.print_media table by first converting the data with the TO_NCLOB function: INSERT INTO print_media (product_id, ad_id, ad_fltextn) VALUES (3502, 31001, TO_NCLOB('Placeholder for new product description')); TO_NUMBER Syntax Purpose TO_NUMBER converts expr to a value of NUMBER data type. The expr can be a BINARY_DOUBLE value or a value of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type containing a number in the format specified by the optional format model fmt. You can specify an expr of BINARY_FLOAT. However, it makes no sense to do so because a float can be interpreted only by its internal presentation. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following examples convert character string data into a number: UPDATE employees SET salary = salary + TO_NUMBER('100.00', '9G999D99') WHERE last_name = 'Perkins'; The 'nlsparam' argument in this function has the same purpose as it does in the TO_CHAR function for number conversions. Refer to TO_CHAR (number) on page 5-221 for more information. See Also: "Data Type Comparison Rules" on page 3-37 for more information. TO_NCLOB ( lob_column char ) TO_NUMBER ( expr , fmt , ’ nlsparam ’ )
  • 404. TO_SINGLE_BYTE 5-230 Oracle Database SQL Language Reference SELECT TO_NUMBER('-AusDollars100','L9G999D99', ' NLS_NUMERIC_CHARACTERS = '',.'' NLS_CURRENCY = ''AusDollars'' ') "Amount" FROM DUAL; Amount ---------- -100 TO_SINGLE_BYTE Syntax Purpose TO_SINGLE_BYTE returns char with all of its multibyte characters converted to their corresponding single-byte characters. char can be of data type CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned is in the same data type as char. Any multibyte characters in char that have no single-byte equivalents appear in the output as multibyte characters. This function is useful only if your database character set contains both single-byte and multibyte characters. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example illustrates going from a multibyte A in UTF8 to a single byte ASCII A: SELECT TO_SINGLE_BYTE( CHR(15711393)) FROM DUAL; T - A TO_TIMESTAMP Syntax Purpose TO_TIMESTAMP converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to a value of TIMESTAMP data type. The optional fmt specifies the format of char. If you omit fmt, then char must be in the default format of the TIMESTAMP data type, which is determined by the NLS_ See Also: "Data Type Comparison Rules" on page 3-37 for more information. TO_SINGLE_BYTE ( char ) TO_TIMESTAMP ( char , fmt , ’ nlsparam ’ )
  • 405. TO_TIMESTAMP_TZ Functions 5-231 TIMESTAMP_FORMAT initialization parameter. The optional 'nlsparam' argument has the same purpose in this function as in the TO_CHAR function for date conversion. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example converts a character string to a timestamp. The character string is not in the default TIMESTAMP format, so the format mask must be specified: SELECT TO_TIMESTAMP ('10-Sep-02 14:10:10.123000', 'DD-Mon-RR HH24:MI:SS.FF') FROM DUAL; TO_TIMESTAMP('10-SEP-0214:10:10.123000','DD-MON-RRHH24:MI:SS.FF') --------------------------------------------------------------------------- 10-SEP-02 02.10.10.123000000 PM TO_TIMESTAMP_TZ Syntax Purpose TO_TIMESTAMP_TZ converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to a value of TIMESTAMP WITH TIME ZONE data type. The optional fmt specifies the format of char. If you omit fmt, then char must be in the default format of the TIMESTAMP WITH TIME ZONE data type. The optional 'nlsparam' has the same purpose in this function as in the TO_CHAR function for date conversion. Examples The following example converts a character string to a value of TIMESTAMP WITH TIME ZONE: SELECT TO_TIMESTAMP_TZ('1999-12-01 11:00:00 -8:00', 'YYYY-MM-DD HH:MI:SS TZH:TZM') FROM DUAL; TO_TIMESTAMP_TZ('1999-12-0111:00:00-08:00','YYYY-MM-DDHH:MI:SSTZH:TZM') -------------------------------------------------------------------- See Also: "Data Type Comparison Rules" on page 3-37 for more information. See Also: NLS_TIMESTAMP_FORMAT parameter for information on the default TIMESTAMP format and "Datetime Format Models" on page 3-59 for information on specifying the format mask Note: This function does not convert character strings to TIMESTAMP WITH LOCAL TIME ZONE. To do this, use a CAST function, as shown in CAST on page 5-28. TO_TIMESTAMP_TZ ( char , fmt , ’ nlsparam ’ )
  • 406. TO_YMINTERVAL 5-232 Oracle Database SQL Language Reference 01-DEC-99 11.00.00.000000000 AM -08:00 The following example casts a null column in a UNION operation as TIMESTAMP WITH LOCAL TIME ZONE using the sample tables oe.order_items and oe.orders: SELECT order_id, line_item_id, CAST(NULL AS TIMESTAMP WITH LOCAL TIME ZONE) order_date FROM order_items UNION SELECT order_id, to_number(null), order_date FROM orders; ORDER_ID LINE_ITEM_ID ORDER_DATE ---------- ------------ ----------------------------------- 2354 1 2354 2 2354 3 2354 4 2354 5 2354 6 2354 7 2354 8 2354 9 2354 10 2354 11 2354 12 2354 13 2354 14-JUL-00 05.18.23.234567 PM 2355 1 2355 2 ... TO_YMINTERVAL Syntax ym_iso_format::= Purpose TO_YMINTERVAL converts a character string of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to an INTERVAL YEAR TO MONTH type. TO_YMINTERVAL accepts argument in one of the two formats: TO_YMINTERVAL ( ’ + – years – months ym_iso_format ’ ) – P years Y months M days D T hours H minutes M seconds . frac_secs S
  • 407. TRANSLATE Functions 5-233 ■ SQL interval format compatible with the SQL standard (ISO/IEC 9075:2003) ■ ISO duration format compatible with the ISO 8601:2004 standard In the SQL format, years is an integer between 0 and 999999999, and months is an integer between 0 and 11. Additional blanks are allowed between format elements. In the ISO format, years and months are integers between 0 and 999999999. Days, hours, minutes, seconds, and frac_secs are non-negative integers, and are ignored, if specified. No blanks are allowed in the value. Examples The following example calculates for each employee in the sample hr.employees table a date one year two months after the hire date: SELECT hire_date, hire_date + TO_YMINTERVAL('01-02') "14 months" FROM employees; HIRE_DATE 14 months --------- --------- 17-JUN-03 17-AUG-04 21-SEP-05 21-NOV-06 13-JAN-01 13-MAR-02 20-MAY-08 20-JUL-09 21-MAY-07 21-JUL-08 . . . The following example makes the same calculation using the ISO format: SELECT hire_date, hire_date + TO_YMINTERVAL('P1Y2M') FROM employees; TRANSLATE Syntax Purpose TRANSLATE returns expr with all occurrences of each character in from_string replaced by its corresponding character in to_string. Characters in expr that are not in from_string are not replaced. The argument from_string can contain more characters than to_string. In this case, the extra characters at the end of from_ string have no corresponding characters in to_string. If these extra characters appear in expr, then they are removed from the return value. If a character appears multiple times in from_string, then the to_string mapping corresponding to the first occurrence is used. You cannot use an empty string for to_string to remove all characters in from_ string from the return value. Oracle Database interprets the empty string as null, and if this function has a null argument, then it returns null. To remove all characters in from_string, concatenate another character to the beginning of from_string and specify this character as the to_string. For example, TRANSLATE(expr, 'x0123456789', 'x') removes all digits from expr. TRANSLATE provides functionality related to that provided by the REPLACE function. REPLACE lets you substitute a single string for another single string, as well as remove TRANSLATE ( expr , from_string , to_string )
  • 408. TRANSLATE ... USING 5-234 Oracle Database SQL Language Reference character strings. TRANSLATE lets you make several single-character, one-to-one substitutions in one operation. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following statement translates a book title into a string that could be used (for example) as a filename. The from_string contains four characters: a space, asterisk, slash, and apostrophe (with an extra apostrophe as the escape character). The to_ string contains only three underscores. This leaves the fourth character in the from_ string without a corresponding replacement, so apostrophes are dropped from the returned value. SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '___') FROM DUAL; TRANSLATE('SQL*PLUSU -------------------- SQL_Plus_Users_Guide TRANSLATE ... USING Syntax Purpose TRANSLATE ... USING converts char into the character set specified for conversions between the database character set and the national character set. The char argument is the expression to be converted. ■ Specifying the USING CHAR_CS argument converts char into the database character set. The output data type is VARCHAR2. ■ Specifying the USING NCHAR_CS argument converts char into the national character set. The output data type is NVARCHAR2. This function is similar to the Oracle CONVERT function, but must be used instead of CONVERT if either the input or the output data type is being used as NCHAR or NVARCHAR2. If the input contains UCS2 code points or backslash characters (), then use the UNISTR function. See Also: "Data Type Comparison Rules" on page 3-37 for more information and REPLACE on page 5-172 Note: The TRANSLATE ... USING function is supported primarily for ANSI compatibility. Oracle recommends that you use the TO_CHAR and TO_NCHAR functions, as appropriate, for converting data to the database or national character set. TO_CHAR and TO_NCHAR can take as arguments a greater variety of data types than TRANSLATE ... USING, which accepts only character data. See Also: CONVERT on page 5-41 and UNISTR on page 5-239 TRANSLATE ( char USING CHAR_CS NCHAR_CS )
  • 409. TREAT Functions 5-235 Examples The following statements use data from the sample table oe.product_ descriptions to show the use of the TRANSLATE ... USING function: CREATE TABLE translate_tab (char_col VARCHAR2(100), nchar_col NVARCHAR2(50)); INSERT INTO translate_tab SELECT NULL, translated_name FROM product_descriptions WHERE product_id = 3501; SELECT * FROM translate_tab; CHAR_COL NCHAR_COL -------------------- -------------------------------------------------- . . . C pre SPNIX4.0 - Sys C pro SPNIX4.0 - Sys C til SPNIX4.0 - Sys C voor SPNIX4.0 - Sys . . . UPDATE translate_tab SET char_col = TRANSLATE (nchar_col USING CHAR_CS); SELECT * FROM translate_tab; CHAR_COL NCHAR_COL ------------------------- ------------------------- . . . C per a SPNIX4.0 - Sys C per a SPNIX4.0 - Sys C pro SPNIX4.0 - Sys C pro SPNIX4.0 - Sys C for SPNIX4.0 - Sys C for SPNIX4.0 - Sys C til SPNIX4.0 - Sys C til SPNIX4.0 - Sys . . . TREAT Syntax Purpose TREAT changes the declared type of an expression. You must have the EXECUTE object privilege on type to use this function. ■ type must be some supertype or subtype of the declared type of expr. If the most specific type of expr is type (or some subtype of type), then TREAT returns expr. If the most specific type of expr is not type (or some subtype of type), then TREAT returns NULL. ■ You can specify REF only if the declared type of expr is a REF type. ■ If the declared type of expr is a REF to a source type of expr, then type must be some subtype or supertype of the source type of expr. If the most specific type of DEREF(expr) is type (or a subtype of type), then TREAT returns expr. If the TREAT ( expr AS REF schema . type )
  • 410. TRIM 5-236 Oracle Database SQL Language Reference most specific type of DEREF(expr) is not type (or a subtype of type), then TREAT returns NULL. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following statement uses the table oe.persons, which is created in "Substitutable Table and Column Examples" on page 16-69. The example retrieves the salary attribute of all people in the persons table, the value being null for instances of people that are not employees. SELECT name, TREAT(VALUE(p) AS employee_t).salary salary FROM persons p; NAME SALARY ------------------------- ---------- Bob Joe 100000 Tim 1000 You can use the TREAT function to create an index on the subtype attributes of a substitutable column. For an example, see "Indexing on Substitutable Columns: Examples" on page 14-86. TRIM Syntax Purpose TRIM enables you to trim leading or trailing characters (or both) from a character string. If trim_character or trim_source is a character literal, then you must enclose it in single quotation marks. ■ If you specify LEADING, then Oracle Database removes any leading characters equal to trim_character. ■ If you specify TRAILING, then Oracle removes any trailing characters equal to trim_character. ■ If you specify BOTH or none of the three, then Oracle removes leading and trailing characters equal to trim_character. ■ If you do not specify trim_character, then the default value is a blank space. ■ If you specify only trim_source, then Oracle removes leading and trailing blank spaces. See Also: "Data Type Comparison Rules" on page 3-37 for more information TRIM ( LEADING TRAILING BOTH trim_character trim_character FROM trim_source )
  • 411. TRUNC (date) Functions 5-237 ■ The function returns a value with data type VARCHAR2. The maximum length of the value is the length of trim_source. ■ If either trim_source or trim_character is null, then the TRIM function returns null. Both trim_character and trim_source can be VARCHAR2 or any data type that can be implicitly converted to VARCHAR2. The string returned is a VARCHAR2 (NVARCHAR2) data type if trim_source is a CHAR or VARCHAR2 (NCHAR or NVARCHAR2) data type, and a CLOB if trim_source is a CLOB data type. The return string is in the same character set as trim_source. Examples This example trims leading zeros from the hire date of the employees in the hr schema: SELECT employee_id, TO_CHAR(TRIM(LEADING 0 FROM hire_date)) FROM employees WHERE department_id = 60 ORDER BY employee_id; EMPLOYEE_ID TO_CHAR(T ----------- --------- 103 20-MAY-08 104 21-MAY-07 105 25-JUN-05 106 5-FEB-06 107 7-FEB-07 TRUNC (date) Syntax trunc_date::= Purpose The TRUNC (date) function returns date with the time portion of the day truncated to the unit specified by the format model fmt. This function is not sensitive to the NLS_ CALENDAR session parameter. It operates according to the rules of the Gregorian calendar. The value returned is always of data type DATE, even if you specify a different datetime data type for date. If you omit fmt, then date is truncated to the nearest day. Refer to "ROUND and TRUNC Date Functions" on page 5-270 for the permitted format models to use in fmt. Examples The following example truncates a date: SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR') "New Year" FROM DUAL; New Year --------- TRUNC ( date , fmt )
  • 412. TRUNC (number) 5-238 Oracle Database SQL Language Reference 01-JAN-92 TRUNC (number) Syntax trunc_number::= Purpose The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is omitted, then n1 is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left of the decimal point. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. If you omit n2, then the function returns the same data type as the numeric data type of the argument. If you include n2, then the function returns NUMBER. Examples The following examples truncate numbers: SELECT TRUNC(15.79,1) "Truncate" FROM DUAL; Truncate ---------- 15.7 SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL; Truncate ---------- 10 TZ_OFFSET Syntax Purpose TZ_OFFSET returns the time zone offset corresponding to the argument based on the date the statement is executed. You can enter a valid time zone region name, a time See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion TRUNC ( n1 , n2 ) TZ_OFFSET ( ’ time_zone_name ’ ’ + – hh : mi ’ SESSIONTIMEZONE DBTMEZONE )
  • 413. UNISTR Functions 5-239 zone offset from UTC (which simply returns itself), or the keyword SESSIONTIMEZONE or DBTIMEZONE. For a listing of valid values for time_zone_ name, query the TZNAME column of the V$TIMEZONE_NAMES dynamic performance view. Examples The following example returns the time zone offset of the US/Eastern time zone from UTC: SELECT TZ_OFFSET('US/Eastern') FROM DUAL; TZ_OFFS ------- -04:00 UID Syntax Purpose UID returns an integer that uniquely identifies the session user (the user who logged on). Examples The following example returns the UID of the current user: SELECT UID FROM DUAL; UNISTR Syntax Purpose UNISTR takes as its argument a text literal or an expression that resolves to character data and returns it in the national character set. The national character set of the database can be either AL16UTF16 or UTF8. UNISTR provides support for Unicode string literals by letting you specify the Unicode encoding value of characters in the string. This is useful, for example, for inserting data into NCHAR columns. The Unicode encoding value has the form 'xxxx' where 'xxxx' is the hexadecimal value of a character in UCS-2 encoding format. Supplementary characters are encoded Note: Time zone region names are needed by the daylight saving feature. These names are stored in two types of time zone files: one large and one small. One of these files is the default file, depending on your environment and the release of Oracle Database you are using. For more information regarding time zone files and names, see Oracle Database Globalization Support Guide. UID UNISTR ( string )
  • 414. UPDATEXML 5-240 Oracle Database SQL Language Reference as two code units, the first from the high-surrogates range (U+D800 to U+DBFF), and the second from the low-surrogates range (U+DC00 to U+DFFF). To include the backslash in the string itself, precede it with another backslash (). For portability and data preservation, Oracle recommends that in the UNISTR string argument you specify only ASCII characters and the Unicode encoding values. Examples The following example passes both ASCII characters and Unicode encoding values to the UNISTR function, which returns the string in the national character set: SELECT UNISTR('abc00e500f100f6') FROM DUAL; UNISTR ------ abcåñö UPDATEXML Syntax Purpose UPDATEXML takes as arguments an XMLType instance and an XPath-value pair and returns an XMLType instance with the updated value. If XPath_string is an XML element, then the corresponding value_expr must be an XMLType instance. If XPath_string is an attribute or text node, then the value_expr can be any scalar data type. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, then the context of the relative path defaults to the root node. The data types of the target of each XPath_string and its corresponding value_ expr must match. The optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath expression(s). If you update an XML element to null, then Oracle removes the attributes and children of the element, and the element becomes empty. If you update the text node of an element to null, Oracle removes the text value of the element, and the element itself remains but is empty. In most cases, this function materializes an XML document in memory and updates the value. However, UPDATEXML is optimized for UPDATE statements on object-relational columns so that the function updates the value directly in the column. This optimization requires the following conditions: ■ The XMLType_instance must be the same as the column in the UPDATE ... SET clause. ■ The XPath_string must resolve to scalar content. See Also: Oracle Database Globalization Support Guide for information on Unicode and national character sets UPDATEXML ( XMLType_instance , XPath_string , value_expr , , namespace_string )
  • 415. UPPER Functions 5-241 Examples The following example updates to 4 the number of docks in the San Francisco warehouse in the sample schema OE, which has a warehouse_spec column of type XMLType: SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks" FROM warehouses WHERE warehouse_name = 'San Francisco'; WAREHOUSE_NAME Number of Docks -------------------- -------------------- San Francisco <Docks>1</Docks> UPDATE warehouses SET warehouse_spec = UPDATEXML(warehouse_spec, '/Warehouse/Docks/text()',4) WHERE warehouse_name = 'San Francisco'; 1 row updated. SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks" FROM warehouses WHERE warehouse_name = 'San Francisco'; WAREHOUSE_NAME Number of Docks -------------------- -------------------- San Francisco <Docks>4</Docks> UPPER Syntax Purpose UPPER returns char, with all letters uppercase. char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same data type as char. The database sets the case of the characters based on the binary mapping defined for the underlying character set. For linguistic-sensitive uppercase, refer to NLS_UPPER on page 5-119. Examples The following example returns each employee's last name in uppercase: SELECT UPPER(last_name) "Uppercase" FROM employees; UPPER ( char )
  • 416. USER 5-242 Oracle Database SQL Language Reference USER Syntax Purpose USER returns the name of the session user (the user who logged on) with the data type VARCHAR2. Oracle Database compares values of this function with blank-padded comparison semantics. In a distributed SQL statement, the UID and USER functions together identify the user on your local database. You cannot use these functions in the condition of a CHECK constraint. Examples The following example returns the current user and the user's UID: SELECT USER, UID FROM DUAL; USERENV Syntax Purpose USERENV returns information about the current session. This information can be useful for writing an application-specific audit trail table or for determining the language-specific characters currently used by your session. You cannot use USERENV in the condition of a CHECK constraint. Table 5–13 describes the values for the parameter argument. All calls to USERENV return VARCHAR2 data except for calls with the SESSIONID, SID, and ENTRYID parameters, which return NUMBER. Note: USERENV is a legacy function that is retained for backward compatibility. Oracle recommends that you use the SYS_CONTEXT function with the built-in USERENV namespace for current functionality. See SYS_CONTEXT on page 5-202 for more information. USER USERENV ( ’ parameter ’ )
  • 417. VALUE Functions 5-243 Examples The following example returns the LANGUAGE parameter of the current session: SELECT USERENV('LANGUAGE') "Language" FROM DUAL; Language ----------------------------------- AMERICAN_AMERICA.WE8ISO8859P1 VALUE Syntax Table 5–13 Parameters of the USERENV Function Parameter Return Value CLIENT_INFO CLIENT_INFO returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package. Caution: Some commercial applications may be using this context value. Refer to the applicable documentation for those applications to determine what restrictions they may impose on use of this context area. See Also: ■ Oracle Database Security Guide for more information on application context ■ CREATE CONTEXT on page 14-9 and SYS_CONTEXT on page 5-202 ENTRYID The current audit entry number. The audit entryid sequence is shared between fine-grained audit records and regular audit records. You cannot use this attribute in distributed SQL statements. ISDBA ISDBA returns 'TRUE' if the user has been authenticated as having DBA privileges either through the operating system or through a password file. LANG LANG returns the ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter. LANGUAGE LANGUAGE returns the language and territory used by the current session along with the database character set in this form: language_territory.characterset SESSIONID SESSIONID returns the auditing session identifier. You cannot specify this parameter in distributed SQL statements. SID SID returns the session ID. TERMINAL TERMINAL returns the operating system identifier for the terminal of the current session. In distributed SQL statements, this parameter returns the identifier for your local session. In a distributed environment, this parameter is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations. VALUE ( correlation_variable )
  • 418. VAR_POP 5-244 Oracle Database SQL Language Reference Purpose VALUE takes as its argument a correlation variable (table alias) associated with a row of an object table and returns object instances stored in the object table. The type of the object instances is the same type as the object table. Examples The following example uses the sample table oe.persons, which is created in "Substitutable Table and Column Examples" on page 16-69: SELECT VALUE(p) FROM persons p; VALUE(P)(NAME, SSN) ------------------------------------------------------------- PERSON_T('Bob', 1234) EMPLOYEE_T('Joe', 32456, 12, 100000) PART_TIME_EMP_T('Tim', 5678, 13, 1000, 20) VAR_POP Syntax Purpose VAR_POP returns the population variance of a set of numbers after discarding the nulls in this set. You can use it as both an aggregate and analytic function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. If the function is applied to an empty set, then it returns null. The function makes the following calculation: (SUM(expr2 ) - SUM(expr)2 / COUNT(expr)) / COUNT(expr) Aggregate Example The following example returns the population variance of the salaries in the employees table: SELECT VAR_POP(salary) FROM employees; See Also: "IS OF type Condition" on page 7-24 for information on using IS OF type conditions with the VALUE function See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 VAR_POP ( expr ) OVER ( analytic_clause )
  • 419. VAR_SAMP Functions 5-245 VAR_POP(SALARY) --------------- 15140307.5 Analytic Example The following example calculates the cumulative population and sample variances in the sh.sales table of the monthly sales in 1998: SELECT t.calendar_month_desc, VAR_POP(SUM(s.amount_sold)) OVER (ORDER BY t.calendar_month_desc) "Var_Pop", VAR_SAMP(SUM(s.amount_sold)) OVER (ORDER BY t.calendar_month_desc) "Var_Samp" FROM sales s, times t WHERE s.time_id = t.time_id AND t.calendar_year = 1998 GROUP BY t.calendar_month_desc ORDER BY t.calendar_month_desc, "Var_Pop", "Var_Samp"; CALENDAR Var_Pop Var_Samp -------- ---------- ---------- 1998-01 0 1998-02 2269111326 4538222653 1998-03 5.5849E+10 8.3774E+10 1998-04 4.8252E+10 6.4336E+10 1998-05 6.0020E+10 7.5025E+10 1998-06 5.4091E+10 6.4909E+10 1998-07 4.7150E+10 5.5009E+10 1998-08 4.1345E+10 4.7252E+10 1998-09 3.9591E+10 4.4540E+10 1998-10 3.9995E+10 4.4439E+10 1998-11 3.6870E+10 4.0558E+10 1998-12 4.0216E+10 4.3872E+10 VAR_SAMP Syntax Purpose VAR_SAMP returns the sample variance of a set of numbers after discarding the nulls in this set. You can use it as both an aggregate and analytic function. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. If the function is applied to an empty set, then it returns null. The function makes the following calculation: See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion VAR_SAMP ( expr ) OVER ( analytic_clause )
  • 420. VARIANCE 5-246 Oracle Database SQL Language Reference (SUM(expr2 ) - SUM(expr)2 / COUNT(expr)) / (COUNT(expr) - 1) This function is similar to VARIANCE, except that given an input set of one element, VARIANCE returns 0 and VAR_SAMP returns null. Aggregate Example The following example returns the sample variance of the salaries in the sample employees table. SELECT VAR_SAMP(salary) FROM employees; VAR_SAMP(SALARY) ---------------- 15283140.5 Analytic Example Refer to the analytic example for VAR_POP on page 5-244. VARIANCE Syntax Purpose VARIANCE returns the variance of expr. You can use it as an aggregate or analytic function. Oracle Database calculates the variance of expr as follows: ■ 0 if the number of rows in expr = 1 ■ VAR_SAMP if the number of rows in expr > 1 If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed. This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. The function returns the same data type as the numeric data type of the argument. See Also: "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 See Also: "Analytic Functions" on page 5-11 for information on syntax, semantics, and restrictions See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion, "About SQL Expressions" on page 6-1 for information on valid forms of expr and "Aggregate Functions" on page 5-9 VARIANCE ( DISTINCT ALL expr ) OVER ( analytic_clause )
  • 421. VSIZE Functions 5-247 Aggregate Example The following example calculates the variance of all salaries in the sample employees table: SELECT VARIANCE(salary) "Variance" FROM employees; Variance ---------- 15283140.5 Analytic Example The following example returns the cumulative variance of salary values in Department 30 ordered by hire date. SELECT last_name, salary, VARIANCE(salary) OVER (ORDER BY hire_date) "Variance" FROM employees WHERE department_id = 30 ORDER BY last_name, salary, "Variance"; LAST_NAME SALARY Variance ------------------------- ---------- ---------- Baida 2900 16283333.3 Colmenares 2500 11307000 Himuro 2600 13317000 Khoo 3100 31205000 Raphaely 11000 0 Tobias 2800 21623333.3 VSIZE Syntax Purpose VSIZE returns the number of bytes in the internal representation of expr. If expr is null, then this function returns null. This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through implicit data conversion. Examples The following example returns the number of bytes in the last_name column of the employees in department 10: SELECT last_name, VSIZE (last_name) "BYTES" FROM employees WHERE department_id = 10 ORDER BY employee_id; LAST_NAME BYTES --------------- ---------- See Also: "Data Type Comparison Rules" on page 3-37 for more information VSIZE ( expr )
  • 422. WIDTH_BUCKET 5-248 Oracle Database SQL Language Reference Whalen 6 WIDTH_BUCKET Syntax Purpose WIDTH_BUCKET lets you construct equiwidth histograms, in which the histogram range is divided into intervals that have identical size. (Compare this function with NTILE, which creates equiheight histograms.) Ideally each bucket is a closed-open interval of the real number line. For example, a bucket can be assigned to scores between 10.00 and 19.999 ... to indicate that 10 is included in the interval and 20 is excluded. This is sometimes denoted [10, 20). For a given expression, WIDTH_BUCKET returns the bucket number into which the value of this expression would fall after being evaluated. ■ expr is the expression for which the histogram is being created. This expression must evaluate to a numeric or datetime value or to a value that can be implicitly converted to a numeric or datetime value. If expr evaluates to null, then the expression returns null. ■ min_value and max_value are expressions that resolve to the end points of the acceptable range for expr. Both of these expressions must also evaluate to numeric or datetime values, and neither can evaluate to null. ■ num_buckets is an expression that resolves to a constant indicating the number of buckets. This expression must evaluate to a positive integer. When needed, Oracle Database creates an underflow bucket numbered 0 and an overflow bucket numbered num_buckets+1. These buckets handle values less than min_value and more than max_value and are helpful in checking the reasonableness of endpoints. Examples The following example creates a ten-bucket histogram on the credit_limit column for customers in Switzerland in the sample table oe.customers and returns the bucket number ("Credit Group") for each customer. Customers with credit limits greater than the maximum value are assigned to the overflow bucket, 11: SELECT customer_id, cust_last_name, credit_limit, WIDTH_BUCKET(credit_limit, 100, 5000, 10) "Credit Group" FROM customers WHERE nls_territory = 'SWITZERLAND' ORDER BY "Credit Group", customer_id, cust_last_name, credit_limit; CUSTOMER_ID CUST_LAST_NAME CREDIT_LIMIT Credit Group ----------- -------------------- ------------ ------------ 825 Dreyfuss 500 1 826 Barkin 500 1 827 Siegel 500 1 853 Palin 400 1 843 Oates 700 2 See Also: Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion WIDTH_BUCKET ( expr , min_value , max_value , num_buckets )
  • 423. XMLAGG Functions 5-249 844 Julius 700 2 835 Eastwood 1200 3 836 Berenger 1200 3 837 Stanton 1200 3 840 Elliott 1400 3 841 Boyer 1400 3 842 Stern 1400 3 848 Olmos 1800 4 849 Kaurusmdki 1800 4 828 Minnelli 2300 5 829 Hunter 2300 5 850 Finney 2300 5 851 Brown 2300 5 852 Tanner 2300 5 830 Dutt 3500 7 831 Bel Geddes 3500 7 832 Spacek 3500 7 833 Moranis 3500 7 834 Idle 3500 7 838 Nicholson 3500 7 839 Johnson 3500 7 845 Fawcett 5000 11 846 Brando 5000 11 847 Streep 5000 11 XMLAGG Syntax Purpose XMLAgg is an aggregate function. It takes a collection of XML fragments and returns an aggregated XML document. Any arguments that return null are dropped from the result. XMLAgg is similar to SYS_XMLAgg except that XMLAgg returns a collection of nodes but it does not accept formatting using the XMLFormat object. Also, XMLAgg does not enclose the output in an element tag as does SYS_XMLAgg. Within the order_by_clause, Oracle Database does not interpret number literals as column positions, as it does in other uses of this clause, but simply as number literals. Examples The following example produces a Department element containing Employee elements with employee job ID and last name as the contents of the elements: SELECT XMLELEMENT("Department", XMLAGG(XMLELEMENT("Employee", e.job_id||' '||e.last_name) ORDER BY last_name)) as "Dept_list" FROM employees e WHERE e.department_id = 30; See Also: XMLELEMENT on page 5-255 and SYS_XMLAGG on page 5-211 XMLAGG ( XMLType_instance order_by_clause )
  • 424. XMLCAST 5-250 Oracle Database SQL Language Reference Dept_list ------------------------------------------------------------- <Department> <Employee>PU_CLERK Baida</Employee> <Employee>PU_CLERK Colmenares</Employee> <Employee>PU_CLERK Himuro</Employee> <Employee>PU_CLERK Khoo</Employee> <Employee>PU_MAN Raphaely</Employee> <Employee>PU_CLERK Tobias</Employee> </Department> The result is a single row, because XMLAgg aggregates the rows. You can use the GROUP BY clause to group the returned set of rows into multiple groups: SELECT XMLELEMENT("Department", XMLAGG(XMLELEMENT("Employee", e.job_id||' '||e.last_name))) AS "Dept_list" FROM employees e GROUP BY e.department_id; Dept_list --------------------------------------------------------- <Department> <Employee>AD_ASST Whalen</Employee> </Department> <Department> <Employee>MK_MAN Hartstein</Employee> <Employee>MK_REP Fay</Employee> </Department> <Department> <Employee>PU_MAN Raphaely</Employee> <Employee>PU_CLERK Khoo</Employee> <Employee>PU_CLERK Tobias</Employee> <Employee>PU_CLERK Baida</Employee> <Employee>PU_CLERK Colmenares</Employee> <Employee>PU_CLERK Himuro</Employee> </Department> . . . XMLCAST Syntax Purpose XMLCast casts value_expression to the scalar SQL data type specified by data type. The value_expression argument is a SQL expression that is evaluated. The data type argument can be of data type NUMBER, VARCHAR2, and any of the datetime data types. See Also: Oracle XML DB Developer's Guide for more information on uses for this function and examples XMLCAST ( value_expression AS datatype )
  • 425. XMLCDATA Functions 5-251 XMLCDATA Syntax Purpose XMLCData generates a CDATA section by evaluating value_expr. The value_expr must resolve to a string. The value returned by the function takes the following form: <![CDATA[string]]> If the resulting value is not a valid XML CDATA section, then the function returns an error. The following conditions apply to XMLCData: ■ The value_expr cannot contain the substring ]]>. ■ If value_expr evaluates to null, then the function returns null. Examples The following statement uses the DUAL table to illustrate the syntax of XMLCData: SELECT XMLELEMENT("PurchaseOrder", XMLAttributes(dummy as "pono"), XMLCdata('<!DOCTYPE po_dom_group [ <!ELEMENT po_dom_group(student_name)*> <!ELEMENT po_purch_name (#PCDATA)> <!ATTLIST po_name po_no ID #REQUIRED> <!ATTLIST po_name trust_1 IDREF #IMPLIED> <!ATTLIST po_name trust_2 IDREF #IMPLIED> ]>')) "XMLCData" FROM DUAL; XMLCData ---------------------------------------------------------- <PurchaseOrder pono="X"><![CDATA[ <!DOCTYPE po_dom_group [ <!ELEMENT po_dom_group(student_name)*> <!ELEMENT po_purch_name (#PCDATA)> <!ATTLIST po_name po_no ID #REQUIRED> <!ATTLIST po_name trust_1 IDREF #IMPLIED> <!ATTLIST po_name trust_2 IDREF #IMPLIED> ]> ]]> </PurchaseOrder> See Also: Oracle XML DB Developer's Guide for more information on this function XMLCDATA ( value_expr )
  • 426. XMLCOLATTVAL 5-252 Oracle Database SQL Language Reference XMLCOLATTVAL Syntax Purpose XMLColAttVal creates an XML fragment and then expands the resulting XML so that each XML fragment has the name column with the attribute name. You can use the AS clause to change the value of the name attribute to something other than the column name. You can do this by specifying c_alias, which is a string literal, or by specifying EVALNAME value_expr. In the latter case, the value expression is evaluated and the result, which must be a string literal, is used as the alias. The alias can be up to 4000 characters. You must specify a value for value_expr. If value_expr is null, then no element is returned. Restriction on XMLColAttVal You cannot specify an object type column for value_ expr. Examples The following example creates an Emp element for a subset of employees, with nested employee_id, last_name, and salary elements as the contents of Emp. Each nested element is named column and has a name attribute with the column name as the attribute value: SELECT XMLELEMENT("Emp", XMLCOLATTVAL(e.employee_id, e.last_name, e.salary)) "Emp Element" FROM employees e WHERE employee_id = 204; Emp Element -------------------------------------------------------------------- <Emp> <column name="EMPLOYEE_ID">204</column> <column name="LAST_NAME">Baer</column> <column name="SALARY">10000</column> </Emp> Refer to the example for XMLFOREST on page 5-258 to compare the output of these two functions. XMLCOMMENT Syntax XMLCOLATTVAL ( value_expr AS c_alias EVALNAME value_expr , ) XMLCOMMENT ( value_expr )
  • 427. XMLCONCAT Functions 5-253 Purpose XMLComment generates an XML comment using an evaluated result of value_expr. The value_expr must resolve to a string. It cannot contain two consecutive dashes (hyphens). The value returned by the function takes the following form: <!--string--> If value_expr resolves to null, then the function returns null. Examples The following example uses the DUAL table to illustrate the XMLComment syntax: SELECT XMLCOMMENT('OrderAnalysisComp imported, reconfigured, disassembled') AS "XMLCOMMENT" FROM DUAL; XMLCOMMENT -------------------------------------------------------------------------------- <!--OrderAnalysisComp imported, reconfigured, disassembled--> XMLCONCAT Syntax Purpose XMLConcat takes as input a series of XMLType instances, concatenates the series of elements for each row, and returns the concatenated series. XMLConcat is the inverse of XMLSequence. Null expressions are dropped from the result. If all the value expressions are null, then the function returns null. Examples The following example creates XML elements for the first and last names of a subset of employees, and then concatenates and returns those elements: SELECT XMLCONCAT(XMLELEMENT("First", e.first_name), XMLELEMENT("Last", e.last_name)) AS "Result" FROM employees e WHERE e.employee_id > 202; Result ---------------------------------------------------------------- <First>Susan</First> <Last>Mavris</Last> <First>Hermann</First> <Last>Baer</Last> See Also: Oracle XML DB Developer's Guide for more information on this function See Also: XMLSEQUENCE on page 5-264 XMLCONCAT ( XMLType_instance , )
  • 428. XMLDIFF 5-254 Oracle Database SQL Language Reference <First>Shelley</First> <Last>Higgins</Last> <First>William</First> <Last>Gietz</Last> 4 rows selected. XMLDIFF Syntax Purpose The XMLDiff function is the SQL interface for the XmlDiff C API. This function compares two XML documents and captures the differences in XML conforming to an Xdiff schema. The diff document is returned as an XMLType document. ■ For the first two arguments, specify the names of two XMLType documents. ■ For the integer, specify a number representing the hashLevel for a C function XmlDiff. If you do not want hashing, set this argument to 0 or omit it entirely. If you do not want hashing, but you want to specify flags, then you must set this argument to 0. ■ For string, specify the flags that control the behavior of the function. These flags are specified by one or more names separated by semicolon. The names are the same as the names of constants for XmlDiff function. Examples The following example compares two XML documents and returns the difference as an XMLType document: SELECT XMLDIFF( XMLTYPE('<?xml version="1.0"?> <bk:book xmlns:bk="http://example.com"> <bk:tr> <bk:td> <bk:chapter> Chapter 1. </bk:chapter> </bk:td> <bk:td> <bk:chapter> Chapter 2. </bk:chapter> </bk:td> </bk:tr> </bk:book>'), See Also: Oracle XML Developer's Kit Programmer's Guide for more information on using this function, including examples, and Oracle Database XML C API Reference for information on the XML APIs for C XMLDiff ( XMLType_document , XMLType_document , integer , string )
  • 429. XMLELEMENT Functions 5-255 XMLTYPE('<?xml version="1.0"?> <bk:book xmlns:bk="http://example.com"> <bk:tr> <bk:td> <bk:chapter> Chapter 1. </bk:chapter> </bk:td> <bk:td/> </bk:tr> </bk:book>') ) FROM DUAL; XMLELEMENT Syntax XML_attributes_clause::= Purpose XMLElement takes an element name for identifier or evaluates an element name for EVALNAME value_expr, an optional collection of attributes for the element, and arguments that make up the content of the element. It returns an instance of type XMLType. XMLElement is similar to SYS_XMLGen except that XMLElement can include attributes in the XML returned, but it does not accept formatting using the XMLFormat object. The XMLElement function is typically nested to produce an XML document with a nested structure, as in the example in the following section. XMLELEMENT ( ENTITYESCAPING NOENTITYESCAPING NAME identifier EVALNAME value_expr , XML_attributes_clause , value_expr AS c_alias ) XMLATTRIBUTES ( ENTITYESCAPING NOENTITYESCAPING SCHEMACHECK NOSCHEMACHECK value_expr AS c_alias EVALNAME value_expr , )
  • 430. XMLELEMENT 5-256 Oracle Database SQL Language Reference For an explanation of the ENTITYESCAPING and NONENTITYESCAPING keywords, please refer to Oracle XML DB Developer's Guide. You must specify a value for Oracle Database to use an the enclosing tag. You can do this by specifying identifier, which is a string literal, or by specifying EVALNAME value_expr. In the latter case, the value expression is evaluated and the result, which must be a string literal, is used as the identifier. The identifier can be up to 4000 characters and does not have to be a column name or column reference. It cannot be an expression or null. The objects that make up the element content follow the XMLATTRIBUTES keyword. In the XML_attributes_clause, if the value_expr is null, then no attribute is created for that value expression. The type of value_expr cannot be an object type or collection. If you specify an alias for value_expr using the AS clause, then the c_ alias or the evaluated value expression (EVALNAME value_expr) can be up to 4000 characters. For the optional value_expr that follows the XML_attributes_clause in the diagram: ■ If value_expr is a scalar expression, then you can omit the AS clause, and Oracle uses the column name as the element name. ■ If value_expr is an object type or collection, then the AS clause is mandatory, and Oracle uses the specified c_alias as the enclosing tag. ■ If value_expr is null, then no element is created for that value expression. Examples The following example produces an Emp element for a series of employees, with nested elements that provide the employee's name and hire date: SELECT XMLELEMENT("Emp", XMLELEMENT("Name", e.job_id||' '||e.last_name), XMLELEMENT("Hiredate", e.hire_date)) as "Result" FROM employees e WHERE employee_id > 200; Result ------------------------------------------------------------------- <Emp> <Name>MK_MAN Hartstein</Name> <Hiredate>2004-02-17</Hiredate> </Emp> <Emp> <Name>MK_REP Fay</Name> <Hiredate>2005-08-17</Hiredate> </Emp> <Emp> <Name>HR_REP Mavris</Name> <Hiredate>2002-06-07</Hiredate> </Emp> <Emp> <Name>PR_REP Baer</Name> <Hiredate>2002-06-07</Hiredate> </Emp> See Also: SYS_XMLGEN on page 5-211
  • 431. XMLEXISTS Functions 5-257 <Emp> <Name>AC_MGR Higgins</Name> <Hiredate>2002-06-07</Hiredate> </Emp> <Emp> <Name>AC_ACCOUNT Gietz</Name> <Hiredate>2002-06-07</Hiredate> </Emp> 6 rows selected. The following similar example uses the XMLElement function with the XML_ attributes_clause to create nested XML elements with attribute values for the top-level element: SELECT XMLELEMENT("Emp", XMLATTRIBUTES(e.employee_id AS "ID", e.last_name), XMLELEMENT("Dept", e.department_id), XMLELEMENT("Salary", e.salary)) AS "Emp Element" FROM employees e WHERE e.employee_id = 206; Emp Element --------------------------------------------------------------- <Emp ID="206" LAST_NAME="Gietz"> <Dept>110</Dept> <Salary>8300</Salary> </Emp> Notice that the AS identifier clause was not specified for the last_name column. As a result, the XML returned uses the column name last_name as the default. Finally, the next example uses a subquery within the XML_attributes_clause to retrieve information from another table into the attributes of an element: SELECT XMLELEMENT("Emp", XMLATTRIBUTES(e.employee_id, e.last_name), XMLELEMENT("Dept", XMLATTRIBUTES(e.department_id, (SELECT d.department_name FROM departments d WHERE d.department_id = e.department_id) as "Dept_name")), XMLELEMENT("salary", e.salary), XMLELEMENT("Hiredate", e.hire_date)) AS "Emp Element" FROM employees e WHERE employee_id = 205; Emp Element ------------------------------------------------------------------- <Emp EMPLOYEE_ID="205" LAST_NAME="Higgins"> <Dept DEPARTMENT_ID="110" Dept_name="Accounting"/> <salary>12008</salary> <Hiredate>2002-06-07</Hiredate> </Emp> XMLEXISTS Syntax XMLEXISTS ( XQuery_string XML_passing_clause )
  • 432. XMLFOREST 5-258 Oracle Database SQL Language Reference XML_passing_clause::= Purpose XMLExists checks whether a given XQuery expression returns a nonempty XQuery sequence. If so, the function returns TRUE; otherwise, it returns FALSE. The argument XQuery_string is a literal string, but it can contain XQuery variables that you bind using the XML_passing_clause. The expr in the XML_passing_clause is an expression returning an XMLType or an instance of a SQL scalar data type that is used as the context for evaluating the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. The result of evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string. XMLFOREST Syntax Purpose XMLForest converts each of its argument parameters to XML, and then returns an XML fragment that is the concatenation of these converted arguments. ■ If value_expr is a scalar expression, then you can omit the AS clause, and Oracle Database uses the column name as the element name. ■ If value_expr is an object type or collection, then the AS clause is mandatory, and Oracle uses the specified expression as the enclosing tag. You can do this by specifying c_alias, which is a string literal, or by specifying EVALNAME value_expr. In the latter case, the value expression is evaluated and the result, which must be a string literal, is used as the identifier. The identifier can be up to 4000 characters and does not have to be a column name or column reference. It cannot be an expression or null. ■ If value_expr is null, then no element is created for that value_expr. Examples The following example creates an Emp element for a subset of employees, with nested employee_id, last_name, and salary elements as the contents of Emp: See Also: Oracle XML DB Developer's Guide for more information on uses for this function and examples PASSING BY VALUE expr AS identifier , XMLFOREST ( value_expr AS c_alias EVALNAME value_expr , )
  • 433. XMLPARSE Functions 5-259 SELECT XMLELEMENT("Emp", XMLFOREST(e.employee_id, e.last_name, e.salary)) "Emp Element" FROM employees e WHERE employee_id = 204; Emp Element ---------------------------------------------------------------- <Emp> <EMPLOYEE_ID>204</EMPLOYEE_ID> <LAST_NAME>Baer</LAST_NAME> <SALARY>10000</SALARY> </Emp> Refer to the example for XMLCOLATTVAL on page 5-252 to compare the output of these two functions. XMLISVALID Syntax Purpose XMLISVALID checks whether the input XMLType_instance conforms to the relevant XML schema. It does not change the validation status recorded for XMLType_ instance. If the input XML document is determined to be valid, then XMLISVALID returns 1; otherwise, it returns 0. If you provide XMLSchema_URL as an argument, then that is used to check conformance. Otherwise, the XML schema specified by the XML document is used to check conformance. ■ XMLType_instance is the XMLType instance to be validated. ■ XMLSchema_URL is the URL of the XML schema against which to check conformance. ■ element is the element of the specified schema against which to check conformance. Use this if you have an XML schema that defines more than one top level element, and you want to check conformance against a specific one of those elements. XMLPARSE Syntax See Also: Oracle XML DB Developer's Guide for information on the use of this function, including examples XMLISVALID ( XMLType_instance , XMLSchema_URL , element ) XMLPARSE ( DOCUMENT CONTENT value_expr WELLFORMED )
  • 434. XMLPATCH 5-260 Oracle Database SQL Language Reference Purpose XMLParse parses and generates an XML instance from the evaluated result of value_ expr. The value_expr must resolve to a string. If value_expr resolves to null, then the function returns null. ■ If you specify DOCUMENT, then value_expr must resolve to a singly rooted XML document. ■ If you specify CONTENT, then value_expr must resolve to a valid XML value. ■ When you specify WELLFORMED, you are guaranteeing that value_expr resolves to a well-formed XML document, so the database does not perform validity checks to ensure that the input is well formed. Examples The following example uses the DUAL table to illustrate the syntax of XMLParse: SELECT XMLPARSE(CONTENT '124 <purchaseOrder poNo="12435"> <customerName> Acme Enterprises</customerName> <itemNo>32987457</itemNo> </purchaseOrder>' WELLFORMED) AS PO FROM DUAL; PO ----------------------------------------------------------------- 124 <purchaseOrder poNo="12435"> <customerName> Acme Enterprises</customerName> <itemNo>32987457</itemNo> </purchaseOrder> XMLPATCH Syntax Purpose The XMLPatch function is the SQL interface for the XmlPatch C API. This function patches an XML document with the changes specified. A patched XMLType document is returned. ■ For the first argument, specify the name of the input XMLType document For the second argument, specify the XMLType document containing the changes to be applied to the first document. The changes should conform to the Xdiff XML schema ■ For string, specify the flags that control the behavior of the function. These flags are specified by one or more names separated by semicolon. The names are the same as the names of constants for XmlPatch C function. See Also: Oracle XML DB Developer's Guide for more information on this function See Also: Oracle XML Developer's Kit Programmer's Guide for more information on using this function, including examples, and Oracle Database XML C API Reference for information on the XML APIs for C XMLPatch ( XMLType_document , XMLType_document )
  • 435. XMLPI Functions 5-261 Example The following example patches an XMLType document with the changes specified in another XMLType and returns a patched XMLType document: SELECT XMLPATCH( XMLTYPE('<?xml version="1.0"?> <bk:book xmlns:bk="http://example.com"> <bk:tr> <bk:td> <bk:chapter> Chapter 1. </bk:chapter> </bk:td> <bk:td> <bk:chapter> Chapter 2. </bk:chapter> </bk:td> </bk:tr> </bk:book>'), XMLTYPE('<?xml version="1.0"?> <xd:xdiff xsi:schemaLocation="http://xmlns.example.com/xdb/xdiff.xsd http://xmlns.example.com/xdb/xdiff.xsd" xmlns:xd="http://xmlns.example.com/xdb/xdiff.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bk="http://example.com"> <?oracle-xmldiff operations-in-docorder="true" output-model="snapshot" diff-algorithm="global"?> <xd:delete-node xd:node-type="element" xd:xpath="/bk:book[1]/bk:tr[1]/bk:td[2]/bk:chapter[1]"/> </xd:xdiff>') ) FROM DUAL; XMLPI Syntax Purpose XMLPI generates an XML processing instruction using identifier and optionally the evaluated result of value_expr. A processing instruction is commonly used to provide to an application information that is associated with all or part of an XML document. The application uses the processing instruction to determine how best to process the XML document. You must specify a value for Oracle Database to use an the enclosing tag. You can do this by specifying identifier, which is a string literal, or by specifying EVALNAME value_expr. In the latter case, the value expression is evaluated and the result, which must be a string literal, is used as the identifier. The identifier can be up to 4000 characters and does not have to be a column name or column reference. It cannot be an expression or null. XMLPI ( NAME identifier EVALNAME value_expr , value_expr )
  • 436. XMLQUERY 5-262 Oracle Database SQL Language Reference The optional value_expr must resolve to a string. If you omit the optional value_ expr, then a zero-length string is the default. The value returned by the function takes this form: <?identifier string?> XMLPI is subject to the following restrictions: ■ The identifier must be a valid target for a processing instruction. ■ You cannot specify xml in any case combination for identifier. ■ The identifier cannot contain the consecutive characters ?>. Examples The following statement uses the DUAL table to illustrate the use of the XMLPI syntax: SELECT XMLPI(NAME "Order analysisComp", 'imported, reconfigured, disassembled') AS "XMLPI" FROM DUAL; XMLPI -------------------------------------------------------------------------------- <?Order analysisComp imported, reconfigured, disassembled?> XMLQUERY Syntax XML_passing_clause::= Purpose XMLQUERY lets you query XML data in SQL statements. It takes an XQuery expression as a string literal, an optional context item, and other bind variables and returns the result of evaluating the XQuery expression using these input values. ■ XQuery_string is a complete XQuery expression, including prolog. ■ The expr in the XML_passing_clause is an expression returning an XMLType or an instance of a SQL scalar data type that is used as the context for evaluating the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. The result of evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string. See Also: Oracle XML DB Developer's Guide for more information on this function XMLQUERY ( XQuery_string XML_passing_clause RETURNING CONTENT NULL ON EMPTY ) PASSING BY VALUE expr AS identifier ,
  • 437. XMLROOT Functions 5-263 ■ RETURNING CONTENT indicates that the result from the XQuery evaluation is either an XML 1.0 document or a document fragment conforming to the XML 1.0 semantics. ■ If the result set is empty, then the function returns the SQL NULL value. The NULL ON EMPTY keywords are implemented by default and are shown for syntactic clarity. Examples The following statement specifies the warehouse_spec column of the oe.warehouses table in the XML_passing_clause as a context item. The statement returns specific information about the warehouses with area greater than 50K. SELECT warehouse_name, EXTRACTVALUE(warehouse_spec, '/Warehouse/Area'), XMLQuery( 'for $i in /Warehouse where $i/Area > 50000 return <Details> <Docks num="{$i/Docks}"/> <Rail> { if ($i/RailAccess = "Y") then "true" else "false" } </Rail> </Details>' PASSING warehouse_spec RETURNING CONTENT) "Big_warehouses" FROM warehouses; WAREHOUSE_ID Area Big_warehouses ------------ --------- -------------------------------------------------------- 1 25000 2 50000 3 85700 <Details><Docks></Docks><Rail>false</Rail></Details> 4 103000 <Details><Docks num="3"></Docks><Rail>true</Rail></Details> . . . XMLROOT Syntax Purpose XMLROOT lets you create a new XML value by providing version and standalone properties in the XML root information (prolog) of an existing XML value. If the value_expr already has a prolog, then the database returns an error. If the input is null, then the function returns null. The value returned takes the following form: See Also: Oracle XML DB Developer's Guide for more information on this function XMLROOT ( value_expr , VERSION value_expr NO VALUE , STANDALONE YES NO NO VALUE )
  • 438. XMLSEQUENCE 5-264 Oracle Database SQL Language Reference <?xml version = "version" [ STANDALONE = "{yes | no}" ]?> ■ The first value_expr specifies the XML value for which you are providing prolog information. ■ In the VERSION clause, value_expr must resolve to a string representing a valid XML version. If you specify NO VALUE for VERSION, then the version defaults to 1.0. ■ If you omit the optional STANDALONE clause, or if you specify it with NO VALUE, then the standalone property is absent from the value returned by the function. Examples The following statement uses the DUAL table to illustrate the syntax of XMLROOT: SELECT XMLROOT ( XMLType('<poid>143598</poid>'), VERSION '1.0', STANDALONE YES) AS "XMLROOT" FROM DUAL; XMLROOT -------------------------------------------------------------------------------- <?xml version="1.0" standalone="yes"?> <poid>143598</poid> XMLSEQUENCE Syntax Purpose XMLSequence has two forms: ■ The first form takes as input an XMLType instance and returns a varray of the top-level nodes in the XMLType. This form is effectively superseded by the SQL/XML standard function XMLTable, which provides for more readable SQL code. Prior to Oracle Database 10g Release 2, XMLSequence was used with SQL function TABLE to do some of what can now be done better with the XMLTable function. ■ The second form takes as input a REFCURSOR instance, with an optional instance of the XMLFormat object, and returns as an XMLSequence type an XML document for each row of the cursor. Because XMLSequence returns a collection of XMLType, you can use this function in a TABLE clause to unnest the collection values into multiple rows, which can in turn be further processed in the SQL query. Note: The XMLSEQUENCE function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLTABLE function instead. See XMLTABLE on page 5-267 for more information. XMLSEQUENCE ( XMLType_instance sys_refcursor_instance , fmt )
  • 439. XMLSEQUENCE Functions 5-265 Examples The following example shows how XMLSequence divides up an XML document with multiple elements into VARRAY single-element documents. In this example, the TABLE keyword instructs Oracle Database to consider the collection a table value that can be used in the FROM clause of the subquery: SELECT EXTRACT(warehouse_spec, '/Warehouse') as "Warehouse" FROM warehouses WHERE warehouse_name = 'San Francisco'; Warehouse ------------------------------------------------------------ <Warehouse> <Building>Rented</Building> <Area>50000</Area> <Docks>1</Docks> <DockType>Side load</DockType> <WaterAccess>Y</WaterAccess> <RailAccess>N</RailAccess> <Parking>Lot</Parking> <VClearance>12 ft</VClearance> </Warehouse> 1 row selected. SELECT VALUE(p) FROM warehouses w, TABLE(XMLSEQUENCE(EXTRACT(warehouse_spec, '/Warehouse/*'))) p WHERE w.warehouse_name = 'San Francisco'; VALUE(P) ---------------------------------------------------------------- <Building>Rented</Building> <Area>50000</Area> <Docks>1</Docks> <DockType>Side load</DockType> <WaterAccess>Y</WaterAccess> <RailAccess>N</RailAccess> <Parking>Lot</Parking> <VClearance>12 ft</VClearance> 8 rows selected. See Also: Oracle XML DB Developer's Guide for more information on this function, and XMLTABLE on page 5-267
  • 440. XMLSERIALIZE 5-266 Oracle Database SQL Language Reference XMLSERIALIZE Syntax Purpose XMLSerialize creates a string or LOB containing the contents of value_expr. ■ If you specify DOCUMENT, then the value_expr must be a valid XML document. ■ If you specify CONTENT, then the value_expr need not be a singly rooted XML document. However it must be valid XML content. ■ The datatype specified can be a string type (VARCHAR2 or VARCHAR, but not NVARCHAR or NVARCHAR2), BLOB, or CLOB . The default is CLOB. ■ If datatype is BLOB, then you can specify the ENCODING clause to use the specified encoding in the prolog. ■ Specify the VERSION clause to use the version you provide as string_literal in the XML declaration (<?xml version="..." ...?>). ■ Specify NO INDENT to strip all insignificant whitespace from the output. Specify INDENT SIZE = N, where N is a whole number, for output that is pretty-printed using a relative indentation of N spaces. If N is 0, then pretty-printing inserts a newline character after each element, placing each element on a line by itself, but omitting all other insignificant whitespace in the output. If INDENT is present without a SIZE specification, then 2-space indenting is used. If you omit this clause, then the behavior (pretty-printing or not) is indeterminate. ■ HIDE DEFAULTS and SHOW DEFAULTS apply only to XML schema-based data. If you specify SHOW DEFAULTS and the input data is missing any optional elements or attributes for which the XML schema defines default values, then those elements or attributes are included in the output with their default values. If you specify HIDE DEFAULTS, then no such elements or attributes are included in the output. HIDE DEFAULTS is the default behavior. Examples The following statement uses the DUAL table to illustrate the syntax of XMLSerialize: SELECT XMLSERIALIZE(CONTENT XMLTYPE('<Owner>Grandco</Owner>')) See Also: Oracle XML DB Developer's Guide for more information on this function XMLSERIALIZE ( DOCUMENT CONTENT value_expr AS datatype ENCODING xml_encoding_spec VERSION string_literal NO INDENT INDENT SIZE = number HIDE SHOW DEFAULTS )
  • 441. XMLTABLE Functions 5-267 FROM DUAL; XMLTABLE Syntax XMLnamespaces_clause::= XMLTABLE_options::= XML_passing_clause::= XML_table_column::= Purpose XMLTable maps the result of an XQuery evaluation into relational rows and columns. You can query the result returned by the function as a virtual relational table using SQL. ■ The XMLNAMESPACES clause contains a set of XML namespace declarations. These declarations are referenced by the XQuery expression (the evaluated XQuery_ string), which computes the row, and by the XPath expression in the PATH clause of XML_table_column, which computes the columns for the entire XMLTable function. If you want to use qualified names in the PATH expressions of the COLUMNS clause, then you need to specify the XMLNAMESPACES clause. ■ XQuery_string is a complete XQuery expression and can include prolog declarations. ■ The expr in the XML_passing_clause is an expression returning an XMLType or an instance of a SQL scalar data type that is used as the context for evaluating the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. The result of evaluating each expr is bound to the XMLTABLE ( XMLnamespaces_clause XQuery_string XMLTABLE_options ) XMLNAMESPACES ( string AS identifier , DEFAULT string ) XML_passing_clause COLUMNS XML_table_column , PASSING BY VALUE expr AS identifier , column FOR ORDINALITY datatype PATH string DEFAULT expr
  • 442. XMLTABLE 5-268 Oracle Database SQL Language Reference corresponding identifier in the XQuery_string. If any expr that is not followed by an AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string. ■ The optional COLUMNS clause defines the columns of the virtual table to be created by XMLTable. – If you omit the COLUMNS clause, then XMLTable returns a row with a single XMLType pseudocolumn named COLUMN_VALUE. – The datatype is required unless XMLTable is used with XML schema-based storage of XMLType, datatype. In this case, if you omit datatype, Oracle XML DB infers the data type from the XML schema. If the database is unable to determine the proper type for a node, then a default type of VARCHAR2(4000) is used. – FOR ORDINALITY specifies that column is to be a column of generated row numbers. There must be at most one FOR ORDINALITY clause. It is created as a NUMBER column. – The optional PATH clause specifies that the portion of the XQuery result that is addressed by XQuery expression string is to be used as the column content. If you omit PATH, then the XQuery expression column is assumed. For example: XMLTable(... COLUMNS xyz is equivalent to XMLTable(... COLUMNS xyz PATH 'XYZ') You can use different PATH clauses to split the XQuery result into different virtual-table columns. – The optional DEFAULT clause specifies the value to use when the PATH expression results in an empty sequence. Its expr is an XQuery expression that is evaluated to produce the default value. Examples The following example converts the result of applying the XQuery '/Warehouse' to each value in the warehouse_spec column of the warehouses table into a virtual relational table with columns Water and Rail: SELECT warehouse_name warehouse, warehouse2."Water", warehouse2."Rail" FROM warehouses, XMLTABLE('/Warehouse' PASSING warehouses.warehouse_spec COLUMNS "Water" varchar2(6) PATH '/Warehouse/WaterAccess', "Rail" varchar2(6) PATH '/Warehouse/RailAccess') warehouse2; WAREHOUSE Water Rail ----------------------------------- ------ ------ Southlake, Texas Y N San Francisco Y N New Jersey N N See Also: Oracle XML DB Developer's Guide for more information on the XMLTable function, including additional examples, and on XQuery in general
  • 443. XMLTRANSFORM Functions 5-269 Seattle, Washington N Y XMLTRANSFORM Syntax Purpose XMLTransform takes as arguments an XMLType instance and an XSL style sheet, which is itself a form of XMLType instance. It applies the style sheet to the instance and returns an XMLType. This function is useful for organizing data according to a style sheet as you are retrieving it from the database. Examples The XMLTransform function requires the existence of an XSL style sheet. Here is an example of a very simple style sheet that alphabetizes elements within a node: CREATE TABLE xsl_tab (col1 XMLTYPE); INSERT INTO xsl_tab VALUES ( XMLTYPE.createxml( '<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output encoding="utf-8"/> <!-- alphabetizes an xml tree --> <xsl:template match="*"> <xsl:copy> <xsl:apply-templates select="*|text()"> <xsl:sort select="name(.)" data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="normalize-space(.)"/> </xsl:template> </xsl:stylesheet> ')); 1 row created. The next example uses the xsl_tab XSL style sheet to alphabetize the elements in one warehouse_spec of the sample table oe.warehouses: SELECT XMLTRANSFORM(w.warehouse_spec, x.col1).GetClobVal() FROM warehouses w, xsl_tab x WHERE w.warehouse_name = 'San Francisco'; XMLTRANSFORM(W.WAREHOUSE_SPEC,X.COL1).GETCLOBVAL() -------------------------------------------------------------------------------- <Warehouse> <Area>50000</Area> See Also: Oracle XML DB Developer's Guide for more information on this function XMLTRANSFORM ( XMLType_instance , XMLType_instance string )
  • 444. ROUND and TRUNC Date Functions 5-270 Oracle Database SQL Language Reference <Building>Rented</Building> <DockType>Side load</DockType> <Docks>1</Docks> <Parking>Lot</Parking> <RailAccess>N</RailAccess> <VClearance>12 ft</VClearance> <WaterAccess>Y</WaterAccess> </Warehouse> ROUND and TRUNC Date Functions Table 5–14 lists the format models you can use with the ROUND and TRUNC date functions and the units to which they round and truncate dates. The default model, 'DD', returns the date rounded or truncated to the day with a time of midnight. Table 5–14 Date Format Models for the ROUND and TRUNC Date Functions Format Model Rounding or Truncating Unit CC SCC One greater than the first two digits of a four-digit year SYYYY YYYY YEAR SYEAR YYY YY Y Year (rounds up on July 1) IYYY IY IY I ISO Year Q Quarter (rounds up on the sixteenth day of the second month of the quarter) MONTH MON MM RM Month (rounds up on the sixteenth day) WW Same day of the week as the first day of the year IW Same day of the week as the first day of the ISO week, which is Monday W Same day of the week as the first day of the month DDD DD J Day DAY DY D Starting day of the week HH HH12 HH24 Hour MI Minute
  • 445. About User-Defined Functions Functions 5-271 The starting day of the week used by the format models DAY, DY, and D is specified implicitly by the initialization parameter NLS_TERRITORY. About User-Defined Functions You can write user-defined functions in PL/SQL, Java, or C to provide functionality that is not available in SQL or SQL built-in functions. User-defined functions can appear in a SQL statement wherever an expression can occur. For example, user-defined functions can be used in the following: ■ The select list of a SELECT statement ■ The condition of a WHERE clause ■ CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses ■ The VALUES clause of an INSERT statement ■ The SET clause of an UPDATE statement user_defined_function::= The optional expression list must match attributes of the function, package, or operator. Restriction on User-defined Functions The DISTINCT and ALL keywords are valid only with a user-defined aggregate function. See Also: Oracle Database Reference and Oracle Database Globalization Support Guide for information on this parameter Note: Oracle SQL does not support calling of functions with Boolean parameters or returns. Therefore, if your user-defined functions will be called from SQL statements, you must design them to return numbers (0 or 1) or character strings ('TRUE' or 'FALSE'). See Also: ■ CREATE FUNCTION on page 14-59 for information on creating functions, including restrictions on user-defined functions ■ Oracle Database Advanced Application Developer's Guide for a complete discussion of the creation and use of user functions schema . package . function user_defined_operator @ dblink . ( DISTINCT ALL expr , )
  • 446. Prerequisites 5-272 Oracle Database SQL Language Reference Prerequisites User-defined functions must be created as top-level functions or declared with a package specification before they can be named within a SQL statement. To use a user function in a SQL expression, you must own or have EXECUTE privilege on the user function. To query a view defined with a user function, you must have SELECT privileges on the view. No separate EXECUTE privileges are needed to select from the view. Name Precedence Within a SQL statement, the names of database columns take precedence over the names of functions with no parameters. For example, if the Human Resources manager creates the following two objects in the hr schema: CREATE TABLE new_emps (new_sal NUMBER, ...); CREATE FUNCTION new_sal RETURN NUMBER IS BEGIN ... END; then in the following two statements, the reference to new_sal refers to the column new_emps.new_sal: SELECT new_sal FROM new_emps; SELECT new_emps.new_sal FROM new_emps; To access the function new_sal, you would enter: SELECT hr.new_sal FROM new_emps; Here are some sample calls to user functions that are allowed in SQL expressions: circle_area (radius) payroll.tax_rate (empno) hr.employees.tax_rate (dependent, empno)@remote Example To call the tax_rate user function from schema hr, execute it against the ss_no and sal columns in tax_table, specify the following: SELECT hr.tax_rate (ss_no, sal) INTO income_tax FROM tax_table WHERE ss_no = tax_id; The INTO clause is PL/SQL that lets you place the results into the variable income_ tax. Naming Conventions If only one of the optional schema or package names is given, then the first identifier can be either a schema name or a package name. For example, to determine whether PAYROLL in the reference PAYROLL.TAX_RATE is a schema or package name, Oracle Database proceeds as follows: 1. Check for the PAYROLL package in the current schema. See Also: CREATE FUNCTION on page 14-59 for information on creating top-level functions and CREATE PACKAGE on page 15-41 for information on specifying packaged functions
  • 447. About User-Defined Functions Functions 5-273 2. If a PAYROLL package is not found, then look for a schema name PAYROLL that contains a top-level TAX_RATE function. If no such function is found, then return an error. 3. If the PAYROLL package is found in the current schema, then look for a TAX_RATE function in the PAYROLL package. If no such function is found, then return an error. You can also refer to a stored top-level function using any synonym that you have defined for it.
  • 448. Name Precedence 5-274 Oracle Database SQL Language Reference
  • 449. 6 Expressions 6-1 6 Expressions This chapter describes how to combine values, operators, and functions into expressions. This chapter includes these sections: ■ About SQL Expressions ■ Simple Expressions ■ Compound Expressions ■ CASE Expressions ■ Column Expressions ■ CURSOR Expressions ■ Datetime Expressions ■ Function Expressions ■ Interval Expressions ■ Model Expressions ■ Object Access Expressions ■ Placeholder Expressions ■ Scalar Subquery Expressions ■ Type Constructor Expressions ■ Expression Lists About SQL Expressions An expression is a combination of one or more values, operators, and SQL functions that evaluates to a value. An expression generally assumes the data type of its components.
  • 450. About SQL Expressions 6-2 Oracle Database SQL Language Reference This simple expression evaluates to 4 and has data type NUMBER (the same data type as its components): 2*2 The following expression is an example of a more complex expression that uses both functions and operators. The expression adds seven days to the current date, removes the time component from the sum, and converts the result to CHAR data type: TO_CHAR(TRUNC(SYSDATE+7)) You can use expressions in: ■ The select list of the SELECT statement ■ A condition of the WHERE clause and HAVING clause ■ The CONNECT BY, START WITH, and ORDER BY clauses ■ The VALUES clause of the INSERT statement ■ The SET clause of the UPDATE statement For example, you could use an expression in place of the quoted string 'Smith' in this UPDATE statement SET clause: SET last_name = 'Smith'; This SET clause has the expression INITCAP(last_name) instead of the quoted string 'Smith': SET last_name = INITCAP(last_name); Expressions have several forms, as shown in the following syntax: Note: The combined values of the NLS_COMP and NLS_SORT settings determine the rules by which characters are sorted and compared. If NLS_COMP is set to LINGUISTIC for your database, then all entities in this chapter will be interpreted according to the rules specified by the NLS_SORT parameter. If NLS_COMP is not set to LINGUISTIC, then the functions are interpreted without regard to the NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle Database Globalization Support Guide for more information on these settings.
  • 451. Simple Expressions Expressions 6-3 expr::= Oracle Database does not accept all forms of expressions in all parts of all SQL statements. Refer to the individual SQL statements in Chapter 10 through Chapter 19 for information on restrictions on the expressions in that statement. You must use appropriate expression notation whenever expr appears in conditions, SQL functions, or SQL statements in other parts of this reference. The sections that follow describe and provide examples of the various forms of expressions. Simple Expressions A simple expression specifies a column, pseudocolumn, constant, sequence number, or null. simple_expression::= In addition to the schema of a user, schema can also be "PUBLIC" (double quotation marks required), in which case it must qualify a public synonym for a table, view, or simple_expression compound_expression case_expression cursor_expression datetime_expression function_expression interval_expression object_access_expression scalar_subquery_expression model_expression type_constructor_expression variable_expression query_name schema table view materialized view . column ROWID ROWNUM string number sequence . CURRVAL NEXTVAL NULL
  • 452. Compound Expressions 6-4 Oracle Database SQL Language Reference materialized view. Qualifying a public synonym with "PUBLIC" is supported only in data manipulation language (DML) statements, not data definition language (DDL) statements. You can specify ROWID only with a table, not with a view or materialized view. NCHAR and NVARCHAR2 are not valid pseudocolumn data types. Some valid simple expressions are: employees.last_name 'this is a text string' 10 N'this is an NCHAR string' Compound Expressions A compound expression specifies a combination of other expressions. compound_expression::= You can use any built-in function as an expression ("Function Expressions" on page 6-10). However, in a compound expression, some combinations of functions are inappropriate and are rejected. For example, the LENGTH function is inappropriate within an aggregate function. The PRIOR operator is used in CONNECT BY clauses of hierarchical queries. Some valid compound expressions are: ('CLARK' || 'SMITH') LENGTH('MOOSE') * 57 SQRT(144) + 72 my_fun(TO_CHAR(sysdate,'DD-MMM-YY')) See Also: Chapter 2, "Pseudocolumns" for more information on pseudocolumns and subquery_factoring_clause on page 19-13 for information on query_name See Also: "Operator Precedence" on page 4-2 and "Hierarchical Queries" on page 9-3 ( expr ) + – PRIOR expr expr * / + – | | expr
  • 453. CASE Expressions Expressions 6-5 CASE Expressions CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to invoke procedures. The syntax is: simple_case_expression::= searched_case_expression::= else_clause::= In a simple CASE expression, Oracle Database searches for the first WHEN ... THEN pair for which expr is equal to comparison_expr and returns return_expr. If none of the WHEN ... THEN pairs meet this condition, and an ELSE clause exists, then Oracle returns else_expr. Otherwise, Oracle returns null. You cannot specify the literal NULL for every return_expr and the else_expr. In a searched CASE expression, Oracle searches from left to right until it finds an occurrence of condition that is true, and then returns return_expr. If no condition is found to be true, and an ELSE clause exists, then Oracle returns else_ expr. Otherwise, Oracle returns null. Oracle Database uses short-circuit evaluation. For a simple CASE expression, the database evaluates each comparison_expr value only before comparing it to expr, rather than evaluating all comparison_expr values before comparing any of them with expr. Consequently, Oracle never evaluates a comparison_expr if a previous comparison_expr is equal to expr. For a searched CASE expression, the database evaluates each condition to determine whether it is true, and never evaluates a condition if the previous condition was true. For a simple CASE expression, the expr and all comparison_expr values must either have the same data type (CHAR, VARCHAR2, NCHAR, or NVARCHAR2, NUMBER, BINARY_FLOAT, or BINARY_DOUBLE) or must all have a numeric data type. If all expressions have a numeric data type, then Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. For both simple and searched CASE expressions, all of the return_exprs must either have the same data type (CHAR, VARCHAR2, NCHAR, or NVARCHAR2, NUMBER, BINARY_ FLOAT, or BINARY_DOUBLE) or must all have a numeric data type. If all return expressions have a numeric data type, then Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type. The maximum number of arguments in a CASE expression is 65535. All expressions count toward this limit, including the initial expression of a simple CASE expression CASE simple_case_expression searched_case_expression else_clause END expr WHEN comparison_expr THEN return_expr WHEN condition THEN return_expr ELSE else_expr
  • 454. Column Expressions 6-6 Oracle Database SQL Language Reference and the optional ELSE expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit, you can nest CASE expressions so that the return_ expr itself is a CASE expression. Simple CASE Example For each customer in the sample oe.customers table, the following statement lists the credit limit as "Low" if it equals $100, "High" if it equals $5000, and "Medium" if it equals anything else. SELECT cust_last_name, CASE credit_limit WHEN 100 THEN 'Low' WHEN 5000 THEN 'High' ELSE 'Medium' END AS credit FROM customers ORDER BY cust_last_name, credit; CUST_LAST_NAME CREDIT -------------------- ------ Adjani Medium Adjani Medium Alexander Medium Alexander Medium Altman High Altman Medium . . . Searched CASE Example The following statement finds the average salary of the employees in the sample table oe.employees, using $2000 as the lowest salary possible: SELECT AVG(CASE WHEN e.salary > 2000 THEN e.salary ELSE 2000 END) "Average Salary" FROM employees e; Average Salary -------------- 6461.68224 Column Expressions A column expression, which is designated as column_expression in subsequent syntax diagrams, is a limited form of expr. A column expression can be a simple expression, compound expression, function expression, or expression list, but it can contain only the following forms of expression: ■ Columns of the subject table — the table being created, altered, or indexed ■ Constants (strings or numbers) See Also: ■ Table 3–10, " Implicit Type Conversion Matrix" on page 3-41 for more information on implicit conversion ■ "Numeric Precedence" on page 3-14 for information on numeric precedence ■ COALESCE on page 5-38 and NULLIF on page 5-124 for alternative forms of CASE logic ■ Oracle Database Data Warehousing Guide for examples using various forms of the CASE expression
  • 455. CURSOR Expressions Expressions 6-7 ■ Deterministic functions — either SQL built-in functions or user-defined functions No other expression forms described in this chapter are valid. In addition, compound expressions using the PRIOR keyword are not supported, nor are aggregate functions. You can use a column expression for these purposes: ■ To create a function-based index. ■ To explicitly or implicitly define a virtual column. When you define a virtual column, the defining column_expression must refer only to columns of the subject table that have already been defined, in the current statement or in a prior statement. The combined components of a column expression must be deterministic. That is, the same set of input values must return the same set of output values. CURSOR Expressions A CURSOR expression returns a nested cursor. This form of expression is equivalent to the PL/SQL REF CURSOR and can be passed as a REF CURSOR argument to a function. A nested cursor is implicitly opened when the cursor expression is evaluated. For example, if the cursor expression appears in a select list, a nested cursor will be opened for each row fetched by the query. The nested cursor is closed only when: ■ The nested cursor is explicitly closed by the user ■ The parent cursor is reexecuted ■ The parent cursor is closed ■ The parent cursor is cancelled ■ An error arises during fetch on one of its parent cursors (it is closed as part of the clean-up) Restrictions on CURSOR Expressions The following restrictions apply to CURSOR expressions: ■ If the enclosing statement is not a SELECT statement, then nested cursors can appear only as REF CURSOR arguments of a procedure. ■ If the enclosing statement is a SELECT statement, then nested cursors can also appear in the outermost select list of the query specification or in the outermost select list of another nested cursor. ■ Nested cursors cannot appear in views. ■ You cannot perform BIND and EXECUTE operations on nested cursors. Examples The following example shows the use of a CURSOR expression in the select list of a query: SELECT department_name, CURSOR(SELECT salary, commission_pct FROM employees e See Also: "Simple Expressions" on page 6-3, "Compound Expressions" on page 6-4, "Function Expressions" on page 6-10, and "Expression Lists" on page 6-16 for information on these forms of expr CURSOR ( subquery )
  • 456. Datetime Expressions 6-8 Oracle Database SQL Language Reference WHERE e.department_id = d.department_id) FROM departments d ORDER BY department_name; The next example shows the use of a CURSOR expression as a function argument. The example begins by creating a function in the sample OE schema that can accept the REF CURSOR argument. (The PL/SQL function body is shown in italics.) CREATE FUNCTION f(cur SYS_REFCURSOR, mgr_hiredate DATE) RETURN NUMBER IS emp_hiredate DATE; before number :=0; after number:=0; begin loop fetch cur into emp_hiredate; exit when cur%NOTFOUND; if emp_hiredate > mgr_hiredate then after:=after+1; else before:=before+1; end if; end loop; close cur; if before > after then return 1; else return 0; end if; end; / The function accepts a cursor and a date. The function expects the cursor to be a query returning a set of dates. The following query uses the function to find those managers in the sample employees table, most of whose employees were hired before the manager. SELECT e1.last_name FROM employees e1 WHERE f( CURSOR(SELECT e2.hire_date FROM employees e2 WHERE e1.employee_id = e2.manager_id), e1.hire_date) = 1 ORDER BY last_name; LAST_NAME ------------------------- Cambrault Higgins Hunold Kochhar Mourgos Zlotkey Datetime Expressions A datetime expression yields a value of one of the datetime data types.
  • 457. Datetime Expressions Expressions 6-9 datetime_expression::= The initial expr is any expression, except a scalar subquery expression, that evaluates to a value of data type TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP WITH LOCAL TIME ZONE. The DATE data type is not supported. If this expr is itself a datetime_expression, then it must be enclosed in parentheses. Datetimes and intervals can be combined according to the rules defined in Table 3–5 on page 3-21. The three combinations that yield datetime values are valid in a datetime expression. If you specify AT LOCAL, then Oracle uses the current session time zone. The settings for AT TIME ZONE are interpreted as follows: ■ The string '(+|-)HH:MM' specifies a time zone as an offset from UTC. ■ DBTIMEZONE: Oracle uses the database time zone established (explicitly or by default) during database creation. ■ SESSIONTIMEZONE: Oracle uses the session time zone established by default or in the most recent ALTER SESSION statement. ■ time_zone_name: Oracle returns the datetime_value_expr in the time zone indicated by time_zone_name. For a listing of valid time zone region names, query the V$TIMEZONE_NAMES dynamic performance view. ■ expr: If expr returns a character string with a valid time zone format, then Oracle returns the input in that time zone. Otherwise, Oracle returns an error. Note: Time zone region names are needed by the daylight saving feature. These names are stored in two types of time zone files: one large and one small. One of these files is the default file, depending on your environment and the release of Oracle Database you are using. For more information regarding time zone files and names, see Oracle Database Globalization Support Guide. See Also: ■ Oracle Database Globalization Support Guide for a complete listing of the time zone region names in both files ■ Oracle Database Reference for information on the dynamic performance views expr AT LOCAL TIME ZONE ’ + – hh : mm ’ DBTIMEZONE SESSIONTIMEZONE ’ time_zone_name ’ expr
  • 458. Function Expressions 6-10 Oracle Database SQL Language Reference Example The following example converts the datetime value of one time zone to another time zone: SELECT FROM_TZ(CAST(TO_DATE('1999-12-01 11:00:00', 'YYYY-MM-DD HH:MI:SS') AS TIMESTAMP), 'America/New_York') AT TIME ZONE 'America/Los_Angeles' "West Coast Time" FROM DUAL; West Coast Time ------------------------------------------------ 01-DEC-99 08.00.00.000000 AM AMERICA/LOS_ANGELES Function Expressions You can use any built-in SQL function or user-defined function as an expression. Some valid built-in function expressions are: LENGTH('BLAKE') ROUND(1234.567*43) SYSDATE A user-defined function expression specifies a call to: ■ A function in an Oracle-supplied package (see Oracle Database PL/SQL Packages and Types Reference) ■ A function in a user-defined package or type or in a standalone user-defined function (see "About User-Defined Functions" on page 5-271) ■ A user-defined function or operator (see CREATE OPERATOR on page 15-34, CREATE FUNCTION on page 14-59, and Oracle Database Data Cartridge Developer's Guide) Some valid user-defined function expressions are: circle_area(radius) payroll.tax_rate(empno) hr.employees.comm_pct@remote(dependents, empno) DBMS_LOB.getlength(column_name) my_function(a_column) In a user-defined function being used as an expression, positional, named, and mixed notation are supported. For example, all of the following notations are correct: CALL my_function(arg1 => 3, arg2 => 4) ... CALL my_function(3, 4) ... CALL my_function(3, arg2 => 4) ... Restriction on User-Defined Function Expressions You cannot pass arguments of object type or XMLType to remote functions and procedures. Interval Expressions An interval expression yields a value of INTERVAL YEAR TO MONTH or INTERVAL DAY TO SECOND. See Also: "About SQL Functions" on page 5-2' and "Aggregate Functions" on page 5-9 for information on built-in functions
  • 459. Model Expressions Expressions 6-11 interval_expression::= The expressions expr1 and expr2 can be any expressions that evaluate to values of data type DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP WITH LOCAL TIME ZONE. Datetimes and intervals can be combined according to the rules defined in Table 3–5 on page 3-21. The six combinations that yield interval values are valid in an interval expression. Both leading_field_precision and fractional_second_precision can be any integer from 0 to 9. If you omit the leading_field_precision for either DAY or YEAR, then Oracle Database uses the default value of 2. If you omit the fractional_second_precision for second, then the database uses the default value of 6. If the value returned by a query contains more digits that the default precision, then Oracle Database returns an error. Therefore, it is good practice to specify a precision that you know will be at least as large as any value returned by the query. For example, the following statement subtracts the value of the order_date column in the sample table orders (a datetime value) from the system timestamp (another datetime value) to yield an interval value expression. It is not known how many days ago the oldest order was placed, so the maximum value of 9 for the DAY leading field precision is specified: SELECT (SYSTIMESTAMP - order_date) DAY(9) TO SECOND FROM orders WHERE order_id = 2458; Model Expressions A model expression is used only in the model_clause of a SELECT statement and then only on the right-hand side of a model rule. It yields a value for a cell in a measure column previously defined in the model_clause. For additional information, refer to model_clause on page 19-28. ( expr1 – expr2 ) DAY ( leading_field_precision ) TO SECOND ( fractional_second_precision ) YEAR ( leading_field_precision ) TO MONTH
  • 460. Model Expressions 6-12 Oracle Database SQL Language Reference model_expression::= When you specify a measure column in a model expression, any conditions and expressions you specify must resolve to single values. When you specify an aggregate function in a model expression, the argument to the function is a measure column that has been previously defined in the model_clause. An aggregate function can be used only on the right-hand side of a model rule. Specifying an analytic function on the right-hand side of the model rule lets you express complex calculations directly in the model_clause. The following restrictions apply when using an analytic function in a model expression: ■ Analytic functions can be used only in an UPDATE rule. ■ You cannot specify an analytic function on the right-hand side of the model rule if the left-hand side of the rule contains a FOR loop or an ORDER BY clause. ■ The arguments in the OVER clause of the analytic function cannot contain an aggregate. ■ The arguments before the OVER clause of the analytic function cannot contain a cell reference. When expr is itself a model expression, it is referred to as a nested cell reference. The following restrictions apply to nested cell references: ■ Only one level of nesting is allowed. ■ A nested cell reference must be a single-cell reference. ■ When AUTOMATIC ORDER is specified in the model_rules_clause, a nested cell reference can be used on the left-hand side of a model rule only if the measure used in the nested cell reference is never updated for any cell in the spreadsheet clause. The model expressions shown below are based on the model_clause of the following SELECT statement: SELECT country,prod,year,s FROM sales_view_ref See Also: "The MODEL clause: Examples" on page 19-45 for an example of using an analytic function on the right-hand side of a model rule measure_column [ condition expr , ] aggregate_function [ condition expr , single_column_for_loop , multi_column_for_loop ] analytic_function
  • 461. Object Access Expressions Expressions 6-13 MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s[prod='Mouse Pad', year=2000] = s['Mouse Pad', 1998] + s['Mouse Pad', 1999], s['Standard Mouse', 2001] = s['Standard Mouse', 2000] ) ORDER BY country, prod, year; The following model expression represents a single cell reference using symbolic notation. It represents the sales of the Mouse Pad for the year 2000. s[prod='Mouse Pad',year=2000] The following model expression represents a multiple cell reference using positional notation, using the CV function. It represents the sales of the current value of the dimension column prod for the year 2001. s[CV(prod), 2001] The following model expression represents an aggregate function. It represents the sum of sales of the Mouse Pad for the years between the current value of the dimension column year less two and the current value of the dimension column year less one. SUM(s)['Mouse Pad',year BETWEEN CV()-2 AND CV()-1] Object Access Expressions An object access expression specifies attribute reference and method invocation. object_access_expression::= The column parameter can be an object or REF column. If you specify expr, then it must resolve to an object type. When a type's member function is invoked in the context of a SQL statement, if the SELF argument is null, Oracle returns null and the function is not invoked. Examples The following example creates a table based on the sample oe.order_ item_typ object type, and then shows how you would update and select from the object column attributes. See Also: CV on page 5-56 and model_clause on page 19-28 table_alias . column . object_table_alias . ( expr ) . attribute . . method ( argument , ) method ( argument , )
  • 462. Placeholder Expressions 6-14 Oracle Database SQL Language Reference CREATE TABLE short_orders ( sales_rep VARCHAR2(25), item order_item_typ); UPDATE short_orders s SET sales_rep = 'Unassigned'; SELECT o.item.line_item_id, o.item.quantity FROM short_orders o; Placeholder Expressions A placeholder expression provides a location in a SQL statement for which a third-generation language bind variable will provide a value. You can specify the placeholder expression with an optional indicator variable. This form of expression can appear only in embedded SQL statements or SQL statements processed in an Oracle Call Interface (OCI) program. placeholder_expression::= Some valid placeholder expressions are: :employee_name INDICATOR :employee_name_indicator_var :department_location Scalar Subquery Expressions A scalar subquery expression is a subquery that returns exactly one column value from one row. The value of the scalar subquery expression is the value of the select list item of the subquery. If the subquery returns 0 rows, then the value of the scalar subquery expression is NULL. If the subquery returns more than one row, then Oracle returns an error. You can use a scalar subquery expression in most syntax that calls for an expression (expr). In all cases, a scalar subquery must be enclosed in its own parentheses, even if its syntactic location already positions it within parentheses (for example, when the scalar subquery is used as the argument to a built-in function). Scalar subqueries are not valid expressions in the following places: ■ As default values for columns ■ As hash expressions for clusters ■ In the RETURNING clause of DML statements ■ As the basis of a function-based index ■ In CHECK constraints ■ In GROUP BY clauses ■ In statements that are unrelated to queries, such as CREATE PROFILE Type Constructor Expressions A type constructor expression specifies a call to a constructor method. The argument to the type constructor is any expression. Type constructors can be invoked anywhere functions are invoked. : host_variable INDICATOR : indicator_variable
  • 463. Type Constructor Expressions Expressions 6-15 type_constructor_expression::= The NEW keyword applies to constructors for object types but not for collection types. It instructs Oracle to construct a new object by invoking an appropriate constructor. The use of the NEW keyword is optional, but it is good practice to specify it. If type_name is an object type, then the expressions must be an ordered list, where the first argument is a value whose type matches the first attribute of the object type, the second argument is a value whose type matches the second attribute of the object type, and so on. The total number of arguments to the constructor must match the total number of attributes of the object type. If type_name is a varray or nested table type, then the expression list can contain zero or more arguments. Zero arguments implies construction of an empty collection. Otherwise, each argument corresponds to an element value whose type is the element type of the collection type. Restriction on Type Constructor Invocation In an invocation of a type constructor method, the number of parameters (expr) specified cannot exceed 999, even if the object type has more than 999 attributes. This limitation applies only when the constructor is called from SQL. For calls from PL/SQL, the PL/SQL limitations apply. Expression Example This example uses the cust_address_typ type in the sample oe schema to show the use of an expression in the call to a constructor method (the PL/SQL is shown in italics): CREATE TYPE address_book_t AS TABLE OF cust_address_typ; DECLARE myaddr cust_address_typ := cust_address_typ( '500 Oracle Parkway', 94065, 'Redwood Shores', 'CA','USA'); alladdr address_book_t := address_book_t(); BEGIN INSERT INTO customers VALUES ( 666999, 'Joe', 'Smith', myaddr, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); END; / Subquery Example This example uses the warehouse_typ type in the sample schema oe to illustrate the use of a subquery in the call to the constructor method. CREATE TABLE warehouse_tab OF warehouse_typ; INSERT INTO warehouse_tab VALUES (warehouse_typ(101, 'new_wh', 201)); CREATE TYPE facility_typ AS OBJECT ( facility_id NUMBER, warehouse_ref REF warehouse_typ); See Also: Oracle Database Object-Relational Developer's Guide for additional information on constructor methods and Oracle Database PL/SQL Language Reference for information on PL/SQL limitations on calls to type constructors NEW schema . type_name ( expr , )
  • 464. Expression Lists 6-16 Oracle Database SQL Language Reference CREATE TABLE buildings (b_id NUMBER, building facility_typ); INSERT INTO buildings VALUES (10, facility_typ(102, (SELECT REF(w) FROM warehouse_tab w WHERE warehouse_name = 'new_wh'))); SELECT b.b_id, b.building.facility_id "FAC_ID", DEREF(b.building.warehouse_ref) "WH" FROM buildings b; B_ID FAC_ID WH(WAREHOUSE_ID, WAREHOUSE_NAME, LOCATION_ID) ---------- ---------- --------------------------------------------- 10 102 WAREHOUSE_TYP(101, 'new_wh', 201) Expression Lists An expression list is a combination of other expressions. expression_list::= Expression lists can appear in comparison and membership conditions and in GROUP BY clauses of queries and subqueries. An expression lists in a comparision or membership condition is sometimes referred to as a row value constructor or row constructor. Comparison and membership conditions appear in the conditions of WHERE clauses. They can contain either one or more comma-delimited expressions or one or more sets of expressions where each set contains one or more comma-delimited expressions. In the latter case (multiple sets of expressions): ■ Each set is bounded by parentheses ■ Each set must contain the same number of expressions ■ The number of expressions in each set must match the number of expressions before the operator in the comparison condition or before the IN keyword in the membership condition. A comma-delimited list of expressions can contain no more than 1000 expressions. A comma-delimited list of sets of expressions can contain any number of sets, but each set can contain no more than 1000 expressions. The following are some valid expression lists in conditions: (10, 20, 40) ('SCOTT', 'BLAKE', 'TAYLOR') ( ('Guy', 'Himuro', 'GHIMURO'),('Karen', 'Colmenares', 'KCOLMENA') ) In the third example, the number of expressions in each set must equal the number of expressions in the first part of the condition. For example: SELECT * FROM employees WHERE (first_name, last_name, email) IN expr , ( expr , )
  • 465. Expression Lists Expressions 6-17 (('Guy', 'Himuro', 'GHIMURO'),('Karen', 'Colmenares', 'KCOLMENA')) In a simple GROUP BY clause, you can use either the upper or lower form of expression list: SELECT department_id, MIN(salary) min, MAX(salary) max FROM employees GROUP BY department_id, salary ORDER BY department_id, min, max; SELECT department_id, MIN(salary) min, MAX(salary) max FROM employees GROUP BY (department_id, salary) ORDER BY department_id, min, max; In ROLLUP, CUBE, and GROUPING SETS clauses of GROUP BY clauses, you can combine individual expressions with sets of expressions in the same expression list. The following example shows several valid grouping sets expression lists in one SQL statement: SELECT prod_category, prod_subcategory, country_id, cust_city, count(*) FROM products, sales, customers WHERE sales.prod_id = products.prod_id AND sales.cust_id=customers.cust_id AND sales.time_id = '01-oct-00' AND customers.cust_year_of_birth BETWEEN 1960 and 1970 GROUP BY GROUPING SETS ( (prod_category, prod_subcategory, country_id, cust_city), (prod_category, prod_subcategory, country_id), (prod_category, prod_subcategory), country_id ) ORDER BY prod_category, prod_subcategory, country_id, cust_city; See Also: "Comparison Conditions" on page 7-4 and IN Condition conditions on page 7-22 See Also: SELECT on page 19-4
  • 466. Expression Lists 6-18 Oracle Database SQL Language Reference
  • 467. 7 Conditions 7-1 7 Conditions A condition specifies a combination of one or more expressions and logical (Boolean) operators and returns a value of TRUE, FALSE, or UNKNOWN. This chapter contains the following sections: ■ About SQL Conditions ■ Comparison Conditions ■ Floating-Point Conditions ■ Logical Conditions ■ Model Conditions ■ Multiset Conditions ■ Pattern-matching Conditions ■ Null Conditions ■ XML Conditions ■ Compound Conditions ■ BETWEEN Condition ■ EXISTS Condition ■ IN Condition ■ IS OF type Condition About SQL Conditions Conditions can have several forms, as shown in the following syntax.
  • 468. About SQL Conditions 7-2 Oracle Database SQL Language Reference condition::= If you have installed Oracle Text, then you can create conditions with the built-in operators that are part of that product, including CONTAINS, CATSEARCH, and MATCHES. For more information on these Oracle Text elements, refer to Oracle Text Reference. If you are using Oracle Expression Filter, then you can create conditions with the built-in EVALUATE operator that is part of that product. For more information, refer to Oracle Database Rules Manager and Expression Filter Developer's Guide. The sections that follow describe the various forms of conditions. You must use appropriate condition syntax whenever condition appears in SQL statements. You can use a condition in the WHERE clause of these statements: ■ DELETE ■ SELECT ■ UPDATE You can use a condition in any of these clauses of the SELECT statement: ■ WHERE ■ START WITH ■ CONNECT BY ■ HAVING comparison_condition floating_point_condition logical_condition model_condition multiset_condition pattern_matching_condition range_condition null_condition XML_condition compound_condition exists_condition in_condition is_of_type_condition
  • 469. About SQL Conditions Conditions 7-3 A condition could be said to be of a logical data type, although Oracle Database does not formally support such a data type. The following simple condition always evaluates to TRUE: 1 = 1 The following more complex condition adds the salary value to the commission_ pct value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 25000: NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000) Logical conditions can combine multiple conditions into a single condition. For example, you can use the AND condition to combine two conditions: (1 = 1) AND (5 < 7) Here are some valid conditions: name = 'SMITH' employees.department_id = departments.department_id hire_date > '01-JAN-08' job_id IN ('SA_MAN', 'SA_REP') salary BETWEEN 5000 AND 10000 commission_pct IS NULL AND salary = 2100 Condition Precedence Precedence is the order in which Oracle Database evaluates different conditions in the same expression. When evaluating an expression containing multiple conditions, Oracle evaluates conditions with higher precedence before evaluating those with lower precedence. Oracle evaluates conditions with equal precedence from left to right within an expression, with the following exceptions: ■ Left to right evaluation is not guaranteed for multiple conditions connected using AND ■ Left to right evaluation is not guaranteed for multiple conditions connected using OR Table 7–1 lists the levels of precedence among SQL condition from high to low. Conditions listed on the same line have the same precedence. As the table indicates, Oracle evaluates operators before conditions. Note: The combined values of the NLS_COMP and NLS_SORT settings determine the rules by which characters are sorted and compared. If NLS_COMP is set to LINGUISTIC for your database, then all entities in this chapter will be interpreted according to the rules specified by the NLS_SORT parameter. If NLS_COMP is not set to LINGUISTIC, then the functions are interpreted without regard to the NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle Database Globalization Support Guide for more information on these settings. See Also: The description of each statement in Chapter 10 through Chapter 19 for the restrictions on the conditions in that statement
  • 470. Comparison Conditions 7-4 Oracle Database SQL Language Reference Comparison Conditions Comparison conditions compare one expression with another. The result of such a comparison can be TRUE, FALSE, or NULL. Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data. When comparing numeric expressions, Oracle uses numeric precedence to determine whether the condition compares NUMBER, BINARY_FLOAT, or BINARY_DOUBLE values. Refer to "Numeric Precedence" on page 3-14 for information on numeric precedence. Two objects of nonscalar type are comparable if they are of the same named type and there is a one-to-one correspondence between their elements. In addition, nested tables of user-defined object types, even if their elements are comparable, must have MAP methods defined on them to be used in equality or IN conditions. Table 7–2 lists comparison conditions. Table 7–1 SQL Condition Precedence Type of Condition Purpose SQL operators are evaluated before SQL conditions See "Operator Precedence" on page 4-2 =, !=, <, >, <=, >=, comparison IS [NOT] NULL, LIKE, [NOT] BETWEEN, [NOT] IN, EXISTS, IS OF type comparison NOT exponentiation, logical negation AND conjunction OR disjunction See Also: Oracle Database Object-Relational Developer's Guide for information on using MAP methods to compare objects Table 7–2 Comparison Conditions Type of Condition Purpose Example = Equality test. SELECT * FROM employees WHERE salary = 2500 ORDER BY employee_id; != ^= < > ¬= Inequality test. Some forms of the inequality condition may be unavailable on some platforms. SELECT * FROM employees WHERE salary != 2500 ORDER BY employee_id; > < Greater-than and less-than tests. SELECT * FROM employees WHERE salary > 2500 ORDER BY employee_id; SELECT * FROM employees WHERE salary < 2500 ORDER BY employee_id;
  • 471. Comparison Conditions Conditions 7-5 Simple Comparison Conditions A simple comparison condition specifies a comparison with expressions or subquery results. simple_comparison_condition::= >= <= Greater-than-or-equal-to and less-than-or-equal-to tests. SELECT * FROM employees WHERE salary >= 2500 ORDER BY employee_id; SELECT * FROM employees WHERE salary <= 2500 ORDER BY employee_id; ANY SOME Compares a value to each value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. Can be followed by any expression or subquery that returns one or more values. Evaluates to FALSE if the query returns no rows. SELECT * FROM employees WHERE salary = ANY (SELECT salary FROM employees WHERE department_id = 30) ORDER BY employee_id; ALL Compares a value to every value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. Can be followed by any expression or subquery that returns one or more values. Evaluates to TRUE if the query returns no rows. SELECT * FROM employees WHERE salary >= ALL ( 1400, 3000) ORDER BY employee_id; Table 7–2 (Cont.) Comparison Conditions Type of Condition Purpose Example expr = != ^= <> > < >= <= expr ( expr , ) = != ^= <> ( subquery )
  • 472. Comparison Conditions 7-6 Oracle Database SQL Language Reference expression_list::= If you use the lower form of this condition (with multiple expressions to the left of the operator), then you must use the lower form of the expression_list, and the values returned by the subquery must match in number and data type the expressions in expression_list. Group Comparison Conditions A group comparison condition specifies a comparison with any or all members in a list or subquery. group_comparison_condition::= expression_list::= See Also: "Expression Lists" on page 6-16 for more information about combining expressions and SELECT on page 19-4 for information about subqueries expr , ( expr , ) expr = != ^= <> > < >= <= ANY SOME ALL ( expression_list subquery ) ( expr , ) = != ^= <> ANY SOME ALL ( expression_list ’ subquery ) expr , ( expr , )
  • 473. Logical Conditions Conditions 7-7 If you use the upper form of this condition (with a single expression to the left of the operator), then you must use the upper form of expression_list. If you use the lower form of this condition (with multiple expressions to the left of the operator), then you must use the lower form of expression_list, and the expressions in each expression_list must match in number and data type the expressions to the left of the operator. Floating-Point Conditions The floating-point conditions let you determine whether an expression is infinite or is the undefined result of an operation (is not a number or NaN). floating_point_condition::= In both forms of floating-point condition, expr must resolve to a numeric data type or to any data type that can be implicitly converted to a numeric data type. Table 7–3 describes the floating-point conditions. Logical Conditions A logical condition combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. Table 7–4 lists logical conditions. See Also: ■ "Expression Lists" on page 6-16 ■ SELECT on page 19-4 Table 7–3 Floating-Point Conditions Type of Condition Operation Example IS [NOT] NAN Returns TRUE if expr is the special value NaN when NOT is not specified. Returns TRUE if expr is not the special value NaN when NOT is specified. SELECT COUNT(*) FROM employees WHERE commission_pct IS NOT NAN; IS [NOT] INFINITE Returns TRUE if expr is the special value +INF or -INF when NOT is not specified. Returns TRUE if expr is neither +INF nor -INF when NOT is specified. SELECT last_name FROM employees WHERE salary IS NOT INFINITE; See Also: ■ "Floating-Point Numbers" on page 3-12 for more information on the Oracle implementation of floating-point numbers ■ "Implicit Data Conversion" on page 3-40 for more information on how Oracle converts floating-point data types expr IS NOT NAN INFINITE
  • 474. Logical Conditions 7-8 Oracle Database SQL Language Reference Table 7–5 shows the result of applying the NOT condition to an expression. Table 7–6 shows the results of combining the AND condition to two expressions. For example, in the WHERE clause of the following SELECT statement, the AND logical condition is used to ensure that only those hired before 2004 and earning more than $2500 a month are returned: SELECT * FROM employees WHERE hire_date < TO_DATE('01-JAN-2004', 'DD-MON-YYYY') AND salary > 2500 ORDER BY employee_id; Table 7–7 shows the results of applying OR to two expressions. Table 7–4 Logical Conditions Type of Condition Operation Examples NOT Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. If it is UNKNOWN, then it remains UNKNOWN. SELECT * FROM employees WHERE NOT (job_id IS NULL) ORDER BY employee_id; SELECT * FROM employees WHERE NOT (salary BETWEEN 1000 AND 2000) ORDER BY employee_id; AND Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE. Otherwise returns UNKNOWN. SELECT * FROM employees WHERE job_id = 'PU_CLERK' AND department_id = 30 ORDER BY employee_id; OR Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE. Otherwise returns UNKNOWN. SELECT * FROM employees WHERE job_id = 'PU_CLERK' OR department_id = 10 ORDER BY employee_id; Table 7–5 NOT Truth Table -- TRUE FALSE UNKNOWN NOT FALSE TRUE UNKNOWN Table 7–6 AND Truth Table AND TRUE FALSE UNKNOWN TRUE TRUE FALSE UNKNOWN FALSE FALSE FALSE FALSE UNKNOWN UNKNOWN FALSE UNKNOWN Table 7–7 OR Truth Table OR TRUE FALSE UNKNOWN TRUE TRUE TRUE TRUE
  • 475. Model Conditions Conditions 7-9 For example, the following query returns employees who have a 40% commission rate or a salary greater than $20,000: SELECT employee_id FROM employees WHERE commission_pct = .4 OR salary > 20000 ORDER BY employee_id; Model Conditions Model conditions can be used only in the MODEL clause of a SELECT statement. IS ANY Condition The IS ANY condition can be used only in the model_clause of a SELECT statement. Use this condition to qualify all values of a dimension column, including NULL. is_any_condition::= The condition always returns a Boolean value of TRUE in order to qualify all values of the column. Example The following example sets sales for each product for year 2000 to 0: SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s[ANY, 2000] = 0 ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 0 France Mouse Pad 2001 3269.09 France Standard Mouse 1998 2390.83 FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for information Table 7–7 (Cont.) OR Truth Table OR TRUE FALSE UNKNOWN dimension_column IS ANY
  • 476. Model Conditions 7-10 Oracle Database SQL Language Reference France Standard Mouse 1999 2280.45 France Standard Mouse 2000 0 France Standard Mouse 2001 2164.54 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 0 Germany Mouse Pad 2001 9535.08 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 0 Germany Standard Mouse 2001 6456.13 16 rows selected. The preceding example requires the view sales_view_ref. Refer to "The MODEL clause: Examples" on page 19-45 to create this view. IS PRESENT Condition is_present_condition::= The IS PRESENT condition can be used only in the model_clause of a SELECT statement. Use this condition to test whether the cell referenced is present prior to the execution of the model_clause. The condition returns TRUE if the cell exists prior to the execution of the model_ clause and FALSE if it does not. Example In the following example, if sales of the Mouse Pad for year 1999 exist, then sales of the Mouse Pad for year 2000 is set to sales of the Mouse Pad for year 1999. Otherwise, sales of the Mouse Pad for year 2000 is set to 0. SELECT country, prod, year, s FROM sales_view_ref MODEL PARTITION BY (country) DIMENSION BY (prod, year) MEASURES (sale s) IGNORE NAV UNIQUE DIMENSION RULES UPSERT SEQUENTIAL ORDER ( s['Mouse Pad', 2000] = CASE WHEN s['Mouse Pad', 1999] IS PRESENT THEN s['Mouse Pad', 1999] ELSE 0 END ) ORDER BY country, prod, year; COUNTRY PROD YEAR S ---------- ----------------------------------- -------- --------- See Also: model_clause on page 19-28 and "Model Expressions" on page 6-11 for information cell_reference IS PRESENT
  • 477. Multiset Conditions Conditions 7-11 France Mouse Pad 1998 2509.42 France Mouse Pad 1999 3678.69 France Mouse Pad 2000 3678.69 France Mouse Pad 2001 3269.09 France Standard Mouse 1998 2390.83 France Standard Mouse 1999 2280.45 France Standard Mouse 2000 1274.31 France Standard Mouse 2001 2164.54 Germany Mouse Pad 1998 5827.87 Germany Mouse Pad 1999 8346.44 Germany Mouse Pad 2000 8346.44 Germany Mouse Pad 2001 9535.08 Germany Standard Mouse 1998 7116.11 Germany Standard Mouse 1999 6263.14 Germany Standard Mouse 2000 2637.31 Germany Standard Mouse 2001 6456.13 16 rows selected. The preceding example requires the view sales_view_ref. Refer to "The MODEL clause: Examples" on page 19-45 to create this view. Multiset Conditions Multiset conditions test various aspects of nested tables. IS A SET Condition Use IS A SET conditions to test whether a specified nested table is composed of unique elements. The condition returns NULL if the nested table is NULL. Otherwise, it returns TRUE if the nested table is a set, even if it is a nested table of length zero, and FALSE otherwise. is_a_set_condition::= Example The following example selects from the table customers_demo those rows in which the cust_address_ntab nested table column contains unique elements: SELECT customer_id, cust_address_ntab FROM customers_demo WHERE cust_address_ntab IS A SET ORDER BY customer_id; CUSTOMER_ID CUST_ADDRESS_NTAB(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) ---------------------------------------------------------------------------------------------- 101 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('514 W Superior St', '46901', 'Kokomo', 'IN', 'US')) 102 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('2515 Bloyd Ave', '46218', 'Indianapolis', 'IN', 'US')) 103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')) 104 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('6445 Bay Harbor Ln', '46254', 'Indianapolis', 'IN', 'US')) 105 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('4019 W 3Rd St', '47404', 'Bloomington', 'IN', 'US')) The preceding example requires the table customers_demo and a nested table column containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table column. nested_table IS NOT A SET
  • 478. Multiset Conditions 7-12 Oracle Database SQL Language Reference IS EMPTY Condition Use the IS [NOT] EMPTY conditions to test whether a specified nested table is empty. A nested table that consists of a single value, a NULL, is not considered an empty nested table. is_empty_condition::= The condition returns a Boolean value: TRUE for an IS EMPTY condition if the collection is empty, and TRUE for an IS NOT EMPTY condition if the collection is not empty. If you specify NULL for the nested table or varray, then the result is NULL. Example The following example selects from the sample table pm.print_media those rows in which the ad_textdocs_ntab nested table column is not empty: SELECT product_id, TO_CHAR(ad_finaltext) AS text FROM print_media WHERE ad_textdocs_ntab IS NOT EMPTY ORDER BY product_id, text; MEMBER Condition member_condition::= A member_condition is a membership condition that tests whether an element is a member of a nested table. The return value is TRUE if expr is equal to a member of the specified nested table or varray. The return value is NULL if expr is null or if the nested table is empty. ■ expr must be of the same type as the element type of the nested table. ■ The OF keyword is optional and does not change the behavior of the condition. ■ The NOT keyword reverses the Boolean output: Oracle returns FALSE if expr is a member of the specified nested table. ■ The element types of the nested table must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example selects from the table customers_demo those rows in which the cust_address_ntab nested table column contains the values specified in the WHERE clause: SELECT customer_id, cust_address_ntab FROM customers_demo WHERE cust_address_typ('8768 N State Rd 37', 47404, 'Bloomington', 'IN', 'US') MEMBER OF cust_address_ntab ORDER BY customer_id; CUSTOMER_ID CUST_ADDRESS_NTAB(STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID) nested_table IS NOT EMPTY expr NOT MEMBER OF nested_table
  • 479. Multiset Conditions Conditions 7-13 ------------ --------------------------------------------------------------------------------- 103 CUST_ADDRESS_TAB_TYP(CUST_ADDRESS_TYP('8768 N State Rd 37', '47404', 'Bloomington', 'IN', 'US')) The preceding example requires the table customers_demo and a nested table column containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table column. SUBMULTISET Condition The SUBMULTISET condition tests whether a specified nested table is a submultiset of another specified nested table. The operator returns a Boolean value. TRUE is returned when nested_table1 is a submultiset of nested_table2. nested_table1 is a submultiset of nested_ table2 when one of the following conditions occur: ■ nested_table1 is not null and contains no rows. TRUE is returned even if nested_table2 is null since an empty multiset is a submultiset of any non-null replacement for nested_table2. ■ nested_table1 and nested_table2 are not null, nested_table1 does not contain a null element, and there is a one-to-one mapping of each element in nested_table1 to an equal element in nested_table2. NULL is returned when one of the following conditions occurs: ■ nested_table1 is null. ■ nested_table2 is null, and nested_table1 is not null and not empty. ■ nested_table1 is a submultiset of nested_table2 after modifying each null element of nested_table1 and nested_table2 to some non-null value, enabling a one-to-one mapping of each element in nested_table1 to an equal element in nested_table2. If none of the above conditions occur, then FALSE is returned. submultiset_condition::= ■ The OF keyword is optional and does not change the behavior of the operator. ■ The NOT keyword reverses the Boolean output: Oracle returns FALSE if nested_ table1 is a subset of nested_table2. ■ The element types of the nested table must be comparable. Refer to "Comparison Conditions" on page 7-4 for information on the comparability of nonscalar types. Example The following example selects from the customers_demo table those rows in which the cust_address_ntab nested table is a submultiset of the cust_address2_ntab nested table: SELECT customer_id, cust_address_ntab FROM customers_demo WHERE cust_address_ntab SUBMULTISET OF cust_address2_ntab ORDER BY customer_id; nested_table1 NOT SUBMULTISET OF nested_table2
  • 480. Pattern-matching Conditions 7-14 Oracle Database SQL Language Reference The preceding example requires the table customers_demo and two nested table columns containing data. Refer to "Multiset Operators" on page 4-6 to create this table and nested table columns. Pattern-matching Conditions The pattern-matching conditions compare character data. LIKE Condition The LIKE conditions specify a test involving pattern matching. Whereas the equality operator (=) exactly matches one character value to another, the LIKE conditions match a portion of one character value to another by searching the first value for the pattern specified by the second. LIKE calculates strings using characters as defined by the input character set. LIKEC uses Unicode complete characters. LIKE2 uses UCS2 code points. LIKE4 uses UCS4 code points. like_condition::= In this syntax: ■ char1 is a character expression, such as a character column, called the search value. ■ char2 is a character expression, usually a literal, called the pattern. ■ esc_char is a character expression, usually a literal, called the escape character. The LIKE condition is the best choice in almost all situations. Use the following guidelines to determine whether any of the variations would be helpful in your environment: ■ Use LIKE2 to process strings using UCS-2 semantics. LIKE2 treats a Unicode supplementary character as two characters. ■ Use LIKE4 to process strings using UCS-4 semantics. LIKE4 treats a Unicode supplementary character as one character. ■ Use LIKEC to process strings using Unicode complete character semantics. LIKEC treats a composite character as one character. If esc_char is not specified, then there is no default escape character. If any of char1, char2, or esc_char is null, then the result is unknown. Otherwise, the escape character, if specified, must be a character string of length 1. All of the character expressions (char1, char2, and esc_char) can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. If they differ, then Oracle converts all of them to the data type of char1. The pattern can contain special pattern-matching characters: ■ An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multibyte character set) in the value. char1 NOT LIKE LIKEC LIKE2 LIKE4 char2 ESCAPE esc_char
  • 481. Pattern-matching Conditions Conditions 7-15 ■ A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multibyte character set) in the value. The pattern '%' cannot match a null. You can include the actual characters % or _ in the pattern by using the ESCAPE clause, which identifies the escape character. If the escape character precedes the character % or _ in the pattern, then Oracle interprets this character literally in the pattern rather than as a special pattern-matching character. You can also search for the escape character itself by repeating it. For example, if @ is the escape character, then you can use @@ to search for @. Table 7–8 describes the LIKE conditions. To process the LIKE conditions, Oracle divides the pattern into subpatterns consisting of one or two characters each. The two-character subpatterns begin with the escape character and the other character is %, or _, or the escape character. Let P1, P2, ..., Pn be these subpatterns. The like condition is true if there is a way to partition the search value into substrings S1, S2, ..., Sn so that for all i between 1 and n: ■ If Pi is _, then Si is a single character. ■ If Pi is %, then Si is any string. ■ If Pi is two characters beginning with an escape character, then Si is the second character of Pi. ■ Otherwise, Pi = Si. With the LIKE conditions, you can compare a value to a pattern rather than to a constant. The pattern must appear after the LIKE keyword. For example, you can issue the following query to find the salaries of all employees with names beginning with R: SELECT salary FROM employees WHERE last_name LIKE 'R%' ORDER BY salary; The following query uses the = operator, rather than the LIKE condition, to find the salaries of all employees with the name 'R%': SELECT salary FROM employees WHERE last_name = 'R%' ORDER BY salary; Table 7–8 LIKE Condition Type of Condition Operation Example x [NOT] LIKE y [ESCAPE 'z'] TRUE if x does [not] match the pattern y. Within y, the character % matches any string of zero or more characters except null. The character _ matches any single character. Any character can follow ESCAPE except percent (%) and underbar (_). A wildcard character is treated as a literal if preceded by the escape character. SELECT last_name FROM employees WHERE last_name LIKE '%A_B%' ESCAPE '' ORDER BY last_name;
  • 482. Pattern-matching Conditions 7-16 Oracle Database SQL Language Reference The following query finds the salaries of all employees with the name 'SM%'. Oracle interprets 'SM%' as a text literal, rather than as a pattern, because it precedes the LIKE keyword: SELECT salary FROM employees WHERE 'SM%' LIKE last_name ORDER BY salary; Case Sensitivity Case is significant in all conditions comparing character expressions that use the LIKE condition and the equality (=) operators. You can perform case or accent insensitive LIKE searches by setting the NLS_SORT and the NLS_COMP session parameters. Pattern Matching on Indexed Columns When you use LIKE to search an indexed column for a pattern, Oracle can use the index to improve performance of a query if the leading character in the pattern is not % or _. In this case, Oracle can scan the index by this leading character. If the first character in the pattern is % or _, then the index cannot improve performance because Oracle cannot scan the index. LIKE Condition: General Examples This condition is true for all last_name values beginning with Ma: last_name LIKE 'Ma%' All of these last_name values make the condition true: Mallin, Markle, Marlow, Marvins, Marvis, Matos Case is significant, so last_name values beginning with MA, ma, and mA make the condition false. Consider this condition: last_name LIKE 'SMITH_' This condition is true for these last_name values: SMITHE, SMITHY, SMITHS This condition is false for SMITH because the special underscore character (_) must match exactly one character of the last_name value. ESCAPE Clause Example The following example searches for employees with the pattern A_B in their name: SELECT last_name FROM employees WHERE last_name LIKE '%A_B%' ESCAPE '' ORDER BY last_name; The ESCAPE clause identifies the backslash () as the escape character. In the pattern, the escape character precedes the underscore (_). This causes Oracle to interpret the underscore literally, rather than as a special pattern matching character. See Also: Oracle Database Globalization Support Guide for more information on this case- and accent-insensitive linguistic sorts
  • 483. Pattern-matching Conditions Conditions 7-17 Patterns Without % Example If a pattern does not contain the % character, then the condition can be true only if both operands have the same length. Consider the definition of this table and the values inserted into it: CREATE TABLE ducks (f CHAR(6), v VARCHAR2(6)); INSERT INTO ducks VALUES ('DUCK', 'DUCK'); SELECT '*'||f||'*' "char", '*'||v||'*' "varchar" FROM ducks; char varchar -------- -------- *DUCK * *DUCK* Because Oracle blank-pads CHAR values, the value of f is blank-padded to 6 bytes. v is not blank-padded and has length 4. REGEXP_LIKE Condition REGEXP_LIKE is similar to the LIKE condition, except REGEXP_LIKE performs regular expression matching instead of the simple pattern matching performed by LIKE. This condition evaluates strings using characters as defined by the input character set. This condition complies with the POSIX regular expression standard and the Unicode Regular Expression Guidelines. For more information, refer to Appendix D, "Oracle Regular Expression Support". regexp_like_condition::= ■ source_char is a character expression that serves as the search value. It is commonly a character column and can be of any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. ■ pattern is the regular expression. It is usually a text literal and can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. It can contain up to 512 bytes. If the data type of pattern is different from the data type of source_ char, Oracle converts pattern to the data type of source_char. For a listing of the operators you can specify in pattern, refer to Appendix D, "Oracle Regular Expression Support". ■ match_parameter is a text literal that lets you change the default matching behavior of the function. You can specify one or more of the following values for match_parameter: – 'i' specifies case-insensitive matching. – 'c' specifies case-sensitive matching. – 'n' allows the period (.), which is the match-any-character wildcard character, to match the newline character. If you omit this parameter, then the period does not match the newline character. – 'm' treats the source string as multiple lines. Oracle interprets ^ and $ as the start and end, respectively, of any line anywhere in the source string, rather than only at the start or end of the entire source string. If you omit this parameter, then Oracle treats the source string as a single line. REGEXP_LIKE ( source_char , pattern , match_param )
  • 484. Pattern-matching Conditions 7-18 Oracle Database SQL Language Reference – 'x' ignores whitespace characters. By default, whitespace characters match themselves. If you specify multiple contradictory values, then Oracle uses the last value. For example, if you specify 'ic', then Oracle uses case-sensitive matching. If you specify a character other than those shown above, then Oracle returns an error. If you omit match_parameter, then: – The default case sensitivity is determined by the value of the NLS_SORT parameter. – A period (.) does not match the newline character. – The source string is treated as a single line. Examples The following query returns the first and last names for those employees with a first name of Steven or Stephen (where first_name begins with Ste and ends with en and in between is either v or ph): SELECT first_name, last_name FROM employees WHERE REGEXP_LIKE (first_name, '^Ste(v|ph)en$') ORDER BY first_name, last_name; FIRST_NAME LAST_NAME -------------------- ------------------------- Steven King Steven Markle Stephen Stiles The following query returns the last name for those employees with a double vowel in their last name (where last_name contains two adjacent occurrences of either a, e, i, o, or u, regardless of case): SELECT last_name FROM employees WHERE REGEXP_LIKE (last_name, '([aeiou])1', 'i') ORDER BY last_name; LAST_NAME ------------------------- De Haan Greenberg Khoo Gee Greene Lee Bloom Feeney See Also: ■ "LIKE Condition" on page 7-14 ■ REGEXP_INSTR on page 5-160, REGEXP_REPLACE on page 5-162, and REGEXP_SUBSTR on page 5-164 for functions that provide regular expression support
  • 485. XML Conditions Conditions 7-19 Null Conditions A NULL condition tests for nulls. This is the only condition that you should use to test for nulls. null_condition::= Table 7–9 lists the null conditions. XML Conditions XML conditions determines whether a specified XML resource can be found in a specified path. EQUALS_PATH Condition The EQUALS_PATH condition determines whether a resource in the Oracle XML database can be found in the database at a specified path. Use this condition in queries to RESOURCE_VIEW and PATH_VIEW. These public views provide a mechanism for SQL access to data stored in the XML database repository. RESOURCE_VIEW contains one row for each resource in the repository, and PATH_ VIEW contains one row for each unique path in the repository. equals_path_condition::= This condition applies only to the path as specified. It is similar to but more restrictive than UNDER_PATH. For path_string, specify the (absolute) path name to resolve. This can contain components that are hard or weak resource links. The optional correlation_integer argument correlates the EQUALS_PATH condition with its ancillary functions DEPTH and PATH. Example The view RESOURCE_VIEW computes the paths (in the any_path column) that lead to all XML resources (in the res column) in the database repository. The following Table 7–9 Null Condition Type of Condition Operation Example IS [NOT] NULL Tests for nulls. See Also: "Nulls" on page 3-70 SELECT last_name FROM employees WHERE commission_pct IS NULL ORDER BY last_name; See Also: UNDER_PATH Condition on page 7-20, DEPTH on page 5-63, and PATH on page 5-131 expr IS NOT NULL EQUALS_PATH ( column , path_string , correlation_integer )
  • 486. Compound Conditions 7-20 Oracle Database SQL Language Reference example queries the RESOURCE_VIEW view to find the paths to the resources in the sample schema oe. The EQUALS_PATH condition causes the query to return only the specified path: SELECT ANY_PATH FROM RESOURCE_VIEW WHERE EQUALS_PATH(res, '/sys/schemas/OE/www.example.com')=1; ANY_PATH ----------------------------------------------- /sys/schemas/OE/www.example.com Compare this example with that for UNDER_PATH Condition on page 7-20. UNDER_PATH Condition The UNDER_PATH condition determines whether resources specified in a column can be found under a particular path specified by path_string in the Oracle XML database repository. The path information is computed by the RESOURCE_VIEW view, which you query to use this condition. Use this condition in queries to RESOURCE_VIEW and PATH_VIEW. These public views provide a mechanism for SQL access to data stored in the XML database repository. RESOURCE_VIEW contains one row for each resource in the repository, and PATH_ VIEW contains one row for each unique path in the repository. under_path_condition::= The optional levels argument indicates the number of levels down from path_ string Oracle should search. For levels, specify any nonnegative integer. The optional correlation_integer argument correlates the UNDER_PATH condition with its ancillary functions PATH and DEPTH. Example The view RESOURCE_VIEW computes the paths (in the any_path column) that lead to all XML resources (in the res column) in the database repository. The following example queries the RESOURCE_VIEW view to find the paths to the resources in the sample schema oe. The query returns the path of the XML schema that was created in "XMLType Table Examples" on page 16-73: SELECT ANY_PATH FROM RESOURCE_VIEW WHERE UNDER_PATH(res, '/sys/schemas/OE/www.example.com')=1; ANY_PATH ---------------------------------------------- /sys/schemas/OE/www.example.com/xwarehouses.xsd Compound Conditions A compound condition specifies a combination of other conditions. See Also: The related condition EQUALS_PATH Condition on page 7-19 and the ancillary functions DEPTH on page 5-63 and PATH on page 5-131 UNDER_PATH ( column , levels , path_string , correlation_integer )
  • 487. BETWEEN Condition Conditions 7-21 compound_condition::= BETWEEN Condition A BETWEEN condition determines whether the value of one expression is in an interval defined by two other expressions. between_condition::= All three expressions must be numeric, character, or datetime expressions. In SQL, it is possible that expr1 will be evaluated more than once. If the BETWEEN expression appears in PL/SQL, expr1 is guaranteed to be evaluated only once. If the expressions are not all the same data type, then Oracle Database implicitly converts the expressions to a common data type. If it cannot do so, then it returns an error. The value of expr1 NOT BETWEEN expr2 AND expr3 is the value of the expression NOT (expr1 BETWEEN expr2 AND expr3) And the value of expr1 BETWEEN expr2 AND expr3 is the value of the boolean expression: expr2 <= expr1 AND expr1 <= expr3 If expr3 < expr2, then the interval is empty. If expr1 is NULL, then the result is NULL. If expr1 is not NULL, then the value is FALSE in the ordinary case and TRUE when the keyword NOT is used. The boolean operator AND may produce unexpected results. Specifically, in the expression x AND y, the condition x IS NULL is not sufficient to determine the value See Also: "Logical Conditions" on page 7-7 for more information about NOT, AND, and OR conditions Note: The implicit data type conversion rules for PL/SQL are different from those for SQL. For more information, see Oracle Database PL/SQL Language Reference. See Also: "Implicit Data Conversion" on page 3-40 for more information on SQL data type conversion ( condition ) NOT condition condition AND OR condition expr1 NOT BETWEEN expr2 AND expr3
  • 488. EXISTS Condition 7-22 Oracle Database SQL Language Reference of the expression. The second operand still must be evaluated. The result is FALSE if the second operand has the value FALSE and NULL otherwise. See "Logical Conditions" on page 7-7 for more information on AND. EXISTS Condition An EXISTS condition tests for existence of rows in a subquery. Table 7–11 shows the EXISTS condition. IN Condition An in_condition is a membership condition. It tests a value for membership in a list of values or subquery in_condition::= Table 7–10 BETWEEN Condition Type of Condition Operation Example [NOT] BETWEEN x AND y [NOT] (expr2 less than or equal to expr1 AND expr1 less than or equal to expr3) SELECT * FROM employees WHERE salary BETWEEN 2000 AND 3000 ORDER BY employee_id; Table 7–11 EXISTS Condition Type of Condition Operation Example EXISTS TRUE if a subquery returns at least one row. SELECT department_id FROM departments d WHERE EXISTS (SELECT * FROM employees e WHERE d.department_id = e.department_id) ORDER BY department_id; EXISTS ( subquery ) expr NOT IN ( expression_list subquery ) ( expr , ) NOT IN ( expression_list , subquery )
  • 489. IN Condition Conditions 7-23 expression_list::= If you use the upper form of the in_condition condition (with a single expression to the left of the operator), then you must use the upper form of expression_list. If you use the lower form of this condition (with multiple expressions to the left of the operator), then you must use the lower form of expression_list, and the expressions in each expression_list must match in number and data type the expressions to the left of the operator. You can specify up to 1000 expressions in expression_list. Oracle Database does not always evaluate the expressions in an expression_list in the order in which they appear in the IN list. However, expressions in the select list of a subquery are evaluated in their specified order. Table 7–12 lists the form of IN condition. If any item in the list following a NOT IN operation evaluates to null, then all rows evaluate to FALSE or UNKNOWN, and no rows are returned. For example, the following statement returns the string 'True' for each row: SELECT 'True' FROM employees WHERE department_id NOT IN (10, 20); However, the following statement returns no rows: See Also: "Expression Lists" on page 6-16 Table 7–12 IN Condition Type of Condition Operation Example IN Equal-to-any-member-of test. Equivalent to =ANY. SELECT * FROM employees WHERE job_id IN ('PU_CLERK','SH_CLERK') ORDER BY employee_id; SELECT * FROM employees WHERE salary IN (SELECT salary FROM employees WHERE department_id =30) ORDER BY employee_id; NOT IN Equivalent to !=ALL. Evaluates to FALSE if any member of the set is NULL. SELECT * FROM employees WHERE salary NOT IN (SELECT salary FROM employees WHERE department_id = 30) ORDER BY employee_id; SELECT * FROM employees WHERE job_id NOT IN ('PU_CLERK', 'SH_CLERK') ORDER BY employee_id; expr , ( expr ,
  • 490. IS OF type Condition 7-24 Oracle Database SQL Language Reference SELECT 'True' FROM employees WHERE department_id NOT IN (10, 20, NULL); The preceding example returns no rows because the WHERE clause condition evaluates to: department_id != 10 AND department_id != 20 AND department_id != null Because the third condition compares department_id with a null, it results in an UNKNOWN, so the entire expression results in FALSE (for rows with department_id equal to 10 or 20). This behavior can easily be overlooked, especially when the NOT IN operator references a subquery. Moreover, if a NOT IN condition references a subquery that returns no rows at all, then all rows will be returned, as shown in the following example: SELECT 'True' FROM employees WHERE department_id NOT IN (SELECT 0 FROM DUAL WHERE 1=2); Restriction on LEVEL in WHERE Clauses In a [NOT] IN condition in a WHERE clause, if the right-hand side of the condition is a subquery, you cannot use LEVEL on the left-hand side of the condition. However, you can specify LEVEL in a subquery of the FROM clause to achieve the same result. For example, the following statement is not valid: SELECT employee_id, last_name FROM employees WHERE (employee_id, LEVEL) IN (SELECT employee_id, 2 FROM employees) START WITH employee_id = 2 CONNECT BY PRIOR employee_id = manager_id; But the following statement is valid because it encapsulates the query containing the LEVEL information in the FROM clause: SELECT v.employee_id, v.last_name, v.lev FROM (SELECT employee_id, last_name, LEVEL lev FROM employees v START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id) v WHERE (v.employee_id, v.lev) IN (SELECT employee_id, 2 FROM employees); IS OF type Condition Use the IS OF type condition to test object instances based on their specific type information. is_of_type_condition::= You must have EXECUTE privilege on all types referenced by type, and all types must belong to the same type family. This condition evaluates to null if expr is null. If expr is not null, then the condition evaluates to true (or false if you specify the NOT keyword) under either of these circumstances: expr IS NOT OF TYPE ( ONLY schema . type , )
  • 491. IS OF type Condition Conditions 7-25 ■ The most specific type of expr is the subtype of one of the types specified in the type list and you have not specified ONLY for the type, or ■ The most specific type of expr is explicitly specified in the type list. The expr frequently takes the form of the VALUE function with a correlation variable. The following example uses the sample table oe.persons, which is built on a type hierarchy in "Substitutable Table and Column Examples" on page 16-69. The example uses the IS OF type condition to restrict the query to specific subtypes: SELECT * FROM persons p WHERE VALUE(p) IS OF TYPE (employee_t); NAME SSN ---------------------------- Joe 32456 Tim 5678 SELECT * FROM persons p WHERE VALUE(p) IS OF (ONLY part_time_emp_t); NAME SSN ---------------------------- Tim 5678
  • 492. IS OF type Condition 7-26 Oracle Database SQL Language Reference
  • 493. 8 Common SQL DDL Clauses 8-1 8 Common SQL DDL Clauses This chapter describes some SQL data definition clauses that appear in multiple SQL statements. This chapter contains these sections: ■ allocate_extent_clause ■ constraint ■ deallocate_unused_clause ■ file_specification ■ logging_clause ■ parallel_clause ■ physical_attributes_clause ■ size_clause ■ storage_clause
  • 494. allocate_extent_clause 8-2 Oracle Database SQL Language Reference allocate_extent_clause Purpose Use the allocate_extent_clause clause to explicitly allocate a new extent for a database object. Explicitly allocating an extent with this clause does not change the values of the NEXT and PCTINCREASE storage parameters, so does not affect the size of the next extent to be allocated implicitly by Oracle Database. Refer to storage_clause on page 8-48 for information about the NEXT and PCTINCREASE storage parameters. You can allocate an extent in the following SQL statements: ■ ALTER CLUSTER (see ALTER CLUSTER on page 10-5) ■ ALTER INDEX: to allocate an extent to the index, an index partition, or an index subpartition (see ALTER INDEX on page 10-77) ■ ALTER MATERIALIZED VIEW: to allocate an extent to the materialized view, one of its partitions or subpartitions, or the overflow segment of an index-organized materialized view (see ALTER MATERIALIZED VIEW on page 11-3) ■ ALTER MATERIALIZED VIEW LOG (see ALTER MATERIALIZED VIEW LOG on page 11-18) ■ ALTER TABLE: to allocate an extent to the table, a table partition, a table subpartition, the mapping table of an index-organized table, the overflow segment of an index-organized table, or a LOB storage segment (see ALTER TABLE on page 12-2) Syntax allocate_extent_clause::= (size_clause::= on page 8-47) Semantics This section describes the parameters of the allocate_extent_clause. For additional information, refer to the SQL statement in which you set or reset these parameters for a particular database object. You cannot specify the allocate_extent_clause and the deallocate_unused_ clause in the same statement. SIZE Specify the size of the extent in bytes. The value of integer can be 0 through 2147483647. To specify a larger extent size, use an integer within this range with K, M, G, or T to specify the extent size in kilobytes, megabytes, gigabytes, or terabytes. ALLOCATE EXTENT ( SIZE size_clause DATAFILE ’ filename ’ INSTANCE integer )
  • 495. allocate_extent_clause Common SQL DDL Clauses 8-3 For a table, index, materialized view, or materialized view log, if you omit SIZE, then Oracle Database determines the size based on the values of the storage parameters of the object. However, for a cluster, Oracle does not evaluate the cluster's storage parameters, so you must specify SIZE if you do not want Oracle to use a default value. DATAFILE 'filename' Specify one of the data files in the tablespace of the table, cluster, index, materialized view, or materialized view log to contain the new extent. If you omit DATAFILE, then Oracle chooses the data file. INSTANCE integer Use this parameter only if you are using Oracle Real Application Clusters. Specifying INSTANCE integer makes the new extent available to the freelist group associated with the specified instance. If the instance number exceeds the maximum number of freelist groups, then Oracle divides the specified number by the maximum number and uses the remainder to identify the freelist group to be used. An instance is identified by the value of its initialization parameter INSTANCE_NUMBER. If you omit this parameter, then the space is allocated to the table, cluster, index, materialized view, or materialized view log but is not drawn from any particular freelist group. Instead, Oracle uses the master freelist and allocates space as needed. Note: If you are using automatic segment-space management, then the INSTANCE parameter of the allocate_extent_clause may not reserve the newly allocated space for the specified instance, because automatic segment-space management does not maintain rigid affinity between extents and instances.
  • 496. constraint 8-4 Oracle Database SQL Language Reference constraint Purpose Use a constraint to define an integrity constraint—a rule that restricts the values in a database. Oracle Database lets you create six types of constraints and lets you declare them in two ways. The six types of integrity constraint are described briefly here and more fully in "Semantics" on page 8-8: ■ A NOT NULL constraint prohibits a database value from being null. ■ A unique constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. ■ A primary key constraint combines a NOT NULL constraint and a unique constraint in a single declaration. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null. ■ A foreign key constraint requires values in one table to match values in another table. ■ A check constraint requires a value in the database to comply with a specified condition. ■ A REF column by definition references an object in another object type or in a relational table. A REF constraint lets you further describe the relationship between the REF column and the object it references. You can define constraints syntactically in two ways: ■ As part of the definition of an individual column or attribute. This is called inline specification. ■ As part of the table definition. This is called out-of-line specification. NOT NULL constraints must be declared inline. All other constraints can be declared either inline or out of line. Constraint clauses can appear in the following statements: ■ CREATE TABLE (see CREATE TABLE on page 16-6) ■ ALTER TABLE (see ALTER TABLE on page 12-2) ■ CREATE VIEW (see CREATE VIEW on page 17-14) ■ ALTER VIEW (see ALTER VIEW on page 13-12) View Constraints Oracle Database does not enforce view constraints. However, you can enforce constraints on views through constraints on base tables. You can specify only unique, primary key, and foreign key constraints on views, and they are supported only in DISABLE NOVALIDATE mode. You cannot define view constraints on attributes of an object column. See Also: "View Constraints" on page 8-18 for additional information on view constraints and "DISABLE Clause" on page 8-16 for information on DISABLE NOVALIDATE mode
  • 497. constraint Common SQL DDL Clauses 8-5 Prerequisites You must have the privileges necessary to issue the statement in which you are defining the constraint. To create a foreign key constraint, in addition, the parent table or view must be in your own schema or you must have the REFERENCES privilege on the columns of the referenced key in the parent table or view. Syntax constraint::= (inline_constraint::= on page 8-5, out_of_line_constraint::= on page 8-5, inline_ref_ constraint::= on page 8-6, out_of_line_ref_constraint::= on page 8-6) inline_constraint::= (references_clause::= on page 8-6) out_of_line_constraint::= (references_clause::= on page 8-6, constraint_state::= on page 8-6) inline_constraint out_of_line_constraint inline_ref_constraint out_of_line_ref_constraint CONSTRAINT constraint_name NOT NULL UNIQUE PRIMARY KEY references_clause CHECK ( condition ) constraint_state CONSTRAINT constraint_name UNIQUE ( column , ) PRIMARY KEY ( column , ) FOREIGN KEY ( column , ) references_clause CHECK ( condition ) constraint_state
  • 498. constraint 8-6 Oracle Database SQL Language Reference inline_ref_constraint::= (references_clause::= on page 8-6, constraint_state::= on page 8-6) out_of_line_ref_constraint::= (references_clause::= on page 8-6, constraint_state::= on page 8-6) references_clause::= constraint_state::= (using_index_clause::= on page 8-7, exceptions_clause::= on page 8-8) SCOPE IS schema . scope_table WITH ROWID CONSTRAINT constraint_name references_clause constraint_state SCOPE FOR ( ref_col ref_attr ) IS schema . scope_table REF ( ref_col ref_attr ) WITH ROWID CONSTRAINT constraint_name FOREIGN KEY ( ref_col ref_attr ) references_clause constraint_state REFERENCES schema . object ( column ) ON DELETE CASCADE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE DEFERRED RELY NORELY using_index_clause ENABLE DISABLE VALIDATE NOVALIDATE exceptions_clause
  • 499. constraint Common SQL DDL Clauses 8-7 using_index_clause::= (create_index::= on page 14-62, index_properties::= on page 8-7) index_properties::= (global_partitioned_index::= on page 14-65, local_partitioned_index::= on page 14-66--part of CREATE INDEX, index_attributes::= on page 8-7. The INDEXTYPE IS ... clause is not valid when defining a constraint.) index_attributes::= (physical_attributes_clause::= on page 14-3, logging_clause::= on page 8-38, key_ compression::= on page 14-64--all part of CREATE INDEX, parallel_clause: not supported in using_index_clause) USING INDEX schema . index ( create_index_statement ) index_properties global_partitioned_index local_partitioned_index index_attributes INDEXTYPE IS domain_index_clause XMLIndex_clause physical_attributes_clause logging_clause ONLINE TABLESPACE tablespace DEFAULT key_compression SORT NOSORT REVERSE VISIBLE INVISIBLE parallel_clause
  • 500. constraint 8-8 Oracle Database SQL Language Reference exceptions_clause::= Semantics This section describes the semantics of constraint. For additional information, refer to the SQL statement in which you define or redefine a constraint for a table or view. Oracle Database does not support constraints on columns or attributes whose type is a user-defined object, nested table, VARRAY, REF, or LOB, with two exceptions: ■ NOT NULL constraints are supported for a column or attribute whose type is user-defined object, VARRAY, REF, or LOB. ■ NOT NULL, foreign key, and REF constraints are supported on a column of type REF. CONSTRAINT constraint_name Specify a name for the constraint. If you omit this identifier, then Oracle Database generates a name with the form SYS_Cn. Oracle stores the name and the definition of the integrity constraint in the USER_, ALL_, and DBA_ CONSTRAINTS data dictionary views (in the CONSTRAINT_NAME and SEARCH_ CONDITION columns, respectively). NOT NULL Constraints A NOT NULL constraint prohibits a column from containing nulls. The NULL keyword by itself does not actually define an integrity constraint, but you can specify it to explicitly permit a column to contain nulls. You must define NOT NULL and NULL using inline specification. If you specify neither NOT NULL nor NULL, then the default is NULL. NOT NULL constraints are the only constraints you can specify inline on XMLType and VARRAY columns. To satisfy a NOT NULL constraint, every row in the table must contain a value for the column. Restrictions on NOT NULL Constraints NOT NULL constraints are subject to the following restrictions: ■ You cannot specify NULL or NOT NULL in a view constraint. ■ You cannot specify NULL or NOT NULL for an attribute of an object. Instead, use a CHECK constraint with the IS [NOT] NULL condition. See Also: Oracle Database Reference for information on the data dictionary views Note: Oracle Database does not index table rows in which all key columns are null except in the case of bitmap indexes. Therefore, if you want an index on all rows of a table, then you must either specify NOT NULL constraints for at least one of the index key columns or create a bitmap index. See Also: "Attribute-Level Constraints Example" on page 8-25 and "NOT NULL Example" on page 8-21 EXCEPTIONS INTO schema . table
  • 501. constraint Common SQL DDL Clauses 8-9 Unique Constraints A unique constraint designates a column as a unique key. A composite unique key designates a combination of columns as the unique key. When you define a unique constraint inline, you need only the UNIQUE keyword. When you define a unique constraint out of line, you must also specify one or more columns. You must define a composite unique key out of line. To satisfy a unique constraint, no two rows in the table can have the same value for the unique key. However, the unique key made up of a single column can contain nulls. To satisfy a composite unique key, no two rows in the table or view can have the same combination of values in the key columns. Any row that contains nulls in all key columns automatically satisfies the constraint. However, two rows that contain nulls for one or more key columns and the same combination of values for the other key columns violate the constraint. When you specify a unique constraint on one or more columns, Oracle implicitly creates an index on the unique key. If you are defining uniqueness for purposes of query performance, then Oracle recommends that you instead create the unique index explicitly using a CREATE UNIQUE INDEX statement. You can also use the CREATE UNIQUE INDEX statement to create a unique function-based index that defines a conditional unique constraint. See "Using a Function-based Index to Define Conditional Uniqueness: Example" on page 14-83 for more information. Restrictions on Unique Constraints Unique constraints are subject to the following restrictions: ■ None of the columns in the unique key can be of LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, REF, TIMESTAMP WITH TIME ZONE, or user-defined type. However, the unique key can contain a column of TIMESTAMP WITH LOCAL TIME ZONE. ■ A composite unique key cannot have more than 32 columns. ■ You cannot designate the same column or combination of columns as both a primary key and a unique key. ■ You cannot specify a unique key when creating a subview in an inheritance hierarchy. The unique key can be specified only for the top-level (root) view. Primary Key Constraints A primary key constraint designates a column as the primary key of a table or view. A composite primary key designates a combination of columns as the primary key. When you define a primary key constraint inline, you need only the PRIMARY KEY keywords. When you define a primary key constraint out of line, you must also specify one or more columns. You must define a composite primary key out of line. To satisfy a primary key constraint: ■ No primary key value can appear in more than one row in the table. ■ No column that is part of the primary key can contain a null. When you create a primary key constraint: ■ Oracle Database uses an existing index if it contains a unique set of values before enforcing the primary key constraint. The existing index can be defined as unique See Also: "Unique Key Example" on page 8-19 and Composite Unique Key Example on page 8-20
  • 502. constraint 8-10 Oracle Database SQL Language Reference or nonunique. When a DML operation is performed, the primary key constraint is enforced using this existing index. ■ If no existing index can be used, then Oracle Database generates a unique index. When you drop a primary key constraint: ■ If the primary key was created using an existing index, then the index is not dropped. ■ If the primary key was created using a system-generated index, then the index is dropped. Restrictions on Primary Key Constraints Primary constraints are subject to the following restrictions: ■ A table or view can have only one primary key. ■ None of the columns in the primary key can be LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type. However, the primary key can contain a column of TIMESTAMP WITH LOCAL TIME ZONE. ■ The size of the primary key cannot exceed approximately one database block. ■ A composite primary key cannot have more than 32 columns. ■ You cannot designate the same column or combination of columns as both a primary key and a unique key. ■ You cannot specify a primary key when creating a subview in an inheritance hierarchy. The primary key can be specified only for the top-level (root) view. Foreign Key Constraints A foreign key constraint (also called a referential integrity constraint) designates a column as the foreign key and establishes a relationship between that foreign key and a specified primary or unique key, called the referenced key. A composite foreign key designates a combination of columns as the foreign key. The table or view containing the foreign key is called the child object, and the table or view containing the referenced key is called the parent object. The foreign key and the referenced key can be in the same table or view. In this case, the parent and child tables are the same. If you identify only the parent table or view and omit the column name, then the foreign key automatically references the primary key of the parent table or view. The corresponding column or columns of the foreign key and the referenced key must match in order and data type. You can define a foreign key constraint on a single key column either inline or out of line. You must specify a composite foreign key and a foreign key on an attribute out of line. To satisfy a composite foreign key constraint, the composite foreign key must refer to a composite unique key or a composite primary key in the parent table or view, or the value of at least one of the columns of the foreign key must be null. You can designate the same column or combination of columns as both a foreign key and a primary or unique key. You can also designate the same column or combination of columns as both a foreign key and a cluster key. See Also: "Primary Key Example" on page 8-20 and "Composite Primary Key Example" on page 8-21
  • 503. constraint Common SQL DDL Clauses 8-11 You can define multiple foreign keys in a table or view. Also, a single column can be part of more than one foreign key. Restrictions on Foreign Key Constraints Foreign key constraints are subject to the following restrictions: ■ None of the columns in the foreign key can be of LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type. However, the primary key can contain a column of TIMESTAMP WITH LOCAL TIME ZONE. ■ The referenced unique or primary key constraint on the parent table or view must already be defined. ■ A composite foreign key cannot have more than 32 columns. ■ The child and parent tables must be on the same database. To enable referential integrity constraints across nodes of a distributed database, you must use database triggers. See CREATE TRIGGER on page 16-94. ■ If either the child or parent object is a view, then the constraint is subject to all restrictions on view constraints. See "View Constraints" on page 8-18. ■ You cannot define a foreign key constraint in a CREATE TABLE statement that contains an AS subquery clause. Instead, you must create the table without the constraint and then add it later with an ALTER TABLE statement. references_clause Foreign key constraints use the references_clause syntax. When you specify a foreign key constraint inline, you need only the references_ clause. When you specify a foreign key constraint out of line, you must also specify the FOREIGN KEY keywords and one or more columns. ON DELETE Clause The ON DELETE clause lets you determine how Oracle Database automatically maintains referential integrity if you remove a referenced primary or unique key value. If you omit this clause, then Oracle does not allow you to delete referenced key values in the parent table that have dependent rows in the child table. ■ Specify CASCADE if you want Oracle to remove dependent foreign key values. ■ Specify SET NULL if you want Oracle to convert dependent foreign key values to NULL. You cannot specify this clause for a virtual column, because the values in a virtual column cannot be updated directly. Rather, the values from which the virtual column are derived must be updated. Restriction on ON DELETE You cannot specify this clause for a view constraint. Check Constraints A check constraint lets you specify a condition that each row in the table must satisfy. To satisfy the constraint, each row in the table must make the condition either TRUE or unknown (due to a null). When Oracle evaluates a check constraint condition for a See Also: ■ Oracle Database Advanced Application Developer's Guide for more information on using constraints ■ "Foreign Key Constraint Example" on page 8-21 and "Composite Foreign Key Constraint Example" on page 8-22 See Also: "ON DELETE Example" on page 8-22
  • 504. constraint 8-12 Oracle Database SQL Language Reference particular row, any column names in the condition refer to the column values in that row. The syntax for inline and out-of-line specification of check constraints is the same. However, inline specification can refer only to the column (or the attributes of the column if it is an object column) currently being defined, whereas out-of-line specification can refer to multiple columns or attributes. Oracle does not verify that conditions of check constraints are not mutually exclusive. Therefore, if you create multiple check constraints for a column, design them carefully so their purposes do not conflict. Do not assume any particular order of evaluation of the conditions. Restrictions on Check Constraints Check constraints are subject to the following restrictions: ■ You cannot specify a check constraint for a view. However, you can define the view using the WITH CHECK OPTION clause, which is equivalent to specifying a check constraint for the view. ■ The condition of a check constraint can refer to any column in the table, but it cannot refer to columns of other tables. ■ Conditions of check constraints cannot contain the following constructs: – Subqueries and scalar subquery expressions – Calls to the functions that are not deterministic (CURRENT_DATE, CURRENT_ TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE, SYSDATE, SYSTIMESTAMP, UID, USER, and USERENV) – Calls to user-defined functions – Dereferencing of REF columns (for example, using the DEREF function) – Nested table columns or attributes – The pseudocolumns CURRVAL, NEXTVAL, LEVEL, or ROWNUM – Date constants that are not fully specified REF Constraints REF constraints let you describe the relationship between a column of type REF and the object it references. ref_constraint REF constraints use the ref_constraint syntax. You define a REF constraint either inline or out of line. Out-of-line specification requires you to specify the REF column or attribute you are further describing. ■ For ref_column, specify the name of a REF column of an object or relational table. ■ For ref_attribute, specify an embedded REF attribute within an object column of a relational table. See Also: ■ Chapter 7, "Conditions" for additional information and syntax ■ "Check Constraint Examples" on page 8-23 and "Attribute-Level Constraints Example" on page 8-25
  • 505. constraint Common SQL DDL Clauses 8-13 Both inline and out-of-line specification let you define a scope constraint, a rowid constraint, or a referential integrity constraint on a REF column. If the scope table or referenced table of the REF column has a primary-key-based object identifier, then the REF column is a user-defined REF column. SCOPE REF Constraints In a table with a REF column, each REF value in the column can conceivably reference a row in a different object table. The SCOPE clause restricts the scope of references to a single table, scope_table. The values in the REF column or attribute point to objects in scope_table, in which object instances of the same type as the REF column are stored. Specify the SCOPE clause to restrict the scope of references in the REF column to a single table. For you to specify this clause, scope_table must be in your own schema or you must have SELECT privileges on scope_table or SELECT ANY TABLE system privileges. You can specify only one scope table for each REF column. Restrictions on Scope Constraints Scope constraints are subject to the following restrictions: ■ You cannot add a scope constraint to an existing column unless the table is empty. ■ You cannot specify a scope constraint for the REF elements of a VARRAY column. ■ You must specify this clause if you specify AS subquery and the subquery returns user-defined REF data types. ■ You cannot subsequently drop a scope constraint from a REF column. Rowid REF Constraints Specify WITH ROWID to store the rowid along with the REF value in ref_column or ref_attribute. Storing the rowid with the REF value can improve the performance of dereferencing operations, but will also use more space. Default storage of REF values is without rowids. Restrictions on Rowid Constraints Rowid constraints are subject to the following restrictions: ■ You cannot define a rowid constraint for the REF elements of a VARRAY column. ■ You cannot subsequently drop a rowid constraint from a REF column. ■ If the REF column or attribute is scoped, then this clause is ignored and the rowid is not stored with the REF value. Referential Integrity Constraints on REF Columns The references_clause of the ref_constraint syntax lets you define a foreign key constraint on the REF column. This clause also implicitly restricts the scope of the See Also: ■ Oracle Database Object-Relational Developer's Guide for more information on REF data types ■ "Foreign Key Constraints" on page 8-10, and "REF Constraint Examples" on page 8-25 See Also: The function DEREF on page 5-63 for an example of dereferencing
  • 506. constraint 8-14 Oracle Database SQL Language Reference REF column or attribute to the referenced table. However, whereas a foreign key constraint on a non-REF column references an actual column in the parent table, a foreign key constraint on a REF column references the implicit object identifier column of the parent table. If you do not specify a constraint name, then Oracle generates a system name for the constraint of the form SYS_Cn. If you add a referential integrity constraint to an existing REF column that is already scoped, then the referenced table must be the same as the scope table of the REF column. If you later drop the referential integrity constraint, then the REF column will remain scoped to the referenced table. As is the case for foreign key constraints on other types of columns, you can use the references_clause alone for inline declaration. For out-of-line declaration you must also specify the FOREIGN KEY keywords plus one or more REF columns or attributes. Restrictions on Foreign Key Constraints on REF Columns Foreign key constraints on REF columns have the following additional restrictions: ■ Oracle implicitly adds a scope constraint when you add a referential integrity constraint to an existing unscoped REF column. Therefore, all the restrictions that apply for scope constraints also apply in this case. ■ You cannot specify a column after the object name in the references_clause. Specifying Constraint State As part of constraint definition, you can specify how and when Oracle should enforce the constraint. constraint_state You can use the constraint_state with both inline and out-of-line specification. Specify the clauses of constraint_state in the order shown, from top to bottom, and do not specify any clause more than once. DEFERRABLE Clause The DEFERRABLE and NOT DEFERRABLE parameters indicate whether or not, in subsequent transactions, constraint checking can be deferred until the end of the transaction using the SET CONSTRAINT(S) statement. If you omit this clause, then the default is NOT DEFERRABLE. ■ Specify NOT DEFERRABLE to indicate that in subsequent transactions you cannot use the SET CONSTRAINT[S] clause to defer checking of this constraint until the transaction is committed. The checking of a NOT DEFERRABLE constraint can never be deferred to the end of the transaction. If you declare a new constraint NOT DEFERRABLE, then it must be valid at the time the CREATE TABLE or ALTER TABLE statement is committed or the statement will fail. ■ Specify DEFERRABLE to indicate that in subsequent transactions you can use the SET CONSTRAINT[S] clause to defer checking of this constraint until a COMMIT statement is submitted. If the constraint check fails, then the database returns an error and the transaction is not committed. This setting in effect lets you disable the constraint temporarily while making changes to the database that might violate the constraint until all the changes are complete. See Also: Oracle Database Object-Relational Developer's Guide for more information on object identifiers
  • 507. constraint Common SQL DDL Clauses 8-15 You cannot alter the deferrability of a constraint. Whether you specify either of these parameters, or make the constraint NOT DEFERRABLE implicitly by specifying neither of them, you cannot specify this clause in an ALTER TABLE statement. You must drop the constraint and r