0% found this document useful (0 votes)
430 views1,167 pages

SQL Reference

This edition applies to version 7 of DB2 for os / 390 and z / OS, 5675-DB2. Make sure you are using the correct edition for the level of the product. This and other books in the library are periodically upd ated with technical changes.

Uploaded by

Tanooj Chowdary
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
430 views1,167 pages

SQL Reference

This edition applies to version 7 of DB2 for os / 390 and z / OS, 5675-DB2. Make sure you are using the correct edition for the level of the product. This and other books in the library are periodically upd ated with technical changes.

Uploaded by

Tanooj Chowdary
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1167

DB2 Universal Database for OS/390 and z/OS

SQL Reference
Version 7
SC26-9944-01

DB2 Universal Database for OS/390 and z/OS
SQL Reference
Version 7
SC26-9944-01

Second Edition, Softcopy Only (August 2001)
This edition applies to Version 7 of IBM DATABASE 2 Universal Database Server fo
r OS/390 and z/OS (DB2 for
OS/390 and z/OS), 5675-DB2, and to any subsequent releases until otherwise indic
ated in new editions. Make sure
you are using the correct edition for the level of the product.
This softcopy version is based on the printed edition of the book and includes t
he changes indicated in the printed
version by vertical bars. Additional changes made to this softcopy version of th
e book since the hardcopy book was
published are indicated by the hash (#) symbol in the left-hand margin. Editoria
l changes that have no technical
significance are not noted.
This and other books in the DB2 for OS/390 and z/OS library are periodically upd
ated with technical changes. These
updates are made available to licensees of the product on CD-ROM and on the Web
(currently at
www.ibm.com/software/data/db2/os390/library.html). Check these resources to ensu
re that you are using the most
current information.
© Copyright International Business Machines Corporation 1982, 2001. All rights res
erved.
US Government Users Restricted Rights – Use, duplication or disclosure restricted
by GSA ADP Schedule Contract
with IBM Corp.
Note
Before using this information and the product it supports, be sure to read the
general information under “Appendix H. Notices” on page 1117.
Contents
About this book . . . . . . . . . . . . . . . . . . . . . . . . xv
Who should read this book . . . . . . . . . . . . . . . . . . . . xv
Conventions and terminology used in this book . . . . . . . . . . . . . xv
Product terminology and citations . . . . . . . . . . . . . . . . . xv
Conventions for describing mixed data values . . . . . . . . . . . . xvi
SQL standards. . . . . . . . . . . . . . . . . . . . . . . . . xvi
How to read the syntax diagrams. . . . . . . . . . . . . . . . . . xvii
How to send your comments . . . . . . . . . . . . . . . . . . . xviii
Summary of changes to this book. . . . . . . . . . . . . . . . . xix
Chapter 1. DB2 concepts . . . . . . . . . . . . . . . . . . . . . 1
Structured query language . . . . . . . . . . . . . . . . . . . . . 2
Static SQL . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Dynamic SQL. . . . . . . . . . . . . . . . . . . . . . . . . 2
Deferred embedded SQL . . . . . . . . . . . . . . . . . . . . 2
Interactive SQL . . . . . . . . . . . . . . . . . . . . . . . . 3
DB2 Open Database Connectivity (ODBC) . . . . . . . . . . . . . . 3
DB2 access for Java (JDBC and SQLJ) . . . . . . . . . . . . . . . 3
Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Unique keys . . . . . . . . . . . . . . . . . . . . . . . . . 5
Primary keys . . . . . . . . . . . . . . . . . . . . . . . . . 5
Parent keys . . . . . . . . . . . . . . . . . . . . . . . . . 6
Foreign keys . . . . . . . . . . . . . . . . . . . . . . . . . 6
Constraints. . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Unique constraints . . . . . . . . . . . . . . . . . . . . . . . 6
Referential constaints . . . . . . . . . . . . . . . . . . . . . . 7
Check constraints . . . . . . . . . . . . . . . . . . . . . . . 9
Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Storage structures. . . . . . . . . . . . . . . . . . . . . . . . 10
Storage groups. . . . . . . . . . . . . . . . . . . . . . . . . 10
Databases . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Application processes, concurrency, and recovery . . . . . . . . . . . . 11
Locking, commit, and rollback . . . . . . . . . . . . . . . . . . 11
Unit of work . . . . . . . . . . . . . . . . . . . . . . . . . 12
Unit of recovery . . . . . . . . . . . . . . . . . . . . . . . 13
Rolling back work . . . . . . . . . . . . . . . . . . . . . . . 13
Packages and application plans. . . . . . . . . . . . . . . . . . . 14
Distributed data. . . . . . . . . . . . . . . . . . . . . . . . . 14
DRDA access . . . . . . . . . . . . . . . . . . . . . . . . 15
DB2 private protocol access . . . . . . . . . . . . . . . . . . . 16
Connection management for DRDA access and DB2 private protocol. . . . 17
Character conversion . . . . . . . . . . . . . . . . . . . . . . 20
Character sets and code pages. . . . . . . . . . . . . . . . . . 22
System CCSIDs . . . . . . . . . . . . . . . . . . . . . . . 23
Expanding conversions. . . . . . . . . . . . . . . . . . . . . 24
Contracting conversions . . . . . . . . . . . . . . . . . . . . 25
Other considerations for using UTF-8 and UTF-16. . . . . . . . . . . 25
© Copyright IBM Corp. 1982, 2001 iii
|
|
Chapter 2. Language elements . . . . . . . . . . . . . . . . . . 27
Characters . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Tokens. . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
SQL identifiers . . . . . . . . . . . . . . . . . . . . . . . . 32
Location identifiers . . . . . . . . . . . . . . . . . . . . . . 34
Host identifiers . . . . . . . . . . . . . . . . . . . . . . . . 34
Naming conventions . . . . . . . . . . . . . . . . . . . . . . . 34
Qualification of unqualified object names . . . . . . . . . . . . . . 39
Schemas and the SQL path . . . . . . . . . . . . . . . . . . . . 40
Aliases and synonyms . . . . . . . . . . . . . . . . . . . . . . 41
Authorization IDs and authorization-names. . . . . . . . . . . . . . . 42
Authorization IDs and schema names . . . . . . . . . . . . . . . 43
Authorization IDs and statement preparation . . . . . . . . . . . . . 43
Authorization IDs and dynamic SQL . . . . . . . . . . . . . . . . 43
Authorization IDs and remote execution. . . . . . . . . . . . . . . 46
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Character strings . . . . . . . . . . . . . . . . . . . . . . . 49
Graphic strings. . . . . . . . . . . . . . . . . . . . . . . . 52
Binary strings . . . . . . . . . . . . . . . . . . . . . . . . 53
Large objects (LOBs) . . . . . . . . . . . . . . . . . . . . . 53
Restrictions using long strings . . . . . . . . . . . . . . . . . . 54
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Datetime values . . . . . . . . . . . . . . . . . . . . . . . 56
Row ID values . . . . . . . . . . . . . . . . . . . . . . . . 60
Distinct types . . . . . . . . . . . . . . . . . . . . . . . . 60
Promotion of data types . . . . . . . . . . . . . . . . . . . . . 61
Casting between data types . . . . . . . . . . . . . . . . . . . . 62
Assignment and comparison . . . . . . . . . . . . . . . . . . . . 64
Numeric assignments . . . . . . . . . . . . . . . . . . . . . 66
String assignments . . . . . . . . . . . . . . . . . . . . . . 68
Datetime assignments . . . . . . . . . . . . . . . . . . . . . 70
Row ID assignments. . . . . . . . . . . . . . . . . . . . . . 71
Distinct type assignments . . . . . . . . . . . . . . . . . . . . 71
Numeric comparisons . . . . . . . . . . . . . . . . . . . . . 72
String comparisons . . . . . . . . . . . . . . . . . . . . . . 73
Datetime comparisons . . . . . . . . . . . . . . . . . . . . . 75
Row ID comparisons. . . . . . . . . . . . . . . . . . . . . . 75
Distinct type comparisons . . . . . . . . . . . . . . . . . . . . 75
Rules for result data types. . . . . . . . . . . . . . . . . . . . . 77
String operands . . . . . . . . . . . . . . . . . . . . . . . 77
Binary string operands . . . . . . . . . . . . . . . . . . . . . 78
Numeric operands. . . . . . . . . . . . . . . . . . . . . . . 78
Datetime operands . . . . . . . . . . . . . . . . . . . . . . 79
Row ID operands . . . . . . . . . . . . . . . . . . . . . . . 79
Distinct type operands . . . . . . . . . . . . . . . . . . . . . 79
Nullable attribute of a result . . . . . . . . . . . . . . . . . . . 79
Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Integer constants . . . . . . . . . . . . . . . . . . . . . . . 79
Floating-point constants . . . . . . . . . . . . . . . . . . . . 80
Decimal constants. . . . . . . . . . . . . . . . . . . . . . . 80
Character string constants. . . . . . . . . . . . . . . . . . . . 80
Datetime constants . . . . . . . . . . . . . . . . . . . . . . 81
Graphic string constants . . . . . . . . . . . . . . . . . . . . 81
Special registers . . . . . . . . . . . . . . . . . . . . . . . . 82
General rules for special registers. . . . . . . . . . . . . . . . . 83
iv SQL Reference
|
CURRENT APPLICATION ENCODING SCHEME . . . . . . . . . . . 85
CURRENT DATE . . . . . . . . . . . . . . . . . . . . . . . 86
CURRENT DEGREE. . . . . . . . . . . . . . . . . . . . . . 86
CURRENT LOCALE LC_CTYPE . . . . . . . . . . . . . . . . . 86
CURRENT OPTIMIZATION HINT . . . . . . . . . . . . . . . . . 87
CURRENT PACKAGESET . . . . . . . . . . . . . . . . . . . 87
CURRENT PATH . . . . . . . . . . . . . . . . . . . . . . . 88
CURRENT PRECISION . . . . . . . . . . . . . . . . . . . . 88
CURRENT RULES . . . . . . . . . . . . . . . . . . . . . . 89
CURRENT SERVER. . . . . . . . . . . . . . . . . . . . . . 90
CURRENT SQLID. . . . . . . . . . . . . . . . . . . . . . . 90
CURRENT TIME . . . . . . . . . . . . . . . . . . . . . . . 90
CURRENT TIMESTAMP . . . . . . . . . . . . . . . . . . . . 91
CURRENT TIMEZONE . . . . . . . . . . . . . . . . . . . . . 91
USER . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Inheriting special registers in a user-defined function or a stored procedure 92
Column names. . . . . . . . . . . . . . . . . . . . . . . . . 94
Qualified column names . . . . . . . . . . . . . . . . . . . . 95
Correlation names. . . . . . . . . . . . . . . . . . . . . . . 95
Column name qualifiers to avoid ambiguity . . . . . . . . . . . . . 96
Column name qualifiers in correlated references . . . . . . . . . . . 97
Resolution of column name qualifiers and column names . . . . . . . . 98
References to variables. . . . . . . . . . . . . . . . . . . . . . 99
References to host variables. . . . . . . . . . . . . . . . . . . . 99
Host variables in dynamic SQL . . . . . . . . . . . . . . . . . 101
References to LOB host variables . . . . . . . . . . . . . . . . 101
References to LOB locator variables . . . . . . . . . . . . . . . 102
References to stored procedure result sets . . . . . . . . . . . . . 102
References to result set locator variables. . . . . . . . . . . . . . 102
Host structures in PL/I, C, and COBOL . . . . . . . . . . . . . . . 103
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Types of functions . . . . . . . . . . . . . . . . . . . . . . 104
Function resolution . . . . . . . . . . . . . . . . . . . . . . 106
Function invocation. . . . . . . . . . . . . . . . . . . . . . 109
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 110
Without operators . . . . . . . . . . . . . . . . . . . . . . 111
With the concatenation operator . . . . . . . . . . . . . . . . . 111
With arithmetic operators. . . . . . . . . . . . . . . . . . . . 113
Arithmetic with two integer operands . . . . . . . . . . . . . . . 114
Arithmetic with an integer and a decimal operand. . . . . . . . . . . 114
Arithmetic with two decimal operands . . . . . . . . . . . . . . . 114
Arithmetic with floating-point operands. . . . . . . . . . . . . . . 116
Datetime operands and durations. . . . . . . . . . . . . . . . . 117
Datetime arithmetic in SQL . . . . . . . . . . . . . . . . . . . 118
Precedence of operations . . . . . . . . . . . . . . . . . . . 122
CASE expressions . . . . . . . . . . . . . . . . . . . . . . 123
CAST specification . . . . . . . . . . . . . . . . . . . . . . 125
Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Basic predicate . . . . . . . . . . . . . . . . . . . . . . . 129
Quantified predicate . . . . . . . . . . . . . . . . . . . . . 131
BETWEEN predicate . . . . . . . . . . . . . . . . . . . . . 133
EXISTS predicate . . . . . . . . . . . . . . . . . . . . . . 133
IN predicate . . . . . . . . . . . . . . . . . . . . . . . . 135
LIKE predicate . . . . . . . . . . . . . . . . . . . . . . . 136
NULL predicate . . . . . . . . . . . . . . . . . . . . . . . 143
Search conditions . . . . . . . . . . . . . . . . . . . . . . . 144
Contents v
|
|
|
|
Options affecting SQL. . . . . . . . . . . . . . . . . . . . . . 145
Precompiler options for dynamic statements. . . . . . . . . . . . . 147
Decimal point representation . . . . . . . . . . . . . . . . . . 147
Apostrophes and quotation marks in string delimiters . . . . . . . . . 148
Katakana characters for EBCDIC. . . . . . . . . . . . . . . . . 149
Mixed data in character strings . . . . . . . . . . . . . . . . . 149
Formatting of datetime strings . . . . . . . . . . . . . . . . . . 150
SQL standard language . . . . . . . . . . . . . . . . . . . . 150
Positioned updates of columns . . . . . . . . . . . . . . . . . 152
Chapter 3. Built-in functions. . . . . . . . . . . . . . . . . . . 153
Column functions . . . . . . . . . . . . . . . . . . . . . . . 158
AVG . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
COUNT . . . . . . . . . . . . . . . . . . . . . . . . . . 160
COUNT_BIG . . . . . . . . . . . . . . . . . . . . . . . . 161
MAX . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
MIN . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
STDDEV or STDDEV_POP. . . . . . . . . . . . . . . . . . . 165
STDDEV_SAMP. . . . . . . . . . . . . . . . . . . . . . . 166
SUM . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
VARIANCE, VAR, or VAR_POP . . . . . . . . . . . . . . . . . 168
VARIANCE_SAMP or VAR_SAMP . . . . . . . . . . . . . . . . 169
Scalar functions . . . . . . . . . . . . . . . . . . . . . . . . 170
ABS or ABSVAL . . . . . . . . . . . . . . . . . . . . . . . 171
ACOS. . . . . . . . . . . . . . . . . . . . . . . . . . . 172
ADD_MONTHS . . . . . . . . . . . . . . . . . . . . . . . 173
ASIN . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
ATAN. . . . . . . . . . . . . . . . . . . . . . . . . . . 176
ATANH . . . . . . . . . . . . . . . . . . . . . . . . . . 177
ATAN2 . . . . . . . . . . . . . . . . . . . . . . . . . . 178
BLOB. . . . . . . . . . . . . . . . . . . . . . . . . . . 179
CCSID_ENCODING . . . . . . . . . . . . . . . . . . . . . 180
CEIL or CEILING . . . . . . . . . . . . . . . . . . . . . . 181
CHAR. . . . . . . . . . . . . . . . . . . . . . . . . . . 182
CLOB. . . . . . . . . . . . . . . . . . . . . . . . . . . 188
COALESCE . . . . . . . . . . . . . . . . . . . . . . . . 189
CONCAT . . . . . . . . . . . . . . . . . . . . . . . . . 191
COS . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
COSH. . . . . . . . . . . . . . . . . . . . . . . . . . . 193
DATE. . . . . . . . . . . . . . . . . . . . . . . . . . . 194
DAY . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
DAYOFMONTH . . . . . . . . . . . . . . . . . . . . . . . 196
DAYOFWEEK. . . . . . . . . . . . . . . . . . . . . . . . 197
DAYOFWEEK_ISO . . . . . . . . . . . . . . . . . . . . . . 198
DAYOFYEAR . . . . . . . . . . . . . . . . . . . . . . . . 199
DAYS. . . . . . . . . . . . . . . . . . . . . . . . . . . 200
DBCLOB . . . . . . . . . . . . . . . . . . . . . . . . . 201
DECIMAL or DEC . . . . . . . . . . . . . . . . . . . . . . 202
DEGREES . . . . . . . . . . . . . . . . . . . . . . . . . 204
DIGITS . . . . . . . . . . . . . . . . . . . . . . . . . . 205
DOUBLE or DOUBLE_PRECISION. . . . . . . . . . . . . . . . 206
EXP . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
FLOAT . . . . . . . . . . . . . . . . . . . . . . . . . . 208
FLOOR . . . . . . . . . . . . . . . . . . . . . . . . . . 209
GRAPHIC . . . . . . . . . . . . . . . . . . . . . . . . . 210
HEX . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
vi SQL Reference
|
|
|
|
|
HOUR . . . . . . . . . . . . . . . . . . . . . . . . . . 214
IDENTITY_VAL_LOCAL . . . . . . . . . . . . . . . . . . . . 215
IFNULL . . . . . . . . . . . . . . . . . . . . . . . . . . 219
INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . 220
INTEGER or INT. . . . . . . . . . . . . . . . . . . . . . . 223
JULIAN_DAY . . . . . . . . . . . . . . . . . . . . . . . . 224
LAST_DAY. . . . . . . . . . . . . . . . . . . . . . . . . 225
LCASE or LOWER . . . . . . . . . . . . . . . . . . . . . . 226
LEFT . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
LENGTH. . . . . . . . . . . . . . . . . . . . . . . . . . 229
LN . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
LOCATE. . . . . . . . . . . . . . . . . . . . . . . . . . 231
LOG10 . . . . . . . . . . . . . . . . . . . . . . . . . . 233
LTRIM . . . . . . . . . . . . . . . . . . . . . . . . . . 234
MAX . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
MICROSECOND. . . . . . . . . . . . . . . . . . . . . . . 236
MIDNIGHT_SECONDS . . . . . . . . . . . . . . . . . . . . 237
MIN . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
MINUTE. . . . . . . . . . . . . . . . . . . . . . . . . . 239
MOD . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
MONTH . . . . . . . . . . . . . . . . . . . . . . . . . . 242
MULTIPLY_ALT . . . . . . . . . . . . . . . . . . . . . . . 243
NEXT_DAY. . . . . . . . . . . . . . . . . . . . . . . . . 244
NULLIF . . . . . . . . . . . . . . . . . . . . . . . . . . 245
POSSTR . . . . . . . . . . . . . . . . . . . . . . . . . 246
POWER . . . . . . . . . . . . . . . . . . . . . . . . . . 248
QUARTER . . . . . . . . . . . . . . . . . . . . . . . . . 249
RADIANS . . . . . . . . . . . . . . . . . . . . . . . . . 250
RAISE_ERROR . . . . . . . . . . . . . . . . . . . . . . . 251
RAND. . . . . . . . . . . . . . . . . . . . . . . . . . . 252
REAL. . . . . . . . . . . . . . . . . . . . . . . . . . . 253
REPEAT. . . . . . . . . . . . . . . . . . . . . . . . . . 254
REPLACE . . . . . . . . . . . . . . . . . . . . . . . . . 256
RIGHT . . . . . . . . . . . . . . . . . . . . . . . . . . 258
ROUND . . . . . . . . . . . . . . . . . . . . . . . . . . 260
ROUND_TIMESTAMP. . . . . . . . . . . . . . . . . . . . . 262
ROWID . . . . . . . . . . . . . . . . . . . . . . . . . . 264
RTRIM . . . . . . . . . . . . . . . . . . . . . . . . . . 265
SECOND . . . . . . . . . . . . . . . . . . . . . . . . . 266
SIGN . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
SIN. . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
SINH . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
SMALLINT . . . . . . . . . . . . . . . . . . . . . . . . . 270
SPACE . . . . . . . . . . . . . . . . . . . . . . . . . . 271
SQRT. . . . . . . . . . . . . . . . . . . . . . . . . . . 272
STRIP . . . . . . . . . . . . . . . . . . . . . . . . . . 273
SUBSTR. . . . . . . . . . . . . . . . . . . . . . . . . . 275
TAN . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
TANH. . . . . . . . . . . . . . . . . . . . . . . . . . . 278
TIME . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
TIMESTAMP . . . . . . . . . . . . . . . . . . . . . . . . 280
TIMESTAMP_FORMAT . . . . . . . . . . . . . . . . . . . . 281
TRANSLATE . . . . . . . . . . . . . . . . . . . . . . . . 282
TRUNCATE or TRUNC . . . . . . . . . . . . . . . . . . . . 285
TRUNC_TIMESTAMP. . . . . . . . . . . . . . . . . . . . . 286
UCASE or UPPER . . . . . . . . . . . . . . . . . . . . . . 287
Contents vii
|
|
|
|
|
|
|
|
|
VARCHAR . . . . . . . . . . . . . . . . . . . . . . . . . 288
VARCHAR_FORMAT . . . . . . . . . . . . . . . . . . . . . 292
VARGRAPHIC . . . . . . . . . . . . . . . . . . . . . . . 293
WEEK . . . . . . . . . . . . . . . . . . . . . . . . . . 296
WEEK_ISO. . . . . . . . . . . . . . . . . . . . . . . . . 297
YEAR. . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Chapter 4. Queries . . . . . . . . . . . . . . . . . . . . . . 299
Authorization . . . . . . . . . . . . . . . . . . . . . . . . . 300
subselect . . . . . . . . . . . . . . . . . . . . . . . . . . 301
select-clause . . . . . . . . . . . . . . . . . . . . . . . . 301
from-clause. . . . . . . . . . . . . . . . . . . . . . . . . 304
where-clause . . . . . . . . . . . . . . . . . . . . . . . . 310
group-by-clause . . . . . . . . . . . . . . . . . . . . . . . 311
having-clause . . . . . . . . . . . . . . . . . . . . . . . . 311
Examples of subselects . . . . . . . . . . . . . . . . . . . . 312
fullselect. . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Character conversion in unions and concatenations . . . . . . . . . . 318
Selecting the result CCSID . . . . . . . . . . . . . . . . . . . 318
Examples of fullselects . . . . . . . . . . . . . . . . . . . . 319
select-statement . . . . . . . . . . . . . . . . . . . . . . . . 321
order-by-clause . . . . . . . . . . . . . . . . . . . . . . . 322
read-only-clause . . . . . . . . . . . . . . . . . . . . . . . 323
update-clause. . . . . . . . . . . . . . . . . . . . . . . . 324
optimize-for-clause . . . . . . . . . . . . . . . . . . . . . . 324
with-clause . . . . . . . . . . . . . . . . . . . . . . . . . 325
queryno-clause . . . . . . . . . . . . . . . . . . . . . . . 326
fetch-first-clause . . . . . . . . . . . . . . . . . . . . . . . 326
Examples of select statements . . . . . . . . . . . . . . . . . 327
Chapter 5. Statements . . . . . . . . . . . . . . . . . . . . . 329
How SQL statements are invoked . . . . . . . . . . . . . . . . . 332
Embedding a statement in an application program . . . . . . . . . . 333
Dynamic preparation and execution. . . . . . . . . . . . . . . . 334
Static invocation of a SELECT statement. . . . . . . . . . . . . . 335
Dynamic invocation of a SELECT statement . . . . . . . . . . . . 335
Interactive invocation . . . . . . . . . . . . . . . . . . . . . 336
ALLOCATE CURSOR. . . . . . . . . . . . . . . . . . . . . . 338
ALTER DATABASE. . . . . . . . . . . . . . . . . . . . . . . 340
ALTER FUNCTION (external scalar) . . . . . . . . . . . . . . . . 343
ALTER FUNCTION (SQL scalar). . . . . . . . . . . . . . . . . . 359
ALTER INDEX . . . . . . . . . . . . . . . . . . . . . . . . 366
ALTER PROCEDURE (external) . . . . . . . . . . . . . . . . . . 378
ALTER PROCEDURE (SQL) . . . . . . . . . . . . . . . . . . . 389
ALTER STOGROUP . . . . . . . . . . . . . . . . . . . . . . 395
ALTER TABLE . . . . . . . . . . . . . . . . . . . . . . . . 398
ALTER TABLESPACE. . . . . . . . . . . . . . . . . . . . . . 419
ASSOCIATE LOCATORS . . . . . . . . . . . . . . . . . . . . 430
BEGIN DECLARE SECTION . . . . . . . . . . . . . . . . . . . 433
CALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
CLOSE . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
COMMENT. . . . . . . . . . . . . . . . . . . . . . . . . . 444
COMMIT. . . . . . . . . . . . . . . . . . . . . . . . . . . 451
CONNECT . . . . . . . . . . . . . . . . . . . . . . . . . . 453
CONNECT (Type 1) . . . . . . . . . . . . . . . . . . . . . . 456
CONNECT (Type 2) . . . . . . . . . . . . . . . . . . . . . . 462
viii SQL Reference
|
|
|
CREATE ALIAS . . . . . . . . . . . . . . . . . . . . . . . . 466
CREATE AUXILIARY TABLE . . . . . . . . . . . . . . . . . . . 468
CREATE DATABASE . . . . . . . . . . . . . . . . . . . . . . 471
CREATE DISTINCT TYPE . . . . . . . . . . . . . . . . . . . . 474
CREATE FUNCTION . . . . . . . . . . . . . . . . . . . . . . 481
CREATE FUNCTION (external scalar). . . . . . . . . . . . . . . . 482
CREATE FUNCTION (external table) . . . . . . . . . . . . . . . . 504
CREATE FUNCTION (sourced) . . . . . . . . . . . . . . . . . . 521
CREATE FUNCTION (SQL scalar) . . . . . . . . . . . . . . . . . 535
CREATE GLOBAL TEMPORARY TABLE. . . . . . . . . . . . . . . 545
CREATE INDEX . . . . . . . . . . . . . . . . . . . . . . . . 550
CREATE PROCEDURE (external) . . . . . . . . . . . . . . . . . 566
CREATE PROCEDURE (SQL) . . . . . . . . . . . . . . . . . . 584
CREATE STOGROUP. . . . . . . . . . . . . . . . . . . . . . 596
CREATE SYNONYM . . . . . . . . . . . . . . . . . . . . . . 599
CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . 601
CREATE TABLESPACE . . . . . . . . . . . . . . . . . . . . . 629
CREATE TRIGGER. . . . . . . . . . . . . . . . . . . . . . . 647
CREATE VIEW . . . . . . . . . . . . . . . . . . . . . . . . 658
DECLARE CURSOR . . . . . . . . . . . . . . . . . . . . . . 665
DECLARE GLOBAL TEMPORARY TABLE . . . . . . . . . . . . . . 672
DECLARE STATEMENT . . . . . . . . . . . . . . . . . . . . . 682
DECLARE TABLE . . . . . . . . . . . . . . . . . . . . . . . 683
DECLARE VARIABLE. . . . . . . . . . . . . . . . . . . . . . 685
DELETE. . . . . . . . . . . . . . . . . . . . . . . . . . . 688
DESCRIBE (prepared statement or table) . . . . . . . . . . . . . . 695
DESCRIBE CURSOR . . . . . . . . . . . . . . . . . . . . . . 702
DESCRIBE INPUT . . . . . . . . . . . . . . . . . . . . . . . 704
DESCRIBE PROCEDURE . . . . . . . . . . . . . . . . . . . . 706
DROP. . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
END DECLARE SECTION . . . . . . . . . . . . . . . . . . . . 721
EXECUTE . . . . . . . . . . . . . . . . . . . . . . . . . . 722
EXECUTE IMMEDIATE . . . . . . . . . . . . . . . . . . . . . 725
EXPLAIN . . . . . . . . . . . . . . . . . . . . . . . . . . 727
FETCH . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
FREE LOCATOR . . . . . . . . . . . . . . . . . . . . . . . 748
GRANT . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
GRANT (collection privileges) . . . . . . . . . . . . . . . . . . . 752
GRANT (database privileges) . . . . . . . . . . . . . . . . . . . 753
GRANT (distinct type or JAR privileges) . . . . . . . . . . . . . . . 755
GRANT (function or procedure privileges) . . . . . . . . . . . . . . 757
GRANT (package privileges) . . . . . . . . . . . . . . . . . . . 762
GRANT (plan privileges) . . . . . . . . . . . . . . . . . . . . . 764
GRANT (schema privileges) . . . . . . . . . . . . . . . . . . . 765
GRANT (system privileges). . . . . . . . . . . . . . . . . . . . 767
GRANT (table or view privileges). . . . . . . . . . . . . . . . . . 770
GRANT (use privileges) . . . . . . . . . . . . . . . . . . . . . 773
HOLD LOCATOR . . . . . . . . . . . . . . . . . . . . . . . 775
INCLUDE . . . . . . . . . . . . . . . . . . . . . . . . . . 776
INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
LABEL ON . . . . . . . . . . . . . . . . . . . . . . . . . . 784
LOCK TABLE . . . . . . . . . . . . . . . . . . . . . . . . . 786
OPEN. . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
PREPARE . . . . . . . . . . . . . . . . . . . . . . . . . . 792
RELEASE (connection) . . . . . . . . . . . . . . . . . . . . . 805
RELEASE SAVEPOINT . . . . . . . . . . . . . . . . . . . . . 808
Contents ix
|
|
RENAME . . . . . . . . . . . . . . . . . . . . . . . . . . 809
REVOKE. . . . . . . . . . . . . . . . . . . . . . . . . . . 811
REVOKE (collection privileges) . . . . . . . . . . . . . . . . . . 816
REVOKE (database privileges) . . . . . . . . . . . . . . . . . . 817
REVOKE (distinct type or JAR privileges). . . . . . . . . . . . . . . 819
REVOKE (function or procedure privileges) . . . . . . . . . . . . . . 821
REVOKE (package privileges). . . . . . . . . . . . . . . . . . . 826
REVOKE (plan privileges) . . . . . . . . . . . . . . . . . . . . 828
REVOKE (schema privileges) . . . . . . . . . . . . . . . . . . . 829
REVOKE (system privileges) . . . . . . . . . . . . . . . . . . . 831
REVOKE (table or view privileges) . . . . . . . . . . . . . . . . . 834
REVOKE (use privileges) . . . . . . . . . . . . . . . . . . . . 837
ROLLBACK . . . . . . . . . . . . . . . . . . . . . . . . . 839
SAVEPOINT . . . . . . . . . . . . . . . . . . . . . . . . . 842
SELECT. . . . . . . . . . . . . . . . . . . . . . . . . . . 844
SELECT INTO . . . . . . . . . . . . . . . . . . . . . . . . 845
SET CONNECTION . . . . . . . . . . . . . . . . . . . . . . 848
SET CURRENT APPLICATION ENCODING SCHEME. . . . . . . . . . 850
SET CURRENT DEGREE . . . . . . . . . . . . . . . . . . . . 851
SET CURRENT LOCALE LC_CTYPE . . . . . . . . . . . . . . . . 853
SET CURRENT OPTIMIZATION HINT. . . . . . . . . . . . . . . . 855
SET CURRENT PACKAGESET . . . . . . . . . . . . . . . . . . 856
SET CURRENT PRECISION . . . . . . . . . . . . . . . . . . . 858
SET CURRENT RULES . . . . . . . . . . . . . . . . . . . . . 859
SET CURRENT SQLID . . . . . . . . . . . . . . . . . . . . . 860
SET host-variable assignment. . . . . . . . . . . . . . . . . . . 862
SETPATH . . . . . . . . . . . . . . . . . . . . . . . . . . 865
SET transition-variable assignment . . . . . . . . . . . . . . . . . 868
SIGNAL SQLSTATE . . . . . . . . . . . . . . . . . . . . . . 871
UPDATE. . . . . . . . . . . . . . . . . . . . . . . . . . . 872
VALUES. . . . . . . . . . . . . . . . . . . . . . . . . . . 882
VALUES INTO . . . . . . . . . . . . . . . . . . . . . . . . 883
WHENEVER . . . . . . . . . . . . . . . . . . . . . . . . . 885
Chapter 6. SQL procedure statements . . . . . . . . . . . . . . . 887
SQL-procedure-statement . . . . . . . . . . . . . . . . . . . . 888
assignment-statement. . . . . . . . . . . . . . . . . . . . . . 889
CALL statement . . . . . . . . . . . . . . . . . . . . . . . . 891
CASE statement. . . . . . . . . . . . . . . . . . . . . . . . 893
compound-statement . . . . . . . . . . . . . . . . . . . . . . 895
GET DIAGNOSTICS statement . . . . . . . . . . . . . . . . . . 901
GOTO statement. . . . . . . . . . . . . . . . . . . . . . . . 902
IF statement . . . . . . . . . . . . . . . . . . . . . . . . . 904
LEAVE statement . . . . . . . . . . . . . . . . . . . . . . . 905
LOOP statement. . . . . . . . . . . . . . . . . . . . . . . . 906
REPEAT statement. . . . . . . . . . . . . . . . . . . . . . . 907
WHILE statement . . . . . . . . . . . . . . . . . . . . . . . 908
Appendix A. Limits in DB2 for OS/390 and z/OS . . . . . . . . . . . 909
Appendix B. Characteristics of SQL statements in DB2 for OS/390 and
z/OS . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
Actions allowed on SQL statements. . . . . . . . . . . . . . . . . 913
SQL statements allowed in external functions and stored procedures . . . . 916
SQL statements allowed in SQL procedures. . . . . . . . . . . . . . 918
x SQL Reference
|
|
|
Appendix C. SQLCA and SQLDA . . . . . . . . . . . . . . . . . 923
SQL communication area (SQLCA) . . . . . . . . . . . . . . . . . 923
Description of fields. . . . . . . . . . . . . . . . . . . . . . 923
The included SQLCA . . . . . . . . . . . . . . . . . . . . . 926
The REXX SQLCA . . . . . . . . . . . . . . . . . . . . . . 929
SQL descriptor area (SQLDA). . . . . . . . . . . . . . . . . . . 930
Field descriptions . . . . . . . . . . . . . . . . . . . . . . 932
Unrecognized and unsupported SQLTYPES. . . . . . . . . . . . . 941
The included SQLDA . . . . . . . . . . . . . . . . . . . . . 942
Identifying an SQLDA in C or C⁺⁺ . . . . . . . . . . . . . . . . 947
The REXX SQLDA . . . . . . . . . . . . . . . . . . . . . . 947
Appendix D. DB2 catalog tables . . . . . . . . . . . . . . . . . 949
Table spaces and indexes . . . . . . . . . . . . . . . . . . . . 950
SQL statements allowed on the catalog . . . . . . . . . . . . . . 955
Reorganizing the catalog. . . . . . . . . . . . . . . . . . . . 957
New and changed catalog tables. . . . . . . . . . . . . . . . . . 958
SYSIBM.IPNAMES table. . . . . . . . . . . . . . . . . . . . . 960
SYSIBM.LOCATIONS table. . . . . . . . . . . . . . . . . . . . 961
SYSIBM.LULIST table. . . . . . . . . . . . . . . . . . . . . . 962
SYSIBM.LUMODES table . . . . . . . . . . . . . . . . . . . . 963
SYSIBM.LUNAMES table . . . . . . . . . . . . . . . . . . . . 964
SYSIBM.MODESELECT table. . . . . . . . . . . . . . . . . . . 966
SYSIBM.SYSAUXRELS table . . . . . . . . . . . . . . . . . . . 967
SYSIBM.SYSCHECKDEP table . . . . . . . . . . . . . . . . . . 968
SYSIBM.SYSCHECKS table . . . . . . . . . . . . . . . . . . . 969
SYSIBM.SYSCHECKS2 table . . . . . . . . . . . . . . . . . . . 970
SYSIBM.SYSCOLAUTH table . . . . . . . . . . . . . . . . . . . 971
SYSIBM.SYSCOLDIST table . . . . . . . . . . . . . . . . . . . 972
SYSIBM.SYSCOLDIST_HIST table . . . . . . . . . . . . . . . . . 973
SYSIBM.SYSCOLDISTSTATS table. . . . . . . . . . . . . . . . . 974
SYSIBM.SYSCOLSTATS table. . . . . . . . . . . . . . . . . . . 975
SYSIBM.SYSCOLUMNS table. . . . . . . . . . . . . . . . . . . 976
SYSIBM.SYSCOLUMNS_HIST table . . . . . . . . . . . . . . . . 981
SYSIBM.SYSCONSTDEP table . . . . . . . . . . . . . . . . . . 983
SYSIBM.SYSCOPY table . . . . . . . . . . . . . . . . . . . . 984
SYSIBM.SYSDATABASE table . . . . . . . . . . . . . . . . . . 988
SYSIBM.SYSDATATYPES table . . . . . . . . . . . . . . . . . . 990
SYSIBM.SYSDBAUTH table . . . . . . . . . . . . . . . . . . . 991
SYSIBM.SYSDBRM table . . . . . . . . . . . . . . . . . . . . 993
SYSIBM.SYSDUMMY1 table . . . . . . . . . . . . . . . . . . . 995
SYSIBM.SYSFIELDS table . . . . . . . . . . . . . . . . . . . . 996
SYSIBM.SYSFOREIGNKEYS table . . . . . . . . . . . . . . . . . 997
SYSIBM.SYSINDEXES table . . . . . . . . . . . . . . . . . . . 998
SYSIBM.SYSINDEXES_HIST table . . . . . . . . . . . . . . . . 1001
SYSIBM.SYSINDEXPART table. . . . . . . . . . . . . . . . . . 1002
SYSIBM.SYSINDEXPART_HIST table . . . . . . . . . . . . . . . 1005
SYSIBM.SYSINDEXSTATS table . . . . . . . . . . . . . . . . . 1006
SYSIBM.SYSINDEXSTATS_HIST table . . . . . . . . . . . . . . . 1007
SYSIBM.SYSJARCLASS_SOURCE table . . . . . . . . . . . . . . 1008
SYSIBM.SYSJARCONTENTS table . . . . . . . . . . . . . . . . 1009
SYSIBM.SYSJARDATA table. . . . . . . . . . . . . . . . . . . 1010
SYSIBM.SYSJAROBJECTS table . . . . . . . . . . . . . . . . . 1011
SYSIBM.SYSJAVAOPTS table . . . . . . . . . . . . . . . . . . 1012
SYSIBM.SYSKEYCOLUSE table . . . . . . . . . . . . . . . . . 1013
SYSIBM.SYSKEYS table . . . . . . . . . . . . . . . . . . . . 1014
Contents xi
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SYSIBM.SYSLOBSTATS table . . . . . . . . . . . . . . . . . . 1015
SYSIBM.SYSLOBSTATS_HIST table. . . . . . . . . . . . . . . . 1016
SYSIBM.SYSPACKAGE table . . . . . . . . . . . . . . . . . . 1017
SYSIBM.SYSPACKAUTH table . . . . . . . . . . . . . . . . . . 1022
SYSIBM.SYSPACKDEP table . . . . . . . . . . . . . . . . . . 1023
SYSIBM.SYSPACKLIST table . . . . . . . . . . . . . . . . . . 1024
SYSIBM.SYSPACKSTMT table . . . . . . . . . . . . . . . . . . 1025
SYSIBM.SYSPARMS table . . . . . . . . . . . . . . . . . . . 1028
SYSIBM.SYSPKSYSTEM table . . . . . . . . . . . . . . . . . . 1030
SYSIBM.SYSPLAN table . . . . . . . . . . . . . . . . . . . . 1031
SYSIBM.SYSPLANAUTH table . . . . . . . . . . . . . . . . . . 1035
SYSIBM.SYSPLANDEP table . . . . . . . . . . . . . . . . . . 1036
SYSIBM.SYSPLSYSTEM table . . . . . . . . . . . . . . . . . . 1037
SYSIBM.SYSPROCEDURES table . . . . . . . . . . . . . . . . 1038
SYSIBM.SYSRELS table . . . . . . . . . . . . . . . . . . . . 1041
SYSIBM.SYSRESAUTH table . . . . . . . . . . . . . . . . . . 1042
SYSIBM.SYSROUTINEAUTH table . . . . . . . . . . . . . . . . 1043
SYSIBM.SYSROUTINES table . . . . . . . . . . . . . . . . . . 1044
SYSIBM.SYSROUTINES_OPTS table . . . . . . . . . . . . . . . 1050
SYSIBM.SYSROUTINES_SRC table . . . . . . . . . . . . . . . . 1051
SYSIBM.SYSSCHEMAAUTH table . . . . . . . . . . . . . . . . 1052
SYSIBM.SYSSEQUENCES table . . . . . . . . . . . . . . . . . 1053
SYSIBM.SYSSEQUENCESDEP table . . . . . . . . . . . . . . . 1054
SYSIBM.SYSSTMT table . . . . . . . . . . . . . . . . . . . . 1055
SYSIBM.SYSSTOGROUP table. . . . . . . . . . . . . . . . . . 1058
SYSIBM.SYSSTRINGS table. . . . . . . . . . . . . . . . . . . 1059
SYSIBM.SYSSYNONYMS table. . . . . . . . . . . . . . . . . . 1061
SYSIBM.SYSTABAUTH table . . . . . . . . . . . . . . . . . . 1062
SYSIBM.SYSTABCONST table . . . . . . . . . . . . . . . . . . 1064
SYSIBM.SYSTABLEPART table. . . . . . . . . . . . . . . . . . 1065
SYSIBM.SYSTABLEPART_HIST table . . . . . . . . . . . . . . . 1068
SYSIBM.SYSTABLES table . . . . . . . . . . . . . . . . . . . 1070
SYSIBM.SYSTABLES_HIST table . . . . . . . . . . . . . . . . . 1074
SYSIBM.SYSTABLESPACE table . . . . . . . . . . . . . . . . . 1075
SYSIBM.SYSTABSTATS table . . . . . . . . . . . . . . . . . . 1078
SYSIBM.SYSTABSTATS_HIST table . . . . . . . . . . . . . . . . 1079
SYSIBM.SYSTRIGGERS table . . . . . . . . . . . . . . . . . . 1080
SYSIBM.SYSUSERAUTH table. . . . . . . . . . . . . . . . . . 1081
SYSIBM.SYSVIEWDEP table . . . . . . . . . . . . . . . . . . 1084
SYSIBM.SYSVIEWS table. . . . . . . . . . . . . . . . . . . . 1085
SYSIBM.SYSVOLUMES table . . . . . . . . . . . . . . . . . . 1086
SYSIBM.USERNAMES table. . . . . . . . . . . . . . . . . . . 1087
Appendix E. Using the catalog in database design . . . . . . . . . 1089
Retrieving catalog information about DB2 storage groups . . . . . . . . 1089
Retrieving catalog information about a table . . . . . . . . . . . . . 1089
Retrieving catalog information about aliases . . . . . . . . . . . . . 1089
Retrieving catalog information about columns. . . . . . . . . . . . . 1090
Retrieving catalog information about indexes . . . . . . . . . . . . . 1091
Retrieving catalog information about views. . . . . . . . . . . . . . 1091
Retrieving catalog information about authorizations. . . . . . . . . . . 1091
Retrieving catalog information about parent keys . . . . . . . . . . . 1092
Retrieving catalog information about foreign keys . . . . . . . . . . . 1092
Retrieving catalog information about check pending . . . . . . . . . . 1093
Retrieving catalog information about table check constraints . . . . . . . 1093
Retrieving catalog information about LOBs. . . . . . . . . . . . . . 1093
xii SQL Reference
|
|
|
|
|
|
|
Retrieving catalog information about user-defined functions and stored
procedures . . . . . . . . . . . . . . . . . . . . . . . . 1094
Retrieving catalog information about triggers . . . . . . . . . . . . . 1094
Retrieving catalog information about distinct types . . . . . . . . . . . 1094
Adding and retrieving comments . . . . . . . . . . . . . . . . . 1095
Verifying the accuracy of the database definition . . . . . . . . . . . 1095
Appendix F. SQL reserved words . . . . . . . . . . . . . . . . 1097
Appendix G. Sample user-defined functions . . . . . . . . . . . . 1099
ALTDATE . . . . . . . . . . . . . . . . . . . . . . . . . . 1100
ALTTIME . . . . . . . . . . . . . . . . . . . . . . . . . . 1103
CURRENCY . . . . . . . . . . . . . . . . . . . . . . . . . 1105
DAYNAME . . . . . . . . . . . . . . . . . . . . . . . . . 1107
MONTHNAME . . . . . . . . . . . . . . . . . . . . . . . . 1108
TABLE_LOCATION . . . . . . . . . . . . . . . . . . . . . . 1109
TABLE_NAME . . . . . . . . . . . . . . . . . . . . . . . . 1111
TABLE_SCHEMA . . . . . . . . . . . . . . . . . . . . . . . 1113
WEATHER . . . . . . . . . . . . . . . . . . . . . . . . . 1115
Appendix H. Notices . . . . . . . . . . . . . . . . . . . . . 1117
Programming interface information. . . . . . . . . . . . . . . . . 1118
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . 1119
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . 1121
Bibliography . . . . . . . . . . . . . . . . . . . . . . . . 1141
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . .X-1
Contents xiii
xiv SQL Reference
About this book
This book is a reference for Structured Query Language (SQL) for DB2 Universal
Database™ Server for OS/390® (DB2® for OS/390) and z/OS.
Unless otherwise stated, references to SQL in this book imply SQL for DB2 for
OS/390 and z/OS, and all objects described in this book are objects of DB2 for
OS/390 and z/OS. The syntax and semantics of most SQL statements are
essentially the same in all IBM® relational database products, and the language
elements common to the products provide a base for the definition of IBM SQL.
Consult IBM SQL Reference if you intend to develop applications that adhere to
IBM SQL.
Important
In this version of DB2® for OS/390® and z/OS, some utility functions are
available as optional products. You must separately order and purchase a
license to such utilities, and discussion of those utility functions in this
publication is not intended to otherwise imply that you have a license to them.
Who should read this book
This book is intended for end users, application programmers, system and databas
e
administrators, and for persons involved in error detection and diagnosis.
This book is a reference rather than a tutorial. It assumes that you are already
familiar with Structured Query Language (SQL) programming concepts.
When you first use this book, consider reading Chapters 1 and 2 sequentially.
These chapters describe the basic concepts of relational databases and SQL, the
basic syntax of SQL, and the language elements that are common to many SQL
statements. The rest of the chapters and appendixes are designed for the quick
location of answers to specific SQL questions. They provide you with query forms
,
SQL statements, SQL procedure statements, DB2 limits, SQLCA, SQLDA, catalog
tables, and SQL reserved words.
Conventions and terminology used in this book
This section explains conventions and terminology used in this book.
Product terminology and citations
In this book, DB2 Universal Database™ Server for OS/390 and z/OS is referred to
as "DB2 for OS/390 and z/OS." In cases where the context makes the meaning
clear, DB2 for OS/390 and z/OS is referred to as "DB2." When this book refers to
other books in this library, a short title is used. (For example, "See DB2 SQL
Reference" is a citation to IBM® DATABASE 2™ Universal Database Server for
OS/390 and z/OS SQL Reference.)
When referring to a DB2 product other than DB2 for OS/390 and z/OS, this book
uses the product’s full name to avoid ambiguity.
The following terms are used as indicated:
© Copyright IBM Corp. 1982, 2001 xv
DB2 Represents either the DB2 licensed program or a particular DB2
subsystem.
C and C language
Represent the C programming language.
CICS® Represents CICS/ESA® and CICS Transaction Server for OS/390.
IMS™ Represents IMS or IMS/ESA®.
MVS Represents the MVS element of OS/390.
OS/390
Represents the OS/390 or z/OS operating system.
RACF®
Represents the functions that are provided by the RACF component of the
SecureWay® Security Server for OS/390 or by the RACF component of the
OS/390 Security Server.
Conventions for describing mixed data values
At sites using a double-byte character set (DBCS), character strings can include
a
mixture of single-byte and double-byte characters. When mixed data values are
shown in the examples, the following conventions apply:
SQL standards
The SQL99 ANSI/ISO standard is a replacement for SQL92. SQL99 includes many
new enhancements, such as object-relational capabilities, triggers, and many bui
lt-in
functions to aid in data analysis. DB2 family functionality that appears in the
SQL99
standard includes:
v SQL Extenders, comprised of text, image, and spatial extenders
v Extensions to SQL for online analytical processing and business intelligence
v Inclusion of federated database support in DB2 Universal Database for UNIX®,
Windows®, OS/2®
v Object-relational extensions (user-defined types, user-defined functions, meth
od,
and so on)
DB2 for OS/390 and z/OS conforms to the following standards for SQL:
v FIPS (Federal Information Processing Standards) publication 127-2, Database
Language SQL
xvi SQL Reference
v ANSI (American National Standards Institute) X3.135-1992, Database Language
SQL, Entry Level
v ISO (International Standards Organization) 9075-1992, Database Language SQL,
Entry Level
v IBM SQL Standards, Version 2
The ANSI and ISO documents are collectively referred to as SQL92. DB2 also
supports a subset of the SQL99 standard, which includes a large portion of the c
ore
standard items.
How to read the syntax diagrams
The following rules apply to the syntax diagrams used in this book:
v Read the syntax diagrams from left to right, from top to bottom, following the
path
of the line.
The ─── symbol indicates the beginning of a statement.
The ─── symbol indicates that the statement syntax is continued on the next
line.
The ─── symbol indicates that a statement is continued from the previous line.
The ─── symbol indicates the end of a statement.
v Required items appear on the horizontal line (the main path).
 required_item 
v Optional items appear below the main path.
 required_item
optional_item

If an optional item appears above the main path, that item has no effect on the
execution of the statement and is used only for readability.

optional_item
required_item 
v If you can choose from two or more items, they appear vertically, in a stack.
If you must choose one of the items, one item of the stack appears on the main
path.
 required_item required_choice1
required_choice2

If choosing one of the items is optional, the entire stack appears below the mai
n
path.
 required_item
optional_choice1
optional_choice2

About this book xvii
If one of the items is the default, it appears above the main path and the
remaining choices are shown below.
 required_item
default_choice
optional_choice
optional_choice

v An arrow returning to the left, above the main line, indicates an item that ca
n be
repeated.
 required_item  repeatable_item 
If the repeat arrow contains a comma, you must separate repeated items with a
comma.
 required_item 
,
repeatable_item 
A repeat arrow above a stack indicates that you can repeat the items in the
stack.
v Keywords appear in uppercase (for example, FROM). They must be spelled exactly
as shown. Variables appear in all lowercase letters (for example, column-name).
They represent user-supplied names or values.
v If punctuation marks, parentheses, arithmetic operators, or other such symbols
are shown, you must enter them as part of the syntax.
How to send your comments
Your feedback helps IBM to provide quality information. Please send any comments
that you have about this book or other DB2 for OS/390 and z/OS documentation.
You can use any of the following methods to provide comments:
v Send your comments by e-mail to [email protected] and include the name
of the product, the version number of the product, and the number of the book. I
f
you are commenting on specific text, please list the location of the text (for
example, a chapter and section title, page number, or a help topic title).
v Send your comments from the Web. Visit the Web site at:
http://www.ibm.com/software/db2os390
The Web site has a feedback page that you can use to send comments.
v Complete the readers’ comment form at the back of the book and return it by
mail, by fax (800-426-7773 for the United States and Canada), or by giving it to
an IBM representative.
xviii SQL Reference
Summary of changes to this book
The major changes to this book are:
Chapter 1. DB2 concepts includes new descriptions of constraints and character
conversion, including Unicode information.
Chapter 2. Language elements contains numerous changes to descriptions of
data types, expressions, and predicates. The chapter also contains the descripti
ons
of a new special register (CURRENT APPLICATION ENCODING SCHEME).
Chapter 3. Built-in functions includes descriptions of over 60 built-in function
s.
(See Table 28 on page 153 for a list and brief description of all the functions.
)
Chapter 4. Queries contains changes for fullselect and the select statement.
Chapter 5. Statements includes many new statements, as well as changed
statements. The new statements are:
“ALTER FUNCTION (SQL scalar)” on page 359
“CREATE FUNCTION (SQL scalar)” on page 535
“DECLARE VARIABLE” on page 685
“SET CURRENT APPLICATION ENCODING SCHEME” on page 850
“SET host-variable assignment” on page 862
“SET transition-variable assignment” on page 868
Statements with new clauses, new values for existing clauses, or other changes
include:
“ALTER FUNCTION (external scalar)” on page 343
“ALTER PROCEDURE (external)” on page 378
“ALTER PROCEDURE (SQL)” on page 389
“ALTER STOGROUP” on page 395
“ALTER TABLE” on page 398
“CALL” on page 434
“COMMENT” on page 444
“CONNECT (Type 1)” on page 456
“CONNECT (Type 2)” on page 462
“CREATE FUNCTION” on page 481
“CREATE FUNCTION (external table)” on page 504
“CREATE GLOBAL TEMPORARY TABLE” on page 545
“CREATE INDEX” on page 550
“CREATE PROCEDURE (external)” on page 566
“CREATE PROCEDURE (SQL)” on page 584
“CREATE STOGROUP” on page 596
“CREATE TABLE” on page 601
“CREATE TABLESPACE” on page 629
“CREATE VIEW” on page 658
“DECLARE CURSOR” on page 665
“DECLARE GLOBAL TEMPORARY TABLE” on page 672
“DELETE” on page 688
“EXECUTE IMMEDIATE” on page 725
“FETCH” on page 739
“GRANT (distinct type or JAR privileges)” on page 755
“GRANT (package privileges)” on page 762
“GRANT (schema privileges)” on page 765
“INSERT” on page 778
© Copyright IBM Corp. 1982, 2001 xix
“OPEN” on page 788
“PREPARE” on page 792
“REVOKE (distinct type or JAR privileges)” on page 819
“SELECT INTO” on page 845
“SET PATH” on page 865
“UPDATE” on page 872
Chapter 6. SQL procedure statements includes changes to statements that can
be used in SQL procedures.
Appendix C. SQLCA and SQLDA describes changes to the SQLDA to support
LOBs and distinct types.
Appendix D. DB2 catalog tables includes descriptions of several new catalog
tables. (See “New and changed catalog tables” on page 958 for a summary of all
catalog table changes.)
xx SQL Reference
Chapter 1. DB2 concepts
Structured query language . . . . . . . . . . . . . . . . . . . . . 2
Static SQL . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Dynamic SQL. . . . . . . . . . . . . . . . . . . . . . . . . 2
Deferred embedded SQL . . . . . . . . . . . . . . . . . . . . 2
Interactive SQL . . . . . . . . . . . . . . . . . . . . . . . . 3
DB2 Open Database Connectivity (ODBC) . . . . . . . . . . . . . . 3
DB2 access for Java (JDBC and SQLJ) . . . . . . . . . . . . . . . 3
Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Unique keys . . . . . . . . . . . . . . . . . . . . . . . . . 5
Primary keys . . . . . . . . . . . . . . . . . . . . . . . . . 5
Parent keys . . . . . . . . . . . . . . . . . . . . . . . . . 6
Foreign keys . . . . . . . . . . . . . . . . . . . . . . . . . 6
Constraints. . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Unique constraints . . . . . . . . . . . . . . . . . . . . . . . 6
Referential constaints . . . . . . . . . . . . . . . . . . . . . . 7
Check constraints . . . . . . . . . . . . . . . . . . . . . . . 9
Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Storage structures. . . . . . . . . . . . . . . . . . . . . . . . 10
Storage groups. . . . . . . . . . . . . . . . . . . . . . . . . 10
Databases . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Application processes, concurrency, and recovery . . . . . . . . . . . . 11
Locking, commit, and rollback . . . . . . . . . . . . . . . . . . 11
Unit of work . . . . . . . . . . . . . . . . . . . . . . . . . 12
Unit of recovery . . . . . . . . . . . . . . . . . . . . . . . 13
Rolling back work . . . . . . . . . . . . . . . . . . . . . . . 13
Rolling back all changes . . . . . . . . . . . . . . . . . . . 13
Rolling back selected changes using savepoints . . . . . . . . . . 13
Packages and application plans. . . . . . . . . . . . . . . . . . . 14
Distributed data. . . . . . . . . . . . . . . . . . . . . . . . . 14
DRDA access . . . . . . . . . . . . . . . . . . . . . . . . 15
DB2 private protocol access . . . . . . . . . . . . . . . . . . . 16
Connection management for DRDA access and DB2 private protocol. . . . 17
SQL connection states . . . . . . . . . . . . . . . . . . . . 18
Application process connection states . . . . . . . . . . . . . . 19
DB2 private connections . . . . . . . . . . . . . . . . . . . 20
When a connection is ended. . . . . . . . . . . . . . . . . . 20
Character conversion . . . . . . . . . . . . . . . . . . . . . . 20
Character sets and code pages. . . . . . . . . . . . . . . . . . 22
System CCSIDs . . . . . . . . . . . . . . . . . . . . . . . 23
Expanding conversions. . . . . . . . . . . . . . . . . . . . . 24
Contracting conversions . . . . . . . . . . . . . . . . . . . . 25
Other considerations for using UTF-8 and UTF-16. . . . . . . . . . . 25
© Copyright IBM Corp. 1982, 2001 1
|
|
Structured query language
Structured query language (SQL) is a standardized language for defining and
manipulating data in a relational database. In accordance with the relational mo
del
of data, the database is perceived as a set of tables, relationships are represe
nted
by values in tables, and data is retrieved by specifying a result table that can
be
derived from one or more tables. DB2 for OS/390 and z/OS transforms the
specification of a result table into a sequence of internal operations that opti
mize
data retrieval. This transformation occurs when the SQL statement is prepared. T
his
transformation is also known as binding.
All executable SQL statements must be prepared before they can be executed. The
result of preparation is the executable or operational form of the statement. Th
e
method of preparing an SQL statement and the persistence of its operational form
distinguish static SQL from dynamic SQL.
Static SQL
The source form of a static SQL statement is embedded within an application
program written in a host language such as COBOL. The statement is prepared
before the program is executed and the operational form of the statement persist
s
beyond the execution of the program.
Static SQL statements in a source program must be processed before the program
is compiled. This processing can be accomplished through the DB2 precompiler or
the SQL statement coprocessor. The DB2 precompiler or the coprocessor checks
the syntax of the SQL statements, turns them into host language comments, and
generates host language statements to invoke DB2.
The preparation of an SQL application program includes precompilation, the
preparation of its static SQL statements, and compilation of the modified source
program, as described in Part 5 of DB2 Application Programming and SQL Guide.
Dynamic SQL
Programs that contain embedded dynamic SQL statements must be precompiled
like those that contain static SQL, but unlike static SQL, the dynamic statement
s
are constructed and prepared at run time. The source form of a dynamic statement
is a character string that is passed to DB2 by the program using the static SQL
statement PREPARE or EXECUTE IMMEDIATE. Whether the operational form of
the statement is persistent depends on whether dynamic statement caching is
enabled. For details on dynamic statement caching, see Part 6 of DB2 Application
Programming and SQL Guide.
You can execute some SQL statements dynamically with the EXEC SQL utility
control statement. See Part 2 of DB2 Utility Guide and Reference.
Deferred embedded SQL
A deferred embedded SQL statement is neither fully static nor fully dynamic. Lik
e a
static statement, it is embedded within an application, but like a dynamic state
ment,
it is prepared during the execution of the application. Although prepared at run
time,
a deferred embedded SQL statement is processed with bind-time rules such that
the authorization ID and qualifier determined at bind time for the plan or packa
ge
owner are used. Deferred embedded SQL statements are used for DB2 private
protocol access to remote data.
DB2 Concepts
2 SQL Reference
|
|
|
|
|
#
#
Interactive SQL
In this book, interactive SQL refers to SQL statements submitted to SPUFI (SQL
processor using file input). SPUFI prepares and executes these statements
dynamically. For more details about using SPUFI, see Part 1 of DB2 Application
Programming and SQL Guide.
DB2 Open Database Connectivity (ODBC)
DB2 Open Database Connectivity (DB2 ODBC) is an alternative to using embedded
static or dynamic SQL. DB2 ODBC is an application programming interface in which
functions are provided to application programs to process SQL statements. The
function calls are available only for C and C⁺⁺ application programs. Through the
interface, the application invokes a C function at execution time to connect to
the
data source, to issue SQL statements, and to get returned data and status
information. Unlike using embedded SQL, no precompilation is required.
Applications developed using this interface might be executed on a variety of da
ta
sources without being compiled against each of the databases. Note that only C
and C⁺⁺ applications can use this interface.
DB2 ODBC provides a consistent interface to query and retrieve system catalog
information across the DB2 family of database management systems. This reduces
the need to write catalog queries that are specific to each database server. DB2
ODBC can return result sets to those programs.
The DB2 ODBC Guide and Reference describes the APIs supported with this
interface.
DB2 access for Java (JDBC and SQLJ)
JavaSoft™ JDBC and SQLJ are two methods for accessing DB2 data from the
Java® programming language. In general, Java applications use JDBC for dynamic
SQL and SQLJ for static SQL.
JDBC is an application programming interface (API) that Java applications can us
e
to access any relational database. JDBC is similar to ODBC and is based on the
X/Open SQL Call Level Interface specification.
SQLJ is an API that provides support for embedded static SQL in Java application
s.
Because DB2 for OS/390 SQLJ support includes JDBC, SQLJ applications can also
execute dynamic SQL statements through JDBC.
The DB2 Application Programming Guide and Reference for Java describes the
APIs supported with these interfaces.
Schemas
A schema is a collection of named objects. The objects that a schema can contain
include distinct types, functions, stored procedures, and triggers. An object is
assigned to a schema when it is created.
The schema name of the object determines the schema to which the object
belongs. When a distinct type, function, or trigger is created, it is given a qu
alified,
two-part name. The first part is the schema name (or the qualifier), which is ei
ther
implicitly or explicitly specified. The second part is the name of the object. W
hen a
stored procedure is created, it is given a three-part name. The first part is a
location
DB2 Concepts
Chapter 1. DB2 concepts 3
name, which is implicitly or explicitly specified, the second part is the schema
name,
which is implicitly or explicitly specified, and the third part is the name of t
he object.
Schemas extend the concept of qualifiers for tables, views, indexes, and aliases
to
enable the qualifiers for distinct types, functions, stored procedures, and trig
gers to
be called schema names.
Tables
Tables are logical structures maintained by DB2. Tables are made up of columns
and rows. There is no inherent order of the rows within a table. At the intersec
tion
of every column and row is a specific data item called a value. A column is a se
t of
values of the same type. A row is a sequence of values such that the nth value i
s a
value of the nth column of the table. Every table must have one or more columns,
but the number of rows can be zero.
Some types of tables include:
base table
A table created with the SQL statement CREATE TABLE and used to hold
persistent user data.
auxiliary table
A table created with the SQL statement CREATE AUXILIARY TABLE and
used to hold the data for a column that is defined in a base table.
temporary table
A table defined by either the SQL statement CREATE GLOBAL
TEMPORARY TABLE (a created temporary table) or DECLARE GLOBAL
TEMPORARY TABLE (a declared temporary table) and used to hold data
temporarily, such as the intermediate results of SQL transactions. Both
created temporary tables and declared temporary tables persist only as
long as the application process. The description of a created temporary
table is stored in the DB2 catalog and the description is shareable across
application processes while the description of a declared temporary table is
neither stored nor shareable. Thus, each application process might refer to
the same declared temporary table but have its own unique description of it.
For a complete comparison of the two types of temporary tables, including
how they differ from base tables, see Part 2 (Volume 1) of DB2
Administration Guide.
result table
A set of rows that DB2 selects or generates from one or more base tables.
empty table
A table with zero rows.
sample table
One of several tables sent with the DB2 licensed program that contains
sample data. Many examples in this book are based on sample tables. See
Appendix A of DB2 Application Programming and SQL Guide for a
description of the sample tables.
DB2 Concepts
4 SQL Reference
Indexes
An index is an ordered set of pointers to rows of a base table or an auxiliary t
able.
Each index is based on the values of data in one or more columns. An index is an
object that is separate from the data in the table. When you define an index usi
ng
the CREATE INDEX statement, DB2 builds this structure and maintains it
automatically.
Indexes can be used by DB2 to improve performance and ensure uniqueness. In
most cases, access to data is faster with an index. A table with a unique index
cannot have rows with identical keys. For more details on designing indexes and
on
their uses, see An Introduction to DB2 for OS/390.
Keys
A key is one or more columns that are identified as such in the description of a
table, an index, or a referential constraint. Referential constraints are descri
bed in .
The same column can be part of more than one key. A key composed of more than
one column is called a composite key.
A composite key is an ordered set of columns of the same table. The ordering of
the columns is not constrained by their ordering within the table. The term valu
e,
when used with respect to a composite key, denotes a composite value. Thus, a
rule, such as “the value of the foreign key must be equal to the value of the pare
nt
key”, means that each component of the value of the foreign key must be equal to
the corresponding component of the value of the parent key.
Unique keys
A unique key is a key that is constrained so that no two of its values are equal
. DB2
enforces the constraint during the execution of the LOAD utility and the SQL
INSERT and UPDATE statements. The mechanism used to enforce the constraint is
a unique index. Thus, every unique key is a key of a unique index. Such an index
is
also said to have the UNIQUE attribute.
The columns of a unique key cannot contain null values.
A unique key can be defined using the UNIQUE clause of the CREATE TABLE or
ALTER TABLE statement. When a unique key is defined in a CREATE TABLE
statement, the table is marked unavailable until the unique index is created by
the
user. However, if the CREATE TABLE statement is processed by the schema
processor, DB2 automatically creates the unique index. When a unique key is
defined in an ALTER TABLE statement, a unique index must already exist on the
columns of that unique key.
Primary keys
A primary key is a unique key that is a part of the definition of a table. A tab
le can
have only one primary key, and the columns of a primary key cannot contain null
values. Primary keys are optional and can be defined in CREATE TABLE or ALTER
TABLE statements.
The unique index on a primary key is called a primary index. When a primary key
is
defined in a CREATE TABLE statement, the table is marked unavailable until the
primary index is created by the user unless the CREATE TABLE statement is
processed by the schema processor. In that case, DB2 automatically creates the
primary index.
DB2 Concepts
Chapter 1. DB2 concepts 5
|
|
|
|
|
|
|
|
|
|
|
|
When a primary key is defined in an ALTER TABLE statement, a unique index must
already exist on the columns of that primary key. This unique index is designate
d as
the primary index.
Parent keys
A parent key is either a primary key or a unique key in the parent table of a
referential constraint. The values of a parent key determine the valid values of
the
foreign key in the constraint.
Foreign keys
A foreign key is a key that is specified in the definition of a referential cons
traint
using the CREATE or ALTER statement. A foreign key refers to or is related to a
specific parent key. A table can have zero or more foreign keys. The value of a
composite foreign key is null if any component of the value is null.
Constraints
Constraints are rules that control values in columns to prevent duplicate values
or
set restrictions on data added to a table.
Constraints fall into the following three types:
v A unique constraint is a rule that prevents duplicate values in one or more
columns in a table. Unique constraints are unique and primary keys. For
example, a unique constraint could be defined on a supplier identifier in a
supplier table to ensure that the same supplier identifier applies to one single
supplier.
v A referential constraint is a rule about values in one or more columns in one
or
more tables. For example, for a set of tables sharing information about a
corporation’s suppliers, a supplier’s ID may change. A referential constraint could
be defined stating that the ID of the supplier in the table must match a supplie
r
ID in the supplier information. If the new ID for the supplier is in the supplie
r
information, this constraint prevents inserts, updates, or deletes caused by
missing supplier information.
v A check constraint sets restrictions on data added to a specific table. For
example, the constraint could be added to define a salary level for an employee
to never be less than a stated amount when salary data is added or updated in a
table for personnel information.
Unique constraints
A unique constraint is a rule that the values of a key are valid only if they ar
e
unique in a table. Unique constraints are optional and can be defined in the
CREATE TABLE or ALTER TABLE statements with the PRIMARY KEY clause or
the UNIQUE clause. The columns specified in a unique constraint must be defined
as NOT NULL. A unique index enforces the uniqueness of the key during changes
to the columns of the unique constraint.
A table can have an arbitrary number of unique constraints, with at most one uni
que
constraint defined as a primary key. A table cannot have more than one unique
constraint on the same set of columns.
A unique constraint that is referenced by the foreign key of a referential const
raint is
called the parent key.
DB2 Concepts
6 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Referential constaints
Referential integrity is the state in which all values of all foreign keys at a
given
DB2 are valid. A referential constraint is the rule that the non-null values of
a foreign
key are valid only if they also appear as values of a parent key. The table that
contains the parent key is called the parent table of the referential constraint
, and
the table that contains the foreign key is a dependent of that table.
Referential constraints are optional and can be defined using CREATE TABLE and
ALTER TABLE statements. Refer to Part 2 (Volume 1) of DB2 Administration Guide
for examples.
DB2 enforces referential constraints when:
v An INSERT statement is applied to a dependent table.
v An UPDATE statement is applied to a foreign key of a dependent table.
v An UPDATE statement is applied to the parent key of a parent table.
v A DELETE statement is applied to a parent table. All affected referential
constraints and all delete rules of all affected relationships must be satisfied
in
order for the delete operation to succeed.
v The LOAD utility with the ENFORCE CONSTRAINTS option is run on a
dependent table.
The order in which referential constraints are enforced is undefined. To ensure
that
the order does not affect the result of the operation, there are restrictions on
the
definition of delete rules and on the use of certain statements. The restriction
s are
specified in the descriptions of the SQL statements CREATE TABLE, ALTER
TABLE, INSERT, UPDATE, and DELETE.
The rules of referential integrity involve the following concepts and terminolog
y:
parent key
A primary key or a unique key of a referential constraint.
parent table
A table that is a parent in at least one referential constraint. A table can be
defined as a parent in an arbitrary number of referential constraints.
dependent table
A table that is a dependent in at least one referential constraint. A table can
be defined as a dependent in an arbitrary number of referential constraints.
A dependent table can also be a parent table.
descendent table
A table that is a dependent of another table or a table that is a dependent
of a descendent table.
referential cycle
A set of referential constraints in which each associated table is a
descendent of itself.
parent row
A row that has at least one dependent row.
dependent row
A row that has at least one parent row.
descendent row
A row that is dependent on another row or a row that is a dependent of a
descendent row.
DB2 Concepts
Chapter 1. DB2 concepts 7
self-referencing row
A row that is a parent of itself.
self-referencing table
A table that is both parent and dependent in the same referential constraint.
The constraint is called a self-referencing constraint.
The following rules provide referential integrity:
insert rule
A non-null insert value of the foreign key must match some value of the
parent key of the parent table.
update rule
A non-null update value of the foreign key must match some value of the
parent key of the parent table.
delete rule
The choices when the referential constraint is defined are RESTRICT, NO
ACTION, CASCADE, or SET NULL. SET NULL can be specified only if
some column of the foreign key allows null values.
The delete rule of a referential constraint applies when a row of the parent tab
le is
deleted. More precisely, the rule applies when a row of the parent table is the
object
of a delete or propagated delete operation and that row has dependents in the
dependent table of the referential constraint. Let P denote the parent table, le
t D
denote the dependent table, and let p denote a parent row that is the object of
a
delete or propagated delete operation. If the delete rule is:
v RESTRICT or NO ACTION, an error occurs and no rows are deleted.
v CASCADE, the delete operation is propagated to the dependent rows of p in D.
v SET NULL, each nullable column of the foreign key of each dependent row of p
in D is set to null.
Each referential constraint in which a table is a parent has its own delete rule
, and
all applicable delete rules are used to determine the result of a delete operati
on.
Thus, a row cannot be deleted if it has dependents in a referential constraint w
ith a
delete rule of RESTRICT or NO ACTION or the deletion cascades to any of its
descendents that are dependents in a referential constraint with the delete rule
of
RESTRICT or NO ACTION.
The deletion of a row from parent table P involves other tables and can affect r
ows
of these tables:
v If D is a dependent of P and the delete rule is RESTRICT or NO ACTION, D is
involved in the operation but is not affected by the operation.
v If D is a dependent of P and the delete rule is SET NULL, D is involved in the
operation and rows of D might be updated during the operation.
v If D is a dependent of P and the delete rule is CASCADE, D is involved in the
operation and rows of D might be deleted during the operation. If rows of D are
deleted, the delete operation on P is said to be propagated to D. If D is also a
parent table, the actions described in this list apply, in turn, to the dependen
ts of
D.
Any table that can be involved in a delete operation on P is said to be
delete-connected to P. Thus, a table is delete-connected to table P if it is a
dependent of P or a dependent of a table to which delete operations from P
cascade.
DB2 Concepts
8 SQL Reference
Check constraints
A check constraint is a rule that specifies the values allowed in one or more
columns of every row of a table. Check constraints are optional and can be defin
ed
using the SQL statements CREATE TABLE and ALTER TABLE. The definition of a
check constraint is a restricted form of a search condition. One of the restrict
ions is
that a column name in a check constraint on table T must identify a column of T.
See Part 2 of DB2 Application Programming and SQL Guide for examples.
A table can have an arbitrary number of check constraints. DB2 enforces the
constraints when:
v A row is inserted into the table.
v A row of the table is updated.
v The LOAD utility with the ENFORCE CONSTRAINTS option is used to populate
the table.
A check constraint is enforced by applying its search condition to each row that
is
inserted, updated, or loaded. An error occurs if the result of the search condit
ion is
false for any row.
Triggers
A trigger defines a set of actions that are executed when a delete, insert, or u
pdate
operation occurs on a specified table. When such an SQL operation is executed,
the trigger is said to be activated.
Triggers can be used along with referential constraints and check constraints to
enforce data integrity rules. Triggers are more powerful than constraints becaus
e
they can also be used to cause updates to other tables, automatically generate o
r
transform values for inserted or updated rows, or invoke functions that perform
operations both inside and outside of DB2. For example, instead of preventing an
update to a column if the new value exceeds a certain amount, a trigger can
substitute a valid value and send a notice to an administrator about the invalid
update.
Triggers are useful for defining and enforcing business rules that involve diffe
rent
states of the data, for example, limiting a salary increase to 10%. Such a limit
requires comparing the value of a salary before and after an increase. For rules
that
do not involve more than one state of the data, consider using referential and c
heck
constraints.
Triggers also move the application logic that is required to enforce business ru
les
into the database, which can result in faster application development and easier
maintenance. With the logic in the database, for example, the previously mention
ed
limit on increases to the salary column of a table, DB2 checks the validity of t
he
changes that any application makes to the salary column. In addition, the
application programs do not need to be changed when the logic changes.
Triggers are optional and are defined using the CREATE TRIGGER statement.
For information on using triggers, see Part 2 of DB2 Application Programming and
SQL Guide.
DB2 Concepts
Chapter 1. DB2 concepts 9
Storage structures
In DB2, a storage structure is a set of one or more VSAM data sets that hold DB2
tables or indexes. A storage structure is also called a page set. A storage stru
cture
can be one of the following:
table space
A table space can hold one or more base tables, or one auxiliary table. All
tables are kept in table spaces. A table space can be defined using the
CREATE TABLESPACE statement.
index space
An index space contains a single index. An index space is defined when the
index is defined using the CREATE INDEX statement.
Storage groups
Defining and deleting the data sets of a storage structure can be left to DB2. I
f it is
left to DB2, the storage structure has an associated storage group. The storage
group is a list of DASD volumes on which DB2 can allocate data sets for associat
ed
storage structures. The association between a storage structure and its storage
group is explicitly or implicitly defined by the statement that created the stor
age
structure.
Alternatively, Storage Management Subsystem (SMS) can be used to manage DB2
data sets. Refer to Part 2 (Volume 1) of DB2 Administration Guide for more
information.
Databases
In DB2, a database is a set of table spaces and index spaces. These index spaces
contain indexes on the tables in the table spaces of the same database. Database
s
are defined using the CREATE DATABASE statement and are primarily used for
administration. Whenever a table space is created, it is explicitly or implicitl
y
assigned to an existing database.
Catalog
Each DB2 maintains a set of tables that contain information about the data under
its
control. These tables are collectively known as the catalog. The catalog tables
contain information about DB2 objects such as tables, views, and indexes. In thi
s
book, “catalog” refers to a DB2 catalog unless otherwise indicated. In contrast, the
catalogs maintained by access method services are known as “integrated catalog
facility catalogs”.
Tables in the catalog are like any other database tables with respect to retriev
al. If
you have authorization, you can use SQL statements to look at data in the catalo
g
tables in the same way that you retrieve data from any other table in the system
.
Each DB2 ensures that the catalog contains accurate descriptions of the objects
that the DB2 controls.
Views
A view provides an alternative way of looking at the data in one or more tables.
A
view is a named specification of a result table. The specification is an SQL SEL
ECT
statement that is effectively executed whenever the view is referenced in an SQL
statement. At any time, the view consists of the rows that would result if the
DB2 Concepts
10 SQL Reference
fullselect were executed. Thus, a view can be thought of as having columns and
rows just like a base table. However, columns added to the base tables after the
view is defined do not appear in the view. For retrieval, all views can be used
like
base tables. Whether a view can be used in an insert, update, or delete operatio
n
depends on its definition, as described in “CREATE VIEW” on page 658.
Views can be used to control access to a table and make data easier to use.
Access to a view can be granted without granting access to the table. The view c
an
be defined to show only portions of data in the table. A view can show summary
data for a given table, combine two or more tables in meaningful ways, or show
only the selected rows that are pertinent to the process using the view.
Example: The following SQL statement defines a view named XYZ. The view
represents a table whose columns are named EMPLOYEE and WHEN_HIRED. The
data in the table comes from the columns EMPNO and HIREDATE of the sample
table DSN8710.EMP. The rows from which the data is taken are for employees in
departments A00 and D11.
CREATE VIEW XYZ (EMPLOYEE, WHEN_HIRED)
AS SELECT EMPNO, HIREDATE
FROM DSN8710.EMP
WHERE WORKDEPT IN ( A00 , D11 );
An index cannot be created for a view. However, an index created for a table on
which a view is based might improve the performance of operations on the view.
The column of a view inherits its attributes (such as data type, precision, and
scale)
from the table or view column, constant, function, or expression from which it i
s
derived. In addition, a view column that maps back to a base table column inheri
ts
any default values or constraints specified for that column of the base table. F
or
example, if a view includes a foreign key of its base table, insert and update
operations using that view are subject to the same referential constraint as the
base
table. Likewise, if the base table of a view is a parent table, delete operation
s using
that view are subject to the same rules as delete operations on the base table.
See
the description of “INSERT” on page 778 and “UPDATE” on page 872 for restrictions
that apply to views with derived columns. For information on referential constra
ints,
see .
Read-only views cannot be used for insert, update, and delete operations. For a
discussion of read-only views, see “CREATE VIEW” on page 658.
The definition of a view is stored in the DB2 catalog. An SQL DROP VIEW
statement can drop a view, and the definition of the view is removed from the
catalog. The definition of a view is also removed from the catalog when any view
or
base table on which the view depends is dropped.
Application processes, concurrency, and recovery
All SQL programs execute as part of an application process. An application proce
ss
involves the execution of one or more programs, and is the unit to which DB2
allocates resources and locks. Different application processes might involve the
execution of different programs, or different executions of the same program. Th
e
means of initiating and terminating an application process are dependent on the
environment.
Locking, commit, and rollback
More than one application process might request access to the same data at the
same time. Furthermore, under certain circumstances, an SQL statement can
DB2 Concepts
Chapter 1. DB2 concepts 11
execute concurrently with a utility on the same table space1. Locking is used to
maintain data integrity under such conditions, preventing, for example, two
application processes from updating the same row of data simultaneously. See Par
t
5 (Volume 2) of DB2 Administration Guide for more information about DB2 locks.
DB2 implicitly acquires locks to prevent uncommitted changes made by one
application process from being perceived by any other. DB2 will implicitly relea
se all
locks it has acquired on behalf of an application process when that process ends
,
but an application process can also explicitly request that locks be released so
oner.
A commit operation releases locks acquired by the application process and commit
s
database changes made by the same process.
DB2 provides a way to back out uncommitted changes made by an application
process. This might be necessary in the event of a failure on the part of an
application process, or in a deadlock situation. An application process, however
, can
explicitly request that its database changes be backed out. This operation is ca
lled
rollback.
The interface used by an SQL program to explicitly specify these commit and
rollback operations depends on the environment. If the environment can include
recoverable resources other than DB2 databases, the SQL COMMIT and
ROLLBACK statements cannot be used. Thus, these statements cannot be used in
an IMS, CICS, or WebSphere™ environment. Refer to Part 4 of DB2 Application
Programming and SQL Guide for more details.
Unit of work
A unit of work is a recoverable sequence of operations within an application
process. A unit of work is sometimes called a logical unit of work. At any time,
an
application process has a single unit of work, but the life of an application pr
ocess
can involve many units of work as a result of commit or full rollback operations
.
A unit of work is initiated when an application process is initiated. A unit of
work is
also initiated when the previous unit of work is ended by something other than t
he
end of the application process. A unit of work is ended by a commit operation, a
full
rollback operation, or the end of an application process. A commit or rollback
operation affects only the database changes made within the unit of work it ends
.
While these changes remain uncommitted, other application processes are unable
to perceive them unless they are running with an isolation level of uncommitted
read. The changes can still be backed out. Once committed, these database
changes are accessible by other application processes and can no longer be
backed out by a rollback. Locks acquired by DB2 on behalf of an application
process that protects uncommitted data are held at least until the end of a unit
of
work.
The initiation and termination of a unit of work define points of consistency wi
thin an
application process. A point of consistency is a claim by the application that t
he
data is consistent. For example, a banking transaction might involve the transfe
r of
funds from one account to another. Such a transaction would require that these
funds be subtracted from the first account, and added to the second. Following t
he
subtraction step, the data is inconsistent. Only after the funds have been added
to
the second account is consistency reestablished. When both steps are complete,
1. See the description of a table space under “Storage structures” on page 10. Concu
rrent execution of SQL statements and utilities
is discussed in Part 5 (Volume 2) of DB2 Administration Guide .
DB2 Concepts
12 SQL Reference
|
|
|
the commit operation can be used to end the unit of work, thereby making the
changes available to other application processes.
Unit of recovery
A DB2 unit of recovery is a recoverable sequence of operations executed by DB2
for an application process. If a unit of work involves changes to other recovera
ble
resources, the unit of work will be supported by other units of recovery. If rel
ational
databases are the only recoverable resources used by the application process, th
en
the scope of the unit of work and the unit of recovery are the same and either t
erm
can be used.
Rolling back work
DB2 can back out all changes made in a unit of recovery or only selected changes
.
Only backing out all changes results in a point of consistency.
Rolling back all changes
The SQL ROLLBACK statement without the TO SAVEPOINT clause specified
causes a full rollback operation. If such a rollback operation is successfully
executed, DB2 backs out uncommitted changes to restore the data consistency that
it assumes existed when the unit of work was initiated. That is, DB2 undoes the
work, as shown in the diagram below:
Rolling back selected changes using savepoints
A savepoint represents the state of data at some particular time during a unit o
f
work. An application process can set savepoints within a unit of work, and then
as
Time
line
Point of
consistency
New point of
consistency
One unit of work
Database updates
Begin
unit of work
COMMIT;
End
unit of work
Figure 1. Unit of work with a commit operation
Point of
consistency
New point of
consistency
Unit of work
Database updates
Begin
unit of work
Data is returned
to its initial state;
end unit of work
Back out updates
ROLLBACK,
failure, or
deadlock;
begin rollback
Time
line
Figure 2. Rolling back all changes from a unit of work
DB2 Concepts
Chapter 1. DB2 concepts 13
logic dictates, roll back only the changes that were made after a savepoint was
set.
For example, part of a reservation transaction might involve booking an airline
flight
and then a hotel room. If a flight gets reserved but a hotel room cannot be
reserved, the application process might want to undo the flight reservation with
out
undoing any database changes made in the transaction prior to making the flight
reservation. SQL programs can use the SQL SAVEPOINT statement to set
savepoints, the SQL ROLLBACK statement with the TO SAVEPOINT clause to
undo changes to a specific savepoint or the last savepoint that was set, and the
SQL RELEASE SAVEPOINT statement to delete a savepoint.
Packages and application plans
A package contains control structures used to execute SQL statements. Packages
are produced during program preparation. The control structures can be thought o
f
as the bound or operational form of SQL statements taken from a database request
module (DBRM). The DBRM contains SQL statements extracted from the source
program during program preparation. All control structures in a package are deri
ved
from the SQL statements embedded in a single source program.
An application plan relates an application process to a local instance of DB2,
specifies processing options, and contains one or both of the following elements
:
v A list of package names
v The bound form of SQL statements taken from one or more DBRMs
Every DB2 application requires an application plan. Plans and packages are
created using the DB2 subcommands BIND PLAN and BIND PACKAGE,
respectively, as described in DB2 Command Reference. See Part 5 of DB2
Application Programming and SQL Guide for a description of program preparation
and identifying packages at run time. Refer to “SET CURRENT PACKAGESET” on
page 856 for rules regarding the selection of a plan element.
Distributed data
A DB2 application program can use SQL to access data at other database
management systems (DBMSs) other than the DB2 at which the application’s plan
is bound. This DB2 is known as the local DB2. The local DB2 and the other DBMSs
are called database servers. Any server other than the local DB2 is considered a
remote server, and access to its data is a distributed operation. The recommende
d
method of accessing data at remote database servers is “DRDA access” on
page 15. “DB2 private protocol access” on page 16 is also available but is not
recommended.
Unit of work
Begin
unit of work
Savepoint A COMMIT
End unit of work
Rollback to A;
database updates
made between
times T1 and T2
are rolled back
Time
line T 1 T 2
Figure 3. Rolling back changes to a savepoint within a unit of work
DB2 Concepts
14 SQL Reference
For servers that support the two-phase commit process, both methods allow for
updating data at several remote locations within the same unit of work. To obtai
n
the more restrictive level of function available at DB2 Version 2 Release 3, ref
er to
16. Table 1 summarizes the main differences between DRDA access and DB2
private protocol access.
Table 1. Differences between DRDA access and DB2 private protocol access
Item DRDA access DB2 private protocol access
Program preparation Requires a remote BIND of
packages
A remote BIND is not applicable
Plan members Can use in packages only Can use in packages or DBRMs
bound directly to the plan
Processing of
embedded statements
Processed as static SQL Processed as deferred embedded
SQL. For a definition, see
“Deferred embedded SQL” on
page 2.
Servers Can use any server that uses the
DRDA protocols
Can use DB2 for OS/390 and
z/OS servers only
SQL statements Can use most SQL statements
supported by the system that
executes the statement (for
details, see DB2 Application
Programming and SQL Guide)
Limited to SQL INSERT,
UPDATE, and DELETE
statements, and to statements
supporting SELECT
Connection
management
Three-part names and aliases
can be used to refer to objects at
another server if the package
was bound with bind option
DBPROTOCOL(DRDA) implicitly
or explicitly specified. Otherwise,
the CONNECT statement is used
to connect an application process
to a server.
Three-part names and aliases are
used to refer to objects at
another server.
Common restrictions: IMS and CICS applications are restricted to read-only
operations at a remote site if:
v Its database server does not support two-phase commit.
v It uses DB2 private protocol access to a DB2 Version 2 Release 3. (DB2 private
protocol access from a DB2 Version 3 or subsequent release requester to a DB2
Version 2 Release 2 server is not supported).
See Part 4 of DB2 Application Programming and SQL Guide for more details about
common restrictions.
DRDA access
DRDA® access supports the execution of dynamic SQL statements and SQL
statements that satisfy all the following conditions:
v The static statements appear in a package bound to an accessible server.
v The statements are executed using that package.
v The objects involved in the execution of the statements are at the server wher
e
the package is bound. If the server is a DB2 subsystem, three-part names and
aliases can be used to refer to another DB2 server.
DB2 Concepts
Chapter 1. DB2 concepts 15
DRDA access can be used in application programs by coding explicit CONNECT
statements or by coding three-part names and specifying the
DBPROTOCOL(DRDA) bind option.
DRDA access is based on a set of protocols known as Distributed Relational
Database Architecture (DRDA). (These protocols are documented by theOpen
Group Technical Standard in DRDA Version 2 Vol. 1: Distributed Relational
Database Architecture (DRDA).) DRDA communication conventions are invisible to
DB2 applications, and allow a DB2 to bind and rebind packages at other servers
and to execute the statements in those packages. See Part 5 of DB2 Application
Programming and SQL Guide for the steps involved in binding packages and plans.
If the server supports the two-phase commit process, use the CONNECT (Type 2)
statement and other connection management statements such as RELEASE.
A system that uses DRDA can request the execution of SQL statements at any
DB2. Preparing DB2 for incoming SQL requests is discussed in Part 3 of DB2
Installation Guide.
When preparing a program for use at a server other than DB2, observe the
following rules:
v For SQL statements processed by the server, use the SQL syntax and semantic
rules of that server. For other statements, use the DB2 rules. For a list of whe
re
statements are processed, see “Appendix B. Characteristics of SQL statements in
DB2 for OS/390 and z/OS” on page 913.
v Use the precompiler option SQL(ALL) when precompiling the program.
Statements that violate DB2 rules are flagged, but their detection does not
prevent the creation of a DBRM.
For more information, refer to the Distributed Relational Database Library.
Remote unit of work is a restricted level of function that is available by DRDA
access when the CONNECT(1) precompiler option is specified. An application
process can have only one connection at a time and cannot connect to a new
server until it executes a commit or rollback operation. This restricts the situ
ations in
which the CONNECT statement can be executed. See “CONNECT” on page 453 for
more information about these restrictions. For more details about CONNECT (Type
1) and a description of the connection states, refer to “CONNECT (Type 1)” on
page 456.
DB2 private protocol access
DB2 private protocol access allows one DB2 to execute a range of statements at
another DB2.
A statement is executed using DB2 private protocol access if it refers to object
s that
are not at the current server and is implicitly or explicitly bound with
DBPROTOCOL(PRIVATE). The current server is the DBMS to which an application
is actively connected. DB2 private protocol access uses DB2 private connections.
The statements that can be executed are SQL INSERT, UPDATE, and DELETE,
and SELECT statements with their associated SQL OPEN, FETCH, and CLOSE
statements. “When an application process has a current server” on page 454
describes what happens when an application process has a current server.
In a program running under DB2, a three-part name or an alias can refer to a tab
le
or view at another DB2. The location name identifies the other DB2 to the DB2
server. A three-part name has the form:
DB2 Concepts
16 SQL Reference
location-name.aaaaaa.ssssss
where aaaaaa.ssssss uniquely identifies the object at the server named
location-name. For example, the name USIBMSTODB21.DSN8710.EMP refers to a
table named DSN8710.EMP at the server whose location name is
USIBMSTODB21. Location naming conventions are described in “Location
identifiers” on page 34. Preparing DB2 for incoming SQL requests is discussed in
Part 3 of DB2 Installation Guide.
Alias names have the same allowable forms as table or view names. The name can
refer to a table or view at the current server or to a table or view elsewhere.
For
more on aliases, see “Aliases and synonyms” on page 41. For more on three-part
names, and on SQL naming conventions in general, see “Naming conventions” on
page 34.
DRDA access has some significant advantages over DB2 private protocol:
v DRDA access uses a more compact format for sending data over the network
and thus improves performance on slow network links.
v Queries sent by DB2 private protocol access are bound at the server whenever
they are first executed in a unit of work. Repeated binds can reduce the
performance of a query that is executed often.
A DBRM for statements executed by DRDA access is bound to a package at the
server once. Those statements can include PREPARE and EXECUTE so that
your application can accept dynamic statements to be executed at the server. But
binding the package is an extra step in program preparation.
v You can use stored procedures with DRDA access.
While a stored procedure is running, it requires no message traffic over the
network and thus reduces the biggest hindrance to high performance for
distributed data.
Connection management for DRDA access and DB2 private protocol
An SQL connection is an association between an application process and a local o
r
remote database server. SQL connections can be managed by the application or by
using bind options. At any time:
v An application process is in the connected or unconnected state and has a set
of
zero or more SQL connections. Each SQL connection of an application process
is uniquely identified by the name of the server of the SQL connection.
v An SQL connection is in one of the following states:
– Current and held
– Current and release pending
– Dormant and held
– Dormant and release pending
Initial state of an application process: An application process is initially in
the
connected state and has exactly one SQL connection. The server of that connectio
n
is the local DB2 subsystem. The initial state of an SQL connection is current an
d
held.
The following diagram shows the state transitions:
DB2 Concepts
Chapter 1. DB2 concepts 17
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SQL connection states
If an application process executes a CONNECT TO statement and the specified
location is known to the local DB2 and is not in the set of existing connections
of
the application process, the location is added to the set of connections and the
connection is placed in the current and held state. If the specified location is
the
current SQL connection of the application process, and if the SQLRULES(DB2) bind
option is in effect, the states of all existing connections remain the same.
An SQL connection in the dormant state is placed in the current state using:
v The SET CONNECTION statement, or
v The CONNECT statement, if the SQLRULES(DB2) bind option is in effect.
When an SQL connection is placed in the current state, the previous current SQL
connection, if any, is placed in the dormant state. No more than one SQL
connection in the set of existing connections of an application process can be
current at any time. Changing the state of an SQL connection from current to
dormant or from dormant to current has no effect on its held or release pending
status.
An SQL connection is placed in the release pending status by the RELEASE
statement. When an application process executes a commit operation, every
release pending connection of the process is ended. Changing the state of an SQL
connection from held to release pending has no effect on its current or dormant
state. Thus, an SQL connection in the release pending status can still be used u
ntil
the next commit operation. Likewise, DB2 private connections in the release
Successful CONNECT
or SET CONNECTION specifying
the existing dormant SQL connection
Current Dormant
Held
Release
Pending
RELEASE
Application Process Connection States
The current SQL connection
is intentionally ended, or a
failure occurs that causes the
loss of the connection
Successful CONNECT or
SET CONNECTION
Connected Unconnected
Begin Process
SQL Connection States
Successful CONNECT
or SET CONNECTION specifying
another SQL connection
Figure 4. SQL connection and application process connection state transitions
DB2 Concepts
18 SQL Reference
pending status can be used until the next commit operation. There is no way to
change the state of a connection from release pending to held.
Application process connection states
A different server can be established by the explicit or implicit execution of a
CONNECT statement. The following rules apply:
v An application process cannot have more than one SQL connection to the same
database server at the same time.
v When an application process executes a SET CONNECTION statement, the
specified location name must be an existing SQL connection in the set of
connections of the application process.
v When an application process executes a CONNECT TO statement and the
SQLRULES(STD) bind option is in effect, the specified location must not be an
existing SQL connection in the set of connections of the application process.
If an application process has a current SQL connection, the application process
is in the connected state. The CURRENT SERVER special register contains the
name of the server of the current SQL connection. The application process can
execute SQL statements that refer to objects managed by that server. If the serv
er
is a DB2 subsystem, the application process can also execute certain SQL
statements that refer to objects managed by a DB2 subsystem with which that
server can establish a connection.
An application process in the unconnected state enters the connected state when
it
successfully executes a CONNECT or SET CONNECTION statement.
If an application process does not have a current SQL connection, the
application process is in the unconnected state. The CURRENT SERVER special
register contains blanks. The only SQL statements that can be executed
successfully at the requester are CONNECT, SET CONNECTION, RELEASE,
COMMIT, ROLLBACK, and local SET statements. COMMIT and ROLLBACK are
also processed by an server. If the application process is in the unconnected st
ate,
the server that processes a COMMIT or ROLLBACK is the local DB2.
An application process in the connected state enters the unconnected state when
its current SQL connection is intentionally ended or the execution of an SQL
statement is unsuccessful because of a failure that causes a rollback operation
at
the server and loss of the SQL connection. SQL connections are intentionally end
ed
when an application process successfully executes a commit operation and any of
the following apply:
v The connection is in the release pending status
v The connection is not in the release pending status but it is a remote connect
ion
and:
– The DISCONNECT(AUTOMATIC) bind option is in effect, or
– The DISCONNECT(CONDITIONAL) bind option is in effect and an open
WITH HOLD cursor is not associated with the connection.
A connect (type 1) statement is implicitly executed when an application process
executes an SQL statement other than COMMIT, CONNECT TO, CONNECT
RESET, SET CONNECTION, RELEASE, or ROLLBACK and if all of the following
conditions apply:
v The CURRENTSERVER bind option was specified when creating the application
plan of the application process and the identified server is not the local DB2.
v An explicit CONNECT statement has not already been successfully or
unsuccessfully executed by the application process.
DB2 Concepts
Chapter 1. DB2 concepts 19
v An implicit connection has not already been successfully or unsuccessfully
executed by the application process. An implicit connection occurs as the result
of execution of an SQL statement that contains a three-part name in a package
that is bound with the DBPROTOCOL(DRDA) option.
If the implicit CONNECT fails, the application process is in the unconnected sta
te.
DB2 private connections
When the server is a DB2 subsystem, DB2 private connections are allocated as
necessary to support references to objects at other DB2 subsystems. Like SQL
connections, DB2 private connections are initially in the held state and can be
placed in the release pending status.
An application process cannot have an explicit SQL connection and a DB2 private
connection to the same DB2 subsystem at the same time. However, an implicit SQL
connection and a DB2 private connection can exist concurrently. Accordingly:
v CONNECT TO x fails if the application process has a DB2 private connection to
x, and
v An attempt to allocate a DB2 private connection to x fails if the application
process has an explicit SQL connection to x.
v An implicit SQL connection through a three-part name is successful if the
application process has a DB2 private connection to x, and
v An attempt to allocate a DB2 private connection to x is successful if the
application process has an implicit SQL connection to x.
When a connection is ended
When a connection is ended, all resources that were acquired by the application
process through the connection and all resources that were used to create and
maintain the connection are deallocated. In the case of an SQL connection to a
DB2 subsystem, the resources acquired can include DB2 private connections.
When the SQL connection is ended, such DB2 private connections are also ended.
This is true even if the DB2 subsystem is the local DB2. For example, assume tha
t
an application process implicitly connected to the local DB2 used DB2 private
protocol access to open a cursor at another DB2. If the application process
executes a RELEASE CURRENT statement, that cursor is closed at the commit
operation, unless the cursor has an attribute of WITH HOLD.
A connection can also be ended as a result of a communications failure in which
case the application process is placed in the unconnected state. All connections
of
an application process are ended when the process terminates.
Character conversion
A string is a sequence of bytes that can represent characters. Within a string,
all the
characters are represented by a common encoding representation. In some cases,
it might be necessary to convert these characters to a different encoding
representation. The process of conversion is known as character conversion.
In client/server environments, character conversion can occur when an SQL
statement is executed remotely. Consider, for example, these two cases:
v The values of host variables sent from the requester to the current server
v The values of result columns sent from the current server to the requester
In either case, the string could have a different representation at the sending
and
receiving systems. Conversion can also occur during string operations on the sam
e
system.
DB2 Concepts
20 SQL Reference
In a local environment, character conversion can occur when:
v An overriding CCSID is specified in the SQLDA (see “SQL descriptor area
(SQLDA)” on page 930).
For languages other than REXX, the CCSID is in the SQLNAME field. For REXX,
the CCSID is in the SQLCCSID field.
v A mixed character string is assigned to an SBCS column or host variable.
Most users do not need a knowledge of character conversion. When character
conversion does occur, it does so automatically, and the conversion, if successf
ul, is
invisible to the application.
The following list defines some of the terms used for character conversion.
ASCII Acronym for American Standard Code for Information Interchange, an
encoding scheme used to represent characters. It is limited to 256 code
positions. The term ASCII is used throughout this book to refer to IBM-PC
Data or ISO 8-bit data.
character set
A defined set of characters, a character being the smallest component of
written language that has semantic value. For example, the following
character set appears in several code pages:
v 26 nonaccented letters A through Z
v 26 nonaccented letters a through z
v digits 0 through 9
v . , : ; ? ( ) " / − _ & + % * = < >
code page
A set of assignments of characters to code points. In EBCDIC, for example,
"A" is assigned code point X'C1' and "B" is assigned code point X'C2'. In
Unicode, "A" is assigned code point ″U+0041″. Within a code page, each
code point has only one specific meaning.
code point
A unique bit pattern that represents a character. It is a numerical index or
position in an encoding table used for encoding characters.
coded character set
A set of unambiguous rules that establishes a character set and the
one to one relationships between the characters of the set and their coded
representations. It is a character set in which each character is assigned a
numeric code value.
coded character set identifier (CCSID)
A two byte, unsigned binary integer that uniquely identifies an encoding
scheme and one or more pairs of character sets and code pages.
EBCDIC
Acronym for Extended Binary Coded Decimal Interchange Code, an
encoding scheme used to represent character data, a group of coded
character sets that consist of 8 bit coded characters. EBCDIC coded
character sets use the first 64 code positions (X'00' to X'3F') for control
codes and the range X'41' to X'FE' for graphic characters.
encoding scheme
A set of rules used to represent character data. All string data stored in a
table must use the same encoding scheme and all tables within a table
DB2 Concepts
Chapter 1. DB2 concepts 21
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
space must use the same encoding scheme, except for global temporary
tables, declared temporary tables, and workfile tablespaces. Encoding
schemes include:
v ASCII
v EBCDIC
v Unicode
substitution byte
A unique character that is substituted during character conversion for any
characters in the source encoding representation that do not have a match
in the target encoding representation.
Unicode
A universal encoding scheme for written characters and text that enables
the exchange of data internationally. It provides a character set standard
that can be used all over the world. It uses a 16-bit encoding form that
provides code points for more than 65,000 characters and an extension
called UTF-16 that allows for encoding as many as a million more
characters. It provides the ability to encode all characters used for the
written languages of the world and treats alphabetic characters, ideographic
characters, and symbols equivalently because it specifies a numeric value
and a name for each of its characters. It includes punctuation marks,
mathematical symbols, technical symbols, geometric shapes, and dingbats.
Three encoding forms include the following:
v UTF-8: Unicode Transformation Format, a 8-bit encoding form designed
for ease of use with existing ASCII-based systems. The CCSID value for
data in UTF-8 format is 1208.
v UCS-2: Universal Character Set coded in 2 octets, which means that
characters are represented in 16-bits per character.
v UTF-16: Unicode Transformation Format, a 16-bit encoding form
designed to provide code values for over a million characters and a
superset of UCS-2. The CCSID value for data in UTF-16 format is 1200.2
Character conversion can affect the results of several SQL operations. In this b
ook,
the effects are described in:
“Conversion rules for string assignment” on page 70
“Conversion rules for string comparison” on page 73
“Character conversion in unions and concatenations” on page 318
Character sets and code pages
The following example shows how a typical character set might map to different
code points in two different code pages.
2. DB2 UDB for OS/390 implements UTF-8 and UTF-16. UTF-8 data is supported in mi
xed data fields and UTF-16 is supported in
graphic data fields.
DB2 Concepts
22 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Even with the same encoding scheme, different coded character sets exist, and th
e
same code point can represent a different character in different coded character
sets. Furthermore, a byte in a character string does not necessarily represent a
character from a single-byte character set (SBCS). Character strings are also us
ed
for mixed data (that is a mixture of single-byte characters and multibyte charac
ters)
and for data that is not associated with any character set (called bit data). No
te that
this is not the case with graphic strings; every pair of bytes in every graphic
string is
assumed to represent a character from a double-byte character set (DBCS).
Character encoding for IBM systems is described in Character Data Representation
Architecture Reference and Registry. For more information on Unicode, see the
Unicode standards Web site at http://www.unicode.org.
System CCSIDs
Every string used in an SQL operation has a CCSID. The CCSID identifies the
manner in which the characters in the string are encoded. Strings can be encoded
in ASCII, EBCDIC, or Unicode. A string representing characters can be one of thr
ee
types:
v A character string composed of SBCS (single-byte character set) characters. In
an SBCS string, each character is represented by a single byte. SBCS is a
subtype of the character data type.
v A graphic string composed of DBCS (double-byte character set) characters. In a
graphic string, each character is represented by a pair of bytes, except in UTF-
16
where surrogates take four bytes per character. For more information on
surrogates, see “Other considerations for using UTF-8 and UTF-16” on page 25.
DB2 Concepts
Chapter 1. DB2 concepts 23
|
|
|
|
|
v An MBCS multibyte character set, in which multibyte characters, including
single-byte characters, can occur. In an EBCDIC mixed string, certain shift
characters serve as left- and right-delimiters for sequences of multibyte
characters that do not include single-byte characters. MIXED is a subtype of the
character data type.
Every query has some context for an encoding scheme (ASCII, EBCDIC, or
Unicode) whether data is explicitly selected from the database or not. If other
string
data from a table or view is selected by a query, the encoding scheme of that st
ring
determines the resulting encoding scheme. The resulting CCSID for string data is
the appropriate CCSID for the encoding scheme of the statement. If there is no
other string data from a table or a view in the query, the default encoding sche
me is
used.
When DB2 is installed, the values specified in fields ASCII CODED CHAR SET,
EBCDIC CODED CHAR SET, and UNICODE CCSID on installation panel DSNTIPF
determine the system CCSIDs for ASCII, EBCDIC, or Unicode data. The ASCII
CODED CHAR SET and EBCDIC CODED CHAR SET fields should contain valid
SBCS CCSIDs if the field MIXED DATA on the same installation panel is NO, or
should contain valid MIXED CCSIDs if the field MIXED DATA is YES. For example,
one CCSID whose value is 37 identifies a widely used form of EBCDIC encoding.
That particular CCSID could be the system CCSID for EBCDIC SBCS strings. The
UNICODE CCSID field on the same installation panel should contain 1208, which is
the CCSID of UTF-8 data. The field DEF ENCODING SCHEME on the installation
panel DSNTIPF determines whether the default encoding scheme is ASCII,
EBCDIC, or Unicode.
At a given DB2, all columns that contain SBCS strings for an encoding scheme are
assumed to have a common CCSID for SBCS data. For example, when character
data is fetched from a table at another DBMS, DB2 converts the data from the
CCSID at the source system to the corresponding CCSID at the target system. If
the character string has a subtype of BIT, its bytes do not represent characters
and
are not converted.
If the CCSID of an input host variable or a host variable substituted for a para
meter
marker is different from the CCSID determined at bind time, and if either CCSID
is
X FFFF (BIT data), an error occurs. Otherwise, the host variable is converted t
o the
coded character set determined by the CCSID at bind time.
For more information about character string subtypes and SBCS and DBCS DB2
sites, see “Data types” on page 48. For information on the subsystem parameters
that determine the default encoding scheme and the system CCSIDs, see DB2
Installation Guide.
Expanding conversions
An expanding conversion occurs when the length of the converted string is greate
r
than that of the source string. For example, an expanding conversion occurs when
an ASCII mixed data string that contains DBCS characters is converted to EBCDIC
mixed data. Because of the addition of shift codes, an error occurs when an
expanding conversion is performed on a fixed-length input host variable that
requires conversion from ASCII mixed to EBCDIC mixed. The remedy is to use a
varying-length string variable with a maximum length that is sufficient to conta
in the
expansion.
DB2 Concepts
24 SQL Reference
#
#
#
#
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Expanding conversions also can occur when string data is converted to or from
Unicode. It can also occur between UTF-8 and UTF-16, depending on the data
being converted. UTF-8 uses one, two, three, or four bytes per character. UTF-16
uses two or four bytes per character. If UTF-8 were being converted to UTF-16, a
one byte character would be expanded to two bytes.
Contracting conversions
A contracting conversion occurs when the length of the converted string is small
er
than that of the source string. For example, a contracting conversion occurs whe
n
an EBCDIC mixed data string that contains DBCS characters is converted to ASCII
mixed data due to the removal of shift codes.
Contracting conversions also can occur when string data is converted to or from
Unicode data. It can also occur between UTF-8 and UTF-16, depending on the data
being converted.
Other considerations for using UTF-8 and UTF-16
Storage for UTF-8 is one to four bytes per character. Storage for UTF-16 is two
or
four bytes per character. For UTF-16, surrogates use four bytes per character.
Surrogates are designed to allow representation of characters in future extensio
ns
of the Unicode standard.
DB2 Concepts
Chapter 1. DB2 concepts 25
|
|
|
|
|
|
|
|
|
|
|
|
|
26 SQL Reference
Chapter 2. Language elements
Characters . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Tokens. . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
SQL identifiers . . . . . . . . . . . . . . . . . . . . . . . . 32
Ordinary identifiers . . . . . . . . . . . . . . . . . . . . . 32
Delimited identifiers . . . . . . . . . . . . . . . . . . . . . 33
Short and long identifiers . . . . . . . . . . . . . . . . . . . 33
Location identifiers . . . . . . . . . . . . . . . . . . . . . . 34
Host identifiers . . . . . . . . . . . . . . . . . . . . . . . . 34
Naming conventions . . . . . . . . . . . . . . . . . . . . . . . 34
Qualification of unqualified object names . . . . . . . . . . . . . . 39
Unqualified alias, index, table, and view names . . . . . . . . . . . 39
Unqualified data type, function, and procedure names . . . . . . . . 40
Schemas and the SQL path . . . . . . . . . . . . . . . . . . . . 40
Aliases and synonyms . . . . . . . . . . . . . . . . . . . . . . 41
Authorization IDs and authorization-names. . . . . . . . . . . . . . . 42
Authorization IDs and schema names . . . . . . . . . . . . . . . 43
Authorization IDs and statement preparation . . . . . . . . . . . . . 43
Authorization IDs and dynamic SQL . . . . . . . . . . . . . . . . 43
Authorization IDs and remote execution. . . . . . . . . . . . . . . 46
DRDA access with DB2 for OS/390 and z/OS only. . . . . . . . . . 46
DRDA access with a server or requester other than DB2 . . . . . . . 47
DB2 private protocol access . . . . . . . . . . . . . . . . . . 47
Authorization ID translations . . . . . . . . . . . . . . . . . . 47
Other security measures . . . . . . . . . . . . . . . . . . . 47
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Character strings . . . . . . . . . . . . . . . . . . . . . . . 49
The effect of encoding schemes on DBCS characters in mixed strings 49
Examples. . . . . . . . . . . . . . . . . . . . . . . . . 50
DB2 and SBCS defaults . . . . . . . . . . . . . . . . . . . 50
DB2 and DBCS defaults . . . . . . . . . . . . . . . . . . . 50
Fixed-length character strings . . . . . . . . . . . . . . . . . 51
Varying-length character strings. . . . . . . . . . . . . . . . . 51
Character string host variables . . . . . . . . . . . . . . . . . 52
Graphic strings. . . . . . . . . . . . . . . . . . . . . . . . 52
Fixed-length graphic strings . . . . . . . . . . . . . . . . . . 52
Varying-length graphic strings . . . . . . . . . . . . . . . . . 52
Graphic string host variables. . . . . . . . . . . . . . . . . . 53
Binary strings . . . . . . . . . . . . . . . . . . . . . . . . 53
Large objects (LOBs) . . . . . . . . . . . . . . . . . . . . . 53
Restrictions using long strings . . . . . . . . . . . . . . . . . . 54
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Small integer (SMALLINT). . . . . . . . . . . . . . . . . . . 55
Large integer (INTEGER) . . . . . . . . . . . . . . . . . . . 55
Single precision floating-point (REAL) . . . . . . . . . . . . . . 55
Double precision floating-point (DOUBLE or FLOAT) . . . . . . . . . 55
Decimal (DECIMAL or NUMERIC). . . . . . . . . . . . . . . . 55
String representations of numbers. . . . . . . . . . . . . . . . 56
Numeric host variables . . . . . . . . . . . . . . . . . . . . 56
Datetime values . . . . . . . . . . . . . . . . . . . . . . . 56
Date. . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Time. . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Timestamp . . . . . . . . . . . . . . . . . . . . . . . . 57
© Copyright IBM Corp. 1982, 2001 27
|
String representations of datetime values . . . . . . . . . . . . . 57
Restrictions on the use of local datetime formats . . . . . . . . . . 59
Row ID values . . . . . . . . . . . . . . . . . . . . . . . . 60
Distinct types . . . . . . . . . . . . . . . . . . . . . . . . 60
Promotion of data types . . . . . . . . . . . . . . . . . . . . . 61
Casting between data types . . . . . . . . . . . . . . . . . . . . 62
Assignment and comparison . . . . . . . . . . . . . . . . . . . . 64
Numeric assignments . . . . . . . . . . . . . . . . . . . . . 66
Decimal or integer to floating-point. . . . . . . . . . . . . . . . 66
Floating-point or decimal to integer . . . . . . . . . . . . . . . 66
Decimal to decimal . . . . . . . . . . . . . . . . . . . . . 67
Integer to decimal. . . . . . . . . . . . . . . . . . . . . . 67
Floating-point to floating-point . . . . . . . . . . . . . . . . . 67
Floating-point to decimal . . . . . . . . . . . . . . . . . . . 67
To COBOL integers . . . . . . . . . . . . . . . . . . . . . 68
String assignments . . . . . . . . . . . . . . . . . . . . . . 68
Storage assignment . . . . . . . . . . . . . . . . . . . . . 68
Retrieval Assignment. . . . . . . . . . . . . . . . . . . . . 69
Assignments involving mixed data strings . . . . . . . . . . . . . 69
Assignments involving C NUL-terminated strings . . . . . . . . . . 69
Conversion rules for string assignment . . . . . . . . . . . . . . 70
Datetime assignments . . . . . . . . . . . . . . . . . . . . . 70
Row ID assignments. . . . . . . . . . . . . . . . . . . . . . 71
Distinct type assignments . . . . . . . . . . . . . . . . . . . . 71
Numeric comparisons . . . . . . . . . . . . . . . . . . . . . 72
String comparisons . . . . . . . . . . . . . . . . . . . . . . 73
String comparisons with field procedures . . . . . . . . . . . . . 73
Conversion rules for string comparison . . . . . . . . . . . . . . 73
Datetime comparisons . . . . . . . . . . . . . . . . . . . . . 75
Row ID comparisons. . . . . . . . . . . . . . . . . . . . . . 75
Distinct type comparisons . . . . . . . . . . . . . . . . . . . . 75
Rules for result data types. . . . . . . . . . . . . . . . . . . . . 77
String operands . . . . . . . . . . . . . . . . . . . . . . . 77
Binary string operands . . . . . . . . . . . . . . . . . . . . . 78
Numeric operands. . . . . . . . . . . . . . . . . . . . . . . 78
Datetime operands . . . . . . . . . . . . . . . . . . . . . . 79
Row ID operands . . . . . . . . . . . . . . . . . . . . . . . 79
Distinct type operands . . . . . . . . . . . . . . . . . . . . . 79
Nullable attribute of a result . . . . . . . . . . . . . . . . . . . 79
Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Integer constants . . . . . . . . . . . . . . . . . . . . . . . 79
Floating-point constants . . . . . . . . . . . . . . . . . . . . 80
Decimal constants. . . . . . . . . . . . . . . . . . . . . . . 80
Character string constants. . . . . . . . . . . . . . . . . . . . 80
Datetime constants . . . . . . . . . . . . . . . . . . . . . . 81
Graphic string constants . . . . . . . . . . . . . . . . . . . . 81
Special registers . . . . . . . . . . . . . . . . . . . . . . . . 82
General rules for special registers. . . . . . . . . . . . . . . . . 83
CURRENT APPLICATION ENCODING SCHEME . . . . . . . . . . . 85
CURRENT DATE . . . . . . . . . . . . . . . . . . . . . . . 86
CURRENT DEGREE. . . . . . . . . . . . . . . . . . . . . . 86
CURRENT LOCALE LC_CTYPE . . . . . . . . . . . . . . . . . 86
CURRENT OPTIMIZATION HINT . . . . . . . . . . . . . . . . . 87
CURRENT PACKAGESET . . . . . . . . . . . . . . . . . . . 87
CURRENT PATH . . . . . . . . . . . . . . . . . . . . . . . 88
CURRENT PRECISION . . . . . . . . . . . . . . . . . . . . 88
Language Elements
28 SQL Reference
|
|
CURRENT RULES . . . . . . . . . . . . . . . . . . . . . . 89
CURRENT SERVER. . . . . . . . . . . . . . . . . . . . . . 90
CURRENT SQLID. . . . . . . . . . . . . . . . . . . . . . . 90
CURRENT TIME . . . . . . . . . . . . . . . . . . . . . . . 90
CURRENT TIMESTAMP . . . . . . . . . . . . . . . . . . . . 91
CURRENT TIMEZONE . . . . . . . . . . . . . . . . . . . . . 91
USER . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Inheriting special registers in a user-defined function or a stored procedure 92
Column names. . . . . . . . . . . . . . . . . . . . . . . . . 94
Qualified column names . . . . . . . . . . . . . . . . . . . . 95
Correlation names. . . . . . . . . . . . . . . . . . . . . . . 95
Column name qualifiers to avoid ambiguity . . . . . . . . . . . . . 96
Column name qualifiers in correlated references . . . . . . . . . . . 97
Resolution of column name qualifiers and column names . . . . . . . . 98
References to variables. . . . . . . . . . . . . . . . . . . . . . 99
References to host variables. . . . . . . . . . . . . . . . . . . . 99
Host variables in dynamic SQL . . . . . . . . . . . . . . . . . 101
References to LOB host variables . . . . . . . . . . . . . . . . 101
References to LOB locator variables . . . . . . . . . . . . . . . 102
References to stored procedure result sets . . . . . . . . . . . . . 102
References to result set locator variables. . . . . . . . . . . . . . 102
Host structures in PL/I, C, and COBOL . . . . . . . . . . . . . . . 103
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Types of functions . . . . . . . . . . . . . . . . . . . . . . 104
Function resolution . . . . . . . . . . . . . . . . . . . . . . 106
Method of finding the best fit . . . . . . . . . . . . . . . . . 108
SQL path considerations for built-in functions . . . . . . . . . . . 109
Function invocation. . . . . . . . . . . . . . . . . . . . . . 109
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 110
Without operators . . . . . . . . . . . . . . . . . . . . . . 111
With the concatenation operator . . . . . . . . . . . . . . . . . 111
With arithmetic operators. . . . . . . . . . . . . . . . . . . . 113
Arithmetic with two integer operands . . . . . . . . . . . . . . . 114
Arithmetic with an integer and a decimal operand. . . . . . . . . . . 114
Arithmetic with two decimal operands . . . . . . . . . . . . . . . 114
Decimal addition and subtraction . . . . . . . . . . . . . . . . 115
Decimal multiplication . . . . . . . . . . . . . . . . . . . . 115
Decimal division . . . . . . . . . . . . . . . . . . . . . . 115
Arithmetic with floating-point operands. . . . . . . . . . . . . . . 116
Datetime operands and durations. . . . . . . . . . . . . . . . . 117
Datetime arithmetic in SQL . . . . . . . . . . . . . . . . . . . 118
Date arithmetic . . . . . . . . . . . . . . . . . . . . . . 118
Time arithmetic . . . . . . . . . . . . . . . . . . . . . . 120
Timestamp arithmetic . . . . . . . . . . . . . . . . . . . . 121
Precedence of operations . . . . . . . . . . . . . . . . . . . 122
CASE expressions . . . . . . . . . . . . . . . . . . . . . . 123
CAST specification . . . . . . . . . . . . . . . . . . . . . . 125
Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Basic predicate . . . . . . . . . . . . . . . . . . . . . . . 129
Quantified predicate . . . . . . . . . . . . . . . . . . . . . 131
BETWEEN predicate . . . . . . . . . . . . . . . . . . . . . 133
EXISTS predicate . . . . . . . . . . . . . . . . . . . . . . 133
IN predicate . . . . . . . . . . . . . . . . . . . . . . . . 135
LIKE predicate . . . . . . . . . . . . . . . . . . . . . . . 136
Examples . . . . . . . . . . . . . . . . . . . . . . . . 141
NULL predicate . . . . . . . . . . . . . . . . . . . . . . . 143
Language Elements
Chapter 2. Language elements 29
|
|
|
Search conditions . . . . . . . . . . . . . . . . . . . . . . . 144
Options affecting SQL. . . . . . . . . . . . . . . . . . . . . . 145
Precompiler options for dynamic statements. . . . . . . . . . . . . 147
Decimal point representation . . . . . . . . . . . . . . . . . . 147
Apostrophes and quotation marks in string delimiters . . . . . . . . . 148
Katakana characters for EBCDIC. . . . . . . . . . . . . . . . . 149
Mixed data in character strings . . . . . . . . . . . . . . . . . 149
Formatting of datetime strings . . . . . . . . . . . . . . . . . . 150
SQL standard language . . . . . . . . . . . . . . . . . . . . 150
Positioned updates of columns . . . . . . . . . . . . . . . . . 152
Language Elements
30 SQL Reference
This chapter defines the basic syntax of SQL and language elements that are
common to many SQL statements.
Characters
The basic symbols of SQL are characters from the EBCDIC syntactic character set.
These characters are classified as letters, digits, or special characters:
v A letter is any one of the uppercase alphabetic characters A through Z plus th
e
three EBCDIC code points reserved as alphabetic extenders for national
languages (the code points X 5B , X 7B , and X 7C , which display as $, #, and @
using code pages 37 and 500).
v A digit is any one of the characters 0 through 9.
v A special character is any character other than a letter or a digit.
SQL statements can also contain double-byte character set (DBCS) characters.
Regardless of the value of the field MIXED DATA on installation panel DSNTIPF,
double-byte characters can be used in SQL ordinary identifiers and graphic strin
g
constants when enclosed by the necessary shift characters. If the value of MIXED
DATA is YES, double-byte characters can also be used in string constants and
delimited identifiers. In SQL application programs, any use of double-byte
characters must be contained within a single line. Thus, a graphic string consta
nt
cannot be continued from one line to the next and, if MIXED DATA is YES, a
character string constant and delimited identifier can be continued from one lin
e to
the next only if the break occurs between single-byte characters. This restricti
on
also applies to the use of double-byte characters within tokens of the host
language.
Tokens
The basic syntactical units of the language are called tokens. A token consists
of
one or more characters of which none are blanks, control characters, or characte
rs
within a string constant or delimited identifier.
Tokens are classified as ordinary or delimiter tokens:
v An ordinary token is a numeric constant, an ordinary identifier, a host identi
fier, or
a keyword.
Examples:
1.1+2 SELECT E 3
v A delimiter token is a string constant, a delimited identifier, an operator sy
mbol,
or any of the special characters shown in the syntax diagrams. A question mark
(?) is also a delimiter token when it serves as a parameter marker, as explained
in “PREPARE” on page 792.
Examples:
, string "fld1" = .
String constants and certain delimited identifiers are the only tokens that can
include a space or control character. Any token can be followed by a space or
control character. Every ordinary token must be followed by a delimiter token, a
space, or a control character; if the syntax does not allow a delimiter token, a
space
or a control character must follow the ordinary token.
Spaces: A space is a sequence of one or more blank characters.
Language Elements
Chapter 2. Language elements 31
Control characters: A control character is a special character that is used for
string
alignment. Treated similar to a space, a control character does not cause a
particular action to occur. DB2 handles the following control characters:
Control character EBCDIC hex value
Tab 05
Form feed 0C
Carriage return 0D
New line or next line 15
Line feed (new line) 25
Uppercase and lowercase: Any token can include lowercase letters, but a
lowercase letter in an ordinary token is folded to uppercase. However, it is onl
y
folded to uppercase in a C program if the appropriate precomiler is specified.
Delimiter tokens are never folded to uppercase.
Example: The statement:
select * from DSN8710.EMP where lastname = Smith ;
is equivalent, after folding, to:
SELECT * FROM DSN8710.EMP WHERE LASTNAME = Smith ;
Identifiers
An identifier is a token used to form a name. An identifier in an SQL statement
is an
SQL identifier, a location identifier, or a host identifier. See “Appendix A. Limi
ts in
DB2 for OS/390 and z/OS” on page 909 for the identifier length limits that DB2
imposes.
SQL identifiers
SQL identifiers can be ordinary identifiers or delimited identifiers. They can a
lso be
short identifiers or long identifiers. Thus, an SQL identifier can be in one of
four
categories: short ordinary, long ordinary, short delimited, or long delimited.
Ordinary identifiers
An ordinary identifier is a letter followed by zero or more characters, each of
which
is a letter, a digit, or the underscore character. An ordinary identifier with a
n
EBCDIC encoding scheme can include Katakana characters if the value of field
EBCDIC CODED CHAR SET on installation panel DSNTIPF is set to 930 or 5026
when the statement is parsed.
DBCS characters are allowed in SQL ordinary identifiers. An SQL ordinary identif
ier,
when used as the name of a table, column, alias, synonym, view, statement, curso
r,
correlation, distinct type, stored procedure, user-defined function, or trigger
name
can be specified using either DBCS characters or single-byte character set (SBCS
)
characters. However, an SQL ordinary identifier cannot contain a mixture of SBCS
and DBCS characters.
The following list shows the rules for forming DBCS SQL ordinary identifiers. Th
ese
are EBCDIC rules because DB2 processes SQL statements in EBCDIC.
v The identifier must start with a shift-out (X 0E ), end with a shift-in (X 0F
), and an
odd-numbered byte between those shifts must not be a shift-out.
v The maximum length is 18 bytes including the shift-out and the shift-in. In ot
her
words, there is a maximum of 16 bytes (8 double-byte characters) between the
shift-out and the shift-in.
Tokens
32 SQL Reference
#
#
v There must be an even number of bytes between the shift-out and the shift-in.
v DBCS blanks (X 4040 ) are not acceptable between the shift-out and the shift-i
n.
v The identifiers are not folded to uppercase or changed in any other way.
v Continuation to the next line is not allowed.
An ordinary identifier must not be identical to a keyword that is a reserved wor
d in
any context in which the identifier is used. For a list of reserved words, see
“Appendix F. SQL reserved words” on page 1097.
Example: The following example is an ordinary identifier:
SALARY
Delimited identifiers
A delimited identifier is a sequence of one or more characters enclosed within
escape characters. The escape character is the quotation mark (") except for:
v Dynamic SQL when the field SQL STRING DELIMITER on installation panel
DSNTIPF is set to the quotation mark (") and either of these conditions is true:
– DYNAMICRULES run behavior applies. For a list of the DYNAMICRULES
bind option values that specify run, bind, define, or invoke behavior, see
Table 2 on page 44.
– DYNAMICRULES bind, invoke, or define behavior applies and installation
panel field USE FOR DYNAMIC RULES is YES.
In this case, the escape character is the apostrophe ( ).
However, for COBOL application programs, if DYNAMICRULES run behavior
does not apply and installation panel field USE FOR DYNAMICRULES is NO, a
COBOL compiler option specifies whether the escape character is the quotation
mark or apostrophe.
v Static SQL in COBOL application programs. A COBOL compiler option specifies
whether the escape character is the quotation mark (") or the apostrophe ( ).
A delimited identifier can be used when the sequence of characters does not qual
ify
as an ordinary identifier. Such a sequence, for example, could be an SQL reserve
d
word, or it could begin with a digit. Two consecutive escape characters are used
to
represent one escape character within the delimited identifier. A delimited iden
tifier
that contains double-byte characters also must contain the necessary shift
characters.
Example: If the escape character is the quotation mark, the following example is
a
delimited identifier:
“VIEW”
Short and long identifiers
SQL identifiers are also classified according to their maximum length. A long
identifier has a maximum length of 18 bytes. A short identifier has a maximum
length of 8 bytes. These limits do not include the escape characters of a delimi
ted
identifier.
Whether an identifier is long or short depends on what it represents. For exampl
e,
the name of a storage group is a short identifier, whereas an unqualified table
name
is a long identifier. “Naming conventions” on page 34 describes what identifiers can
represent and whether those representing a given type of entity are long or shor
t.
Identifiers
Chapter 2. Language elements 33
|
Database names and table space names are examples of short identifiers that will
be used as part of data set names. Such identifiers, whether ordinary or delimit
ed,
must conform to the MVS rules for forming data set names. For example, a short
ordinary identifier used to name a database must not contain an underscore
character.
Location identifiers
A location identifier is like an SQL identifier, except as follows:
v The maximum length is 16 bytes.
v The ordinary form must not include alphabetic extenders, lowercase letters, or
Katakana characters.
v The characters allowed in the delimited form are the same as those allowed in
the ordinary form.
Host identifiers
A host identifier is a name declared in the host program. The rules for forming
a
host identifier are the rules of the host language.
Naming conventions
The rules for forming a name depend on the type of the object designated by the
name. The syntax diagrams use different terms for different types of names. The
following list defines these terms.
alias-name
A qualified or unqualified name that designates an alias, table, or view. An
alias name designates an alias when it is preceded by the keyword ALIAS,
as in CREATE ALIAS, DROP ALIAS, COMMENT ON ALIAS, and LABEL
ON ALIAS. In all other contexts, an alias name designates a table or view.
For example, COMMENT ON ALIAS A specifies a comment about the alias
A, whereas COMMENT ON TABLE A specifies a comment about the table
or view designated by A.
An alias can be defined at a local server and can refer to a table or view
that is at the current server or a remote server. The alias name can be used
wherever the table name or view name can be used to refer to the table or
view in an SQL statement. The rules for forming an alias name are the
same as the rules for forming a table name or a view name, as explained
below. A fully qualified alias name (a three-part name) can refer to an alias
at a remote server. However, the table or view identified by the alias at the
remote server must exist at the remote server.
Statements that use three-part names and refer to distributed data result in
either DB2 private protocol access or DRDA access to the remote site.
DRDA access for three-part names is used when the plan or package that
contains the query to distributed data is bound with bind option
DBPROTOCOL(DRDA), or the value of field DATABASE PROTOCOL on
installation panel DSNTIP5 is DRDA and bind option PROTOCOL was not
specified when the plan or package was bound. When an application
program uses three-part name aliases for remote objects and DRDA
access, the application program must be bound at each location that is
specified in the three-part names. Also, each alias needs to be defined at
the local site. An alias at a remote site can refer to yet another server as
long as a referenced alias eventually refers to a table or view.
Identifiers
34 SQL Reference
#
#
authorization-name
A short identifier that designates a set of privileges. It can also designate a
user or group of users, but DB2 does not control this property. See
“Authorization IDs and authorization-names” on page 42 for the distinction
between an authorization name and an authorization ID.
aux-table-name
A qualified or unqualified name that designates an auxiliary table. The rules
for the name are the same as the rules for table-name. See “table-name”
on page 38.
bpname
A name that identifies a buffer pool. The following list shows the names of
the different buffer pool sizes.
4KB BP0, BP1, BP2, ..., BP49
8KB BP8K0, BP8K1, BP8K2, ..., BP8K9
16KB BP16K0, BP16K1, BP16K2, ..., BP16K9
32KB BP32K, BP32K1, BP32K2, ..., BP32K9
built-in-data-type
A qualified or unqualified name that identifies an IBM-supplied data type. A
qualified name is SYSIBM followed by a period and the name of the built-in
data type. An unqualified name has an implicit qualifier, the schema name,
which is determined by the rules in “Qualification of unqualified object
names” on page 39.
catalog-name
A short identifier that designates an integrated catalog facility catalog.
collection-id
A long identifier that identifies a collection of packages; therefore, a
collection ID is a qualifier for a package ID. Refer to Chapter 1 of DB2
Command Reference for naming conventions.
column-name
A qualified or unqualified name that designates a column of a table or view.
A qualified column name is a qualifier followed by a period and a long
identifier. The qualifier is a table name, a view name, a synonym, an alias,
or a correlation name.
An unqualified column name is a long identifier.
constraint-name
A short identifier that designates a referential constraint or a long identifier
that designates a unique constraint or a check constraint on a table.
correlation-name
A long identifier that designates a table, a view, or individual rows of a table
or view.
cursor-name
A long identifier that designates an SQL cursor.
database-name
A short identifier that designates a database. The identifier must start with a
letter and must not include special characters.
descriptor-name
A host identifier that designates an SQL descriptor area (SQLDA). See
“References to host variables” on page 99 for a description of a host
identifier. A descriptor name never includes an indicator variable.
Naming Conventions
Chapter 2. Language elements 35
|
distinct-type-name
A qualified or unqualified name that designates a distinct type.
A qualified distinct type name is a two-part name. The first part is a short
identifier. The short identifier is the schema name of the distinct type. The
second part is a long identifier. A period must separate each of the parts.
An unqualified distinct type name is a long identifier with an implicit qualifie
r.
The implicit qualifier is the schema name, which is determined by the
context in which the distinct type appears as described by the rules in
“Qualification of unqualified object names” on page 39.
function-name
A qualified or unqualified name that designates a user-defined function, a
cast function that was generated when a distinct type was created, or a
built-in function.
A qualified function name is a two-part name. The first part is a short
identifier. The short identifier is the schema name of the function. The
second part is a long identifier. A period must separate each of the parts.
An unqualified function name is a long identifier with an implicit qualifier.
The implicit qualifier is the schema name, which is determined by the
context in which the function appears as described by the rules in
“Qualification of unqualified object names” on page 39.
host-variable
A sequence of tokens that designates a host variable. A host variable
includes at least one host identifier, as explained in “References to host
variables” on page 99.
index-name
A qualified or unqualified name that designates an index.
A qualified index name is a short identifier followed by a period and a long
identifier. The short identifier is the authorization ID that owns the index.
An unqualified index name is a long identifier with an implicit qualifier. The
implicit qualifier is an authorization ID that is determined by the rules set
forth in “Qualification of unqualified object names” on page 39.
For an index on a declared temporary table, the qualifier must be
SESSION.
location-name
A location identifier that identifies an instance of a database management
system.
package-id
A short identifier that identifies a package. For packages created using
DB2, a package ID is the name of the program whose precompilation
produced the package’s DBRM. Refer to Chapter 1 of DB2 Command
Reference for naming conventions.
plan-name
A short identifier that identifies an application plan. Refer to Chapter 1 of
DB2 Command Reference for naming conventions.
procedure-name
A qualified or unqualified name that designates a stored procedure.
A fully qualified procedure name is a three-part name. The first part is a
location name that identifies the DBMS at which the procedure is stored.
Naming Conventions
36 SQL Reference
The second part is the schema name of the stored procedure. The third
part is a long identifier. A period must separate each of the parts.
A two-part procedure name is implicitly qualified with the location name of
the current server. The first part is the schema name of stored procedure.
The second part is a long identifier. A period must separate the two parts.
A one-part or unqualified procedure name is a long identifier with two
implicit qualifiers. The first implicit qualifier is the location name of the
current server. The second implicit qualifier depends on the server. If the
server is DB2 for OS/390 and z/OS, the implicit qualifier is schema name,
which is determined by the context in which the unqualified name appears
as described by the rules in “Qualification of unqualified object names” on
page 39.
The content of an SQL procedure name (whether as a simple identifier or a
delimited identifer) must contain only the uppercase alphabetic characters A
through Z, the characters 0 through 9, or the underscore. The name must
begin with an alphabetic character.
program-name
A short identifier that designates an exit routine.
schema-name
A short identifier that designates a schema. A schema-name that is used as
a qualifier of the name of an object is often also an authorization ID. The
objects that are qualified with a schema name are distinct types, stored
procedures, triggers, and user-defined functions. Built-in data types and
built-in functions are also qualified with a schema name.
specific-name
A qualified or unqualified name that designates a unique name for a
user-defined function.
A qualified specific name is a two-part name. The first part is a short
identifier. The short identifier is the schema name. The second part is a
long identifier. A period must separate each of the parts.
An unqualified specific name is a long identifier with an implicit qualifier. Th
e
implicit qualifier is the schema name, which is determined by the context in
which the unqualified name appears as described by the rules in
“Qualification of unqualified object names” on page 39.
A specific name can be used to identify a function to alter, comment on,
drop, grant privileges on, revoke privileges from, or be the source function
for another function. A specific name cannot be used to invoke a function.
In addition to being used in certain SQL statements, a specific name must
be used in DB2 commands to uniquely identify a function.
SQL-variable-name
A qualified or unqualified name that designates a variable in an SQL
procedure body. The unqualified form of an SQL variable name is an SQL
identifier of 1 to 64 bytes. If the SQL variable is a delimited identifier, the
contents of the delimited identifier must conform to the rules for ordinary
identifiers. The qualified form is an SQL procedure statement label followed
by a period (.) and an SQL identifier.
statement-name
A long identifier that designates a prepared SQL statement.
Naming Conventions
Chapter 2. Language elements 37
#
#
#
#
stogroup-name
A short identifier that designates a storage group. The identifier must start
with a letter and must not include special characters.
svpt-name
A savepoint identifier that designates a savepoint. A savepoint identifier is
like an SQL identifier except it has a maximum length of 128 bytes.
synonym
A long identifier that designates a synonym, a table, or a view. The table or
view must exist at the current server. A synonym designates a synonym
when it is preceded by the keyword SYNONYM, as in CREATE SYNONYM
and DROP SYNONYM. In all other contexts, a synonym designates a local
table or view and can be used wherever the name of a table or view can be
used in an SQL statement. A qualified name is never interpreted as a
synonym.
table-name
A qualified or unqualified name that designates a table.
A fully qualified table name is a three-part name. The first part is a location
name that designates the DBMS at which the table is stored. The second
part is the authorization ID that designates the owner of the table. The third
part is a long identifier. A period must separate each of the parts.
A two-part table name is implicitly qualified by the location name of the
current server. The first part is the authorization ID that designates the
owner of the table. The second part is a long identifier. A period must
separate the two parts.
A one-part or unqualified table name is a long identifier with two implicit
qualifiers. The first implicit qualifier is the location name of the current
server. The second is an authorization ID, which is determined by the rules
set forth in “Qualification of unqualified object names” on page 39.
For a declared temporary table, the qualifier that designates the owner (the
second part in a three-part name and the first part in a two-part name) must
be SESSION. For complete details on specifying a name when a declared
temporary table is defined and then later referring to that declared
temporary table in other SQL statements, see “DECLARE GLOBAL
TEMPORARY TABLE” on page 672.
table-space-name
A short identifier that designates a table space of an identified database.
The identifier must start with a letter and must not include special
characters. If a database is not identified, DSNDB04 is implicit.
trigger-name
A qualified or unqualified name that designates a trigger.
A qualified trigger name is a two-part name. The first part is a short
identifier. The short identifier is the schema name of the trigger. The second
part is also a short identifier. A period must separate each of the parts.
An unqualified trigger name is a short identifier with an implicit qualifier. Th
e
implicit qualifier is the schema name, which is determined by the rules set
forth in “Qualification of unqualified object names” on page 39.
Naming Conventions
38 SQL Reference
version-id
An identifier3 of 1 to 64 characters that is assigned to a package when the
package is created. The version ID that is assigned is taken from the
version ID associated with the program being bound. Version IDs are
specified for programs as a parameter of the DB2 precompiler. Refer to
Chapter 1 of DB2 Command Reference for naming conventions.
view-name
A qualified or unqualified name that designates a view.
A fully qualified view name is a three-part name. The first part is a location
name that designates the DBMS where the view is defined. The second
part is the authorization ID that designates the owner of the view. The third
part is a long identifier. A period must separate each of the parts.
A two-part view name is implicitly qualified by the location name of the
current server. The first part is the authorization ID that designates the
owner of the view. The second part is a long identifier. A period must
separate the two parts.
A one-part or unqualified view name is a long identifier with two implicit
qualifiers. The first implicit qualifier is the location name of the current
server. The second is an authorization ID, which is determined by the rules
set forth in “Qualification of unqualified object names”.
Qualification of unqualified object names
Unqualified object names are implicitly qualified. The rules for qualifying a na
me
differ depending on the type of object that the name identifies.
Unqualified alias, index, table, and view names
Unqualified alias, index, table, and view names are implicitly qualified as foll
ows:
v For static SQL statements, the implicit qualifier is the identifier specified
in the
QUALIFIER option of the BIND subcommand used to bind the SQL statements. If
this bind option was not used when the plan or package was created or last
rebound, the implicit qualifier is the authorization ID of the owner of the plan
or
package.
v For dynamic SQL statements, the behavior as specified by the combination of
bind option DYNAMICRULES and the run-time environment determines the
implicit qualifier. (For a list of these behaviors and the DYNAMICRULES values
that determine them, see Table 2 on page 44).
– If DYNAMICRULES run behavior applies, the implicit qualifier is the SQL
authorization ID in the CURRENT SQLID special register. Run behavior is the
default.
– If bind behavior applies, the identifier implicitly or explicitly specified in t
he
QUALIFIER option of the BIND subcommand, as explained above for static
SQL statements.
– If define behavior applies, the implicit qualifier is the owner of the function
or
stored procedure (the owner is the definer).
– If invoke behavior applies, the implicit qualifier is the authorization ID of th
e
invoker of the function or stored procedure.
Exception: For bind, define, and invoke behavior, the implicit qualifier of
PLAN_TABLE (output from the EXPLAIN statement) is always the value in
special register CURRENT SQLID.
3. The version-id can begin with a digit, for example, when it is a timestamp.
Naming Conventions
Chapter 2. Language elements 39
Unqualified data type, function, and procedure names
The qualification of data type, function, and stored procedure names depends on
the SQL statement in which the unqualified name appears:
v If an unqualified name is the main object of an ALTER, CREATE, COMMENT
ON, DROP, GRANT, or REVOKE statement, the name is implicitly qualified with
a schema name as follows:
– In a static statement, the implicit schema name is the identifier specified in t
he
QUALIFIER option of the BIND subcommand used to bind the SQL
statements. If this bind option was not used when the plan or package was
created or last rebound, the implicit qualifier is the authorization ID of the
owner of the plan or package.
– In a dynamic statement, the implicit schema name is the SQL authorization ID
in the CURRENT SQLID special register.
v Otherwise, the implicit schema name for the unqualified name is determined as
follows:
– For data type names, DB2 searches the SQL path and selects the first
schema in the path such that the data type exists in the schema and the user
has authorization to use the data type.
– For function names, DB2 uses the SQL path in conjunction with function
resolution, as described under “Function resolution” on page 106.
– For stored procedure names4, DB2 searches the SQL path and selects the
first schema in the path such that the schema contains a procedure with the
same name and number of parameters and the user has authorization to use
the procedure.
For information on the SQL path, see “Schemas and the SQL path”.
Schemas and the SQL path
The SQL path is an ordered list of schema names. DB2 uses the path to resolve
the schema name for unqualified data type, function, and stored procedure names
that appear in any context other than as the main object of an ALTER, CREATE,
DROP, COMMENT ON, GRANT or REVOKE statement.5 Searching through the
path from left to right, DB2 implicitly qualifies the object name with the first
schema
name in the path that contains the same object with the same unqualified name fo
r
which the user has appropriate authorization. For procedures, DB2 selects a
matching procedure name only if the number of parameters is also the same. For
functions, DB2 uses a process called function resolution in conjunction with the
SQL path to determine which function to choose because several functions with th
e
same name can reside in a schema. (For details, see “Function resolution” on
page 106.)
For example, if the SQL path is SMITH, XGRAPHIC, SYSIBM and an unqualified
distinct type name MYTYPE was specified, DB2 looks for MYTYPE first in schema
SMITH, then XGRAPHIC, and then SYSIBM.
The PATH bind option establishes the SQL path used to resolve:
v Unqualified data type and function names in static SQL statements
4. In CALL statements only.
5. The SQL path does not apply to unqualified procedure names in ASSOCIATE LOCAT
OR and DESCRIBE PROCEDURE
statements. For these statements, an implicit schema name is not generated.
Naming Conventions
40 SQL Reference
v Unqualified procedure names in SQL CALL statements that specify the procedure
name as a literal (CALL ’literal’)
If the PATH bind option was not specified when the plan or package was created o
r
last rebound, its default value is: SYSIBM, SYSFUN, SYSPROC, plan or package
qualifier.
The CURRENT PATH special register determines the SQL path used to resolve:
v Unqualified data type and function names in dynamic SQL statements
v Unqualified procedure names in SQL CALL statements that specify the procedure
name in a host variable (CALL host-variable)
Generally, the initial value of the CURRENT PATH special register is:
v The value of the PATH bind option, or
v SYSIBM, SYSFUN, SYSPROC, value of CURRENT SQLID special register if the
PATH bind option was not specified.
For additional details on the initial value of CURRENT PATH special register and
changing its value, see “CURRENT PATH” on page 88 and “SET PATH” on
page 865.
If schema SYSIBM or SYSPROC is not explicitly specified in the SQL path, the
schema is implicitly assumed at the front of the path; if both are not specified
, they
are assumed in the order of SYSIBM, SYSPROC. For example, assume that the
SQL path is explicitly specified as SYSIBM, GEORGIA, SMITH. As an implicitly
assumed schema, SYSPROC is added to the beginning of the explicit path
effectively making the path:
SYSPROC, SYSIBM, GEORGIA, SMITH
Aliases and synonyms
A table or view can be referred to in an SQL statement by its name, by an alias
that
has been defined for its name, or by a synonym that has been defined for its nam
e.
Thus, aliases and synonyms can be thought of as alternate names for tables and
views.
The option of referencing a table or view by an alias or a synonym is not explic
itly
shown in the syntax diagrams or mentioned in the description of SQL statements.
Nevertheless, an alias or a synonym can be used wherever a table or view can be
referred to in an SQL statement, with two exceptions: a local alias cannot be us
ed
in CREATE ALIAS, and a synonym cannot be used in CREATE SYNONYM. If an
alias is used in CREATE SYNONYM, it must identify a table or view at the current
server. The synonym is defined on the name of that table or view. If a synonym i
s
used in CREATE ALIAS, the alias is defined on the name of the table or view
identified by the synonym.
The effect of using an alias or a synonym in an SQL statement is that of text
substitution. For example, if A is an alias for table Q.T, one of the steps invo
lved in
the preparation of SELECT * FROM A is the replacement of A by Q.T . Likewise,
if
S is a synonym for Q.T, one of the steps involved in the preparation of SELECT *
FROM S is the replacement of S by Q.T .
The differences between aliases and synonyms are as follows:
v SYSADM or SYSCTRL authority or the CREATE ALIAS privilege is required to
define an alias. No authorization is required to define a synonym.
Schemas and the SQL path
Chapter 2. Language elements 41
v An alias can be defined on the name of a table or view, including tables and
views that are not at the current server. A synonym can only be defined on the
name of a table or view at the current server.
v An alias can be defined on an undefined name. A synonym can only be defined
on the name of an existing table or view.
v Dropping a table or view has no effect on its aliases. But dropping a table or
view does drop its synonyms.
v An alias is a qualified name that can be used by any authorization ID. A synon
ym
is an unqualified name that can only be used by the authorization ID that create
d
it.
v An alias defined at one DB2 subsystem can be used at another DB2 subsystem.
A synonym can only be used at the DB2 subsystem where it is defined.
v When an alias is used, an error occurs if the name that it designates is undef
ined
or is the name of an alias at the current server. (The alias can represent anoth
er
alias at a different server, which can represent yet another alias at yet anothe
r
server as long as eventually a referenced alias represents a table or view.) Whe
n
a synonym is used, this error cannot occur.
Authorization IDs and authorization-names
An authorization ID is a character string that designates a defined set of privi
leges.
Processes can successfully execute SQL statements only if they have the authorit
y
to perform the specified functions. A process derives this authority from its
authorization IDs. An authorization ID can also designate a user or a group of
users, but DB2 does not control this property.
DB2 uses authorization IDs to provide:
v Authorization checking of SQL statements
v Implicit qualifiers for database objects like tables, views, aliases, and inde
xes
Whenever a connection is established between DB2 and a process, DB2 obtains an
authorization ID and passes it to the authorization exit. The list of one or mor
e
authorization IDs returned by the exit are used as the authorization IDs of the
process.
Every process has exactly one primary authorization ID. Any other authorization
IDs
of a process are secondary authorization IDs. As explained below, the use of the
se
authorization IDs depends on whether the process is a bind process or an
application process.
An authorization-name specified in an SQL statement should not be confused with
an authorization ID of a process. For example, assume that SMITH is your TSO
logon, DYNAMICRULES run behavior is in effect, and you execute the following
statements interactively:
CREATE TABLE TDEPT LIKE DSN8710.DEPT;
GRANT SELECT ON TDEPT TO KEENE;
Also assume that your site has not replaced the default exit routine for connect
ion
authorization and that you have not executed SET CURRENT SQLID. Thus, when
the GRANT statement is prepared and executed by SPUFI, the SQL authorization
ID is SMITH. KEENE is an authorization name specified in the GRANT statement.
Authorization to execute the GRANT statement is checked against SMITH, and
SMITH is the implicit qualifier of TDEPT. The authorization rule is that the pri
vilege
Aliases and Synonyms
42 SQL Reference
|
|
|
set designated by SMITH must include the SELECT privilege with the GRANT
option on SMITH.TDEPT. There is no check involving KEENE.
If SMITH is the implicit qualifier for a statement that contains NAME1, NAME1
identifies the same object as SMITH.NAME1. If the implicit qualifier is other th
an
SMITH, NAME1 and SMITH.NAME1 identify different objects.
Authorization IDs and schema names
An authorization ID that is the same as the name of a schema implicitly has the
CREATEIN, ALTERIN, and DROPIN privileges for that schema.
Authorization IDs and statement preparation
A process that creates a plan or package is called a bind process. The connectio
n
with DB2 is the result of the execution of a BIND or REBIND subcommand. Both
subcommands allow for the specification of the authorization ID of the owner of
the
plan or package. The authorization ID specified as owner must be one of the
authorization IDs of the process, unless one of these has SYSADM or SYSCTRL
authority. In this case, the owner can be set to any value. BINDAGENT can specif
y
an owner other than himself (or one of his representatives), but it has to be
someone that granted him BINDAGENT. The default owner for BIND is the primary
authorization ID. The default owner for REBIND is the previous owner of the plan
or
package (ownership is unchanged if an owner is not explicitly specified). BIND a
nd
REBIND are discussed in Chapter 2 of DB2 Command Reference.
The authorization ID used for the authorization checking of embedded SQL
statements is that of the owner of the plan or package. If an embedded SQL
statement refers to tables or views at a DB2 subsystem other than the one at whi
ch
the plan or package is bound, the authorization checking is deferred until run t
ime.
For more information on this, see “Authorization IDs and remote execution” on
page 46.
If VALIDATE(BIND) is specified, the privileges required to use or manipulate obj
ects
at the DB2 subsystem at which the plan or package is bound must exist at bind
time. If the privileges or the referenced objects do not exist and
SQLERROR(NOPACKAGE) is in effect, the bind operation is unsuccessful. If
SQLERROR(CONTINUE) is specified, then the bind is successful and any
statements in error are flagged. If any statements in error are flagged, an erro
r will
occur when you attempt to execute them at run time.
If a plan or package is bound with VALIDATE(RUN), authorization checking is stil
l
performed at bind time, but the referenced objects and the privileges required t
o
use these objects need not exist at this time. If any privilege required for a
statement does not exist at bind time, an authorization check is performed
whenever the statement is first executed within a unit of work, and all privileg
es
required for the statement must exist at that time. If any privilege does not ex
ist,
execution of the statement is unsuccessful. When the authorization check is
performed at run time, it is performed against the plan or package owner, not th
e
SQL authorization ID. For the effect of this option on cursors, see “DECLARE
CURSOR” on page 665.
Authorization IDs and dynamic SQL
This discussion applies to dynamic SQL statements that refer to objects at the
current server. For those that refer to objects elsewhere, see “Authorization IDs
and
remote execution” on page 46.
Authorization IDs and Authorization-names
Chapter 2. Language elements 43
Bind option DYNAMICRULES determines the authorization ID that is used for
checking authorization when dynamic SQL statements are processed. In addition,
the option also controls other dynamic SQL attributes such as the implicit quali
fier
that is used for unqualified alias, index, table, and view names; the source for
application programming options; and whether certain SQL statements can be
invoked dynamically.
The set of values for the authorization ID and other dynamic SQL attributes is c
alled
the dynamic SQL statement behavior. The four possible behaviors are run, bind,
define, and invoke. As Table 2 shows, the combination of the value of the
DYNAMICRULES bind option and the run-time environment determines which of
behavior is used. DYNAMICRULES(RUN), which implies run behavior, is the
default.
Table 2. How DYNAMICRULES and the run-time environment determine dynamic SQL
statement behavior
DYANMICRULES value
Behavior of dynamic SQL statements
Stand-alone program
environment
User-defined function or
stored procedure
environment
RUN Run behavior Run behavior
BIND Bind behavior Bind behavior
DEFINERUN Run behavior Define behavior
DEFINEBIND Bind behavior Define behavior
INVOKERUN Run behavior Invoke behavior
INVOKEBIND Bind behavior Invoke behavior
Note: BIND and RUN values can be specified for both packages and plans. The othe
r values
can be specified only for packages.
In the following behavior descriptions, a package that runs under a user-defined
function or stored procedure package is a package whose associated program
meets one of the following conditions:
v The program is called by a user-defined function or stored procedure.
v The program is in a series of nested calls that start with a user-defined func
tion
or stored procedure.
Run behavior
DB2 uses the authorization ID of the application process and the SQL
authorization ID (the value of special register CURRENT SQLID) for
authorization checking of dynamic SQL statements.
A process that uses a plan and its associated packages is called an
application process. At any time, the SQL authorization ID is the value of
CURRENT SQLID. This SQL special register can be initialized by the
connection or sign-on exit routine. If the exit does not set a value, the initia
l
value of CURRENT SQLID is the primary authorization ID of the process.
You can use the SQL statement SET CURRENT SQLID to change the
value of CURRENT SQLID. Unless some authorization ID of the process
has SYSADM authority, the new value must be one of the authorization IDs
of the process. Thus, CURRENT SQLID usually contains either the primary
authorization ID of the process or one of its secondary authorization IDs.
Privilege set: If the dynamically prepared statement is other than an
ALTER, CREATE, DROP, GRANT, RENAME, or REVOKE statement, each
Authorization IDs and Authorization-names
44 SQL Reference
privilege required for the statement can be a privilege designated by any
authorization ID of the process. Therefore, the privilege set is the union of
the set of privileges held by each authorization ID.
If the dynamic SQL statement is an ALTER, CREATE, DROP, GRANT,
RENAME, or REVOKE statement, the only authorization ID that is used for
authorization checking is the SQL authorization ID. Therefore, the privilege
set is the privileges held by that single authorization ID of the process.
Implicit qualification: As explained under “Qualification of unqualified
object names” on page 39, when an SQL statement is dynamically
prepared, the SQL authorization ID is also used as the implicit qualifier for
all unqualified tables, aliases, views, and indexes.
Bind behavior
The same rules that are used to determine the authorization ID for static
(embedded) statements are used for dynamic statements. DB2 uses the
primary authorization ID of the owner of the package or plan for
authorization checking of dynamic SQL statements, as explained in detail
under “Authorization IDs and statement preparation” on page 43.
Privilege set: The privilege set is the privileges that are held by the primary
authorization ID of the owner of the package or plan.
Implicit qualification: The identifier specified in the QUALIFIER option of
the bind command that is used to bind the SQL statements is the implicit
qualifier for all unqualified tables, views, aliases, and indexes. If this bind
option was not used when the plan or package was created or last
rebound, the implicit qualifier is the authorization ID of the owner of the plan
or package.
Define behavior
Define behavior applies only if the dynamic SQL statement is in a package
that is run as a stored procedure or user-defined function (or runs under a
stored procedure or user-defined function package), and the package was
bound with DYNAMICRULES(DEFINEBIND) or
DYNAMICRULES(DEFINERUN). DB2 uses the authorization ID of the
stored procedure or user-defined function owner (the definer) for
authorization checking of dynamic SQL statements in the application
package.
Privilege set: The privilege set is the privileges that are held by the
authorization ID of the stored procedure or user-defined function owner.
Implicit qualification: The authorization ID of the stored procedure or
user-defined function owner is also the implicit qualifier for unqualified table
,
view, alias, and index names.
Invoke behavior
Invoke behavior applies only if the dynamic SQL statement is in a package
that is run as a stored procedure or user-defined function (or runs under a
stored procedure or user-defined function package), and the package was
bound with DYNAMICRULES(INVOKEBIND) or
DYNAMICRULES(INVOKERUN). DB2 uses the authorization ID of the
stored procedure or user-defined function invoker for authorization checking
of dynamic SQL statements in the application package.
Privilege set: The privilege set is the privileges that are held by the
authorization ID of the stored procedure or user-defined function invoker.
However, if the invoker is the primary authorization ID of the process or the
CURRENT SQLID value, secondary authorization IDs are also checked if
Authorization IDs and Authorization-names
Chapter 2. Language elements 45
they are needed for the required authorization. Therefore, in that case, the
privilege set is the union of the set of privileges held by each authorization
ID.
Implicit qualification: The authorization ID of the stored procedure or
user-defined function invoker is also the implicit qualifier for unqualified
table, view, alias, and index names.
Restricted statements when run behavior does not apply: When bind, define, or
invoke behavior is in effect, you cannot use the following dynamic SQL statement
s:
ALTER, CREATE, DROP, GRANT, RENAME, and REVOKE.
For more information on authorization and examples of determining authorization
for
dynamic SQL statements, see Part 3 of DB2 Administration Guide. For complete
details about the DYNAMICRULES bind option, see DB2 Command Reference.
Authorization IDs and remote execution
The authorization rules for remote execution depend on whether the distributed
operation is:
v DRDA access with a DB2 for OS/390 and z/OS server and requester
v DRDA access with a server and requester other than DB2
v DB2 private protocol access
DRDA access with DB2 for OS/390 and z/OS only
Any static statement executed using DRDA access is in a package bound at a
server other than the local DB2. Before the package can be bound, its owner must
have the BINDADD privilege and the CREATE IN privilege for the package’s
collection. Also required are enough privileges to execute the package’s static SQ
L
statements that refer to data on that server. All these privileges are recorded
in the
DB2 catalog of the server, not that of the local DB2. Such privileges must be
granted by GRANT statements executed at the server. This allows the server to
control the creation and use of packages that are run from other DBMSs.
A user who invokes an application that has a plan at the local DB2 must have the
EXECUTE privilege on the plan recorded in the DB2 catalog of the requester. If t
he
application uses a package bound at a server other than the local DB2 and the
package is not a user-defined function, stored procedure, or trigger package, th
e
plan owner must have the EXECUTE privilege on the package recorded in the DB2
catalog of the server. The plan needs no other privilege to execute the package.
EXECUTE authority is also required to use a package that is a user-defined
function, stored procedure, or trigger package; however, the plan owner is not t
he
required holder of the privilege, as explained in Part 3 (Volume 1) of DB2
Administration Guide. In the case of trigger packages, the authorization ID of t
he
SQL statement that activates the trigger must have the EXECUTE privilege on the
trigger. Again, all these privileges must be recorded in the DB2 catalog of the
server.
Having the appropriate privileges recorded as described above allows the executi
on
of the static SQL statements in the package, and the execution of dynamic SQL
statements if DYNAMICRULES bind, define, or invoke behavior is in effect. If
DYNAMICRULES run behavior is in effect, the authorization rules for dynamic SQL
statements is different. Authorization for the execution of dynamic SQL statemen
ts
must come from the set of authorization IDs derived during connection processing
.
An application goes through connection processing when it first connects to a
Authorization IDs and Authorization-names
46 SQL Reference
server or when it reuses a CICS or IMS thread that has a different primary
authorization ID. For details on connection processing, see Part 3 (Volume 1) of
DB2 Administration Guide.
If an application uses Recoverable Resources Manager Services attachment facilit
y
(RRSAF) and has no plan, authority to execute the package is determined in the
same way as when the requester is not DB2 for OS/390 and z/OS, which is
described next under “DRDA access with a server or requester other than DB2”.
DRDA access with a server or requester other than DB2
DB2 for OS/390 and z/OS as the server: If the requester is not a DB2 for OS/390
and z/OS subsystem, there is no DB2 application plan involved. In this case, the
privilege set of the authorization ID, which is determined by the DYNAMICRULES
behavior, must have the EXECUTE privilege on the package. Dynamic SQL
statements in the package are executed according to the DYNAMICRULES
behavior, as described in “Authorization IDs and dynamic SQL” on page 43.
DB2 for OS/390 and z/OS as the requester: The authorization rules for remote
execution are those of the server.
DB2 private protocol access
Any statement that refers to a table or view at a DB2 subsystem other than the
current server and is bound with bind option DBPROTOCOL(PRIVATE) is executed
using DB2 private protocol access. Such statements are processed as deferred
embedded SQL statements. The additional cost of the dynamic bind occurs once for
every unit of work where the statement is executed. Authorization to execute suc
h
statements is checked against the owner of a plan or package. Authorization IDs
for
executing dynamic statements are handled just as they are for DRDA access. In
either case, the pertinent privileges must be recorded in the catalog of the DBM
S
that executes the statement.
Authorization ID translations
Three authorization IDs played roles in the foregoing discussion. These are the
user’s primary authorization ID and those for the owner of the application plan an
d
the owner of a package. Each of these is sent to the remote DBMS. And each may
undergo translations before it is used.
For example, a user known as SMITH at the local DBMS could be known, after
translation, as JONES at the server. Likewise, a package owner known as GRAY
could be known as WINTERS at the server. If so, JONES or WINTERS would be
used, instead of SMITH or GRAY, to determine the authorization ID for dynamic
SQL statements in the package. If the DYNAMICRULES run behavior applies,
JONES, who is executing the dynamic statement at the server, is used. If
DYNAMICRULES bind behavior applies, WINTERS, the package owner at the
server, is used.
Two sets of communications database (CDB) catalog tables control the translation
s.
One set is at the local DB2, and the other set is at the remote DB2. Translation
can
take place at either or both sites. For how to use and maintain these tables, se
e
Part 3 (Volume 1) of DB2 Administration Guide.
Other security measures
The fact that DB2 authority requirements are satisfied does not guarantee that a
user has access to a given server. Other security measures may also come into
play. For example, requests to execute remote SQL statements could be denied
Authorization IDs and Authorization-names
Chapter 2. Language elements 47
based on Resource Access Control Facility (RACF®) considerations. Developing
such security measures is discussed in Part 3 (Volume 1) of DB2 Administration
Guide.
Data types
The smallest unit of data that can be manipulated in SQL is called a value. How
values are interpreted depends on the data type of their source. The sources of
values are:
Columns
Constants
Expressions
Functions
Host variables
Special registers
DB2 supports both IBM-supplied data types (built-in data types) and user-defined
data types (distinct types). This section describes the built-in data types. For
a
description of distinct types, see “Distinct types” on page 60.
Figure 5 shows the built-in data types that DB2 supports.
Nulls: All data types include the null value. Distinct from all nonnull values,
the null
value is a special value that denotes the absence of a (nonnull) value. Although
all
data types include the null value, some sources of values cannot provide the nul
l
value. For example, constants, columns that are defined as NOT NULL, and special
Figure 5. Built-in data types supported by DB2
Authorization IDs and Authorization-names
48 SQL Reference
registers cannot contain null values; the COUNT and COUNT_BIG functions cannot
return a null value; and ROWID columns cannot store a null value although a null
value can be returned for a ROWID column as the result of a query.
Character strings
A character string is a sequence of bytes. The length of the string is the numbe
r of
bytes in the sequence. If the length is zero, the value is called the empty stri
ng. The
empty string should not be confused with the null value.
Except for C NUL-terminated strings, the length of a varying-length string is
specified by the value of its length control field. For varying-length character
strings,
the length control field specifies the number of bytes.
Each character string has a subtype of SBCS, MIXED, or BIT.
v The bytes of a character string with subtype SBCS represent characters from a
single-byte character set (SBCS). Such strings are called SBCS data.
v The bytes of a character string with subtype MIXED can represent a mixture of
characters from a multibyte character set (MBCS), which includes cahracters
from a single-byte chanracter set (SBCS). Strings that may contain MBCS
characters are called mixed data. EBCDIC mixed data may contain shift
characters, which are not MBCS data. Unicode data is always MIXED, regardless
of the MIXED option on the DSNTIPF install option panel.
v The bytes of a character string with BIT subtype do not represent characters;
therefore, character conversion never occurs for these strings. Such strings are
called BIT data.
Character strings with a CLOB data type can only have an SBCS or MIXED
subtype.
Character subtypes provide a simple and portable way of specifying the CCSID of
a
character string column. The subtype is implicitly or explicitly specified when
the
column is defined in a CREATE or ALTER TABLE statement. The default depends
on which encoding scheme is in use. With Unicode, the default is MIXED. With
ASCII and EBCDIC, the default is SBCS or MIXED depending on the value of the
field MIXED DATA on installation panel DSNTIPF. The following list shows the
CCSID for each subtype:
BIT The CCSID is X FFFF (65535).
SBCS The CCSID is the system CCSID for SBCS data.
MIXED The CCSID is the system CCSID for mixed data.
The FOREIGNKEY column of the SYSCOLUMNS catalog table stores information
about the subtype of a character string column. An administrator can update this
column to change the subtype of existing columns. DB2 does not ensure that the
bytes of a character string are consistent with its CCSID and does not use CCSID
s
for any purpose other than character conversion.
The effect of encoding schemes on DBCS characters in mixed
strings
The method of representing DBCS characters within a mixed string differs among
the encoding schemes.
v ASCII reserves a set of code points for SBCS characters and another set as the
first half of DBCS characters. Upon encountering the first half of a DBCS
character, the system knows that it is to read the next byte in order to obtain
the
complete character.
Data Types
Chapter 2. Language elements 49
#
#
#
#
|
|
|
|
|
v EBCDIC makes use of two special code points:
– A shift-out character (X 0E ) to introduce a string of DBCS characters.
– A shift-in character (X 0F ) to end a string of DBCS characters.
DBCS sequences within mixed data strings are recognized as the string is read
from left to right. At any time, the recognizer is in SBCS mode or DBCS mode. In
SBCS mode, which is the initial mode, any byte other than a shift-out is
interpreted as an SBCS character. When a shift-out is read, the recognizer enter
s
DBCS mode. In DBCS mode, the next byte and every second byte after that byte
is interpreted as the first byte of a DBCS character unless it is a shift charac
ter. If
the byte is a shift-out, an error occurs. If the byte is a shift-in, the recogni
zer
returns to SBCS mode. An error occurs if the recognizer is in DBCS mode after
processing the last byte of the string. Because of the shift characters, EBCDIC
mixed data requires more storage than ASCII mixed data.
v UTF-8 is a varying-length encoding of byte sequences with the high bits
indicating the part of the sequence to which a byte belongs. The first byte
indicates the number of bytes to follow in a byte sequence.
v UTF-16 uses a fixed 16-bit code assignment for each character, except for
characters encoded by surrogates, which consist of a pair of 16-bit values.
Examples
CHAR(9) in ASCII.
CHAR(13) in EBCDIC.
CHAR(11) in Unicode.
Because of the differences of the representation of mixed data strings in ASCII
and
EBCDIC, mixed data is not transparently portable. To minimize the effects of the
se
differences, use varying-length strings in applications that require mixed data
and
operate on both ASCII and EBCDIC data.
DB2 and SBCS defaults
For a DB2 installation with SBCS, the default encoding scheme is ASCII or EBCDIC
and the value of field MIXED DATA on installation panel DSNTIPF is NO. The
subtype of character strings is SBCS with SBCS being the default. The values of
fields ASCII CODED CHAR SET or EBCDIC CODED CHAR SET determine the
system CCSID that identifies the SBCS coded character set used for that DB2. The
default for Unicode data is mixed.
DB2 and DBCS defaults
For a DB2 installation with DBCS, the default encoding scheme is ASCII or EBCDIC
and the value of field MIXED DATA on installation panel DSNTIPF is YES. For
ASCII and EBCDIC, the subtype of character strings is SBCS, BIT, or MIXED,with
MIXED being the default. The values of fields ASCII CODED CHAR SET or
EBCDIC CODED CHAR SET determine the system CCSIDs used for SBCS data,
mixed data, and graphic data. For Unicode, the MIXED DATA field is not relevant
because the subtype for Unicode data is always mixed.
Data Types
50 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ASCII and EBCDIC are structured so that some data is represented in SBCS
characters and some data is represented in DBCS or mixed (MBCS) characters.
Mixed data allows both SBCS and DBCS characters as does UTF-8, in a sense. In
UTF-8, A–Z, a–z, 0–9, and a few other characters are SBCS while everything else
is MBCS. UTF-16 is different. In UTF-16, A–Z, a–z, 0–9, and most everything else,
except surrogate characters, are DBCS. Surrogates consist of a pair of 16-bit
values.
A mixed data string can have zero or more sequences of SBCS characters and
zero or more sequences of multiple-byte characters. Each EBCDIC multiple-byte
sequence must be preceded by the shift-out control character (X 0E ) and followe
d
by the shift-in control character (X 0F ). There must be an even number of bytes
between the shift characters and each pair of bytes is assumed to represent a
DBCS character.
DB2 recognizes DBCS sequences within mixed data strings when performing
character-sensitive operations at a DB2 installation with DBCS. These operations
include parsing, character conversion, and the pattern matching specified by the
LIKE predicate. DB2 also recognizes DBCS sequences:
v In source language statements, static SQL statements, and deferred embedded
SQL statements if the GRAPHIC precompiler option is implicitly or explicitly
specified
v In dynamic SQL statements if DYNAMICRULES bind, define, or invoke behavior
is in effect, the value of installation panel field USE FOR DYNAMICRULES is
NO, and the GRAPHIC precompiler option is implicitly or explicitly specified
Fixed-length character strings
All the values of a column with a fixed-length character string data type have t
he
same length, which is determined by the length attribute of the column. The leng
th
attribute must be between 1 and 255 inclusive. Every fixed-length string column
is a
short string column. A fixed-length character string column can also be called a
CHAR or CHARACTER column.
Varying-length character strings
The types of varying-length character strings are:
v VARCHAR (or synonyms CHAR VARYING and CHARACTER VARYING)6
v CLOB (or synonyms CHAR LARGE OBJECT and CHARACTER LARGE
OBJECT)
The values of a column with any one of these string types can have different
lengths. The length attribute of the column determines the maximum length a valu
e
can have.
For a VARCHAR column, the length attribute must be between 1 and m inclusive,
where m is determined by the maximum record size as described in “Maximum
record size” on page 624 in the description of the CREATE TABLE statement. For a
CLOB column, the length attribute must be between 1 and 2 147 483 647 inclusive.
(2 147 483 647 is 2 gigabytes minus 1 byte.) For more information about CLOBs,
see “Large objects (LOBs)” on page 53.
6. The syntax of the ALTER and CREATE TABLE statements allows a column to be def
ined as LONG VARCHAR as an alternative
for VARCHAR(a) where a is the maximum number of characters that is associated wi
th the column. However, after processing the
CREATE or ALTER TABLE statement, DB2 considers the column to be VARCHAR(a).
Data Types
Chapter 2. Language elements 51
|
|
|
|
|
|
|
A VARCHAR column with a maximum length that is greater than 255 bytes or a
CLOB column of any length is a long string column. For the restrictions that app
ly
to the use of long string columns, see “Restrictions using long strings” on page 54.
Character string host variables
Host variables with CHAR and CLOB string types can be defined in all host
languages. (In C, CHAR string variables are limited to a length of 1.) Host vari
ables
with a VARCHAR string type can be defined in all host languages except Fortran.
In
Assembler, C, and COBOL, VARCHAR string variables are simulated as described
in Part 2 of DB2 Application Programming and SQL Guide. In C, VARCHAR string
variables can also be represented by NUL-terminated strings.
A VARCHAR string variable with a maximum length that is greater than 255 bytes
or a CLOB string variable of any length is a long string variable. Long string
variables are subject to the same restrictions as long string columns. For
information, see “Restrictions using long strings” on page 54.
Graphic strings
A graphic string is a sequence of DBCS characters. The length of the string is t
he
number of characters in the sequence. Like character strings, graphic strings ca
n
be empty. An empty string should not be confused with the null value.
Fixed-length graphic strings
All the values of a column with a fixed-length graphic string data type have the
same length, which is determined by the length attribute of the column. The leng
th
attribute must be between 1 and 127 inclusive. Every fixed-length graphic string
column is a short string column. A fixed-length graphic string column can also b
e
called a GRAPHIC column.
Varying-length graphic strings
The types of varying-length graphic strings are:
v VARGRAPHIC7
v DBCLOB
The values of a column with any one of these string types can have different
lengths. The length attribute of the column determines the maximum length a valu
e
can have. For varying-length graphic strings, the length control field specifies
the
number of MBCS (multi-byte) characters, with each character represented by a pai
r
of bytes, except in UTF-16 where surrogates use four bytes for each character.
For VARGRAPHIC columns, the length attribute of the column must be between 1
and m inclusive, where m is determined by the maximum record size as described
in “Maximum record size” on page 624 in the description of the CREATE TABLE
statement. For DBCLOB columns, the length attribute must be between 1 and
1 073 741 823 inclusive. In all cases, the length control field of a varying-len
gth
graphic string indicates the number of characters, not bytes. For UTF-16, two DB
CS
characters can be used to describe a glyph, but the characters are still conside
red
DBCS characters. For more information about DBCLOBs, see “Large objects
(LOBs)” on page 53.
7. The syntax of the ALTER and CREATE TABLE statements allows a column to be def
ined as LONG VARGRAPHIC as an
alternative for VARGRAPHIC(a) where a is the maximum number of characters that i
s associated with the column. However, after
processing the CREATE or ALTER TABLE statement, DB2 considers the column to be V
ARGRAPHIC(a).
Data Types
52 SQL Reference
|
|
|
A VARGRAPHIC column with a maximum length that is greater than 127 characters
or a DBCLOB column of any length is a long string column. For the restrictions t
hat
apply to the use of long string columns, see “Restrictions using long strings” on
page 54.
Graphic string host variables
Host variables with a graphic string type can be defined in all host languages
except Fortran.
A VARGRAPHIC string variable with a maximum length that is greater than 127
characters or a DBCLOB string variable of any length is a long string variable.
Long
string variables are subject to the same restrictions as long string columns. Fo
r
information, see “Restrictions using long strings” on page 54.
Binary strings
A binary string is a sequence of bytes. The length of a binary string (BLOB stri
ng) is
the number of bytes in the sequence. The CCSID is X FFFF (65535).
For a BLOB column, the length attribute must be between 1 and 2 147 483 647
inclusive. (2 147 483 647 is 2 gigabytes minus 1 byte.)
A host variable with a BLOB string type can be defined in all host languages.
For more information about BLOBs, see “Large objects (LOBs)”.
Large objects (LOBs)
The term large object (LOB) refers to any of the following data types:
CLOB A character large object (CLOB) is a varying-length string with a
maximum length of 2 147 483 647 bytes (2 gigabytes minus 1 byte).
A CLOB is designed to store large SBCS data or mixed data, such
as lengthy documents. For example, you can store information such
as an employee resume, the script of a play, or the text of novel in
a CLOB. Alternatively, you can store such information in UTF-8 in a
mixed CLOB. A CLOB is a varying-length character string.
DBCLOB A double-byte character large object (DBCLOB) is a varying-length
string with a maximum length of 1 073 741 823 double-byte
characters. A DBCLOB is designed to store large DBCS data. For
example, you could store the information mentioned for CLOB (an
employee resume, the script for a play, or the text of a novel) in
UTF-16 in a DBCLOB. A DBCLOB is a varying-length graphic
string.
BLOB A binary large object (BLOB) is a varying-length string with a
maximum length of 2 147 483 647 bytes (2 gigabytes minus 1 byte).
A BLOB is designed to store non-traditional data such as pictures,
voice, and mixed media. BLOBs can also store structured data for
use by distinct types and user-defined functions. A BLOB is
considered to be a binary string.
Although BLOB strings and FOR BIT DATA character strings might
be used for similar purposes, the two data types are not
compatible. The BLOB function can be used to change a FOR BIT
DATA character string into a BLOB string.
Data Types
Chapter 2. Language elements 53
|
|
|
|
|
|
Each LOB column is a long string column, and each LOB string variable is a long
string variable. For information on the restrictions that apply to the use of lo
ng
strings and the additional restrictions that apply only to LOBs, see “Restrictions
using long strings”.
When an application does not need a LOB value to be stored in application
memory, the application can use a large object locator (LOB locator) to referenc
e
the LOB value.
A LOB locator is a host variable with a value that represents a single LOB value
in
the database server. A LOB locator can also represent a LOB expression, such as:
SUBSTR( <lob 1> CONCAT <lob 2> CONCAT <lob 3>, <start>, <length> )
For information on manipulating LOBs with LOB locators, see Part 3 of DB2
Application Programming and SQL Guide.
Restrictions using long strings
A long string has one of the following varying-length string data types:
v For character strings. A VARCHAR string with a maximum length that is greater
than 255 bytes or any CLOB string.
v For graphic strings. A VARGRAPHIC string with a maximum length that is greater
than 127 characters or any DBCLOB string.
v For binary strings. Any BLOB string.
Table 3 indicates the contexts in which long strings cannot be referenced. The
restrictions differ slightly for long strings with LOB data types (CLOB, DBCLOB,
and
BLOB).
Table 3. Contexts in which long strings cannot be referenced
Context of usage VARCHAR (>255) or
VARGRAPHIC (>127)
LOB (CLOB, DBCLOB, or BLOB)
A GROUP BY clause Not allowed Not allowed
An ORDER BY clause Not allowed Not allowed
A CREATE INDEX statement Not allowed Not allowed
A SELECT DISTINCT statement Not allowed Not allowed
A subselect of a UNION without the
ALL keyword
Not allowed Not allowed
A host variable in a EXECUTE
IMMEDIATE or a PREPARE
statement
— Not allowed
Predicates Cannot be used in any predicate
except EXISTS and LIKE. This
restriction includes a
simple-when-clause in a CASE
expression. expression WHEN
expression in a simple-when-clause is
equivalent to a predicate with
expression=expression.
Cannot be used in any predicate
except EXISTS, LIKE, and NULL. This
restriction includes a
simple-when-clause in a CASE
expression. expression WHEN
expression in a simple-when-clause is
equivalent to a predicate with
expression=expression.
The definition of primary, unique, and
foreign keys
Not allowed Not allowed
Check constraints — Cannot be specified for a LOB column
Data Types
54 SQL Reference
Table 3. Contexts in which long strings cannot be referenced (continued)
Context of usage VARCHAR (>255) or
VARGRAPHIC (>127)
LOB (CLOB, DBCLOB, or BLOB)
Field procedure — Cannot be specified for a LOB
column.
Parameters of built-in functions Some functions that allow varying-length charac
ter strings, varying-length
graphic strings, or both types of strings as input arguments do not support
VARCHAR or VARGRAPHIC long strings, CLOB or DBCLOB strings, or both
as input. See the description of the individual functions in “Chapter 3. Built-in
functions” on page 153 for the data types that are allowed as input to each
function.
Distributed data applications — LOB columns cannot be used if
remote access is performed with DB2
private protocol access.
Numbers
The numeric data types are binary integer, floating-point, and decimal. Binary
integer includes small integer and large integer. Floating-point includes single
precision and double precision. Binary numbers are exact representations of
integers, decimal numbers are exact representations of real numbers, and
floating-point numbers are approximations of real numbers.
All numbers have a sign and a precision. When the value of a column or the resul
t
of an expression is a decimal or floating-point zero, its sign is positive. The
precision of binary integers and decimal numbers is the total number of binary o
r
decimal digits excluding the sign. The precision of floating-point numbers is ei
ther
single or double, referring to the number of hexadecimal digits in the fraction.
Small integer (SMALLINT)
A small integer is a System/390 binary integer with a precision of 15 bits. The
range
of small integers is -32768 to +32767.
Large integer (INTEGER)
A large integer is a System/390 binary integer with a precision of 31 bits. The
range
of large integers is -2147483648 to +2147483647.
Single precision floating-point (REAL)
A single precision floating-point number is a System/390 short (32 bits)
floating-point number. The range of single precision floating-point numbers is a
bout
-7.2E+75 to 7.2E+75. In this range, the largest negative value is about -5.4E-79
,
and the smallest positive value is about 5.4E-079.
Double precision floating-point (DOUBLE or FLOAT)
A double precision floating-point number is a System/390 long (64 bits)
floating-point number. The range of double precision floating-point numbers is a
bout
-7.2E+75 to 7.2E+75. In this range, the largest negative value is about -5.4E-79
,
and the smallest positive value is about 5.4E-079.
Decimal (DECIMAL or NUMERIC)
A decimal number is a System/390 packed decimal number with an implicit decimal
point. The position of the decimal point is determined by the precision and the
scale
of the number. The scale, which is the number of digits in the fractional part o
f the
number, cannot be negative or greater than the precision. The maximum precision
is 31 digits.
Data Types
Chapter 2. Language elements 55
All values of a decimal column have the same precision and scale. The range of a
decimal variable or the numbers in a decimal column is -n to +n, where n is the
largest positive number that can be represented with the applicable precision an
d
scale. The maximum range is 1 − 10³¹ to 10³¹ − 1.
String representations of numbers
Values whose data types are small integer, large integer, floating point, and de
cimal
are stored in an internal form that is transparent to the user of SQL. But strin
g
representations of numbers can be used in some contexts. A valid string
representation of a number must conform to the rules for numeric constants. For
more information, see “Constants” on page 79.
The encoding scheme in use determines what type of strings may be used for
string representation of numbers. For ASCII and EBCDIC, a string representation
of
a number must be a character string. For UNICODE, a string representation of a
number can be either a character string or a graphic string. Thus, the only time
a
graphic string can be used for a number is when the encoding scheme is
UNICODE.
Numeric host variables
Binary integer variables can be defined in all host languages.
Floating point variables can be defined in all host languages. All languages sup
port
System/390 floating point format. Assembler, C, and C⁺⁺ also support IEEE
floating-point format. In assembler, C, and C⁺⁺ programs, the precompiler option
FLOAT tells DB2 whether floating-point variables contain data in System/390
floating-point format or IEEE floating-point format.
Decimal variables can be defined in all host languages except Fortran. In COBOL,
decimal numbers can be represented in the packed decimal format used for
columns or in the format denoted by DISPLAY SIGN LEADING SEPARATE.
Datetime values
The datetime data types are described in the following sections. Such values are
neither strings nor numbers. Nevertheless, datetime values can be used in certai
n
arithmetic and string operations and are compatible with certain strings. Moreov
er,
strings can represent datetime values, as discussed in “String representations of
datetime values” on page 57.
Date
A date is a three-part value (year, month, and day) designating a point in time
using
the Gregorian calendar, which is assumed to have been in effect from the year 1
A.D.8 The range of the year part is 0001 to 9999. The range of the month part is
1
to 12. The range of the day part is 1 to 28, 29, 30, or 31, depending on the mon
th
and year.
The internal representation of a date is a string of 4 bytes. Each byte consists
of
two packed decimal digits. The first 2 bytes represent the year, the third byte
the
month, and the last byte the day.
The length of a DATE column as described in the catalog is the internal length,
which is 4 bytes. The length of a DATE column as described in the SQLDA is the
external length, which is 10 bytes unless a date exit routine was specified when
8. Historical dates do not always follow the Gregorian calendar. Dates between 1
582-10-04 and 1582-10-15 are accepted as valid
dates although they never existed in the Gregorian calendar.
Data Types
56 SQL Reference
||
|
|
|
|
|
|
|
|
|
|
your DB2 subsystem was installed. (Writing a date exit routine is described in
Appendix B (Volume 2) of DB2 Administration Guide.) In that case, the string for
mat
of a date can be up to 255 bytes in length. Accordingly, DCLGEN9 defines
fixed-length string variables for DATE columns with a length equal to the value
of
the field LOCAL DATE LENGTH on installation panel DSNTIP4, or a length of 10
bytes if a value for the field was not specified.
Time
A time is a three-part value (hour, minute, and second) designating a time of da
y
using a 24-hour clock. The range of the hour part is 0 to 24. The range of the
minute and second parts is 0 to 59. If the hour is 24, the minute and second par
ts
are both zero.
The internal representation of a time is a string of 3 bytes. Each byte consists
of
two packed decimal digits. The first byte represents the hour, the second byte t
he
minute, and the last byte the second.
The length of a TIME column as described in the catalog is the internal length
which is 3 bytes. The length of a TIME column as described in the SQLDA is the
external length which is 8 bytes unless a time exit routine was specified when y
our
DB2 subsystem was installed. (Writing a date exit routine is described in Append
ix
B (Volume 2) of DB2 Administration Guide.) In that case, the string format of a
time
can be up to 255 bytes in length. Accordingly, DCLGEN9 defines fixed-length stri
ng
variables for TIME columns with a length equal to the value of the field LOCAL
TIME LENGTH on installation panel DSNTIP4, or a length of 8 bytes if a value for
the field was not specified.
Timestamp
A timestamp is a seven-part value (year, month, day, hour, minute, second, and
microsecond) that represents a date and time as defined previously, except that
the
time includes a fractional specification of microseconds.
The internal representation of a timestamp is a string of 10 bytes, each of whic
h
consists of two packed decimal digits. The first 4 bytes represent the date, the
next
3 bytes the time, and the last 3 bytes the microseconds.
The length of a TIMESTAMP column as described in the catalog is the internal
length which is 10 bytes. The length of a TIMESTAMP column as described in the
SQLDA is the external length which is 26 bytes. DCLGEN therefore defines 26-byte
,
fixed-length string variables for TIMESTAMP columns.
String representations of datetime values
Values whose data types are date, time, or timestamp are represented in an
internal form that is transparent to the user of SQL. But dates, times, and
timestamps can also be represented by strings. These representations directly
concern the SQL user because there are no special SQL constants for datetime
values and no host variables with a data type of date, time, or timestamp.
The encoding scheme in use determines what type of strings may be used for
string representation of datetime values. For ASCII and EBCDIC, a string
representation of a datetime value must be a character string. For UNICODE, a
string representation of a datetime value can be either a character string or a
9. DCLGEN is a DB2 DSN subcommand for generating table declarations for designat
ed tables or views. The declarations are stored
in MVS data sets, for later inclusion in DB2 source programs.
Data Types
Chapter 2. Language elements 57
|
|
|
|
graphic string. Thus, the only time a graphic string can be used for a datetime
value
is when the encoding scheme is UNICODE.
For retrieval, datetime values must be assigned to string variables. When a date
or
time is assigned to a variable, the string format is determined by a precompiler
option or subsystem parameter. When a string representation of a datetime value
is
used in other operations, it is converted to a datetime value. However, this can
be
done only if the string representation is recognized by DB2 or an exit provided
by
the installation and the other operand is a compatible datetime value. An input
string representation of a date or time value with LOCAL specified can be any sh
ort
string. The following sections describe the string formats that are recognized b
y
DB2.
Datetime values that are represented by strings can appear in contexts requiring
values whose data types are date, time, timestamp by using the DATE, TIME, or
TIMESTAMP functions.
Date strings: A string representation of a date is a string that starts with a d
igit and
has a length of at least 8 characters. Trailing blanks can be included, leading
blanks
are not allowed, and leading zeros can be omitted in the month and day portions.
Table 4 shows the valid string formats for dates. Each format is identified by n
ame
and includes an associated abbreviation (for use by the CHAR function) and an
example of its use. For an installation-defined date string format, the format a
nd
length must have been specified when DB2 was installed. They cannot be listed
here.
Table 4. Formats for string representations of dates
Format name Abbreviation Date format Example
International Standards Organization ISO yyyy-mm-dd 1987-10-12
IBM USA standard USA mm/dd/yyyy 10/12/1987
IBM European standard EUR dd.mm.yyyy 12.10.1987
Japanese industrial standard Christian
era
JIS yyyy-mm-dd 1987-10-12
Installation-defined LOCAL Any installationdefined
form

Note: For LOCAL, the date exit for ASCII data is DSNXVDTA, the date exit for EBC
DIC is
DSNXVDTX, and the date exit for Unicode is DSNXVDTU.
Time strings: A string representation of a time is a string that starts with a d
igit,
and has a length of at least 4 characters. Trailing blanks can be included, lead
ing
blanks are not allowed, and leading zeros can be omitted in the hour part of the
time; seconds can be omitted entirely. If you choose to omit seconds, an implici
t
specification of 0 seconds is assumed. Thus 13.30 is equivalent to 13.30.00.
Table 5 on page 59 shows the valid string formats for times. Each format is
identified by name and includes an associated abbreviation (for use by the CHAR
function) and an example of its use. In the case of an installation-defined time
string
format, the format and length must have been specified when your DB2 subsystem
was installed. They cannot be listed here.
10. This is an earlier version of the ISO format. JIS can be used to get the cur
rent ISO format.
Data Types
58 SQL Reference
|
|
||
Table 5. Formats for string representations of times
Format name Abbreviation Time format Example
International Standards
Organization10
ISO hh.mm.ss 13.30.05
IBM USA standard USA hh:mm AM or
PM
1:30 PM
IBM European standard EUR hh.mm.ss 13.30.05
Japanese industrial standard Christian
era
JIS hh:mm:ss 13:30:05
Installation-defined LOCAL Any installationdefined
form

Note: For LOCAL, the date exit for ASCII data is DSNXVDTA, the date exit for EBC
DIC is
DSNXVDTX, and the date exit for Unicode is DSNXVDTU.
In the USA format:
v The minutes can be omitted, thereby specifying 00 minutes. For example, 1 PM
is equivalent to 1:00 PM.
v The letters A, M, and P can be lowercase.
v A single blank must precede the AM or PM.
v The hour must not be greater than 12 and cannot be 0 except for the special
case of 00:00 AM.
Using the ISO format of the 24-hour clock, the correspondence between the USA
format and the 24-hour clock is as follows:
v 12:01 AM through 12:59 AM correspond to 00.01.00 through 00.59.00
v 01:00 AM through 11:59 AM correspond to 01.00.00 through 11.59.00
v 12:00 PM (noon) through 11:59 PM correspond to 12.00.00 through 23.59.00
v 12:00 AM (midnight) corresponds to 24.00.00
v 00:00 AM (midnight) corresponds to 00.00.00
Timestamp strings: A string representation of a timestamp is a string that start
s
with a digit and has a length of at least 16 characters. The complete string
representation of a timestamp has the form yyyy-mm-dd-hh.mm.ss.nnnnnn. Trailing
blanks can be included, leading blanks are not allowed, and leading zeros can be
omitted in the month, day, and hour part of the timestamp; trailing zeros can be
truncated or omitted entirely from microseconds. If you choose to omit any digit
of
the microseconds portion, an implicit specification of 0 is assumed. Thus,
1990-3-2-8.30.00.10 is equivalent to 1990-03-02-08.30.00.100000.
Restrictions on the use of local datetime formats
The following rules apply to the character string representation of dates and ti
mes:
For input: In distributed operations, DB2 as a server uses its local date or tim
e
routine to evaluate host variables and literals. This means that character strin
g
representation of dates and times can be:
v One of the standard formats
v A format recognized by the server’s local date/time exit
For output: With DRDA access, DB2 as a server returns date and time host
variables in the format defined at the server. With DB2 private protocol access,
DB2
as a server returns date and time host variables in the format defined at the
requesting system. To have date and time host variables returned in another form
at,
use CHAR(date-expression, XXXX) where XXXX is JIS, EUR, USA, ISO, or LOCAL
to explicitly specify the specific format.
Data Types
Chapter 2. Language elements 59
||
For BIND PACKAGE COPY: When binding a package using the COPY option, DB2
uses the ISO format for output values unless the SQL statement explicitly specif
ies
a different format. Input values can be specified in the format described above
under “For input” on page 59.
Row ID values
A row ID is a value that uniquely identifies a row in a table. A column or a hos
t
variable can have a row ID data type. A ROWID column enables queries to be
written that navigate directly to a row in the table. Each value in a ROWID colu
mn
must be unique, and DB2 maintains the values permanently, even across table
space reorganizations. When a row is inserted into the table, DB2 generates a
value for the ROWID column unless one is supplied. If a value is supplied, it mu
st
be a valid row ID value that was previously generated by DB2 and the column must
be defined as GENERATED BY DEFAULT. Users cannot update the value of a
ROWID column.
The internal representation of a row ID value is transparent to the user. The va
lue is
never subject to translation because it is considered to contain BIT data. The l
ength
of a ROWID column as described in the LENGTH column of catalog table
SYSCOLUMNS is the internal length, which is 17 bytes. The length as described in
the LENGTH2 column of catalog table SYSCOLUMNS is the external length, which
is 40 bytes.
In a distributed data environment, the row ID data type is not supported for DB2
private protocol access. For information about using row IDs, see DB2 Applicatio
n
Programming and SQL Guide.
Distinct types
A distinct type is a user-defined data type that shares its internal representat
ion with
a built-in data type (its source type), but is considered to be a separate and
incompatible data type for most operations. For example, the semantics for a
picture type, a text type, and an audio type that all use the built-in data type
BLOB
for their internal representation are quite different. A distinct type is create
d with the
SQL statement CREATE DISTINCT TYPE.
For example, the following statement creates a distinct type named AUDIO:
CREATE DISTINCT TYPE AUDIO AS BLOB (1M):
Although AUDIO has the same representation as the built-in data type BLOB, it is
a
separate data type that is not comparable to a BLOB or to any other data type. T
his
inability to compare AUDIO to other data types allows functions to be created
specifically for AUDIO and assures that these functions cannot be applied to oth
er
data types.
The name of a distinct type is qualified with a schema name. The implicit schema
name for an unqualified name depends on the context in which the distinct type
appears. If an unqualified distinct type name is used:
v In a CREATE DISTINCT TYPE or the object of DROP, COMMENT ON, GRANT,
or REVOKE statement, DB2 uses the normal process of qualification by
authorization ID to determine the schema name.
v In any other context, DB2 uses the SQL path to determine the schema name.
DB2 searches the schemas in the path, in sequence, and selects the first
schema in the path such that the distinct type exists in the schema and the user
Data Types
60 SQL Reference
has authorization to use the data type. For a description of the SQL path, see
“Schemas and the SQL path” on page 40.
A distinct type does not automatically acquire the functions and operators of it
s
source type because they might not be meaningful. (For example, it might make
sense for a “length” function of the AUDIO type to return the length in seconds
rather than in bytes.) Instead, distinct types support strong typing. Strong typ
ing
ensures that only the functions and operators that are explicitly defined on a d
istinct
type can be applied to that distinct type. However, a function or operator of th
e
source type can be applied to the distinct type by creating an appropriate
user-defined function. The user-defined function must be sourced on the existing
function that has the source type as a parameter. For example, the following ser
ies
of SQL statements shows how to create a distinct type named MONEY based on
data type DECIMAL(9,2), how to define the + operator for the distinct type, and
how
the operator might be applied to the distinct type:
CREATE DISTINCT TYPE MONEY AS DECIMAL(9,2) WITH COMPARISONS;
CREATE FUNCTION "+"(MONEY,MONEY)
RETURNS MONEY
SOURCE SYSIBM."+"(DECIMAL(9,2),DECIMAL(9,2));
CREATE TABLE SALARY_TABLE
(SALARY MONEY,
COMMISSION MONEY);
SELECT SALARY + COMMISSION FROM SALARY_TABLE;
A distinct type is subject to the same restrictions as its source type. For exam
ple, a
table can only have one ROWID column. Therefore, a table with a ROWID column
cannot also have a column with distinct type that is sourced on a row ID.
The comparison operators are automatically generated for distinct types, except
those that are sourced on a CLOB, DBCLOB, or BLOB. In addition, DB2
automatically generates functions for every distinct type that support casting f
rom
the source type to the distinct type and from the distinct type to the source ty
pe. For
example, for the AUDIO type created above, these are generated cast functions:
FUNCTION schema-name.BLOB (schema-name.AUDIO) RETURNS SYSIBM.BLOB (1M)
FUNCTION schema-name.AUDIO (SYSIBM.BLOB (1M)) RETURNS schema-name.AUDIO
In a distributed data environment, distinct types are not supported for DB2 priv
ate
protocol access.
Promotion of data types
Data types can be classified into groups of related data types. Within such grou
ps,
an order of precedence exists in which one data type is considered to precede
another data type. This precedence enables DB2 to support the promotion of one
data type to another data type that appears later in the precedence order. For
example, DB2 can promote the data type CHAR to VARCHAR and the data type
INTEGER to DOUBLE PRECISION; however, DB2 cannot promote a CLOB to a
VARCHAR.
DB2 considers the promotion of data types when:
v Performing function resolution (see “Function resolution” on page 106)
v Casting distinct types (see “Casting between data types” on page 62)
v Assigning distinct types to built-in data types (see “Distinct type assignments” o
n
page 71)
Data Types
Chapter 2. Language elements 61
For each data type, Table 6 shows the precedence list (in order) that DB2 uses t
o
determine the data types to which the data type can be promoted. The table
indicates that the best choice is the same data type and not promotion to anothe
r
data type.
Table 6. Precedence of data types
Data type1,2 Data type precedence list (in best-to-worst order)
CHAR or GRAPHIC CHAR or GRAPHIC, VARCHAR or VARGRAPHIC, CLOB or
DBCLOB
VARCHAR or
VARGRAPHIC
VARCHAR or VARGRAPHIC, CLOB or DBCLOB
CLOB or DBCLOB CLOB or DBCLOB
BLOB BLOB
SMALLINT SMALLINT, INTEGER, decimal, real, double
INTEGER INTEGER, decimal, real, double
decimal decimal, real, double
real real, double
double double
DATE DATE
TIME TIME
TIMESTAMP TIMESTAMP
ROWID ROWID
A distinct type The same distinct type
Notes:
1. The data types in lowercase letters represent the following data types:
decimal DECIMAL(p,s) or NUMERIC(p,s)
real REAL or FLOAT(n) where n is not greater than 24
double DOUBLE, DOUBLE PRECISION, FLOAT or FLOAT(n) where n is
greater than 24
2. Other synonyms for the listed data types are considered to be the same as the
synonym
listed.
Casting between data types
There are many occasions when a value with a given data type needs to be cast
(changed) to a different data type or to the same data type with a different len
gth,
precision, or scale. Data type promotion, as described in “Promotion of data types”
on page 61, is one example of when a value with one data type needs to be cast
to a new data type. A data type that can be changed to another data type is
castable from the source data type to the target data type.
The casting of one data type to another can occur implicitly or explicitly. You
can
use the function notation syntax or CAST specification syntax to explicitly cast
a
data type. DB2 might implicitly cast data types during assignments that involve
a
distinct type (see “Distinct type assignments” on page 71). In addition, when you
create a sourced user-defined function, the data types of the parameters of the
source function must be castable to the data types of the function that you are
creating (see “CREATE FUNCTION” on page 481).
Promotion of Data Types
62 SQL Reference
If truncation occurs when a character or graphic string is cast to another data
type,
a warning occurs if any non-blank characters are truncated. This truncation
behavior is unlike the assignment of character or graphic strings to a target wh
en
an error occurs if any non-blank characters are truncated.
For casts that involve a distinct type as either the data type to be cast to or
from,
Table 7 shows the supported casts. For casts between built-in data types, Table
8
on page 64 shows the supported casts.
Table 7. Supported casts when a distinct type is involved
Data type ... Is castable to data type ...
Distinct type DT Source data type of distinct type DT
Source data type of distinct type DT Distinct type DT
Distinct type DT Distinct type DT
Data type A Distinct type DT where A is promotable to the source data type of di
stinct type
DT (see “Promotion of data types” on page 61)
INTEGER Distinct type DT if DT’s source data type is SMALLINT
DOUBLE Distinct type DT if DT’s source data type is REAL
VARCHAR Distinct type DT if DT’s source data type is CHAR
VARGRAPHIC Distinct type DT if DT’s source data type is GRAPHIC
When a distinct type is involved in a cast, a cast function that was generated w
hen
the distinct type was created is used. How DB2 chooses the function depends on
whether function notation or CAST specification syntax is used. (For details, se
e
“Function resolution” on page 106 and “CAST specification” on page 125,
respectively.) Function resolution is similar for both. However, in CAST specifi
cation,
when an unqualifed distinct type is specified as the target data type, DB2 first
resolves the schema name of the distinct type and then uses that schema name to
locate the cast function.
Casting Between Data Types
Chapter 2. Language elements 63
Table 8. Supported casts between built-in data types
To data type1 →
Cast from
data type ↓
S
M
A
L
L
I
N
T
I
N
T
E
G
E
R
D
E
C
I
M
A
L
R
E
A
L
D
O
U
B
L
E
C
H
A
R
V
A
R
C
H
A
R
C
L
O
B
G
R
A
P
H
I
C
V
A
R
G
R
A
P
H
I
C
D
B
C
L
O
B
B
L
O
B
D
A
T
E
T
I
M
E
T
I
M
E
S
T
A
M
P
R
O
W
I
D
SMALLINT Y Y Y Y Y Y Y         
INTEGER Y Y Y Y Y Y Y         
DECIMAL Y Y Y Y Y Y Y         
REAL Y Y Y Y Y Y Y         
DOUBLE Y Y Y Y Y Y Y         
CHAR Y Y Y Y Y Y Y Y Y Y Y2 Y Y Y Y Y
VARCHAR Y Y Y Y Y Y Y Y Y Y Y2 Y Y Y Y Y
CLOB      Y Y Y Y Y Y2 Y    
GRAPHIC  Y2 Y2 Y2 Y2 Y3 Y3 Y3 Y Y Y Y Y Y2 Y2 
VARGRAPHIC  Y2 Y2 Y2 Y2 Y3 Y3 Y3 Y Y Y Y Y Y2 Y2 
DBCLOB      Y3 Y3 Y3 Y Y Y Y    
BLOB            Y    
DATE      Y Y      Y   
TIME      Y Y       Y  
TIMESTAMP      Y Y      Y Y Y 
ROWID      Y Y     Y    Y
Note:
1. Other synonyms for the listed data types are considered to be the same as the
synonym listed. Some exceptions
exist when the cast involves character string data if the subtype is FOR BIT DAT
A.
2. These data types are castable between each other only if the data is Unicode.
3. These data types are castable between each other only if the data is Unicode.
The result length for these casts is
3 * LENGTH(graphic string).
Assignment and comparison
The basic operations of SQL are assignment and comparison. Assignment
operations are performed during the execution of INSERT, UPDATE, FETCH,
SELECT INTO, SET assignment, and VALUES INTO statements. In addition, when
a function is invoked or a stored procedure is called, the arguments of the func
tion
or stored procedure are assigned. Comparison operations are performed during the
execution of statements that include predicates and other language elements such
as MAX, MIN, DISTINCT, GROUP BY, and ORDER BY.
The basic rule for both operations is that data types of the operands must be
compatible. The compatibility rule also applies to other operations that are
described under “Rules for result data types” on page 77. Table 9 on page 65 shows
the compatibility matrix for data types.
Casting Between Data Types
64 SQL Reference
|
|
|
|
|
|
|||||
Table 9. Compatibility of data types for assignments and comparisons. Y indicate
s that the data types are compatible.
N indicates no compatibility. For any number in a column, read the corresponding
note at the bottom of the table.
Operands
Binary
integer
Decimal
number
Floating
point
Character
string
Graphic
string
Binary
string Date Time
Timestamp
Row
ID
Distinct
type
Binary
Integer
Y Y Y N N N N N N N 2
Decimal
Number
Y Y Y N N N N N N N 2
Floating
Point
Y Y Y N N N N N N N 2
Character
String
N N N Y N4,5 N3 1 1 1 N 2
Graphic
String
N N N N4,5 Y N 1,4 1,4 1,4 N 2
Binary
String
N N N N3 N Y N N N N 2
Date N N N 1 1,4 N Y N N N 2
Time N N N 1 1,4 N N Y N N 2
Timestamp
N N N 1 1,4 N N N Y N 2
Row ID N N N N N N N N N Y 2
Distinct
Type
2 2 2 2 2 2 2 2 2 2 Y2
Notes:
1. The compatibility of datetime values is limited to assignment and comparison:
v Datetime values can be assigned to string columns and to string variables, as
explained in “Datetime
assignments” on page 70.
v A valid string representation of a date can be assigned to a date column or co
mpared to a date.
v A valid string representation of a time can be assigned to a time column or co
mpared to a time.
v A valid string representation of a timestamp can be assigned to a timestamp co
lumn or compared to a
timestamp.
2. A value with a distinct type is comparable only to a value that is defined wi
th the same distinct type. In general,
DB2 supports assignments between a distinct type value and its source data type.
For additional information, see
“Distinct type assignments” on page 71.
3. All character strings, even those with subtype FOR BIT DATA, are not compatib
le with binary strings.
4. These data types are compatible if the graphic string is Unicode UTF-16. On a
ssignment and comparison from
Graphic to Character, the resulting length is 3 * (LENGTH(graphic string)).
5. Character strings with subtype FOR BIT DATA are not compatible with Unicode U
TF-16 Graphic Data.
Compatibility with a column that has a field procedure is determined by the data
type of the column, which applies to the decoded form of its values.
A basic rule for assignment operations is that a null value cannot be assigned t
o a
column that cannot contain null values, nor to a host variable that does not hav
e an
associated indicator variable. For a host variable that does have an associated
indicator variable, a null value is assigned by setting the indicator variable t
o a
negative value. See “References to host variables” on page 99 for a discussion of
indicator variables.
Assignment and Comparison
Chapter 2. Language elements 65
|
|
|
|
|
||
|
Numeric assignments
The basic rule for numeric assignments is that the whole part of a decimal or
integer number cannot be truncated. If necessary, the fractional part of a decim
al
number is truncated.
Decimal or integer to floating-point
Because floating-point numbers are only approximations of real numbers, the resu
lt
of assigning a decimal or integer number to a floating-point column or variable
might not be identical to the original number.
Floating-point or decimal to integer
When a single precision floating-point number is converted to integer, rounding
occurs on the seventh significant digit, zeros are added to the end of the numbe
r, if
necessary, starting from the seventh significant digit, and the fractional part
of the
number is eliminated.
When a double precision floating-point or decimal number is converted to integer
,
the fractional part of the number is eliminated.
The following examples show a single precision floating-point number converted t
o
an integer:
Example 1:
The floating-point number 2.0000045E6
assigned to an integer
column or host variable is: 2000000
Example 2:
The floating-point number 2.00000555E8
assigned to an integer
column or host variable is: 200001000
The following examples show a double precision floating-point number converted t
o
an integer:
Example 1:
The floating-point number 2.0000045E6
assigned to an integer
column or host variable is: 2000004
Example 2:
The floating-point number 2.00000555E8
assigned to an integer
column or host variable is: 200000555
The following examples show a decimal number converted to an integer:
Example 1:
The decimal number 2000004.5
assigned to an integer
column or host variable is: 2000004
Example 2:
The decimal number 200000555.0
assigned to an integer
column or host variable is: 200000555
Assignment and Comparison
66 SQL Reference
Decimal to decimal
When a decimal number is assigned to a decimal column or variable, the number is
converted, if necessary, to the precision and the scale of the target. The neces
sary
number of leading zeros is added or eliminated, and, in the fractional part of t
he
number, the necessary number of trailing zeros is added, or the necessary number
of trailing digits is eliminated.
Integer to decimal
When an integer is assigned to a decimal column or variable, the number is
converted first to a temporary decimal number and then, if necessary, to the
precision and scale of the target. The precision and scale of the temporary deci
mal
number is 5,0 for a small integer or 11,0 for a large integer.
Floating-point to floating-point
When a single precision System/390 floating-point number is assigned to a double
precision floating-point column or variable, the single precision data is padded
with
eight hex zeros.
When a double precision System/390 floating-point number is assigned to a single
precision floating-point column or variable, the double precision data is conver
ted
and rounded up on the seventh hex digit.
In assembler, C, or C⁺⁺ applications that are precompiled with the FLOAT(IEEE)
option, floating-point constants and values in host variables are assumed to hav
e
IEEE floating-point format. All floating-point data is stored in DB2 in System/3
90
floating-point format. Therefore, when the FLOAT(IEEE) precompiler option is in
effect, DB2 performs the following conversions:
v When a number in short or long IEEE floating-point format is assigned to a
single-precision or double-precision floating-point column, DB2 converts the
number to System/390 floating-point format.
v When a single-precision or double-precision floating-point column value is
assigned to a short or long floating-point host variable, DB2 converts the colum
n
value to IEEE floating-point format.
Floating-point to decimal
When a single precision floating-point number is assigned to a decimal column or
variable, the number is first converted to a temporary decimal number of precisi
on 6
by rounding on the seventh decimal digit. Twenty five zeros are then appended to
the number to bring the precision to 31. Because of rounding, a number less than
0.5×10-6 is reduced to 0.
When a double precision floating-point number is assigned to a decimal column or
variable, the number is first converted to a temporary decimal number of precisi
on
15, and then, if necessary, truncated to the precision and scale of the target.
In this
conversion, zeros are added to the end of the number, if necessary, to bring the
precision to 16. The number is then rounded (using floating-point arithmetic) on
the
sixteenth decimal digit to produce a 15-digit number. Because of rounding, a
number less in magnitude than 0.5×10-15 is reduced to 0. If the decimal number
requires more than 15 digits to the left of the decimal point, an error is repor
ted.
Otherwise, the scale is given the largest possible value that allows the whole p
art of
the number to be represented without loss of significance.
The following examples show the effect of converting a double precision
floating-point number to decimal:
Example 1:
Assignment and Comparison
Chapter 2. Language elements 67
The floating-point number .123456789098765E-05
in decimal notation is: .00000123456789098765
+5
Rounding adds 5
in the 16th position .00000123456789148765
and truncates the result to .000001234567891
Zeros are then added to the
end of a 31-digit result: .0000012345678910000000000000000
Example 2:
The floating-point number 1.2339999999999E+01
in decimal notation is: 12.33999999999900
+5
Rounding adds 5
in the 16th position 12.33999999999905
and truncates the result to 12.3399999999990
Zeros are then added to the
end of a 31-digit result: 12.33999999999900000000000000000
To COBOL integers
Assignment to COBOL integer variables uses the full size of the integer. Thus, t
he
value placed in the COBOL data item might be out of the range of values.
Example 1: If COL1 contains a value of 12345, the following statements cause the
value 12345 to be placed in A, even though A has been defined with only 4 digits
:
01A PIC S9999 BINARY.
EXEC SQL SELECT COL1
INTO :A
FROM TABLEX
END-EXEC.
Example 2: The following COBOL statement results in 2345 being placed in A:
MOVE 12345 TO A.
String assignments
The following rules apply when both the source and the target are strings. When
a
datetime data type is involved, see “Datetime assignments” on page 70. For the
special considerations that apply when a distinct type is involved in an assignm
ent,
especially to a host variable, see “Distinct type assignments” on page 71.
There are two types of string assignments:
v Storage assignment is when a value is assigned to a column or a parameter of a
function or stored procedure.
v Retrieval assignment is when a value is assigned to a host variable.
The rules differ for storage and retrieval assignment.
Storage assignment
The basic rule is that the length of the string assigned to a column or paramete
r of
a function or stored procedure must not be greater than the length attribute of
the
Assignment and Comparison
68 SQL Reference
column or the parameter. Trailing blanks are included in the length of the strin
g.
When the length of the string is greater than the length attribute of the column
or
the parameter, the following actions occur:
v If all of the trailing characters that must be truncated to make a string fit
the
target are blanks and the string is a character or graphic string, the string is
truncated and assigned without warning.
v Otherwise, the string is not assigned and an error occurs to indicate that at
least
one of the excess characters is non-blank.
When a string is assigned to a fixed-length column or parameter and the length o
f
the string is less than the length attribute of the target, the string is padded
to the
right with the necessary number of SBCS or DBCS blanks. The pad character is
always a blank even for columns defined with the FOR BIT DATA attribute.
Retrieval Assignment
The length of a string assigned to a host variable can be greater than the lengt
h
attribute of the host variable. When the length of the string is greater than th
e
length of the host variable, the string is truncated on the right by the necessa
ry
number of SBCS or DBCS characters. When this occurs, the value W is assigned
to the SQLWARN1 field of the SQLCA. Furthermore, if an indicator variable is
provided, it is set to the original length of the string.
When a character string is assigned to a fixed-length variable and the length of
the
string is less than the length attribute of the target, the string is padded to
the right
with the necessary number of blanks. The pad character is always a blank even fo
r
strings defined with the FOR BIT DATA attribute.
Assignments involving mixed data strings
A mixed data string that contains DBCS characters cannot be assigned to an SBCS
column, SBCS parameter, or SBCS host variable. The following rules apply when a
mixed data string is assigned to a host variable and the string is longer than t
he
length attribute of the variable:
v If the string is not well-formed mixed data, it is truncated as if it were BIT
or
graphic data.
v If the string is well-formed mixed data, it is modified on the right such that
it is
well-formed mixed data with a length that is the same as the length attribute of
the variable and the number of characters lost is minimal.
Assignments involving C NUL-terminated strings
A C NUL-terminated string variable referenced in a CONNECT statement need not
contain a NUL (X 00 ). Otherwise, DB2 enforces the convention that the value of
a
NUL-terminated string variable, either character or graphic, is NUL-terminated.
An
input host variable that does not contain a NUL will cause an error. A value
assigned to an output variable will always be NUL-terminated even if a character
must be truncated to make room for the NUL.
When a string of length n is assigned to a C NUL-terminated string variable with
a
length greater than n+1, the rules depend on whether the source string is a valu
e of
a fixed-length string or a varying-length string:
v If the source is a fixed-length string, the string is padded on the right with
x-n-1
blanks, where x is the length of the variable. The padded string is then assigne
d
to the variable and a NUL is placed in the last byte of the variable.
v If the source is a varying-length string, the string is assigned to the first
n bytes
of the variable and a NUL is placed in the next byte.
Assignment and Comparison
Chapter 2. Language elements 69
Conversion rules for string assignment
A character or graphic string assigned to a column or host variable is first
converted, if necessary, to the coded character set of the target. Conversion is
necessary only if all the following are true:
v The CCSIDs of string and target are different.
v Neither CCSID is X FFFF (neither the string nor the target is defined as BIT
data).
v The string is neither null nor empty.
An error occurs if:
v The SYSSTRINGS table is used but contains no information about the pair of
CCSIDs and DB2 cannot do the conversion through OS/390 support for Unicode
or Language Environment.
v A character of the string cannot be converted and the operation is assignment
to
a column or to a host variable that has no indicator variable.
v A mixed data string that contains DBCS characters is assigned to an SBCS
column.
A warning occurs if:
v A character of the string is converted to a substitution character. A substitu
tion
character is the character that is used when a character of the source character
set is not part of the target character set. For example, if the source characte
r
set includes Katakana characters and the target character set does not, a
Katakana character is converted to the EBCDIC SUB X 3F .
v A character of the string cannot be converted and the operation is assignment
to
a host variable that has an indicator variable. For example, a DBCS character
cannot be converted if the host variable has an SBCS CCSID. In this case, the
string is not assigned to the host variable and the indicator variable is set to
-2.
Datetime assignments
A DATE, TIME, or TIMESTAMP value can only be assigned to a column with a
matching data type (whether DATE, TIME, or TIMESTAMP), a string column, or a
string variable. The string column or string variable can be fixed or varying-le
ngth,
but must not be a BLOB, CLOB, or DBCLOB column or variable. A value assigned
to a DATE, TIME, or TIMESTAMP column must have a matching data type (whether
DATE, TIME, or TIMESTAMP) or must be a valid string representation of the
matching data type. The string representation must not be a BLOB, CLOB, or
DBCLOB. A datetime value cannot be assigned to a column that has a field
procedure.
When a datetime value is assigned to a string variable or column, it is converte
d to
its string representation. Leading zeros are not omitted from any part of the da
te,
time, or timestamp. The required length of the target varies depending on the
format of the string representation. If the length of the target is greater than
required, it is padded on the right with blanks. If the length of the target is
less than
required, the result depends on the type of datetime value involved, and on the
type
of target.
v If the target is a string column (except for BLOB, CLOB, or DBCLOB), truncatio
n
is not allowed. The length of the column must be at least 10 for a date, 8 for a
time, and 19 for a timestamp.
v When the target is a host variable, the following rules apply:
For a DATE: The length of the variable must not be less than 10.
Assignment and Comparison
70 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For a TIME: If the USA format is used, the length of the variable must not be
less than 8. This format does not include seconds.
If the ISO, EUR, or JIS format is used, the length of the variable must not be
less than 5. If the length is 5, 6, or 7, the seconds part of the time is omitte
d
from the result and SQLWARN1 is set to W . In this case, the seconds part of
the time is assigned to the indicator variable if one is provided, and, if the
length is 6 or 7, the value is padded with blanks so that it is a valid string
representation of a time.
For a TIMESTAMP: The length of the variable must not be less than 19. If
the length is between 19 and 25, the timestamp is truncated like a string,
causing the omission of one or more digits of the microsecond part. If the
length is 20, the trailing decimal point is replaced by a blank so that the valu
e
is a valid string representation of a timestamp.
Row ID assignments
A row ID value can only be assigned to a column, parameter, or host variable wit
h a
row ID data type. For the value of the ROWID column, the column must be defined
as GENERATED BY DEFAULT and the column must have a unique, single-column
index. The value that is specified for the column must be a valid row ID value t
hat
was previously generated by DB2.
Distinct type assignments
The rules that apply to the assignments of distinct types to host variables are
different than the rules for all other assignments that involve distinct types.
Assignments to host variables: The assignment of distinct type to a host variabl
e
is based on the source data type of the distinct type. Therefore, the value of a
distinct type is assignable to a host variable only if the source data type of t
he
distinct type is assignable to the host variable.
Example: Assume that distinct type AGE was created with the following SQL
statement:
CREATE DISTINCT TYPE AGE AS SMALLINT WITH COMPARISONS;
When the statement was executed, DB2 also generated these cast functions:
AGE (SMALLINT) RETURNS AGE
AGE (INTEGER) RETURNS AGE
SMALLINT (AGE) RETURNS SMALLINT
Next, assume that column STU_AGE was defined in table STUDENTS with distinct
type AGE. Now, consider this valid assignment of a student’s age to host variable
HV_AGE, which has an INTEGER data type:
SELECT STU_AGE INTO :HV_AGE FROM STUDENTS WHERE STU_NUMBER = 200;
The distinct type value is assignable to host variable HV_AGE because the source
data type of the distinct type (SMALLINT) is assignable to the host variable
(INTEGER). If distinct type AGE had been sourced on a character data type such
as CHAR(5), the above assignment would be invalid because a character type
cannot be assigned to an integer type.
Assignments other than to host variables: A distinct type can be the source or
target of an assignment. Assignment is based on whether the data type of the val
ue
to be assigned is castable to the data type of the target. (Table 7 on page 63 s
hows
Assignment and Comparison
Chapter 2. Language elements 71
|
|
|
|
|
which casts are supported when a distinct type is involved). Therefore, a distin
ct
type value can be assigned to any target other than a host variable when:
v The target of the assignment has the same distinct type, or
v The distinct type is castable to the data type of the target
Any value can be assigned to a distinct type when:
v The value to be assigned has the same distinct type as the target, or
v The data type of the assigned value is castable to the target distinct type
Example: Assume that the source data type for distinct type AGE is SMALLINT:
CREATE DISTINCT TYPE AGE AS SMALLINT WITH COMPARISONS
Next, assume that two tables TABLE1 and TABLE2 were created with four identical
column descriptions:
AGECOL AGE
SMINTCOL SMALLINT
INTCOL INTEGER
DECCOL DEC(6,2)
Using the following SQL statement and substituting various values for X and Y to
insert values into various columns of TABLE1 from TABLE2, Table 10 shows
whether the assignments are valid. DB2 uses assignment rules in this INSERT
statement to determine if X can be assigned to Y.
INSERT INTO TABLE1(Y)
SELECT X FROM TABLE2;
Table 10. Assessment of various assignments for example INSERT statement
X (column
in TABLE2)
Y (column
in TABLE1) Valid Reason
AGECOL AGECOL Yes Source and target are same distinct
type
SMINTCOL AGECOL Yes SMALLINT can be cast to AGE
INTCOL AGECOL Yes INTEGER can be cast to AGE (because
AGE’s source type is SMALLINT)
DECCOL AGECOL No DECIMAL cannot be cast to AGE
AGECOL SMINTCOL Yes AGE can be cast to its source type of
SMALLINT
AGECOL INTCOL No AGE cannot be cast to INTEGER
AGECOL DECCOL No AGE cannot be cast to DECIMAL
Numeric comparisons
Numbers are compared algebraically, that is, with regard to sign. For example, −2
is
less than +1.
If one number is an integer and the other is decimal, the comparison is made wit
h a
temporary copy of the integer, which has been converted to decimal.
When decimal numbers with different scales are compared, the comparison is made
with a temporary copy of one of the numbers that has been extended with trailing
zeros so that its fractional part has the same number of digits as the other num
ber.
Assignment and Comparison
72 SQL Reference
If one number is double precision floating point and the other is integer, decim
al, or
single precision floating point, the comparison is made with a temporary copy of
the
other number which has been converted to double precision floating point. Howeve
r,
if a single precision floating point number is compared with a floating point co
nstant,
the comparison is made with a single precision form of the constant.
Two floating point numbers are equal only if the bit configurations of their
normalized forms are identical.
String comparisons
Two strings are compared by comparing the corresponding bytes of each string. If
the strings do not have the same length, the comparison is made with a temporary
copy of the shorter string that has been padded on the right with blanks so that
it
has the same length as the other string.
Two strings are equal if they are both empty or if all corresponding bytes are e
qual.
An empty string is equal to a blank string. If two strings are not equal, their
relationship (that is, which has the greater value) is determined by the compari
son
of the first pair of unequal bytes from the left end of the strings. This compar
ison is
made according to the collating sequence associated with the encoding scheme of
the data. For ASCII data, characters A through Z (both upper and lowercase) have
a greater value than characters 0 through 9. For EBCDIC data, characters A
through Z (both upper and lowercase) have a lesser value than characters 0
through 9.
Varying length strings with different lengths are equal if they differ only in t
he
number of trailing blanks. In operations that select one value from a collection
of
such values, the value selected is arbitrary. The operations that can involve su
ch an
arbitrary selection are DISTINCT, MAX, MIN, and references to a grouping column.
See the description of GROUP BY for further information about the arbitrary
selection involved in references to a grouping column.
String comparisons with field procedures
If a column with a field procedure is compared with the value of a variable or a
constant, the variable or constant is encoded by the field procedure before the
comparison is made. If the comparison operator is LIKE, the variable or constant
is
not encoded and the column value is decoded.
If a column with a field procedure is compared with another column, that column
must have the same field procedure. The comparison is performed on the encoded
form of the values in the columns. If the encoded values are numeric, their data
types must be identical; if they are strings, their data types must be compatibl
e.
If two encoded strings of different lengths are compared, the shorter is tempora
rily
padded with encoded blanks so that it has the same length as the other string.
In a CASE expression, if a column with a field procedure is used as the
result expression in a THEN or ELSE clause, all other columns that are used as
result expressions must have the same field procedure. Otherwise, no column used
in a result expression may name a field procedure.
Conversion rules for string comparison
When two strings are compared, one of the strings is first converted, if necessa
ry,
to the coded character set of the other string. Conversion is necessary only if
all of
the following are true:
v The CCSIDs of the two strings are different.
Assignment and Comparison
Chapter 2. Language elements 73
v Neither CCSID is X'FFFF' (neither string is defined as BIT data or is a BLOB
string).
v The string selected for conversion is neither null nor empty.
v For Unicode data only, the following conversion tables (Table 11 or Table 12
indicate that conversion is necessary.
The conversion that occurs when SBCS data is compared with mixed data depends
on the encoding scheme. For ASCII and EBCDIC data, the conversion depends on
the value of the field MIXED DATA on installation panel DSNTIPF at the DB2 that
does the comparison:
v If this value is YES, the SBCS operand is converted to MIXED.
v If this value is NO, the MIXED operand is converted to SBCS.
For comparison of two Unicode strings, the following table shows which operand i
s
selected for conversion.
Table 11. Operand that supplies the CCSID for character conversion for the CCSID
for
Unicode data
First operand
Second operand
SBCS Data Mixed UTF 8 Data
DBCS UTF 16
Data
SBCS Data See next table. second second
Mixed UTF 8 Data first See next table. second
DBCS UTF 16 Data first first See next table.
In other cases, the string selected for conversion depends on the type of the
operands. The following table shows which operand supplies the target CCSID,
given the operand types.
Table 12. Operand that supplies the CCSID for character conversion
First operand
Second operand
Column
value
String
constant
Special
register
Derived
value
Host
variable
Column Value first first first first first
String Constant second first first first first
Special Register second first first first first
Derived Value second second second first first
Host Variable second second second second first/second1
Note: 1. Both operands are converted, if necessary, to the system CCSID of the s
erver for
the encoding scheme in effect.
For example, assume a comparison of the form:
string constant = derived value
Here, the relevant table entry is in the second row and fourth column. The value
for
this entry shows that the first operand (string constant) supplies the target CC
SID.
Thus, the derived value is converted, if necessary, to the coded character set o
f the
string constant.
An error occurs if a character of the string cannot be converted, the SYSSTRINGS
table is used but contains no information about the pair of CCSIDs of the operan
ds
Assignment and Comparison
74 SQL Reference
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
being compared, or DB2 cannot do the conversion through OS/390 support for
Unicode or Language Environment. A warning occurs if a character of the string i
s
converted to a substitution character.
Datetime comparisons
A DATE, TIME, or TIMESTAMP value can be compared either with another value of
the same data type or with a string representation of that data type. All compar
isons
are chronological, which means the further a point in time is from January 1, 00
01,
the greater the value of that point in time.
Comparisons involving TIME values and string representations of time values
always include seconds. If the string representation omits seconds, zero seconds
are implied.
Comparisons involving TIMESTAMP values are chronological without regard to
representations that might be considered equivalent. Thus, the following predica
te is
true:
TIMESTAMP( 1990-02-23-00.00.00 ) > 1990-02-22-24.00.00
Row ID comparisons
A value with a row ID type can only be compared to another row ID value. The
comparison of the row ID values is based on their internal representations. The
maximum number of bytes that are compared is 17 bytes, which is the number of
bytes in the internal representation. Therefore, row ID values that differ in by
tes
beyond the 17th byte are considered to be equal.
Distinct type comparisons
A value with a distinct type can only be compared to another value with exactly
the
same type because distinct types have strong typing, which means that a distinct
type is compatible only with its own type. Therefore, to compare a distinct type
to a
value with a different data type, the distinct type value must be cast to the da
ta type
of the comparison value or the comparison value must be cast to the distinct typ
e.
For example, because constants are built-in data types, a constant can be
compared to a distinct type value only if it is first cast to the distinct type
or vice
versa.
Table 13 shows examples of valid and invalid comparisons, assuming the following
SQL statements were used to define two distinct types AGE_TYPE and
CAMP_DATE and table CAMP_ROSTER table.
CREATE DISTINCT TYPE AGE_TYPE AS INTEGER WITH COMPARISONS;
CREATE DISTINCT TYPE CAMP_DATE AS DATE WITH COMPARISONS;
CREATE TABLE CAMP_ROSTER
( NAME VARCHAR(20),
ATTENDEE_NUMBER INTEGER NOT NULL,
AGE AGE_TYPE,
FIRST_CAMP_DATE CAMP_DATE,
LAST_CAMP_DATE CAMP_DATE,
BIRTHDATE DATE);
Table 13. Examples of valid and invalid comparisons involving distinct types
SQL statement Valid Reason
Distinct types with distinct types
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE < LAST_CAMP_DATE;
Yes Both values are the same distinct type.
Assignment and Comparison
Chapter 2. Language elements 75
|
|
|
Table 13. Examples of valid and invalid comparisons involving distinct types (co
ntinued)
SQL statement Valid Reason
Distinct types with columns of the same source data type
SELECT * FROM CAMP_ROSTER
WHERE AGE > ATTENDEE_NUMBER;
No A distinct type cannot be compared to integer.
SELECT * FROM CAMP_ROSTER
WHERE INTEGER(AGE) > ATTENDEE_NUMBER;
SELECT * FROM CAMP_ROSTER
WHERE CAST(AGE AS INTEGER) > ATTENDEE_NUMBER;
Yes The distinct type is cast to an integer, making the
comparison of two integers.
SELECT * FROM CAMP_ROSTER
WHERE AGE > AGE_TYPE(ATTENDEE_NUMBER);
SELECT * FROM CAMP_ROSTER
WHERE AGE > CAST(ATTENDEE_NUMBER as AGE_TYPE);
Yes Integer ATTENDEE_NUMBER is cast to the
distinct type AGE_TYPE, making both values the
same distinct type.
Distinct types with constants
SELECT * FROM CAMP_ROSTER
WHERE AGE IN (15,16,17);
No A distinct type cannot be compared to a constant.
SELECT * FROM CAMP_ROSTER
WHERE INTEGER(AGE) IN (15,16,17);
Yes The distinct type is cast to the data type of
constants, making all the values in the
comparison integers.
SELECT * FROM CAMP_ROSTER
WHERE AGE IN
(AGE_TYPE(15),AGE_TYPE(16),AGE_TYPE(17));
Yes Constants are cast to distinct type AGE_TYPE,
making all the values in the comparison the same
distinct type.
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE > 06/12/99 ;
No A distinct type cannot be compared to a constant.
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE >
CAST( 06/12/99 AS CAMP_DATE);
No The string constant ’06/12/99’, a VARCHAR data
type, cannot be cast directly to distinct type
CAMP_DATE, which is sourced on a DATE data
type. As illustrated in the next row, the constant
must be cast to a DATE data type and then to
the distinct type.
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE >
CAST(DATE( 06/12/1999 ) AS CAMP_DATE);
Yes The string constant ’06/12/99’ is cast to the
distinct type CAMP_DATE, making both values
the same distinct type. To cast a string constant
to a distinct type that is sourced on a DATE,
TIME, or TIMESTAMP data type, the string
constant must first be cast to a DATE, TIME, or
TIMESTAMP data type.
Distinct types with host variables
SELECT * FROM CAMP_ROSTER
WHERE AGE BETWEEN :HV_INTEGER AND :HV_INTEGER2;
No The host variables have integer data types. A
distinct type cannot be compared to an integer.
SELECT * FROM CAMP_ROSTER
WHERE AGE
BETWEEN CAST(:HV_INTEGER AS AGE_TYPE)
AND AGE_TYPE(:HV_INTEGER2);
Yes The host variables are cast to distinct type
AGE_TYPE, making all the values the same
distinct type.
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE > :HV_VARCHAR;
No The host variable has a VARCHAR data type. A
distinct type cannot be compared to a
VARCHAR.
Assignment and Comparison
76 SQL Reference
Table 13. Examples of valid and invalid comparisons involving distinct types (co
ntinued)
SQL statement Valid Reason
SELECT * FROM CAMP_ROSTER
WHERE FIRST_CAMP_DATE >
CAST(DATE(:HV_VARCHAR) AS CAMP_DATE);
Yes The host variable is cast to the distinct type
CAMP_DATE, making both values the same
distinct type. To cast a VARCHAR host variable
to a distinct type that is sourced on a DATE,
TIME, or TIMESTAMP data type, the host
variable must first be cast to a DATE, TIME, or
TIMESTAMP data type.
Rules for result data types
Rules that are applied to the operands of an operation determine the data type o
f
the result. This section explains when those rules apply and lists them by the
possible data types of operands.
The rules apply to:
v Corresponding columns in UNION or UNION ALL operations
v Result expressions of a CASE expression
v Arguments of the scalar functions COALESCE, IFNULL, and VALUE
v Expression values of the IN list of an IN predicate
The rules are applied subject to other restrictions on long strings for the vari
ous
operations.
Evaluation of the operands of an operation determines the data type of the resul
t. If
an operation has more than one pair of operands, DB2 determines the result type
of the first pair, uses this result type with the next operand to determine the
next
result type, and so on. The last intermediate result type and the last operand
determine the result type of the operation.
String operands
Character and graphic strings are compatible with other character and graphic
strings as long as there is a conversion between their corresponding CCSIDs.
Table 14. Result data types with string operands
One operand Other operand Data type of the result
CHAR(x) CHAR(y) CHAR(z) where z = max(x,y)
CHAR(x) GRAPHIC(y) GRAPHIC(z) where z = max(x,y)
VARCHAR(x) CHAR(y) or
VARCHAR(y)
VARCHAR(z) where z = max(x,y)
VARCHAR(x) GRAPHIC(y) or
VARCHAR(y)
VARGRAPHIC(z) where z = max(x,y)
CLOB(x) CHAR(y), VARCHAR(y),
or CLOB(y)
CLOB(z) where z = max(x,y)
CLOB(x) VARGRAPHIC(y),
GRAPHIC(y),or
DBCLOB(y)
DBCLOB(z) where z = max(x,y)
Assignment and Comparison
Chapter 2. Language elements 77
|
|
|
|
|
|
|
|
| |
|
| |
|
| |
|
||
Table 14. Result data types with string operands (continued)
One operand Other operand Data type of the result
VARGRAPHIC(x) VARGRAPHIC(y),
GRAPHIC(y),
VARCHAR(y), or
CHAR(y)
VARGRAPHIC(z) where z = max(x,y)
DBCLOB(x) DBCLOB(y),
VARGRAPHIC(y),
GRAPHIC(y), CLOB(y),
VARCHAR(y), or
CHAR(y)
DBCLOB(z) where z = max(x,y)
Character string subtypes are determined as indicated in the following table:
Table 15. Result data types with character string operands
One operand Other operand Data type of the result
Bit data Mixed, SBCS, or bit
data
Bit data
Mixed data Mixed or SBCS data Mixed data
SBCS data SBCS data SBCS data
Binary string operands
Binary strings (BLOBs) are compatible only with other binary strings (BLOB)s. Th
e
data type of the result is a BLOB. Other data types can be treated as a BLOB dat
a
type by using the BLOB scalar function to cast the data type to a BLOB. The leng
th
of the result BLOB is the largest length of all the data types.
Table 16. Result data types with binary string operands
One operand Other operand Data type of the result
BLOB(x) BLOB(y) BLOB(z) where z = max(x,y)
Numeric operands
Numeric types are compatible only with other numeric types.
Table 17. Result data types with numeric operands
One operand Other operand Data type of the result
SMALLINT SMALLINT SMALLINT
INTEGER INTEGER INTEGER
INTEGER SMALLINT INTEGER
DECIMAL(w,x) SMALLINT DECIMAL(p,x) where
p = x+max(w-x,5)1
DECIMAL(w,x) INTEGER DECIMAL(p,x) where
p = x+max(w-x,11)1
DECIMAL(w,x) DECIMAL(y,z) DECIMAL(p,s) where
p = max(x,z)+max(w-x,y-z)1s = max(x,z)
REAL REAL REAL
REAL DECIMAL, INTEGER,
or SMALLINT
DOUBLE
Rules for Result Data Types
78 SQL Reference
|
|
|||
|
||||
|
|
|
|
|
|
| |
|
|
|
|
Table 17. Result data types with numeric operands (continued)
One operand Other operand Data type of the result
DOUBLE any numeric DOUBLE
Note:
1. Precision cannot exceed 31.
Datetime operands
A DATE type is compatible with another DATE type or any string expression that
contains a valid string representation of a date. A string representation must n
ot be
a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. The data type of the result is DATE.
A TIME type is compatible with another TIME type or any string expression that
contains a valid string representation of a time. A string representation must n
ot be
a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. The data type of the result is TIME.
A TIMESTAMP type is compatible with another TIMESTAMP type or any string
expression that contains a valid string representation of a timestamp. A string
representation must not be a BLOB, CLOB, or DBCLOB and must have an actual
length that is not greater than 255 bytes. The data type of the result is TIMEST
AMP.
Row ID operands
A row ID data type is compatible only with itself. The result has a row ID data
type.
Distinct type operands
A distinct type is compatible only with itself. The data type of the result is t
he
distinct type.
Nullable attribute of a result
With the exception of the COALESCE and VALUE functions, the result of an
operation can be null unless the operands do not allow nulls.
Constants
A constant (also called a literal) specifies a value. Constants are classified a
s string
constants or numeric constants. Numeric constants are further classified as inte
ger,
floating-point, or decimal. String constants are classified as character or grap
hic.
All constants have the attribute NOT NULL. A negative sign in a numeric constant
with a value of zero is ignored.
Constants have a built-in data type. Therefore, an operation that involves a con
stant
and a distinct type requires that the distinct type be cast to the built-in data
type of
the constant or the constant be cast to the distinct type. For example, see Tabl
e 13
on page 75, which contains an example of casting data types to compare a
constant to a distinct type.
Integer constants
An integer constant specifies a binary integer as a signed or unsigned number th
at
has a maximum of 10 significant digits and no decimal point. If the value is not
Rules for Result Data Types
Chapter 2. Language elements 79
|
|
|
|
|
|
|
|
|
|
|
|
within the range of a large integer, the constant is interpreted as a decimal
constant. The data type of an integer constant is large integer.
Examples:
64 -15 +100 32767 720176
In syntax diagrams, the term integer is used for an integer constant that must n
ot
include a sign.
Floating-point constants
A floating-point constant specifies a floating-point number as two numbers
separated by an E. The first number can include a sign and a decimal point. The
second number can include a sign but not a decimal point. The value of the
constant is the product of the first number and the power of 10 specified by the
second number. It must be within the range of floating-point numbers. The number
of characters in the constant must not exceed 30. Excluding leading zeros, the
number of digits in the first number must not exceed 17 and the number of digits
in
the second must not exceed 2. The data type of a floating-point constant is doub
le
precision floating-point.
Examples: The following floating-point constants represent the numbers 150,
200000, -0.22, and 500:
15E12.E5 -2.2E-1+5.E+2
Decimal constants
A decimal constant specifies a decimal number as a signed or unsigned number of
no more than 31 digits and either includes a decimal point or is not within the
range
of binary integers. The precision is the total number of digits, including those
, if any,
to the right of the decimal point. The total includes all leading and trailing z
eros. The
scale is the number of digits to the right of the decimal point, including trail
ing
zeros.
Examples: The following decimal constants have, respectively, precisions and
scales of 5 and 2; 4 and 0; 2 and 0; 23 and 2:
025.50 1000. -15. +375893333333333333333.33
Character string constants
A character string constant specifies a varying-length character string. There a
re
two forms of character string constant:
v A sequence of characters that starts and ends with a string delimiter, which i
s
either an apostrophe ( ) or a quotation mark ("). For the factors that determine
which is applicable, see “Apostrophes and quotation marks in string delimiters”
on page 148. This form of string constant specifies the character string
contained between the string delimiters. The number of bytes between the
delimiters must not be greater than 255. Two consecutive string delimiters are
used to represent one string delimiter within the character string.
v An X followed by a sequence of characters that starts and ends with a string
delimiter. This form of a character string constant is also called a hexadecimal
constant. The characters between the string delimiters must be an even number
of hexadecimal digits. The number of hexadecimal digits must not exceed 254. A
hexadecimal digit is a digit or any of the letters A through F (uppercase or
lowercase). Under the conventions of hexadecimal notation, each pair of
Constants
80 SQL Reference
hexadecimal digits represents a character. A hexadecimal constant allows you to
specify characters that do not have a keyboard representation.
Examples:
12/14/1985 32 DON T CHANGE X FFFF
The rightmost string in the example ( ) represents an empty character string
constant, which is a string of zero length.
A character string constant is classified as mixed data if it includes a DBCS
substring. In all other cases, a character string constant is classified as SBCS
data.
The CCSID assigned to the constant is the appropriate system CCSID of the
database server. A mixed string constant can be continued from one line to the n
ext
only if the break occurs between single byte characters. A Unicode string is alw
ays
considered mixed regardless of the content of the string.
For Unicode, character constants can be assigned to UTF-8 and UTF-16. The form
of the constant does not matter. Typically, character string constants are used
only
with character strings, but they also can be used with graphic UTF-16 data.
However, hexadecimal constants are just character data. Thus, hexadecimal
constants being used to insert data into UTF-16 data strings should be in UTF-8
format, not UTF-16 format. For example, if you wanted to insert the number 1 int
o a
UTF-16 column, you would use X 31 , not X 0031 . Even though X 0031 is a UTF-16
value, DB2 treats it as two separate UTF-8 codepoints. Thus, X 0031 would
become X 00000031 .
Datetime constants
A datetime constant is a character string constant of a particular format. Chara
cter
string constants are described under the previous heading, “Character string
constants” on page 80. For information about the valid string formats, see “String
representations of datetime values” on page 57.
Graphic string constants
A graphic string constant specifies a varying-length graphic string. (Shift-in a
nd
shift-out characters for EBCDIC data are discussed in “Character strings” on
page 49.)
In EBCDIC environments, the forms of graphic string constants are11:
11. The PL/I form of graphic string constants is supported only in static SQL st
atements.
Constants
Chapter 2. Language elements 81
|
|
|
|
|
|
|
|
|
|
|
In SQL statements and in host language statements in a source program, graphic
string constants cannot be continued from one line to the next. The maximum
number of DBCS characters in a graphic string constant is 124.
For Unicode, graphic constants can be assigned to UTF-8 and UTF-16. The form of
the constant does not matter. Typically, graphic string constants are used only
with
graphic strings; however, they also can be used with character UTF-8 data.
Special registers
A special register is a storage area defined for a process by DB2. Wherever its
name appears in an SQL statement, the name is replaced by the register’s value
when the statement is executed. Thus, the name acts like a function that has no
arguments. The form of a special register is as follows:
dbcs-string
G dbcs-string G G
G
g
g
dbcs-string
N
N
n
n

N
PL/I
All other
contexts
dbcs-string G G
Context Graphic String Constant Empty String Example
GS G G
I
S
I
S
I
S
I
S
I
S
I
S
I
S
I
S
I
S
I
S
I
S
I
S
O
S
O
S
O
S
O
S
O
S
O
S
O
S
O
S
O
S
O
S
O
S
O
Grepresents a
DBCS G (X 42C7 )
represents a
DBCS apostrophe
(X 427D )
Constants
82 SQL Reference
|
|
|
General rules for special registers
Following these general rules for special registers, each special register is
described individually.
Changing register values: A commit or rollback operation has no effect on the
values of special registers. Nor does any SQL statement, with the following
exceptions:
v SQL SET statements can change the values of CURRENT APPLICATION
ENCODING SCHEME, CURRENT DEGREE, CURRENT LOCALE LC_CTYPE,
CURRENT OPTIMIZATION HINT, CURRENT PACKAGESET, CURRENT PATH,
CURRENT PRECISION, CURRENT RULES, and CURRENT SQLID12.
v SQL CONNECT statements can change the value of CURRENT SERVER.
12. If the SET CURRENT SQLID statement is executed in a stored procedure or user
-defined function package that has a dynamic
SQL behavior other than run behavior, the SET CURRENT SQLID statement does not a
ffect the authorization ID that is used for
dynamic SQL statements in the package. The dynamic SQL behavior determines the a
uthorization ID. For more information, see
the discussion of DYNAMICRULES in Chapter 2 of DB2 Command Reference.
special registers
 CURRENT APPLICATION ENCODING SCHEME
CURRENT DATE
(1)
CURRENT_DATE
CURRENT DEGREE
CURRENT LC_CTYPE
LOCALE
CURRENT_LC_CTYPE
CURRENT MEMBER
CURRENT OPTIMIZATION HINT
CURRENT PACKAGESET
CURRENT PATH
FUNCTION
CURRENT_PATH
CURRENT PRECISION
CURRENT RULES
CURRENT SERVER
CURRENT SQLID
CURRENT TIME
(1)
CURRENT_TIME
CURRENT TIMESTAMP
(1)
CURRENT_TIMESTAMP
CURRENT TIMEZONE
USER

Notes:
1 The SQL standard uses the form with the underline.
Special Registers
Chapter 2. Language elements 83
|
|
CCSIDS for register values: The values of certain special registers are characte
r
strings. The registers with string values are:
v CURRENT APPLICATION ENCODING SCHEME
v CURRENT DEGREE
v CURRENT LOCALE LC_CTYPE
v CURRENT MEMBER
v CURRENT OPTIMIZATION HINT
v CURRENT PACKAGESET
v CURRENT PATH
v CURRENT PRECISION
v CURRENT RULES
v CURRENT SERVER
v CURRENT SQLID
v USER
The CCSID that is associated with these registers is the one named in the ASCII
CODED CHAR SET, EBCDIC CODED CHAR SET, or the UNICODE CCSID field
on installation panel DSNTIPF at the server executing the statement. The CCSID
that is used depends on whether the SQL statement in which the special register
is
referenced involves data in ASCII, EBCDIC, or Unicode tables; if no table is
involved, the CCSID for the default encoding scheme for your system is used. Fie
ld
DEF ENCODING SCHEME on installation panel specifies whether the default
encoding scheme is EBCDIC, ASCII, or UNICODE. For the SET host-variable and
VALUES INTO statements, the application encoding scheme bind option determines
the desired encoding scheme.
Datetime special registers: The datetime registers are named CURRENT DATE,
CURRENT TIME, and CURRENT TIMESTAMP. Datetime special registers are
stored in an internal format. When two or more of these registers are implicitly
or
explicitly specified in a single SQL statement, they represent the same point in
time.
A datetime special register is implicitly specified when it is used to provide t
he
default value of a datetime column.
If the SQL statement in which a datetime special register is used is in a
user-defined function or stored procedure that is within the scope of a trigger,
DB2
uses the timestamp for the triggering SQL statement to determine the special
register value.
The values of these special registers are based on:
v The time-of-day clock of the processor for the server executing the SQL
statement
v The MVS TIMEZONE parameter for this processor. The TIMEZONE parameter is
in SYS1.PARMLIB(CLOCKXX).
To evaluate the references when the statement is being executed, a single readin
g
from the time-of-day clock is incremented by the number of hours, minutes, and
seconds specified by the TIMEZONE parameter. The values derived from this are
assumed to be the local date, time, or timestamp, where local means local to the
DB2 that executes the statement. This assumption is correct if the clock is set
to
local time and the MVS TIMEZONE parameter is zero or the clock is set to GMT
and the MVS TIMEZONE parameter gives the difference from GMT. Universal time,
coordinated (UTC) is another name for Greenwich Mean Time (GMT).
Since the datetime special registers and the CURRENT TIMEZONE special register
depend on the MVS parameter PARMTZ(SYS1.PARMLIB(CLOCKXX)), their values
are affected if the MVS local time at the server is changed by the MVS system
Special Registers
84 SQL Reference
|
|
|
|
|
|
command SET CLOCK. The values of the CURRENT DATE and CURRENT
TIMESTAMP special registers might be affected if the MVS local date at the serve
r
is changed by the MVS system command SET DATE13.
Where special registers are processed: In distributed applications, CURRENT
APPLICATION ENCODING SCHEME, CURRENT SERVER, and CURRENT
PACKAGESET are processed locally. All other special registers are processed at
the server.
CURRENT APPLICATION ENCODING SCHEME
CURRENT APPLICATION ENCODING SCHEME specifies which encoding scheme
is to be used for dynamic statements. It allows an application to indicate the
encoding scheme that is used to process data. This register is not supported in
REXX applications or in stored procedures written in REXX.
The initial value of CURRENT APPLICATION ENCODING SCHEME is determined
by the value of the ENCODING bind option if the bind option is specified. If the
bind
option was not specified, then the initial value is the value of field DEFAULT
APPLICATION ENCODING SCHEME on installation panel DSNTIPF. You can
changes the value of the register by executing the statement SET CURRENT
APPLICATION ENCODING SCHEME. For a description of the statement, see “SET
CURRENT APPLICATION ENCODING SCHEME” on page 850.
The value contained in the special register is a character representation of a
CCSID. Although you can use the values ASCII, EBCDIC, or UNICODE to set the
special register, what is stored in the special register is a character represen
tation
of the numeric CCSID that corresponds to the value used in the SET CURRENT
APPLICATION ENCODING SCHEME statement. The value ASCII, EBCDIC, or
UNICODE is not stored. The CCSID_ENCODING scalar function can be used to
get a value of ASCII, EBCDIC, or UNICODE from a numeric CCSID value.
The data type is CHAR(8). If necessary, the value is padded on the right with
blanks so that its length is 8 bytes.
For stored procedures and user-defined functions, the initial value of the CURRE
NT
APPLICATION ENCODING SCHEME special register is determined by the value of
the ENCODING bind option for the package that is associated with the procedure o
r
function. If the bind option was not specified, then the initial value is the va
lue of the
field DEFAULT APPLICATION ENCODING SCHEME field on installation panel
DSNTIPF.
For triggers, the initial value of the CURRENT APPLICATION ENCODING SCHEME
special register is the value of field DEFAULT APPLICATION ENCODING SCHEME
on installation panel DSNTIPF.
Example: The CURRENT APPLICATION ENCODING SCHEME special register can
be used like any other special register:
EXEC SQL VALUES(CURRENT APPLICATION ENCODING SCHEME) INTO :HV1;
EXEC SQL INSERT INTO T1VALUES (CURRENT APPLICATION ENCODING SCHEME);
EXEC SQL SET :HV1= CURRENT APPLICATION ENCODING SCHEME;
EXEC SQL SELECT C1FROM T1WHERE C1= CURRENT APPLICATION ENCODING SCHEME;
13. Whether the SET DATE command affects these special registers depends on the
MVS system level and the program temporary
fix (PTF) level of the system.
Special Registers
Chapter 2. Language elements 85
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
CURRENT DATE
CURRENT DATE, or equivalently CURRENT_DATE, specifies the current date. The
data type is DATE. The value of CURRENT DATE in a user-defined function or
stored procedure is inherited according to the rules in Table 19 on page 92. For
other applications, the date is derived by the DB2 that executes the SQL stateme
nt
that refers to the special register. For a description of how the date is derive
d, see
“Datetime special registers” on page 84.
Example: Display the average age of employees.
SELECT AVG(YEAR(CURRENT DATE - BIRTHDATE))
FROM DSN8710.EMP;
CURRENT DEGREE
CURRENT DEGREE specifies the degree of parallelism for the execution of queries
that are dynamically prepared by the application process. The data type of the
register is CHAR(3) and the only valid values are 1 (padded on the right with tw
o
blanks) and ANY.
If the value of CURRENT DEGREE is 1 when a query is dynamically prepared, the
execution of that query will not use parallelism. If the value of CURRENT DEGREE
is ANY when a query is dynamically prepared, the execution of that query can
involve parallelism. See Part 5 (Volume 2) of DB2 Administration Guide for a
description of query parallelism.
The initial value of CURRENT DEGREE is determined by the value of field
CURRENT DEGREE on installation panel DSNTIP4. The default for the initial value
of that field is 1 unless your installation has changed it to be ANY by modifyin
g the
value in that field. The initial value of CURRENT DEGREE in a user-defined
function or stored procedure is inherited according to the rules in Table 19 on
page 92.
You can change the value of the register by executing the statement SET
CURRENT DEGREE. For details about this statement, see “SET CURRENT
DEGREE” on page 851.
CURRENT DEGREE is a register at the database server. Its value applies to
queries that are dynamically prepared at that server and to queries that are
dynamically prepared at another DB2 subsystem as a result of the use of a DB2
private connection between that server and that DB2 subsystem.
Example: The following statement inhibits parallelism:
SET CURRENT DEGREE = 1 ;
CURRENT LOCALE LC_CTYPE
CURRENT LOCALE LC_CTYPE specifies the LC_CTYPE locale that will be used
to execute SQL statements that use a built-in function that references a locale.
Functions LCASE, UCASE, and TRANSLATE (with a single argument) refer to the
locale when they are executed. The data type is CHAR(50). If necessary, the valu
e
is padded on the right with blanks so that its length is 50 bytes.
The initial value of CURRENT LOCALE LC_CTYPE is determined by the value of
field LOCALE LC_CTYPE on installation panel DSNTIPF. The default for the initial
value of that field is blank unless your installation has changed the value of t
hat
Special Registers
86 SQL Reference
|
|
|
|
|
|
|
field. The initial value of CURRENT LOCALE LC_CTYPE in a user-defined function
or stored procedure is inherited according to the rules in Table 19 on page 92.
You can change the value of the register by executing the statement SET
CURRENT LOCALE LC_CTYPE. For details about this statement, see “SET
CURRENT LOCALE LC_CTYPE” on page 853.
Example: Save the value of current register CURRENT LOCALE LC_CTYPE in
host variable HV1, which is defined as VARCHAR(50).
EXEC SQL VALUES(CURRENT LOCALE LC_CTYPE) INTO :HV1;
CURRENT OPTIMIZATION HINT
CURRENT OPTIMIZATION HINT specifies the user-defined optimization hint that
DB2 should use to generate the access path for dynamic statements. The data type
is CHAR(8).
The value of the register identifies the rows in auth.PLAN_ID that DB2 uses to
generate the access path. If the value of the register is all blanks, DB2 uses n
ormal
optimization and ignores optimization hints. If the value of the register includ
es any
non-blank characters and DB2 was installed without optimization hints enabled (f
ield
OPTIMIZATION HINTS on installation panel DSNTIP4), a warning occurs.
The initial value of CURRENT OPTIMIZATION HINT is the value of the OPTHINT
bind option. The initial value of CURRENT OPTIMIZATION HINT in a user-defined
function or stored procedure is inherited according to the rules in Table 19 on
page 92. You can change the value of the special register by executing the
statement SET CURRENT OPTIMIZATION HINT. For details about this statement,
see “SET CURRENT OPTIMIZATION HINT” on page 855.
Example: Set the CURRENT OPTIMIZATION HINT special register so that DB2
uses the optimization plan hint that is identified by host variable NOHYB when
generating the access path for dynamic statements.
SET CURRENT OPTIMIZATION HINT = :NOHYB
For more information about telling DB2 how to generate access paths, see Part 6
of
DB2 Application Programming and SQL Guide.
CURRENT PACKAGESET
CURRENT PACKAGESET specifies a string of blanks or the collection ID of the
package or packages that will be used to execute SQL statements. The data type i
s
CHAR(18). If necessary, the collection ID is padded on the right with blanks so
that
its length is 18 bytes.
The initial value of CURRENT PACKAGESET is blanks. The value is a collection ID
only if the application process has explicitly specified a collection ID by mean
s of
the SET CURRENT PACKAGESET statement. For details about this statement, see
“SET CURRENT PACKAGESET” on page 856. The initial value of CURRENT
PACKAGESET in a user-defined function or stored procedure is inherited according
to the rules in Table 19 on page 92.
Example: Before passing control to another program, identify the collection ID f
or its
package as ALPHA.
EXEC SQL SET CURRENT PACKAGESET = ALPHA ;
Special Registers
Chapter 2. Language elements 87
|
|
|
|
|
|
|
|
CURRENT PATH
CURRENT PATH, or equivalently CURRENT_PATH, specifies the SQL path used to
resolve unqualified data type names and function names in dynamically prepared
SQL statements. It is also used to resolve unqualified procedure names that are
specified as host variables in SQL CALL statements (CALL host-variable). The dat
a
type is VARCHAR(254).
The CURRENT PATH special register contains a list of one or more schema
names, where each schema name is enclosed in delimiters and separated from the
following schema by a comma (any delimiters within the string are repeated as th
ey
are in any delimited identifier). The delimiters and commas are included in the
254
character length.
For information on when the SQL path is used to resolve unqualified names in bot
h
dynamic and static SQL statements and the effect of its value, see “Schemas and
the SQL path” on page 40.
The initial value of the CURRENT PATH special register is:
v The value of the PATH bind option, or
v ″SYSIBM″, ″SYSFUN″, ″SYSPROC″, ″value of CURRENT SQLID special
register″ if the PATH bind option was not specified
The initial value of CURRENT PATH in a user-defined function or stored procedure
is inherited according to the rules in Table 19 on page 92.
You can change the value of the register by executing the statement SET PATH.
For details about this statement, see “SET PATH” on page 865.
Example: Set the special register so that schema SMITH is searched before
schemas SYSIBM, SYSFUN, and SYSPROC.
SET PATH = SMITH, SYSIBM, SYSFUN, SYSPROC;
CURRENT PRECISION
CURRENT PRECISION specifies the rules to be used when both operands in a
decimal operation have precisions of 15 or less. The data type of the register i
s
CHAR(5), and the only valid values are DEC15 and DEC31 . DEC15 specifies the
rules that do not allow a precision greater than 15 digits, and DEC31 specifies
the
rules that allow a precision of up to 31 digits. The rules for DEC31 are always
used
if either operand has a precision greater than 15.
The initial value of CURRENT PRECISION is determined by the value of field
DECIMAL ARITHMETIC on installation panel DSNTIP4. The default for the initial
value is DEC15 unless your installation has changed it to be DEC31 by modifying
the value in that field. The initial value of CURRENT PRECISION in a user-define
d
function or stored procedure is inherited according to the rules in Table 19 on
page 92.
You can change the value of the register by executing the statement SET
CURRENT PRECISION. For details about this statement, see “SET CURRENT
PRECISION” on page 858.
CURRENT PRECISION only affects dynamic SQL. If the value of CURRENT
PRECISION is DEC15 when an SQL statement is dynamically prepared, DEC15
rules will apply. If the value of CURRENT PRECISION is DEC31 when an SQL
statement is dynamically prepared, DEC31 rules will apply. Preparation of a
Special Registers
88 SQL Reference
|
|
#
#
|
|
|
statement with DEC31 instead of DEC15 is more likely to result in an error,
especially for division operations. For more information, see “Arithmetic with two
decimal operands” on page 114.
Example: Set CURRENT PRECISION so that subsequent statements that are
prepared use DEC31 rules for decimal arithmetic:
SET CURRENT PRECISION = DEC31 ;
CURRENT RULES
CURRENT RULES specifies whether certain SQL statements are executed in
accordance with DB2 rules or the rules of the SQL standard. The data type of the
register is CHAR(3), and the only valid values are DB2 and STD .
CURRENT RULES is a register at the database server. If the server is not the loc
al
DB2, the initial value of the register is DB2 . Otherwise, the initial value is
the same
as the value of the SQLRULES bind option. The initial value of CURRENT RULES
in a user-defined function or stored procedure is inherited according to the rul
es in
Table 19 on page 92.
You can change the value of the register by executing the statement SET
CURRENT RULES. For details about this statement, see “SET CURRENT RULES”
on page 859.
CURRENT RULES affects the statements listed in Table 18. The table summarizes
when the statements are affected and shows where to find detailed information.
CURRENT RULES also affects whether DB2 issues an existence error (SQLCODE
-204) or an authorization error (SQLCODE -551) when an object does not exist.
Table 18. Summary of statements affected by CURRENT RULES
Statement What is affected Details on
page
ALTER TABLE Enforcement of check constraints added.
Default value of the delete rule for referential
constraints.
Whether DB2 creates LOB table spaces, auxiliary
tables, and indexes on auxiliary tables for added
LOB columns.
Whether DB2 creates an index for an added
ROWID column that is defined with GENERATED
BY DEFAULT.
398
CREATE TABLE Default value of the delete rule for referential
constraints.
Whether DB2 creates LOB table spaces, auxiliary
tables, and indexes on auxiliary tables for LOB
columns.
Whether DB2 creates an index for a ROWID
column that is defined with GENERATED BY
DEFAULT.
601
DELETE Authorization requirements for searched DELETE. 688
GRANT Granting privileges to yourself. 749
REVOKE Revoking privileges from authorization IDs 811
Special Registers
Chapter 2. Language elements 89
|
|
|
Table 18. Summary of statements affected by CURRENT RULES (continued)
Statement What is affected Details on
page
UPDATE Authorization requirements for searched UPDATE. 872
Example: Set CURRENT RULES so that a later ALTER TABLE statement is
executed in accordance with the rules of the SQL standard:
SET CURRENT RULES = STD ;
CURRENT SERVER
CURRENT SERVER specifies the location name of the current server. The data
type is CHAR(16). If necessary, the location name is padded on the right with
blanks so that its length is 16 bytes.
The initial value of CURRENT SERVER depends on the CURRENTSERVER bind
option. If CURRENTSERVER X is specified on the bind subcommand, the initial
value is X. If the option is not specified, the initial value is the location na
me of the
local DB2. The initial value of CURRENT SERVER in a user-defined function or
stored procedure is inherited according to the rules in Table 19 on page 92. The
value of CURRENT SERVER is changed by the successful execution of a
CONNECT statement.
The value of CURRENT SERVER is a string of blanks when:
v The application process is in the unconnected state, or
v The application process is connected to a local DB2 subsystem that does not
have a location name.
Example: Set the host variable CS to the location name of the current server.
EXEC SQL SET :CS = CURRENT SERVER;
CURRENT SQLID
CURRENT SQLID specifies the SQL authorization ID of the process. The data type
is CHAR(8). If necessary, the authorization ID is padded on the right with blank
s so
that its length is 8 bytes.
The initial value of CURRENT SQLID can be provided by the connection or sign-on
exit routine. If not, the initial value is the primary authorization ID of the p
rocess.
The initial value of CURRENT SQLID in a user-defined function or stored procedur
e
is inherited according to the rules in Table 19 on page 92.
CURRENT SQLID can only be referred to in an SQL statement that is executed by
the current server.
Example: Set the SQL authorization ID to ’GROUP34’ (one of the authorization IDs
of the process).
SET CURRENT SQLID = GROUP34 ;
CURRENT TIME
CURRENT TIME, or equivalently CURRENT_TIME, specifies the current time. The
data type is TIME.
Special Registers
90 SQL Reference
|
|
|
|
The time is derived by the DB2 that executes the SQL statement that refers to th
e
special register. For a description of how the time is derived, see “Datetime spec
ial
registers” on page 84. The value of CURRENT TIME in a user-defined function or
stored procedure is inherited according to the rules in Table 19 on page 92.
Example: Display information about all project activities and include the curren
t date
and time in each row of the result.
SELECT DSN8710.PROJACT.*, CURRENT DATE, CURRENT TIME
FROM DSN8710.PROJACT;
CURRENT TIMESTAMP
CURRENT TIMESTAMP, or equivalently CURRENT_TIMESTAMP, specifies the
current timestamp. The data type is TIMESTAMP.
The timestamp is derived by the DB2 that executes the SQL statement that refers
to the special register. For a description of how the timestamp is derived, see
“Datetime special registers” on page 84. The value of CURRENT TIMESTAMP in a
user-defined function or stored procedure is inherited according to the rules in
Table 19 on page 92.
Example: Display information about the full image copies that were taken in the
last
week.
SELECT * FROM SYSIBM.SYSCOPY
WHERE TIMESTAMP > CURRENT TIMESTAMP - 7 DAYS;
CURRENT TIMEZONE
CURRENT TIMEZONE specifies the MVS TIMEZONE parameter in the form of a
time duration. The data type is DECIMAL(6,0).
The time duration is derived by the DB2 that executes the SQL statement that
refers to the special register. The seconds part of the time duration is always
zero.
An error occurs if the hours portion of the MVS TIMEZONE parameter is not
between -24 and 24. The value of CURRENT TIMEZONE in a user-defined function
or stored procedure is inherited according to the rules in Table 19 on page 92.
Example: Display information from SYSCOPY, but with the TIMESTAMP converted
to GMT. This example is based on the assumption that the installation sets the
clock to GMT and the MVS TIMEZONE parameter to the difference from GMT.
SELECT DBNAME, TSNAME, DSNUM, ICTYPE, TIMESTAMP - CURRENT TIMEZONE
FROM SYSIBM.SYSCOPY;
USER
USER specifies the primary authorization ID of the process. The data type is
CHAR(8). If necessary, the authorization ID is padded on the right with blanks s
o
that its length is 8 bytes.
If USER is referred to in an SQL statement that is executed at a remote DB2 and
the primary authorization ID has been translated to a different authorization ID
,
USER specifies the translated authorization ID. For an explanation of authorizat
ion
ID translation, see Part 3 (Volume 1) of DB2 Administration Guide. The value of
USER in a user-defined function or stored procedure is determined according to t
he
rules in Table 19 on page 92.
Special Registers
Chapter 2. Language elements 91
|
|
|
|
|
|
|
|
|
|
Example: Display information about tables, views, and aliases that are owned by
the primary authorization ID of the process.
SELECT * FROM SYSIBM.SYSTABLES WHERE CREATOR = USER;
Inheriting special registers in a user-defined function or a stored
procedure
Table 19 shows information you need when you use special registers in a
user-defined function or stored procedure.
Table 19. Characteristics of special registers in a user-defined function or a s
tored procedure
Special register Initial value when
INHERIT SPECIAL
REGISTERS option is
specified
Initial value when
DEFAULT SPECIAL
REGISTERS option is
specified
Routine
can use
SET
statement
to modify?
CURRENT
APPLICATION
ENCODING SCHEME
The value of bind option
ENCODING for the
user-defined function or
stored procedure
package
The value of bind option
ENCODING for the
user-defined function or
stored procedure
package
Yes
CURRENT DATE New value for each SQL
statement in the
user-defined function or
stored procedure
package1
New value for each SQL
statement in the
user-defined function or
stored procedure
package1
Not
applicable4
CURRENT DEGREE Inherited from invoker2 The value of field
CURRENT DEGREE on
installation panel
DSNTIP4
Yes
CURRENT LOCALE
LC_CTYPE
Inherited from invoker The value of field
CURRENT LC_CTYPE
on installation panel
DSNTIPF
Yes
CURRENT
OPTIMIZATION HINT
The value of bind option
OPTHINT for the
user-defined function or
stored procedure
package or inherited
from invoker5
The value of bind option
OPTHINT for the
user-defined function or
stored procedure
package
Yes
CURRENT
PACKAGESET
Inherited from invoker3 Inherited from invoker3 Yes
CURRENT PATH The value of bind option
PATH for the
user-defined function or
stored procedure
package or inherited
from invoker5
The value of bind option
PATH for the
user-defined function or
stored procedure
package
Yes
CURRENT PRECISION Inherited from invoker The value of field
DECIMAL ARITHMETIC
on installation panel
DSNTIP4
Yes
Special Registers
92 SQL Reference
|
|
|
|
|
|
|||
||||
|||||
|||
|||||
|
|
||||
|||||
||
|
|||
||
|
|||
|| ||||||
|||||
|
||
|
|||||
|||||
|
|
|||
Table 19. Characteristics of special registers in a user-defined function or a s
tored
procedure (continued)
Special register Initial value when
INHERIT SPECIAL
REGISTERS option is
specified
Initial value when
DEFAULT SPECIAL
REGISTERS option is
specified
Routine
can use
SET
statement
to modify?
CURRENT RULES Inherited from invoker The value of bind option
SQLRULES for the
user-defined function
package or stored
procedure package
Yes
CURRENT SERVER Inherited from invoker Inherited from invoker Yes
CURRENT SQLID The primary
authorization ID of the
application process or
inherited from invoker6
The primary
authorization ID of the
application process
Yes7
CURRENT TIME New value for each SQL
statement in the
user-defined function or
stored procedure
package1
New value for each SQL
statement in the
user-defined function or
stored procedure
package1
Not
applicable4
CURRENT TIMESTAMP New value for each SQL
statement in the
user-defined function or
stored procedure
package1
New value for each SQL
statement in the
user-defined function or
stored procedure
package1
Not
applicable4
CURRENT TIMEZONE Inherited from invoker Inherited from invoker Not
applicable4
CURRENT USER Primary authorization ID
of the application
process
Primary authorization ID
of the application
process
Not
applicable4
Special Registers
Chapter 2. Language elements 93
|
|
|
|||
||||
|||||
||||
|
|
|||
|||
|
|
||||
|||||
||
|
||||
|||||
||
|
|
|
||
|||
||
Table 19. Characteristics of special registers in a user-defined function or a s
tored
procedure (continued)
Special register Initial value when
INHERIT SPECIAL
REGISTERS option is
specified
Initial value when
DEFAULT SPECIAL
REGISTERS option is
specified
Routine
can use
SET
statement
to modify?
Note:
1. If the user-defined function or stored procedure is invoked within the scope
of a trigger,
DB2 uses the timestamp for the triggering SQL statement as the timestamp for all
SQL
statements in the package.
2. DB2 allows parallelism at only one level of a nested SQL statement. If you se
t the value
of the CURRENT DEGREE special register to ANY, and parallelism is disabled, DB2
ignores the CURRENT DEGREE value.
3. If the user-defined function or stored procedure definer specifies a value fo
r COLLID in
the CREATE FUNCTION statement, DB2 sets CURRENT PACKAGESET to the value of
COLLID.
4. Not applicable because no SET statement exists for the special register.
5. If a program within the scope of the invoking program issues a SET statement
for the
special register before the user-defined function or stored procedure is invoked
, the
special register inherits the value from the SET statement. Otherwise, the speci
al register
contains the value that is set by the bind option for the user-defined function
or stored
procedure package.
6. If a program within the scope of the invoking program issues a SET CURRENT SQ
LID
statement before the user-defined function or stored procedure is invoked, the s
pecial
register inherits the value from the SET statement. Otherwise, CURRENT SQLID
contains the authorization ID of the application process.
7. If the user-defined function or stored procedure package uses a value other t
han RUN for
the DYNAMICRULES bind option, the SET CURRENT SQLID statement can be executed
but does not affect the authorization ID that is used for the dynamic SQL statem
ents in
the package. The DYNAMICRULES value determines the authorization ID that is used
for
dynamic SQL statements. For more information, see the discussion of DYNAMICRULES
in Chapter 2 of DB2 Command Reference.
Column names
The meaning of a column name depends on its context. A column name can be
used to:
v Declare the name of a column, as in a CREATE TABLE statement or in a
CREATE FUNCTION statement that defines a table function.
v Identify a column, as in a CREATE INDEX statement.
v Specify values of the column, as in the following contexts:
– In a column function, a column name specifies all values of the column in the
group or intermediate result table to which the function is applied. (Groups
and intermediate result tables are explained in Chapter 4. Queries, which
begins on page 299.) For example, MAX(SALARY) applies the function MAX
to all values of the column SALARY in a group.
– In a GROUP BY or ORDER BY clause, a column name specifies all values in
the intermediate result table to which the clause is applied. For example,
ORDER BY DEPT orders an intermediate result table by the values of the
column DEPT.
– In an expression, a search condition, or a scalar function, a column name
specifies a value for each row or group to which the construct is applied. For
Special Registers
94 SQL Reference
|
|
|
|||
||||
|||||
|
|||
|||
|||
|
|||||
||||
|||||||
|
example, when the search condition CODE = 20 is applied to some row, the
value specified by the column name CODE is the value of the column CODE
in that row.
v Temporarily, rename a column, as in the correlation-clause of a table referenc
ed
in a FROM clause.
Qualified column names
A qualifier for a column name can be a table name, a view name, an alias name, a
synonym, or a correlation name.
Whether a column name can be qualified depends, like its meaning, on its context
:
v In some forms of the COMMENT ON and LABEL ON statements, a column
name must be qualified. This is shown in the syntax diagrams.
v Where the column name specifies values of the column, a column name can be
qualified at the user’s option.
v In all other contexts, a column name must not be qualified. This rule will be
mentioned in the discussion of each statement to which it applies.
Where a qualifier is optional, it can serve two purposes. See “Column name
qualifiers to avoid ambiguity” on page 96 and “Column name qualifiers in correlated
references” on page 97 for details.
Correlation names
A correlation name can be defined in the FROM clause of a query and in the first
clause of an UPDATE or DELETE statement. For example, the clause FROM
X.MYTABLE Z establishes Z as a correlation name for X.MYTABLE.
With Z defined as a correlation name for table X.MYTABLE, only Z should be used
to qualify a reference to a column of X.MYTABLE in that SELECT statement.
A correlation name is associated with a table, view, nested table expression or
table
function only within the context in which it is defined. Hence, the same correla
tion
name can be defined for different purposes in different statements. In a nested
table
expression or table function, a correlation name is required.
As a qualifier, a correlation name can be used to avoid ambiguity or to establis
h a
correlated reference. It can also be used merely as a shorter name for a table o
r
view. In the example, Z might have been used merely to avoid having to enter
X.MYTABLE more than once.
The use of a correlation name in the FROM clause also allows the option of
specifying a list of column names to be associated with the columns of the resul
t
table. As with a correlation name, the listed column names should be the names
that are used to reference the columns in that SELECT statement. For example,
assume that the name of the first column in the DEPT table is DEPTNO. Given this
FROM clause:
FROM DEPT D (NUM,NAME,MGR,ANUM,LOC)
You should use D.NUM instead of D.DEPTNO to reference the first column of the
table.
Column Names
Chapter 2. Language elements 95
Column name qualifiers to avoid ambiguity
In the context of a function, a GROUP BY clause, an ORDER BY clause, an
expression, or a search condition, a column name refers to values of a column in
some table, view, nested table expression, or table function. The tables, views,
nested table expression, or table function reference that might contain the colu
mn
are called the object tables of the context. Two or more object tables might con
tain
columns with the same name. One reason for qualifying a column name is to name
the table from which the column comes.
Table designators: A qualifier that names a specific object table is called a ta
ble
designator. The clause that identifies the object tables also establishes the ta
ble
designators for them. For example, the object tables of an expression in a SELEC
T
clause are named in the FROM clause that follows it, as in this statement:
SELECT DISTINCT Z.EMPNO, EMPTIME, PHONENO
FROM DSN8710.EMP Z, DSN8710.EMPPROJACT
WHERE WORKDEPT = D11
AND EMPTIME > 0.5
AND Z.EMPNO = DSN8710.EMPPROJACT.EMPNO;
This example illustrates how to establish table designators in the FROM clause:
v A correlation name that follows a table name, view name, nested table
expression, or table function is a table designator. Thus, Z is a table designat
or
and qualifies the first column name after SELECT.
v A table name or view name that is not followed by a correlation name is a tabl
e
designator. Thus, the qualified table name, DSN8710.EMPPROJACT is a table
designator and qualifies the EMPNO column.
Avoiding undefined or ambiguous references in DB2 SQL: When a column
name refers to values of a column, exactly one object table must include a colum
n
with that name. The following situations are considered errors:
v No object table contains a column with the specified name. The reference is
undefined.
v The column name is qualified by a table designator, but the table named does
not include a column with the specified name. Again, the reference is undefined.
v The name is unqualified and more than one object table includes a column with
that name. The reference is ambiguous.
Avoid ambiguous references by qualifying a column name with a uniquely defined
table designator. If the column is contained in several object tables with diffe
rent
names, the table names can be used as designators.
Two or more object tables can be instances of the same table. A FROM clause that
includes n references to the same table should include at least n - 1 unique
correlation names.
For example, in the following FROM clause X and Y are defined to refer,
respectively, to the first and second instances of the table EMP.
SELECT X.LASTNAME, Y.LASTNAME
FROM DSN8710.EMP X, DSN8710.EMP Y
WHERE Y.JOB = MANAGER
AND X.WORKDEPT = Y.WORKDEPT
AND X.JOB <> MANAGER ;
Column Names
96 SQL Reference
Column name qualifiers in correlated references
A subselect and a fullselect are forms of a query that can be used as a componen
t
of various SQL statements. Refer to “Chapter 4. Queries” on page 299 for more
information on subselects and fullselects. A subselect or a fullselect used with
in a
search condition of any statement is called a subquery.
A subquery can include search conditions of its own, and these search conditions
can, in turn, include subqueries. Thus, an SQL statement can contain a hierarchy
of
subqueries. Those elements of the hierarchy that contain subqueries are said to
be
at a higher level than the subqueries they contain.
Every element of the hierarchy has a clause that establishes one or more table
designators. This is the FROM clause, except in the highest level of an UPDATE o
r
DELETE statement. A search condition of a subquery can reference not only
columns of the tables identified by the FROM clause of its own element of the
hierarchy, but also columns of tables identified at any level along the path fro
m its
own element to the highest level of the hierarchy. A reference to a column of a
table
identified at a higher level is called a correlated reference.
A correlated reference to column C of table T can be of the form C, T.C, or Q.C,
if
Q is a correlation name defined for T. However, a correlated reference in the fo
rm
of an unqualified column name is not good practice. The following explanation
is based on the assumption that a correlated reference is always in the form of
a
qualified column name and that the qualifier is a correlation name.
A qualified column name, Q.C, is a correlated reference only if these three
conditions are met:
v Q.C is used in a search condition or in a select list of a subquery.
v Q does not name a table used in the FROM clause of that subquery.
v Q does name a table used at some higher level.
Q.C refers to column C of the table or view at the level where Q is used as the
table designator of that table or view. Because the same table or view can be
identified at many levels, unique correlation names are recommended as table
designators. If Q is used to name a table at more than one level, Q.C refers to
the
lowest level that contains the subquery that includes Q.C.
For example, in the following statement, the correlated reference X.WORKDEPT (in
the last line) refers to the value of WORKDEPT in table DSN8710.EMP at the level
of the first FROM clause (which establishes X as a correlation name for
DSN8710.EMP.). The statement lists employees who make less than the average
salary for their department.
SELECT EMPNO, LASTNAME, WORKDEPT
FROM DSN8710.EMP X
WHERE SALARY < (SELECT AVG(SALARY)
FROM DSN8710.EMP
WHERE WORKDEPT = X.WORKDEPT);
The following example shows a correlated reference in the select list of the
subquery.
SELECT T1.KEY1
FROM BP1TBL T1
GROUP BY T1.KEY1
HAVING MAX(T1.KEY1) = (SELECT MIN(T1.KEY1) + MIN(T2.KEY1)
FROM BP2TBL T2);
Column Names
Chapter 2. Language elements 97
|
|
|
|
|
|
|
|||||
Resolution of column name qualifiers and column names
Names in a FROM clause are either exposed or non-exposed. A correlation name
for a table name, view name, nested table expression, or reference to a function
reference is always exposed. A table name or a view name that is not followed by
a
correlation name is also exposed.
In IBM SQL and ANSI/ISO SQL, the exposed names in a FROM clause must be
unique, and the qualifier of a column name must be an exposed name.
The rules for finding the referent of a column name qualifier are as follows:
1. Let Q be a one-, two-, or three-part name, and let Q.C denote a column name
in subselect S. Q must designate a table or view identified in the statement tha
t
includes S and that table or view must have a column named C. An additional
requirement differs for two cases:
v If Q.C is not in a search-condition or S is not a subquery, Q must designate a
table or view identified in the FROM clause of S. For example, if Q.C is in a
SELECT clause, Q refers to a table or view in the following FROM clause.
v If Q.C is in a search-condition and S is a subquery, Q must designate a table
or view identified either in the FROM clause of S or in a FROM clause of a
subselect that directly or indirectly includes S. For example, if Q.C is in a
WHERE clause and S is the only subquery in the statement, the table or view
that Q refers to is either in the FROM clause of S or the FROM clause of the
subselect that includes S.
2. The same table or view can be identified more than once in the same
statement. The particular occurrence of the table or view that Q refers to is
determined by a procedure equivalent to the following steps:
a. The one- and two-part names in every FROM clause and the one- and
two-part qualifiers of column names are expanded into a fully-qualified form.
For example, if a dynamic SQL statement uses FROM Q and
DYNAMICRULES run behavior (RUN) is in effect, Q is expanded to S.A.Q,
where S is the value of CURRENT SERVER and A is the value of
CURRENT SQLID. (If DYNAMICRULES bind behavior is in effect instead, A
is the plan or package qualifier as determined during the bind process.) We
refer to this step later as “name completion”. An error occurs if the first part
of every name (the location) is not the same.
b. Q, now a three-part name, is compared with every name in the FROM
clause of S. If Q.C is in a search-condition and S is a subquery, Q is next
compared with every name in the FROM clause of the subselect that
contains S. If that subselect is a subquery, Q is then compared with every
name in the FROM clause of the subselect containing that subquery, and so
on. If a FROM clause includes multiple names, the comparisons in that
clause are made in order from left to right.
c. The referent of Q is selected by these rules:
v If Q matches exactly one name, that name is selected.
v If Q matches more than one name, but only one exposed name, that
exposed name is selected.
v If Q matches more than one exposed name, the first of those names is
selected.
v If Q matches more than one name, none of which are exposed names,
the first of those names is selected.
Column Names
98 SQL Reference
|
If Q does not match any name, or if the table or view designated by Q does
not include a column named C, an error occurs.
d. Otherwise, Q.C is resolved to column C of the occurrence of the table or
view identified by the selected name.
3. A warning occurs for any of these cases:
v The selected name is not an exposed name.
v The selected name is an exposed name that has an unexposed duplicate
that appears before the selected name in the ordered list of names to which
Q is compared.
v The selected name is an exposed name that has an exposed duplicate in the
same FROM clause.
v Another name would have been selected had the matching been performed
before name completion.
The warnings indicate cases of ambiguous references in which the referent
selected might not be the same one that would have been selected in releases
of DB2 before Version 2 Release 3.
The rules for resolving column name qualifiers apply to every SQL statement
that includes a subselect and are applied before synonyms and aliases are
resolved. In the case of a searched UPDATE or DELETE statement, the first
clause of the statement identifies the table or view to be updated or deleted.
That clause can include a correlation name and, with regard to name resolution,
is equivalent to the first FROM clause of a SELECT statement. For example, a
subquery in the search condition of an UPDATE statement can include a
correlated reference to a column of the updated rows.
The rules for column names in the ORDER BY clause are the same as other
clauses.
References to variables
A variable is a host variable or an SQL variable that is referenced in an SQL
statement. Host variables are defined by statements of a host language. SQL
variables are defined by an SQL compound-statement in an SQL procedure.
Variables cannot be referenced in dynamic SQL statements; parameter markers
must be used instead. In this book, unless otherwise noted, the term host variab
le
in syntax diagrams is used to indicate where a host-variable, SQL variable, or
parameter marker can be used.
For more information on host variables, see “References to host variables”. For
more information on SQL variables, see “compound-statement” on page 895. For
more information on parameter markers, see “Parameter markers” on page 798.
References to host variables
A host variable is either of these items that is referred to in an SQL statement
:
v A variable in a host language such as a PL/I variable, C variable, Fortran
variable, COBOL data item, or Assembler language storage area
v A host language construct that was generated by an SQL precompiler from a
variable declared using SQL extensions
Column Names
Chapter 2. Language elements 99
|
|
|
|
|
|
|
|
|
|
|
Host variables are defined directly by statements of the host language or indire
ctly
by SQL extensions as described in Part 2 of DB2 Application Programming and
SQL Guide. Host variables cannot be referenced in dynamic SQL statements.
In PL/I, C, and COBOL, host variables can be referred to in ways that do not app
ly
to Fortran and Assembler language. This is explained in “Host structures in PL/I,
C,
and COBOL” on page 103. The following applies to all host languages.
The term host-variable, as used in the syntax diagrams, shows a reference to a
host variable. In a SET assignment statement and the INTO clause of a FETCH,
SELECT INTO, or VALUES INTO statement, a host variable is an output variable to
which a value is assigned by DB2. In all other contexts, a host variable is an i
nput
variable which provides a value to DB2.
The general form of a host variable reference is:
Each host identifier must be declared in the source program, except in a program
written in REXX. The first host identifier designates the main variable; the sec
ond
host identifier designates its indicator variable. The variable designated by th
e
second host identifier must be a small integer. The purposes of the indicator
variable are to:
v Specify the null value. A negative value of the indicator variable specifies t
he null
value. A -2 null indicates a numeric conversion or arithmetic expression error
occurred in the SELECT list of an outer SELECT statement.
v Record the original length of a truncated string.
v Indicate that a character could not be converted.
v Record the seconds portion of a time if the time is truncated on assignment to
a
host variable.
For example, if :V1:V2 is used to specify an insert or update value, and if V2 i
s
negative, the value specified is the null value. If V2 is not negative, the valu
e
specified is the value of V1.
Similarly, if :V1:V2 is specified in a FETCH or SELECT INTO statement, and if th
e
value returned is null, V1 is not changed and V2 is set to -1 or -2. It is set t
o -1 if
the value selected was actually null. It is set to -2 if the null value was retu
rned
because of numeric conversion errors or arithmetic expression errors in the
SELECT list of an outer SELECT statement. It is also set to -2 as the result of
a
character conversion error. If the value returned is not null, that value is ass
igned to
V1, and V2 is set to zero (unless the assignment to V1 requires string truncatio
n, in
which case V2 is set to the original length of the string). If an assignment req
uires
truncation of the seconds part of a time, V2 is set to the number of seconds.
If the second host identifier is omitted, the host variable does not have an ind
icator
variable: the value specified by the host variable :V1 is always the value of V1
and
null values cannot be assigned to the variable. Thus, this form should not be us
ed
 :host-identifier
INDICATOR
:host-identifier

References to Host Variables
100 SQL Reference
|
|
in an INTO clause unless the corresponding result column cannot contain null
values. If this form is used for an output host variable and the value returned
is null,
DB2 will generate an error at run time.
An SQL statement that refers to host variables must be within the scope of the
declaration of those host variables. For host variables referred to in the SELEC
T
statement of a cursor, that rule applies to the OPEN statement rather than to th
e
DECLARE CURSOR statement.
All references to host variables must be preceded by a colon. If an SQL
statement references a host variable without a preceding colon, the precompiler
issues an error for the missing colon or interprets the host variable as an
unqualified column name, which might lead to unintended results. The interpretat
ion
of a host variable without a colon as a column name occurs when the host variabl
e
is referenced in a context in which a column name can also be referenced.
Host variables in dynamic SQL
In dynamic SQL statements, parameter markers are used instead of host variables.
A parameter marker is a question mark (?) that represents a position in a dynami
c
SQL statement where the application will provide a value; that is, where a host
variable would be found if the statement string were a static SQL statement. The
following examples show a static SQL statement that uses host variables and a
dynamic statement that uses parameter markers:
INSERT INTO DEPT VALUES (:HV_DEPTNO, :HV_DEPTNAME, :HV_MGRNO, :HV_ADMRDEPT)
INSERT INTO DEPT VALUES (?, ?, ?, ?)
For more information on parameter markers, see “Parameter markers” on page 798
under the PREPARE statement.
References to LOB host variables
Regular LOB variables (CLOB, DBCLOB, and BLOB) and LOB locator variables
(see “References to LOB locator variables” on page 102) can be defined in all host
languages, except in REXX. Where LOBs are allowed, the term host-variable in a
syntax diagram can refer to a regular host variable or a locator variable. Since
these variables are not native data types in host programming languages, SQL
extensions are used and the precompilers generate the host language constructs
necessary to represent each variable.
When it is possible to define a host variable that is large enough to hold an en
tire
LOB value and the performance benefit of delaying the transfer of data from the
server is not required, a LOB locator is not needed. However, host language
restrictions, storage restrictions, or performance often dictate against storing
an
entire LOB value in temporary storage. When it is preferable not to store an ent
ire
LOB value, a LOB locator can be used to refer to the LOB value and portions of t
he
LOB value can be selected into or updated from host variables that contain only
a
portion of the LOB value.
Like all other host variables, a LOB locator variable can have an associated
indicator variable. Indicator variables for LOB locator variables behave in the
same
way as indicator variables for other data types. When a null value is returned f
rom
the database, the indicator variable is set and the locator host variable is
unchanged. This means a locator can never represent a null value.
References to Host Variables
Chapter 2. Language elements 101
|
References to LOB locator variables
A LOB locator variable is a host variable that contains the locator representing
a
LOB value on the database server.
A locator variable in an SQL statement must identify a LOB locator variable
described in the program according to the rules for declaring locator variables.
This
is always indirectly through an SQL statement. For example, in C:
static volatile SQL TYPE IS CLOB_LOCATOR *loc1;
The term locator-variable, as used in the syntax diagrams, shows a reference to
a
LOB locator variable. The meta-variable locator-variable can be expanded to incl
ude
a host-identifier the same as that for host-variable.
Like all other host variables, a LOB locator variable can have an associated
indicator variable. Indicator variables for LOB locator variables behave in the
same
way as indicator variables for other data types. When a null value is returned f
rom
the database, the indicator variable is set and the locator host variable is
unchanged. This means a locator can never represent a null value. However, when
the indicator variable associated with a LOB locator is null, the value of the
referenced LOB value is null.
If a locator variable does not currently represent any value, an error occurs wh
en
the locator variable is referenced.
At transaction commit, all LOB locators that were acquired by the transaction ar
e
released unless a HOLD LOCATOR statement was issued for the LOB locator. At
transaction termination, all LOB locators are released.
References to stored procedure result sets
When an application needs to access a result set returned from a stored procedur
e,
the invoking application must first define a result set locator to access the re
sult set.
An ASSOCIATE LOCATOR statement defines a result set locator, which identifies
the stored procedure that returns the result set. The DESCRIBE PROCEDURE
statement can be used to determine the number of result sets that a stored
procedure returns, and the DESCRIBE CURSOR statement can be used to get
information about a result set. The ALLOCATE CURSOR statement is used to
define a cursor and associate it with a result set locator. The application then
issues
FETCH statements to retrieve rows from the result set.
References to result set locator variables
A result set locator variable is a host variable that contains the locator that
identifies
a stored procedure result set.
A result set locator variable in an SQL statement must identify a result set loc
ator
variable described in the program according to the rules for declaring result se
t
locator variables. This is always indirectly through an SQL statement. For examp
le,
in C:
static volatile SQL TYPE IS RESULT_SET_LOCATOR *loc1;
The term rs-locator-variable, as used in the syntax diagrams, shows a reference
to
a result set locator variable. The meta-variable rs-locator-variable can be expa
nded
to include a host-identifier the same as that for host-variable.
References to Host Variables
102 SQL Reference
|
|
|
When the indicator variable associated with a result set locator is null, the
referenced result set is not defined.
If a result set locator variable does not currently represent any stored procedu
re
result set, an error occurs when the locator variable is referenced.
A commit operation destroys all open cursors that were declared in the stored
procedure without the WITH HOLD operation and the result set locators that are
associated with those cursors. Otherwise, a cursor and its associated result set
locator persist past the commit.
Host structures in PL/I, C, and COBOL
A host structure is a PL/I structure, C structure, or COBOL group that is referr
ed to
in an SQL statement. Host structures are defined by statements of the host
language, as explained in Part 2 of DB2 Application Programming and SQL Guide.
As used here, the term “host structure” does not include an SQLCA or SQLDA.
The form of a host structure reference is identical to the form of a host variab
le
reference. The reference :S1:S2 is a host structure reference if S1 names a host
structure. If S1 designates a host structure, S2 must be a small integer variabl
e or
an array of small integer variables. S1 is the host structure and S2 is its indi
cator
array.
A host structure can be referred to in any context where a list of host variable
s can
be referenced. A host structure reference is equivalent to a reference to each o
f the
host variables contained within the structure in the order which they are define
d in
the host language structure declaration. The nth variable of the indicator array
is the
indicator variable for the nth variable of the host structure.
In PL/I, for example, if V1, V2, and V3 are declared as the variables within the
structure S1, the statement:
EXEC SQL FETCH CURSOR1INTO :S1;
is equivalent to:
EXEC SQL FETCH CURSOR1INTO :V1, :V2, :V3;
If the host structure has m more variables than the indicator array, the last m
variables of the host structure do not have indicator variables. If the host str
ucture
has m fewer variables than the indicator array, the last m variables of the indi
cator
array are ignored. These rules also apply if a reference to a host structure inc
ludes
an indicator variable or a reference to a host variable includes an indicator ar
ray. If
an indicator array or variable is not specified, no variable of the host structu
re has
an indicator variable.
In addition to structure references, individual host variables or indicator vari
ables in
PL/I, C, and COBOL can be referred to by qualified names. The qualified form is
a
host identifier followed by a period and another host identifier. The first host
identifier must name a structure, and the second host identifier must name a hos
t
variable within that structure.
In PL/I, C, and COBOL, the syntax of host-variable is:
References to Host Variables
Chapter 2. Language elements 103
In general, a host-variable in an expression must identify a host variable (not
a
structure) described in the program according to the rules for declaring host
variables. However, there are a few SQL statements that allow a host variable in
an
expression to identify a structure, as specifically noted in the descriptions of
the
statements.
The following examples show references to host variables and host structures:
:V1 :S1.V1 :S1.V1:V2 :S1.V2:S2.V4
Functions
A function is an operation denoted by a function name followed by zero or more
operands that are enclosed in parentheses. It represents a relationship between
a
set of input values and a set of result values. The input values to a function a
re
called arguments. For example, a function can be passed two input arguments that
have date and time data types and return a value with a timestamp data type as t
he
result.
Types of functions
There are several ways to classify functions. One way to classify functions is a
s
built-in functions, user-defined functions, or cast functions that are generated
for
distinct types.
v Built-in functions are IBM-supplied functions that come with DB2 for OS/390 an
d
z/OS and are in the SYSIBM schema. Built-in functions include operator
functions such as ″+″, column functions such as AVG, and scalar functions such
as SUBSTR. For a list of the built-in column and scalar functions and informatio
n
on these functions, see “Chapter 3. Built-in functions” on page 153.
v User-defined functions are functions that are registered to DB2 in catalog tab
le
SYSIBM.SYSROUTINES using the CREATE FUNCTION statement. These
functions allow users to extend the function of the database system by adding
their own or third party vendor function definitions.
A user-defined function can be an external, sourced, or SQL scalar function. An
external function is defined to the database with a reference to a load module
that is executed when the function is invoked. A sourced function is defined to
the database with a reference to a built-in function or another user-defined
function. Sourced functions are useful for supporting the use of built-in column
and scalar functions for distinct types. An SQL function is defined in the RETUR
N
clause of the function.
A user-defined function resides in the schema in which it was registered. The
schema cannot be SYSIBM. In addition to being external or sourced,
user-defined functions can be further categorized as scalar, column, or table
functions.
To help you define and implement user-defined functions, sample user-defined
functions are supplied with DB2. You can also use these sample user-defined
 : host-identifier
host-identifier.


INDICATOR
: host-identifier
host-identifier.

Host Structures in PL/I, C, and COBOL
104 SQL Reference
|
|
functions in your application program just as you would any other user-defined
function if the appropriate installation job has been run. For a list of the sam
ple
user-defined functions, see “Appendix G. Sample user-defined functions” on
page 1099. For more information on creating and using user-defined functions,
see Part 2 of DB2 Application Programming and SQL Guide.
v Cast functions are automatically generated by DB2 when a distinct type is
created using the CREATE DISTINCT TYPE statement. These functions support
casting from the distinct type to the source type and from the source type to th
e
distinct type. The ability to cast between the data types is important because a
distinct type is compatible only with itself.
The generated cast functions reside in the same schema as the distinct type for
which they were created. The schema cannot be SYSIBM. For more information
on the functions that are generated for a distinct type, see “CREATE DISTINCT
TYPE” on page 474.
Another way to classify functions is as column, scalar, or table functions, depe
nding
on the input data values and result values.
v A column function returns a single-value result for the argument it receives.
The
argument is a set of like values (such as the values of a column). Column
functions are sometimes called aggregating functions. Built-in functions and
user-defined sourced functions can be column functions. An external user-defined
function cannot be a column function.
v A scalar function also returns a single-value result for the arguments it rece
ives.
Each argument is a single value. Built-in functions and user-defined functions,
both external and sourced, can be scalar functions. The functions that are
created for distinct types are also scalar functions.
v A table function returns a table for the set of arguments it receives. Each
argument is a single value. A table function can only be referenced in the FROM
clause of a subselect. Table functions can be used to apply SQL language
processing power to data that is not DB2 data or to convert such data into a DB2
table. For example, a table function can take a file and convert it to a table,
get
data from the World Wide Web and tabularize it, or access a Lotus® Notes™
database and return information about mail messages. Only external
user-defined functions can be table functions.
Each reference to a scalar or column function (either built-in or user-defined)
conforms to the following syntax:
In the above syntax, expression cannot include a column function. See
“Expressions” on page 110 for other rules for expression.
The ALL or DISTINCT keyword can only be specified for a column function or a
user-defined function that is sourced on a column function. The TABLE keyword ca
n
only be used in a trigger body.
 function-name

( )
ALL ,
DISTINCT
expression
TABLE transition-table-name

Functions
Chapter 2. Language elements 105
Each reference to a table function conforms to the following syntax:
In the above syntax, expression is the same as it is for a scalar or column func
tion.
For more details on referencing a table function, see the description of the FRO
M
clause on page 304, the only place where a table function can be referenced.
For a description of the built-in functions, see “Chapter 3. Built-in functions” on
page 153. DB2 Application Programming and SQL Guide contains detailed
information on creating and using user-defined functions. (See “Appendix G.
Sample user-defined functions” on page 1099 for descriptions of the sample
user-defined functions that are supplied with DB2).
Function resolution
A function is invoked by its function name, which is implicitly or explicitly qu
alified
with a schema name, followed by parentheses that enclose the arguments to the
function. Within the database, each function is uniquely identified by its funct
ion
signature, which is its schema name, function name, the number of parameters,
and the data types of the parameters. Thus, a schema can contain several
functions that have the same name but each of which have a different number of
parameters or parameters with different data types. Also, a function with the sa
me
name, number of parameters, and types of parameters can exist in multiple
schemas.
Because multiple functions with the same name can exist in the same schema or
different schemas, DB2 must determine which function to execute. The process of
choosing the function is called function resolution.
Function resolution is similar for functions that are invoked with a qualified o
r
unqualified function name with the exception that for an unqualified name, DB2
needs to search more than one schema.
Qualified function resolution: When a function is invoked with a schema name
and a function name, DB2 only searches the specified schema to resolve which
function to execute. DB2 finds the appropriate function instance when all of the
following conditions are true:
v The name of the function instance matches the name in the function invocation.
v The number of input parameters in the function instance matches the number of
function arguments in the function invocation.
v The invoker of the function is authorized to execute the function instance.
v The data type of each input argument of the function invocation matches or is
promotable to the data type of the corresponding parameter of the function
instance.
For a function invocation that passes a transition table, the data type, length,
precision, and scale of each column in the transition table must match exactly t
he
data type, length, precision, and scale of each column of the table that is name
d
in the function instance definition.


TABLE (function-name( ))
,
expression
TABLE transition-table-name
correlation-clause 
Functions
106 SQL Reference
If the function invocation contains no untyped parameter markers, the
comparison of data types results in one best fit, which is the choice for execut
ion
(see “Method of finding the best fit” on page 108). For information on the
promotion of data types, see “Promotion of data types” on page 61.
For a function invocation that contains untyped parameter markers, the data
types of those parameter markers are considered to match or be promotable to
the data types of the parameters in the function instance.
v The create timestamp for the function must be older than the bind timestamp fo
r
the package or plan in which the function is invoked.
If a function invoked from a trigger body receives a transition table, and the
invocation occurs during an automatic rebind, the form of the invoked function
used for function selection includes only the columns of the table that existed
at
the time of the original BIND or REBIND package or plan for the invoking
program.
If the function invocation contains untyped parameter markers, the comparison
can result in more than one best fit. In that case, DB2 returns an error.
If DB2 authorization checking is in effect, and DB2 performs an automatic rebind
on a plan or package that contains a user-defined function invocation, any
user-defined functions that were created after the original BIND or REBIND of th
e
invoking plan or package are not candidates for execution.
If you use an access control authorization exit routine, some user-defined
functions that were not candidates for execution before the original BIND or
REBIND of the invoking plan or package might become candidates for execution
during the automatic rebind of the invoking plan or package. See Appendix B
(Volume 2) of DB2 Administration Guide for information about function resolution
with access control authorization exit routines.
If no function in the schema meets these criteria, an error occurs. If a functio
n is
selected, its successful use depends on it being invoked in a context in which t
he
returned result is allowed. For example, if the function returns an integer data
type
where a character data type is required, or returns a table function where a tab
le
function is not allowed, an error occurs.
Unqualified function resolution: When a function is invoked with only a function
name and no schema name, DB2 needs to search more than one schema to
resolve the function instance to execute. DB2 uses these steps to choose the
function:
1. The SQL path contains the list of schemas to search. For each schema in the
path, DB2 selects a candidate function based on the same criteria described
immediately above for qualified function resolution. However, if no function in
the schema meets the criteria, an error does not occur, and a candidate function
is not selected for that schema.
2. After identifying the candidate functions for the schemas in the path, DB2
selects the candidate with the best fit as the function to execute. If more than
one schema contains the function instance with the best fit (the function
signatures are identical except for the schema name), DB2 selects the function
whose schema is earliest in the SQL path. If no function in any schema in the
SQL path meets the criteria, an error occurs.
The create timestamp of a user-defined function must be older than the timestamp
resulting from an explicit bind for the plan or package containing the function
invocation. During autobind, built-in functions introduced in a later DB2 releas
e than
the DB2 release that was used to explicitly bind the package or plan are not
considered for function resolution.
Functions
Chapter 2. Language elements 107
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For more information on user-defined functions, such as how you can simplify
function resolution or use the DSN_FUNCTION_TABLE to see how DB2 resolves a
function, see DB2 Application Programming and SQL Guide.
Method of finding the best fit
More than one function instance with the same name might be a candidate for
execution. In that case, DB2 compares the argument and parameter data types to
determine which function is the best fit for the invocation.
If the data types of all the parameters for a given function are the same as tho
se of
the arguments in the function invocation, that function is the best fit. If ther
e is no
exact match, DB2 compares the data types in the parameter lists from left to rig
ht,
using this method:
1. DB2 compares the data types of the first argument in the function invocation
to
the data type of the first parameter in each function. Any length, precision,
scale, subtype, and encoding scheme attributes of the data types are not
considered in the comparison.
2. For this argument, if one function has a data type that fits the function
invocation better than the data types in the other functions, that function is t
he
best fit. The precedence list for the promotion of data types in Table 6 on
page 62 shows the data types that fit each data type, in best-to-worst order.
3. If the data types of the first parameter for all the candidate functions fit
the
function invocation equally well, DB2 repeats this process for the next argument
of the function invocation. DB2 continues this process for each argument until a
best fit is found.
Examples of function resolution: The following examples illustrate function
resolution.
Example 1: Assume that MYSCHEMA contains two functions, both named FUNA,
that were registered with these partial CREATE FUNCTION statements.
1. CREATE FUNCTION MYSCHEMA.FUNA (VARCHAR(10), INT, DOUBLE) ...
2. CREATE FUNCTION MYSCHEMA.FUNA (VARCHAR(10), REAL, DOUBLE) ...
Also assume that a function with three arguments of data types VARCHAR(10),
SMALLINT, and DECIMAL is invoked with a qualified name:
MYSCHEMA.FUNA(VARCHARCOL, SMALLINTCOL, DECIMALCOL)
The data types of the first parameter for the two function instances in the sche
ma,
which are both VARCHAR(10), fit the data type of the first argument of the funct
ion
invocation, which is VARCHAR(10), equally well. However, for the second
parameter, the data type of the first function (INT) fits the data type of the s
econd
argument (SMALLINT) better than the data type of second function (REAL).
Therefore, DB2 selects Function 1 as the function instance to execute.
Example 2: Assume that these functions were registered with these partial CREATE
FUNCTION statements:
1. CREATE FUNCTION SMITH.ADDIT (CHAR(5), INT, DOUBLE) ...
2. CREATE FUNCTION SMITH.ADDIT (INT, INT, DOUBLE) ...
3. CREATE FUNCTION SMITH.ADDIT (INT, INT, DOUBLE, INT) ...
4. CREATE FUNCTION JOHNSON.ADDIT (INT, DOUBLE, DOUBLE) ...
5. CREATE FUNCTION JOHNSON.ADDIT (INT, INT, DOUBLE) ...
6. CREATE FUNCTION TODD.ADDIT (REAL) ...
7. CREATE FUNCTION TAYLOR.SUBIT (INT, INT, DECIMAL) ...
Functions
108 SQL Reference
Also assume that the SQL path at the time an application invokes a function is
″TAYLOR″ ″JOHNSON″, ″SMITH″. The function is invoked with three data types
(INT, INT, DECIMAL) as follows:
SELECT ... ADDIT(INTCOL1, INTCOL2, DECIMALCOL) ...
Function 5 is chosen as the function instance to execute based on the following
evaluation:
v Function 6 is eliminated as a candidate because schema TODD is not in the SQL
path.
v Function 7 in schema TAYLOR is eliminated as a candidate because it does not
have the correct function name.
v Both Function 4 and 5 in schema JOHNSON are candidates because the data
types of their parameters match or are promotable to the data types of the
arguments. However, Function 5 is chosen as the better candidate because
although the data types of the first parameter of both functions (INT) match the
first argument (INT), the data type of the second parameter of Function 5 (INT)
is
a better match of the second argument (INT) than Function 4 (DOUBLE).
v Function 1 and 3 in schema SMITH are eliminated as candidates. The CHAR
data type of the first parameter of Function 1 is not promotable to INT. Functio
n 3
has the wrong number of parameters. Function 2 is a candidate because the
data types of its parameters match or are promotable to the data types of the
arguments.
v Of the remaining candidates, Function 2 and 5, DB2 selects Function 5 because
schema JOHNSON comes before schema SMITH in the SQL path.
SQL path considerations for built-in functions
Function resolution applies to all functions, including built-in functions. The
built-in
functions are in schema SYSIBM. If a built-in function is invoked without its sc
hema
name, the SQL path is searched. If SYSIBM is not first in the path, it is possib
le
that DB2 will select another function instead of the intended function. If schem
a
SYSIBM or SYSPROC is not explicitly specified in the SQL path, the schema is
implicitly assumed at the front of the path. DB2 adds implicitly assumed schemas
in
the order of SYSIBM and SYSPROC. See “Schemas and the SQL path” on page 40
for information on how to specify the path so that the intended function is sele
cted
when it is invoked with an unqualified name.
Function invocation
Once the function is selected, there are still possible reasons why the use of t
he
function may not be permitted. Each function is defined to return a result with
a
specific data type. If this result data type is not compatible with the context
in which
the function is invoked, an error occurs. For example, assume functions named
STEP are defined with different data types:
STEP(SMALLINT)returns CHAR(5)
STEP(DOUBLE)returns INTEGER
Assume also that the function is invoked with the following function reference
(where S is a SMALLINT column):
SELECT ... 3+STEP(S) ...
Because there is an exact match on argument type, the first STEP is chosen. An
error occurs on the statement because the result type is CHAR(5) instead of a
numeric type as required for an argument of the addition operator.
An error also occurs in the following examples:
Functions
Chapter 2. Language elements 109
|
|
|
|
|
|
||
|
|
|
|
|
|
|
v The function is referenced in a FROM clause, but the function selected by the
function resolution step is a scalar or column function.
v The function calls for a scalar or column function, but the function resolutio
n step
is a table function.
In cases where the arguments of the function invocation are not an exact match t
o
the data types of the parameters of the selected function, the arguments are
converted to the data type of the parameter at execution using the same rules as
assignment to columns. See “Assignment and comparison” on page 64. Problems
with conversions can also occur when precision, scale, length, or the encoding
scheme differs between the argument and the parameter. Conversion might occur
for a character string argument when the corresponding parameter of the function
has a different encoding scheme or CCSID. For example, an error occurs on
function invocation when mixed data that actually contains DBCS characters is
specified as an argument and the corresponding parameter of the function is
declared with an SBCS subtype.
Additionally, a character FOR BIT DATA argument cannot be passed as input for a
parameter that is not defined as character FOR BIT DATA. Likewise, a character
argument that is not FOR BIT DATA cannot be passed as input for a parameter that
is defined as character FOR BIT DATA.
Expressions
An expression specifies a value. The form of an expression is as follows:
Functions
110 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Without operators
If no operators are used, the result of the expression is the specified value.
Examples:
SALARY :SALARY SALARY MAX(SALARY)
With the concatenation operator
Both CONCAT and the vertical bars (||) represent the concatenation operator.
Vertical bars (or the characters that must be used in place of vertical bars in
some
countries14) can cause parsing errors in statements passed from one DBMS to
another. The problem occurs if the statement undergoes character conversion with
certain combinations of source and target CCSIDs14. Thus, CONCAT is the
preferable concatenation operator.
When two strings operands are concatenated, the result of the expression is a
string. The operands of concatenation must be compatible strings. A binary strin
g
14. DB2 supports code point combinations X 4F4F , X BBBB , and X 5A5A to mean c
oncatenation. X BBBB and X 5A5A are
interpreted to mean concatenation only on single byte character set DB2 subsyste
ms.
 
operator
(1)
function
+ (expression)
- constant
column-name
host-variable
special-register
(2)
labeled-duration
(3)
case-expression
(4)
cast-specification

Notes:
1 Includes all functions except table functions. See “Functions” on page 104 for mor
e information.
2 See “Labeled durations” on page 117 for more information.
3 See “CASE expressions” on page 123 for more information.
4 See “CAST specification” on page 125 for more information.
operator:
 CONCAT
||
/
*
+
-

Expressions
Chapter 2. Language elements 111
cannot be concatenated with a character string, including character strings that
are
defined as FOR BIT DATA (for more information on the compatibility of data types
,
see the compatibility matrix in Table 9 on page 65). A distinct type that is sou
rced on
a string type can be concatenated only if an appropriate user-defined function i
s
created, as explained at the end of this section.
If either operand can be null, the result can be null, and if either is null, th
e result is
the null value. Otherwise, the result consists of the first operand string follo
wed by
the second.
Table 20 shows how the string operands determine the data type and the length
attribute of the result (the order in which the operands are concatenated has no
effect on the result).
Table 20. Data type and length of concatenated operands
One
operand
Other
operand
Combined
length
attribute Result1
CHAR(A) CHAR(B) <256 CHAR(A+B)2
CHAR(B) >255 VARCHAR(A+B)
VARCHAR(B) - VARCHAR(A+B)
VARCHAR(A) VARCHAR(B) - VARCHAR(A+B)
CLOB(A) CHAR(B) - CLOB(MIN(A+B, 2G))
VARCHAR(B) - CLOB(MIN(A+B, 2G))
CLOB(B) - CLOB(MIN(A+B, 2G))
GRAPHIC(A) UTF-16
UNICODE DATA4
CHAR(B) - VARGRAPHIC(A+B) 3
VARCHAR(B) - VARGRAPHIC(A+B) 3
VARGRAPHIC(A)
UTF-16 UNICODE
DATA4
CHAR(B) - VARGRAPHIC(A+B) 3
VARCHAR(B) - VARGRAPHIC(A+B) 3
DBCLOB(A) GRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
VARGRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
DBCLOB(B) - DBCLOB(MIN(A+B, 1G))
BLOB(A) BLOB(B) - BLOB(MIN(A+B, 2G))
Notes:
1. 2G represents 2 147 483 647 bytes
1G represents 1 073 741 823 double-byte characters
2. Neither CHAR(A) nor CHAR(B) must contain mixed data. If either operand contai
ns
mixed data, the result is VARCHAR(A+B).
3. CHAR(B) or VARCHAR(B) is converted to UTF-16 and the result is concatenated t
o
GRAPHIC(A) or VARGRAHPIC(A)
4. UTF-16 data is the only graphic data that can be used with a character operan
d..
As Table 20 shows, the length of the result is the sum of the lengths of the
operands. However, the length of the result is two bytes less if redundant shift
code
characters are eliminated from the result. Redundant shift code characters exist
when both character strings are EBCDIC mixed data, and the first string ends wit
h
a “shift-in” character (X 0F ) and the second operand begins with a “shift-out”
character (X 0E ). These two shift code characters are removed from the result.
Expressions
112 SQL Reference
||
|
The CCSID of the result is determined by the rules set forth in “Character
conversion in unions and concatenations” on page 318. Some consequences of
those rules are the following:
v If either operand is BIT data, the result is BIT data.
v The conversion that occurs when SBCS data is compared with mixed data
depends on the encoding scheme. If the encoding scheme is Unicode, the SBCS
operand is converted to MIXED. Otherwise, the conversion depends on the field
MIXED DATA on installation panel DSNTIPF for the DB2 that does the
comparison:
– Mixed data if the MIXED DATA option at the server is YES15
– SBCS data if the MIXED DATA option at the server is NO.16
If an operand is a string from a column with a field procedure, the operation ap
plies
to the decoded form of the value. The result does not inherit the field procedur
e.
One operand of concatenation can be a parameter marker. When one operand is a
parameter marker, its data type and length attributes are considered to be the s
ame
as those for the operand that is not a parameter marker. The order of concatenat
ion
operations must be considered to determine these attributes in the case of neste
d
concatenation.
No operand of concatenation can be a distinct type even if the distinct type is
sourced on a character data type. To concatenate a distinct type, create a
user-defined function that is sourced on the CONCAT operator. For example, if
distinct types TITLE and TITLE_DESCRIPTION were both sourced on data type
VARCHAR(25), the following user-defined function, named ATTACH, could be used
to concatenate the two distinct types:
CREATE FUNCTION ATTACH (TITLE, TITLE_DESCRIPTION)
RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())
Alternatively, the concatenation operator could be overloaded by using a
user-defined function to add the distinct types:
CREATE FUNCTION "||" (TITLE, TITLE_DESCRIPTION)
RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())
With arithmetic operators
If arithmetic operators are used, the result of the expression is a number deriv
ed
from the application of the operators to the values of the operands. The result
of the
expression can be null. If any operand has the null value, the result of the
expression is the null value. Arithmetic operators (except unary plus, which is
meaningless) must not be applied to strings. For example, USER+2 is invalid.
Multiplication and division operators must not be applied to datetime values, wh
ich
can only be added and subtracted.
The prefix operator + (unary plus) does not change its operand. The prefix opera
tor
- (unary minus) reverses the sign of a nonzero operand. If the data type of A is
small integer, the data type of -A is large integer. The first character of the
token
following a prefix operator must not be a plus or minus sign.
The infix operators +, -, *, and / specify addition, subtraction, multiplication
, and
division, respectively. The value of the second operand of division must not be
zero.
15. The result is not necessarily well-formed mixed data.
16. If the mixed data cannot be converted to pure SBCS data, an error occurs.
Expressions
Chapter 2. Language elements 113
|
|
|
|
|
|
|
Arithmetic with two integer operands
If both operands of an arithmetic operator are integers, the operation is perfor
med
in binary and the result is a large integer. Any remainder of division is lost.
The
result of an integer arithmetic operation (including unary minus) must be within
the
range of large integers.
Arithmetic with an integer and a decimal operand
If one operand is an integer and the other is decimal, the operation is performe
d in
decimal using a temporary copy of the integer that has been converted to a decim
al
number with zero scale and precision as defined in the following table:
Operand Precision of decimal copy
Column or variable: large integer 11
Column or variable: small integer 5
Constant: more than five digits (including
leading zeros)
Same as the number of digits in the constant
Constant: five digits or fewer 5
Arithmetic with two decimal operands
If both operands are decimal, the operation is performed in decimal. The result
of
any decimal arithmetic operation is a decimal number with a precision and scale
that depend on two factors:
The precision and scale of the operands
In the discussion of operations with two decimal operands, the precision
and scale of the first operand are denoted by p and s, that of the second
operand by p and s . Thus, for a division, the dividend has precision p and
scale s, and the divisor has precision p and scale s .
Whether DEC31 or DEC15 is in effect for the operation
DEC31 and DEC15 specify the rules to be used when both operands in a
decimal operation have precisions of 15 or less. DEC15 specifies the rules
which do not allow a precision greater than 15 digits, and DEC31 specifies
the rules which allow a precision of up to 31 digits. The rules for DEC31 are
always used if either operand has a precision greater than 15.
For static SQL statements, the value of the field DECIMAL ARITHMETIC on
installation panel DSNTIP4 or the precompiler option DEC determines whether
DEC15 or DEC31 is used.
For dynamic SQL statements, the value of the field DECIMAL ARITHMETIC on
installation panel DSNTIP4, the precompiler option DEC, or the special register
CURRENT PRECISION determines whether DEC15 or DEC31 is used according to
these rules:
v Field DECIMAL ARITHMETIC applies if either of these conditions is true:
– DYNAMICRULES run behavior applies and the application has not set
CURRENT PRECISION.
For a list of the DYNAMICRULES bind option values that specify run, bind,
define, or invoke behavior, see Table 2 on page 44.
– DYNAMICRULES bind, define, or invoke behavior applies; the value of
installation panel field USE FOR DYNAMICRULES is YES; and the
application has not set CURRENT PRECISION.
Expressions
114 SQL Reference
v Precompiler option DEC applies if DYNAMICRULES bind, define, or invoke
behavior is in effect, the value of installation panel field USE FOR
DYNAMICRULES is NO, and the application has not set CURRENT PRECISION.
v Special register CURRENT PRECISION applies if the application sets the
register.
The value of DECIMAL ARITHMETIC is the default value for the precompiler option
and the special register. SQL statements executed using SPUFI use the value in
DECIMAL ARITHMETIC.
Decimal addition and subtraction
If the operation is addition or subtraction and the operands do not have the sam
e
scale, the operation is performed with a temporary copy of one of the operands t
hat
has been extended with trailing zeros so that its fractional part has the same
number of digits as the other operand.
The precision of the result is the minimum of n and the quantity
MAX(p-s,p -s )+MAX(s,s )+1. The scale is MAX(s,s ). n is 31 if DEC31 is in effec
t or
if the precision of at least one operand is greater than 15. Otherwise, n is 15.
Decimal multiplication
For multiplication, the precision of the result is MIN(n,p+p ), and the scale is
MIN(n,s+s ). n is 31 if DEC31 is in effect or if the precision of at least one o
perand
is greater than 15. Otherwise, n is 15.
If both operands have a precision greater than 15, the operation is performed us
ing
a temporary copy of the operand with the smaller precision. If the operands have
the same precision, the second operand is selected. If more than 15 significant
digits are needed for the integral part of the copy, the statement’s execution is
ended and an error occurs. Otherwise, the copy is converted to a number with
precision 15, by truncating the copy on the right. The truncated copy has a scal
e of
MAX(0,S-(P-15)), where P and S are the original precision and scale. If, in the
process of truncation, one or more nonzero digits are removed, SQLWARN7 in
SQLCA is set to W, indicating loss of precision.
When both operands have a precision greater than 15, the foregoing formulas for
the precision and scale of the result still apply, with one change: for the oper
and
selected as the copy, use the precision and scale of the truncated copy; that is
, use
15 as the precision and MAX(0,S-(P-15)) for the scale.
Let n denote the value of the operand with the greater precision or the first op
erand
in the case of operands with the same precision. The number of leading zeros in
a
31-digit representation of n must be greater than the precision of the other ope
rand.
This is always the case if the precision of the operand is 15 or less. With grea
ter
precisions, overflow can occur even if the precision of the result is less than
31. For
example, the expression:
10000000000000000000000000. * 1
will cause overflow because the number of leading zeros in the 31-digit
representation of the large number and the precision of the small number are bot
h
5 (see “Arithmetic with an integer and a decimal operand” on page 114).
Decimal division
The rules for a specific decimal division depend on three factors:
v Whether the DEC31 option is in effect for the operation
v Whether p is greater than 15
Expressions
Chapter 2. Language elements 115
v Whether p is greater than 15
The following table shows how the precision and scale of the result depend on
these factors. In that table, the occurrence of “N/A” in a row implies that the
indicated factor is not relevant to the case represented by the row.
Table 21. Precision (p) and scale (s) of the result of a decimal division
DEC31 p p P S
Not in effect ≤15 ≤15 15 15-(p-s+s )
In effect ≤15 ≤15 31 N-(p-s+s ), where
N is 30-p if p is odd.
N is 29-p if p is even.
N/A >15 ≤15 31 N-(p-s+s ), where
N is 30-p if p is odd.
N is 29-p if p is even.
N/A N/A >15 31 15-(p-s+x), where
x is MAX(0,s -(p -15))
(See Note 2 below)
Notes on decimal division:
1. If the calculated value of S is negative, an error occurs.
2. If p is greater than 15, the division is performed using a temporary copy of
the
divisor. If more than 15 significant digits are needed for the integral part of
the
divisor, the statement’s execution is ended, and an error occurs. Otherwise, the
copy is converted to a number with precision 15, by truncating the copy on the
right. The truncated copy has a scale of MAX(0,s -(p -15)), which is the formula
for x that appears in row 4 of Table 21. If, in the process of truncation, one o
r
more nonzero digits are removed, SQLWARN7 in SQLCA is set to W, indicating
loss of precision.
3. A value of YES for field MINIMUM DIVIDE SCALE on installation panel
DSNTIPF specifies that the scale of the result of a decimal division is never le
ss
than 3. To this end, the precision and scale of the result are first calculated
using the rules shown in Table 21. The actual scale is then the calculated scale
or 3, whichever is greater. The actual precision is the calculated precision.
Arithmetic with floating-point operands
If either operand of an arithmetic operator is floating-point, the operation is
performed in floating-point. If necessary, the operands are first converted to d
ouble
precision floating-point numbers. Thus, if any element of an expression is a
floating-point number, the result of the expression is a double precision
floating-point number.
An operation involving a floating-point number and an integer is performed with
a
temporary copy of the integer that has been converted to double precision
floating-point. An operation involving a floating-point number and a decimal num
ber
is performed with a temporary copy of the decimal number that has been converted
to double precision floating-point. The result of a floating-point operation mus
t be
within the range of floating-point numbers.
Expressions
116 SQL Reference
Datetime operands and durations
Datetime values can be incremented, decremented, and subtracted. These
operations may involve decimal numbers called durations. A duration is a number
representing an interval of time. There are four types of durations:
Labeled durations
The form a labeled duration is as follows:
A labeled duration represents a specific unit of time as expressed by a
number (which can be the result of an expression) followed by one of the
seven duration keywords:17 YEARS, MONTHS, DAYS, HOURS, MINUTES,
SECONDS, or MICROSECONDS. The number specified is converted as if it
were assigned to a DECIMAL(15,0) number.
A labeled duration can only be used as an operand of an arithmetic
operator, and the other operand must have a data type of DATE, TIME, or
TIMESTAMP. Thus, the expression HIREDATE + 2 MONTHS + 14 DAYS is
valid, whereas the expression HIREDATE + (2 MONTHS + 14 DAYS) is not.
In both of these expressions, the labeled durations are 2 MONTHS and 14
DAYS.
Date duration
A date duration represents a number of years, months, and days expressed
as a DECIMAL(8,0) number. To be properly interpreted, the number must
have the format yyyymmdd, where yyyy represents the number of years,
mm the number of months, and dd the number of days. The result of
subtracting one DATE value from another, as in the expression HIREDATE -
BIRTHDATE, is a date duration.
Time duration
A time duration represents a number of hours, minutes, and seconds
expressed as a DECIMAL(6,0) number. To be properly interpreted, the
number must have the format hhmmss, where hh represents the number of
hours, mm the number of minutes, and ss the number of seconds. The
result of subtracting one TIME value from another is a time duration.
17. The singular form of these keywords is also acceptable: YEAR, MONTH, DAY, HO
UR, MINUTE, SECOND, and MICROSECOND.

(1)
function
(expression)
constant
column-name
host-variable
YEAR
YEARS
MONTH
MONTHS
DAY
DAYS
HOUR
HOURS
MINUTE
MINUTES
SECOND
SECONDS
MICROSECOND
MICROSECONDS

Notes:
1 Includes all functions except table functions.
Expressions
Chapter 2. Language elements 117
Timestamp duration
A timestamp duration represents a number of years, months, days, hours,
minutes, seconds, and microseconds expressed as a DECIMAL(20,6)
number. To be properly interpreted, the number must have the format
yyyyxxddhhmmsszzzzzz, where yyyy, xx, dd, hh, mm, ss and zzzzzz
represent, respectively, the number of years, months, days, hours, minutes,
seconds, and microseconds. The result of subtracting one TIMESTAMP
value from another is a timestamp duration.
Datetime arithmetic in SQL
The only arithmetic operations that can be performed on datetime values are
addition and subtraction. If a datetime value is the operand of addition, the ot
her
operand must be a duration. The specific rules governing the use of the addition
operator with datetime values follow.
v If one operand is a date, the other operand must be a date duration or labeled
duration of years, months, or days.
v If one operand is a time, the other operand must be a time duration or a label
ed
duration of hours, minutes, or seconds.
v If one operand is a timestamp, the other operand must be a duration. Any type
of
duration is valid.
v Neither operand of the addition operator can be a parameter marker. For a
discussion of parameter markers, see Parameter markers in “PREPARE” on
page 792 .
The rules for the use of the subtraction operator on datetime values are not the
same as those for addition because a datetime value cannot be subtracted from a
duration, and because the operation of subtracting two datetime values is not th
e
same as the operation of subtracting a duration from a datetime value. The speci
fic
rules governing the use of the subtraction operator with datetime values follow.
v If the first operand is a date, the second operand must be a date, a date
duration, a string representation of a date, or a labeled duration of years, mon
ths,
or days.
v If the second operand is a date, the first operand must be a date, or a string
representation of a date.
v If the first operand is a time, the second operand must be a time, a time dura
tion,
a string representation of a time, or a labeled duration of hours, minutes, or
seconds.
v If the second operand is a time, the first operand must be a time, or string
representation of a time.
v If the first operand is a timestamp, the second operand must be a timestamp, a
string representation of a timestamp, or a duration.
v If the second operand is a timestamp, the first operand must be a timestamp or
a
string representation of a timestamp.
v Neither operand of the subtraction operator can be a parameter marker.
When an operand in a datetime expression is a string, it may undergo character
conversion before it is interpreted and converted to a datetime value. When its
CCSID is not that of the default for mixed strings, a mixed string is converted
to the
default mixed data representation. When its CCSID is not that of the default for
SBCS strings, an SBCS string is converted to the default SBCS representation.
Date arithmetic
Dates can be subtracted, incremented, or decremented.
Expressions
118 SQL Reference
Subtracting dates: The result of subtracting one date (DATE2) from another
(DATE1) is a date duration that specifies the number of years, months, and days
between the two dates. The data type of the result is DECIMAL(8,0). If DATE1 is
greater than or equal to DATE2, DATE2 is subtracted from DATE1. If DATE1 is less
than DATE2, however, DATE1 is subtracted from DATE2, and the sign of the result
is made negative. The following procedural description clarifies the steps invol
ved in
the operation RESULT = DATE1 - DATE2.
Date subtraction: result = date1 - date2
v If DAY(DATE2) <= DAY(DATE1)
then DAY(RESULT) = DAY(DATE1) - DAY(DATE2).
v If DAY(DATE2) > DAY(DATE1)
then DAY(RESULT) = N + DAY(DATE1) - DAY(DATE2)
where N = the last day of MONTH(DATE2).
MONTH(DATE2) is then incremented by 1.
v If MONTH(DATE2) <= MONTH(DATE1)
then MONTH(RESULT) = MONTH(DATE1) - MONTH(DATE2).
v If MONTH(DATE2) > MONTH(DATE1)
then MONTH(RESULT) = 12 + MONTH(DATE1) - MONTH(DATE2)
and YEAR(DATE2) is incremented by 1.
v YEAR(RESULT) = YEAR(DATE1) - YEAR(DATE2).
For example, the result of DATE( 3/15/2000 ) - 12/31/1999 is 215 (or, a durati
on of
0 years, 2 months, and 15 days). In this example, notice that the second operand
did not need to be converted to a date. According to one of the rules for
subtraction, described under “Datetime arithmetic in SQL” on page 118, the second
operand can be a string representation of a date if the first operand is a date.
Incrementing and decrementing dates: The result of adding a duration to a date,
or of subtracting a duration from a date, is itself a date. (For the purposes of
this
operation, a month denotes the equivalent of a calendar page. Adding months to a
date, then, is like turning the pages of a calendar, starting with the page on w
hich
the date appears.) The result must fall between the dates January 1, 0001 and
December 31, 9999 inclusive. If a duration of years is added or subtracted, only
the
year portion of the date is affected. The month is unchanged, as is the day unle
ss
the result would be February 29 of a non-leap-year. Here the day portion of the
result is set to 28, and the SQLWARN6 field of the SQLCA is set to W, indicating
that an end-of-month adjustment was made to correct an invalid date. Part 2 of D
B2
Application Programming and SQL Guide also describes how SQLWARN6 is set.
Similarly, if a duration of months is added or subtracted, only months and, if
necessary, years are affected. The day portion of the date is unchanged unless t
he
result would be invalid (September 31, for example). In this case the day is set
to
the last day of the month, and the SQLWARN6 field of the SQLCA is set to W to
indicate the adjustment.
Adding or subtracting a duration of days will, of course, affect the day portion
of the
date, and potentially the month and year.
Expressions
Chapter 2. Language elements 119
Date durations, whether positive or negative, can also be added to and subtracte
d
from dates. As with labeled durations, the result is a valid date, and SQLWARN6
is
set to W to indicate any necessary end-of-month adjustment.
When a positive date duration is added to a date, or a negative date duration is
subtracted from a date, the date is incremented by the specified number of years
,
months, and days, in that order. Thus, DATE1+X, where X is a positive
DECIMAL(8,0) number, is equivalent to the expression:
DATE1+ YEAR(X) YEARS + MONTH(X) MONTHS + DAY(X) DAYS
When a positive date duration is subtracted from a date, or a negative date dura
tion
is added to a date, the date is decremented by the specified number of days,
months, and years, in that order. Thus, DATE1-X, where X is a positive
DECIMAL(8,0) number, is equivalent to the expression:
DATE1- DAY(X) DAYS - MONTH(X) MONTHS - YEAR(X) YEARS
Adding a month to a date gives the same day one month later unless that day does
not exist in the later month. In that case, the day in the result is set to the
last day
of the later month. For example, January 28 plus one month gives February 28; on
e
month added to January 29, 30, or 31 results in either February 28 or, for a lea
p
year, February 29. If one or more months is added to a given date and then the
same number of months is subtracted from the result, the final date is not
necessarily the same as the original date.
The order in which labeled date durations are added to and subtracted from dates
can affect the results. When you add labeled date durations to a date, specify t
hem
in the order of YEARS + MONTHS + DAYS. When you subtract labeled date
durations from a date, specify them in the order of DAYS - MONTHS - YEARS. For
example, to add one year and one day to a date, specify:
DATE1+ 1YEAR + 1DAY
To subtract one year, one month, and one day from a date, specify:
DATE1- 1DAY - 1MONTH - 1YEAR
Time arithmetic
Times can be subtracted, incremented, or decremented.
Subtracting times: The result of subtracting one time (TIME2) from another
(TIME1) is a time duration that specifies the number of hours, minutes, and
seconds between the two times. The data type of the result is DECIMAL(6,0). If
TIME1 is greater than or equal to TIME2, TIME2 is subtracted from TIME1. If
TIME1 is less than TIME2, however, TIME1 is subtracted from TIME2, and the sign
of the result is made negative. The following procedural description clarifies t
he
steps involved in the operation RESULT = TIME1 - TIME2.
Expressions
120 SQL Reference
Time subtraction: result = time1 - time2
v If SECOND(TIME2) <= SECOND(TIME1)
then SECOND(RESULT) = SECOND(TIME1) - SECOND(TIME2).
v If SECOND(TIME2) > SECOND(TIME1)
then SECOND(RESULT) = 60 + SECOND(TIME1) - SECOND(TIME2)
and MINUTE(TIME2) is incremented by 1.
v If MINUTE(TIME2) <= MINUTE(TIME1)
then MINUTE(RESULT) = MINUTE(TIME1) - MINUTE(TIME2).
v If MINUTE(TIME2) > MINUTE(TIME1)
then MINUTE(RESULT) = 60 + MINUTE(TIME1) - MINUTE(TIME2)
and HOUR(TIME2) is incremented by 1.
v HOUR(RESULT) = HOUR(TIME1) - HOUR(TIME2).
For example, the result of TIME( 11:02:26 ) - 00:32:56 is 102930 (a duration o
f 10
hours, 29 minutes, and 30 seconds). In this example, notice that the second
operand did not need to be converted to a time. According to one of the rules fo
r
subtraction, described under “Datetime arithmetic in SQL” on page 118, the second
operand can be a string representation of a time if the first operand is a time.
Incrementing and decrementing times: The result of adding a duration to a time,
or of subtracting a duration from a time, is itself a time. Any overflow or unde
rflow of
hours is discarded, thereby ensuring that the result is always a time. If a dura
tion of
hours is added or subtracted, only the hours portion of the time is affected. Ad
ding
24 hours to the time 00:00:00 results in the time 24:00:00 . However, adding
24
hours to any other time results in the same time; for example, adding 24 hours t
o
the time 00:00:59 results in the time 00:00:59 . The minutes and seconds are
unchanged.
Similarly, if a duration of minutes is added or subtracted, only minutes and, if
necessary, hours are affected. The seconds portion of the time is unchanged.
Adding or subtracting a duration of seconds affects the seconds portion of the t
ime
and may affect the minutes and hours.
Time durations, whether positive or negative, can also be added to and subtracte
d
from times. The result is a time that has been incremented or decremented by the
specified number of hours, minutes, and seconds, in that order. Thus, TIME1 + X,
where X is a positive DECIMAL(6,0) number, is equivalent to the expression
TIME1+ HOUR(X) HOURS + MINUTE(X) MINUTES + SECOND(X) SECONDS
Timestamp arithmetic
Timestamps can be subtracted, incremented, or decremented.
Subtracting timestamps: The result of subtracting one timestamp (TS2) from
another (TS1) is a timestamp duration that specifies the number of years, months
,
days, hours, minutes, seconds, and microseconds between the two timestamps.
The data type of the result is DECIMAL(20,6). If TS1 is greater than or equal to
TS2, TS2 is subtracted from TS1. If TS1 is less than TS2, however, TS1 is
Expressions
Chapter 2. Language elements 121
subtracted from TS2 and the sign of the result is made negative. The following
procedural description clarifies the steps involved in the operation RESULT = TS
1 -
TS2.
Timestamp subtraction: result = ts1 - ts2
v If MICROSECOND(TS2) <=
MICROSECOND(TS1)
then MICROSECOND(RESULT) = MICROSECOND(TS1) - MICROSECOND(TS2).
v If MICROSECOND(TS2) > MICROSECOND(TS1)
then MICROSECOND(RESULT) = 1000000 + MICROSECOND(TS1)
- MICROSECOND(TS2)
and SECOND(TS2) is incremented by 1.
v The seconds and minutes part of the timestamps are subtracted as
specified in the rules for subtracting times.
v If HOUR(TS2) <= HOUR(TS1)
then HOUR(RESULT) = HOUR(TS1) - HOUR(TS2).
v If HOUR(TS2) > HOUR(TS1)
then HOUR(RESULT) = 24 + HOUR(TS1) - HOUR(TS2)
and DAY(TS2) is incremented by 1.
v The date part of the timestamps is subtracted as specified in the
rules for subtracting dates.
Incrementing and decrementing timestamps: The result of adding a duration to a
timestamp, or of subtracting a duration from a timestamp, is itself a timestamp.
Date
and time arithmetic is performed as previously defined, except that an overflow
or
underflow of hours is carried into the date part of the result, which must be wi
thin
the range of valid dates. When the result of an operation is midnight, the time
portion of the result can be 24.00.00 or 00.00.00 ; a comparison of those two
values does not result in equal .
Precedence of operations
Expressions within parentheses are evaluated first. When the order of evaluation
is
not specified by parentheses, prefix operators are applied before multiplication
and
division, and multiplication, division, and concatenation are applied before add
ition
and subtraction. Operators at the same precedence level are applied from left to
right.
Example 1:
1.10 * (SALARY + BONUS) + SALARY / :VAR3
(2) (1) (4) (3)
Example 2: In this example, the first operation (CONCAT) combines the character
strings in the variables YYYYMM and DD into a string representing a date. The
second operation (-) then subtracts that date from the date being processed in
DATECOL. The result is a date duration that indicates the time elapsed between t
he
two dates.
Expressions
122 SQL Reference
DATECOL - :YYYYMM CONCAT :DD
(2) (1)
CASE expressions
A CASE expression allows an expression to be selected based on the evaluation of
one or more conditions. In general, the value of the case-expression is the valu
e of
the result-expression following the first (leftmost) case that evaluates to true
. If no
case evaluates to true and the ELSE keyword is present, the result is the value
of
the result-expression or NULL. If no case evaluates to true and the ELSE keyword
is not present, the result is NULL. When a case evaluates to unknown (because of
NULLs), the case is NOT true and hence is treated the same way as a case that
evaluates to false.
CASE
Begins a case-expression.
searched-when-clause
Specifies a search-condition that is applied to each row or group of table data
presented for evaluation, and the result when that condition is true.
simple-when-clause
Specifies that the value of the expression prior to the first WHEN keyword is
tested for equality with the value of each expression that follows the WHEN
keyword. It also specifies the result for when that condition is true.
The data type of the expression prior to the first WHEN keyword must be
comparable to the data types of each expression that follows the WHEN
keywords. The data type of any of the expressions cannot be a CLOB,
DBCLOB or BLOB. In addition, the expression prior to the first WHEN keyword
cannot include a user-defined function that is nondeterministic or has an
external action.
 CASE searched-when-clause
simple-when-clause
ELSE NULL
ELSE result-expression
END 
searched-when-clause:
  WHEN search-condition THEN result-expression
NULL

simple-when-clause:
 expression  WHEN expression THEN result-expression
NULL

Expressions
Chapter 2. Language elements 123
result-expression
Specifies an expression that follows the THEN and ELSE keyword. It specifies
the result of a searched-when-clause or a simple-when-clause that is true, or
the result if no case is true. There must be at least one result-expression in t
he
CASE expression with a defined data type. NULL cannot be specified for every
case.
All result-expressions must be compatible. The attributes of the result are
determined according to the rules that are described in “Rules for result data
types” on page 77. When the result is a string, its attributes include a CCSID.
For the rules on how the CCSID is determined, see “System CCSIDs” on
page 23.
search-condition
Specifies a condition that is true, false, or unknown about a row or group of
table data. The search-condition cannot contain a subselect. If the CASE
expression is in a select list or an IN predicate, the search-condition cannot b
e
a quantified predicate, an IN predicate, or an EXISTS predicate.
END
Ends a case-expression.
Example 1 (simple-when-clause): Assume that in the EMPLOYEE table the first
character of a department number represents the division in the organization. Us
e a
CASE expression to list the full name of the division to which each employee
belongs.
SELECT EMPNO, LASTNAME,
CASE SUBSTR(WORKDEPT,1,1)
WHEN A THEN Administration
WHEN B THEN Human Resources
WHEN C THEN Design
WHEN D THEN Operations
END
FROM EMPLOYEE;
Example 2 (searched-when-clause): You can also use a CASE expression to avoid
“division by zero” errors. From the EMPLOYEE table, find all employees who earn
more than 25 percent of their income from commission, but who are not fully paid
on commission:
SELECT EMPNO, WORKDEPT, SALARY+COMM FROM EMPLOYEE
WHERE (CASE WHEN SALARY=0 THEN 0
ELSE COMM/(SALARY+COMM)
END) > 0.25;
Example 3 (searched-when-clause): You can use a CASE expression to avoid
″division by zero″ errors in another way. The following queries show an
accumulation or summing operation. In the first query, DB2 performs the division
before performing the CASE statement and an error occurs along with the results.
SELECT REF_ID,PAYMT_PAST_DUE_CT,
CASE
WHEN PAYMT_PAST_DUE_CT=0 THEN 0
WHEN PAYMT_PAST_DUE_CT>0 THEN 1
END
FROM PAY_TABLE
GROUP BY REF_ID,PAYMT_PAST_DUE_CT;
However, if the CASE expression is included in the SUM column function, the
CASE expression would prevent the errors. In the following query, the CASE
expression screens out the unwanted division because the CASE operation is
performed before the division.
Expressions
124 SQL Reference
SELECT REF_ID,PAYMT_PAST_DUE_CT,
SUM(CASE
WHEN PAYMT_PAST_DUE_CT=0 THEN 0
WHEN PAYMT_PAST_DUE_CT>0 THEN
SUM(BAL_AMT/PAYMT_PAST_DUE_CT)
END
FROM PAY_TABLE
GROUP BY REF_ID,PAYMT_PAST_DUE_CT;
Example 4: This example shows how to group the results of a query by a CASE
expression without having to re-type the expression. Using the sample employee
table, find the maximum, minimum, and average salary. Instead of finding these
values for each department, assume that you want to combine some departments
into the same group.
SELECT CASE_DEPT,MAX(SALARY),MIN(SALARY),AVG(SALARY)
FROM (SELECT SALARY,CASE WHEN WORKDEPT = A00 OR WORKDEPT = E21
THEN A00_E21
WHEN WORKDEPT = D11 OR WORKDEPT = E11
THEN D11_E11
ELSE WORKDEPT
END AS CASE_DEPT
FROM DSN8710.EMP) X
GROUP BY CASE_DEPT;
There are two scalar functions, NULLIF and COALESCE, that are specialized to
handle a subset of the functionality provided by CASE. Table 22 shows the
equivalent expressions using CASE or these functions.
Table 22. Equivalent case expressions
CASE expression Equivalent expression
CASE WHEN e1=e2
THEN NULL ELSE e1 END
NULLIF(e1,e2)
CASE WHEN e1 IS NOT NULL
THEN e1 ELSE e2 END
COALESCE(e1,e2)
CASE WHEN e1 IS NOT NULL
THEN e1 ELSE COALESCE(e2,...,eN) END
COALESCE(e1,e2,...,eN)
CAST specification
The CAST specification returns the first operand (the cast operand) converted to
the data type that is specified by the second operand. If the data type of eithe
r
operand is a distinct type, the privilege set must implicitly include EXECUTE
 CAST ( expression AS data-type )
NULL
parameter-marker

data-type:
 built-in-data-type
schema. distinct-type-name

Expressions
Chapter 2. Language elements 125
authority on the generated cast functions for the distinct type. If the data typ
e of the
second operand is a distinct type, the privilege set must also include USAGE
authority on the distinct type.
expression
Specifies that the cast operand is an expression other than NULL or a
parameter marker. The result is the value of the operand value converted to the
specified data type.
Table 7 on page 63 and Table 8 on page 64 shows the supported casts between
data types. If you specify an unsupported cast, an error occurs.
When a character string is cast to a character string with a different length or
a
graphic string is cast to a graphic string with a different length, a warning oc
curs
if any characters except trailing blanks are truncated. A warning also occurs if
any characters are truncated when a BLOB operand is cast.
NULL
Specifies that the cast operand is null. The result is a null value with the
specified data type.
parameter-marker
A parameter marker, which is normally considered an expression, has a special
meaning as a cast operand. When the cast operand is a parameter-marker, the
data type that is specified represents the “promise” that the replacement value
for the parameter marker will be assignable to that data type (using “store
assignment” rules for strings). Such a parameter marker is considered a typed
parameter marker. Typed parameter markers are treated like any other typed
value for the purpose of function resolution, a DESCRIBE of a select list, or
column assignment.
data type
The name of a built-in data type or a distinct type. If a data type has length,
precision, or scale attributes, specify the attributes. If the attributes are no
t
specified, the default values are used. For example, the default for CHAR is a
length of 1, and the default for DECIMAL is a precision of 5 and a scale of 0.
For the default values of the other data types, see the description of
“built-in-data-type” on page 606 for the CREATE TABLE statement. (For
portability across operating systems, when specifying a floating-point data type
,
use REAL or DOUBLE instead of FLOAT.)
v If the cast operand is expression, see “Casting between data types” on
page 62 and use any of the target data types that are supported for the data
type of the cast operand.
v If the cast operand is NULL, you can use any data type.
v If the cast operand is a parameter-marker, you can use any data type. If the
data type is a distinct type, the application that uses the parameter marker
will use the source data type of the distinct type.
Resolution of cast functions: DB2 uses the schema name and the data type
name of the target data type to locate the function to use to convert the first
operand to the data type of the second operand. If an unqualified data type name
is
specified for the second operand, DB2 first resolves the schema name of the data
type (by searching the SQL path and selecting the first schema such that the dat
a
type exists in the schema and the user has authorization to use the data type).
DB2
finds the appropriate cast function when all of the following conditions are tru
e:
v The schema name of the function matches the schema name of the target data
type.
v The function name matches the name of the target data type.
Expressions
126 SQL Reference
v The data type of the expression matches or is promotable to the data type of t
he
function’s parameter.
This comparison of data types results in one best fit, which is the choice for
execution (see “Method of finding the best fit” on page 108). For information on
the promotion of data types, see “Promotion of data types” on page 61.
v The user has EXECUTE authority on the function.
v The create timestamp for the function is older than the bind timestamp for the
statement in which the CAST specification is used.
If DB2 authorization checking is in effect, and DB2 performs an automatic rebind
on a plan or package that contains a CAST specification, any cast functions that
were created after the original BIND or REBIND of the invoking plan or package
are not candidates for execution.
Result of the CAST: When numeric data is cast to character data, the data type o
f
the result is a fixed-length character string, which is similar to the result th
at the
CHAR function would give. (For more information, see “CHAR” on page 182.) When
character data is cast to numeric data, the data type of the result depends on t
he
data type of the specified number. For example, character data that is cast to a
n
integer becomes a large integer, which is similar to the result that the INT fun
ction
would give. (For more information see “INTEGER or INT” on page 223.)
If the data type of the result is character, the subtype of the result is determ
ined as
follows:
v If the expression and data-type are both character, the subtype of the result
is
the same as the subtype of expression.
v If the field MIXED DATA on installation panel DSNTPF is NO, the subtype of the
result is SBCS.
v If the expression is a row ID and data-type is character, the result has a sub
type
of FOR BIT DATA, unless the data-type is CLOB.
v Otherwise, the subtype of the result is MIXED.
If the data type of the result is a string data type and not character FOR BIT D
ATA,
the encoding scheme of the result is determined as follows:
v If the expression and data-type are both character, the encoding scheme and
CCSID of the result are the same as expression. For example, assume
CHAR_COL is a character column in the following:
CAST(CHAR_COL AS VARCHAR(25))
The result of the CAST is a varying length string with the same encoding scheme
and CCSID as the input.
v If the expression and data-type are both graphic, the encoding scheme and
CCSID of the result are the same as expression.
v If the result is character, the encoding scheme of the result depends on the v
alue
of the field DEF ENCODING SCHEME on installation panel DSNTIPF. The
CCSID of the result is the default CCSID for the encoding scheme and subtype
of the result.
v If the result is graphic, the encoding scheme of the result depends on the val
ue
of the field DEF ENCODING SCHEME on installation panel DSNTIPF. The
CCSID of the result is the default CCSID for the encoding scheme of the result.
Expressions
Chapter 2. Language elements 127
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Alternative syntax for casting distinct types: There is alternative syntax for
casting a distinct type to its source data type and vice versa. Assume that a di
stinct
type D_MONEY was defined with the following statement and column MONEY was
defined with that data type.
CREATE DISTINCT TYPE D_MONEY AS DECIMAL(9,2) WITH COMPARISONS;
DECIMAL(MONEY) is equivalent syntax to CAST(MONEY AS DECIMAL(9,2)). Both
forms of the syntax use the cast function that DB2 generated when the distinct t
ype
D_MONEY was created to convert the distinct type to its source type of
DECIMAL(9,2).
However, it is possible that different cast functions may be chosen for the
equivalent syntax forms because of the difference in function resolution, partic
ularly
the treatment on unqualified names. Although the process of function resolution
is
similar for both, in the CAST specification as described above, DB2 uses the
schema name of the target data type to locate the function. Therefore, if an
unqualified data type name is specified as the target data type, DB2 uses the SQ
L
path to resolve the schema name of the distinct type and then searches for the
function in that schema. In function notation, when an unqualified function name
is
specified, DB2 searches the schemas in the SQL path to find an appropriate
function match, as described under “Function resolution” on page 106. For example,
assume that you defined the following distinct types, which implicitly gives you
both
USAGE authority on the distinct types and EXECUTE authority on the cast
functions that are generated for them:
CREATE DISTINCT TYPE SCHEMA1.AGE AS DECIMAL(2,0) WITH COMPARISONS;
one of the generated cast functions is:
FUNCTION SCHEMA1.AGE(SYSIBM.DECIMAL(2,0)) RETURNS SCHEMA1.AGE
CREATE DISTINCT TYPE SCHEMA2.AGE AS INTEGER WITH COMPARISONS;
one of the generated cast functions is:
FUNCTION SCHEMA2.AGE(SYSIBM.INTEGER) RETURNS SCHEMA2.AGE
If STU_AGE, an INTEGER host variable, is cast to the distinct type with either o
f
the following statements and the SQL path is SYSIBM, SCHEMA1, SCHEMA2:
Syntax 1: CAST(:STU_AGE AS AGE);
Syntax 2: AGE(:STU_AGE);
different cast functions are chosen. For syntax 1, DB2 first resolves the schema
name of distinct type AGE as SCHEMA1 (the first schema in the path that contains
a distinct type named AGE for which you have USAGE authority). Then it looks for
a suitable function in that schema and chooses SCHEMA1.AGE because the data
type of STU_AGE, which is INTEGER, is promotable to the data type of the
function argument, which is DECIMAL(2,0). For syntax 2, DB2 searches all the
schemas in the path for an appropriate function and chooses SCHEMA2.AGE. DB2
selects SCHEMA2.AGE over SCHEMA1.AGE because the data type of its
argument (INTEGER) is an exact match for STU_AGE (INTEGER) and, therefore, a
better match than the argument for SCHEMA1.AGE, which is DECIMAL(2,0).
Example 1: Assume that an application needs only the integer portion of the
SALARY column, which is defined as DECIMAL(9,2) from the EMPLOYEE table.
The following query for the employee number and the integer value of SALARY
could be prepared.
SELECT EMPNO, CAST(SALARY AS INTEGER) FROM EMPLOYEE;
Example 2: Assume that two distinct types exist in schema SCHEMAX. Distinct type
D_AGE was sourced on SMALLINT and is the data type for the AGE column in the
Expressions
128 SQL Reference
PERSONNEL table. Distinct type D_YEAR was sourced on INTEGER and is the
data type for the RETIRE_YEAR column in the same table. The following UPDATE
statement could be prepared.
UPDATE PERSONNEL SET RETIRE_YEAR =?
WHERE AGE = CAST( ? AS SCHEMAX.D_AGE);
The first parameter is an untyped parameter marker that has a data type of
RETIRE_YEAR. However, the application will use an integer for the parameter
marker. The parameter marker does not need to be cast because the SET is an
assignment.
The second parameter marker is a typed parameter marker that is cast to the
distinct type D_AGE. Casting the parameter marker satisfies the requirement that
comparisons must be performed with compatible data types. The application will
use the source data type, SMALLINT, to process the parameter marker.
Predicates
A predicate specifies a condition that is true, false, or unknown about a given
row or
group. The types of predicates are:
The following rules apply to predicates of any type:
v All values specified in a predicate must be compatible.
v Except for the first operand of LIKE, the operand of a predicate must not be a
character string with a maximum length greater than 255 or a graphic string with
a maximum length greater than 127.
v Except for EXISTS, a subquery in a predicate must specify a single column.
In addition to the examples of predicates in the following sections, see “Distinct
type
comparisons” on page 75, which contains several examples of predicates that use
distinct types.
Basic predicate
18. The following forms of the comparison operators are also supported in basic
and quantified predicates: !=, !<, and !>. In addition,
in code pages 437, 819, and 850, the forms ¬=, ¬<, and ¬> are supported. All these pro
duct-specific forms of the comparison
operators are intended only to support existing SQL statements that use these op
erators and are not recommended for use when
writing new SQL statements.
A not sign (¬) or the character that must be used in its place in certain countrie
s, can cause parsing errors in statements passed
from one DBMS to another. The problem occurs if the statement undergoes characte
r conversion with certain combinations of
source and target CCSIDs. To avoid this problem, substitute an equivalent operat
or for any operator that includes a not sign. For
example, substitute <> for ¬= , <= for ¬> , and >= for ¬< .
 basic predicate
quantified predicate
BETWEEN predicate
EXISTS predicate
IN predicate
LIKE predicate
NULL predicate

Expressions
Chapter 2. Language elements 129
|
A basic predicate compares two values or compares a set of values with another
set of values. In the syntax diagram, when expression is specified with fullsele
ct,
the fullselect returns a single result column. If the value of either operand is
null or
the result of the fullselect is empty, the result of the predicate is unknown.
Otherwise, the result is either true or false.
A row-value-expression is a set of value expressions. Its form is (value-express
ion,
value expression,..., value expression). In the syntax diagram for a basic predi
cate,
when a row-value-expression is specified on the left side of the = or the <>
operator, another row-value-expression must be specified on the right side, as i
n
the following two cases:
v If the operator is =, the result is true if all pairs of expressions evaluate
to true,
and false otherwise.
v If the operator is <>, the result is true if any pair of expressions evaluate
to true,
and false otherwise.
The use of any other operators or combination of operators when a row value
expression appears on the left side of a basic predicate results in an error.
A fullselect in a basic predicate must not return more than one value, whether n
ull
or not null.
For values x and y:
Predicate Is true if and only if...
x = y x is equal to y
x <> y x is not equal to y
x < y x is less than y
x > y x is greater than y
x <= y x is less than or equal to y
x >= y x is greater than or equal to y
Examples for values x and y:
EMPNO = 528671
SALARY < 20000
PRSTAFF <> :VAR1
SALARY >=4 (SELECT AVG(SALARY) FROM DSN8710.EMP)
 expression = expression
(1) (fullselect)
<>
<
>
<=
>=
(1)
( row-value-expression ) = ( row-value-expression )
<>

Notes:
1 Other comparison operators are also supported18.
Predicates
130 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Example: List the name, first name, and salary of the employee who is responsibl
e
for the ’SECRET’ project. This employee may appear in either the PROJA1 or
PROJA2 tables. A UNION is used in case the employee appears in both tables to
eliminate duplicate RESEMP values.
SELECT LASTNAME, FIRSTNAME, SALARY
FROM DSN8710.EMP X
WHERE EMPNO = (
SELECT RESPEMP
FROM PROJA1X
WHERE MAJPROJ = SECRET
UNION
SELECT RESPEMP
FROM PROJA2 X
WHERE MAJPROJ = SECRET );
Quantified predicate
A quantified predicate compares a value or values with a collection of values. I
n the
syntax diagram, when an expression is specified, fullselect1 returns a single re
sult
column and any number of values, whether null or not null. In the diagram, when
more than one row-value-expression is specified, fullselect2 returns a number of
result columns that is equal to the number of expressions on the left side of =
SOME, = ANY, or <> ALL. A fullselect1 refers to a single column result. A fullse
lect2
refers to the number of row-value expressions.
When ALL is specified, the result of the predicate is:
v True if the result of the fullselect is empty or if the specified relationship
is true
for every value returned by the fullselect.
v False if the specified relationship is false for at least one value returned b
y the
fullselect.
v Unknown if the specified relationship is not false for any values returned by
the
fullselect and at least one comparison is unknown because of a null value.
When SOME or ANY is specified, the result of the predicate is:
v True if the specified relationship is true for at least one value returned by
the
fullselect.
v False if the result of the fullselect is empty or if the specified relationshi
p is false
for every value returned by the fullselect.
 expression = SOME (fullselect1)
(1) ANY
<> ALL
<
>
<=
>=
( row-value-expression ) = SOME (fullselect2)
ANY
(1)
( row-value-expression ) <> ALL (fullselect2)

Notes:
1 Other comparison operators are also supported18.
Predicates
Chapter 2. Language elements 131
|
|
|
|
||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v Unknown if the specified relationship is not true for any of the values return
ed by
the fullselect and at least one comparison is unknown because of a null value.
The use of any other operators or combination of operators when a
row-value-expression appears on the left side of a quantified predicate results
in an
error.
Examples: Use the tables below when referring to the following examples. In all
examples, “row n of TBLA” refers to the row in TBLA for which COLA has the value
n.
TBLA: COLA TBLB: COLB COLC TBLC: COLB COLC
1234
2 2 2 2
3 --
Example 1: In the following predicate, the fullselect returns the values 2 and 3
. The
predicate is false for rows 1, 2, and 3 of TBLA, and is true for row 4.
COLA > ALL(SELECT COLB FROM TBLB
UNION
SELECT COLB FROM TBLC)
Example 2: In the following predicate, the fullselect returns the values 2 and 3
. The
predicate is false for rows 1 and 2 of TBLA, and is true for rows 3 and 4.
COLA > ANY(SELECT COLB FROM TBLB
UNION
SELECT COLB FROM TBLC)
Example 3: In the following predicate, the fullselect returns the values 2 and n
ull.
The predicate is false for rows 1 and 2 of TBLA, and is unknown for rows 3 and 4
.
The result is an empty table.
COLA > ALL(SELECT COLC FROM TBLB
UNION
SELECT COLC FROM TBLC)
Example 4: In the following predicate, the fullselect returns the values 2 and n
ull.
The predicate is unknown for rows 1 and 2 of TBLA, and is true for rows 3 and 4.
COLA >SOME(SELECT COLC FROM TBLB
UNION
SELECT COLC FROM TBLC)
Example 5: In the following predicate, the fullselect returns an empty result co
lumn.
Hence, the predicate is true for all rows of TBLA.
COLA < ALL(SELECT COLB FROM TBLB WHERE COLB>3
UNION
SELECT COLB FROM TBLC WHERE COLB>3)
Example 6: In the following predicate, the fullselect returns an empty result co
lumn.
Hence, the predicate is false for all rows of TBLA.
COLA < ANY(SELECT COLB FROM TBLB WHERE COLB>3
UNION
SELECT COLB FROM TBLC WHERE COLB>3)
If COLA were null in one or more rows of TBLA, the predicate would still be fals
e
for all rows of TBLA.
Predicates
132 SQL Reference
|
|
|
|
|
|
|
|||
|
|
|||
|
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
BETWEEN predicate
The BETWEEN predicate determines whether a given value lies between two other
given values specified in ascending order. Each of the predicate’s two forms has a
n
equivalent search condition, as shown below:
Table 23. BETWEEN predicate and equivalent search conditions
BETWEEN predicate Equivalent search condition
value1BETWEEN value2 AND value3 value1>= value2 AND value1<= value3
value1NOT BETWEEN value2 AND value3
or, equivalently:
NOT(value1BETWEEN value2 AND value3)
value1< value2 OR value1> value3
Search conditions are discussed in “Search conditions” on page 144.
If the operands include a mixture of datetime values and valid string representa
tions
of datetime values, all values are converted to the data type of the datetime
operand.
Example: Consider predicate:
A BETWEEN B AND C
The following table shows the value of the predicate for various values of A, B,
and
C.
Value of A Value of B Value of C Value of predicate
1,2, or 3 1 3 true
0 or 4 1 3 false
0 1 null false
4 null 3 false
null any any unknown
2 1 null unknown
3 null 4 unknown
EXISTS predicate
The EXISTS predicate tests for the existence of certain rows.
The result of the predicate is true if the result table returned by the fullsele
ct
contains at least one row. Otherwise, the result is false.
 expression BETWEEN expression AND expression
NOT

 EXISTS (fullselect) 
Predicates
Chapter 2. Language elements 133
|
|
The SELECT clause in the fullselect can specify any number of columns because
the values returned by the fullselect are ignored. For convenience, use:
SELECT *
Unlike the NULL, LIKE, and IN predicates, the EXISTS predicate has no form that
contains the word NOT. To negate an EXISTS predicate, precede it with the logica
l
operator NOT, as follows:
NOT EXISTS (fullselect)
The result is then false if the EXISTS predicate is true, and true if the predic
ate is
false. Here, NOT is a logical operator and not a part of the predicate. Logical
operators are discussed in “Search conditions” on page 144.
The result cannot be unknown.
Example 1: The following query lists the employee number of everyone represented
in DSN8710.EMP who works in a department where at least one employee has a
salary less than 20000. Like many EXISTS predicates, the one in this query
involves a correlated variable.
SELECT EMPNO
FROM DSN8710.EMP X
WHERE EXISTS (SELECT * FROM DSN8710.EMP
WHERE X.WORKDEPT=WORKDEPT AND SALARY<20000);
Example 2: List the subscribers (SNO) in the state of California who made at lea
st
one call during the first quarter of 2000. Order the results according to SNO. E
ach
MONTHnn table has columns for SNO, CHARGES, and DATE. The CUST table
has columns for SNO and STATE.
SELECT C.SNO
FROM CUST C
WHERE C.STATE = CA
AND EXISTS (
SELECT *
FROM MONTH1
WHERE DATE BETWEEN 01/01/2000 AND 01/31/2000
AND C.SNO = SNO
UNION ALL
SELECT *
FROM MONTH2
WHERE DATE BETWEEN 02/01/2000 AND 02/29/2000
AND C.SNO = SNO
UNION ALL
SELECT *
FROM MONTH3
WHERE DATE BETWEEN 03/01/2000 AND 03/31/2000
AND C.SNO = SNO
)
ORDER BY C.SNO;
Predicates
134 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||||||||||||||||
IN predicate
The IN predicate compares a value with a set of values.
When expression and fullselect1 are used the fullselect must specify a single re
sult
column and can return any number of values, whether null or not null. The IN
predicate is equivalent to the quantified predicate as follows:
Table 24. IN predicate and equivalent quantified predicates
IN predicate Equivalent quantified predicate
expression IN (fullselect) expression = ANY (fullselect)
expression NOT IN (fullselect) expression <> ALL (fullselect)
When expression is used in the non-fullselect form of the IN predicate, the seco
nd
operand is a set of one or more values specified by any combination of
expressions. The values for expression1 and expression2 or the column of
fullselect1 in the IN predicate must be compatible. Each expression in
row-value-expression and its corresponding column of fullselect2 must be
compatible. To determine the attributes of the result type used in the compariso
n,
see “Rules for result data types” on page 77. For information on the types of
expressions, see “Expressions” on page 110. If expression is a single host variable,
the host variable can identify a structure. Any host variable or structure that
is
specified must be described in the application program according to the rules fo
r
declaring host structures and variables. An IN predicate of the form:
expression IN (value1, value2,..., valuen)
is logically equivalent to:
expression IN (SELECT * FROM R)
when T is a table with a single row and R is a result table formed by the follow
ing
fullselect:
SELECT value1FROM T
UNION
SELECT value2 FROM T
UNION
...
UNION
SELECT valuen FROM T
When row-value-expression is used, fullselect2 returns a number of result column
s
that is equal to the number of expressions on the left side of the IN predicate.


expression1 IN (fullselect1)
NOT ,
( expression2 )
( row-value-expression ) IN (fullselect2)
NOT

Predicates
Chapter 2. Language elements 135
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
If the operands of the IN predicate are strings with different CCSIDs, the rules
used
to determine which operands are converted are those for operations that combine
strings. See “String comparisons” on page 73.
Example 1: The following predicate is true for any row whose employee is in
department D11, B01, or C01.
WORKDEPT IN ( D11 , B01 , C01 )
Example 2: The following predicate is true for any row whose employee works in
department E11.
EMPNO IN (SELECT EMPNO FROM DSN8710.EMP
WHERE WORKDEPT = E11 )
Example 3: The following predicate is true if the date that a project is estimat
ed to
start (PRENDATE) is within the next two years.
YEAR(PRENDATE) IN (YEAR(CURRENT DATE),
YEAR(CURRENT DATE + 1YEAR),
YEAR(CURRENT DATE + 2 YEARS))
Example 4: The following example obtains the phone number of an employee in
DSN8710.EMP where the employee number (EMPNO) is a value specified within
the COBOL structure defined below.
77 PHNUM PIC X(6).
01EMPNO-STRUCTURE.
05 CHAR-ELEMENT-1PIC X(6) VALUE 000140 .
05 CHAR-ELEMENT-2 PIC X(6) VALUE 000340 .
05 CHAR-ELEMENT-3 PIC X(6) VALUE 000220 .
...
EXEC SQL DECLARE PHCURS CURSOR FOR
SELECT PHONENO FROM DSN8710.EMP
WHERE EMPNO IN
(:EMPNO-STRUCTURE.CHAR-ELEMENT-1,
:EMPNO-STRUCTURE.CHAR-ELEMENT-2,
:EMPNO-STRUCTURE.CHAR-ELEMENT-3)
END-EXEC.
EXEC SQL OPEN PHCURS
END-EXEC.
EXEC SQL FETCH PHCURS INTO :PHNUM
END-EXEC.
LIKE predicate
The LIKE predicate searches for strings that have a certain pattern. The
match-expression is the string to be tested for conformity to the pattern specif
ied in
pattern-expression. Underscore and percent sign characters in the pattern have a
special meaning instead of their literal meanings unless escape-expression is
specified, as discussed under the description of pattern-expression.
The following rules summarize how a predicate in the form of “m LIKE p” is
evaluated:
 match-expression
NOT
LIKE pattern-expression
ESCAPE escape-expression

Predicates
136 SQL Reference
|
|
|
v If m or p is null, the result of the predicate is unknown.
v If m and p are both empty, the result of the predicate is true.
v If m is empty and p is not, the result of the predicate is unknown unless p
consists of one or more percent signs.
v If m is not empty and p is empty, the result of the predicate is false.
v Otherwise, if m matches the pattern in p, the result of the predicate is true.
The
description of pattern-expression provides a detailed explanation on how the
pattern is matched to evaluate the predicate to true or false. See the “rigorous
description of the pattern” for this information.
The values for match-expression, pattern-expression, and escape-expression must
all be character or graphic strings or a mixture of both or they must all be bin
ary
strings (BLOBs). None of the expressions can yield a distinct type; however, an
expression can be a function that casts a distinct type to its source type.
There are slight differences in what expressions are supported for each argument
.
The description of each argument lists the supported expressions:
match-expression
An expression that specifies the string to be tested for conformity to a certain
pattern of characters.
LIKE pattern-expression
An expression that specifies the pattern of characters to be matched.
The expression can be specified by any one of the following:
v A constant
v A special register
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above (though nested
function invocations cannot be used)
v A CAST specification whose arguments are any of the above
v An expression that concatenates (using CONCAT or ||) any of the above
The expression must also meet these restrictions:
v The maximum length of pattern-expression must not be larger than 4000
bytes.
v If a host variable is used in pattern-expression, the host variable must be
defined in accordance with the rules for declaring string host variables and
must not be a structure.
v If escape-expression is specified, pattern-expression must not contain the
escape character identified by escape-expression except when immediately
followed by the escape character, % , or _ . For example, if + is the escape
character, any occurrences of + other than ++ , +_ , or +% in the pattern
is
an error.
When the pattern specified in a LIKE predicate is a parmeter marker and a
fixed-length character host variable is used to replace the parameter marker,
specify a value for the host variable that is the correct length. If you do not
specify the correct length, the select does not return the intended results. For
example, if the host variable is defined as CHAR(10) and the value WYSE% is
assigned to that host variable, the host variable is padded with blanks on
assignment. The pattern used is ’WYSE%,’ which requests DB2 to search for all
values that start with WYSE and end with five blank spaces. If you intended to
search for only the values that start with ’WYSE,’ you should assign the value
’WYSE%%%%%%’ to the host variable.
Predicates
Chapter 2. Language elements 137
|
|
|
|
|
|
|
|
|
|
|
|
|
|
If the pattern is specified in a fixed-length string variable, any trailing blan
ks are
interpreted as part of the pattern. Therefore, it is better to use a varying-len
gth
string variable with an actual length that is the same as the length of the
pattern. If the host language does not allow varying-length string variables,
place the pattern in a fixed-length string variable whose length is the length o
f
the pattern.
For more on the use of host variables with specific programming languages,
see Part 2 of DB2 Application Programming and SQL Guide.
The pattern is used to specify the conformance criteria for values in the
match-expression where:
v The underscore character (_) represents any single character.
v The percent sign (%) represents a string of zero or more characters.
v Any other character represents a single occurrence of itself.
If the pattern-expression needs to include either the underscore or the percent
character, the escape-expression is used to specify a character to precede
either the underscore or percent character in the pattern. For character strings
,
the terms character, percent sign, and underscore refer to SBCS characters.
For graphic strings, the terms refer to double-byte or UTF-16 characters.
Predicates
138 SQL Reference
|
|
|
A rigorous description of the pattern
This more rigorous description of the pattern ignores the use of the
escape-expression.
Let m denote the value of match-expression and let p denote the value of
pattern-expression. The string p is interpreted as a sequence of the
minimum number of substring specifiers so each character of p is part of
exactly one substring specifier. A substring specifier is an underscore, a
percent sign, or any non-empty sequence of characters other than an
underscore or a percent sign.
The result of the predicate is unknown if m or p is the null value.
Otherwise, the result is either true or false. The result is true if m and p
are both empty strings or there exists a partitioning of m into substrings
such that:
v A substring of m is a sequence of zero or more contiguous characters
and each character of m is part of exactly one substring.
v If the nth substring specifier is an underscore, the nth substring of m is
any single character.
v If the nth substring specifier is a percent sign, the nth substring of m is
any sequence of zero or more characters.
v If the nth substring specifier is neither an underscore nor a percent
sign, the nth substring of m is equal to that substring specifier and has
the same length as that substring specifier.
v The number of substrings of m is the same as the number of substring
specifiers.
It follows that if p is an empty string and m is not an empty string, the
result is false. Similarly, if m is an empty string and p is not an empty
string, the result is false.
The predicate m NOT LIKE p is equivalent to the search condition NOT (m
LIKE p).
Mixed data patterns: If match-expression represents mixed data, the pattern is
assumed to be mixed data. For ASCII and EBCDIC, the special characters in
the pattern are interpreted as follows:
v An SBCS underscore refers to one SBCS character.
v A DBCS underscore refers to one MBCS character.
v A percent sign (either SBCS or DBCS) refers to a string of zero or more
SBCS or MBCS characters.
v Redundant shift bytes in match-expression or pattern-expression are ignored.
For Unicode, the special characters in the pattern are interpreted as follows:
v An SBCS or DBCS underscore refers to one character (either SBCS or
MBCS).
v A percent sign (either SBCS or DBCS) refers to a string of zero or more
SBCS or MBCS characters.
Predicates
Chapter 2. Language elements 139
|
|
|
|
|
When the LIKE predicate is used with Unicode data, the Unicode percent sign
and underscore use the code points indicated in the following table:
Character UTF-8 UTF-16
Half-width % X 25 X 0025
Full-width % X EFBC85 X FF05
Half-width_ X 5F X 005F
Full-width_ X EFBCBF X FF3F
The full-width or half-width % matches zero or more characters. The full-width
or half width _ character matches exactly one character. (For ASCII or EBCDIC
data, a full-width _ character matches one DBCS character.)
ESCAPE escape-expression
An expression that specifies the escape character to be used to modify the
special meaning of the underscore (_) and percent (%) characters in
pattern-expression. Specifying an expression, which is optional, allows values
that contain the actual percent and underscore characters to be matched. The
escape character consists of a single SBCS (1 byte) or DBCS (2 bytes)
character. An escape clause is allowed for Unicode mixed (UTF-8) data, but is
restricted for ASCII and EBCDIC mixed data.
The expression can be specified by any one of:
v A constant
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above (though nested
function invocations cannot be used)
v A CAST specification whose arguments are any of the above
The following rules also apply to the use of the ESCAPE clause and
escape-expression:
v The result of escape-expression must be one SBCS or DBCS character or a
binary string that contains exactly 1 byte.
v The ESCAPE clause cannot be used if match-expression is mixed data.
v If escape-expression is specified by a host variable, the host variable must
be defined in accordance with the rules for declaring fixed-length string host
variables.19 If the host variable has a negative indicator variable, the result
of
the predicate is unknown.
v The pattern must not contain the escape character except when followed by
the escape character, % or _ . For example, if + is the escape character,
any occurrences of + other than ++ , +_ , or +% in the pattern is an error
.
The following example shows the effect of successive occurrences of the
escape character, which in this case is the plus sign (+).
When the pattern string is... The actual pattern is...
+% A percent sign
++% A plus sign followed by zero or more
arbitrary characters
+++% A plus sign followed by a percent sign
19. If it is NUL-terminated, a C character string variable of length 2 can be sp
ecified.
Predicates
140 SQL Reference
|
|
||
|
|
|
|
||||
|
|
|
|
Examples
Example 1: The following predicate is true when the string to be tested in NAME
has the value SMITH, NESMITH, SMITHSON, or NESMITHY. It is not true when
the string has the value SMYTHE:
NAME LIKE %SMITH%
Example 2: In the predicate below, a host variable named PATTERN holds the
string for the pattern:
NAME LIKE :PATTERN ESCAPE +
Assume that the string in PATTERN has the value:
AB+_C_%
Observe that in this string, the plus sign preceding the first underscore is an
escape
character. The predicate is true when the string being tested in NAME has the va
lue
AB_CD or AB_CDE. It is false when this string has the value AB, AB_, or AB_C.
Example 3: The following two predicates are equivalent; three of the four percen
t
signs in the first predicate are redundant.
NAME LIKE AB%%%%CD
NAME LIKE AB%CD
Example 4: Assume that a distinct type named ZIP_TYPE with a source data type
of CHAR(5) exists and an ADDRZIP column with data type ZIP_TYPE exists in
some table TABLEY. The following statement selects the row if the zip code
(ADDRZIP) begins with ’9555’.
SELECT * FROM TABLEY
WHERE CHAR(ADDRZIP) LIKE 9555% ;
Example 5: The RESUME column in sample table
DSN8710.EMP_PHOTO_RESUME is defined as a CLOB. The following statement
selects the RESUME column when the string JONES appears anywhere in the
column.
SELECT RESUME FROM DSN8710.EMP_PHOTO_RESUME
WHERE RESUME LIKE %JONES% ;
Example 6: In the following table, assume COL1 is a column that contains mixed
EBCDIC data. The table shows the results when the predicate in the first column
is
evaluated using the COL1 value in the second column:
Predicates
Chapter 2. Language elements 141
Example 7: In the following table, assume COL1 is a column that contains mixed
ASCII data. The table shows the results when the predicate in the first column i
s
evaluated using the COL1 value in the second column:
Example 8: In the following table, assume COL1 is a column that contains Unicode
data. The table shows the results when the predicate in the first column is
evaluated using the COL1 value in the second column:
Predicates
142 SQL Reference
|
|
|
NULL predicate
The NULL predicate tests for null values.
The result of a NULL predicate cannot be unknown. If the value of the expression
is
null, the result is true. If the value is not null, the result is false. If NOT
is specified,
the result is reversed.
A parameter marker must not be specified for or within the expression.
Example: The following predicate is true whenever PHONENO has the null value,
and is false otherwise.
PHONENO IS NULL
 expression IS NULL
NOT

Predicates
Chapter 2. Language elements 143
Search conditions
A search condition specifies a condition that is true, false, or unknown about a
given row or group. When the condition is true, the row or group qualifies for t
he
results. When the condition is false or unknown, the row or group does not quali
fy.
The result of a search condition is derived by application of the specified logi
cal
operators (AND, OR, NOT) to the result of each specified predicate. If logical
operators are not specified, the result of the search condition is the result of
the
specified predicate.
AND and OR are defined in the following table, in which P and Q are any
predicates:
Table 25. Truth table for AND and OR
P Q P AND Q P OR Q
True True True True
True False False True
True Unknown Unknown True
False True False True
False False False False
False Unknown False Unknown
Unknown True Unknown True
Unknown False False Unknown
Unknown Unknown Unknown Unknown
NOT(true) is false and NOT(false) is true, but NOT(unknown) is still unknown. Th
e
NOT logical operator has no affect on an unknown condition. The result of
NOT(unknown) is still unknown.
Search conditions within parentheses are evaluated first. If the order of evalua
tion is
not specified by parentheses, NOT is applied before AND, and AND is applied
before OR. The order in which operators at the same precedence level are
evaluated is undefined to allow for optimization of search conditions.
Example 1: In the first of the search conditions below, AND is applied before OR
. In
the second, OR is applied before AND.
SALARY>:SS AND COMM>:CC OR BONUS>:BB
SALARY>:SS AND (COMM>:CC OR BONUS>:BB)
Example 2: In the first of the search conditions below, NOT is applied before AN
D.
In the second, AND is applied before NOT.
NOT SALARY>:SS AND COMM>:CC
NOT (SALARY>:SS AND COMM>:CC)
 predicate
NOT (search-condition)

AND predicate
OR NOT (search-condition)

Search Conditions
144 SQL Reference
|||
Example 3: For the following search condition, AND is applied first. After the
application of AND, the ORs could be applied in either order without changing th
e
result. DB2 can therefore select the order of applying the ORs.
SALARY>:SS AND COMM>:CC OR BONUS>:BB OR SEX=:GG
Options affecting SQL
Certain DB2 precompiler options, DB2 subsystem parameters (set through the
installation panels), bind options, and special registers affect how SQL stateme
nts
can be composed or determine how SQL statements are processed.
Table 26 summarizes the effect of these options and shows where to find more
information. (Some of the items are described in detail following the table, whi
le
other items are described elsewhere.)
Table 26. Summary of items affecting composition and processing of SQL statement
s
Precompiler option Other1 Affects
DYNAMICRULES bind option The rules that DB2 applies to dynamic SQL statements.
For details about authorization, see “Authorization IDs
and dynamic SQL” on page 43. The bind option can
also affect decimal point representation, string
delimiters, mixed data, and decimal arithmetic.
For details about how DB2 applies the precompiler
options to dynamic SQL statements when
DYNAMICRULES bind, define, or invoke behavior is in
effect, see “Precompiler options for dynamic
statements” on page 147.
USE FOR DYNAMICRULES Use of precompiler options for dynamic statements
when DYNAMICRULES bind, define, or, invoke
behavior is in effect. For details, see “Precompiler
options for dynamic statements” on page 147.
COMMA
PERIOD
DECIMAL POINT IS Representation of decimal points in SQL statements.
For details, see page 147.
APOSTSQL
QUOTESQL
SQL STRING DELIMITER Representation of string delimiters in SQL statements.
For details, see page 148.
ASCII CODED CHAR SET A numeric value that determines the CCSID of ASCII
string data.
For details, see page 149.
EBCDIC CODED CHAR SET A numeric value that determines the CCSID of EBCDIC
string data and whether Katakana characters can be
used in ordinary identifiers.
For details, see page 149.
UNICODE CCSID A numeric value that determines the CCSID of Unicode
string data.
For details, see page 149.
GRAPHIC
NOGRAPHIC
MIXED DATA Use of ASCII or EBCDIC character strings with a
mixture of SBCS and DBCS characters.
For details, see page 149.
Search Conditions
Chapter 2. Language elements 145
|
|
|
Table 26. Summary of items affecting composition and processing of SQL statement
s (continued)
Precompiler option Other1 Affects
DATE
TIME
DATE FORMAT
TIME FORMAT
LOCAL DATE LENGTH
LOCAL TIME LENGTH
Formatting of datetime strings.
For details, see page 150.
STDSQL Conformance with the SQL standard.
For details, see page 150.
NOFOR or STDSQL Whether the FOR UPDATE OF clause must be
specified (in the SELECT statement of the DECLARE
CURSOR statement).
For details, see page 152.
CONNECT Whether the rules for a type 1 or a type 2 CONNECT
statement apply. See “CONNECT” on page 453 for a
description of the rules.
CURRENTSERVER bind option Establishing a server other than the local DB2
subsystem.
For details, see “Establishing a different server” on
page 455.
SQLRULES bind option Whether a type 2 CONNECT statement is processed
with DB2 rules or SQL standard rules.
CURRENT RULES special register Whether the statements ALTER TABLE, CREATE
TABLE, GRANT, and REVOKE are processed with DB2
rules or SQL standard rules. For details, see
“CURRENT RULES” on page 89.
Whether DB2 automatically creates the LOB table
space, auxiliary table, and index on the auxiliary table
for a LOB column in a base table. For details, see
“Creating a table with LOB columns” on page 623.
Whether DB2 automatically creates an index on a
ROWID column that is defined with GENERATED BY
DEFAULT. For details, see the description of the clause
for “CREATE TABLE” on page 601.
Whether a stored procedure runs as a main or
subprogram. For details, see “CREATE PROCEDURE
(external)” on page 566.
SQLRULES bind option or
CURRENT RULES special
register
Whether SQLCODE +236 is issued when the SQLDA
provided on DESCRIBE or PREPARE INTO is too small
and the result columns do not involve LOBs or distinct
types. For details, see “DESCRIBE (prepared statement
or table)” on page 695 and “Appendix C. SQLCA and
SQLDA” on page 923.
Whether the SELECT privilege is required in a
searched DELETE or UPDATE. For details, see
“DELETE” on page 688 or “UPDATE” on page 872.
Options affecting SQL
146 SQL Reference
Table 26. Summary of items affecting composition and processing of SQL statement
s (continued)
Precompiler option Other1 Affects
DEC DECIMAL ARITHMETIC or
CURRENT PRECISION special
register
Whether DEC15 or DEC31 rules are used when both
operands in a decimal operation have 15 digits or less.
For details, see “Arithmetic with two decimal operands”
on page 114.
Note: 1The entries in this column are fields on installation panels unless other
wise noted.
For further details on precompiler options, see Part 5 of DB2 Application
Programming and SQL Guide. For more details on bind options, see Chapter 2 of
DB2 Command Reference.
Precompiler options for dynamic statements
Generally, dynamic statements use the application programming defaults specified
on installation panel DSNTIPF. However, if the value of installation panel field
USE
FOR DYNAMICRULES is NO and DYNAMICRULES bind, define, or invoke
behavior is in effect, the following precompiler options are used instead of the
application programming defaults:
v COMMA or PERIOD
v APOST or QUOTE
v APOSTSQL or QUOTESQL
v GRAPHIC or NOGRAPHIC
v DEC(15) or DEC(31)
For some languages, the precompiler option defaults to a value and no alternativ
e
is allowed. If the value of installation panel field USE FOR DYNAMICRULES is
YES, dynamic statements use the application programming defaults regardless of
the value of bind option DYNAMICRULES.
For additional information on the effect of precompiler options and application
programming defaults on:
v Decimal point representation, see page 147.
v String delimiters, see page 148.
v Mixed data, see page 149.
v Decimal arithmetic, see “Arithmetic with two decimal operands” on page 114.
For a list of the DYNAMICRULES bind option values that specify run, bind, define
,
or invoke behavior, see Table 2 on page 44.
Decimal point representation
Decimal points in SQL statements are represented with either periods or commas.
Two values control the representation:
v The value of field DECIMAL POINT IS on installation panel DSNTIPF, which can
be a comma (,) or period (.)
v COMMA or PERIOD, which are mutually exclusive DB2 precompiler options for
COBOL
These values apply to SQL statements as follows:
v For a distributed operation, the decimal point is the first of the following v
alues
that applies:
– The decimal point value specified by the requester
Options affecting SQL
Chapter 2. Language elements 147
– The value of field DECIMAL POINT IS on panel DSNTIPF at the DB2 where
the package is bound
v Otherwise:
For static SQL statements:
- In a COBOL program, the DB2 precompiler option COMMA or PERIOD
determines the decimal point representation for every static SQL statement.
If neither precompiler option is specified, the value of DECIMAL POINT IS
at precompilation time determines the representation.
- In non-COBL programs, the decimal representation for static SQL
statements is always the period.
For dynamic SQL statements:
- If DYNAMICRULES run behavior applies, the decimal point is the value of
field DECIMAL POINT IS on installation panel DSNTIPF at the local DB2
when the statement is prepared.
For a list of the DYNAMICRULES bind option values that specify run, bind,
define, or invoke behavior, see Table 2 on page 44.
- If DYNAMICRULES bind, define, or invoke behavior applies, and the value
of install panel field USE FOR DYNAMICRULES is YES, the decimal point
is the value of field DECIMAL POINT IS.
If bind, define, or invoke behavior applies, and field USE FOR DYNAMIC
RULES is NO, the precompiler option determines the decimal point
representation. For COBOL programs, which supports precompiler option
COMMA or PERIOD, the decimal point representation is determined as
described above for static SQL statements in COBOL programs. For
programs written in other host languages, the default precompiler option,
which can only be PERIOD, is used.
If the comma is the decimal point, these rules apply:
v In any constant, a comma intended as a separator must be followed by space.
Such commas could appear, for example, in a VALUES clause, an IN predicate,
or an ORDER BY clause in which numbers are used to identify columns.
v In any context, a comma intended as a decimal point must not be followed by a
space.
v If the DECIMAL POINT IS field (and not the precompiler option) determines the
comma as the decimal point, DB2 will recognize either a comma or a period as
the decimal point in numbers in dynamic SQL.
Apostrophes and quotation marks in string delimiters
The following precompiler options control the representation of string delimiter
s:
v APOST and QUOTE are mutually exclusive DB2 precompiler options for COBOL.
Their meanings are exactly what they are for the COBOL compilers:
– APOST names the apostrophe ( ) as the string delimiter in COBOL
statements.
– QUOTE names the quotation mark (") as the string delimiter.
Neither option applies to SQL syntax. Do not confuse them with the APOSTSQL
and QUOTESQL options.
v APOSTSQL and QUOTESQL are mutually exclusive DB2 precompiler options for
COBOL. Their meanings are:
– APOSTSQL names the apostrophe ( ) as the string delimiter and the quotation
mark (") as the escape character in SQL statements.
Options affecting SQL
148 SQL Reference
– QUOTESQL names the quotation mark (") as the string delimiter and the
apostrophe ( ) as the escape character in SQL statements.
These values apply to SQL statements as follows:
v For a distributed operation, the string delimiter is the first of the followin
g values
that applies:
– The SQL string delimiter value specified by the requester
– The value of the field SQL STRING DELIMITER on installation panel
DSNTIPF at the DB2 where the package is bound
v Otherwise:
– For static SQL statements:
In a COBOL program, the DB2 precompiler option APOSTSQL or QUOTESQL
determines the string delimiter and escape character. If neither precompiler
option is specified, the value of field SQL STRING DELIMITER on installation
panel DSNTIPF determines the string delimiter and escape character.
In a non-COBOL program, the string delimiter is the apostrophe, and the
escape character is the quotation mark.
– For dynamic SQL statements:
- If DYNAMICRULES run behavior applies, the string delimiter and escape
character is the value of field SQL STRING DELIMITER on installation
panel DSNTIPF at the local DB2 when the statement is prepared.
For a list of the DYNAMICRULES bind option values that specify run, bind,
define, or invoke behavior, see Table 2 on page 44.
- If DYNAMICRULES bind, define, or invoke behavior applies and the value
of install panel field USE FOR DYNAMICRULES is YES, the string delimiter
and escape character is the value of field SQL STRING DELIMITER.
If bind, define, or invoke behavior applies and USE FOR DYNAMICRULES
is NO, the precompiler option determines the string delimiter and escape
character. For COBOL programs, precompiler option APOSTSQL or
QUOTESQL determines the string delimiter and escape character. If neither
precompiler option is specified, the value of field SQL STRING DELIMITER
determines them. For programs written in other host languages, the default
precompiler option, which can only be APOSTSQL, determines the string
delimiter and escape character.
Katakana characters for EBCDIC
The field EBCDIC CODED CHAR SET on installation panel DSNTIPF determines
the system CCSIDs for EBCDIC-encoded data. Ordinary identifiers with an EBCDIC
encoding scheme can contain Katakana characters if the field contains the value
5026 or 930. There are no corresponding precompiler options. EBCDIC CODED
CHAR SET applies equally to static and dynamic statements. For dynamically
prepared statements, the applicable value is always the one at the local DB2.
Mixed data in character strings
The field MIXED DATA on installation panel DSNTIPF can have the value YES or
NO for ASCII or EBCDIC character strings. The value YES indicates that character
strings can contain a mixture of SBCS and DBCS characters. The value NO
indicates that they cannot. For Unicode, the default is always mixed. A
corresponding precompiler option (GRAPHIC or NOGRAPHIC) exists for every host
language supported.
Options affecting SQL
Chapter 2. Language elements 149
For static SQL statements, the value of the precompiler option determines whethe
r
ASCII or EBCDIC character strings can contain mixed data. For dynamic SQL
statements, either the value of field MIXED DATA or the precompiler option is us
ed,
depending on the value of bind option DYNAMICRULES in effect:
v If DYNAMICRULES run behavior applies, field MIXED DATA is used.
For a list of the DYNAMICRULES bind option values that specify run, bind,
define, or invoke behavior, see Table 2 on page 44.
v If bind, define, or invoke behavior applies and the value of install panel fie
ld USE
FOR DYNAMICRULES is YES, field MIXED DATA is used. If USE FOR
DYNAMICRULES is NO, the precompiler option is used.
The value of MIXED DATA and the precompiler option affects the parsing of SQL
character string constants, the execution of the LIKE predicate, and the assignm
ent
of character strings to host variables when truncation is needed. It can also af
fect
concatenation, as explained in “With the concatenation operator” on page 111. A
value that applies to a statement executed at the local DB2 also applies to any
statement executed at another server. An exception is the LIKE predicate, for wh
ich
the applicable value of MIXED DATA is always the one at the statement’s server.
The value of MIXED DATA also affects the choice of system CCSIDs for the local
DB2 and the choice of data subtypes for character columns. When this value is
YES, multiple CCSIDs are available for ASCII and EBCDIC data (SBCS, DBCS,
and MIXED). The CCSID specified in the ASCII CODED CHAR SET or EBCDIC
CODED CHAR SET field is the MIXED CCSID. In this case, DB2 derives the SBCS
and MIXED CCSIDs from the DBCS CCSID specified installation panel DSNTIPF.
Moreover, a character column can have any one of the allowable data
subtypes—BIT, SBCS, or MIXED.
On the other hand, when MIXED DATA is NO, the only ASCII or EBCDIC system
CCSIDs are those for SBCS data. Therefore, only BIT and SBCS can be data
subtypes for character columns.
Formatting of datetime strings
Fields on installation panel DSNTIPF (DATE FORMAT, TIME FORMAT, LOCAL
DATE LENGTH, and LOCAL TIME LENGTH) and DB2 precompiler options affect
the formatting of datetime strings.
The formatting of datetime strings is described in “String representations of date
time
values” on page 57. Unlike the subsystem parameters and options previously
described, a value in effect for a statement executed at the local DB2 is not
necessarily in effect for a statement executed at a different server. See “Restric
tions
on the use of local datetime formats” on page 59 for more information.
SQL standard language
DB2 SQL and the SQL standard are not identical. The STDSQL precompiler option
addresses some of the differences:
v STDSQL(NO) indicates that conformance with the SQL standard is not intended.
The default is the value of field STD SQL LANGUAGE on installation panel
DSNTIP4 (which has a default of NO).
v STDSQL(YES)20 indicates that conformance with the SQL standard is intended.
20. STDSQL(86) is a synonym, but STDSQL(YES) should be used.
Options affecting SQL
150 SQL Reference
When a program is precompiled with the STDSQL(YES) option, the following rules
apply:
Declaring host variables: All host variable declarations must lie between pairs
of
BEGIN DECLARE SECTION and END DECLARE SECTION statements:
BEGIN DECLARE SECTION
(one or more host variable declarations)
END DECLARE SECTION
Separate pairs of these statements can bracket separate sets of host variable
declarations.
Declarations for SQLCODE and SQLSTATE: The programmer must declare host
variables for either SQLCODE or SQLSTATE, or both. SQLCODE should be defined
as a fullword integer and SQLSTATE should be defined as a 5-byte character strin
g.
SQLCODE and SQLSTATE cannot be part of any structure. The variables must be
declared in the DECLARE SECTION of a program; however, SQLCODE can be
declared outside of the DECLARE SECTION when no host variable is defined for
SQLSTATE. For PL/I, an acceptable declaration can look like this:
DECLARE SQLCODE BIN FIXED(31);
DECLARE SQLSTATE CHAR(5);
In Fortran programs, the variable SQLCOD should be used for SQLCODE, and
either SQLSTATE or SQLSTA can be used for SQLSTATE.
Definitions for the SQLCA: An SQLCA must not be defined in your program,
either by coding its definition manually or by using the INCLUDE SQLCA statement
.
When STDSQL(YES) is specified, the DB2 precompiler automatically generates an
SQLCA that includes the variable name SQLCADE instead of SQLCODE and
SQLSTAT instead of SQLSTATE. After each SQL statement executes, DB2 assigns
status information to SQLCODE and SQLSTATE, whose declarations are described
above, as follows:
v SQLCODE: DB2 assigns the value in SQLCADE to SQLCODE. In Fortran,
SQLCAD and SQLCOD are used for SQLCADE and SQLCODE, respectively.
v SQLSTATE: DB2 assigns the value in SQLSTAT to SQLSTATE. (In Fortran,
SQLSTT and SQLSTA are used for SQLSTAT and SQLSTATE, respectively.)
v No declaration for either SQLSTATE or SQLCODE: DB2 assigns the value in
SQLCADE to SQLCODE.
If the precompiler encounters an INCLUDE SQLCA statement, it ignores the
statement and issues a warning message. The precompiler also does not recognize
hand-coded definitions, and a hand-coded definition creates a compile-time confl
ict
with the precompiler-generated definition. A similar conflict arises if definiti
ons of
SQLCADE or SQLSTAT, other than the ones generated by the DB2 precompiler,
appear in the program.
Comments in static SQL statements: Static SQL statements can include SQL
comments. Two consecutive hyphens (--) indicate that the characters after the
hyphens are a comment.
SQL comments are recognized only in a program that has been precompiled with
the STDSQL(YES) option. If STDSQL(YES) is not specified, the use of an SQL
comment might cause a syntax error. Host language comments can be used
instead.
Options affecting SQL
Chapter 2. Language elements 151
When allowed, SQL comments are subject to the following rules:
v The two hyphens must be on the same line, not separated by a space.
v Comments can be started wherever a space is valid (except within a delimiter
token or between EXEC and SQL).
v Comments are terminated by the end of the line.
v Comments are not allowed within statements that are dynamically prepared
(using PREPARE or EXECUTE IMMEDIATE).
v Within a statement embedded in a COBOL program, the two hyphens must be
preceded by a blank unless they begin a line.
This example shows how to include comments in a statement:
EXEC SQL CREATE VIEW PRJ_MAXPER -- projects with most support personnel
AS SELECT PROJNO, PROJNAME -- number and name of project
FROM DSN8710.PROJ
WHERE DEPTNO = E21 -- systems support dept code
AND PRSTAFF > 1
END-EXEC.
Positioned updates of columns
The NOFOR precompiler option affects the use of the FOR UPDATE OF clause.
The NOFOR option is in effect when either of the following are true:
v The NOFOR option is specified.
v The STDSQL(YES) option is in effect.
Otherwise, the NOFOR option is not in effect. The following table summarizes the
differences when the option is in effect and when the option is not in effect:
Table 27. The NOFOR precompiler option
When NOFOR is in effect When NOFOR is not in effect
The use of the FOR UPDATE OF clause in
the SELECT statement of the DECLARE
CURSOR statement is optional. This clause
restricts updates to the specified columns and
causes the acquisition of update locks when
the cursor is used to fetch a row. If no
columns are specified, positioned updates
can be made to any updatable columns in the
table or view that is identified in the first
FROM clause in the SELECT statement. If
the FOR UPDATE OF clause is not specified,
positioned updates can be made to any
columns that the program has DB2 authority
to update.
The FOR UPDATE OF clause must be
specified.
DBRMs must be built entirely in virtual
storage, which might possibly increase the
virtual storage requirements of the DB2
precompiler. However, creating DBRMs
entirely in virtual storage might ease
concurrency problems with DBRM libraries.
DBRMs can be built incrementally using the
DB2 precompiler.
Options affecting SQL
152 SQL Reference
|||||
Chapter 3. Built-in functions
A built-in function is a function that is supplied with DB2 for OS/390 and z/OS.
A
built-in function is denoted by a function name followed by one or more operands
that are enclosed in parentheses. The operands are called arguments, and each
argument is specified by an expression. The result of a built-in function is a s
ingle
value derived by applying the operation of the function to the arguments.
The built-in functions are in schema SYSIBM. A built-in function can be invoked
with
or without its schema name. Regardless of whether a schema name qualifies the
function name, DB2 uses function resolution to determine which function to use.
For
more information on functions and the process of function resolution, see
“Functions” on page 104.
Built-in functions are classified as column functions or scalar functions. Altho
ugh
both types of functions return a single value, their arguments differ. The argum
ent of
a column function is a set of like values. Each argument of a scalar function is
a
single value.
In the syntax of SQL, the term function is used only in the definition of an
expression. Thus, a function can be used only where an expression is
used.However, some restrictions apply to the use of column functions as specifie
d
in “Column functions” on page 158 and in “Chapter 4. Queries” on page 299. Most
of the built-in functions can also be used as the source function for a user-def
ined
function as described under “CREATE FUNCTION (sourced)” on page 521.
Table 28 lists the built-in functions that DB2 supports.
Table 28. Supported functions
Function name Description Page
ABS or ABSVAL Returns the absolute value of its argument 171
ACOS Returns the arccosine of an argument as an angle, expressed in
radians
172
ADD_MONTHS Returns a date that represents the date argument plus the
number of months argument
173
ASIN Returns the arcsine of an argument as an angle, expressed in
radians
175
ATAN Returns the arctangent of an argument as an angle, expressed in
radians
176
ATANH Returns the hyperbolic arctangent of an argument as an angle,
expressed in radians
177
ATAN2 Returns the arctangent of x and y coordinates as an angle,
expressed in radians
178
AVG Returns the average of a set of numbers 159
BLOB Returns a BLOB representation of its argument 179
CCSID_ENCODING Returns the encoding scheme of a CCSID with a value of ASCII,
EBCDIC, UNICODE, or UNKNOWN
180
CEIL or CEILING Returns the smallest integer greater than or equal to the
argument
181
CHAR Returns a fixed-length character string representation of its
argument
182
© Copyright IBM Corp. 1982, 2001 153
|
|
|
|
| |
|
| |
Table 28. Supported functions (continued)
Function name Description Page
CLOB Returns a CLOB representation of its argument 188
COALESCE Returns the first argument in a set of arguments that is not null 189
CONCAT Returns the concatenation of two strings 191
COS Returns the cosine of an argument that is expressed as an angle
in radians
192
COSH Returns the hyperbolic cosine of an argument that is expressed
as an angle in radians
193
COUNT Returns the number of rows or values in a set of rows or values 160
COUNT_BIG Same as COUNT, except the result can be greater than the
maximum value of an integer
161
DATE Returns a date derived from its argument 194
DAY Returns the day part of its argument 195
DAYOFMONTH Similar to DAY 196
DAYOFWEEK Returns an integer in the range of 1 to 7, where 1 represents
Sunday
197
DAYOFWEEK_ISO Returns an integer in the range of 1 to 7, where 1 represents
Monday
198
DAYOFYEAR Returns an integer in the range of 1 to 366, where 1 represents
January 1
199
DAYS Returns an integer representation of a date 200
DBCLOB Returns a DBCLOB representation of its argument 201
DECIMAL or DEC Returns a decimal representation of its argument 202
DEGREES Returns the number of degrees for an argument that is expressed
in radians
204
DIGITS Returns a character string representation of a number 205
DOUBLE or
DOUBLE-PRECISION
Returns a double precision floating-point representation of its
argument
206
EXP Returns the exponential function of an argument 207
FLOAT Same as DOUBLE 206
FLOOR Returns the largest integer that is less than or equal to the
argument
209
GRAPHIC Returns a GRAPHIC representation of its argument 210
HEX Returns a hexadecimal representation of its argument 213
HOUR Returns the hour part of its argument 214
IDENTITY_VAL_LOCAL Returns the most recently assigned value for an identity colu
mn 215
IFNULL Returns the first argument in a set of two arguments that is not
null
219
INSERT Returns a string that is composed of an argument inserted into
another argument at the same position where some number of
bytes have been deleted
220
INTEGER or INT Returns an integer representation of its argument 223
JULIAN_DAY Returns an integer that represents the number of days from
January 1, 4712 B.C.
224
Built-in functions
154 SQL Reference
|
| |
|
| |
|
|
|
Table 28. Supported functions (continued)
Function name Description Page
LAST_DAY Returns a date that represents the last day of the month of the
date argument
225
LCASE or LOWER Returns a string with the characters converted to lowercase 226
LEFT Returns a string that consists of the specified number of leftmost
bytes of a string
227
LENGTH Returns the length of its argument 229
LN Returns the natural logarithm of an argument 230
LOCATE Returns the position at which the first occurrence of an argument
starts within another argument
231
LOG10 Returns the base 10 logarithm of an argument 233
LTRIM Returns the characters of a string with the leading blanks
removed
234
MAX Returns the maximum value in a set of column values 163
MAX (scalar) Returns the maximum value in a set of values 235
MICROSECOND Returns the microsecond part of its argument 236
MIDNIGHT_SECONDS Returns an integer in the range of 0 to 86400 that represents t
he
number of seconds between midnight and the argument
237
MIN Returns the minimum value in a set of column values 164
MIN (scalar) Returns the minimum value in a set of values 238
MINUTE Returns the minute part of its argument 239
MOD Returns the remainder of one argument divided by a second
argument
240
MONTH Returns the month part of its argument 242
MULTIPLY_ALT Returns the product of the two arguments as a decimal value,
used when the sum of the argument precisions exceeds 31
243
NEXT_DAY Returns a timestamp that represents the first weekday, named by
the second argument, after the date argument
244
NULLIF Returns NULL if the arguments are equal; else the first argument 245
POSSTR Returns the position of the first occurrence of an argument within
another argument
246
POWER Returns the value of one argument raised to the power of a
second argument
248
QUARTER Returns an integer in the range of 1 to 4 that represents the
quarter of the year for the date specified in the argument
249
RADIANS Returns the number of radians for an argument that is expressed
in degrees
250
RAISE_ERROR Raises an error in the SQLCA with the specified SQLSTATE and
error description
251
RAND Returns a double precision floating-point random number 252
REAL Returns a single precision floating-point representation of its
argument
253
REPEAT Returns a character string composed of an argument repeated a
specified number of times
254
REPLACE Returns a string in which all occurrences of an argument within a
second argument are replaced with a third argument
256
Built-in functions
Chapter 3. Built-in functions 155
|
|
|
|
| |
|
| |
Table 28. Supported functions (continued)
Function name Description Page
RIGHT Returns a string that consists of the specified number of rightmost
bytes of a string
258
ROUND Returns a number rounded to the specified number of places to
the right or left of the decimal place
260
ROUND_TIMESTAMP Returns a timestamp rounded to the unit specified by the
timestamp format string
262
ROWID Returns a row ID representation of its argument 264
RTRIM Returns the characters of an argument with the trailing blanks
removed
265
SECOND Returns the second part of its argument 266
SIGN Returns the sign of an argument 267
SIN Returns the sine of an argument that is expressed as an angle in
radians
268
SINH Returns the hyperbolic sine of an argument that is expressed as
an angle in radians
269
SMALLINT Returns a small integer representation of its argument 270
SPACE Returns a string that consists of the number of blanks the
argument specifies
271
SQRT Returns the square root of its argument 272
STDDEV or STDDEV_POP Returns the standard deviation (/n) of a set of numbers 165
STDDEV_SAMP Returns the sample standard deviation (/n-1) of a set of numbers 166
STRIP Returns the characters of a string with the blanks (or specified
character) at the beginning, end, or both beginning and end of the
string removed
273
SUBSTR Returns a substring of a string 275
SUM Returns the sum of a set of numbers 167
TAN Returns the tangent of an argument that is expressed as an angle
in radians
277
TANH Returns the hyperbolic tangent of an argument that is expressed
as an angle in radians
278
TIME Returns a time derived from its argument 279
TIMESTAMP Returns a timestamp derived from its arguments 280
TIMESTAMP_FORMAT Returns a timestamp for a character string expression, using a
specified format to interpret the string
281
TRANSLATE Returns a string with one or more characters translated 282
TRUNCATE or TRUNC Returns a number truncated to the specified number of places t
o
the right or left of the decimal point
285
TRUNC_TIMESTAMP Returns a timestamp truncated to the unit specified by the
timestamp format string
286
UCASE or UPPER Returns a string with the characters converted to uppercase 287
VARCHAR Returns the varying-length character string representation of its
argument
288
VARCHAR_FORMAT Returns a character string representation of a timestamp, with th
e
string in a specified format
292
VARGRAPHIC Returns a graphic string representation of its argument 293
Built-in functions
156 SQL Reference
|
| |
|
|
| |
|
|
| |
|
Table 28. Supported functions (continued)
Function name Description Page
VARIANCE, VAR, or VAR_POP Returns the variance of a set of numbers 168
VARIANCE_SAMP or
VAR_SAMP
Returns the sample variance of a set of numbers 169
WEEK Returns an integer that represents the week of the year with
Sunday as the first day of the week
296
WEEK_ISO Returns an integer that represents the week of the year with
Monday as first day of a week
297
YEAR Returns the year part of its argument 298
Built-in functions
Chapter 3. Built-in functions 157
||
|
|
| |
Column functions
The following information applies to all built-in column functions, except for t
he
COUNT(*) and COUNT_BIG(*) variations of the COUNT and COUNT_BIG
functions.
The argument of a column function is a set of values derived from an expression.
The expression must include a column name and must not include another column
function. The scope of the set is a group or an intermediate result table as
explained in “Chapter 4. Queries” on page 299.
If a GROUP BY clause is specified in a query and the intermediate result from th
e
FROM, WHERE, GROUP BY, and HAVING clauses is the empty set, then the
column functions are not applied and the result of the query is the empty set.
If the GROUP BY clause is not specified in a query and the intermediate result s
et
of the FROM, WHERE, and HAVING clauses is the empty set, then the column
functions are applied to the empty set.
For example, the result of the following SELECT statement is the number of disti
nct
values of JOB for employees in department D11:
SELECT COUNT(DISTINCT JOB)
FROM DSN8710.EMP
WHERE WORKDEPT = D11 ;
The keyword DISTINCT is not considered an argument of the function but rather a
specification of an operation that is performed before the function is applied.
If
DISTINCT is specified, duplicate values are eliminated. If ALL is implicitly or
explicitly specified, duplicate values are not eliminated.
A column function can be used in a WHERE clause only if that clause is part of a
subquery of a HAVING clause and the column name specified in the expression is
a correlated reference to a group. If the expression includes more than one colu
mn
name, each column name must be a correlated reference to the same group.
The result of the COUNT and COUNT_BIG functions cannot be the null value. As
specified in the description of AVG, MAX, MIN, STDDEV, SUM, and VARIANCE, the
result is the null value when the function is applied to an empty set. However,
the
result is also the null value when the function is specified in an outer select
list, the
argument is given by an arithmetic expression, and any evaluation of the
expression causes an arithmetic exception (such as division by zero).
If the argument values of a column function are strings from a column with a fie
ld
procedure, the function is applied to the encoded form of the values and the res
ult
of the function inherits the field procedure.
Following in alphabetic order is a definition of each of the built-in column fun
ctions.
Column functions
158 SQL Reference
|
|
|
|
|
|
AVG
The schema is SYSIBM.
The AVG function returns the average of a set of numbers.
The argument values must be of any built-in numeric data type, and their sum mus
t
be within the range of the data type of the result.
The data type of the result is the same as the data type of the argument values,
except that the result is a large integer if the argument values are small integ
ers,
and the result is double precision floating-point if the argument values are sin
gle
precision floating-point. The result can be null.
If the data type of the argument values is decimal with precision p and scale s,
the
precision (P) and scale (S) of the result depend on p and the decimal precision
option:
v If p is greater than 15 or the DEC31 option is in effect, P is 31 and S is
max(0,28-p+s).
v Otherwise, P is 15 and S is 15-p+s.
The function is applied to the set of values derived from the argument values by
the
elimination of null values. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the average value of the set. If the type of the result is an integer,
the
fractional part of the average is lost. The order in which the summation part of
the
operation is performed is undefined but every intermediate result must be within
the
range of the result data type.
Example: Assuming DEC15, set the DECIMAL(15,2) variable AVERAGE to the
average salary in department D11 of the employees in the sample table
DSN8710.EMP.
EXEC SQL SELECT AVG(SALARY)
INTO :AVERAGE
FROM DSN8710.EMP
WHERE WORKDEPT = D11 ;

ALL
AVG( expression)
DISTINCT

AVG
Chapter 3. Built-in functions 159
COUNT
The schema is SYSIBM.
The COUNT function returns the number of rows or values in a set of rows or
values.
The argument values can be of any built-in data type other than a BLOB, CLOB, or
DBCLOB. If DISTINCT is used, the resulting expression cannot have a maximum
length greater than 255 for a character column and 127 for a graphic column.
The result is a large integer. The result cannot be null.
The argument of COUNT(expression) or COUNT(ALL expression) is a set of values.
The function is applied to the set of values derived from the argument values by
the
elimination of null values. The result is the number of non-null values in the s
et,
including duplicates.
The argument of COUNT(DISTINCT expression) is a set of values. The function is
applied to the set of values derived from the argument values by the elimination
of
null values and duplicate values. The result is the number of values in the set.
The argument of COUNT(*) is a set of rows. The result is the number of rows in t
he
set. Any row that includes only null values is included in the count.
Example 1: Set the integer host variable FEMALE to the number of females
represented in the sample table DSN8710.EMP.
EXEC SQL SELECT COUNT(*)
INTO :FEMALE
FROM DSN8710.EMP
WHERE SEX = F ;
Example 2: Set the integer host variable FEMALE_IN_DEPT to the number of
departments that have at least one female as a member.
EXEC SQL SELECT COUNT(DISTINCT WORKDEPT)
INTO :FEMALE_IN_DEPT
FROM DSN8710.EMP
WHERE SEX = F ;

ALL
COUNT( expression )
DISTINCT
*

COUNT
160 SQL Reference
|
|
|
|
COUNT_BIG
The schema is SYSIBM.
The COUNT_BIG function returns the number of rows or values in a set of rows or
values. It is similar to COUNT except that the result can be greater than the
maximum value of an integer.
The argument values can be of any built-in data type other than a BLOB, CLOB, or
DBCLOB. If DISTINCT is used, the resulting expression must not have a maximum
length greater than 255 for a character column or 127 for a graphic column.
The result of the function is a decimal number with precision 31 and scale 0. Th
e
result cannot be null.
The argument of COUNT_BIG(expression) or COUNT_BIG(ALL expression) is a set
of values. The function is applied to the set of values derived from the argumen
t
values by the elimination of null values. The result is the number of non-null v
alues
in the set, including duplicates.
The argument of COUNT_BIG(DISTINCT expression) is a set of values. The
function is applied to the set of values derived from the argument values by the
elimination of null and duplicate values. The result is the number of different
nonnull
values in the set.
The argument of COUNT_BIG(*) is a set of rows. The result is the number of rows
in the set. A row that includes only null values is included in the count.
Example 1: The examples for COUNT are also applicable for COUNT_BIG. Refer to
the COUNT examples and substitute COUNT_BIG for the occurrences of COUNT.
The results are the same except for the data type of the result.
Example 2: To create a sourced function that is similar to the built-in COUNT_BI
G
function, the definition of the sourced function must include the type of the co
lumn
that can be specified when the new function is invoked. In this example, the
CREATE FUNCTION statement creates a sourced function that takes a CHAR
column as input and uses COUNT_BIG to perform the counting. The result is
returned as a double precision floating-point number. The query shown counts the
number of unique departments in the sample employee table.
CREATE FUNCTION RICK.COUNT(CHAR()) RETURNS DOUBLE
SOURCE SYSIBM.COUNT_BIG(CHAR());
SET PATH RICK, SYSTEM PATH;
SELECT COUNT(DISTINCT WORKDEPT) FROM DSN8710.EMP;
The empty parenthesis in the parameter list for the new function (RICK.COUNT)
means that the input parameter for the new function is the same type as the inpu
t
parameter for the function named in the SOURCE clause. The empty parenthesis in

ALL
COUNT_BIG( expression )
DISTINCT
*

COUNT_BIG
Chapter 3. Built-in functions 161
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the parameter list in the SOURCE clause (SYSIBM.COUNT_BIG) means that when
DB2 uses function resolution to identify the source function, the attribute (in
this
example the length) is ignored for determining whether the data types match.
COUNT_BIG
162 SQL Reference
|
|
|
MAX
The schema is SYSIBM.
The MAX function returns the maximum value in a set of values.
The argument values can be of any built-in data type other than a BLOB, CLOB,
DBCLOB, or row ID. Character string arguments cannot have a maximum length
greater than 255, and graphic string arguments cannot have a maximum length
greater than 127.
The data type of the result and its other attributes (for example, the length an
d
CCSID of a string) are the same as the data type and attributes of the argument
values. The result can be null.
The function is applied to the set of values derived from the argument values by
the
elimination of null values.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the maximum value in the set.
The specification of DISTINCT has no effect on the result and is not advised.
Example 1: Set the DECIMAL(8,2) variable MAX_SALARY to the maximum monthly
salary of the employees represented in the sample table DSN8710.EMP.
EXEC SQL SELECT MAX(SALARY) / 12
INTO :MAX_SALARY
FROM DSN8710.EMP;
Example 2: Find the surname that comes last in the collating sequence for the
employees represented in the sample table DSN8710.EMP. Set the VARCHAR(15)
variable LAST_NAME to that surname.
EXEC SQL SELECT MAX(LASTNAME)
INTO :LAST_NAME
FROM DSN8710.EMP;

ALL
MAX( expression)
DISTINCT

MAX
Chapter 3. Built-in functions 163
MIN
The schema is SYSIBM.
The MIN function returns the minimum value in a set of values.
The argument values can be of any built-in data type other than a BLOB, CLOB,
DBCLOB, or row ID. Character string arguments cannot have a maximum length
greater than 255, and graphic string arguments cannot have a maximum length
greater than 127.
The data type of the result and its other attributes (for example, the length an
d
CCSID of a string) are the same as the data type and attributes of the argument
values. The result can be null.
The function is applied to the set of values derived from the argument values by
the
elimination of null values.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the minimum value in the set.
The specification of DISTINCT has no effect on the result and is not advised.
Example 1: Set the DECIMAL(15,2) variable MIN_SALARY to the minimum monthly
salary of the employees represented in the sample table DSN8710.EMP.
EXEC SQL SELECT MIN(SALARY) / 12
INTO :MIN_SALARY
FROM DSN8710.EMP;
Example 2: Find the surname that comes first in the collating sequence for the
employees represented in the sample table DSN8710.EMP. Set the VARCHAR(15)
variable FIRST_NAME to that surname.
EXEC SQL SELECT MIN(LASTNAME)
INTO :FIRST_NAME
FROM DSN8710.EMP;

ALL
MIN( expression)
DISTINCT

MIN
164 SQL Reference
STDDEV or STDDEV_POP
The schema is SYSIBM.
The STDDEV function returns the standard deviation (/n) of a set of numbers. The
formula that is used to calculate STDDEV is:
STDDEV = SQRT(VAR)
where SQRT(VAR) is the square root of the variance.
The argument values must each be the value of any built-in numeric data type, an
d
their sum must be within the range of the data type of the result.
The result of the function is double precision floating-point number. The result
can
be null.
Before the function is applied to the set of values derived from the argument va
lues,
null values are eliminated. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the standard deviation of the values in the set.
The order in which the values are aggregated is undefined, but every intermediat
e
result must be within the range of the result data type.
Example: Using sample table DSN8710.EMP, set the host variable DEV, which is
defined as double precision floating-point, to the standard deviation of the sal
aries
for the employees in department A00 (WORKDEPT= A00 ).
SELECT STDDEV(SALARY)
INTO :DEV
FROM DSN8710.EMP
WHERE WORKDEPT = A00 ;
For this example, host variable DEV is set to a double precision float-pointing
number with an approximate value of 9742.43.

ALL (1)
STDDEV( expression)
DISTINCT

Notes:
1 STDDEV_POP can be specified as an alternative to STDDEV.
STDDEV
Chapter 3. Built-in functions 165
STDDEV_SAMP
The schema is SYSIBM.
The STDDEV_SAMP function returns the standard deviation (/n-1) of a set of
numbers. The formula that is used to calculate STDDEV_SAMP is:
STDDEV_SAMP = SQRT(VAR_SAMP)
where SQRT(VAR_SAMP) is the square root of the sample variance.
The argument values must each be the value of any built-in numeric data type, an
d
their sum must be within the range of the data type of the result.
The result of the function is a double precision floating-point number. The resu
lt can
be null.
Before the function is applied to the set of values derived from the argument va
lues,
null values are eliminated. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, or a set with only one row, the resu
lt is
the null value. Otherwise, the result is the sample standard deviation of the va
lues
in the set.
The order in which the values are aggregated is undefined, but every intermediat
e
result must be within the range of the result data type.
Example: Using sample table DSN8710.EMP, set the host variable DEV, which is
defined as double precision floating-point, to the sample standard deviation of
the
salaries for the employees in department A00 (WORKDEPT= A00 ).
SELECT STDDEV_SAMP(SALARY)
INTO :DEV
FROM DSN8710.EMP
WHERE WORKDEPT = ’A00’;
For this example, host variable DEV is set to a double precision float-pointing
number with an approximate value of +1.08923711835394E+004.

ALL
STDDEV_SAMP( expression)
DISTINCT

STDDEV_SAMP
166 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
SUM
The schema is SYSIBM.
The SUM function returns the sum of a set of numbers.
The argument values must be of any built-in numeric data type, and their sum mus
t
be within the range of the data type of the result.
The data type of the result is the same as the data type of the argument values,
except that the result is a large integer if the argument values are small integ
ers,
and the result is double precision floating-point if the argument values are sin
gle
precision floating-point. The result can be null.
If the data type of the argument values is decimal, the scale of the result is t
he
same as the scale of the argument values, and the precision of the result depend
s
on the precision of the argument values and the decimal precision option:
v If the precision of the argument values is greater than 15 or the DEC31 option
is
in effect, the precision of the result is min(31,P+10), where P is the precision
of
the argument values.
v Otherwise, the precision of the result is 15.
The function is applied to the set of values derived from the argument values by
the
elimination of null values. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the sum of the values in the set. The order in which the summation is
performed is undefined but every intermediate result must be within the range of
the
result data type.
Example: Set the large integer host variable INCOME to the total income from all
sources (salaries, commissions, and bonuses) of the employees represented in the
sample table DSN8710.EMP. If DEC31 is not in effect, the resultant sum is
DECIMAL(15,2) because all three columns are DECIMAL(9,2).
EXEC SQL SELECT SUM(SALARY+COMM+BONUS)
INTO :INCOME
FROM DSN8710.EMP;

ALL
SUM( expression)
DISTINCT

SUM
Chapter 3. Built-in functions 167
VARIANCE, VAR, or VAR_POP
The schema is SYSIBM.
The VARIANCE or VAR function returns the variance of a set of numbers. The
result is the biased variance (/n) of the set of numbers. The formula used to
calculate VARIANCE is:
VARIANCE = SUM(X**2)/COUNT(X) - (SUM(X)/COUNT(X))**2
The argument values must be of any built-in numeric type, and their sum must be
within the range of the data type of the result.
The result of the function is a double precision floating-point number. The resu
lt can
be null.
Before the function is applied to the set of values derived from the argument va
lues,
null values are limited. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, the result is the null value. Otherw
ise, the
result is the variance of the values in the set.
The order in which the values are added is undefined, but every intermediate res
ult
must be within the range of the result data type.
Example: Using sample table DSN8710.EMP, set host variable VARNCE, which is
defined as double precision floating-point, to the variance of the salaries (SAL
ARY)
for those employees in department (WORKDEPT) A00 .
SELECT VARIANCE(SALARY)
INTO :VARNCE
FROM DSN8710.EMP
WHERE WORKDEPT = A00 ;
The result in VARNCE is set to a double precision-floating point number with an
approximate value of 94915000.00.

ALL (1)
VARIANCE ( expression)
VAR DISTINCT

Notes:
1 VAR_POP can be specified as an alternative to VARIANCE or VAR.
VARIANCE or VAR
168 SQL Reference
VARIANCE_SAMP or VAR_SAMP
The schema is SYSIBM.
The VARIANCE_SAMP or VAR_SAMP function returns the sample variance of a set
of numbers. The result is the sample variance (/n-1) of the set of numbers. The
formula used to calculate VARIANCE is:
VAR_SAMP = (SUM(X**2) - ((SUM(X)**2) / (COUNT(*)))) / (COUNT(*) - 1)
The argument values must be of any built-in numeric type, and their sum must be
within the range of the data type of the result.
The result of the function is a double precision floating-point number. The resu
lt can
be null.
Before the function is applied to the set of values derived from the argument va
lues,
null values are limited. If DISTINCT is specified, duplicate values are also
eliminated.
If the function is applied to an empty set, or a set with only one row, the resu
lt is
the null value. Otherwise, the result is the variance of the values in the set.
The order in which the values are added is undefined, but every intermediate res
ult
must be within the range of the result data type.
Example: Using sample table DSN8710.EMP, set host variable VARNCE, which is
defined as double precision floating-point, to the sample variance of the salari
es
(SALARY) for those employees in department (WORKDEPT) A00 .
SELECT VARIANCE_SAMP(SALARY)
INTO :VARNCE
FROM DSN8710.EMP
WHERE WORKDEPT = ’A00’;
The result in VARNCE is set to a double precision-floating point number with an
approximate value of 118643750.

ALL
VARIANCE_SAMP ( expression)
VAR_SAMP DISTINCT

VARIANCE_SAMP or VAR_SAMP
Chapter 3. Built-in functions 169
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
Scalar functions
A built-in scalar function can be used wherever an expression can be used.
However, the restrictions that apply to the use of expressions and column functi
ons
also apply when an expression or column function is used within a scalar functio
n.
For example, the argument of a scalar function can be a column function only if
a
column function is allowed in the context in which the scalar function is used.
If the argument of a scalar function is a string from a column with a field proc
edure,
the function applies to the decoded form of the value and the result of the func
tion
does not inherit the field procedure.
Example: The following SELECT statement calls for the employee number, last
name, and age of each employee in department D11 in the sample table
DSN8710.EMP. To obtain the ages, the scalar function YEAR is applied to the
expression:
CURRENT DATE - BIRTHDATE
in each row of DSN8710.EMP for which the employee represented is in department
D11:
SELECT EMPNO, LASTNAME, YEAR(CURRENT DATE - BIRTHDATE)
FROM DSN8710.EMP
WHERE WORKDEPT = D11 ;
Following in alphabetic order is the definition of each of the built-in scalar f
unctions.
Scalar functions
170 SQL Reference
ABS or ABSVAL
The schema is SYSIBM.
The ABS function returns the absolute value of the argument.
The argument is an expression that returns a value of any built-in numeric data
type.
The result of the function has the same data type and length attribute as the
argument. The result can be null. If the argument is null, the result is the nul
l value.
Example: Assume that host variable PROFIT is a large integer with a value of
-50000. The following statement returns a large integer with a value of 50000.
SELECT ABS(:PROFIT)
FROM SYSIBM.SYSDUMMY1;
 ABS ( expression )
ABSVAL

ABS
Chapter 3. Built-in functions 171
ACOS
The schema is SYSIBM.
The ACOS function returns the arccosine of the argument as an angle expressed in
radians. The ACOS and COS functions are inverse operations.
The argument is an expression whose value is a number in the range of -1 to 1,
and has any built-in numeric data type. If the argument is not a double precisio
n
floating-point number, it is converted to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable ACOSINE is DECIMAL(10,9) with a value of
0.070737202. The following statement:
SELECT ACOS(:ACOSINE)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 1.
49.
 ACOS(expression) 
ACOS
172 SQL Reference
ADD_MONTHS
The schema is SYSIBM.
The ADD_MONTHS function returns a date that represents date-expression plus
expression months.
date-expression must be a date, a timestamp, or a valid string representation of
a
date or timestamp. A string representation must not be a BLOB, CLOB, or
DBCLOB, and must have an actual length that is not greater than 255 bytes. For
the valid formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a DATE. The result can be null; if any argument is
null,
the result is the null value.
If date-expression is the last day of the month or if the resulting month has fe
wer
days than the day component of date-expression, then the result is the last day
of
the resulting month. Otherwise, the result has the same day component as
date-expression.
expression can be any zero-scale numeric value.
Example 1: Assume today is January 31, 2000. Set the host variable ADD_MONTH
with the last day of January plus 1 month.
SET :ADD_MONTH = ADD_MONTHS(LAST_DAY(CURRENT_DATE), 1);
The host variable ADD_MONTH is set with the value representing the end of
February, 2000-02-29.
Example 2: Assume DATE is a host variable with the value July 27, 1965. Set the
host variable ADD_MONTH with the value of that day plus 3 months.
SET :ADD_MONTH = ADD_MONTHS(:DATE,3);
The host variable ADD_MONTH is set with the value representing the day plus 3
months, 1965-10-27.
Example 3: It is possible to achieve similar results with the ADD_MONTHS functio
n
and date arithmetic. The following examples demonstrate the similarities and
contrasts.
SET :DATEHV = DATE( 2000-2-28 ) + 4 MONTHS;
SET :DATEHV = ADD_MONTHS( 2000-2-28 , 4);
In both cases, the host variable DATEHV is set with the value ’2000–06–28’.
Now consider the same examples but with the date ’2000–2–29’ as the argument.
SET :DATEHV = DATE( 2000-2-29 ) + 4 MONTHS;
The host variable DATEHV is set with the value ’2000–06–29’.
SET :DATEHV = ADD_MONTHS( 2000-2-29 , 4);
 ADD_MONTHS(date-expression,expression) 
ADD_MONTHS
Chapter 3. Built-in functions 173
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The host variable DATEHV is set with the value ’2000–06–30’.
In this case, the ADD_MONTHS function returns the last day of the month, which i
s
June 30, 2000, instead of June 29, 2000. The reason is that February 29 is the l
ast
day of the month. So, the ADD_MONTHS function returns the last day of June.
ADD_MONTHS
174 SQL Reference
|
|
|
|
ASIN
The schema is SYSIBM.
The ASIN function returns the arcsine of the argument as an angle expressed in
radians. The ASIN and SIN functions are inverse operations.
The argument is an expression whose value is a number in the range of -1 to 1,
and has any built-in numeric data type. If the argument is not a double precisio
n
floating-point number, it is converted to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable ASINE is DECIMAL(10,9) with a value of
0.997494987. The following statement:
SELECT ASIN(:ASINE)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 1.
50.
 ASIN(expression) 
ASIN
Chapter 3. Built-in functions 175
ATAN
The schema is SYSIBM.
The ATAN function returns the arctangent of the argument as an angle expressed i
n
radians. The ATAN and TAN functions are inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable ATANGENT is DECIMAL(10,8) with a value of
14.10141995. The following statement:
SELECT ATAN(:ATANGENT)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 1.
50.
 ATAN(expression) 
ATAN
176 SQL Reference
ATANH
The schema is SYSIBM.
The ATANH function returns the hyperbolic arc tangent of the argument as an angl
e
expressed in radians. The ATANH and TANH functions are inverse operations.
The argument is an expression whose value is a number in the range of -1 to 1,
and has any built-in numeric data type. If the argument is not a double precisio
n
floating-point number, it is converted to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HATAN is DECIMAL(10,9) with a value of
0.905148254. The following statement:
SELECT ATANH(:HATAN)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 1.
50.
 ATANH(expression) 
ATANH
Chapter 3. Built-in functions 177
ATAN2
The schema is SYSIBM.
The ATAN2 function returns the arctangent of x and y coordinates as an angle
expressed in radians. The first and second arguments specify the x and y
coordinates, respectively.
Each argument is an expression that returns the value of any built-in numeric da
ta
type. Both arguments must not be 0. Any argument that is not a double precision
floating-point number is converted to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if any argument is null, the result is the null value.
Example: Assume that host variables HATAN2A and HATAN2B are DOUBLE host
variables with values of 1 and 2, respectively. The following statement:
SELECT ATAN2(:HATAN2A,:HATAN2B)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of
1.1071487.
 ATAN2(expression1,expression2) 
ATAN2
178 SQL Reference
BLOB
The schema is SYSIBM.
The BLOB function returns a BLOB representation of a string of any type or a row
ID type.
expression
An expression whose value is a character string, graphic string, binary string,
or
a row ID type.
integer
An integer value specifying the length attribute of the resulting BLOB data type
.
The value must be an integer between 0 and the maximum length of a BLOB.
Do not specify integer if expression is a row ID type.
If you do not specify integer, the length attribute of the result is the same as
the
length attribute of expression, except when the input is graphic data. In this
case, the length attribute of the result is twice the length of expression.
The result of the function is a BLOB. If the first argument can be null, the res
ult can
be null; if the first argument is null, the result is the null value.
The actual length of the result is the minimum of the length attribute of the re
sult
and the actual length of expression (or twice the length of expression when the
input is graphic data). If the length of expression is greater than the length
specified, truncation is performed. A warning is returned unless the first input
argument is a character string and all the truncated characters are blanks, or t
he
first input argument is a graphic string and all the truncated characters are
double-byte blanks.
Example 1: The following function returns a BLOB for the string This is a BLOB
.
SELECT BLOB( This is a BLOB )
FROM SYSIBM.SYSDUMMY1;
Example 2: The following function returns a BLOB for the large object that is
identified by locator myclob_locator.
SELECT BLOB(:myclob_locator)
FROM SYSIBM.SYSDUMMY1;
Example 3: Assume that a table has a BLOB column named TOPOGRAPHIC_MAP
and a VARCHAR column named MAP_NAME. Locate any maps that contain the
string Engles Island and return a single binary string with the map name
concatenated in front of the actual map.
SELECT BLOB(MAP_NAME || : ) || TOPOGRAPHIC_MAP
FROM ONTARIO_SERIES_4
WHERE TOPOGRAPHIC_MAP LIKE BLOB( %Engles Island% )
 BLOB(expression )
, integer

BLOB
Chapter 3. Built-in functions 179
CCSID_ENCODING
The schema is SYSIBM.
The CCSID_ENCODING function returns the encoding scheme of a CCSID in the
form of a character string with a value of one of the following: ASCII, EBCDIC,
UNICODE, or UNKNOWN.
The argument can be of any built-in data type other than a character string with
a
maximum length greater than 255 or a graphic string with a length greater than 1
27.
It cannot be a BLOB, CLOB, or DBCLOB.
The result of the function is a fixed-length character string of length 8, which
is
padded on the right if necessary. If the argument can be null, the result can be
null.
If the argument is null, the result is the null value.
If another string data from a table or view is selected by a query, the encoding
scheme of that string determines the resulting encoding scheme. The resulting
CCSID for string data is the appropriate CCSID for the encoding scheme of the
statement. If there is no other string data from a table or a view in the query,
the
default encoding scheme is used.
Example 1: The following function returns a CCSID with a value for EBCDIC data.
SELECT CCSID_ENCODING(37) AS CCSID
FROM SYSIBM.SYSDUMMY1;
Example 2: The following function returns a CCSID with a value for ASCII data.
SELECT CCSID_ENCODING(850) AS CCSID
FROM SYSIBM.SYSDUMMY1;
Example 3: The following function returns a CCSID with a value for Unicode data.
SELECT CCSID_ENCODING(1208) AS CCSID
FROM SYSIBM.SYSDUMMY1;
Example 4: The following function returns a CCSID with a value of UNKNOWN.
SELECT CCSID_ENCODING(1) AS CCSID
FROM SYSIBM.SYSDUMMY1;
 CCSID_ENCODING(expression) 
CCSID_ENCODING
180 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
||
|
||
|
||
|
CEIL or CEILING
The schema is SYSIBM.
The CEIL or CEILING function returns the smallest integer value that is greater
than
or equal to the argument.
The argument is an expression that returns a value of any built-in numeric data
type.
The result of the function has the same data type and length attribute as the
argument except that the scale is 0 if the argument is DECIMAL. For example, an
argument with a data type of DECIMAL(5,5) results in DECIMAL(05,0). The result
can be null. If the argument is null, the result is the null value.
Example 1: The following statement shows the use of CEILING on positive and
negative values:
SELECT CEILING(3.5), CEILING(3.1), CEILING(-3.1), CEILING(-3.5)
FROM FROM SYSIBM.SYSDUMMY1;
This example returns: 04., 04., -03., -03.
Example 2: Using sample table DSN8710.EMP, find the highest monthly salary for
all the employees. Round the result up to the next integer. The SALARY column
has a decimal data type.
SELECT CEIL(MAX(SALARY)/12)
FROM DSN8710.EMP;
This example returns 04396. because the highest paid employee is Christine Haas
who earns $52750.00 per year. Her average monthly salary before applying the
CEIL function is 4395.83.
 CEIL ( expression )
CEILING

CEIL or CEILING
Chapter 3. Built-in functions 181
CHAR
The schema is SYSIBM.
The CHAR function returns a fixed-length character string representation of one
of
the following values:
v Datetime value if the first argument is a date, time, or timestamp
v Character string value if the first argument is any type of character string
v Integer number if the first argument is a small or large integer
v Decimal number if the first argument is a decimal number
v Floating-point number if the first argument is a single or double precision
floating-point number
v Row ID value if the first argument is a row ID
The result of the function is a fixed-length character string (CHAR).
Datetime to Character:
 CHAR(datetime-expression )
, ISO
USA
EUR
JIS
LOCAL

Character to Character:
 CHAR(character-expression )
, integer

Integer to Character:
 CHAR(integer-expression) 
Decimal to Character:
 CHAR(decimal-expression )
, decimal-character

Floating-Point to Character:
 CHAR(floating-point-expression) 
Row ID to Character:
 CHAR(row-ID-expression) 
CHAR
182 SQL Reference
If the first argument can be null, the result can be null. If the first argument
is null,
the result is the null value.
Datetime to Character
datetime-expression
An expression whose value has one of the following three data types:
date The result is the character string representation of the date in the
format that is specified by the second argument. If the second argument
is omitted, the DATE precompiler option, if one is provided, or else field
DATE FORMAT on installation panel DSNTIP4 specifies the format. If
the format is to be LOCAL, field LOCAL DATE LENGTH on installation
panel DSNTIP4 specifies the length of the result. Otherwise, the length
of the result is 10.
LOCAL denotes the local format at the DB2 that executes the SQL
statement. If LOCAL is used for the format, a date exit routine must be
installed at that DB2.
An error occurs if the second argument is specified and is not a valid
value.
time The result is the character string representation of the time in the format
specified by the second argument. If the second argument is omitted,
the TIME precompiler option, if one is provided, or else field TIME
FORMAT on installation panel DSNTIP4 specifies the format. If the
format is to be LOCAL, the field LOCAL TIME LENGTH on installation
panel DSNTIP4 specifies the length of the result. Otherwise, the length
of the result is 8.
LOCAL denotes the local format at the DB2 that executes the SQL
statement. If LOCAL is used for the format, a time exit routine must be
installed at that DB2.
An error occurs if the second argument is specified and is not a valid
value.
timestamp
The result is the character string representation of the timestamp. The
length of the result is 26. The second argument must not be specified.
The CCSID of the result is the SBCS CCSID of the appropriate encoding
scheme.
Character to Character
character-expression
An expression whose value is any type of character string.
string-expression
An expression whose value is any type of string, except BLOB.
integer
The length attribute for the resulting fixed-length character string. The value
must be between 1 and 255. If the length is not specified, the length of the
result is the same as the length of string-expression, which must be 255 bytes
or less but must not be an empty string. If the string-expression is a graphic
string, the length of the result is (3 * length(string-expression)).
CHAR
Chapter 3. Built-in functions 183
|
|
|
|
|
If the length of string-expression is less than the length attribute of the resu
lt, the
result is padded with blanks to the length of the result. If the length of
string-expression is greater than the length attribute of the result, the result
is
truncated. Unless all of the truncated characters are blanks, a warning is retur
ned.
If string-expression is an empty string, an error occurs.
If character-expression is bit data, the result is bit data. Otherwise, the CCSI
D of
the result is the same as the CCSID of character-expression.
Integer to Character
integer-expression
An expression whose value is an integer data type (SMALLINT or INTEGER).
The result is the fixed-length character string representation of the argument i
n the
form of an SQL integer constant. The result consists of n characters that are th
e
significant digits that represent the value of the argument with a preceding min
us
sign if the argument is negative. The result is left justified, and its length d
epends
on whether the argument is a small or large integer:
v For a small integer, the length of the result is 6. If the number of character
s in
the result is less than 6, the result is padded on the right with blanks to a le
ngth
of 6.
v For a large integer, the length of the result is 11; if the number of characte
rs in
the result is less than 11, the result is padded on right with blanks to a lengt
h of
11.
A positive value always includes one trailing blank.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Decimal to Character
decimal-expression
An expression whose value is a decimal data type. To specify a different
precision and scale, you can use the DECIMAL scalar function first to make the
change.
decimal-character
Specifies the single-byte character constant (CHAR or VARCHAR only) that is
used to delimit the decimal digits in the resulting character string. Do not spe
cify
a digit, plus ( + ), minus ( −') or blank. The default is a period ('.') or comma
(,).
For information on what factors govern the choice, see “Options affecting SQL”
on page 145.
The result is the fixed length character string representation of the argument i
n the
form of an SQL decimal constant. The result includes a decimal character and p
digits, where p is the precision of the decimal expression. If the argument is
negative, the first character of the result is a minus sign. Otherwise, the firs
t
character is a blank, which means that a positive value always has one leading
blank.
The length of the result is 2+p, where p is the precision of the decimal express
ion.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Floating Point to Character
CHAR
184 SQL Reference
floating point expression
An expression whose value is a floating point data type (DOUBLE or REAL).
The result is the fixed length character string representation of the argument i
n the
form of a floating point constant. The length of the result is 24 bytes.
If the argument is negative, the first character of the result is a minus sign.
Otherwise, the first character is a digit. If the value of the argument is zero,
the
result is 0E0. Otherwise, the result includes the smallest number of characters
that
can represent the value of the argument such that the mantissa consists of a sin
gle
digit, other than zero, followed by a period and a sequence of digits.
If the number of characters in the result is less than 24, the result is padded
on the
right with blanks to length of 24.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Row ID to Character
row ID expression
An expression whose value is a row ID data type.
The result is the fixed length character string representation of the argument.
It is
bit data and does not have an associated CCSID.
The length of the result is 40. If the length of row ID expression is less than
40, the
result is padded on the right with hexadecimal zeroes to length of 40.
Example 1: HIREDATE is a DATE column in sample table DSN8710.EMP. When it
represents 15 December 1976 (as it does for employee 140):
EXEC SQL SELECT CHAR(HIREDATE, USA)
INTO :DATESTRING
FROM DSN8710.EMP
WHERE EMPNO = '000140';
returns the string value '12/15/1976' in character string variable DATESTRING.
Example 2: Host variable HOUR has a data type of DECIMAL(6,0) and contains a
value of 50000. Interpreted as a time duration, this value is 5 hours. Assume th
at
STARTING is a TIME column in some table. Then, when STARTING represents 17
hours, 30 minutes, and 12 seconds after midnight:
CHAR(STARTING+:HOURS, USA)
returns the value '10:30 PM'.
Example 3: Assume that RECEIVED is defined as a TIMESTAMP column in table
TABLEY. When the value of the date portion of RECEIVED represents 10 March
1997 and the time portion represents 6 hours and 15 seconds after midnight, this
example:
SELECT CHAR(RECEIVED)
FROM TABLEY
WHERE INTCOL = 1234;
returns the string value '1997 03 10 06.00.15.000000'.
CHAR
Chapter 3. Built in functions 185
Example 4: For sample table DSN8710.EMP, the following SQL statement sets the
host variable AVERAGE, which is defined as CHAR(33), to the character string
representation of the average employee salary.
EXEC SQL SELECT CHAR(AVG(SALARY))
INTO :AVERAGE
FROM DSN8710.EMP;
With DEC31, the result of AVG applied to a decimal number is a decimal number
with a precision of 31 digits. The only host languages in which such a large dec
imal
variable can be defined are Assembler and C. For host languages that do not
support such large decimal numbers, use the method shown in this example.
Example 5: For the rows in sample table DSN8710.EMP, return the values in
column LASTNAME, which is defined as VARCHAR(15), as a fixed length character
string and limit the length of the results to 10 characters.
SELECT CHAR(LASTNAME,10)
FROM DSN8710.EMP;
For rows that have a LASTNAME with a length greater than 10 characters
(excluding trailing blanks), a warning that the value is truncated is returned.
Example 6: For the rows in sample table DSN8710.EMP, return the values in
column EDLEVEL, which is defined as SMALLINT, as a fixed length character
string.
SELECT CHAR(EDLEVEL)
FROM DSN8710.EMP;
An EDLEVEL of 18 is returned as CHAR(6) value '18 ' (18 followed by four
blanks).
Example 7: In sample table DSN8710.EMP, the SALARY column is defined as
DECIMAL(9,2). For those employees who have a salary of 18357.50, return the hire
date and the salary, using a comma as the decimal character in the salary
(18357,50).
SELECT HIREDATE, CHAR(SALARY, ',')
FROM DSN8710.EMP
WHERE SALARY = 18357.50;
The salary is returned as the string value '00018357,50'.
Example 8: Repeat the scenario in Example 7 except subtract the SALARY column
from 20000.25 and return the salary with the default decimal character.
SELECT HIREDATE, CHAR (20000.25  SALARY)
FROM DSN8710.EMP
WHERE SALARY = 18357.50;
The salary is returned as the string value '0001642.75'.
Example 9: Assume that host variable SEASONS_TICKETS is defined as INTEGER
and has a value of 10000. Use the DECIMAL and CHAR functions to change the
value into the character string '10000.00'.
SELECT CHAR(DECIMAL(:SEASONS_TICKETS,7,2))
FROM SYSIBM.SYSDUMMY1;
CHAR
186 SQL Reference
Example 10: Assume that columns COL1 and COL2 in table T1 are both defined as
REAL and that T1 contains a single row with the values 7.1E+1 and 7.2E+2 for the
two columns. Add the two columns and represent the result as a character string.
SELECT CHAR(COL1+ COL2)
FROM T1;
The result is the character value '1.43E2 '.
CHAR
Chapter 3. Built in functions 187
CLOB
The schema is SYSIBM.
The CLOB function returns a CLOB representation of a string.
string expression
An expression whose value is a string. If string expression is bit data, an erro
r
occurs. Use a BLOB data type for bit data.
integer
The length attribute for the resulting fixed length string. An integer value
specifying the length attribute of the resulting CLOB data type. The value must
be between 0 and the maximum length of a CLOB.
If you do not specify integer, the length attribute of the result is the same as
the
length attribute of string expression. If the string expression is a graphic str
ing,
the length of the result is (3 * length(string expression)).
The result of the function is a CLOB. If the first argument can be null, the res
ult can
be null; if the first argument is null, the result is the null value.
The actual length of the result is the minimum of the length attribute of the re
sult
and the actual length of string expression. If the length of string expression i
s
greater than the length specified, the result is truncated. Unless all of the tr
uncated
characters are blanks, a warning is returned.
The subtype and CCSID of the result are determined as follows:
v If string expression is character SBCS data, the result is SBCS data and the
CCSID is CCSID for the encoding scheme of the SQL statement.
v If the first argument is mixed data, the result is mixed data and the CCSID is
the
CCSID for the encoding scheme of the SQL statement.
Example: The following function returns a CLOB for the string 'This is a CLOB'.
SELECT CLOB('This is a CLOB')
FROM SYSIBM.SYSDUMMY1;
 CLOB(string expression )
, integer

CLOB
188 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
COALESCE
The schema is SYSIBM.
The COALESCE function returns the first argument that is not null. VALUE can be
used as a synonym for COALESCE. Use COALESCE to conform to the SQL
standard.
The arguments must be compatible. For more information on compatibility, refer t
o
the compatibility matrix in Table 9 on page 65. The arguments can be of either a
built-in or user-defined data type.21
The arguments are evaluated in the order in which they are specified, and the re
sult
of the function is the first argument that is not null. The result can be null o
nly if all
arguments can be null. The result is null only if all arguments are null.
The selected argument is converted, if necessary, to the attributes of the resul
t. The
attributes of the result are determined using the “Rules for result data types” on
page 77. If the COALESCE function has more than two arguments, the rules are
applied to the first two arguments to determine a candidate result type. The rul
es
are then applied to that candidate result type and the third argument to determi
ne
another candidate result type. This process continues until all arguments are
analyzed and the final result type is determined.
The COALESCE function can also handle a subset of the functions provided by
CASE expressions. The result of using COALESCE(e1,e2) is the same as using the
expression:
CASE WHEN e1IS NOT NULL THEN e1ELSE e2 END
Example 1: Assume that SCORE1 and SCORE2 are SMALLINT columns in table
GRADES, and that nulls are allowed in SCORE1 but not in SCORE2. Select all the
rows in GRADES for which SCORE1 + SCORE2 > 100, assuming a value of 0 for
SCORE1 when SCORE1 is null.
SELECT * FROM GRADES
WHERE COALESCE(SCORE1,0) + SCORE2 > 100;
Example 2: Assume that a table named DSN8710.EMP contains a DATE column
named HIREDATE, and that nulls are allowed for this column. The following query
selects all rows in DSN8710.EMP for which the date in HIREDATE is either
unknown (null) or earlier than 1 January 1960.
SELECT * FROM DSN8710.EMP
WHERE COALESCE(HIREDATE,DATE( 1959-12-31 )) < 1960-01-01 ;
21. This function cannot be used as a source function when creating a user-defin
ed function. Because it accepts any compatible data
types as arguments, it is not necessary to create additional signatures to suppo
rt user-defined distinct types.
 COALESCE (expression  ,expression )
VALUE

COALESCE
Chapter 3. Built-in functions 189
The predicate could also be coded as VALUE(HIREDATE, 1959-12-31 ) because for
comparison purposes, a string representation of a date can be compared to a date
.
Example 3: Assume that for the years 1993 and 1994 there is a table that records
the sales results of each department. Each table, S1993 and S1994, consists of a
DEPTNO column and a SALES column, neither of which can be null. The following
query provides the sales information for both years.
SELECT COALESCE(S1993.DEPTNO,S1994.DEPTNO) AS DEPT, S1993.SALES, S1994.SALES
FROM S1993 FULL JOIN S1994 ON S1993.DEPTNO = S1994.DEPTNO
ORDER BY DEPT;
The full outer join ensures that the results include all departments, regardless
of
whether they had sales or existed in both years. The COALESCE function allows
the two join columns to be combined into a single column, which enables the
results to be ordered.
COALESCE
190 SQL Reference
CONCAT
The schema is SYSIBM.
You can use either the keyword CONCAT keyword or vertical bars (||) to invoke th
e
concatenation function. Vertical bars (or the characters that must be used in pl
ace
of vertical bars in some countries) can cause parsing errors in statements passe
d
from one DBMS to another. The problem occurs if the statement undergoes
character conversion with certain combinations of source and target CCSIDs. Thus
,
CONCAT is the preferable syntax.
The CONCAT function, which is identical to the CONCAT operator, links two string
arguments to form a string expression. The two arguments must be compatible
strings. For more information on compatibility, refer to the compatibility matri
x in
Table 9 on page 65.
The result of the function is a string that consists of the first argument strin
g
followed by the second. If either argument can be null, the result can be null;
if
either is null, the result is the null value.
See “With the concatenation operator” on page 111 for more information.
Example: Using sample table DSN8710.EMP, concatenate column FIRSTNME with
column LASTNAME. Both columns are defined as varying-length character strings.
SELECT CONCAT(FIRSTNME, LASTNAME)
FROM DSN8710.EMP;
 CONCAT (expression1,expression2)
(1)
″||″

Notes:
1 The vertical bars (||) must be surrounded by the SQL escape character in effec
t (″ or ’).
CONCAT
Chapter 3. Built-in functions 191
#
#
#
COS
The schema is SYSIBM.
The COS function returns the cosine of the argument, where the argument is an
angle expressed in radians. The COS and ACOS functions are inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable COSINE is DECIMAL(2,1) with a value of 1.5.
The following statement:
SELECT COS(:COSINE)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 0.
07.
 COS(expression) 
COS
192 SQL Reference
COSH
The schema is SYSIBM.
The COSH function returns the hyperbolic cosine of the argument, where the
argument is an angle expressed in radians.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HCOS is DECIMAL(2,1) with a value of 1.5.
The following statement:
SELECT COSH(:HCOS)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 2.
35.
 COSH(expression) 
COSH
Chapter 3. Built-in functions 193
DATE
The schema is SYSIBM.
The DATE function returns a date derived from its argument.
The argument must be a date, a timestamp, a valid string representation of a dat
e
or timestamp, a positive number with a built-in data type that is less than or e
qual
to 3652059, or a string of length 7. An argument with a string data type must no
t be
a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. For the valid formats of string representations of dates and
timestamps, see “String representations of datetime values” on page 57.
If the argument is a string, the result is the date represented by the string. I
f the
CCSID of the string is not the same as the corresponding default CCSID at the
server, the string is first converted to that CCSID.
The result of the function is a date. If the argument can be null, the result ca
n be
null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a timestamp, the result is the date part of the timestamp.
If the argument is a date, the result is that date.
If the argument is a number, the result is the date that is n-1 days after
January 1, 0001, where n is the integral part of the number.
If the argument is a string, the result is the date represented by the string. I
f
the CCSID of the string is not the same as the corresponding default CCSID at
the server, the string is first converted to that CCSID.
Example 1: Assume that RECEIVED is a TIMESTAMP column in some table, and
that one of its values is equivalent to the timestamp 1988-12-25-17.12.30.00000
0 .
Then, for this value:
DATE(RECEIVED)
returns the internal representation of 25 December 1988.
Example 2: Assume that DATCOL is a CHAR(7) column in some table, and that one
of its values is the character string 1989061 . Then, for this value:
DATE(DATCOL)
returns the internal representation of 2 March 1989.
Example 3: DB2 recognizes 1989-03-02 as the ISO representation of 2 March
1989. Therefore:
DATE( 1989-03-02 )
returns the internal representation of 2 March 1989.
 DATE(expression) 
DATE
194 SQL Reference
|
|
|
|
|
|
|
|
|
DAY
The schema is SYSIBM.
The DAY function returns the day part of its argument.
The argument must be a date, timestamp, date duration, timestamp duration, or
valid string representation of a date or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. For the valid formats of string representations of dates and
timestamps, see “String representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules for the function depend on the data type of the argument:
If the argument is a date, timestamp, or string representation of either, the
result is the day part of the value, which is an integer between 1 and 31.
If the argument is a date duration or timestamp duration, the result is the
day part of the value, which is an integer between -99 and 99. A nonzero result
has the same sign as the argument.
Example 1: Set the INTEGER host variable DAYVAR to the day of the month on
which employee 140 in the sample table DSN8710.EMP was hired.
EXEC SQL SELECT DAY(HIREDATE)
INTO :DAYVAR
FROM DSN8710.EMP
WHERE EMPNO = 000140 ;
Example 2: Assume that DATE1 and DATE2 are DATE columns in the same table.
Assume also that for a given row in this table, DATE1 and DATE2 represent the
dates 15 January 2000 and 31 December 1999, respectively. Then, for the given
row:
DAY(DATE1- DATE2)
returns the value 15.
 DAY(expression) 
DAY
Chapter 3. Built-in functions 195
|
|
|
|
|
DAYOFMONTH
The schema is SYSIBM.
The DAYOFMONTH function returns the day part of its argument. The function is
similar to the DAY function, except DAYOFMONTH does not support a date or
timestamp duration as an argument.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer between 1 and 31, which represents
the
day part of the value. If the argument can be null, the result can be null; if t
he
argument is null, the result is the null value.
Example: Set the INTEGER variable DAYVAR to the day of the month on which
employee 140 in sample table DSN8710.EMP was hired.
SELECT DAYOFMONTH(HIREDATE)
INTO :DAYVAR
FROM DSN8710.EMP
WHERE EMPNO = 000140 ;
 DAYOFMONTH(expression) 
DAYOFMONTH
196 SQL Reference
|
|
|
|
|
DAYOFWEEK
The schema is SYSIBM.
The DAYOFWEEK function returns an integer in the range of 1 to 7 that represents
the day of the week where 1 is Sunday and 7 is Saturday.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: Using sample table DSN8710.EMP, set the integer host variable
DAY_OF_WEEK to the day of the week that Christine Haas (EMPNO = 000010 )
was hired (HIREDATE).
SELECT DAYOFWEEK(HIREDATE)
INTO :DAY_OF_WEEK
FROM DSN8710.EMP
WHERE EMPNO = 000010 ;
The result is that DAY_OF_WEEK is set to 6, which represents Friday.
Example 2: The following query returns four values: 1, 2, 1, and 2.
SELECT DAYOFWEEK(CAST( 10/11/1998 AS DATE)),
DAYOFWEEK(TIMESTAMP( 10/12/1998 , 01.02 )),
DAYOFWEEK(CAST(CAST( 10/11/1998 AS DATE) AS CHAR(20))),
DAYOFWEEK(CAST(TIMESTAMP( 10/12/1998 , 01.02 ) AS CHAR(20)))
FROM SYSIBM.SYSDUMMY1;
 DAYOFWEEK(expression) 
DAYOFWEEK
Chapter 3. Built-in functions 197
|
|
|
|
|
DAYOFWEEK_ISO
The schema is SYSIBM.
The DAYOFWEEK_ISO function returns an integer in the range of 1 to 7 that
represents the day of the week, where 1 is Monday and 7 is Sunday.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: Using sample table DSN8710.EMP, set the integer host variable
DAY_OF_WEEK to the day of the week that Christine Haas (EMPNO = 000010 )
was hired (HIREDATE).
SELECT DAYOFWEEK_ISO(HIREDATE)
INTO :DAY_OF_WEEK
FROM DSN8710.EMP
WHERE EMPNO = 000010 ;
The result is that DAY_OF_WEEK is set to 5, which represents Friday.
Example 2: The following query returns four values: 7, 1, 7, and 1.
SELECT DAYOFWEEK_ISO(CAST( 10/11/1998 AS DATE)),
DAYOFWEEK_ISO(TIMESTAMP( 10/12/1998 , 01.02 )),
DAYOFWEEK_ISO(CAST(CAST( 10/11/1998 AS DATE) AS CHAR(20))),
DAYOFWEEK_ISO(CAST(TIMESTAMP( 10/12/1998 , 01.02 ) AS CHAR(20)))
FROM SYSIBM.SYSDUMMY1;
Example 3: The following list shows what is returned by the DAYOFWEEK_ISO
function for various dates.
DATE DAYOFWEEK_ISO
1997-12-28 7
1997-12-31 3
1998-01-01 4
1999-01-01 5
1999-01-04 1
1999-12-31 5
2000-01-01 6
2000-01-03 1
 DAYOFWEEK_ISO(expression) 
DAYOFWEEK_ISO
198 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|||||
|
|
||||||||||
|
DAYOFYEAR
The schema is SYSIBM.
The DAYOFYEAR function returns an integer in the range of 1 to 366 that
represents the day of the year where 1 is January 1.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example: Using sample table DSN8710.EMP, set the integer host variable
AVG_DAY_OF_YEAR to the average of the day of the year on which employees
were hired (HIREDATE):
SELECT AVG(DAYOFYEAR(HIREDATE))
INTO :AVG_DAY_OF_YEAR
FROM DSN8710.EMP;
The result is that AVG_DAY_OF_YEAR is set to 202.
 DAYOFYEAR(expression) 
DAYOFYEAR
Chapter 3. Built-in functions 199
|
|
|
|
|
DAYS
The schema is SYSIBM.
The DAYS function returns an integer representation of a date.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null. If the argument is null, the result is the null value.
The result is 1 more than the number of days from January 1, 0001 to D, where D
is the date that would occur if the DATE function were applied to the argument.
Example: Set the INTEGER host variable DAYSVAR to the number of days that
employee 140 had been with the company on the last day of 1997.
EXEC SQL SELECT DAYS( 1997-12-31 ) - DAYS(HIREDATE) + 1
INTO :DAYSVAR
FROM DSN8710.EMP
WHERE EMPNO = 000140 ;
 DAYS(expression) 
DAYS
200 SQL Reference
|
|
|
|
|
DBCLOB
The schema is SYSIBM.
The DBCLOB function returns a DBCLOB representation of a string type.
The length of the result is measured in double-byte characters.
string-expression
An expression whose value is a string. The expression cannot be character
FOR BIT DATA. The value must not be an empty string constant.
integer
An integer value specifying the length attribute of the resulting DBCLOB. The
value must be between 0 and the maximum length of a DBCLOB.
If you do not specify integer, the length attribute of the result is the same as
the
length attribute of string-expression.
The result of the function is a DBCLOB. If the first argument can be null, the r
esult
can be null; if the first argument is null, the result is the null value.
The actual length of the result is the minimum of the length attribute of the re
sult
and the actual length of string-expression. If the length of string-expression i
s
greater than the length specified, the result is truncated. Unless all of the tr
uncated
characters are double-byte blanks, a warning is returned.
The CCSID of the result is the same as the CCSID of string-expression.
Example: Assume that the application encoding scheme is Unicode. The following
statement returns a graphic (UTF-16) host variable.
VALUES DBCLOB( 123 )
INTO :GHV1;
 DBCLOB(string-expression )
, integer

DBCLOB
Chapter 3. Built-in functions 201
|
|
|
#
|
DECIMAL or DEC
The schema is SYSIBM.
The DECIMAL or DEC function returns a decimal representation of a number or
character string in the form of a numeric constant.
numeric-expression
An expression that returns a value of any built-in numeric data type.
The result of the function is a decimal number. The result is the same number
that would occur if the argument were assigned to a decimal column or variable
with precision p and scale s, where p and s are specified by the second and
third arguments.
string-expression
An expression that returns any type of string (except a BLOB, CLOB, or
DBCLOB) with a maximum length that is not greater than 255 bytes. Leading
and trailing blanks are removed from the string, and the resulting substring mus
t
conform to the rules for forming a string representation of an SQL integer or
decimal constant.
The result of the function is a decimal number. The result is the same number
that would occur if the corresponding integer or decimal constant were assigned
to a decimal column or variable with precision p and scale s, where p and s are
specified by the second and third arguments.
precision-integer
An integer constant with a value in the range of 1 to 31. The value of this
second argument specifies the precision of the result.
The default value depends on the data type of the first argument as follows:
v 5 if the first argument is a small integer
v 11 if the first argument is a large integer
v 15 in all other cases
scale-integer
An integer constant with a value in the range of 1 to p, where p is the value of
the second argument. The value of this third argument specifies the scale of the
result. The default value is 0.
decimal-character
A single-byte character constant used to delimit the decimal digits in
Numeric to Decimal:
 DECIMAL (numeric-expression )
DEC ,precision-integer
,scale-integer

Character to Decimal:
 DECIMAL (string-expression )
DEC ,precision-integer
,scale-integer
,decimal-character

DECIMAL or DEC
202 SQL Reference
|
|
|
|
string-expression from the whole part of the number. The character cannot be a
digit, plus (+), minus (-), or blank. The default value is period (.) or comma (
,);
the default value cannot be used in string-expression if a different value for
decimal-character is specified.
The data type of the result is DECIMAL(p,s), where p and s are the second and
third arguments. If the first argument can be null, the result can be null; if t
he first
argument is null, the result is null.
An error occurs if the number of significant digits required to represent the wh
ole
part of the number is greater than p-s.
Example 1: Represent the average salary of the employees in DSN8710.EMP as an
8-digit decimal number with two of these digits to the right of the decimal poin
t.
SELECT DECIMAL(AVG(SALARY),8,2)
FROM DSN8710.EMP;
Example 2: Assume that updates to the SALARY column are input as a character
string that uses comma as the decimal character. For example, the user inputs
21400,50. The input value is assigned to the host variable NEWSALARY that is
defined as CHAR(10), and the host variable is used in the following UPDATE
statement:
UPDATE DSN8710.EMP
SET SALARY = DECIMAL (:NEWSALARY,9,2, , )
WHERE EMPNO = :EMPID;
DECIMAL or DEC
Chapter 3. Built-in functions 203
|
|
|
|
|
|
|
|
|
|||
|
DEGREES
The schema is SYSIBM.
The DEGREES function returns the number of degrees converted from the
argument expressed in radians.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HRAD is a DOUBLE with a value of
3.1415926536. The following statement:
SELECT DEGREES(:HRAD)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of
180.0.
 DEGREES(expression) 
DEGREES
204 SQL Reference
DIGITS
The schema is SYSIBM.
The DIGITS function returns a character string representation of its argument.
The argument must be a built-in exact numeric data type of SMALLINT, INTEGER,
or DECIMAL.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
The result of the function is a fixed-length character string representing the a
bsolute
value of the argument without regard to its scale. The result does not include a
sign
or a decimal point. Instead, it consists exclusively of digits, including, if ne
cessary,
leading zeros to fill out the string. The length of the string is:
v 5 if the argument is a small integer
v 10 if the argument is a large integer
v p if the argument is a decimal number with a precision of p
Example 1: Assume that an INTEGER column called INTCOL containing a 10-digit
number is in a table called TABLEX. INTCOL has the data type INTEGER instead
of CHAR(10) to save space. List all combinations of the first four digits in col
umn
INTCOL.
SELECT DISTINCT SUBSTR(DIGITS(INTCOL),1,4)
FROM TABLEX;
Example 2: Assume that COLUMNX has the data type DECIMAL(6,2), and that one
of its values is -6.28. Then, for this value:
DIGITS(COLUMNX)
the value 000628 is returned.
The result is a string of length six (the precision of the column) with leading
zeros
padding the string out to this length. Neither sign nor decimal point appear in
the
result.
 DIGITS(expression) 
DIGITS
Chapter 3. Built-in functions 205
#
#
DOUBLE or DOUBLE_PRECISION
The schema is SYSIBM.
The DOUBLE or DOUBLE_PRECISION function returns a double precision
floating-point representation of a number or character string in the form of a
numeric constant. FLOAT is a synonym for DOUBLE or DOUBLE_PRECISION.
numeric-expression
An expression that returns a value of any built-in numeric data type.
The result of the function is a double precision floating-point number. The resu
lt
is the same number that would occur if the expression were assigned to a
double precision floating-point column or variable.
string-expression
An expression that returns any type of string (except a BLOB, CLOB, or
DBCLOB) with an actual length that is not greater than 255 bytes. Leading and
trailing blanks are removed from the string, and the resulting substring must
conform to the rules for forming a string representation of an SQL floating-poin
t
constant.
The result of the function is a double precision floating-point number. The resu
lt
is the same number that would occur if the corresponding numeric constant
were assigned to a double precision floating-point column or variable.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Using sample table DSN8710.EMP, find the ratio of salary to commission
for employees whose commission is not zero. The columns involved in the
calculation, SALARY and COMM, have decimal data types. To eliminate the
possibility of out-of-range results, apply the DOUBLE function to SALARY so that
the division is carried out in floating-point.
SELECT EMPNO, DOUBLE(SALARY)/COMM
FROM DSN8710.EMP
WHERE COMM > 0;
 DOUBLE ( numeric-expression )
DOUBLE_PRECISION string-expression
FLOAT

DOUBLE or DOUBLE_PRECISION
206 SQL Reference
|
|
EXP
The schema is SYSIBM.
The EXP function returns the exponential function of the argument (a value that
is
the base of the natural logarithm (e) raised to a power specified by the argumen
t).
The EXP and LOG functions are inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable E is DECIMAL(10,9) with a value of
3.453789832. The following statement:
SELECT EXP(:E)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of
31.62.
 EXP(expression) 
EXP
Chapter 3. Built-in functions 207
FLOAT
The schema is SYSIBM.
The FLOAT function returns a floating-point representation of its argument.
FLOAT is a synonym for the DOUBLE function. See “DOUBLE or
DOUBLE_PRECISION” on page 206 for details.
 FLOAT(expression) 
FLOAT
208 SQL Reference
FLOOR
The schema is SYSIBM.
The FLOOR function returns the largest integer value that is less than or equal
to
the argument.
The argument is an expression that returns a value of any built-in numeric data
type.
The result of the function has the same data type and length attribute as the
argument. The result can be null. If the argument is null, the result is the nul
l value.
When the argument is DECIMAL, the scale of the result is 0 and not the scale of
the input argument.
Example: Using sample table DSN8710.EMP, find the highest monthly salary,
rounding the result down to the next integer. The SALARY column has a decimal
data type.
SELECT FLOOR(MAX(SALARY)/12)
FROM DSN8710.EMP;
This example returns 04395 because the highest paid employee is Christine Haas
who earns $52750.00 per year. Her average monthly salary before applying the
FLOOR function is 4395.83.
 FLOOR(expression) 
FLOOR
Chapter 3. Built-in functions 209
|
|
GRAPHIC
The schema is SYSIBM.
The GRAPHIC function returns a graphic representation of a character string valu
e,
with the single-byte characters converted to double-byte characters, or a graphi
c
string value if the first argument is a graphic string.
The result of the function is a fixed-length graphic string (GRAPHIC).
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
The length attribute of the result is measured in double-byte characters because
it
is a graphic string.
Character to Graphic
character-expression
An expression whose value must be an EBCDIC-encoded or Unicode-encoded
character string. The GRAPHIC function is not allowed for ASCII data. The
argument does not need to be mixed data, but any occurrences of X 0E and
X 0F in the string must conform to the rules for EBCDIC mixed data. (See
“Character strings” on page 49 for these rules.)
The value of the expression must not be an empty string or have the value
X 0E0F if the string is an EBCDIC string.
integer
The length of the resulting fixed-length graphic string. The value must be an
integer between 1 and 127. If the length of character-expression is less than th
e
length specified, the result is padded with double-byte blanks to the length of
the result.
If integer is not specified, the length of the result for an EBCDIC string is th
e
minimum of 127 and the length attribute of character-expression, excluding shift
characters. For a Unicode (UTF-8) string, the length is data dependent, but
does not exceed 127.
The CCSID of the result is the system CCSID for EBCDIC or Unicode GRAPHIC
data. If the input is EBCDIC and there is no system CCSID for EBCDIC GRAPHIC
data, the CCSID of the result is X FFFE .
Character to Graphic:
 GRAPHIC(character-expression )
, integer

Graphic to Graphic:
 GRAPHIC(graphic-expression )
, integer

GRAPHIC
210 SQL Reference
|
|
|
|
|
|
|
For EBCDIC data:
Each character of character-expression determines a character of the result. The
argument might need to be converted to the native form of mixed data before the
result is derived. Let M be the system CCSID for mixed data. The argument is not
converted if any of the following conditions is true:
v The argument is mixed data and its CCSID is M.
v The argument is SBCS data and its CCSID is the same as the system CCSID for
SBCS data. In this case, the operation proceeds as if the CCSID of the argument
is M.
v The argument cannot be BIT data.
Otherwise, the argument is a new string S derived by converting the characters t
o
the coded character set identified by M. If there is no system CCSID for EBCDIC
mixed data, conversion is to the coded character set that the system EBCDIC
CCSID for SBCS data identifies.
The result is derived from S using the following steps:
v Each shift character (X 0E or X 0F ) is removed.
v Each double-byte character remains as is.
v Each single-byte character is replaced by a double-byte character.
The replacement for an SBCS character is the equivalent DBCS character if an
equivalent exists. Otherwise, the replacement is X FEFE . The existence of an
equivalent character depends on M. If there is no system CCSID for mixed data,
the DBCS equivalent of X xx for EBCDIC is X 42xx , except for X 40 , whose DBCS
equivalent is X 4040 .
For Unicode data:
Each character of character-expression determines a character of the result. The
argument might need to be converted to the native form of mixed data before the
result is derived. Let M be the system CCSID for mixed data. The argument is not
converted if any of the following conditions is true:
v The argument is mixed data, and its CCSID is M.
v The argument is SBCS data, and its CCSID is the same as the system CCSID
for SBCS data. In this case, the operation proceeds as if the CCSID of the
argument is M.
Otherwise, the argument is a new string S derived by converting the characters t
o
the coded character set identified by M.
The result is derived from S by using the following steps:
v Each non-surrogate character is replaced by a Unicode double-byte character (a
UTF-16 code point). A non-surrogate character in UTF-8 is between 1 and 3
bytes.
v Each surrogate character is replaced by a pair of Unicode double-byte characte
rs
(a pair of UTF-16 code points).
The replacement for a single-byte character is the Unicode equivalent character
if
an equivalent exists. Otherwise, the replacement is X FEFE .
Graphic to Graphic
GRAPHIC
Chapter 3. Built-in functions 211
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
graphic-expression
An expression whose value is a graphic string. The graphic string must not be
an empty string.
integer
The length of the resulting fixed-length graphic string. The value must be an
integer between 1 and 127. If the length of graphic-expression is less than the
length specified, the result is padded with double-byte blanks to the length of
the result.
If integer is not specified, the length of the result is the minimum of 127 and
the
length attribute of graphic-expression.
If the length of the graphic-expression is greater than the specified length of
the
result, the result is truncated. Unless all the truncated characters are blanks,
a
warning is returned.
The CCSID of the result is the same as the CCSID of graphic-expression.
Example: Assume that MYCOL is a VARCHAR column in TABLEY. The following
function returns the string in MYCOL as a fixed-length graphic string.
SELECT GRAPHIC(MYCOL)
FROM TABLEY;
GRAPHIC
212 SQL Reference
HEX
The schema is SYSIBM.
The HEX function returns a hexadecimal representation of its argument.
The argument can be of any built-in data type other than a character or binary
string with a maximum length greater than 255 or a graphic string with a maximum
length greater than 127.
The result of the function is a character string. If the argument can be null, t
he
result can be null; if the argument is null, the result is the null value.
The result is a string of hexadecimal digits. The first two represent the first
byte of
the argument, the next two represent the second byte of the argument, and so
forth. If the argument is a datetime value, the result is the hexadecimal
representation of the internal form of the argument.
If the argument is a graphic string, the length of the result is four times the
maximum length of the argument. Otherwise, the length of the result is twice the
(maximum) length of the argument.
If the argument is not a varying-length string, and the length of the result is
less
than 255, the result is a fixed-length string. Otherwise, the result is a varyin
g-length
string whose maximum length depends on the following considerations:
If the argument is not a varying-length string, the maximum length of the
result string is the same as the length of the result.
If the argument is a varying-length character or binary string, the maximum
length of the result string is twice the maximum length of the argument.
If the argument is a varying-length graphic string, the maximum length of
the result string is four times the maximum length of the argument.
If the maximum length of the result is greater than 254 bytes, the result is sub
ject to
the restrictions that apply to long strings.
Example: Return the hexadecimal representation of START_RBA in the
SYSIBM.SYSCOPY catalog table.
SELECT HEX(START_RBA) FROM SYSIBM.SYSCOPY;
 HEX(expression) 
HEX
Chapter 3. Built-in functions 213
HOUR
The schema is SYSIBM.
The HOUR function returns the hour part of its argument.
The argument must be a time, timestamp, time duration, timestamp duration, or
valid string representation of a time or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. For the valid formats of string representations of times and
timestamps, see “String representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a time, timestamp, or string representation of either, the
result is the hour part of the value, which is an integer between 1 and 24.
If the argument is a time duration or timestamp duration, the result is the
hour part of the value, which is an integer between -99 and +99. A nonzero
result has the same sign as the argument.
Example: Assume that a table named CLASSES contains a row for each scheduled
class. Also assume that the class starting times are in a TIME column named
STARTTM. Select those rows in CLASSES that represent classes that start after
the noon hour.
SELECT *
FROM CLASSES
WHERE HOUR(STARTTM) > 12;
 HOUR(expression) 
HOUR
214 SQL Reference
|
|
|
|
|
IDENTITY_VAL_LOCAL
The schema is SYSIBM.
The IDENTITY_VAL_LOCAL function is a nondeterministic function 22 that returns
the most recently assigned value for an identity column. The function has no inp
ut
parameters.
The result is DECIMAL(31,0), regardless of the actual data type of the identity
column that the result value corresponds to.
The value returned is the value that was assigned to the identity column of the
table
identified in the most recent row INSERT statement with a VALUES clause for a
table with an identity column. The INSERT statement has to be issued at the same
level; that is, the value has to be available locally within the level at which
it was
assigned until replaced by the next assigned value. A new level is initiated whe
n a
trigger, function, or stored procedure is invoked. A trigger condition is at the
same
level as the associated triggered action.
The assigned value can be a value supplied by the user (if the identity column i
s
defined as GENERATED BY DEFAULT) or an identity value that was generated by
DB2.
The function returns the null value in the following situations:
v When a single row INSERT statement with a VALUES clause has not been
issued for a table containing an identity column at the current processing level
v When a COMMIT or ROLLBACK of a unit of work occurred since the most recent
INSERT statement that assigned a value
The result of the function is not affected by the following statements:
v An INSERT statement with a VALUES clause for a table that does not contain an
identity column
v An INSERT statement with a subselect
v A ROLLBACK TO SAVEPOINT statement
Notes
The following notes explain the behavior of the function when it is invoked in
various situations:
Invoking the function within the VALUES clause of an INSERT statement
Expressions in the VALUES clause of an INSERT statement are evaluated
before values are assigned to the target columns of the INSERT statement.
Thus, when you invoke IDENTITY_VAL_LOCAL in a VALUES clause of an
INSERT statement, the value that is used is the most recently assigned
value for an identity column from a previous INSERT statement. The
22. Being nondeterministic affects what optimization (such as view processing an
d parallel processing) can be done when this
function is used and in what contexts the function can be invoked. For example,
the RAND function is another built-in scalar that
is not deterministic. Using nondeterministic functions within a predicate can ca
use unpredictable results.
 IDENTITY_VAL_LOCAL() 
IDENTITY_VAL_LOCAL
Chapter 3. Built-in functions 215
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
function returns the null value if no such INSERT statement had been
executed within the same level as the invocation of the
IDENTITY_VAL_LOCAL function.
Invoking the function following a failed INSERT statement
The function returns an unpredictable result when it is invoked after the
unsuccessful execution of a single row INSERT with a VALUES clause for a
table with an identity column. The value might be the value that would have
been returned from the function had it been invoked before the failed
INSERT or the value that would have been assigned had the INSERT
succeeded. The actual value returned depends on the point of failure and is
therefore unpredictable.
Invoking the function within the SELECT statement of a cursor
Because the results of the IDENTITY_VAL_LOCAL function are not
deterministic, the result of an invocation of the IDENTITY_VAL_LOCAL
function from within the SELECT statement of a cursor can vary for each
FETCH statement.
Invoking the function within the trigger condition of an insert trigger
The result of invoking the IDENTITY_VAL_LOCAL function from within the
condition of an insert trigger is the null value.
Invoking the function within a triggered action of an insert trigger
Multiple before or after insert triggers can exist for a table. In such cases,
each trigger is processed separately, and identity values generated by SQL
statements issued within a triggered action are not available to other
triggered actions using the IDENTITY_VAL_LOCAL function. This is the
case even though the multiple triggered actions are conceptually defined at
the same level.
Do not use the IDENTITY_VAL_LOCAL function in the triggered action of a
before insert trigger. The result of invoking the IDENTITY_VAL_LOCAL
function from within the triggered action of a before insert trigger is the null
value.The value for the identity column of the table for which the trigger is
defined cannot be obtained by invoking the IDENTITY_VAL_LOCAL
function within the triggered action of a before insert trigger. However, the
value for the identity column can be obtained in the triggered action by
referencing the trigger transition variable for the identity column.
The result of invoking the IDENTITY_VAL_LOCAL function in the triggered
action of an after insert trigger is the value assigned to an identity column
of the table identified in the most recent single row INSERT statement. That
statement is the one invoked in the same triggered action that had a
VALUES clause for a table containing an identity column. If a single row
INSERT statement with a VALUES clause for a table containing an identity
column was not executed within the same triggered action before invoking
the IDENTITY_VAL_LOCAL function, then the function returns a null value.
Invoking the function following an INSERT with triggered actions
The result of invoking the function after an INSERT that activates triggers is
the value actually assigned to the identity column (that is, the value that
would be returned on a subsequent SELECT statement). This value is not
necessarily the value provided in the VALUES clause of the INSERT
statement or a value generated by DB2. The assigned value could be a
value that was specified in a SET transition variable statement within the
triggered action of a before insert trigger for a trigger transition variable
associated with the identity column.
IDENTITY_VAL_LOCAL
216 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Examples
Example 1: Set the variable IVAR to the value assigned to the identity column in
the EMPLOYEE table. The value returned from the function in the VALUES
statement should be 1.
CREATE TABLE EMPLOYEE
(EMPNO INTEGER GENERATED ALWAYS AS IDENTITY,
NAME CHAR(30),
SALARY DECIMAL(5,2),
DEPTNO SMALLINT);
INSERT INTO EMPLOYEE
(NAME, SALARY, DEPTNO)
VALUES ( Rupert , 989.99, 50);
VALUES IDENTITY_VAL_LOCAL() INTO :IVAR;
Example 2: Assume two tables, T1 and T2, have an identity column named C1.
DB2 generates values 1, 2, 3, . . . for the C1 column in table T1, and values 10
, 11,
12, . . . for the C1 column in table T2.
CREATE TABLE T1(C1SMALLINT GENERATED ALWAYS AS IDENTITY,
C2 SMALLINT );
CREATE TABLE T2 (C1DECIMAL(1 5,0) GENERATED BY DEFAULT AS IDENTITY
(START WITH 10),
C2 SMALLINT );
INSERT INTO T1(C2) VALUES (5);
INSERT INTO T1(C2) VALUES (5);
SELECT * FROM T1;
C1C2
----------- ----------
1 5
2 5
VALUES IDENTITY_VAL_LOCAL() INTO :IVAR;
At this point, the IDENTITY_VAL_LOCAL function would return a value of 2 in IVAR
.
The following INSERT statement inserts a single row into T2 where column C2 gets
a value of 2 from the IDENTITY_VAL_LOCAL function
INSERT INTO T2 (C2) VALUES (IDENTITY_VAL_LOCAL());
SELECT * FROM T2
WHERE C1= DECIMAL(IDENTITY_VAL_LOCAL(),15,0);
C1C2
---------------------------------- ----------
1 0 2
Invoking the IDENTITY_VAL_LOCAL function after this insert would result in a val
ue
of 10, which is the value generated by DB2 for column C1 of T2. Assume another
single row is inserted into T2. For the following INSERT statement, DB2 assigns
a
value of 13 to identity column C1 and gives C2 a value of 10 from
IDENTITY_VAL_LOCAL. Thus, C2 is given the last identity value that was inserted
into T2.
INSERT INTO T2 (C2, C1) VALUES (IDENTITY_VAL_LOCAL(), 13);
IDENTITY_VAL_LOCAL
Chapter 3. Built-in functions 217
|
|
|
|
|||||||||||
|
|
|
|||||||||||||||||||
|
|
|
||||||||
|
|
|
|
|
|
|
Example 3: The IDENTITY_VAL_LOCAL function can also be invoked in an
INSERT statement that both invokes the IDENTITY_VAL_LOCAL function and
causes a new value for an identity column to be assigned. The next value to be
returned is thus established when the IDENTITY_VAL_LOCAL function is invoked
after the INSERT statement completes. For example, consider the following table
definition:
CREATE TABLE T1(C1SMALLINT GENERATED BY DEFAULT AS IDENTITY,
C2 SMALLINT);
For the following INSERT statement, specify a value of 25 for the C2 column, and
DB2 generates a value of 1 for C1, the identity column. This establishes 1 as th
e
value that will be returned on the next invocation of the IDENTITY_VAL_LOCAL
function.
INSERT INTO T1(C2) VALUES (25);
In the following INSERT statement, the IDENTITY_VAL_LOCAL function is invoked
to provide a value for the C2 column. A value of 1 (the identity value assigned
to
the C1 column of the first row) is assigned to the C2 column, and DB2 generates
a
value of 2 for C1, the identity column. This establishes 2 as the value that wil
l be
returned on the next invocation of the IDENTITY_VAL_LOCAL function.
INSERT INTO T1(C2) VALUES (IDENTITY_VAL_LOCAL());
In the following INSERT statement, the IDENTITY_VAL_LOCAL function is again
invoked to provide a value for the C2 column, and the user provides a value of 1
1
for C1, the identity column. A value of 2 (the identity value assigned to the C1
column of the second row) is assigned to the C2 column. The assignment of 11 to
C1 establishes 11 as the value that will be returned on the next invocation of t
he
IDENTITY_VAL_LOCAL function.
INSERT INTO T1 (C2, C1) VALUES (IDENTITY_VAL_LOCAL(), 11);
After the 3 INSERT statements have been processed, table T1 contains the
following:
SELECT * FROM T1;
C1C2
----------- -----------
125
2 1
11 2
The contents of T1 illustrate that the expressions in the VALUES clause are
evaluated before the assignments for the columns of the INSERT statement. Thus,
an invocation of an IDENTITY_VAL_LOCAL function invoked from a VALUES
clause of an INSERT statement uses the most recently assigned value for an
identity column in a previous INSERT statement.
IDENTITY_VAL_LOCAL
218 SQL Reference
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||||
|
|
|
|
|
IFNULL
The schema is SYSIBM.
The IFNULL function returns the first argument that is not null.
IFNULL is identical to the COALESCE and VALUE scalar functions except that
IFNULL is limited to two arguments instead of multiple arguments. For a descript
ion,
see “COALESCE” on page 189.
Example: For all the rows in sample table DSN8710.EMP, select the employee
number and salary. If the salary is missing (is null), have the value 0 returned
.
SELECT EMPNO, IFNULL(SALARY,0)
FROM DSN8710.EMP;
 IFNULL(expression,expression) 
IFNULL
Chapter 3. Built-in functions 219
INSERT
The schema is SYSIBM.
The INSERT function returns a string where, beginning at expression2 in
expression1, expression3 bytes have been deleted and expression4 has been
inserted.
expression1
An expression that specifies the source string. The source string can be any
type of character string except a CLOB or any type of graphic string except a
DBCLOB. The actual length of the string must be greater than zero.
expression2
An expression that returns an integer. The integer specifies the starting point
within the source string where the deletion of bytes and the insertion of anothe
r
string is to begin. The value of the integer must be in the range of 1 to the
length of expression1 plus one.
expression3
An expression that returns an integer. The integer specifies the number of bytes
that are to be deleted from the source string, starting at the position identifi
ed
by expression2. The value of the integer must be in the range of 0 to the length
of expression1.
expression4
An expression that specifies the string to be inserted into the source string,
starting at the position identified by expression2. The string to be inserted ca
n
be any type of character string except a CLOB or any type of graphic string
except a DBCLOB.
expression1 and expression4 must have compatible string types. For more
information on compatibility, see “Conversion rules for string comparison” on
page 73. Neither expression1 nor expression4 can be a CLOB or DBCLOB.
The result of the function depends on the data type of the first and fourth
arguments:
v VARCHAR if expression1 and expression4 are character strings
v VARGRAPHIC if expression1 and expression4 are graphic strings
The length attribute of the result depends on the arguments:
v If expression2 and expression3 are constants, the length attribute of the resu
lt is:
L1- MIN((L1- V2 + 1), V3) + L4
where:
L1 is the length attribute of expression1
V2 is the value of expression2
V3 is the value of expression3
L4 is the length attribute of expression4
v Otherwise, the length attribute of the result is the length attribute of expre
ssion1
plus the length attribute of expression4. In this case, the length attribute of
 INSERT(expression1,expression2,expression3,expression4) 
INSERT
220 SQL Reference
|
|
|
expression1 plus the length attribute of expression4 must not exceed 4000 for a
VARCHAR result or 2000 for a VARGRAPHIC result.
The actual length of the result is:
A1- MIN((A1- V2 + 1), V3) + A4
where:
A1 is the actual length of expression1
V2 is the value of expression2
V3 is the value of expression3
A4 is the actual length of expression4
If the actual length of the result string exceeds the maximum for the return dat
a
type, an error occurs.
If any argument can be null, the result can be null; if any argument is null, th
e result
is the null value.
The subtype and CCSID of the result are determined as follows:
v If either expression1 and expression4 is character bit data, the result is bit
data
and does not have an associated CCSID.
v If expression1 and expression4 are both character SBCS data, the result is
SBCS data and the CCSID is the CCSID for ASCII, EBCDIC, or Unicode SBCS
data, depending on the encoding scheme of the SQL statement.
v If expression1 and expression4 are both graphic data, the result is graphic da
ta
and the CCSID is the CCSID for ASCII, EBCDIC, Unicode graphic data,
depending on the encoding scheme of the SQL statement.
v Otherwise, the result is mixed data. The CCSID is the CCSID for ASCII, EBCDIC
or Unicode mixed data, depending on the encoding scheme of the SQL
statement.
Example 1: The following example shows how the string INSERTING can be
changed into other strings. The use of the CHAR function limits the length of th
e
resulting string to 10 bytes.
SELECT CHAR(INSERT( INSERTING ,4,2, IS ),10),
CHAR(INSERT( INSERTING ,4,0, IS ),10),
CHAR(INSERT( INSERTING ,4,2, ),10)
FROM SYSIBM.SYSDUMMY1;
This example returns INSISTING , INSISERTIN , and INSTING
Example 2: The previous example demonstrated how to insert text into the middle
of some text. This example shows how to insert text before some text by using 1
as
the starting point (expression2).
SELECT CHAR(INSERT( INSERTING ,1,0, XX ),10),
CHAR(INSERT( INSERTING ,1,1, XX ),10),
CHAR(INSERT( INSERTING ,1,2, XX ),10),
CHAR(INSERT( INSERTING ,1,3, XX ),10)
FROM SYSIBM.SYSDUMMY1;
This example returns XXINSERTIN , XXNSERTING , XXSERTING , and
XXERTING
Example 3: The following example shows how to insert text after some text. Add
XX at the end of string ABCABC . Because the source string is 6 characters lo
ng,
set the starting position to 7 (one plus the length of the source string).
INSERT
Chapter 3. Built-in functions 221
|
|
|
SELECT CHAR(INSERT( ABCABC ,7,0, XX ),10)
FROM SYSIBM.SYSDUMMY1;
This example returns ABCABCXX .
INSERT
222 SQL Reference
INTEGER or INT
The schema is SYSIBM.
The INTEGER or INT function returns an integer representation of a number or
character string in the form of a numeric constant.
numeric-expression
An expression that returns a value of any built-in numeric data type.
The result of the function is a large integer. The result is the same number tha
t
would occur if the argument were assigned to a large integer column or
variable. If the whole part of the argument is not within the range of integers,
an
error occurs. If present, the decimal part of the argument is truncated.
string-expression
An expression that returns any type of string (except a BLOB, CLOB, or
DBCLOB) with an actual length that is not greater than 255 bytes. Leading and
trailing blanks are removed from the string, and the resulting substring must
conform to the rules for forming a string representation of an SQL integer
constant.
The result of the function is a large integer. The result is the same number tha
t
would occur if the corresponding numeric constant were assigned to a large
integer column or variable.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example 1: Using sample table DSN8710.EMP, find the average salary of the
employees in department A00, rounding the result to the nearest dollar.
SELECT INTEGER(AVG(SALARY)+.5)
FROM DSN8710.EMP
WHERE WORKDEPT = A00 ;
Example 2: Using sample table DSN8710.EMP, select the EMPNO column, which is
defined as CHAR(6), in integer form.
SELECT INTEGER(EMPNO)
FROM DSN8710.EMP;
 INTEGER ( numeric-expression )
INT string-expression

INTEGER or INT
Chapter 3. Built-in functions 223
|
|
JULIAN_DAY
The schema is SYSIBM.
The JULIAN_DAY function returns an integer value representing a number of days
from January 1, 4712 B.C. (the start of the Julian date calendar) to the date
specified in the argument.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. (For the vali
d
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: Using sample table DSN8710.EMP, set the integer host variable JDAY
to the Julian day of the day that Christine Haas (EMPNO = 000010 ) was employed
(HIREDATE = 1965-01-01 ).
SELECT JULIAN_DAY(HIREDATE)
INTO :JDAY
FROM DSN8710.EMP
WHERE EMPNO = 000010 ;
The result is that JDAY is set to 2438762.
Example 2: Set integer host variable JDAY to the Julian day for January 1, 1998.
SELECT JULIAN_DAY( 1998-01-01 )
INTO :JDAY
FROM SYSIBM.SYSDUMMY1;
The result is that JDAY is set to 2450815.
 JULIAN_DAY(expression) 
JULIAN_DAY
224 SQL Reference
|
|
|
|
|
LAST_DAY
The schema is SYSIBM.
The LAST_DAY scalar function returns a date that represents the last day of the
month indicated by date-expression.
date-expression must be a date, a timestamp, or a valid string representation of
a
date or timestamp. A string representation must not be a BLOB, CLOB, or
DBCLOB, and must have an actual length that is not greater than 255 bytes. For
the valid formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a DATE. The result can be null; if the value of
date-expression is null, the result is the null value.
Example 1: Set the host variable END_OF_MONTH with the last day of the current
month.
SET :END_OF_MONTH = LAST_DAY(CURRENT_DATE);
The host variable END_OF_MONTH is set with the value representing the end of
the current month. If the current day is 2000-02-10, then END_OF_MONTH is set to
2000-02-29.
Example 2: Set the host variable END_OF_MONTH with the last day of the month
in EUR format for the given date.
SET :END_OF_MONTH = CHAR(LAST_DAY( 1965-07-07 ), EUR);
The host variable END_OF_MONTH is set with the value ’31.07.1965’.
 LAST_DAY(date-expression) 
LAST_DAY
Chapter 3. Built-in functions 225
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LCASE or LOWER
The schema is SYSIBM.
The LCASE or LOWER function returns a string in which all the characters have
been converted to lowercase characters.
string-expression
An expression that specifies the string to be converted. The string must be a
character or graphic string. A character string argument must not be a CLOB
and must have an actual length that is not greater than 255. A graphic string
argument must not be a DBCLOB and must have an actual length that is not
greater than 127.
The alphabetic characters of the argument are translated to lowercase characters
based on the value of the LC_CTYPE locale in effect for the statement. For
example, characters A-Z are translated to a-z, and characters with diacritical m
arks
are translated to their lowercase equivalent, if any. The locale is determined b
y
special register CURRENT LOCALE LC_CTYPE. For information about the special
register, see “CURRENT LOCALE LC_CTYPE” on page 86.
If the LC_CTYPE locale is blank when the function is executed, the result of the
function depends on the data type of string-expression.
v For ASCII and EBCDIC, if string-expression specifies a graphic string expressi
on,
then an error occurs. For a character string expression, characters A-Z are
translated to a-z and characters with diacritical marks are not translated.
v For Unicode, string-expression can be either a character string expression or
a
graphic string expression. The characters A-Z are translated to a-z and all othe
r
characters, including characters with diacritic marks, are left unchanged. If
LOCALE LC_CTYPE is not blank, an error occurs.
The length attribute, data type, subtype, and CCSID of the result are the same a
s
the argument. If the argument can be null, the result can be null; if the argume
nt is
null, the result is the null value.
Example: Return the characters in the value of host variable NAME in lowercase.
NAME has a data type of VARCHAR(30) and a value of Christine Smith . Assume
that the locale in effect is blank.
SELECT LCASE(:NAME)
FROM SYSIBM.SYSDUMMY1;
The result is the value christine smith .
 LCASE (string-expression)
LOWER

LCASE or LOWER
226 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
LEFT
The schema is SYSIBM.
The LEFT function returns a string consisting of the specified number of leftmos
t
integer characters of string-expression. If string-expression is a character or
binary
string, a character is a byte. If string-expression is a graphic string, a chara
cter is a
DBCS character.
The CCSID of the result is the same as that of the string-expression.
string-expression
An expression that specifies the string from which the result is derived. The
string must be a character, graphic, or binary string. A substring of
string-expression is zero or more contiguous bytes of string-expression.
The string can contain mixed data. However, because the function operates on
a strict byte-count basis, the result is not necessarily a properly formed mixed
data character string.
integer
An expression that specifies the length of the result. The value must be an
integer between 0 and n, where n is the length attribute of string-expression.
The string-expression is effectively padded on the right with the necessary numb
er
of characters so that the specified substring of string-expression always exists
. The
encoding scheme of the data determines the padding character:
v For ASCII SBCS data or ASCII mixed data, the padding character is X 20 .
v For ASCII DBCS data, the padding character depends on the CCSID; for
example, for Japan (CCSID 301) the padding character is X 8140 , while for
simplified Chinese it is X A1A1 .
v For EBCDIC SBCS data or EBCDIC mixed data, the padding character is X 40 .
v For EBCDIC DBCS data, the padding character is X 4040 .
v For Unicode SBCS data or UTF-8 (Unicode mixed data), the padding character is
X 20 .
v For UTF-16 (Unicode DBCS) data, the padding character is X 0020 .
v For binary data, the padding character is X 00 .
The result of the function is a varying-length string with a length attribute th
at is the
same as the length attribute of string-expression and a data type that depends o
n
the data type of string:
v VARCHAR if string-expression is CHAR or VARCHAR
v CLOB if string-expression is CLOB
v VARGRAPHIC if string-expression is GRAPHIC or VARGRAPHIC
v DBCLOB if string-expression is DBCLOB
v BLOB if string-expression is BLOB
If any argument of the function can be null, the result can be null; if any argu
ment is
null, the result is the null value.
 LEFT(string-expression,integer) 
LEFT
Chapter 3. Built-in functions 227
|
|
|
|
|
|
|
Example 1: Assume that host variable ALPHA has a value of ABCDEF . The
following statement:
SELECT LEFT(:ALPHA,3)
FROM SYSIBM.SYSDUMMY1;
returns ABC , which are the three leftmost characters in ALPHA.
Example 2: Assume that host variable NAME, which is defined as VARCHAR(50),
has a value of KATIE AUSTIN and the integer host variable FIRSTNAME_LEN has
a value of 5. The following statement:
SELECT LEFT(:NAME, :FIRSTNAME_LEN)
FROM SYSIBM.SYSDUMMY1;
returns the value KATIE .
Example 3: The following statement returns a zero length string.
SELECT LEFT( ABCABC ,0)
FROM SYSIBM.SYSDUMMY1;
Example 4: The FIRSTNME column in sample EMP table is defined as
VARCHAR(12). Find the first name for an employee whose last name is ’BROWN’
and return the first name in a 10-byte string.
SELECT LEFT(FIRSTNME,10)
FROM DSN8710.EMP
WHERE LASTNAME= BROWN ;
This function returns a VARCHAR(10) string that has the value of ’DAVID’ followed
by 5 blank characters.
LEFT
228 SQL Reference
LENGTH
The schema is SYSIBM.
The LENGTH function returns the length of its argument.
The argument is an expression that returns a value of any built-in data type.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The result is the length of the argument. The length does not include the null
indicator byte of column arguments that allow null values. The length of strings
includes blanks but does not include the length control field of varying-length
strings. The length of a varying-length string is the actual length, not the max
imum
length.
The length of a graphic string is the number of double-byte characters. Unicode
UTF-16 data is treated as graphic data; a UTF-surrogate character takes two DBCS
characters to represent and as such is counted as two DBCS characters.
The length of all other values is the number of bytes used to represent the valu
e:
v 2 for small integer
v 4 for large integer
v 4 for single precision floating-point
v 8 for double precision floating-point
v INTEGER(p/2)+1 for decimal numbers with precision p
v 4 for date
v 3 for time
v 10 for timestamp
v The length of the string for character strings
v The length of the row ID
Example 1: Assume that FIRSTNME is a VARCHAR(12) column that contains
ETHEL for employee 280. The following query:
SELECT LENGTH(FIRSTNME)
FROM DSN8710.EMP
WHERE EMPNO = 000280 ;
returns the value 5.
Example 2: Assume that HIREDATE is a column of data type DATE. Then,
regardless of value:
LENGTH(HIREDATE)
returns the value 4, and
LENGTH(CHAR(HIREDATE, EUR))
returns the value 10.
 LENGTH(expression) 
LENGTH
Chapter 3. Built-in functions 229
|
|
|
LN
The schema is SYSIBM.
The LN function returns the natural logarithm of the argument. The LN and EXP
functions are inverse operations. LOG is a synonym for LN.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable NATLOG is DECIMAL(4,2) with a value of
31.62. The following statement:
SELECT LN(:NATLOG)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 3.
45.
 LN(expression) 
LN
230 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
||
|
LOCATE
The schema is SYSIBM.
The LOCATE function returns the starting position of the first occurrence of one
string (the search-string) within another string (the source-string). Numbers fo
r the
starting position begin at 1 and not 0. If search-string is not found in source-
string,
the function returns 0.
search-string
An expression that specifies the string that is to be searched for. The search
string can be a character, graphic, or binary string with an actual length that
is
no greater than 4000 bytes. The expression can be specified by any of the
following:
v A constant
v A special register
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above
v A CAST specification whose arguments are any of the above
v An expression that concatenates (using CONCAT or ||) any of the above
v A column name
These rules are similar to those that are described for pattern-expression for t
he
LIKE predicate.
source-string
An expression that specifies the source string that is to be searched. The
source string can be a character, graphic, or binary string. The expression can
be specified by any of the following:
v A constant
v A special register
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above
v A CAST specification whose arguments are any of the above
v A column name
v An expression that concatenates (using CONCAT or ||) any of the above
start
An expression whose value is a positive integer. The integer specifies the
position in the source string at which the search begins. If start is specified,
the
LOCATE function is equivalent to:
POSSTR(SUBSTR(source-string, integer), search-string) + integer - 1
If start is not specified, the search begins at the first character of the sourc
e
string and the LOCATE function is equivalent to:
POSSTR(source-string, search-string)
The first and second arguments must have compatible string types. For more
information on compatibility, see “Conversion rules for string comparison” on
page 73.
 LOCATE(search-string,source-string )
, start

LOCATE
Chapter 3. Built-in functions 231
|
|
|
The result of the function is a large integer. If any argument can be null, the
result
can be null; if any argument is null, the result is the null value.
For more information about LOCATE, see the description of “POSSTR” on
page 246.
Example 1: Find the location of the first occurrence of the character N in the
string
DINING .
SELECT LOCATE( N , DINING )
FROM SYSIBM.SYSDUMMY1;
The result is the value 3.
Example 2: For all the rows in the table named IN_TRAY, select the RECEIVED
column, the SUBJECT column, and the starting position of the string GOOD withi
n
the NOTE_TEXT column.
SELECT RECEIVED, SUBJECT, LOCATE( GOOD , NOTE_TEXT)
FROM IN_TRAY
WHERE LOCATE( GOOD , NOTE_TEXT) <> 0;
LOCATE
232 SQL Reference
LOG10
The schema is SYSIBM.
The LOG10 function returns the base 10 logarithm of the argument.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HLOG is an INTEGER with a value of 100. The
following statement:
SELECT LOG10(:HLOG)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 2.
 LOG10(expression) 
LOG10
Chapter 3. Built-in functions 233
LTRIM
The schema is SYSIBM.
The LTRIM function removes blanks from the beginning of a string expression. The
LTRIM function returns the same results as the STRIP function with LEADING
specified:
STRIP(string-expression,LEADING)
string-expression must be any character string expression other than a CLOB or
any graphic string expression other than a DBCLOB. The characters that are
interpreted as leading blanks depend on the encoding scheme of the data and the
data type:
v If the argument is a graphic string, the leading DBCS blanks are removed. For
data that is encoded in ASCII, the ASCII CCSID determines the hex value that
represents a double-byte blank. For example, for Japan (CCSID 301), X 8140
represents a double-byte blank, while it is X A1A1 for Simplified Chinese. For
EBCDIC-encoded data, X 4040 represents a double-byte blank. For
Unicode-encoded data, X 0020 represents a UTF-16 blank.
v Otherwise, leading SBCS blanks are removed. For data that is encoded in ASCII,
X 20 represents a blank. For EBCDIC-encoded data, X 40 represents a blank.
For Unicode-encoded data, X 20 represents a single-byte blank.
The result of the function depends on the data type of its argument:
v VARCHAR if the argument is a character string
v VARGRAPHIC if the argument is a graphic string
The length attribute of the result is the same as the length attribute of
string-expression. The actual length of the result is the length of the expressi
on
minus the number of characters removed. If all of the characters are removed, th
e
result is an empty string.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value. The CCSID of the result is the same as that of string-express
ion.
Example: Assume that host variable HELLO is defined as CHAR(9) and has a value
of Hello .
SELECT LTRIM(:HELLO)
FROM SYSIBM.SYSDUMMY1;
The result is Hello .
 LTRIM( string-expression) 
LTRIM
234 SQL Reference
|
|
|
MAX
The schema is SYSIBM.
The MAX scalar function returns the maximum value in a set of values. The
arguments must be compatible. For more information on compatibility, refer to th
e
compatibility matrix in Table 9 on page 65. All but the first argument can be
parameter markers. There must be two or more arguments.
The argument values can be of any built-in data type other than a CLOB, DBCLOB,
BLOB, or row ID. Character string arguments cannot have an actual length greater
than 255, and graphic string arguments cannot have an actual length greater than
127.
The selected argument is converted, if necessary, to the attributes of the resul
t. The
attributes of the result are determined using the “Rules for result data types” on
page 77. If the MAX function has more than two arguments, the rules are applied
to
the first two arguments to determine a candidate result type. The rules are then
applied to that candidate result type and the third argument to determine anothe
r
candidate result type. This process continues until all arguments are analyzed a
nd
the final result type is determined.
The result can be null if at least one argument can be null; the result is the n
ull
value if one of the arguments is null.
Example 1: Assume the host variable M1 is a DECIMAL(2,1) host variable with a
value of 5.5, host variable M2 is a DECIMAL(3,1) host variable with a value of 4
.5,
and host variable M3 is a DECIMAL(3,2) host variable with a value of 6.25. The
function
MAX(:M1,:M2,:M3)
returns the value 6.25.
Example 2: Assume the host variable M1 is a CHAR(2) host variable with a value o
f
’AA’, host variable M2 is a CHAR(3) host variable with a value of ’AA ’, and host
variable M3 is a CHAR(4) host variable with a value of ’AA A’. The function
MAX(:M1,:M2,:M3)
returns the value ’AAA’.
 
(1)
MAX(expression ,expression ) 
Notes:
1 GREATEST can be specified as an alternative to MAX.
MAX
Chapter 3. Built-in functions 235
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MICROSECOND
The schema is SYSIBM.
The MICROSECOND function returns the microsecond part of its argument.
The argument must be a time, timestamp, a timestamp duration, or a valid string
representation of a timestamp. A string representation must not be a BLOB, CLOB,
or DBCLOB and must have an actual length that is not greater than 255 bytes. (Fo
r
the valid formats of string representations of times and timestamps, see “String
representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a time, timestamp or string representation of either, the
result is the microsecond part of the value, which is an integer between 0 and
999999.
If the argument is a duration, the result is the microsecond part of the value,
which is an integer between -999999 and 999999. A nonzero result has the
same sign as the argument.
Example: Assume that table TABLEX contains a TIMESTAMP column named
TSTMPCOL and a SMALLINT column named INTCOL. Select the microseconds
part of the TSTMPCOL column of the rows where the INTCOL value is 1234:
SELECT MICROSECOND(TSTMPCOL) FROM TABLEX
WHERE INTCOL = 1234;
 MICROSECOND(expression) 
MICROSECOND
236 SQL Reference
|
|
|
|
|
|
|
|
MIDNIGHT_SECONDS
The schema is SYSIBM.
The MIDNIGHT_SECONDS function returns an integer value in the range of 0 to
86400 that represents the number of seconds between midnight and the time
specified by the argument.
The argument must be a time, a timestamp, or a valid string representation of a
time or timestamp. A string representation must not be a BLOB, CLOB,or DBCLOB,
and must have an actual length that is not greater than 255 bytes. (For the vali
d
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: Find the number of seconds between midnight and 00:01:00, and
midnight and 13:10:10. Assume that host variable XTIME1 has a value of 00:01:00
,
and that XTIME2 has a value of 13:10:10 .
SELECT MIDNIGHT_SECONDS(:XTIME1), MIDNIGHT_SECONDS(:XTIME2)
FROM SYSIBM.SYSDUMMY1;
This example returns 60 and 47410. Because there are 60 seconds in a minute and
3600 seconds in an hour, 00:01:00 is 60 seconds after midnight ((60 * 1) + 0), a
nd
13:10:10 is 47410 seconds ((3600 * 13) + (60 * 10) + 10).
Example 2: Find the number of seconds between midnight and 24:00:00, and
midnight and 00:00:00.
SELECT MIDNIGHT_SECONDS( 24:00:00 ), MIDNIGHT_SECONDS( 00:00:00 )
FROM SYSIBM.SYSDUMMY1;
This example returns 86400 and 0. Although these two values represent the same
point in time, different values are returned.
 MIDNIGHT_SECONDS(expression) 
MIDNIGHT_SECONDS
Chapter 3. Built-in functions 237
|
|
|
|
|
MIN
The schema is SYSIBM.
The MIN scalar function returns the minimum value in a set of values. The
arguments must be compatible. For more information on compatibility, refer to th
e
compatibility matrix in Table 9 on page 65. All but the first argument can be
parameter markers. There must be two or more arguments.
The argument values can be of any built-in data type other than a CLOB, DBCLOB,
BLOB, or row ID. Character string arguments cannot have an actual length greater
than 255, and graphic string arguments cannot have an actual length greater than
127.
The selected argument is converted, if necessary, to the attributes of the resul
t. The
attributes of the result are determined using the “Rules for result data types” on
page 77. If the MIN function has more than two arguments, the rules are applied
to
the first two arguments to determine a candidate result type. The rules are then
applied to that candidate result type and the third argument to determine anothe
r
candidate result type. This process continues until all arguments are analyzed a
nd
the final result type is determined.
The result can be null if at least one argument can be null; the result is the n
ull
value if one of the arguments is null.
Example 1: Assume the host variable M1 is a DECIMAL(2,1) host variable with a
value of 5.5, host variable M2 is a DECIMAL(3,1) host variable with a value of 4
.5,
and host variable M3 is a DECIMAL(3,2) host variable with a value of 6.25. The
function
MIN(:M1,:M2,:M3)
returns the value 4.5.
Example 2: Assume the host variable M1 is a CHAR(2) host variable with a value o
f
’AA’, host variable M2 is a CHAR(3) host variable with a value of ’AAA’, and host
variable M3 is a CHAR(4) host variable with a value of ’AAAA’. The function
MIN(:M1,:M2,:M3)
returns the value ’AA’ .
 
(1)
MIN(expression ,expression ) 
Notes:
1 LEAST can be specified as an alternative to MIN.
MIN
238 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MINUTE
The schema is SYSIBM.
The MINUTE function returns the minute part of its argument.
The argument must be a time, a timestamp, time duration, timestamp duration, or
a
valid string representation of a time or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. (For the valid formats of string representations of times and
timestamps, see “String representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a time, timestamp, or string representation of either, the
result is the minute part of the value, which is an integer between 0 and 59.
If the argument is a time duration or timestamp duration, the result is the
minute part of the value, which is an integer between -99 and 99. A nonzero
result has the same sign as the argument.
Example: Assume that a table named CLASSES contains one row for each
scheduled class. Assume also that the class starting times are in the TIME colum
n
named STARTTM. Using these assumptions, select those rows in CLASSES that
represent classes that start on the hour.
SELECT * FROM CLASSES
WHERE MINUTE(STARTTM) = 0;
 MINUTE(expression) 
MINUTE
Chapter 3. Built-in functions 239
|
|
|
|
|
MOD
The schema is SYSIBM.
The MOD function divides the first argument by the second argument and returns
the remainder.
The formula used to calculate the remainder is:
MOD(x,y) = x - (x/y) * y
where x/y is the truncated integer result of the division.
The arguments must each be an expression that returns a value of any built-in
numeric data type. The second argument cannot be zero.
If an argument can be null, the result can be null; if an argument is null, the
result is
the null value.
The attributes of the result are based on the arguments as follows:
v If both arguments are integers, the data type of the result is a large integer
.
v If one argument is an integer and the other is a decimal, the data type of the
result is decimal with the same precision and scale as the decimal argument.
v If both arguments are decimal, the data type of the result is decimal. The
precision of the result is min(p-s,p’-s’) + max(s,s’), and the scale of the result is
max(s,s’), where the symbols p and s denote the precision and scale of the first
operand, and the symbols p’ and s’ denote the precision and scale of the second
operand.
v If either argument is a floating-point number, the data type of the result is
double
precision floating-point.
The operation is performed in floating-point. If necessary, the operands are fir
st
converted to double precision floating-point numbers. For example, an operation
that involves a floating-point number and either an integer or a decimal number
is
performed with a temporary copy of the integer or decimal number that has been
converted to double precision floating-point. The result of a floating-point
operation must be within the range of floating-point numbers.
Example: Assume that M1 and M2 are two host variables. Find the remainder of
dividing M1 by M2.
SELECT MOD(:M1,:M2)
FROM SYSIBM.SYSDUMMY1;
The following table shows the result for this function for various values of M1
and
M2.
M1 data type M1 value M2 data type M2 value
Result of
MOD(:M1,:M2)
INTEGER 5 INTEGER 2 1
INTEGER 5 DECIMAL(3,1) 2.2 0.6
 MOD(expression,expression) 
MOD
240 SQL Reference
M1 data type M1 value M2 data type M2 value
Result of
MOD(:M1,:M2)
INTEGER 5 DECIMAL(3,2) 2.20 0.60
DECIMAL(4,2) 5.50 DECIMAL(4,1) 2.0 1.50
MOD
Chapter 3. Built-in functions 241
MONTH
The schema is SYSIBM.
The MONTH function returns the month part of its argument.
The argument must be a date, a timestamp, date duration, timestamp duration, or
a
valid string representation of a date or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. (For the valid formats of string representations of dates and
timestamps, see “String representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a date, timestamp, or string representation of either, the
result is the month part of the value, which is an integer between 1 and 12.
If the argument is a date duration or timestamp duration, the result is the
month part of the value, which is an integer between -99 and 99. A nonzero
result has the same sign as the argument.
Example: Select all rows in the sample table DSN8710.EMP for employees who
were born in May:
SELECT * FROM DSN8710.EMP
WHERE MONTH(BIRTHDATE) = 5;
 MONTH(expression) 
MONTH
242 SQL Reference
|
|
|
|
|
|
|
MULTIPLY_ALT
The schema is SYSIBM.
The MULTIPLY_ALT scalar function returns the product of the two arguments as a
decimal value. It is provided as an alternative to the multiplication operator,
especially when the sum of the precisions of the arguments exceeds 31.
The arguments can be any built-in exact numeric data type (DECIMAL, INTEGER,
or SMALLINT).
The result of the function is a DECIMAL. The precision and scale of the result a
re
determined as follows, using the symbols p and s to denote the precision and sca
le
of the first argument, and the symbols p’ and s’ to denote the precision and scale o
f
the second argument.
v The precision is MIN(31, p+p’)
v The scale is:
– 0 if the scale of both arguments is 0
– MIN(31, s+s’) if p+p’ is less than or equal to 31
– MAX( MIN(3, s+s’), 31-(p-s+p’-s’) ) if p+p’ is greater than 31.
The result can be null if at least one argument can be null; the result is the n
ull
value if one of the arguments is null.
The MULTIPLY_ALT function is a better choice than the multiplication operator
when performing decimal arithmetic where a scale of at least 3 is desired and th
e
sum of the precisions exceeds 31. In these cases, the internal computation is
performed so that overflows are avoided and then assigned to the result type val
ue
using truncation for any loss of scale in the final result. Note that the possib
ility of
overflow of the final result is still possible when the scale is 3.
The following table compares the result types using MULTIPLY_ALT and the
multiplication operator:
Type of Argument1 Type of Argument2 Result using
MULTIPLY_ALT
Result using
multiplication
operator
DECIMAL(31,3) DECIMAL(15,8) DECIMAL(31,3) DECIMAL(31,11)
DECIMAL(26,23) DECIMAL(10,1) DECIMAL(31,19) DECIMAL(31,24)
DECIMAL(18,17) DECIMAL(20,19) DECIMAL(31,29) DECIMAL(31,31)
DECIMAL(16,3) DECIMAL(17,8) DECIMAL(31,9) DECIMAL(31,11)
DECIMAL(26,5) DECIMAL(11,0) DECIMAL(31,3) DECIMAL(31,5)
DECIMAL(21,1) DECIMAL(15,1) DECIMAL(31,2) DECIMAL(31,2)
 MULTIPLY_ALT(exact-numeric-expression,exact-numeric-expression) 
MULTIPLY_ALT
Chapter 3. Built-in functions 243
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
| |||
|
|
|
|
|
|
|
NEXT_DAY
The schema is SYSIBM.
The NEXT_DAY scalar function returns a timestamp that represents the first
weekday, named by expression, that is later than the date date-expression. If
expression is a timestamp or valid string representation of a timestamp, the
timestamp value has the same hours, minutes, seconds, and microseconds as
expression. If expression is a date, or a valid string representation of a date,
then
the hours, minutes, seconds, and microseconds value of the result is 0.
The result of the function is a TIMESTAMP. The result can be null; if any argume
nt
is null, the result is the null value.
date-expression must be a date, a timestamp, or a valid string representation of
a
date or timestamp. A string representation must not be a BLOB, CLOB, or
DBCLOB, and must have an actual length that is not greater than 255 bytes. For
the valid formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
expression is the day of the week specified as follows:
Day of week Abbreviation
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
MON
TUE
WED
THU
FRI
SAT
SUN
expression can be specified as either the full name or the abbreviation. The
minimum length of the input is the length of the abbreviated version. Any charac
ters
immediately following a valid abbreviation are ignored.
Example 1: Set the host variable NEXTDAY with the date of the Tuesday following
April 24, 2000.
SET :NEXTDAY = NEXT_DAY(CURRENT_DATE, TUESDAY );
The host variable NEXTDAY is set with the value of
’2000–04–25–00.00.00.000000’, assuming that the value of the CURRENT_DATE
special register is ’2000–04–24’.
Example 2: Set the host variable NEXTDAY with the date of the first Monday in
May, 2000. Assume the host variable DAYHV = ’MON’.
SET :NEXTDAY = NEXT_DAY(LAST_DAY(CURRENT_TIMESTAMP),:DAYHV);
The host variable NEXTDAY is set with the value of ’2000-05-01-12.01.01.123456’,
assuming that the value of the CURRENT_TIMESTAMP special register is
’2000-04-24-12.01.01.123456’.
 NEXT_DAY(date-expression,expression) 
NEXT_DAY
244 SQL Reference
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|||||||
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
NULLIF
The schema is SYSIBM.
The NULLIF function returns null if the two arguments are equal; otherwise, it
returns the value of the first argument.
The two arguments must be compatible. (See the compatibility matrix in Table 9 o
n
page 65.) Neither argument can be a BLOB, CLOB, or DBCLOB. The attributes of
the result are the attributes of the first argument. Any numbers specified must
be of
a built-in numeric data type.
For example, if the result of the first argument is a character string, the resu
lt of the
other must also be a character string; if the result of the first argument is nu
mber,
the result of the other must also be a number.
The result of using NULLIF(e1,e2) is the same as using the CASE expression:
CASE WHEN e1=e2 THEN NULL ELSE e1 END
When e1=e2 evaluates to unknown because one or both arguments is null, CASE
expressions consider the evaluation not true. In this case, NULLIF returns the v
alue
of the first argument.
Example: Assume that host variables PROFIT, CASH, and LOSSES have decimal
data types with the values of 4500.00, 500.00, and 5000.00 respectively. The
following function returns a null value:
NULLIF (:PROFIT + :CASH , :LOSSES)
 NULLIF(expression,expression) 
NULLIF
Chapter 3. Built-in functions 245
POSSTR
The schema is SYSIBM.
The POSSTR function returns the starting position of the first occurrence of one
string (the search-string) within another string (the source-string). Numbers fo
r the
starting position begin at 1 and not 0.
source-string
An expression that specifies the source string that is to be searched. The
source string can be a character, graphic, or binary string. The expression can
be specified by any of the following:
v A constant
v A special register
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above
v A column name
v A CAST specification whose arguments are any of the above
v An expression that concatenates (using CONCAT or ||) any of the above
search-string
An expression that specifies the string that is to be searched for. The search
string can be a character, graphic, or binary string with an actual length that
is
no greater than 4000 bytes. The expression can be specified by any of the
following:
v A constant
v A special register
v A host variable (including a LOB locator variable)
v A scalar function whose arguments are any of the above
v A column name
v A CAST specification whose arguments are any of the above
v An expression that concatenates (using CONCAT or ||) any of the above
These rules are similar to those that are described for pattern-expression for t
he
LIKE predicate.
The first and second arguments must have compatible string types. For more
information on compatibility, see “Conversion rules for string comparison” on
page 73.
Both search-string and source-string have zero or more contiguous positions. For
character strings and binary strings, a position is a byte. For graphic strings,
a
position is a DBCS character. Graphic Unicode data is treated as UTF-16 data; a
UTF-surrogate character takes two DBCS characters to represent and as such is
counted as two DBCS characters.
The strings can contain mixed data.
v For ASCII data, if the search string or source string contains mixed data, the
search string is found only if the same combination of single-byte and
double-byte characters are found in the source string in exactly the same
positions.
 POSSTR(source-string,search-string) 
POSSTR
246 SQL Reference
|
|
|
|
|
|
v For EBCDIC data, if the search string or source string contains mixed data, th
e
search string is found only if any shift-in or shift-out characters are found in
the
source string in exactly the same positions, ignoring any redundant shift
characters.
v For UTF-8 data, if the search string or source string contains mixed data, the
search string is found only if the same combination of single-byte and multi-byt
e
characters are found in the source string in exactly the same position.
The result of the function is a large integer. If either of the arguments can be
null,
the result can be null; if either of the arguments are null, the result is the n
ull value.
The value of the result is determined by applying these rules in the order in wh
ich
they appear:
v If the length of the search string is zero, the result is 1.
v If the length of the source string is zero, the result is 0.
v If the value of the search string is equal to an identical length substring of
contiguous positions from the value of the source string, the result is the star
ting
position of the first such substring within the value of the source string.
v If none of the above conditions are met, the result is 0.
Example: Select the RECEIVED column, the SUBJECT column, and the starting
position of the string GOOD BEER within the NOTE_TEXT column for all rows in
the IN_TRAY table that contain that string.
SELECT RECEIVED, SUBJECT, POSSTR(NOTE_TEXT, GOOD BEER )
FROM IN_TRAY
WHERE POSSTR(NOTE_TEXT, GOOD BEER ) <> 0;
POSSTR
Chapter 3. Built-in functions 247
|
|
|
POWER
The schema is SYSIBM.
The POWER function returns the value of expression1 to the power of expression2.
Each argument is an expression that returns the value of any built-in numeric da
ta
type. If either argument includes a DECIMAL or REAL data type, the arguments are
converted to a double precision floating-point number for processing by the func
tion.
The result of the function depends on the data type of the arguments:
v If both arguments are SMALLINT or INTEGER, the result is INTEGER.
v Otherwise, the result is DOUBLE.
The result can be null; if any argument is null, the result is the null value.
Example 1: Assume that host variable HPOWER is INTEGER with a value of 3. The
following statement:
SELECT POWER(2,:HPOWER)
FROM SYSIBM.SYSDUMMY1;
returns the value 8.
Example 2: The following statement:
SELECT POWER(0,0)
FROM SYSIBM.SYSDUMMY1;
returns the value 1.
 POWER(expression1,expression2) 
POWER
248 SQL Reference
QUARTER
The schema is SYSIBM.
The QUARTER function returns an integer in the range of 1 to 4 that represents t
he
quarter of the year in which the date occurs. For example, the function returns
a 1
for any dates in January, February, or March.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. (For the vali
d
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: The following function returns 3 because August is in the third quart
er
of the year.
SELECT QUARTER( 1996-08-25 )
FROM SYSIBM.SYSDUMMY1
Example 2: Using sample table DSN8710.PROJ, set the integer host variable
QUART to the quarter of the year in which activity number 70 for project AD3111
occurred. Activity completion dates are recorded in column ACENDATE.
SELECT QUARTER(ACENDATE)
INTO :QUART
FROM DSN8710.PROJ
WHERE PROJNO = AD3111 AND ACTNO = 70;
QUART is set to 4.
 QUARTER(expression) 
QUARTER
Chapter 3. Built-in functions 249
|
|
|
|
|
RADIANS
The schema is SYSIBM.
The RADIANS function returns the number of radians for an argument that is
expressed in degrees.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HDEG is an INTEGER with a value of 180.
The following statement:
SELECT RADIANS(:HDEG)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of
3.1415926536.
 RADIANS(expression) 
RADIANS
250 SQL Reference
RAISE_ERROR
The schema is SYSIBM.
The RAISE_ERROR function causes the statement that includes the function to
return an error with the specified SQLSTATE (along with SQLCODE -438) and error
condition. The RAISE_ERROR function always returns NULL with an undefined
data type.
sqlstate
An expression that returns a character string (CHAR or VARCHAR) of exactly 5
characters. The sqlstate value must follow these rules for application-defined
SQLSTATEs:
v Each character must be from the set of digits ( 0 through 9 ) or non-accente
d
upper case letters ( A through Z ).
v The SQLSTATE class (first two characters) cannot be 00 , 01 , or 02
because these are not error classes.
v If the SQLSTATE class (first two characters) starts with the character 0
through 6 or A through H , the subclass (last three characters) must start
with a letter in the range I through Z .
v If the SQLSTATE class (first two characters) starts with the character 7 , 8
,
9 , or I though Z , the subclass (last three characters) can be any of 0
through 9 or A through Z .
diagnostic-string
An expression that returns a character string with a data type of CHAR or
VARCHAR and a length of up to 70 bytes. The string contains EBCDIC data
that describes the error condition. If the string is longer than 70 bytes, it is
truncated.
To use this function in a context where “Rules for result data types” on page 77 do
not apply, such as alone in a select list, you must use a cast specification to
give a
data type to the null value that is returned. The RAISE_ERROR function is most
useful with CASE expressions.
Example: For each employee in sample table DSN8710.EMP, list the employee
number and education level. List the education level as Post Graduate, Graduate
and Diploma instead of the integer that it is stored as in the table. If an educ
ation
level is greater than 20, raise an error ( 70001 ) with a description.
SELECT EMPNO,
CASE WHEN EDLEVEL < 16 THEN Diploma
WHEN EDLEVEL < 18 THEN Graduate
WHEN EDLEVEL < 21THEN Post Graduate
ELSE RAISE_ERROR( 70001 ,
EDUCLVL has a value greater than 20 )
END
FROM DSN8710.EMP;
 RAISE_ERROR(sqlstate,diagnostic-string) 
RAISE_ERROR
Chapter 3. Built-in functions 251
RAND
The schema is SYSIBM.
The RAND function returns a random floating-point value between 0 and 1. An
argument can be used as an optional seed value.
If an argument is specified, it must be an integer (SMALLINT or INTEGER) between
0 and 2 147 483 646.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HRAND is an INTEGER with a value of 100.
The following statement:
SELECT RAND(:HRAND)
FROM SYSIBM.SYSDUMMY1;
returns a random floating-point number between 0 and 1, such as the approximate
value .0121398.
To generate values in a numeric interval other than 0 to 1, multiply the RAND
function by the size of the desired interval. For example, to get a random numbe
r
between 0 and 10, such as the approximate value 5.8731398, multiply the function
by 10:
SELECT (RAND(:HRAND) * 10)
FROM SYSIBM.SYSDUMMY1;
 RAND( )
expression

RAND
252 SQL Reference
REAL
The schema is SYSIBM.
The REAL function returns a single precision floating-point representation of a
number or string in the form of a numeric constant.
numeric-expression
The argument is an expression that returns a value of any built-in numeric data
type.
The result of the function is a single precision floating-point number. The resu
lt
is the same number that would occur if the argument were assigned to a single
precision floating-point column or variable. If the numeric value of the argumen
t
is not within the range of single precision floating-point, an error occurs.
string-expression
An expression that returns any type of string (except a BLOB, CLOB, or
DBCLOB) with an actual length that is not greater than 255 bytes. Leading and
trailing blanks are removed from the string, and the resulting substring must
conform to the rules for forming a string representation of an SQL floating-poin
t
constant.
The result of the function is a single precision floating-point number. The resu
lt
is the same number that would occur if the corresponding numeric constant
were assigned to a single precision floating-point column or variable.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Using sample table DSN8710.EMP, find the ratio of salary to commission
for employees whose commission is not zero. The columns involved, SALARY and
COMM, have decimal data types. To express the result in single precision
floating-point, apply REAL to SALARY so that the division is carried out in
floating-point (actually double precision) and then apply REAL to the complete
expression so that the results are returned in single precision floating-point.
SELECT EMPNO, REAL(REAL(SALARY)/COMM)
FROM DSN8710.EMP
WHERE COMM > 0;
 REAL( numeric-expression )
string-expression

REAL
Chapter 3. Built-in functions 253
|
|
REPEAT
The schema is SYSIBM.
The REPEAT function returns a string composed of expression repeated integer
times.
expression
An expression that specifies the string to be repeated. The string must be any
type of character string except a CLOB, or any type of graphic string except a
DBCLOB. The actual length of the string must be 32767 bytes or less.
integer
An expression whose value is a positive integer. The integer specifies the
number of times to repeat the string.
The result of the function depends on the data type of the first argument:
v VARCHAR if expression is a character string
v VARGRAPHIC if expression is graphic string
If integer is a constant, the length attribute of the result is the length attri
bute of
expression times integer. Otherwise, the length attriubte depends on the data ty
pe
of the result:
v 4000 for VARCHAR
v 2000 for VARGRAPHIC
The actual length of the result is the actual length of expression times integer
. If the
actual length of the result string exceeds the maximum for the return type, an e
rror
occurs.
If any argument can be null, the result can be null; if any argument is null, th
e result
is the null value.
The subtype and CCSID of the result are determined as follows:
v If expression is character bit data, the result is bit data and does not have
an
associated CCSID.
v If expression is character SBCS data, the result is SBCS data and the CCSID is
the CCSID for ASCII, EBCDIC, or Unicode SBCS data, depending on the
encoding scheme of the SQL statement.
v If expression is graphic data, the result is graphic data and the CCSID is the
CCSID for ASCII, EBCDIC, or Unicode graphic data, depending on the encoding
scheme of the SQL statement.
v Otherwise, the result is mixed data. The CCSID is the CCSID for ASCII,
EBCDIC, or Unicode mixed data, depending on the encoding scheme of the SQL
statement.
Example 1: Repeat abc two times to create abcabc .
SELECT REPEAT( abc ,2)
FROM SYSIBM.SYSDUMMY1;
 REPEAT(expression,integer) 
REPEAT
254 SQL Reference
|
|
|
Example 2: List the phrase REPEAT THIS five times. Use the CHAR function to
limit the output to 60 bytes.
SELECT CHAR(REPEAT( REPEAT THIS ,5), 60)
FROM SYSIBM.SYSDUMMY1;
This example results in REPEAT THISREPEAT THISREPEAT THISREPEAT
THISREPEAT THIS .
Example 3: For the following query, the LENGTH function returns a value of 0
because the result of repeating a string zero times is an empty string, which is
a
zero-length string.
SELECT LENGTH(REPEAT( REPEAT THIS ,0))
FROM SYSIBM.SYSDUMMY1;
Example 4: For the following query, the LENGTH function returns a value of 0
because the result of repeating an empty string any number of times is an empty
string, which is a zero-length string.
SELECT LENGTH(REPEAT( , 5))
FROM SYSIBM.SYSDUMMY1;
REPEAT
Chapter 3. Built-in functions 255
REPLACE
The schema is SYSIBM.
The REPLACE function replaces all occurrences of expression2 in expression1 with
expression3. If expression2 is not found in expression1, expression1 is returned
unchanged.
expression1
An expression that specifies the source string. The expression cannot be an
empty string.
expression2
An expression that specifies the string to be removed from the source string.
The expression cannot be an empty string.
expression3
An expression that specifies the replacement string.
The arguments must have compatible string types. For more information on
compatibility, see “Conversion rules for string comparison” on page 73. If the
arguments are character strings, none must be a CLOB. If the arguments are
graphic strings, none must be a DBCLOB. The actual length of each string must be
32767 bytes or less.
The result of the function depends on the data type of the arguments:
v VARCHAR if the arguments are character strings
v VARGRAPHIC if the arguments are graphic strings
The length attribute of the result depends on the arguments:
v If the length attribute of expression3 is less than or equal to the length att
ribute
of expression2, the length attribute of the result is the length attribute of
expression1.
v Otherwise, the length attribute of the result is:
(L3 * (L1/L2)) + MOD(L1,L2)
where:
L1 is the length attribute of expression1
L2 is the length attribute of expression2
L3 is the length attribute of expression3
If the result is a character string, the length attribute of the result must not
exceed 4000. If the result is a graphic string, the length attribute of the resu
lt
must not exceed 2000.
The actual length of the result is the actual length of expression1 plus the num
ber
of occurrences of expression2 that exist in expression1 multiplied by the actual
length of expression3 minus the actual length of expression2. If the actual leng
th of
the result string exceeds the maximum for the return data type, an error occurs.
If any argument can be null, the result can be null; if any argument is null, th
e result
is the null value.
 REPLACE(expression1,expression2,expression3) 
REPLACE
256 SQL Reference
|
|
|
|
|
The subtype and CCSID of the result are determined as follows:
v If expression1, expression2, or expression3 is bit data, the result is bit dat
a and
does not have an associated CCSID.
v If all three expressions are character SBCS data, the result is SBCS data and
the CCSID is the CCSID for ASCII, EBCDIC, or Unicode SBCS data, depending
on the encoding scheme of the SQL statement.
v If all three expressions are graphic data, the result is graphic data and the
CCSID is the CCSID for ASCII, EBCDIC, or Unicode graphic data, depending on
the encoding scheme of the SQL statement.
v Otherwise, the result is mixed data. The CCSID is the CCSID for ASCII,
EBCDIC, or Unicode mixed data, depending on the encoding scheme of the SQL
statement.
Example 1: Replace all occurrences of the character N in the string DINING w
ith
VID . Use the CHAR function to limit the output to 10 bytes.
SELECT CHAR(REPLACE( DINING , N , VID ),10)
FROM SYSIBM.SYSDUMMY1:
The result is the string DIVIDIVIDG .
Example 2: Replace string ABC in the string ABCXYZ with nothing, which is th
e
same as removing ABC from the string.
SELECT REPLACE( ABCXYZ , ABC , )
FROM SYSIBM.SYSDUMMY1:
The result is the string XYZ .
Example 3: Replace string ABC in the string ABCCABCC with AB . This example
illustrates that the result can still contain the string that is to be replaced
(in this
case, ABC ) because all occurrences of the string to be replaced are identified
prior
to any replacement.
SELECT REPLACE( ABCCABCC , ABC , AB )
FROM SYSIBM.SYSDUMMY1:
The result is the string ABCABC .
REPLACE
Chapter 3. Built-in functions 257
|
|
|
RIGHT
The schema is SYSIBM.
The RIGHT function returns a string consisting of the specified number of rightm
ost
integer characters of string-expression. If string-expression is a character or
binary
string, a character is a byte. If string-expression is a graphic string, a chara
cter is a
DBCS character.
The CCSID of the result is the same as that of the string-expression.
string-expression
An expression that specifies the string from which the result is derived. The
string must be a character, graphic, or binary string. A substring of
string-expression is zero or more contiguous bytes of string-expression.
The string can contain mixed data. However, because the function operates on
a strict byte-count basis, the result is not necessarily a properly formed mixed
data character string.
integer
An expression that specifies the length of the result. The value must be an
integer between 0 and n, where n is the length attribute of string-expression.
The string-expression is effectively padded on the right with the necessary numb
er
of blank characters so that the specified substring of string-expression always
exists. The encoding scheme of the data determines the padding character:
v For ASCII SBCS data or ASCII mixed data, the padding character is X 20 .
v For ASCII DBCS data, the padding character depends on the CCSID; for
example, for Japan (CCSID 301) the padding character is X 8140 , while for
simplified Chinese it is X A1A1 .
v For EBCDIC SBCS data or EBCDIC mixed data, the padding character is X 40 .
v For EBCDIC DBCS data, the padding character is X 4040 .
v For Unicode SBCS data or UTF-8 data (Unicode mixed data), the padding
character is X 20 .
v For UTF-16 data (Unicode DBCS data), the padding character is X 0020 .
v For binary data, the padding character is X 00 .
The result of the function is a varying-length string with a length attribute th
at is the
same as the length attribute of string-expression and a data type that depends o
n
the data type of string-expression:
v VARCHAR if string-expression is CHAR or VARCHAR
v CLOB if string-expression is CLOB
v VARGRAPHIC if string-expression is GRAPHIC or VARGRAPHIC
v DBCLOB if string-expression is DBCLOB
v BLOB if string-expression is BLOB
If any argument of the function can be null, the result can be null; if any argu
ment is
null, the result is the null value. The CCSID of the result is the same as that
of
string-expression.
 RIGHT(string-expression,integer) 
RIGHT
258 SQL Reference
|
|
|
|
|
|
|
|
|
Example 1: Assume that host variable ALPHA has a value of ABCDEF . The
following statement:
SELECT RIGHT(ALPHA,3)
FROM SYSIBM.SYSDUMMY1;
returns the value DEF , which are the three rightmost characters in ALPHA.
Example 2: The following statement returns a zero length string.
SELECT RIGHT( ABCABC ,0)
FROM SYSIBM.SYSDUMMY1;
RIGHT
Chapter 3. Built-in functions 259
ROUND
The schema is SYSIBM.
The ROUND function returns expression1 rounded to expression2 places to the
right of the decimal point if expression2 is positive or to the left of the deci
mal point
if expression2 is zero or negative. For example, ROUND(748.58,-3) returns 700.
expression1
An expression that returns a value of any built-in numeric data type.
expression2
An expression that returns a small or large integer. The value of integer
specifies the number of places to the right of the decimal point for the result
if
expression2 is not negative. If expression2 is negative, expression1 is rounded
to the sum of the absolute value of expression2+1 number of places to the left
of the decimal point.
If the absolute value of expression2 is larger than the number of digits to the
left of the decimal point, the result is 0. (For example, ROUND(748.58,-4)
returns 0.)
If expression1 is positive, a value of 5 is rounded to the next higher positive
number. If expression1 is negative, a value of 5 is rounded to the next lower
negative number.
The result of the function has the same data type and length attribute as the fi
rst
argument except that the precision is increased by one if the argument is DECIMA
L
and the precision is less than 31. For example, an argument with a data type of
DECIMAL(5,2) results in DECIMAL(06,2). An argument with a data type of
DECIMAL(31,2) results in DECIMAL(031,2).
The result can be null. If any argument is null, the result is the null value.
Example 1: Calculate the number 873.726 rounded to 2, 1, 0, -1, -2, -3, and -4
decimal places respectively.
SELECT ROUND(873.726,2),
ROUND(873.726,1),
ROUND(873.726,0),
ROUND(873.726,-1),
ROUND(873.726,-2)
ROUND(873.726,-3),
ROUND(873.726,-4),
FROM SYSIBM.SYSDUMMY1;
This example returns the values 0873.730, 0873.700, 0874.000, 0870.000,
0900.000, 1000.000, and 0000.000.
Example 2: To demonstrate how numbers are rounded in positive and negative
values, calculate the numbers 3.5, 3.1, -3.1, -3.5 rounded to 0 decimal places.
 ROUND(expression1,expression2) 
ROUND
260 SQL Reference
#
#
#
SELECT ROUND(3.5,0),
ROUND(3.1,0),
ROUND(-3.1,0),
ROUND(-3.5,0)
FROM SYSIBM.SYSDUMMY1;
This example returns the values 04.0, 03.0, -03.0, and -04.0. (Notice that in th
e
positive value 3.5, 5 is rounded up to the next higher number while in the negat
ive
value -3.5, 5 is rounded down to the next lower negative number.)
ROUND
Chapter 3. Built-in functions 261
ROUND_TIMESTAMP
The schema is SYSIBM.
The ROUND_TIMESTAMP scalar function returns a timestamp that is the
timestamp-expression rounded to the unit specified by the format-string. If
format-string is not specified, timestamp-expression is rounded to the nearest d
ay,
as if ’DD’ is specified for format-string.
timestamp-expression must be a timestamp, or a valid string representation of a
timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB, and
must have an actual length that is not greater than 255 bytes. For the valid for
mats
of string representations of dates and timestamps, see “String representations of
datetime values” on page 57.
Allowable values for format-string are listed in Table 29.
The result of the function is a TIMESTAMP. The result can be null; if any argume
nt
is null, the result is the null value.
Notes
The following format models are used with the ROUND_TIMESTAMP and
TRUNC_TIMESTAMP functions.
Table 29. ROUND_TIMESTAMP and TRUNC_TIMESTAMP Format Models
Format Model Rounding or Truncating
Unit
ROUND_TIMESTAMP
Example
TRUNC_TIMESTAMP
Example
CC
SCC
One greater than the first
two digits of a four digit
year. (Rounds up on the
50th year of the century)
Input Value:
1897-12-04-12.22.22.000000
Result:
1900-01-01-00.00.00.000000
Input Value:
1897-12-04-12.22.22.000000
Result:
1800-01-01-00.00.00.000000
SYYYY
YYYY
YEAR
SYEAR
YYY
YY
Y
Year (Rounds up on July
1st)
Input Value:
1897-12-04-12.22.22.000000
Result:
1898-01-01-00.00.00.000000
Input Value:
1897-12-04-12.22.22.000000
Result:
1897-01-01-00.00.00.000000
IYYY
IYY
IY
I
ISO Year (Rounds up on
July 1st)
Input Value:
1897-12-04-12.22.22.000000
Result:
1898-01-01-00.00.00.000000
Input Value:
1897-12-04-12.22.22.000000
Result:
1897-01-01-00.00.00.000000
Q Quarter (Rounds up on the
sixteenth day of the second
month of the quarter)
Input Value:
1999-06-04-12.12.30.000000
Result:
1999-07-01-00.00.00.000000
Input Value:
1999-06-04-12.12.30.000000
Result:
1999-04-01-00.00.00.000000
MONTH
MON
MM
RM
Month (Rounds up on the
sixteenth day of the month)
Input Value:
1999-06-18-12.12.30.000000
Result:
1999-07-01-00.00.00.000000
Input Value:
1999-06-18-12.15.00.000000
Result:
1999-06-01-00.00.00.000000
 ROUND_TIMESTAMP(timestamp-expression )
,format-string

ROUND_TIMESTAMP
262 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
| ||
|| ||||
|||||||
|| ||||
||||
|| |
||
||||
||||
||
Table 29. ROUND_TIMESTAMP and TRUNC_TIMESTAMP Format Models (continued)
Format Model Rounding or Truncating
Unit
ROUND_TIMESTAMP
Example
TRUNC_TIMESTAMP
Example
WW Same day of the week as
the first day of the year
(Rounds up on the 12th
hour of the 3rd day of the
week, with respect to the
first day of the year)
Input Value:
2000-05-05-12.12.30.000000
Result:
2000-05-06-00.00.00.000000
Input Value:
2000-05-05-12.15.00.000000
Result:
2000-04-29-00.00.00.000000
IW Same day of the week as
the first day of the ISO year
(Rounds up on the 12th
hour of the 3rd day of the
week, with respect to the
first day of the ISO year)
Input Value:
2000-05-05-12.12.30.000000
Result:
2000-05-08-00.00.00.000000
Input Value:
2000-05-05-12.15.00.000000
Result:
2000-05-01-00.00.00.000000
W Same day of the week as
the first day of the month
(Rounds up on the 12th
hour of the 3rd day of the
week, with respect to the
first day of the month)
Input Value:
2000-05-17-12.12.30.000000
Result:
2000-05-15-00.00.00.000000
Input Value:
2000-05-17-12.15.00.000000
Result:
2000-05-15-00.00.00.000000
DDD
DD
J
Day (Rounds up on the 12th
hour of the day)
Input Value:
2000-05-17-12.59.59.000000
Result:
2000-05-18-00.00.00.000000
Input Value:
2000-05-17-12.59.59.000000
Result:
2000-05-17-00.00.00.000000
DAY
DY
D
Starting day of the week
(Rounds up with respect to
the 12th hour of the third
day of the week. The first
day of the week is always
Sunday).
Input Value:
2000-05-17-12.59.59.000000
Result:
2000-05-14-00.00.00.000000
Input Value:
2000-05-17-12.59.59.000000
Result:
2000-05-14-00.00.00.000000
HH
HH12
HH24
Hour (Rounds up at 30
minutes)
Input Value:
2000-05-17-23.59.59.000000
Result:
2000-05-18-00.00.00.000000
Input Value:
2000-05-17-23.59.59.000000
Result:
2000-05-17-23.00.00.000000
MI Minute (Rounds up at 30
seconds)
Input Value:
2000-05-17-23.58.45.000000
Result:
2000-05-17-23.59.00.000000
Input Value:
2000-05-17-23.58.45.000000
Result:
2000-05-17-23.58.00.000000
SS Second (Rounds up at
500000 microseconds)
Input Value:
2000-05-17-23.58.45.500000
Result:
2000-05-17-23.58.46.000000
Input Value:
2000-05-17-23.58.45.500000
Result:
2000-05-17-23.58.45.000000
Example
Set the host variable RND_TMSTMP with the input timestamp rounded to the
nearest year value.
SET :RND_TMSTMP = ROUND_TIMESTAMP(TIMESTAMP_FMT( 2000-08-14 17:30:00 ,
YYYY-MM-DD HH24:MM:SS , YEAR );
The value set is 2001-01-01-00.00.00.000000.
ROUND_TIMESTAMP
Chapter 3. Built-in functions 263
|
|
| ||
|
|||||
||||
|
|||||
||||
|
|||||
||||
|||
|| ||||
|||
||||||
||||
|||
|| ||||
|
| ||||
|
| ||||
|||||
||
|
||
|
ROWID
The schema is SYSIBM.
The ROWID function casts the input argument to a row ID.
The argument can be any type of character string, except a CLOB, with a maximum
length that is no greater than 255 bytes. Although the character string can cont
ain
any value, it is recommended that the character string contain a row ID value th
at
was previously generated by DB2 to ensure a valid row ID value is returned. For
example, the function can be used to convert a ROWID value that was cast to a
CHAR value back to a ROWID value.
If the actual length of expression is less than 40, the result is not padded. If
the
actual length of expression is greater than 40, the result is truncated. If non-
blank
characters are truncated, a warning is returned.
The result of the function is a row ID.
The length attribute of the result is 40. The actual length of the result is the
length
of expression.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value. However, a null row ID value cannot be used as the value for
a
row ID column in the database.
Example: Assume that table EMPLOYEE contains a ROWID column EMP_ROWID.
Also assume that the table contains a row that is identified by a row ID value t
hat is
equivalent to X F0DFD230E3C0D80D81C201AA0A280100000000000203 . Using
direct row access, select the employee number for that row.
SELECT EMPNO
FROM EMPLOYEE
WHERE EMP_ROWID=ROWID(X F0DFD230E3C0D80D81C201AA0A280100000000000203 );
 ROWID(expression) 
ROWID
264 SQL Reference
RTRIM
The schema is SYSIBM.
The RTRIM function removes blanks from the end of a string expression. The
RTRIM function returns the same results as the STRIP function with TRAILING
specified:
STRIP(string-expression,TRAILING)
string-expression must be any character string expression other than a CLOB or
any graphic string expression other than a DBCLOB. The characters that are
interpreted as trailing blanks depend on the encoding scheme of the data and the
data type:
v If the argument is a graphic string, then the trailing DBCS blanks are removed
. If
the data is encoded in ASCII, the ASCII CCSID determines the hex value that
represents a double-byte blank. For example, for Japan (CCSID 301), X 8140
represents a double-byte blank, while it is X A1A1 for Simplified Chinese. For
EBCDIC-encoded data, X 4040 represents a double-byte blank. For
Unicode-encoded data, X 0020 represents a double-byte blank.
v Otherwise, the trailing SBCS blanks are removed. For data that is encoded in
ASCII, X 20 represents a blank. For EBCDIC-encoded data, X 40 represents a
blank. For Unicode-encoded data, X 20 represents an SBCS or UTF-8 blank.
The result of the function depends on the data type of its argument:
v VARCHAR if the argument is a character string
v VARGRAPHIC if the argument is a graphic string
The length attribute of the result is the same as the length attribute of
string-expression. The actual length of the result is the length of the expressi
on
minus the number of characters removed. If all of the characters are removed, th
e
result is an empty string.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value. The CCSID of the result is the same as that of string-express
ion.
Example: Assume that host variable HELLO is defined as CHAR(9) and has a value
of Hello .
SELECT RTRIM(:HELLO)
FROM SYSIBM.SYSDUMMY1;
This example removes the trailing blanks and results in Hello .
 RTRIM(string-expression) 
RTRIM
Chapter 3. Built-in functions 265
|
|
|
|
SECOND
The schema is SYSIBM.
The SECOND function returns the seconds part of its argument.
The argument must be a time, a timestamp, time duration, timestamp duration, or
a
valid string representation of a date or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. (For the valid formats of string representations of times and
timestamps, see “String representations of datetime values” on page 57.)
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a time, timestamp, or string representation of either, the
result is the seconds part of the value, which is an integer between 0 and 59.
If the argument is a time duration or timestamp duration, the result is the
seconds part of the value, which is an integer between -99 and 99. A nonzero
result has the same sign as the argument.
Example 1: Assume that the variable TIME_DUR is declared in a PL/I program as
DECIMAL(6,0) and can therefore be interpreted as a time duration. Then, when
TIME_DUR has the value 153045:
SECOND(:TIME_DUR)
returns the value 45.
Example 2: Assume that RECEIVED is a TIMESTAMP column and that one of its
values is the internal equivalent of 1988-12-25-17.12.30.000000 . Then, for thi
s
value:
SECOND(RECEIVED)
returns the value 30.
 SECOND(expression) 
SECOND
266 SQL Reference
|
|
|
|
|
|
|
SIGN
The schema is SYSIBM.
The SIGN function returns an indicator of the sign of the argument. The returned
value is:
-1 if the argument is less than zero
0 if the argument is zero
1 if the argument is greater than zero
The argument is an expression that returns a value of any built-in numeric data
type, except DECIMAL(31,31).
The result of the function has the same data type and length attribute as the
argument except that when the argument is DECIMAL, the precision is increased by
one if the argument’s precision and scale are equal. For example, an argument with
a data type of DECIMAL(5,5) results in DECIMAL(6,5).
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Assume that host variable PROFIT is a large integer with a value of
50000.
SELECT SIGN(:PROFIT)
FROM SYSIBM.SYSDUMMY1;
This example returns the value 1.
 SIGN(expression) 
SIGN
Chapter 3. Built-in functions 267
SIN
The schema is SYSIBM.
The SIN function returns the sine of the argument, where the argument is an angl
e
expressed in radians. The SIN and ASIN functions are inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable SINE is DECIMAL(2,1) with a value of 1.5. The
following statement:
SELECT SIN(:SINE)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 0.
99.
 SIN(expression) 
SIN
268 SQL Reference
SINH
The schema is SYSIBM.
The SINH function returns the hyperbolic sine of the argument, where the argumen
t
is an angle expressed in radians.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HSINE is DECIMAL(2,1) with a value of 1.5.
The following statement:
SELECT SINH(:HSINE)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 2.
12.
 SINH(expression) 
SINH
Chapter 3. Built-in functions 269
SMALLINT
The schema is SYSIBM.
The SMALLINT function returns a small integer representation of a number or
character string in the form of a numeric constant.
numeric-expression
An expression that returns a value of any built-in numeric data type.
The result of the function is a small integer. The result is the same number tha
t
would occur if the argument were assigned to a small integer column or
variable. If the whole part of the argument is not within the range of small
integers, an error occurs. If present, the decimal part of the argument is
truncated.
string-expression
An expression that returns any type of string, (except a BLOB, CLOB, or
DBCLOB), with an actual length that is not greater than 255 bytes. Leading and
trailing blanks are removed from the string, and the resulting substring must
conform to the rules for forming a string representation of an SQL integer
constant.
The result of the function is a small integer. The result is the same number tha
t
would occur if the corresponding numeric constant were assigned to a small
integer column or variable.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Using sample table DSN8710.EMP, find the average education level
(EDLEVEL) of the employees in department A00 . Round the result to the nearest
full education level.
SELECT SMALLINT(AVG(EDLEVEL)+.5)
FROM DSN8710.EMP
WHERE DEPT = A00 ;
Assuming that the five employees in the department have education levels of 19,
18, 14, 18, and 14, the result is 17.
 SMALLINT( numeric-expression )
string-expression

SMALLINT
270 SQL Reference
|
|
SPACE
The schema is SYSIBM.
The SPACE function returns a character string that consists of the number of SBC
S
blanks that the argument specifies.
The argument is an expression that results in an integer. The integer specifies
the
number of SBCS blanks for the result, and it must be between 0 and 32767.
The result of the function is a varying-length character string (VARCHAR) that
contains SBCS data.
If expression is a constant, the length attribute of the result is the constant.
Otherwise, the length attribute of the result is 4000. The actual length of the
result
is the value of expression. The actual length of the result must not be greater
than
the length attribute of the result.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: The following statement returns a character string that consists of 5
blanks followed by a zero-length string.
SELECT SPACE(5), SPACE(0)
FROM SYSIBM.SYSDUMMY1;
 SPACE(expression) 
SPACE
Chapter 3. Built-in functions 271
SQRT
The schema is SYSIBM.
The SQRT function returns the square root of the argument.
The argument can be any built-in numeric data type. If the argument is not doubl
e
precision floating point, it is converted to a double precision floating-point n
umber
for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable SQUARE is defined as DECIMAL(2,1) and has
a value of 9.0. Find the square root of SQUARE.
SELECT SQRT(:SQUARE)
FROM SYSIBM.SYSDUMMY1;
This example returns a double precision floating-point number with an approximat
e
value of 3.
 SQRT(expression1) 
SQRT
272 SQL Reference
STRIP
The schema is SYSIBM.
The STRIP function removes blanks or another specified character from the end,
the beginning, or both ends of a string expression.
The first argument is an expression that returns any type of string except a BLO
B,
CLOB, or DBCLOB.
The second argument indicates whether characters are removed from the
beginning, the end, or both ends of the string. If you do not specify a second
argument, blanks are removed from both the beginning and end of the string.
The third argument is a single-character constant that indicates the SBCS or DBC
S
character that is to be removed. The first and third argument must have compatib
le
string types. For more information on compatibility, see “Conversion rules for str
ing
comparison” on page 73. If the data type is not appropriate or the value contains
more than one character, an error is returned.
If you do not specify the third argument, the following occurs:
v If the first argument is a graphic string, then the default strip character is
a DBCS
blank. The hex representation of a DBCS blank depends on the encoding
scheme and CCSID of the data. For example, for data encoded in ASCII, a
DBCS blank for Japan (CCSID 301) is X 8140 , while for simplified Chinese it is
X A1A1 . For EBCDIC DBCS, X 4040 is interpreted as a DBCS blank. For
UTF-16 (Unicode DBCS), X 0020 is interpreted as a DBCS blank.
v If the first argument is SBCS data, then the default strip character is an SBC
S
blank. If the data is encoded in ASCII, then X 20 represents a blank. If the da
ta
is encoded in EBCDIC, then X 40 represents a blank. If the data is encoded in
UTF-8 (Unicode mixed), then X 20 represents a blank.
The result of the function is a varying-length string with the same maximum leng
th
as the length attribute of the string. The actual length of the result is the le
ngth of
the expression minus the number of characters removed. If all of the characters
are
removed, the result is an empty, varying-length string.
The CCSID of the result is the same as that of the string. If the first argument
can
be null, the result can be null; if the first argument is null, the result is th
e null value.
Example 1: Assume that host variable HELLO is defined as CHAR(9) and has a
value of Hello :
STRIP(:HELLO)
 STRIP ( string-expression )
,BOTH
,B ,strip-character
,LEADING
,L
,TRAILING
,T

STRIP
Chapter 3. Built-in functions 273
|
|
|
|
|
|
|
This example results in Hello . If there had been any ending blanks, they would
have been removed, too.
Rewrite the example so that no beginning blanks are removed.
STRIP(:HELLO,TRAILING)
This results in Hello .
Example 2: Assume that host variable BALANCE is defined as CHAR(9) and has a
value of 000345.50 :
STRIP(:BALANCE,L, 0 )
This example results in 345.50 .
STRIP
274 SQL Reference
SUBSTR
The schema is SYSIBM.
The SUBSTR function returns a substring of a string.
string-expression
An expression that specifies the string from which the result is derived. The
string must be a character, graphic, or binary string. If string-expression is a
character string, the result of the function is a character string. If it is a g
raphic
string, the result of the function is a graphic string. If it is a binary string
, the
result of the function is a binary string.
A substring of string-expression is zero or more contiguous characters of string
.
If string-expression is a graphic string, a character is a DBCS character. If
string-expression is a character string or a binary string, a character is a byt
e.
The SUBSTR function accepts mixed data strings. However, because SUBSTR
operates on a strict byte-count basis, the result will not necessarily be a
properly formed mixed data string.
start
An expression that specifies the position within string-expression to be the fir
st
character of the result. The value of integer must be between 1 and the length
attribute of string-expression. (The length attribute of a varying-length string
is
its maximum length.) A value of 1 indicates that the first character of the
substring is the first character of string-expression.
length
An expression that specifies the length of the resulting substring. The length
must be an integer in the range 0 to n, where n is equal to L-S+1 (L is the
length attribute of string-expression and S is the value of start). The specifie
d
length must not be the integer constant 0.
If string-expression is a varying-length string and if length is explicitly spec
ified,
string-expression is effectively padded on the right with the necessary number
of characters so that the specified substring of string-expression always exists
.
Hexadecimal zeroes are used as the padding character when string-expression
is BLOB data. Otherwise, a blank that is appropriate for string-expression 23is
used as the padding character. If string-expression is a fixed-length string,
omission of length is an implicit specification of LENGTH(string-expression) -
start + 1, which is the number of characters from the character specified by
start to the last character of string-expression. If string-expression is a
varying-length string, omission of length is an implicit specification of zero o
r
LENGTH(string-expression) - start + 1, whichever is greater.
If length is explicitly specified by an integer constant that is 255 or less, th
e
result is a fixed-length string. If length is not explicitly specified, but
string-expression is a fixed-length string and start is an integer constant, the
result is a fixed-length string. In all other cases, the result is a varying-len
gth
string with a maximum length that is the same as the length attribute of
23. The appropriate blank is defined by the data type and sub-type (if necessary
) of string-expression
 SUBSTR(string-expression,start )
,length

SUBSTR
Chapter 3. Built-in functions 275
|
|
|
|
|
|
|
|
|
|
|
|
string-expression. The result is subject to the restrictions that apply to long
strings if its maximum length is greater than 255. These restrictions also apply
if
it is a graphic string whose maximum length is greater than 127.
If any argument of SUBSTR can be null, the result can be null. If any argument i
s
null, the result is the null value. The CCSID of the result is the CCSID of
string-expression.
Example 1: FIRSTNME is a VARCHAR(12) column in sample table DSN8710.EMP.
One of its values is the 5-character string MAUDE . When FIRSTNME has this valu
e:
Function ... Returns ...
SUBSTR(FIRSTNME,2,3) AUD
SUBSTR(FIRSTNME,2) AUDE
SUBSTR(FIRSTNME,2,6) AUDE followed by two blanks
SUBSTR(FIRSTNME,6) a zero-length string
SUBSTR(FIRSTNME,6,4) four blanks
Example 2: Sample table DSN8710.PROJ contains column PROJNAME, which is
defined as VARCHAR(24). Select all rows from that table for which the string in
PROJNAME begins with W L PROGRAM .
SELECT * FROM DSN8710.PROJ
WHERE SUBSTR(PROJNAME,1,12) = W L PROGRAM ;
Assume that the table has only the rows that were supplied by DB2. Then the
predicate is true for just one row, for which PROJNAME has the value W L PROGRA
M
DESIGN . The predicate is not true for the row in which PROJNAME has the value
W
L PROGRAMMING because, in the predicate’s string constant, PROGRAM is followed
by a
blank.
Example 3: Assume that a LOB locator named my_loc represents a LOB value that
has a length of 1 gigabyte. Assign the first 50 bytes of the LOB value to host
variable PORTION.
SET :PORTION = SUBSTR(:my_loc,1,50);
Example 4: Assume that host variable RESUME has a CLOB data type and holds
an employee’s resume. This example shows some of the statements that find the
section of department information in the resume and assign it to host variable
DeptBuf. First, the POSSTR function is used to find the beginning and ending
location of the department information. Within the resume, the department
information starts with the string Department Information Section and ends
immediately before the string Education Section . Then, using these beginning a
nd
ending positions, the SUBSTR function assigns the information to the host variab
le.
SET :DInfoBegPos = POSSTR(:RESUME, Department Information Section );
SET :DInfoEnPos = POSSTR(:RESUME, Education Section );
SET :DeptBuf = SUBSTR(:RESUME, :DInfoBegPos, :DInfoEnPos - :DInfoBegPos);
SUBSTR
276 SQL Reference
TAN
The schema is SYSIBM.
The TAN function returns the tangent of the argument, where the argument is an
angle expressed in radians. The TAN and ATAN functions are inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable TANGENT is DECIMAL(2,1) with a value of
1.5. The following statement:
SELECT TAN(:TANGENT)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of
14.10.
 TAN(expression) 
TAN
Chapter 3. Built-in functions 277
TANH
The schema is SYSIBM.
The TANH function returns the hyperbolic tangent of the argument, where the
argument is an angle expressed in radians. The TANH and ATANH functions are
inverse operations.
The argument is an expression that returns the value of any built-in numeric dat
a
type. If the argument is not a double precision floating-point number, it is con
verted
to one for processing by the function.
The result of the function is a double precision floating-point number. The resu
lt can
be null; if the argument is null, the result is the null value.
Example: Assume that host variable HTANGENT is DECIMAL(2,1) with a value of
1.5. The following statement:
SELECT TANH(:HTANGENT)
FROM SYSIBM.SYSDUMMY1;
returns a double precision floating-point number with an approximate value of 0.
90.
 TANH(expression) 
TANH
278 SQL Reference
TIME
The schema is SYSIBM.
The TIME function returns a time derived from its argument.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. (For the vali
d
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.)
If the argument is a string, the result the time or time part of the timestamp
represented by the string. If the CCSID of the string is not the same as the
corresponding default CCSID at the server, the string is first converted to that
CCSID. If the argument can be null, the result can be null; if the argument is n
ull,
the result is the null value.
The other rules depend on the data type of the argument:
If the argument is a time, the result is that time.
If the argument is a timestamp, the result is the time part of the timestamp.
If the argument is a character string, the result is the time or time part of th
e
timestamp represented by the character string. If the CCSID of the string is not
the same as the corresponding default CCSID at the server, the string is first
converted to that CCSID.
Example: Assume that a table named CLASSES contains one row for each
scheduled class. Assume also that the class starting times are in the TIME colum
n
named STARTTM. Using these assumptions, select those rows in CLASSES that
represent classes that start at 1:30 P.M.
SELECT *
FROM CLASSES
WHERE TIME(STARTTM) = 13:30:00 ;
 TIME(expression) 
TIME
Chapter 3. Built-in functions 279
|
|
|
|
|
|
|
|
|
|
TIMESTAMP
The schema is SYSIBM.
The TIMESTAMP function returns a timestamp derived from its argument or
arguments.
The rules for the arguments depend on whether the second argument is specified.
If only one argument is specified, it must be a timestamp, a valid string
representation of a timestamp, a character string of length 8, or a string of
length 14. The argument cannot be a BLOB, CLOB, or DBCLOB. (String
representations for a timestamp are described in “String representations of
datetime values” on page 57.)
A string of length 8 is assumed to be a System/390 Store Clock value.
A string of length 14 must be a string of digits that represents a valid date an
d
time in the form yyyymmddhhmmss, where yyyy is the year, mm is the month,
dd is the day, hh is the hour, mm is the minute, and ss is the seconds.
If both arguments are specified, the first argument must be a date or a valid
string representation of a date and the second argument must be a time or a
valid string representation of a time. Neither argument can be a BLOB, CLOB,
or DBCLOB. (Table 4 on page 58 and Table 5 on page 59 list the valid formats
for string representations for dates and times.)
The result of the function is a timestamp. If either argument can be null, the r
esult
can be null; if either argument is null, the result is the null value.
The other rules depend on whether the second argument is specified:
If both arguments are specified, the result is a timestamp with the date
specified by the first argument and the time specified by the second argument.
The microsecond part of the timestamp is zero.
If only one argument is specified and it is a timestamp, the result is that
timestamp.
If only one argument is specified and it is a string, the result is the
timestamp represented by that string. The timestamp represented by a string of
length 14 has a microsecond part of zero. The interpretation of a string as a
Store Clock value will yield a timestamp with a year between 1900 to 2042 as
described in ESA/390 Principles of Operation.
If an argument is a string with a CCSID that is not the same as the correspondin
g
default CCSID at the server, the string is first converted to that CCSID.
Example: Assume that table TABLEX contains a DATE column named DATECOL
and a TIME column named TIMECOL. For some row in the table, assume that
DATECOL represents 25 December 1988 and TIMECOL represents 17 hours, 12
minutes, and 30 seconds after midnight. Then, for this row:
TIMESTAMP(DATECOL, TIMECOL)
returns the value 1988-12-25-17.12.30.000000 .
 TIMESTAMP(expression )
,expression

TIMESTAMP
280 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
TIMESTAMP_FORMAT
The schema is SYSIBM.
The TIMESTAMP_FORMAT function returns a timestamp.
string-expression
An expression that returns any type of string (except a BLOB, CLOB, or
DBCLOB) with a maximum length that is not greater than 255 bytes. Leading
and trailing blanks are removed from the string, and the resulting substring is
interpreted as a timestamp using the format specified by format-string.
format-string
An expression that returns a character string constant with a maximum length
that is not greater than 255 bytes. format-string contains a template of how
string-expression is to be interpreted as a timestamp value. Leading and trailin
g
blanks are removed from the string, and the resulting substring must be a valid
template for a timestamp. The only valid format for the function is:
’YYYY-MM-DD HH24:MI:SS’
where:
YYYY 4-digit year
MM Month (01-12, January = 01)
DD Day of month (01-31)
HH24 Hour of day (00–24, when the value is 24, the minutes and seconds
must be 0).
MI Minutes (00–59)
SS Seconds (00–59)
The result of the function is a timestamp.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Set the character variable TVAR to the value of CREATEDTS from
SYSIBM.SYSDATABASE if it is equal to one second before the beginning of the
year 2000 (’1999-12-31 23:59:59’). The character string should be interpreted in the
only format that can be specified for the function.
SELECT VARCHAR_FORMAT(CREATEDTS, YYYY-MM-DD HH24:MI:SS )
INTO :TVAR
FROM SYSIBM.SYSDATABASE;
WHERE CREATEDTS =
TIMESTAMP_FORMAT( 1999-12-31 23:59:59 , YYYY-MM-DD HH24:MI:SS );

(1)
TIMESTAMP_FORMAT(string-expression,format-string) 
Notes:
1 TO_DATE can be specified as synonym for TIMESTAMP_FORMAT.
TIMESTAMP_FORMAT
Chapter 3. Built-in functions 281
TRANSLATE
The schema is SYSIBM.
The TRANSLATE function translates one or more characters of string-expression.
string-expression
An expression that specifies the string to be translated. The string must be a
character or graphic string. A character string argument must not be a CLOB
and must have an actual length that is not greater than 255. A graphic string
argument must not be a DBCLOB and must have an actual length that is not
greater than 127.
to-string
A string that specifies the characters to which certain characters in
string-expression are to be translated. This string is sometimes called the outp
ut
translation table. The string must be a character or graphic string. A character
string argument must not be a CLOB and must have an actual length that is not
greater than 255. A graphic string argument must not be a DBCLOB and must
have an actual length that is not greater than 127.
If the length of to-string is less than the length of from-string, to-string is
padded
to the length of from-string with the pad-character or a blank. If the length of
to-string is greater than from-string, the extra characters in to-string are ign
ored
without warning.
from-string
A string that specifies the characters that if found in string-expression are to
be
translated. This string is sometimes called the input translation table. When a
character in from-string is found, the character in string-expression is transla
ted
to the character in to-string that is in the corresponding position of the chara
cter
in from-string.
from-string must be a character or a graphic string. A character string argument
must not be a CLOB and must have an actual length that is not greater than
255. A graphic string argument must not be a DBCLOB and must have an
actual length that is not greater than 127.
If from-string contains duplicate characters, the first occurrence of the charac
ter
is used, and no warning is issued. The default value for from-string is a string
that starts with the character X 00 and ends with the character X FF (decimal
255).
pad-character
A string that specifies the character with which to pad to-string if its length
is
less than from-string. The string must be a character string (except a CLOB) or
a graphic string (except a DBCLOB) with a length of 1. A length of 1 is one
single byte for character strings and one double byte string for graphic
strings.The default is a blank that is appropriate for string-expression.
 TRANSLATE(string-expression )
, to-string
, ’ ’
, from-string
, pad-character

TRANSLATE
282 SQL Reference
|
|
|
All of the arguments must have the same string type. They must all be character
strings or all be graphic strings.
If string-expression is the only argument that is specified, the characters of i
ts value
are translated to uppercase based on the LC_CTYPE locale in effect for the
statement, which is determined by special register CURRENT LOCALE LC_CTYPE.
For example, a-z are translated to A-Z, and characters with diacritical marks ar
e
translated to their uppercase equivalent, if any. (For a description of the uppe
rcase
tables that are used for this translation, see IBM National Language Support
Reference Manual Volume 2.
If the LC_CTYPE locale is blank when the function is executed, the result of the
function depends on the data type of string-expression.
v For ASCII and EBCDIC, if string-expression specifies a graphic string expressi
on,
then an error occurs. For a character string expression, characters a-z are
translated to A-Z and characters with diacritical marks are not translated.
v For Unicode, string-expression can be either a character string expression or
a
graphic string expression, and LOCALE LC-CTYPE must be blank (no locale
specified). The characters a-z are translated to A-Z and all other characters,
including characters with diacritic marks, are left unchanged. If LOCALE
LC_CTYPE is not blank, an error occurs.
If more than one argument is specified, the result string is built
character-by-character from string-expression with each character in from-string
being translated to the corresponding character in to-string. For each character
in
string-expression, the from-string is searched for the same character. If the
character is found to be the nth character in from-string, the resulting string
will
contain the nth character from to-string. If to-string is less than n characters
long,
the resulting string will contain the pad-character. If the character is not fou
nd in
from-string, it is moved to the result string without being translated.
The string can contain mixed data. However, because the function operates on a
strict byte-count basis, the result is not necessarily a properly formed mixed d
ata
character string.
The length attribute, data type, subtype, and CCSID of the result are the same a
s
string-expression. If the first argument can be null, the result can be null. If
the
argument is null, the result is the null value.
Example 1: Return the string abcdef in uppercase characters. Assume that the
locale in effect is blank.
SELECT TRANSLATE ( abcdef )
FROM SYSIBM.SYSDUMMY1
The result is the value ABCDEF .
Example 2: Assume that host variable SITE has a data type of VARCHAR(30) and
contains Hanauma Bay .
SELECT TRANSLATE (:SITE)
FROM SYSIBM.SYSDUMMY1
Returns the value HANAUMA BAY . The result is all uppercase characters because
only one argument is specified.
SELECT TRANSLATE (:SITE, j , B )
FROM SYSIBM.SYSDUMMY1
TRANSLATE
Chapter 3. Built-in functions 283
|
|
|
|
|
|
|
|
|
|
Returns the value Hanauma jay .
SELECT TRANSLATE (:SITE, ei , aa )
FROM SYSIBM.SYSDUMMY1
Returns the value Heneume Bey .
SELECT TRANSLATE (:SITE, bA , Bay , % )
FROM SYSIBM.SYSDUMMY1
Returns the value HAnAumA bA% .
SELECT TRANSLATE (:SITE, r , Bu )
FROM SYSIBM.SYSDUMMY1
Returns the value Hana ma ray .
Example 3: Assume that host variable SITE has a data type of VARCHAR(30) and
contains Pivabiska Lake Place .
SELECT TRANSLATE (:SITE, $$ , Ll )
FROM SYSIBM.SYSDUMMY1
Returns the value Pivabiska $ake P$ace .
SELECT TRANSLATE (:SITE, pLA , Place , . )
FROM SYSIBM.SYSDUMMY1
Returns the value pivAbiskA LAk. pLA.. .
TRANSLATE
284 SQL Reference
TRUNCATE or TRUNC
The schema is SYSIBM.
The TRUNCATE or TRUNC function returns expression1 truncated to expression2
places to the right of the decimal point. If expression2 is negative, expression
1 is
truncated to the absolute value of expression2 places to the left of the decimal
point. If the absolute value of expression2 is larger than the number of digits
to the
left of the decimal point, the result is 0. For example, TRUNCATE(748.58,-4) ret
urns
0.
expression1
An expression that results in a value of any built-in numeric data type.
expression2
An expression that results in a small or large integer.
The result of the function has the same data type and length attribute as the fi
rst
argument. The result can be null. If any argument is null, the result is the nul
l value.
Example 1: Using sample employee table DSN8710.EMP, calculate the average
monthly salary for the highest paid employee. Truncate the result to two places
to
the right of the decimal point.
SELECT TRUNCATE(MAX(SALARY)/12,2)
FROM DSN8710.EMP;
Because the highest paid employee in the sample employee table earns $52750.00
per year, the example returns the value 4395.83.
Example 2: Return the number 873.726 truncated to 2, 1, 0, -1, and -2 decimal
places respectively.
SELECT TRUNC(873.726,2),
TRUNC(873.726,1),
TRUNC(873.726,0),
TRUNC(873.726,-1),
TRUNC(873.726,-2)
FROM TABLEX
WHERE INTCOL = 1234;
This example returns the values 873.720, 873.700, 873.000, 870.000, and 800.000.
 TRUNCATE (expression1,expression2)
TRUNC

TRUNCATE or TRUNC
Chapter 3. Built-in functions 285
TRUNC_TIMESTAMP
The schema is SYSIBM.
The TRUNC_TIMESTAMP scalar function returns a timestamp that is the
timestamp-expression truncated to the unit specified by the format-string. If
format-string is not specified, timestamp-expression is truncated to the nearest
day,
as if ’DD’ was specified for format-string.
timestamp-expression must be a timestamp, or a valid string representation of a
timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB, and
must have an actual length that is not greater than 255 bytes. For the valid for
mats
of string representations of dates and timestamps, see “String representations of
datetime values” on page 57.
Allowable values for format-string are listed in Table 29 on page 262.
The result of the function is a TIMESTAMP. The result can be null; if any argume
nt
is null, the result is the null value.
Example: Set the host variable TRNK_TMSTMP with the current year rounded to
the nearest year value.
SET :TRNK_TMSTMP = TRUNC_TIMESTAMP( 2000-03-14-17.30.00 , YEAR );
The host variable TRNK_TMSTMP is set with the value 2000-01-01-
00.00.00.000000.
 TRUNC_TIMESTAMP(timestamp-expression )
,format-string

TRUNC_TIMESTAMP
286 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
UCASE or UPPER
The schema is SYSIBM.
The UCASE or UPPER function returns a string in which all the characters have
been converted to uppercase characters.
string-expression
An expression that specifies the string to be converted. The string must be a
character or graphic string. A character string argument must not be a CLOB
and must have an actual length that is not greater than 255. A graphic string
argument must not be a DBCLOB and must have an actual length that is not
greater than 127.
The alphabetic characters of the argument are translated to uppercase characters
based on the value of the LC_CTYPE locale in effect for the statement. For
example, characters a-z are translated to A-Z, and characters with diacritical m
arks
are translated to their uppercase equivalent, if any. The locale is determined b
y
special register CURRENT LOCALE LC_CTYPE. For information about the special
register, see “CURRENT LOCALE LC_CTYPE” on page 86.
If the LC_CTYPE locale is blank when the function is executed, the result of the
function depends on the data type of string-expression.
v For ASCII and EBCDIC, if string-expression specifies a graphic string expressi
on,
then an error occurs. For a character string expression, characters a-z are
translated to A-Z and characters with diacritical marks are not translated.
v For Unicode, string-expression can be either a character string expression or
a
graphic string expression. The characters a-z are translated to A-Z and all othe
r
characters, including characters with diacritic marks, are left unchanged. If
LOCALE LC_CTYPE is not blank, an error occurs.
The length attribute, data type, subtype, and CCSID of the result are the same a
s
the expression. If the argument can be null, the result can be null; if the argu
ment is
null, the result is the null value.
Example: Return the string abcdef in uppercase characters. Assume that the loc
ale
in effect is blank.
SELECT TRANSLATE ( abcdef )
FROM SYSIBM.SYSDUMMY1
The result is the value ABCDEF .
 UCASE (string-expression)
UPPER

UCASE or UPPER
Chapter 3. Built-in functions 287
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
VARCHAR
The schema is SYSIBM.
The VARCHAR function returns a varying-length character string representation of
a
character string, graphic string, datetime value, integer number, decimal number
,
floating-point number, or row ID value.
The result of the function is a varying-length character string (VARCHAR). If th
e first
argument can be null, the result can be null; if the first argument is null, the
result is
the null value.
Character to Varchar
Character to Varchar:
 VARCHAR(character-expression )
, integer

Graphic to Varchar:
 VARCHAR(graphic-expression )
, integer

Datetime to Varchar:
 VARCHAR(datetime-expression) 
Integer to Varchar:
 VARCHAR(integer-expression) 
Decimal to Varchar:
 VARCHAR(decimal-expression )
, decimal-character

Floating-point to Varchar:
 VARCHAR(floating-point-expression) 
Row ID to Varchar:
 VARCHAR(row-ID-expression) 
VARCHAR
288 SQL Reference
|
character-expression
An expression that returns a value that is CHAR, VARCHAR, or CLOB data
type.
integer
The length attribute for the resulting varying-length character string. The valu
e
must be between 1 and 32767. If the length is not specified, the length of the
result is the same as the length of character-expression. If the first argument
is
mixed data, the second argument cannot be less than 4.
If the second argument is not specified and if the character-expression is an
empty string constant, the length attribute of the result is 1 and the result is
an
empty string. Otherwise, the length attribute of the result is the same as the
length attribute of the first argument.
The actual length of the result is the minimum of the length attribute of the re
sult
and the actual length of character-expression. If the length of character-expres
sion
is greater than the length attribute of the result, the result is truncated. Unl
ess all
the truncated characters are blanks appropriate for character-expression, a warn
ing
is returned.
If character-expression is bit data, the result is bit data. Otherwise, the CCSI
D of
the result is the same as the CCSID of character-expression.
Graphic to Varchar
graphic-expression
An expression that returns a value that is a GRAPHIC, VARGRAPHIC, or
DBCLOB data type.
integer
The length attribute for the resulting varying-length character string. The valu
e
must be between 1 and 32740.
If second argument is not specified, the length attribute of the result is
determined as follows (where n is the length attribute of the first argument):
v If the graphic-expression is the empty graphic string constant, the length
attribute of the result is 1.
v If the result is SBCS data, the result length is n.
v If the result is mixed data, the result length is (3*(length(string-expression
)).
The actual length of the result is the minimum of the length attribute of the
result and the actual length of graphic-expression. If the length of the charact
er
expression is greater than the length attribute of the result, the result is
truncated. Unless all the truncated characters were blanks appropriate for
graphic-expression, a warning is returned .
Datetime to Varchar
datetime-expression
An expression whose value has one of the following three data types:
date The result is a varying-length character string representation of the date
in the format that is specified by the DATE precompiler option, if one is
provided, or else field DATE FORMAT on installation panel DSNTIP4
specifies the format. If the format is to be LOCAL, field LOCAL DATE
LENGTH on installation panel DSNTIP4 specifies the length of the
result. Otherwise, the length attribute and actual length of the result is
10.
VARCHAR
Chapter 3. Built-in functions 289
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LOCAL denotes the local format at the DB2 that executes the SQL
statement.
time The result is a varying-length character string representation of the time
in the format specified by the TIME precompiler option, if one is
provided, or else field TIME FORMAT on installation panel DSNTIP4
specifies the format. If the format is to be LOCAL, the field LOCAL
TIME LENGTH on installation panel DSNTIP4 specifies the length of
the result. Otherwise, the length attribute and actual length of the result
is 8.
LOCAL denotes the local format at the DB2 that executes the SQL
statement.
timestamp
The result is the varying-length character string representation of the
timestamp. The length attribute and actual length of the result is 26.
The CCSID of the result is the SBCS CCSID of the appropriate encoding
scheme.
Integer to Varchar
integer-expression
An expression that returns a value with a small or large integer data type.
The result is a varying-length character string representation (VARCHAR) of the
argument in the form of an SQL integer constant.
The length attribute of the result depends on whether the argument is a small or
large integer as follows:
v If the argument is a small integer, the length attribute of the result is 6 by
tes.
v If the argument is a large integer, the length attribute of the result is 11 b
ytes.
The actual length of the result is the smallest number of characters that can be
used to represent the value of the argument. Leading zeroes are not included. If
the
argument is negative, the first character of the result is a minus sign. Otherwi
se, the
first character is a digit.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Decimal to Varchar
decimal-expression
An expression that returns a value that is a decimal data type. To change the
precision and scale of the expression’s value, apply the DECIMAL function to
the expression before applying the VARCHAR function.
decimal-character
Specifies a single-byte character constant (CHAR or VARCHAR) that represents
the decimal point in the resulting character string. The character cannot be a
digit, a plus sign (+), a minus sign (−), or a blank. The default is the period (.
) or
comma (,). For information on what factors govern the choice, see “Options
affecting SQL” on page 145.
VARCHAR
290 SQL Reference
The result is a varying length character string representation (VARCHAR) of the
argument in the form of an SQL decimal constant. The result includes a character
that represents the decimal point and p digits where p is the precision of
decimal expression.
The length attribute of the result is 2+p where p is the precision of
decimal expression. The actual length of the result is the smallest number of
characters that can be used to represent the result, except that trailing zeros
are
included. Leading zeros are not included. If the argument is negative, the resul
t
begins with a minus sign. Otherwise, the result begins with a digit.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Floating Point to Varchar
floating point expression
An expression that returns a value that is a floating point data type.
The result is a varying length character string representation (VARCHAR) of the
argument in the form of an SQL floating point constant.
The length attribute of the result is 24. The actual length of the result is the
smallest
number of characters that can represent the value of the argument such that the
mantissa consists of a single digit other than zero followed by a period and a
sequence of digits. If the argument is negative, the first character of the resu
lt is a
minus sign; otherwise, the first character is a digit. If the argument is zero,
the
result is 0E0.
The CCSID of the result is the SBCS CCSID of the appropriate encoding scheme.
Row ID to Varchar
row ID expression
An expression whose value must be of a row ID data type.
The result is a varying length character string representation (VARCHAR) of the
argument. It is bit data and does not have an associated CCSID.
The length attribute of the result is 40. The actual length of the result is the
length
of row ID expression.
Example: Assume that host variable JOB_DESC is defined as VARCHAR(8). Using
sample table DSN8710.EMP, set JOB_DESC to the varying length string equivalent
of the job description (column JOB defined as CHAR(8)) for the employee with the
last name of 'QUINTANA'.
SELECT VARCHAR(JOB)
INTO :JOB_DESC
FROM DSN8710.EMP
WHERE LASTNAME = 'QUINTANA';
VARCHAR
Chapter 3. Built in functions 291
VARCHAR_FORMAT
The schema is SYSIBM.
The VARCHAR_FORMAT function returns a character representation of a
timestamp in the format indicated by format string.
timestamp expression
An expression that returns a timestamp.
format string
An expression that returns a character string constant with a maximum length
that is not greater than 255 bytes. format string contains a template of how
timestamp expression is to be formatted. Leading and trailing blanks are
removed from the string, and the resulting substring must conform to the rules
for formatting a timestamp. The only valid format that can be specified for the
function is:
’YYYY-MM-DD HH24:MI:SS’
where:
YYYY 4-digit year
MM Month (01-12, January = 01)
DD Day of month (01-31)
HH24 Hour of day (00–24, when the value is 24, the minutes and seconds
must be 0).
MI Minutes (00–59)
SS Seconds (00–59)
The result is the varying-length character string that contains the argument in
the
format specified by format-string. format-string also determines the length attr
ibute
and actual length of the result.
If the argument can be null, the result can be null; if the argument is null, th
e result
is the null value.
Example: Set the character variable TVAR to the timestamp value of CREATEDTS
from SYSIBM.SYSDATABASE, using the character string format supported by the
function to specify the format of the value for TVAR.
SELECT VARCHAR_FORMAT(CREATEDTS, YYYY-MM-DD HH24:MI:SS )
INTO :TVAR
FROM SYSIBM.SYSDATABASE;

(1)
VARCHAR_FORMAT(timestamp-expression,format-string) 
Notes:
1 TO_CHAR can be specified as a synonym for VARCHAR_FORMAT.
VARCHAR_FORMAT
292 SQL Reference
VARGRAPHIC
The schema is SYSIBM.
The VARGRAPHIC function returns a varying-length graphic string representation o
f
a character string value, with the single-byte characters converted to double-by
te
characters, or a graphic string value.
The result of the function is a varying-length graphic string (VARGRAPHIC). If t
he
length attribute of the result is greater than 127 double-byte characters, the r
esult is
a long string and subject to the restrictions that apply to long strings.
If the first argument can be null, the result can be null; if the first argument
is null,
the result is the null value.
The length attribute and actual length of the result are measured in double-byte
characters because the result is a graphic string.
Character to Vargraphic
character-expression
An expression whose value must be an EBCDIC-encoded or Unicode-encoded
character string. The GRAPHIC function is not allowed for ASCII data. The
argument does not need to be mixed data, but any occurrences of X 0E and
X 0F in the string must conform to the rules for EBCDIC mixed data. (See
“Character strings” on page 49 for these rules.)
integer
The length attribute of the resulting varying-length graphic string. The value o
f
integer must be between 1 and 16352.
If the second argument is not specified and if the character-expression is an
empty string constant or has a value X 0E0F , the length attribute of the result
is
1 and the result is an empty string. Otherwise, the length attribute of the resu
lt
is the same as the length attribute of the first argument.
The actual length of the result is the minimum of the length attribute of the re
sult
and the actual length of character-expression. If the length of character-expres
sion,
as measured in single-byte characters, is greater than the specified length of t
he
result, as measured in double-byte characters, the result is truncated. Unless a
ll the
truncated characters are blanks appropriate for character-expression, a warning
is
returned.
Character to Vargraphic:
 VARGRAPHIC(character-expression )
, integer

Graphic to Vargraphic:
 VARGRAPHIC(graphic-expression )
, integer

VARGRAPHIC
Chapter 3. Built-in functions 293
|
|
|
|
|
|
|
|
|
|
|
For EBCDIC input data:
Each character of character-expression determines a character of the result. The
argument might need to be converted to the native form of mixed data before the
result is derived. Let M denote the system EBCDIC CCSID for mixed data. The
argument is not converted if any of the following conditions is true:
v The argument is mixed data and its CCSID is M.
v The argument is SBCS data and its CCSID is the same as the system CCSID for
SBCS data. In this case, the operation proceeds as if the CCSID of the argument
is M.
v The argument is BIT data. In this case, the operation proceeds as if the CCSID
of the argument is M.
Otherwise, the argument is a new string S derived by converting the characters t
o
the coded character set identified by M. If there is no system CCSID for mixed d
ata,
conversion is to the coded character set that the system CCSID for SBCS data
identifies.
The result is derived from S using the following steps:
v Each shift character (X 0E or X 0F ) is removed.
v Each double-byte character remains as is.
v Each single-byte character is replaced by a double-byte character.
The replacement for a single-byte character is the equivalent DBCS character if
an
equivalent exists. Otherwise, the replacement is X FEFE . The existence of an
equivalent character depends on M. If there is no system CCSID for mixed data,
the DBCS equivalent of X xx for EBCDIC is X 42xx , except for X 40 , whose DBCS
equivalent is X 4040 .
For Unicode input data:
Each character of character-expression determines a character of the result. The
argument might need to be converted to the native form of mixed data before the
result is derived. Let M denote the system CCSID for mixed data. The argument is
not converted if any of the following conditions is true:
v The argument is mixed data, and its CCSID is M.
v The argument is SBCS data, and its CCSID is the same as the system CCSID
for SBCS data. In this case, the operation proceeds as if the CCSID of the
argument is M.
v The argument cannot be BIT data.
Otherwise, the argument is a new string S derived by converting the characters t
o
the coded character set identified by M.
The result is derived from S using the following steps:
v Each non-surrogate character is replaced by a Unicode double-byte character (a
UTF-16 code point).
v Each surrogate character is replaced by a pair of Unicode double-byte characte
rs
(a pair of UTF-16 code points).
The replacement for a single-byte character is the Unicode equivalent character
if
an equivalent exists. Otherwise, the replacement is X FFFD .
Graphic to Vargraphic
VARGRAPHIC
294 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
graphic-expression
An expression that returns a value that is an EBCDIC-encoded or
Unicode-encoded graphic string.
integer
The length attribute for the resulting varying-length graphic string. The value
must be an integer between 1 and 16352.
If the second argument is not specified and if the graphic-expression is an
empty string constant, the length attribute of the result is 1 and the result is
an
empty string. Otherwise, the length attribute of the result is the same as the
length attribute of the first argument.
If the first argument is an empty string, the result is an empty string.
The actual length of the result depends on the number of characters in
graphic-expression. If the length of graphic-expression is greater than the leng
th
specified, the result is truncated. Unless all of the truncated characters are
double-byte blanks, a warning is returned.
The CCSID of the result is the same as the CCSID of graphic-expression.
Example: Assume that GRPHCOL is a VARGRAPHIC column in table TABLEX and
MIXEDSTRING is a character-string host variable that contains mixed data. For
various rows in TABLEX, an application uses a positioned UPDATE statement to
replace the value of GRPHCOL with the value of MIXEDSTRING. Before
GRPHCOL can be updated, the current value of MIXEDSTRING must be converted
to a varying-length graphic string. The following statement shows how to code th
e
VARGRAPHIC function within the UPDATE statement to ensure this conversion.
EXEC SQL UPDATE TABLEX
SET GRPHCOL = VARGRAPHIC(:MIXEDSTRING)
WHERE CURRENT OF CRSNAME;
VARGRAPHIC
Chapter 3. Built-in functions 295
|
|
|
|
|
WEEK
The schema is SYSIBM.
The WEEK function returns an integer in the range of 1 to 54 that represents the
week of the year. The week starts with Sunday.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a CLOB and must have an
actual length that is not greater than 255 bytes. For the valid formats of strin
g
representations of dates and timestamps, see “String representations of datetime
values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example: Using sample table DSN8710.PROJ, set the integer host variable WEEK
to the week of the year that project AD2100 ended.
SELECT WEEK(PRENDATE)
INTO :WEEK
FROM DSN8710.PROJ
WHERE PROJNO = AD2100 ;
The result is that WEEK is set 6.
 WEEK(expression) 
WEEK
296 SQL Reference
|
|
|
|
|
WEEK_ISO
The schema is SYSIBM.
The WEEK function returns an integer in the range of 1 to 53 that represents the
week of the year. The week starts with Monday and includes 7 days. Week 1 is the
first week of the year to contain a Thursday, which is equivalent to the first w
eek
containing January 4. Thus, it is possible to have up to 3 days at the beginning
of
the year appear as the last week of the previous year, or to have up to 3 days a
t
the end of a year appear as the first week of the next year.
The argument must be a date, a timestamp, or a valid string representation of a
date or timestamp. A string representation must not be a BLOB, CLOB, or DBCLOB
and must have an actual length that is not greater than 255 bytes. For the valid
formats of string representations of dates and timestamps, see “String
representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
Example 1: Using sample table DSN8710.PROJ, set the integer host variable
WEEK to the week of the year that project AD2100 ended.
SELECT WEEK_ISO(PRENDATE)
INTO :WEEK
FROM DSN8710.PROJ
WHERE PROJNO = AD2100 ;
Example 2:The following list shows what is returned by the WEEK_ISO function for
various dates.
DATE WEEK_ISO
1997-12-28 52
1997-12-31 1
1998-01-01 1
1999-01-01 53
1999-01-04 1
1999-12-31 52
2000-01-01 52
2000-01-03 1
 WEEK_ISO(expression) 
WEEK_ISO
Chapter 3. Built-in functions 297
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
||||||||||
|
YEAR
The schema is SYSIBM.
The YEAR function returns the year part of its argument.
The argument must be a date, a timestamp, date duration, timestamp duration, or
a
valid string representation of a date or timestamp. A string representation must
not
be a BLOB, CLOB, or DBCLOB and must have an actual length that is not greater
than 255 bytes. For the valid formats of string representations of dates and
timestamps, see “String representations of datetime values” on page 57.
The result of the function is a large integer. If the argument can be null, the
result
can be null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument specified:
If the argument is a date, a timestamp, or a string representation of either,
the result is the year part of the value, which is an integer between 1 and 9999
.
If the argument is a date duration or a timestamp duration, the result is the
year part of the value, which is an integer between -9999 and 9999. A nonzero
result has the same sign as the argument.
Example: From the table DSN8710.EMP, select all rows for employees who were
born in 1941.
SELECT *
FROM DSN8710.EMP
WHERE YEAR(BIRTHDATE) = 1941;
 YEAR(expression) 
YEAR
298 SQL Reference
|
|
|
|
|
|
|
Chapter 4. Queries
Authorization . . . . . . . . . . . . . . . . . . . . . . . . . 300
subselect . . . . . . . . . . . . . . . . . . . . . . . . . . 301
select-clause . . . . . . . . . . . . . . . . . . . . . . . . 301
from-clause. . . . . . . . . . . . . . . . . . . . . . . . . 304
table-spec . . . . . . . . . . . . . . . . . . . . . . . . 305
joined-table. . . . . . . . . . . . . . . . . . . . . . . . 308
join-condition . . . . . . . . . . . . . . . . . . . . . . . 309
Join operations . . . . . . . . . . . . . . . . . . . . . . 310
where-clause . . . . . . . . . . . . . . . . . . . . . . . . 310
group-by-clause . . . . . . . . . . . . . . . . . . . . . . . 311
having-clause . . . . . . . . . . . . . . . . . . . . . . . . 311
Examples of subselects . . . . . . . . . . . . . . . . . . . . 312
fullselect. . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Character conversion in unions and concatenations . . . . . . . . . . 318
Selecting the result CCSID . . . . . . . . . . . . . . . . . . . 318
Examples of fullselects . . . . . . . . . . . . . . . . . . . . 319
select-statement . . . . . . . . . . . . . . . . . . . . . . . . 321
order-by-clause . . . . . . . . . . . . . . . . . . . . . . . 322
read-only-clause . . . . . . . . . . . . . . . . . . . . . . . 323
update-clause. . . . . . . . . . . . . . . . . . . . . . . . 324
optimize-for-clause . . . . . . . . . . . . . . . . . . . . . . 324
with-clause . . . . . . . . . . . . . . . . . . . . . . . . . 325
queryno-clause . . . . . . . . . . . . . . . . . . . . . . . 326
fetch-first-clause . . . . . . . . . . . . . . . . . . . . . . . 326
Examples of select statements . . . . . . . . . . . . . . . . . 327
© Copyright IBM Corp. 1982, 2001 299
|
A query specifies a result table. A query is a component of certain SQL statemen
ts.
There are three forms of a query:
A subselect
A fullselect
A select-statement
A subselect is a subset of a fullselect, and a fullselect is a subset of a
select-statement.
Another SQL statement called SELECT INTO is described in “SELECT INTO” on
page 845. SELECT INTO is not a subselect, fullselect, or a select-statement.
Authorization
The privilege set that is defined below must include one of the following:
v Ownership of the table or view
v The SELECT privilege on the table or view
v DBADM authority for the database (tables only)
v SYSADM authority
v SYSCTRL authority (catalog tables only)
For each user-defined function that is referenced in a query, the EXECUTE privil
ege
on the user-defined function is also required.
If the select-statement is part of a DECLARE CURSOR statement, the privilege set
is the privileges that are held by the authorization ID of the owner of the plan
or
package.
For dynamically prepared statements, the privilege set depends on the dynamic
SQL statement behavior, which is specified by bind option DYNAMICRULES:
Run behavior
The privilege set is the union of the privilege sets that are held by each
authorization ID of the process.
Bind behavior
The privilege set is the privileges that are held by the authorization ID of the
owner of the plan or package.
Define behavior
The privilege set is the privileges that are held by the authorization ID of the
owner of the stored procedure or user-defined function.
Invoke behavior
The privilege set is the privileges that are held by the authorization ID of the
invoker of the stored procedure or user-defined function.
For a list of the DYNAMICRULES values that specify run, bind, define, or invoke
behavior, see Table 2 on page 44.
When any form of a query is used as a component of another statement, the
authorization rules that apply to the query are specified in the description of
that
statement. For example, see “CREATE VIEW” on page 658 for the authorization
rules that apply to the subselect component of CREATE VIEW.
If your installation uses the access control authorization exit (DSNX@XAC), that
exit
may be controlling the authorization rules instead of the rules that are listed
here.
Queries
300 SQL Reference
subselect
The subselect is a component of the fullselect.
A subselect specifies a result table derived from the result of its first FROM c
lause.
The derivation can be described as a sequence of operations in which the result
of
each operation is input for the next. (This is only a way of describing the subs
elect.
The method used to perform the derivation may be quite different from this
description.)
The clauses of the subselect are processed in the following sequence:
1. FROM clause
2. WHERE clause
3. GROUP BY clause
4. HAVING clause
5. SELECT clause
select-clause
The SELECT clause specifies the columns of the final result table. The column
values are produced by the application of the select list to R. The select list
is a list
of names and expressions specified in the SELECT clause, and R is the result of
the previous operation of the subselect. For example, if SELECT, FROM, and
WHERE are the only clauses specified, then R is the result of that WHERE clause.
ALL
Retains all rows of the final result table and does not eliminate redundant
duplicates. This is the default.
DISTINCT
Eliminates all but one of each set of duplicate rows of the final result table.
DISTINCT must not be used more than once in a subselect, with the exception
of its use with a column function whose expression is a column. The same
DISTINCT column function with the same column expression can be referred to
more than once in a subselect. This restriction includes SELECT DISTINCT and
the use of DISTINCT in a column function of the select list or HAVING clause. It
does not include occurrences of DISTINCT in subqueries of the subselect.
 select-clause from-clause
where-clause group-by-clause having-clause


ALL
SELECT
DISTINCT

*
,
expression
AS
column-name
table-name .*
view-name
correlation-name

subselect
Chapter 4. Queries 301
Two rows are duplicates of one another only if each value in the first row is
equal to the corresponding value in the second row. For determining duplicate
rows, two null values are considered equal.
Select list notation:
* Represents a list of names that identify the columns of table R. The first nam
e
in the list identifies the first column of R, the second name identifies the sec
ond
column of R, and so on.
The list of names is established when the statement containing the SELECT
clause is prepared. Therefore, * does not identify any columns that have been
added to a table after the statement has been prepared.
expression
Can be any expression of the type that is described in “Expressions” on
page 110. Each column-name in the expression must unambiguously identify a
column of R.
AS column-name
Names or renames the result column. The name must not be qualified and
does not have to be unique.
name.*
Represents a list of names that identify the columns of name. name can be a
table name, view name, or correlation name, and must designate a table or
view named in the FROM clause. If a table is specified, it must not be an
auxiliary table. The first name in the list identifies the first column of the t
able or
view, the second name in the list identifies the second column of the table or
view, and so on.
The list of names is established when the statement containing the SELECT
clause is prepared. Therefore, * does not identify any columns that have been
added to a table after the statement has been prepared.
SQL statements can be implicitly or explicitly rebound (prepared again). The eff
ect
of a rebind on statements that include * or name.* is that the list of names is
re-established. Therefore, the number of columns returned by the statement may
change.
The number of columns in the result of SELECT is the same as the number of
expressions in the operational form of the select list (that is, the list establ
ished at
the time the statement is prepared), and cannot exceed 750. The result of a
subquery must be a single column unless the subquery is used in an EXISTS
predicate.
Limitation on long string columns: The result of an expression must not be a
character string with a maximum length greater than 255 or a graphic string with
a
maximum length greater than 127 if:
v SELECT DISTINCT is used.
v The subselect is a subquery.
v The subselect is an operand of UNION.
Applying the select list: Some of the results of applying the select list to R
depend on whether GROUP BY or HAVING is used. The next two separate lists
describe the results.
If neither GROUP BY nor HAVING is used:
subselect
302 SQL Reference
v The select list must not include column functions, or it must be entirely a li
st of
column functions.
v If the select list does not include column functions, it is applied to each ro
w of R
and the result contains as many rows as there are rows in R.
v If the select list is a list of column functions, R is the source of the argum
ents of
the functions and the result of applying the select list is one row, even when R
has no rows.
If GROUP BY or HAVING is used:
v Each column-name in the select list must either identify a grouping column or
be
specified within a column function.
v The select list is applied to each group of R, and the result contains as many
rows as there are groups in R. When the select list is applied to a group of R,
that group is the source of the arguments of the column functions in the select
list.
v You cannot use GROUP BY with a name defined using the AS clause unless the
name is defined in a nested table expression. “Example 6” on page 313
demonstrates the valid use of AS and GROUP BY in a SELECT statement.
In either case, the nth column of the result contains the values specified by ap
plying
the nth expression in the operational form of the select list.
Null attributes of result columns: Result columns allow null values if they are
derived from one of the following:
v Any column function except COUNT or COUNT_BIG
v A column that allows null values
v A view column in an outer select list that is derived from an arithmetic expre
ssion
v An arithmetic expression in an outer select list
v An arithmetic expression that allows nulls
v A scalar function or string expression that allows null values
v A host variable that has an indicator variable
v A result of a UNION if at least one of the corresponding items in the select l
ist is
nullable
Names of result columns: The name of a result column of a subselect is
determined as follows:
v If the AS clause is specified, the name of the result column is the name speci
fied
on the AS clause. The name need not be unique.
v If the AS clause is not specified and the result column is derived from a colu
mn
name, the result column name is the unqualified name of that column.
v All other result columns are unnamed.
Names of result columns are placed into the SQL descriptor area (SQLDA) when
the DESCRIBE statement is executed. This allows an interactive SQL processor
such as SPUFI or QMF to use the column names when displaying the results. The
names in the SQLDA include those specified by the AS clause.
subselect
Chapter 4. Queries 303
Data types of result columns: Each column of the result of SELECT acquires a
data type from the expression from which it is derived.
Table 30. Data types of result columns
When the expression is... The data type of the result column is...
The name of any numeric
column
The same as the data type of the column, with the same precision and scale for
decimal columns.
An integer constant INTEGER.
A decimal or floating-point
constant
The same as the data type of the constant, with the same precision and scale for
decimal constants. For floating-point constants, the data type is DOUBLE
PRECISION.
The name of any numeric host
variable
The same as the data type of the variable, with the same precision and scale for
decimal variables. The result is decimal if the data type of the host variable i
s not an
SQL data type; for example, DISPLAY SIGN LEADING SEPARATE in COBOL.
An arithmetic or string
expression
The same as the data type of the result, with the same precision and scale for
decimal results as described in “Expressions” on page 110.
Any function The data type of the result of the function. For a built-in functio
n, see “Chapter 3.
Built-in functions” on page 153 to determine the data type of the result. For a
user-defined function, the data type of the result is what was defined in the CR
EATE
FUNCTION statement for the function.
The name of any string column The same as the data type of the column, with the
same length attribute.
The name of any string host
variable
The same as the data type of the variable, with a length attribute equal to the
length
of the variable. The result is a varying-length character string if the data typ
e of the
host variable is not an SQL data type; for example, a NUL-terminated string in C
.
A character string constant of
length n
VARCHAR(n).
A graphic string constant of
length n
VARGRAPHIC(n).
The name of a datetime column The same as the data type of the column.
The name of a ROWID column Row ID.
The name of a distinct type
column
The same as the distinct type of the column, with the same length, precision, an
d
scale attributes, if any.
from-clause
The FROM clause specifies an intermediate result table, R. If a single table-spe
c is
specified, R is the result of that table-spec. If more than one table-spec is sp
ecified,
R consists of all possible combinations of the rows of the result of each table-
spec.
Each row of R is a row from the result of the first table-spec concatenated with
a
row from the result of the second table-spec, concatenated with a row from the
result of the third table-spec, and so on. The number of rows in R is the produc
t of
the number of rows in the result of each table-spec. Thus, if the result of any
table-spec is empty, R is empty.
 
,
FROM table-spec 
subselect
304 SQL Reference
table-spec
A table-spec specifies an intermediate result table:
v If a single table or view is identified, the intermediate result table is simp
ly that
table or view.
v If a table locator is identified, the host variable represents the intermediat
e table.
The intermediate table has the same structure as the table identified in
table-name.
v A fullselect in parentheses is called a nested table expression. If a nested t
able
expression is specified, the result table is the result of that nested table
expression. The columns of the result do not need unique names, but a column
with a non-unique name cannot be referenced. At any time, the table consists of
the rows that would result if the fullselect were executed.
v If a function-name is specified, the intermediate result table is the set of r
ows
returned by the table function.
v If a joined-table is specified, the intermediate result table is the result of
one or
more join operations as explained below.
Each table-name or view-name specified in every FROM clause of the same SQL
statement must identify a table or view that exists at the same DB2 subsystem. T
he
table-spec:
 table-name
view-name correlation-clause
table-locator-reference
( fullselect ) correlation-clause
TABLE
table-function-reference
joined-table

table-locator-reference:
 TABLE ( table-locator-variable LIKE table-name ) 
table-function-reference:


TABLE (function-name( ))
,
expression
TABLE transition_table_name
correlation-clause 
correlation-clause

AS

correlation-name
,
( column-name )

subselect
Chapter 4. Queries 305
|
|
|
|
|
tables that are identified must not be auxiliary tables. The tables, table funct
ions, or
underlying tables of the views that are identified must have the same encoding
scheme—either all ASCII, all EBCDIC, or all Unicode. If a FROM clause is specified
in a subquery of a basic predicate, a view that includes GROUP BY or HAVING
must not be identified.
Each table-locator-variable must specify a host variable with a table locator ty
pe.
The only way to assign a value to a table locator is to pass the old or new tran
sition
table of a trigger to a user-defined function or stored procedure. A table locat
or host
variable must not have a null indicator and must not be a parameter marker. In
addition, a table locator can be used only in a manipulative SQL statement.
Each function-name, together with the types of its arguments, must resolve to a
table function that exists at the same DB2 subsystem. An algorithm called functi
on
resolution, which is described on page 106, uses the function name and the
arguments to determine the exact function to use. Unless given column names in
the correlation-clause, the column names for a table function are those specifie
d on
the RETURNS clause of the CREATE FUNCTION statement. This is analogous to
the column names of a table, which are defined in the CREATE TABLE.
Each correlation-name in a correlation-clause defines a designator for the
immediately preceding intermediate result table (table-name, view-name, nested
table expression, or function-name reference), which can be used to qualify
references to the columns of the table. Using column-names to list and rename th
e
columns is optional. A correlation name must be specified for nested table
expressions and references to table functions.
If a list of column-names is specified in a correlation-clause, the number of na
mes
must be the same as the number of columns in the corresponding table, view,
nested table expression, or table function. Each name must be unique and
unqualified. If columns are added to an underlying table of a table-spec, the nu
mber
of columns in the result of the table-spec no longer matches the number of names
in its correlation-clause. Therefore, when a rebind of a package containing the
query in question is attempted, DB2 returns an error and the rebind fails. At th
at
point, change the correlation-clause of the embedded SQL statement in the
application program so that the number of names matches the number of columns.
Then, precompile, compile, bind, and link-edit the modified program.
An exposed name is a correlation-name or a table-name or view name that is not
followed by a correlation-name. The exposed names in a FROM clause should be
unique, and only exposed names should be used as qualifiers of column names.
Thus, if the same table name is specified twice, at least one specification of t
he
table name should be followed by a unique correlation name. That correlation nam
e
should be used to qualify references to columns of that instance of the table. I
n
addition, if column names are listed for the correlation name in the FROM clause
,
those columns names should be used to reference the columns. For more
information, see “Column name qualifiers in correlated references” on page 97.
Correlated references in table-specs: In general, nested table expressions and
table functions can be specified in any FROM clause. Columns from the nested
table expressions and table functions can be referenced in the select list and i
n the
rest of the fullselect using the correlation name. The scope of this correlation
name
is the same as correlation names for other table or view names in the FROM
clause. The basic rule that applies for both these cases is that the correlated
reference must be from a table-spec at a higher level in the hierarchy of
subqueries.
subselect
306 SQL Reference
|
|
|
|
|
|
|
|
Nested table expressions can be used in place of a view to avoid creating a view
when general use of the view is not required. They can also be used when the
desired result table is based on host variables.
For table functions, an additional capability exists. A table function can conta
in one
or more correlated references to other tables in the same FROM clause if the
referenced tables precede the reference in the left-to-right order of the tables
in the
FROM clause. The same capability exists for nested table expressions if the
optional keyword TABLE is specified; otherwise, only references to higher levels
in
the hierarchy of subqueries is allowed.
A nested table expression or table function that contains correlated references
to
other tables in the same FROM clause:
v Cannot participate in a FULL OUTER JOIN or a RIGHT OUTER JOIN
v Can participate in LEFT OUTER JOIN or an INNER JOIN if the referenced tables
precede the reference in the left-to-right order of the tables in the FROM claus
e
Table 31 shows some examples of valid and invalid correlated references. TABF1
and TABF2 represent table functions.
Table 31. Examples of correlated references
Subselect Valid Reason
SELECT T.C1, Z.C5
FROM TABLE( TABF1(T.C2) ) AS Z, T
WHERE T.C3 = Z.C4;
No T.C2 cannot be resolved because
T does not precede TABF1 in
FROM
SELECT T.C1, Z.C5
FROM T, TABLE( TABF1(T.C2) ) AS Z
WHERE T.C3 = Z.C4;
Yes T precedes TABF1 in FROM,
making T.C2 known
SELECT A.C1, B.C5
FROM TABLE( TABF2(B.C2) ) AS A,
TABLE( TABF1(A.C6) ) AS B
WHERE A.C3 = B.C4;
No B in B.C2 cannot be resolved
because the table function that
would resolve it, TABF1, follows
its reference in TABF2 in FROM
SELECT D.DEPTNO, D.DEPTNAME,
EMPINFO.AVGSAL, EMPINFO.EMPCOUNT
FROM DEPT D,
(SELECT AVG(E.SALARY) AS AVGSAL,
COUNT(*) AS EMPCOUNT
FROM EMP E
WHERE E.WORKDEPT = D.DEPTNO)
AS EMPINFO;
No DEPT precedes nested table
expression, but keyword TABLE
is not specified, making D.DEPTNO
unknown
SELECT D.DEPTNO, D.DEPTNAME,
EMPINFO.AVGSAL, EMPINFO.EMPCOUNT
FROM DEPT D,
TABLE (SELECT AVG(E.SALARY) AS AVGSAL,
COUNT(*) AS EMPCOUNT
FROM EMP E
WHERE E.WORKDEPT = D.DEPTNO)
AS EMPINFO;
Yes DEPT precedes nested table
expression and keyword TABLE
is specified, making D.DEPTNO
known
subselect
Chapter 4. Queries 307
||||||||
||||||||
joined-table
A joined-table specifies an intermediate result table that is the result of eith
er an
inner equi-join or an outer join. The table is derived by applying one of the
join-operators: INNER, RIGHT OUTER, LEFT OUTER, or FULL OUTER to its
operands. If a join-operator is not specified, INNER is implicit. The order in w
hich a
LEFT OUTER JOIN or RIGHT OUTER JOIN is performed can affect the result.
As described in more detail under “Join operations” on page 310 an inner join
combines each row of the left table with every row of the right table keeping on
ly
the rows where the join-condition is true. Thus, the result table may be missing
rows from either or both of the joined tables. Outer joins include the rows prod
uced
by the inner join as well as the missing rows, depending on the type of outer jo
in as
follows:
Left outer. Includes the rows from the left table that were missing from the inn
er
join.
Right Outer. Includes the rows from the right table that were missing from the
inner join.
Full Outer. Includes the rows from both tables that were missing from the inner
join.
A joined-table can be used in any context in which any form of the SELECT
statement is used. Both a view and a cursor is read-only if its SELECT statement
includes a joined-table.

INNER
table-spec JOIN table-spec ON join-condition
OUTER
LEFT
RIGHT
( joined-table )

subselect
308 SQL Reference
join-condition
For INNER, LEFT OUTER, and RIGHT OUTER joins, the join-condition is a
search-condition that must conform to these rules:
v It cannot contain any subqueries.
v Any column that is referenced in an expression of the join-condition must be a
column of one of the operand tables of the associated join operator (in the scop
e
of the same joined-table clause).
For a FULL OUTER (or FULL) join, the join-condition is a search condition in whi
ch
the predicates can only be combined with AND. In addition, each predicate must
have the form expression = expression , where one expression references only
columns of one of the operand tables of the associated join operator, and the ot
her
expression references only columns of the other operand table. The values of the
expressions must be comparable.
Each full-join-expression in a FULL OUTER join must include a column name or a
cast function that references a column. The COALESCE and VALUE functions are
allowed.
For any type of join, column references in an expression of the join-condition a
re
resolved using the rules for resolution of column name qualifiers specified in
“Resolution of column name qualifiers and column names” on page 98 before any
rules about which tables the columns must belong to are applied.
For INNER, LEFT OUTER, and RIGHT OUTER joins:
 search-condition 
For FULL OUTER joins:
 
AND
full-join-expression = full-join-expression 
full-join-expression:


column-name
(1)
cast-function
COALESCE ( column-name , column-name )
VALUE (1) (1)
cast-function , cast-function

Notes:
1 cast-function must only contain a column and the casting data type must be a d
istinct type or the
data type upon which the distinct type was based.
subselect
Chapter 4. Queries 309
Join operations
A join-condition specifies pairings of T1 and T2, where T1 and T2 are the left a
nd
right operand tables of its associated JOIN operator. For all possible combinati
ons
of rows T1 and T2, a row of T1 is paired with a row of T2 if the join-condition
is
true. When a row of T1 is joined with a row of T2, a row in the result consists
of the
values of that row of T1 concatenated with the values of that row of T2. The
execution might involve the generation of a “null row”. The null row of a table
consists of a null value for each column of the table, regardless of whether the
columns allow null values.
The following summarizes the results of the join operations:
v The result of T1 INNER JOIN T2 consists of their paired rows.
v The result of T1 LEFT OUTER JOIN T2 consists of their paired rows and, for
each unpaired row of T1, the concatenation of that row with the null row of T2.
All
columns derived from T2 allow null values.
v The result of T1 RIGHT OUTER JOIN T2 consists of their paired rows and, for
each unpaired row of T2, the concatenation of that row with the null row of T1.
All
columns derived from T1 allow null values.
v The result of T1 FULL OUTER JOIN T2 consists of their paired rows and, for
each unpaired row of T1, the concatenation of that row with the null row of T2,
and for each unpaired row of T2, the concatenation of that row with the null row
in T1. All columns of the result table allow null values.
A join operation is part of a FROM clause; therefore, for the purpose of predict
ing
which rows will be returned from a SELECT statement containing a join operation,
assume that the join operation is performed before the other clauses in the
statement.
where-clause
The WHERE clause specifies an intermediate result table that consists of those
rows of R for which the search condition is true. R is the result of the FROM cl
ause
of the subselect.
The search condition must conform to the following rules:
v Each column name must unambiguously identify a column of R or be a
correlated reference. A column name is a correlated reference if it identifies a
column of a table or view that is identified in an outer subselect.
v A column function must not be specified unless the WHERE clause is specified i
n
a subquery of a HAVING clause and the argument of the function is a correlated
reference to a group.
Any subquery in the search-condition is effectively executed for each row of R a
nd
the results are used in the application of the search-condition to the given row
of R.
A subquery is actually executed for each row of R only if it includes a correlat
ed
reference. In fact, a subquery with no correlated references is executed just on
ce,
whereas a subquery with a correlated reference may have to be executed once for
each row.
 WHERE search-condition 
subselect
310 SQL Reference
|
|
|
group-by-clause
The GROUP BY clause specifies an intermediate result table that consists of a
grouping of the rows of R. R is the result of the previous clause.
Each column-name must unambiguously identify a column of R other than a long
string column. Each identified column is called a grouping column.
The result of GROUP BY is a set of groups of rows. In each group of more than
one row, all values of each grouping column are equal; and all rows with the sam
e
set of values of the grouping columns are in the same group. For grouping, all n
ull
values within a grouping column are considered equal.
Because every row of a group contains the same value of any grouping column, the
name of a grouping column can be used in a search condition in a HAVING clause
or an expression in a SELECT clause. In each case, the reference specifies only
one value for each group. However, if the grouping column contains varying-lengt
h
strings with trailing blanks, the values in the group can differ in the number o
f
trailing blanks and may not all have the same length. In that case, a reference
to
the grouping column still specifies only one value for each group, but the value
for a
group is chosen arbitrarily from the available set of values. Thus, the actual l
ength
of the result value is unpredictable.
The GROUP BY clause must not be used in a subquery of a basic predicate or
must not be used if R is derived from a view whose outer subselect includes
GROUP BY or HAVING clauses.
having-clause
The HAVING clause specifies an intermediate result table that consists of those
groups of R for which the search-condition is true. R is the result of the previ
ous
clause. If this clause is not GROUP BY, R is considered a single group with no
grouping columns.
Each column-name in search-condition must:
v Unambiguously identify a grouping column of R, or
v Be specified within a column function24, or
v Be a correlated reference. A column-name is a correlated reference if it ident
ifies
a column of a table or view identified in an outer subselect.
24. See “Chapter 3. Built-in functions” on page 153 for restrictions that apply to t
he use of column functions.
 
,
GROUP BY column-name 
 HAVING search-condition 
subselect
Chapter 4. Queries 311
|
|
|
A group of R to which the search condition is applied supplies the argument for
each function in the search condition, except for any function whose argument is
a
correlated reference.
If the search condition contains a subquery, the subquery can be thought of as
being executed each time the search condition is applied to a group of R, and th
e
results used in applying the search condition. In actuality, the subquery is exe
cuted
for each group only if it contains a correlated reference. For an illustration o
f the
difference, see Example 4 and Example 5 in “Examples of subselects” below.
A correlated reference to a group of R must either identify a grouping column or
be
contained within a column function.
The HAVING clause must not be used in a subquery of a basic predicate. When
HAVING is used without GROUP BY, any column name in the select list must
appear within a column function.
Examples of subselects
Example 1: Show all rows of the table DSN8710.EMP.
SELECT * FROM DSN8710.EMP;
Example 2: Show the job code, maximum salary, and minimum salary for each
group of rows of DSN8710.EMP with the same job code, but only for groups with
more than one row and with a maximum salary greater than 50000.
SELECT JOB, MAX(SALARY), MIN(SALARY)
FROM DSN8710.EMP
GROUP BY JOB
HAVING COUNT(*) > 1AND MAX(SALARY) > 50000;
Example 3: For each employee in department E11, get the following information
from the table DSN8710.EMPPROJACT: employee number, activity number, activity
start date, and activity end date. Using the CHAR function, convert the start an
d
end dates to their USA formats. Get the needed department information from the
table DSN8710.EMP.
SELECT EMPNO, ACTNO, CHAR(EMSTDATE,USA), CHAR(EMENDATE,USA)
FROM DSN8710.EMPPROJACT
WHERE EMPNO IN (SELECT EMPNO FROM DSN8710.EMP
WHERE WORKDEPT = E11 );
Example 4: Show the department number and maximum departmental salary for all
departments whose maximum salary is less than the average salary for all
employees. (In this example, the subquery would be executed only once.)
SELECT WORKDEPT, MAX(SALARY)
FROM DSN8710.EMP
GROUP BY WORKDEPT
HAVING MAX(SALARY) < (SELECT AVG(SALARY)
FROM DSN8710.EMP);
Example 5: Show the department number and maximum departmental salary for all
departments whose maximum salary is less than the average salary for employees
in all other departments. (In contrast to Example 4, the subquery in this statem
ent,
containing a correlated reference, would need to be executed for each group.)
SELECT WORKDEPT, MAX(SALARY)
FROM DSN8710.EMP Q
GROUP BY WORKDEPT
subselect
312 SQL Reference
HAVING MAX(SALARY) < (SELECT AVG(SALARY)
FROM DSN8710.EMP
WHERE NOT WORKDEPT = Q.WORKDEPT);
Example 6: For each group of employees hired during the same year, show the
year-of-hire and current average salary. (This example demonstrates how to use t
he
AS clause in a FROM clause to name a derived column that you want to refer to in
a GROUP BY clause.)
SELECT HIREYEAR, AVG(SALARY)
FROM (SELECT YEAR(HIREDATE) AS HIREYEAR, SALARY
FROM DSN8710.EMP) AS NEWEMP
GROUP BY HIREYEAR;
Example 7: For an example of how to group the results of a query by an expressio
n
in the SELECT clause without having to retype the expression, see “Example 4” on
page 125 for CASE expressions.
Example 8: Get the employee number and employee name for all the employees in
DSN8710.EMP. Order the results by the date of hire.
SELECT EMPNO, FIRSTNME, LASTNAME
FROM DSN8710.EMP
ORDER BY HIREDATE;
Example 9: Assume that an external function named ADDYEARS exists. For a
given date, the function adds a given number of years and returns a new date. (T
he
data types of the two input parameters to the function are DATE and INTEGER.)
Get the employee number and employee name for all employees who have been
hired within the last 5 years.
SELECT EMPNO, FIRSTNME, LASTNAME
FROM DSN8710.EMP
WHERE ADDYEARS(HIREDATE, 5) > CURRENT DATE;
To distinguish the different types of joins, to show nested table expressions, a
nd to
demonstrate how to combine join columns, the remaining examples use these two
tables:
The PARTS table The PRODUCTS table
PART PROD# SUPPLIER PROD# PRODUCT PRICE
======= ===== ============ ===== =========== =====
WIRE 10 ACWF 505 SCREWDRIVER 3.70
OIL 160 WESTERN_CHEM 30 RELAY 7.55
MAGNETS 10 BATEMAN 205 SAW 18.90
PLASTIC 30 PLASTIK_CORP 10 GENERATOR 45.75
BLADES 205 ACE_STEEL
Example 10: Join the tables on the PROD# column to get a table of parts with the
ir
suppliers and the products that use the parts:
SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS, PRODUCTS
WHERE PARTS.PROD# = PRODUCTS.PROD#;
or
SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS INNER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;
Either one of these two statements give this result:
subselect
Chapter 4. Queries 313
PART SUPPLIER PROD# PRODUCT
======= ============ ===== ==========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
BLADES ACE_STEEL 205 SAW
Notice two things about the example:
v There is a part in the parts table (OIL) whose product (#160) is not listed in
the
products table. There is a product (SCREWDRIVER, #505) that has no parts
listed in the parts table. Neither OIL nor SCREWDRIVER appears in the result of
the join.
An outer join, however, includes rows where the values in the joined columns do
not match.
v There is explicit syntax to express that this familiar join is not an outer jo
in but an
inner join. You can use INNER JOIN in the FROM clause instead of the comma.
Use ON when you explicitly join tables in the FROM clause.
You can specify more complicated join conditions to obtain different sets of res
ults.
For example, eliminate the suppliers that begin with the letter A from the table
of
parts, suppliers, product numbers and products:
SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS INNER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#
AND SUPPLIER NOT LIKE A% ;
The result of the query is all rows that do not have a supplier that begins with
A:
PART SUPPLIER PROD# PRODUCT
======= ============ ===== ==========
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
Example 11: Join the tables on the PROD# column to get a table of all parts and
products, showing the supplier information, if any.
SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS FULL OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;
The result is:
PART SUPPLIER PROD# PRODUCT
======= ============ ===== ==========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
BLADES ACE_STEEL 205 SAW
OIL WESTERN_CHEM 160 (null)
(null) (null) (null) SCREWDRIVER
The clause FULL OUTER JOIN includes unmatched rows from both tables. Missing
values in a row of the result table are filled with nulls.
Example 12: Join the tables on the PROD# column to get a table of all parts,
showing what products, if any, the parts are used in:
SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS LEFT OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;
The result is:
subselect
314 SQL Reference
PART SUPPLIER PROD# PRODUCT
======= ============ ===== ==========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
BLADES ACE_STEEL 205 SAW
OIL WESTERN_CHEM 160 (null)
The clause LEFT OUTER JOIN includes rows from the table identified before it
where the values in the joined columns are not matched by values in the joined
columns of the table identified after it.
Example 13: Join the tables on the PROD# column to get a table of all products,
showing the parts used in that product, if any, and the supplier.
SELECT PART, SUPPLIER, PRODUCTS.PROD#, PRODUCT
FROM PARTS RIGHT OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;
The result is:
PART SUPPLIER PROD# PRODUCT
======= ============ ===== ===========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
BLADES ACE_STEEL 205 SAW
(null) (null) 505 SCREWDRIVER
The clause RIGHT OUTER JOIN includes rows from the table identified after it
where the values in the joined columns are not matched by values in the joined
columns of the table identified before it.
Example 14: The result of Example 11 (a full outer join) shows the product numbe
r
for SCREWDRIVER as null, even though the PRODUCTS table contains a product
number for it. This is because PRODUCTS.PROD# was not listed in the SELECT
list of the query. Revise the query using COALESCE, a synonym for the VALUE
function, so that all part numbers from both tables are shown.
SELECT PART, SUPPLIER,
COALESCE(PARTS.PROD#, PRODUCTS.PROD#) AS PRODNUM, PRODUCT
FROM PARTS FULL OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;
In the result, notice that the AS clause (AS PRODNUM), provides a name for the
result of the COALESCE function:
PART SUPPLIER PRODNUM PRODUCT
======= ============ ======= ===========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
BLADES ACE_STEEL 205 SAW
OIL WESTERN_CHEM 160 (null)
(null) (null) 505 SCREWDRIVER
Example 15: For all parts that are used in product numbers less than 200, show t
he
part, the part supplier, the product number, and the product name. Use a nested
table expression.
subselect
Chapter 4. Queries 315
SELECT PART, SUPPLIER, PRODNUM, PRODUCT
FROM (SELECT PART, PROD# AS PRODNUM, SUPPLIER
FROM PARTS
WHERE PROD# < 200) AS PARTX
LEFT OUTER JOIN PRODUCTS
ON PRODNUM = PROD#;
The result is:
PART SUPPLIER PRODNUM PRODUCT
======= ============ ======= ==========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
PLASTIC PLASTIK_CORP 30 RELAY
OIL WESTERN_CHEM 160 (null)
subselect
316 SQL Reference
fullselect
The fullselect is a component of the select-statement, the CREATE VIEW
statement, and the INSERT statement. The fullselect is also a component of certa
in
predicates that, in turn, are components of a subselect. A subselect that is a
component of a predicate is called a subquery.
A fullselect specifies a result table. If UNION is not used, the result of the f
ullselect
is the result of the specified subselect.25
UNION or UNION ALL
Derives a result table by combining two other result tables, R1 and R2. If
UNION ALL is specified, the result consists of all rows in R1 and R2. If UNION
is specified without the ALL option, the result is the set of all rows in either
R1
or R2, with duplicate rows eliminated.
If the nth column of R1 and the nth column of R2 have the same result column
name, the nth column of R has the same result column name. If the nth column
of R1 and the nth column of R2 do not have the same name, the result column
in R is unnamed.
Qualified column names cannot be used in the ORDER BY clause when
UNION or UNION ALL is also specified.
Duplicate rows: Two rows are duplicates if each value in the first is equal to t
he
corresponding value of the second. For determining duplicates, two null values a
re
considered equal.
UNION and UNION ALL are associative operations. However, when UNION and
UNION ALL are used in the same statement, the result depends on the order in
which the operations are performed. Operations within parentheses are performed
first. When the order is not specified by parentheses, operations are performed
in
order from left to right.
Rules for columns: R1 and R2 must have the same number of columns and the
data type of the nth column of R1 must be compatible with the data type of the n
th
column of R2. If UNION is specified without the ALL option, R1 and R2 must not
include a long string column.
The nth column of the result of UNION and UNION ALL is derived from the nth
columns of R1 and R2.
For information on the valid combinations of operand columns and the data type o
f
the result column, see “Rules for result data types” on page 77.
25. DB2 allows SELECT INTO as the operand of UNION. This is a deprecated feature
with undefined results.
 subselect
(fullselect)

UNION subselect
UNION ALL (fullselect)

fullselect
Chapter 4. Queries 317
|
|
|
|
Character conversion in unions and concatenations
The SQL operations that combine strings include concatenation, UNION, UNION
ALL, and the IN list of an IN predicate. Within an SQL statement, concatenation
combines two or more strings into a new string. Within a fullselect, UNION, UNIO
N
ALL, or the IN list of an IN predicate combine two or more string columns result
ing
from the subselects into results column. All such operations have the following
in
common:
v The choice of a result CCSID for the string or column
v The possible conversion of one or more of the component strings or columns to
the result CCSID
For all such operations, the rules for those two actions are the same, as descri
bed
in “Selecting the result CCSID”. These rules also apply to the COALESCE (or
VALUE) scalar function.
Selecting the result CCSID
The result CCSID is selected at bind time. The result CCSID is the CCSID of one
of
the operands.
Two operands: When two operands are used, the result CCSID is determined by
the operand types, their CCSIDs, and their relative positions in the operation.
The
rules shown here apply when neither CCSID is X FFFF . When a CCSID is X FFFF ,
the result CCSID is always X FFFF , and no character conversions take place.
If one CCSID is for SBCS data and the other is for mixed data, the operand
selected depends on the value of the MIXED DATA field on installation panel
DSNTIPF at the DB2 where the operation takes place:
v If this value is YES, the operand MIXED furnishes the result CCSID.
v If this value is NO, the operand SBCS furnishes the result CCSID.
Unicode data can be mixed regardless of the setting of the MIXED field on
installation panel DSNTIPF.
If both CCSIDs are the same type (both SBCS, both MIXED, or both GRAPHIC
CCSIDs), then the operand that furnishes the result CCSID is as shown in Table 3
2.
For example, assume a concatenation of the form:
string-constant CONCAT derived-value
The value in the second row and fourth column shows that the first operand
(string-constant) supplies the result CCSID.
Table 32. Operand that supplies the CCSID for character conversion
First operand
Second operand
Column
value
String
constant
Special
register
Derived
value
Host
variable
Column value first first first first first
String constant second first first first first
Special register second first first first first
Derived value second second second first first
Host variable second second second second neither1
Note: 1. Both operands are converted, if necessary, to the system CCSID of the s
erver.
fullselect
318 SQL Reference
|
|
|
|
|
|
|
|
Three or more operands:
If all the operands have the same CCSID, the result CCSID is the common
CCSID.
If at least one of the CCSIDs has the value X FFFF , the result CCSID also has
the value X FFFF .
Otherwise, selection proceeds as follows:
1. The rules for a pair of operands are applied to the first two operands. This
picks
a “candidate” for the second step. The candidate is the operand that would
furnish the result CCSID if just the first two operands were involved in the
operation.
2. The rules are applied to the Step 1 candidate and the third operand, thereby
selecting a second candidate.
3. If a fourth operand is involved, the rules are applied to the second candidat
e
and fourth operand, to select a third candidate, and so on.
The process continues until all operands have been used. The remaining candidate
is the one that furnishes the result CCSID. Whenever the rules for a pair are
applied to a candidate and an operand, the candidate is considered to be the fir
st
operand.
Consider, for example, the following concatenation:
A CONCAT B CONCAT C
Here, the rules are first applied to the strings A and B. Suppose that the strin
g
selected as candidate is A. Then the rules are applied to A and C. If the string
selected is again A, then A furnishes the result CCSID. Otherwise, C furnishes t
he
result CCSID.
Character conversion of components: An operand of concatenation or the
selected argument of the COALESCE (or VALUE) scalar function is converted, if
necessary, to the coded character set of the result string. Each string of an op
erand
of UNION or UNION ALL is converted, if necessary, to the coded character set of
the result column. In either case, the coded character set is the one identified
by
the result CCSID. Character conversion is necessary only if all of the following
are
true:
v The result and operand CCSIDs are different.
v Neither CCSID is X FFFF (neither string is defined as BIT data).
v The string is neither null nor empty.
v The SYSSTRINGS catalog table indicates that conversion is necessary.
An error occurs if a character of a string cannot be converted, SYSSTRINGS is
used but contains no information about the CCSID pair, or DB2 cannot do the
conversion through DB2 for OS/390 and z/OS support for Unicode or Language
Environment. A warning occurs if a character of a string is converted to the
substitution character.
Examples of fullselects
Example 1: A query specifies the union of result tables R1 and R2. A column in R
1
has the data type CHAR(10) and the subtype BIT. The corresponding column in R2
has the data type CHAR(15) and the subtype SBCS. Hence, the column in the
fullselect
Chapter 4. Queries 319
|
|
|
|
|
union has the data type CHAR(15) and the subtype BIT. Values from the first
column are converted to CHAR(15) by adding five trailing blanks.
Example 2: Show all the rows from DSN8710.EMP.
SELECT * FROM DSN8710.EMP;
Example 3: Using sample tables DSN8710.EMP and DSN8710.EMPROJACT, list
the employee numbers of all employees for which either of the following statemen
ts
are true:
v Their department numbers begin with D .
v They are assigned to projects whose project numbers begin with AD .
SELECT EMPNO FROM DSN8710.EMP
WHERE WORKDEPT LIKE D%
UNION
SELECT EMPNO FROM DSN8710.EMPPROJACT
WHERE PROJNO LIKE AD% ;
The result is the union of two result tables, one formed from the sample table
DSN8710.EMP, the other formed from the sample table DSN8710.EMPPROJACT.
The result—a one-column table—is a list of employee numbers. Because UNION,
rather than UNION ALL, was used, the entries in the list are distinct. If instea
d
UNION ALL were used, certain employee numbers would appear in the list more
than once. These would be the numbers for employees in departments that begin
with D while their projects begin with AD .
Example 4: Find the average charges for each subscriber (SNO) in the state of
California during the last Friday of each month in the first quarter of 2000. Gr
oup
the result according to SNO. Each MONTHnn table has columns for SNO,
CHARGES, and DATE. The CUST table has columns for SNO and STATE.
SELECT V.SNO, AVG(V.CHARGES)
FROM CUST, TABLE (
SELECT SNO, CHARGES, DATE
FROM MONTH1
WHERE DATE BETWEEN 01/01/2000 AND 01/31/2000
UNION ALL
SELECT SNO, CHARGES, DATE
FROM MONTH2
WHERE DATE BETWEEN 02/01/2000 AND 02/29/00
UNION ALL
SELECT SNO, CHARGES, DATE
FROM MONTH3
WHERE DATE BETWEEN 03/01/2000 AND 03/31/2000
) AS V(SNO, CHARGES, DATE)
WHERE CUST.SNO=V.SNO
AND CUST.STATE= CA
AND DATE IN ( 01/28/2000 , 02/25/2000 , 03/31/2000 )
GROUP BY V.SNO;
fullselect
320 SQL Reference
|
|
|
|
|||||
|
|||
|
||||||||
select-statement
The select-statement is the form of a query that can be directly specified in a
DECLARE CURSOR statement, or prepared and then referenced in a DECLARE
CURSOR statement. It can also be issued interactively using SPUFI causing a
result table to be displayed at your terminal. In any case, the table specified
by
select-statement is the result of the fullselect.
The tables and view identified in a select statement can be at the current serve
r or
any DB2 subsystem with which the current server can establish a connection.
For local queries on DB2 for OS/390 and z/OS or remote queries in which the
server and requester are DB2 for OS/390 and z/OS, if a table is encoded as ASCII
or Unicode, the retrieved data is encoded in EBCDIC. For information on retrievi
ng
data encoded in ASCII or Unicode, see Part 6 of DB2 Application Programming and
SQL Guide.
A select statement can implicitly or explicitly invoke user-defined functions or
implicitly invoke stored procedures. This technique is known as nesting of SQL
statements. A function or procedure is implicitly invoked in a select statement
when
it is invoked at a lower level. For instance, if you invoke a user-defined funct
ion
from a select statement and the user-defined function invokes a stored procedure
,
you are implicitly invoking the stored procedure. When you execute a select
statement on a table, no INSERT, UPDATE, or DELETE statement at a lower level
of nesting must be executed on the same table.
For example, suppose that you execute this SQL statement at level 1 of nesting:
SELECT UDF1(C1) FROM T1;
You cannot execute this SQL statement at a lower level of nesting:
INSERT INTO T1VALUES(...);
 fullselect
(1)
order-by-clause

(2)
read-only-clause
(3)
update-clause
optimize-for-clause
with-clause
queryno-clause
fetch-first-clause

Notes:
1 If the order-by-clause is specified, the update-clause cannot be specified exc
ept when the
select-statement is associated with an INSENSITIVE or SENSITIVE STATIC SCROLL CU
RSOR.
2 The same clause must not be specified more than once.
3 If the update-clause is specified, the fetch-first-clause cannot be specified.
select-statement
Chapter 4. Queries 321
|
|
|
|
|
|
|
|
|
|
|
|
order-by-clause
The ORDER BY clause specifies an ordering of the rows of the result table. If a
single sort-key is identified, the rows are ordered by the values of that sort-k
ey. If
more than one sort-key is identified, the rows are ordered by the values of the
first
sort-key, then by the values of the second sort-key, and so on. A sort-key canno
t be
a long string column.
A named column in the select list can be identified by a sort-key that is an int
eger
or a column name. An unnamed column in the select list must be identified by an
integer or by an expression. A column is unnamed if the AS clause is not specifi
ed
in the select list and the column is derived from a constant, an expression with
operators, or a function. If the fullselect includes a UNION operator, the fulls
elect
rules on named columns apply.
column-name
Usually identifies a column of the result table. In this case, column-name must
be the name of a named column in the select list. If the fullselect includes a
UNION or UNION ALL, the column name cannot be qualified.
If the query is a subselect, the column-name can also identify a column name
of a table, view, or nested table expression identified in the FROM clause. An
error occurs if the subselect includes any of the following:
v DISTINCT in the select list
v Column functions in the select list
v GROUP BY clause
integer
Must be greater than 0 and not greater than the number of columns in the
result table. The integer n identifies the nth column of the result table.
expression
Specifies an expression with operators (that is, not simply a column-name or
integer). The query to which ordering is applied must be a subselect to use this
form of the sort-key.
The expression cannot include a non-deterministic function or a function with an
external action. Any column name in the expression must conform to the rules
described in “Column names in sort keys” on page 323. An expression cannot
be specified if DISTINCT is used in the select list of the subselect.
If the subselect is grouped, the expression can be an expression in the select
list of the subselect or can include a column function, constant, or host variab
le.
If the expression is not in the select list, the following rules apply:
 
,
ASC
ORDER BY sort-key
DESC

sort-key:
 column-name
integer
expression

select-statement
322 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v If the subselect contains a GROUP BY clause, all columns in the expression
must be in the GROUP BY clause.
v If the subselect does not contain a GROUP BY clause (the result is grouped
because a column function is in the ORDER BY clause), all expressions in
the select list must be grouped data, constants, or host variables.
ASC
Uses the values of the sort-key in ascending order. This is the default.
DESC
Uses the values of the sort-key in descending order.
Ordering is performed in accordance with the comparison rules described in
Chapter 2. Language elements, beginning on page 72. The null value is higher tha
n
all other values. If your ordering specification does not determine a complete
ordering, rows with duplicate values of the last identified sort-keyy have an ar
bitrary
order. If you do not specify ORDER BY, the rows of the result table have an
arbitrary order.
Column names in sort keys: A column name in a sort-key must conform to the
following rules:
v If the column name is qualified, the query must be a subselect. The column
name must unambiguously identify a column of a table, view, or nested table
expression in the FROM clause of the subselect; its value is used to compute the
value of the sort specification.
v If the column name is unqualified, the following two cases apply:
– The query is a subselect. In this case, the column name must unambiguously
identify a column of a table, view, or nested table expression in the FROM
clause of the subselect. If the column name is identical to one column of the
result table, its value is used to compute the value of the sort specification.
If
the column name is not identical to one column, it must unambiguously
identify a column of a table, view, or nested table expression in the FROM
clause of the fullselect.
– The query is not a subselect (that is, the query includes a UNION or UNION
ALL). The column name must be identical to exactly one column of the result
table; its value is used to compute the value of the sort specification.
read-only-clause
The clause FOR FETCH ONLY26 declares that the result table is read-only. The
cursor cannot be used in positioned updates and deletes with one exception. A
SENSITIVE STATIC scrollable cursor can perform positioned updates or deletes
even if FOR READ ONLY is specified in its SELECT statement.
Some result tables are read-only by nature (for example, a table based on a
read-only view.) FOR FETCH ONLY can still be specified for such tables, but the
specification has no effect. For result tables for which updates and deletes are
26. Or, FOR READ ONLY is equivalent.
 FOR FETCH ONLY
READ

select-statement
Chapter 4. Queries 323
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
possible, specifying FOR FETCH ONLY can possibly improve the performance of
FETCH operations and distributed operations.
If factors other than specifying the FOR READ ONLY clause make the result table
read-only, positioned updates or deletes cannot be done. A read-only result tabl
e
must not be referred to in an UPDATE or DELETE statement, whether it is
read-only by nature or specified as FOR FETCH ONLY.
update-clause
The optional UPDATE clause identifies the columns that can be updated in a later
positioned UPDATE statement. Each column name must be unqualified and must
identify a column of the table or view identified in the first FROM clause of th
e
fullselect. The clause must not be specified if the result table of the fullsele
ct is
read-only. For a discussion of read-only result tables, see “DECLARE CURSOR” on
page 665. The clause must also not be specified if a created temporary table is
referenced in the first FROM clause of the select-statement.
If the UPDATE clause is specified without a list of columns, the columns that ca
n be
updated will include all the updatable columns of the table or view that is iden
tified
in the first FROM clause of the fullselect.
The declaration of a cursor referred to in a positioned UPDATE statement need no
t
include an UPDATE clause if the STDSQL(YES) or NOFOR option is specified
when the program is precompiled. For more on the subject, see “Positioned
updates of columns” on page 152.
When FOR UPDATE is used, FETCH operations referencing the cursor acquire U
or X locks rather than S locks when:
v The isolation level of the statement is cursor stability.
v The isolation level of the statement is repeatable read or read stability and
field U
LOCK FOR RR/RS on installation panel DSNTIPI is set to get U locks.
v The isolation level of the statement is repeatable read or read stability and
KEEP
UPDATE LOCKS is specified in the SQL statement, an X lock, instead of a U
lock, is acquired at FETCH time.
No locks are acquired on declared temporary tables. For a discussion of U locks
and S locks, see Part 5 (Volume 2) of DB2 Administration Guide.
optimize-for-clause


FOR UPDATE
,
OF column-name

 OPTIMIZE FOR integer ROWS
ROW

select-statement
324 SQL Reference
|
|
|
|
|
|
|
|
The OPTIMIZE FOR clause requests special optimization of the select-statement. I
f
the clause is omitted, optimization is based on the assumption that all rows of
the
result table will be retrieved. If the clause is specified, optimization is base
d on the
assumption that the number of rows retrieved will not exceed n, where n is the
value of the integer.
The OPTIMIZE FOR clause does not limit the number of rows that can be fetched
or affect the result in any way other than performance. In general, if you are
retrieving only a few rows, use OPTIMIZE FOR 1 ROW to influence the access
path that DB2 selects. For more information about using this clause, see DB2
Application Programming and SQL Guide.
with-clause
The WITH clause specifies the isolation level at which the statement is executed
.
(Isolation level does not apply to declared temporary tables because no locks ar
e
acquired.)
CS Cursor stability
UR Uncommitted read
RR Repeatable read
RR KEEP UPDATE LOCKS
Repeatable read keep update locks
RS Read stability
RS KEEP UPDATE LOCKS
Read stability keep update locks
WITH UR can be specified only if the result table is read-only.
WITH RR KEEP UPDATE LOCKS or WITH RS KEEP UPDATE LOCKS can be
specified only if the FOR UPDATE OF clause is also specified. KEEP UPDATE
LOCKS tells DB2 to acquire and hold an X lock instead of an U or S lock on all
qualified pages and rows. Although this option can reduce concurrency, it can
prevent some types of deadlocks.
The default isolation level of the statement depends on:
v The isolation of the package or plan that the statement is bound in
v Whether the result table is read-only
If package isolation
is:
And plan isolation
is:
And the result table
is:
Then the default
isolation is:
RR Any Any RR
RS Any Any RS
CS Any Any CS
 WITH CS
UR
RR
KEEP UPDATE LOCKS
RS
KEEP UPDATE LOCKS

select-statement
Chapter 4. Queries 325
If package isolation
is:
And plan isolation
is:
And the result table
is:
Then the default
isolation is:
UR Any Read-only UR
Not read-only CS
Not specified Not specified Any RR
RR Any RR
RS Any RS
CS Any CS
UR Read-only UR
Not read-only CS
See “Notes” on page 668 for a list of the characteristics that make a result table
read-only. A simple way to ensure that a result table is read-only is to specify
FOR
FETCH ONLY or FOR READ ONLY in the SQL statement.
queryno-clause
The QUERYNO clause specifies the number to be used for this SQL statement in
EXPLAIN output and trace records. The number is used for the QUERYNO columns
of the plan tables for the rows that contain information about this SQL statemen
t.
This number is also used in the QUERYNO column of the SYSIBM.SYSSTMT and
SYSIBM.SYSPACKSTMT catalog tables.
If the clause is omitted, the number associated with the SQL statement is the
statement number assigned during precompilation. Thus, if the application progra
m
is changed and then precompiled, that statement number might change.
Using the QUERYNO clause to assign unique numbers to the SQL statements in a
program is helpful:
v For simplifying the use of optimization hints for access path selection
v For correlating SQL statement text with EXPLAIN output in the plan table
For information on using optimization hints, such as enabling the system for
optimization hints and setting valid hint values, and for information on accessi
ng the
plan table, see Part 5 (Volume 2) of DB2 Administration Guide.
fetch-first-clause
The FETCH FIRST clause limits the number of rows that can be fetched. It
improves the performance of queries with potentially large result sets when only
a
 QUERYNO integer 
 FETCH FIRST
1
integer
ROW
ROWS
ONLY 
select-statement
326 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
limited number of rows are needed. If the clause is specified, the number of row
s
retrieved will not exceed n, where n is the value of the integer. An attempt to
fetch
n+1 rows is handled the same way as normal end of data. The value of integer
must be positive and non-zero. The default is 1.
If the OPTIMIZE FOR clause is not specified, a default of ″OPTIMIZE FOR integer
ROWS″ is assumed. If both the FETCH FIRST and OPTIMIZE FOR clauses are
specified, the lower of the integer values from these clauses is used to influen
ce
optimization and the communications buffer size.
If both the FETCH FIRST clause and the ORDER BY clause are specified, the
ordering is performed on the entire result set prior to returning the first n ro
ws.
Examples of select statements
Example 1: Select all the rows from DSN8710.EMP.
SELECT * FROM DSN8710.EMP;
Example 2: Select all the rows from DSN8710.EMP, arranging the result table in
chronological order by date of hiring.
SELECT * FROM DSN8710.EMP ORDER BY HIREDATE;
Example 3: Select the department number (WORKDEPT) and average
departmental salary (SALARY) for all departments in the table DSN8710.EMP.
Arrange the result table in ascending order by average departmental salary.
SELECT WORKDEPT, AVG(SALARY)
FROM DSN8710.EMP
GROUP BY WORKDEPT
ORDER BY 2;
Example 4: Change various salaries, bonuses, and commissions in the table
DSN8710.EMP. Confine the changes to employees in departments D11 and D21.
Use positioned updates to do this with a cursor named UP_CUR. Use a FOR
UPDATE clause in the cursor declaration to indicate that all updatable columns a
re
updated. Below is the declaration for a PL/I program.
EXEC SQL DECLARE UP_CUR CURSOR FOR
SELECT WORKDEPT, EMPNO, SALARY, BONUS, COMM
FROM DSN8710.EMP
WHERE WORKDEPT IN ( D11 , D21 )
FOR UPDATE;
Beginning where the cursor is declared, all updatable columns would be updated.
If
only specific columns needed to be updated, such as only the salary column, the
FOR UPDATE clause could be used to specify the salary column (FOR UPDATE
OF SALARY).
Example 5: Find the maximum, minimum, and average bonus in the table
DSN8710.EMP. Execute the statement with uncommitted read isolation, regardless
of the value of ISOLATION with which the plan or package containing the statemen
t
is bound. Assign 13 as the query number for the SELECT statement.
EXEC SQL
SELECT MAX(BONUS), MIN(BONUS), AVG(BONUS)
INTO :MAX, :MIN, :AVG
FROM DSN8710.EMP
WITH UR
QUERYNO 13;
select-statement
Chapter 4. Queries 327
|
|
|
|
|
|
|
|
|
|
|
If bind option EXPLAIN(YES) is specified, rows are inserted into the plan table.
The
value used for the QUERYNO column for these rows is 13.
Example 6: The cursor declaration shown below is in a PL/I program. In the query
within the declaration, X.RMT_TAB is an alias for a table at some other DB2.
Hence, when the query is used, it is processed using DRDA access. See
“Distributed data” on page 14.
The declaration indicates that no positioned updates or deletes will be done wit
h the
query’s cursor. It also specifies that the access path for the query be optimized
for
the retrieval of at most 50 rows. Even so, the program can retrieve more than 50
rows from the result table, which consists of the entire table identified by the
alias.
However, when more than 50 rows are retrieved, performance could possibly
degrade.
EXEC SQL DECLARE C1CURSOR FOR
SELECT * FROM X.RMT_TAB
OPTIMIZE FOR 50 ROWS
FOR FETCH ONLY;
The FETCH FIRST clause could be used instead of the OPTIMIZE FOR clause to
ensure that only 50 rows are retrieved as in the following example:
EXEC SQL DECLARE C1CURSOR FOR
SELECT * FROM X.RMT_TAB
FETCH FIRST 50 ROWS Only;
select-statement
328 SQL Reference
|
|
|
|||
Chapter 5. Statements
This chapter contains syntax diagrams, semantic descriptions, rules, and example
s
of the use of the SQL statements listed in the following table.
Table 33. SQL statements
SQL statement Function Page
ALLOCATE CURSOR Defines and associates a cursor with a result set locator variab
le 338
ALTER DATABASE Changes the description of a database 340
ALTER FUNCTION (external
scalar)
Changes the description of a user-defined external scalar or table
function
343
ALTER FUNCTION (SQL
scalar)
Changes the description of an SQL scalar function 359
ALTER INDEX Changes the description of an index 366
ALTER PROCEDURE
(external)
Changes the description of a stored procedure 378
ALTER PROCEDURE
(SQL))
Changes the description of an SQL procedure 389
ALTER STOGROUP Changes the description of a storage group 395
ALTER TABLE Changes the description of a table 398
ALTER TABLESPACE Changes the description of a table space 419
ASSOCIATE LOCATORS Gets the result set locator value for each result set returne
d by a stored
procedure
430
BEGIN DECLARE SECTION Marks the beginning of a host variable declaration section
433
CALL Calls a stored procedure 434
CLOSE Closes a cursor 442
COMMENT Replaces or adds a comment to the description of an object 444
COMMIT Ends a unit of recovery and commits the database changes made by
that unit of recovery
451
CONNECT (Type 1) Connects the process to a server 456
CONNECT (Type 2) Connects the process to a server 462
CREATE ALIAS Defines an alias 466
CREATE AUXILIARY TABLE Defines an auxiliary table for storing LOB data 466
CREATE DATABASE Defines a database 471
CREATE DISTINCT TYPE Defines a distinct type (user-defined data type) 474
CREATE FUNCTION
(external scalar)
Defines a user-defined external scalar function 482
CREATE FUNCTION
(external table)
Defines a user-defined external table function 504
CREATE FUNCTION
(sourced)
Defines a user-defined function that is based on an existing scalar or
column function
521
CREATE FUNCTION (SQL
scalar)
Defines a user-defined SQL scalar function 535
CREATE GLOBAL
TEMPORARY TABLE
Defines a created temporary table at the current server 545
CREATE INDEX Defines an index on a table 550
© Copyright IBM Corp. 1982, 2001 329
|
||
|
||
|
Table 33. SQL statements (continued)
SQL statement Function Page
CREATE PROCEDURE
(external)
Defines an external stored procedure 566
CREATE PROCEDURE
(SQL)
Defines an SQL procedure 584
CREATE STOGROUP Defines a storage group 596
CREATE SYNONYM Defines an alternate name for a table or view 599
CREATE TABLE Defines a table 601
CREATE TABLESPACE Defines a table space, which includes allocating and formattin
g the table
space
629
CREATE TRIGGER Defines a trigger 647
CREATE VIEW Defines a view of one or more tables or views 658
DECLARE CURSOR Defines an SQL cursor 665
DECLARE GLOBAL
TEMPORARY TABLE
Defines a declared temporary table at the current server 672
DECLARE STATEMENT Declares names used to identify prepared SQL statements 682
DECLARE TABLE Provides the programmer and the precompiler with a description of
a
table or view
683
DECLARE VARIABLE Defines a CCSID for a host variable 685
DELETE Deletes one or more rows from a table 688
DESCRIBE (prepared
statement or TABLE)
Describes the result columns of a prepared statement or the columns of
a table or view
695
DESCRIBE CURSOR Puts information about the result set associated with a cursor i
nto a
descriptor
702
DESCRIBE INPUT Puts information about the input parameters (markers) of a prepar
ed
statement into a descriptor
704
DESCRIBE PROCEDURE Puts information about the result sets returned by a stored p
rocedure
into a descriptor
706
DROP Deletes objects 709
END DECLARE SECTION Marks the end of a host variable declaration section 721
EXECUTE Executes a prepared SQL statement 722
EXECUTE IMMEDIATE Prepares and executes an SQL statement 725
EXPLAIN Obtains information about how an SQL statement would be executed 727
FETCH Positions the cursor (BEFORE/AFTER), returns data (CURRENT), or
both postions the cursor and returns data
739
FREE LOCATOR Removes the association between a LOB locator variable and its valu
e 748
GRANT (collection
privileges)
Grants authority to create a package in a collection 752
GRANT (database
privileges)
Grants privileges on a database 753
GRANT (distinct type or JAR
privileges)
Grants the usage privilege on a distinct type (user-defined data type) or
JARs
755
GRANT (function or
procedure privileges)
Grants privileges on a user-defined function or a stored procedure 757
GRANT (package privileges) Grants authority to bind, execute, or copy a package
762
Statements
330 SQL Reference
|
|
| |
|| |
Table 33. SQL statements (continued)
SQL statement Function Page
GRANT (plan privileges) Grants authority to bind or execute an application plan
764
GRANT (schema privileges) Grants privileges on a schema 765
GRANT (system privileges) Grants system privileges 765
GRANT (table or view
privileges)
Grants privileges on a table or view 770
GRANT (use privileges) Grants authority to use specified buffer pools, storage g
roups, or table
spaces
773
HOLD LOCATOR Allows a LOB locator variable to retain its association with its va
lue
beyond a unit of work
775
INCLUDE Inserts declarations into a source program 776
INSERT Inserts one or more rows into a table 778
LABEL ON Replaces or adds a label on the description of a table, view, alias, or
column
784
LOCK TABLE Locks a table or table space partition in shared or exclusive mode 78
6
OPEN Opens a cursor 788
PREPARE Prepares an SQL statement (with optional parameters) for execution 792
RELEASE (connection) Places one or more connections in the release pending statu
s 805
RELEASE SAVEPOINT Releases a savepoint and any subsequently set savepoints withi
n a unit
of recovery
808
RENAME TABLE Renames an existing table 809
REVOKE (collection
privileges)
Revokes authority to create a package in a collection 816
REVOKE (database
privileges)
Revokes privileges on a database 817
REVOKE (distinct type or
JAR privileges)
Revokes the usage privilege on a distinct type (user-defined data type)
or JARs
819
REVOKE (Function or
Procedure privileges)
Revokes privileges on a user-defined function or a stored procedure 821
REVOKE (package
privileges)
Revokes authority to bind, execute, or copy a package 826
REVOKE (plan privileges) Revokes authority to bind or execute an application pla
n 828
REVOKE (schema
privileges)
Revokes privileges on a schema 829
REVOKE (system privileges) Revokes system privileges 831
REVOKE (table or view
privileges)
Revokes privileges on a table or view 834
REVOKE (use privileges) Revokes authority to use specified buffer pools, storage
groups, or table
spaces
837
ROLLBACK Ends a unit of recovery and backs out the changes to the database
made by that unit of recovery, or partially rolls back the changes to a
savepoint within the unit of recovery
839
SAVEPOINT Sets a savepoint within a unit of recovery 842
SELECT Specifies the SELECT statement of the cursor 844
SELECT INTO Specifies a result table of no more than one row and assigns the val
ues
to host variables
845
Statements
Chapter 5. Statements 331
|| |
Table 33. SQL statements (continued)
SQL statement Function Page
SET CONNECTION Establishes the database server of the process by identifying one
of its
existing connections
848
SET CURRENT
APPLICATION ENCODING
SCHEME
Assigns a value to the CURRENT APPLICATION ENCODING SCHEME
special register
850
SET CURRENT DEGREE Assigns a value to the CURRENT DEGREE special register 851
SET CURRENT LOCALE
LC_CTYPE
Assigns a value to the CURRENT LOCALE LC_CTYPE special register 853
SET CURRENT
OPTIMIZATION HINT
Assigns a value to the CURRENT OPTIMIZATION HINT special register 855
SET CURRENT
PACKAGESET
Assigns a value to the CURRENT PACKAGESET special register 856
SET CURRENT PRECISION Assigns a value to the CURRENT PRECISION special register
858
SET CURRENT RULES Assigns a value to the CURRENT RULES special register 859
SET CURRENT SQLID Assigns a value to the CURRENT SQLID special register 860
SET host-variable
Assignment
Assigns values to host variables 862
SET PATH Assigns a value to the CURRENT PATH special register 865
SET transition-variable
Assignment
Assigns values to transition variables 868
SIGNAL SQLSTATE Signals an error with a user-specified SQLSTATE and description
UPDATE Updates the values of one or more columns in one or more rows of a
table
872
VALUES Provides a method to invoke a user-defined function from a trigger 882
VALUES INTO Assigns values to host variables 883
WHENEVER Defines actions to be taken on the basis of SQL return codes 885
How SQL statements are invoked
The SQL statements described in this chapter are classified as executable or
nonexecutable. The section on invocation in the description of each statement
indicates whether or not the statement is executable.
Executable statements can be invoked in the following ways:
v Embedded in an application program
v Dynamically prepared and executed
v Dynamically prepared and executed using DB2 ODBC function calls
v Issued interactively
Depending on the statement, you can use some or all of these methods. The
section on invocation in the description of each statement tells you which metho
ds
can be used. See “Appendix B. Characteristics of SQL statements in DB2 for
OS/390 and z/OS” on page 913 for a list of executable statements.
A nonexecutable statement can only be embedded in an application program.
Statements
332 SQL Reference
|||
|| |
||
|
#
||
|
In addition to the statements described in this chapter, there is one more SQL
statement construct: the select-statement. (See “select-statement” on page 321.) It
is not included in this chapter because it is used in a different way from other
statements.
A select-statement can be invoked in the following ways:
v Included in DECLARE CURSOR and implicitly executed by OPEN
v Dynamically prepared, referred to in DECLARE CURSOR, and implicitly executed
by OPEN
v Dynamically executed (no PREPARE required) using a DB2 ODBC function call
v Issued interactively
The first two methods are called, respectively, the static and the dynamic invoc
ation
of select-statement.
Embedding a statement in an application program
You can include SQL statements in a source program that will be submitted to the
precompiler. Such statements are said to be embedded in the application program.
An embedded statement can be placed anywhere in the application program where
a host language statement is allowed. You must precede each embedded statement
with EXEC SQL.
Executable statements: An executable statement embedded in an application
program is executed every time a statement of the host language would be
executed if specified in the same place. (Thus, for example, a statement within
a
loop is executed every time the loop is executed, and a statement within a
conditional construct is executed only when the condition is satisfied.)
An embedded statement can contain references to host variables. A host variable
referred to in this way can be used in one of two ways:
As input
The current value of the host variable is used in the execution of the
statement.
As output
The variable is assigned a new value as a result of executing the
statement.
In particular, all references to host variables in expressions and predicates ar
e
effectively replaced by current values of the variables; that is, the variables
are
used as input. The treatment of other references is described individually for e
ach
statement.
The successful or unsuccessful execution of the statement is indicated by settin
g
the SQLCODE and SQLSTATE fields in the SQLCA.27 You must therefore follow all
executable statements by a test of SQLCODE or SQLSTATE. Alternatively, you can
use the WHENEVER statement (which is itself nonexecutable) to change the flow of
control immediately after the execution of an embedded statement.
Nonexecutable statements: An embedded nonexecutable statement is processed
only by the precompiler. The statement is never executed, and acts as a
27. SQLCODE and SQLSTATE cannot be in the SQLCA when the precompiler option STDS
QL(YES) is in effect. See “SQL standard
language” on page 150.
Statements
Chapter 5. Statements 333
“no-operation” if placed among executable statements of the application program.
Therefore, you must not follow such statements by a test of the SQLCODE or
SQLSTATE field in the SQLCA.
Dynamic preparation and execution
Your application program can dynamically build an SQL statement in the form of a
character string placed in a host variable. In general, the statement is built f
rom
some data available to the application program (for example, input from a termin
al).
The statement so constructed can be prepared for execution by means of the
(embedded) statement PREPARE and executed by means of the (embedded)
statement EXECUTE, as described in Part 6 of DB2 Application Programming and
SQL Guide. Alternatively, you can use the (embedded) statement EXECUTE
IMMEDIATE to prepare and execute a statement in one step.
The statement may also be prepared by calling the DB2 ODBC SQLPrepare
function and then executed by calling the DB2 ODBC SQLExecute function. In both
cases, the application does not contain an embedded PREPARE or EXECUTE
statement. You can execute the statement, without preparation, by passing the
statement to the DB2 ODBC SQLExecDirect function.
DB2 ODBC Guide and Reference describes the APIs supported with this interface.
A statement that is going to be prepared must not contain references to host
variables. It can instead contain parameter markers. (See “Parameter markers” on
page 798 in the description of the PREPARE statement for rules concerning
parameter markers.) When the prepared statement is executed, the parameter
markers are effectively replaced by current values of the host variables specifi
ed in
the EXECUTE statement. (See “EXECUTE” on page 722 for rules concerning this
replacement.) Once prepared, a statement can be executed several times with
different values of host variables.
Parameter markers are not allowed in the SQL statement prepared and executed
using EXECUTE IMMEDIATE.
The successful or unsuccessful execution of the statement is indicated by the
values returned in the SQLCODE and SQLSTATE fields in the SQLCA after the
EXECUTE (or EXECUTE IMMEDIATE) statement. You should check the fields as
described above for embedded statements.
As explained in “Authorization IDs and dynamic SQL” on page 43, the
DYNAMICRULES behavior in effect determines the privilege set that is used for
authorization checking when dynamic SQL statements are processed. Table 34
summarizes those privilege sets. (See Table 2 on page 44 for a list of the
DYNAMICRULES bind option values that determine which behavior is in effect).
Table 34. DYANMICRULES behaviors and authorization checking
DYNAMICRULES
behavior
Privilege set
Run behavior The union of the set of privileges held by each authorization ID of
the process if the dynamically prepared statement is other than an
ALTER, CREATE, DROP, GRANT, RENAME, or REVOKE
statement.
The privileges that are held by the SQL authorization ID of the
process if the dynamic SQL statement is a CREATE, GRANT, or
REVOKE statement.
Statements
334 SQL Reference
Table 34. DYANMICRULES behaviors and authorization checking (continued)
DYNAMICRULES
behavior
Privilege set
Bind behavior The privileges that are held by the primary authorization ID of th
e
owner of the package or plan.
Define behavior The privileges that are held by the authorization ID of the stor
ed
procedure or user-defined function owner (definer).
Invoke behavior The privileges that are held by the authorization ID of the stor
ed
procedure or user-defined function invoker. However, if the invoker is
the primary authorization ID of the process or the CURRENT SQLID
value, secondary authorization IDs are also checked if they are
needed for the required authorization. Therefore, in that case, the
privilege set is the union of the set of privileges that are held by
each authorization ID.
Static invocation of a SELECT statement
You can include a SELECT statement as a part of the (nonexecutable) statement
DECLARE CURSOR. Such a statement is executed every time you open the cursor
by means of the (embedded) statement OPEN. After the cursor is open, you can
retrieve the result table a row at a time by successive executions of the (embed
ded)
SQL FETCH statement.
If the application is using DB2 ODBC, the SELECT statement is first prepared wit
h
the SQLPrepare function call. It is then executed with the SQLExecute function c
all.
Data is then fetched with the SQLFetch function call. The application does not
explicitly open the cursor.
The SELECT statement used in this way can contain references to host variables.
These references are effectively replaced by the values that the variables have
at
the moment of executing OPEN.
The successful or unsuccessful execution of the SELECT statement is indicated by
the values returned in the SQLCODE and SQLSTATE fields in the SQLCA after the
OPEN. You should check the fields as described above for embedded statements.
If the application is using DB2 ODBC, the successful execution of the SELECT
statement is indicated by the return code from the SQLExecute function call. If
necessary, the application may retrieve the SQLCA by calling the SQLGetSQLCA
function.
Dynamic invocation of a SELECT statement
Your application program can dynamically build a SELECT statement in the form of
a character string placed in a host variable. In general, the statement is built
from
some data available to the application program (for example, a query obtained fr
om
a terminal). The statement so constructed can be prepared for execution by means
of the (embedded) statement PREPARE, and referred to by a (nonexecutable)
statement DECLARE CURSOR. The statement is then executed every time you
open the cursor by means of the (embedded) statement OPEN. After the cursor is
open, you can retrieve the result table a row at a time by successive executions
of
the (embedded) SQL FETCH statement.
The SELECT statement used in that way must not contain references to host
variables. It can instead contain parameter markers. (See “Notes” in “PREPARE” on
page 792
Statements
Chapter 5. Statements 335
page 791 for rules concerning parameter markers.) The parameter markers are
effectively replaced by the values of the host variables specified in the OPEN
statement. (See “OPEN” on page 788 for rules concerning this replacement.)
The successful or unsuccessful execution of the SELECT statement is indicated by
the values returned in the SQLCODE and SQLSTATE fields in the SQLCA after the
OPEN. You should check the fields as described above for embedded statements.
Interactive invocation
IBM relational database management systems allow you to enter SQL statements
from a terminal. DB2 for OS/390 and z/OS provides SPUFI to prepare and execute
these statements. Other products are also available. A statement entered in this
way is said to be issued interactively.
A statement issued interactively must not contain parameter markers or reference
s
to host variables, because these make sense only in the context of an applicatio
n
program. For the same reason, there is no SQLCA involved.
Checking the execution of SQL statements
An application program that contains executable SQL statements must include one
or both of the following stand-alone host variables:
v SQLCODE (SQLCOD in Fortran)
v SQLSTATE (SQLSTT in Fortran)
Or,
v An SQLCA, which can be provided by using the INCLUDE SQLCA statement
Whether you define stand-alone SQLCODE and SQLSTATE host variables or an
SQLCA in your program depends on the DB2 precompiler option you choose.
If the application is using DB2 ODBC and it calls the SQLGetSQLCA function, it
need only include an SQLCA. Otherwise, all notification of success or errors is
specified with return codes for the various function calls.
When you specify STDSQL(YES), which indicates conformance to the SQL
standard, you should not define an SQLCA. The stand-alone variable for SQLCODE
must be a valid host variable in the DECLARE SECTION of a program. It can also
be declared outside of the DECLARE SECTION when no variable is defined for
SQLSTATE. The stand-alone variable for SQLSTATE must be declared in the
DECLARE SECTION; it must not be declared as an element of a structure.
When you specify STDSQL(NO), which indicates conformance to DB2 rules, you
must include an SQLCA explicitly.
SQLCODE
Regardless of whether the application program provides an SQLCA or a
stand-alone variable for SQLCODE, DB2 sets SQLCODE after each SQL statement
is executed. DB2 conforms to the SQL standard as follows:
v If SQLCODE = 0, execution was successful.
v If SQLCODE > 0, execution was successful with a warning.
v If SQLCODE < 0, execution was not successful.
SQLCODE +100 indicates "no data". For example, a FETCH statement returned no
data because the cursor was positioned after the last row of the result table. T
he
Statements
336 SQL Reference
SQL standard does not define the meaning of any other specific positive or negat
ive
values of SQLCODE and the meaning of these values is not the same in all
implementations of SQL.
If the application is using DB2 ODBC, an SQLCODE is only returned if the
application issues the SQLGetSQLCA function.
SQLSTATE
Regardless of whether the application program provides an SQLCA or a
stand-alone variable for SQLSTATE, DB2 sets SQLSTATE after each SQL
statement is executed. DB2 returns values that conform to the error specificatio
n in
the SQL standard.
If the application is using DB2 ODBC, the SQLSTATE returned conforms to the
ODBC Version 2.0 specification.
SQLSTATE provides application programs with common codes for common error
conditions (the values of SQLSTATE are product-specific if the error or warning
is
product-specific). Furthermore, SQLSTATE is designed so that application program
s
can test for specific errors or classes of errors. The coding scheme is the same
for
all IBM implementations of SQL. The SQLSTATE values are based on the
SQLSTATE specifications contained in the SQL standard.
Error messages and the tokens that are substituted for variables in error messag
es
are associated with SQLCODE values, not SQLSTATE values.
Statements
Chapter 5. Statements 337
ALLOCATE CURSOR
The ALLOCATE CURSOR statement specifies a cursor and associates it with a
result set locator variable.
Invocation
This statement can be embedded in an application program. It is an executable
statement that can be dynamically prepared. It cannot be issued interactively.
Authorization
None required.
Syntax
Description
cursor-name
Identifies the cursor. The name must not identify a cursor that has already been
declared in the source program.
CURSOR FOR RESULT SET rs-locator-variable
Specifies a result set locator variable that has been declared in the applicatio
n
program according to the rules for declaring result set locator variables.
The result set locator variable must contain a valid result set locator value, a
s
returned by the ASSOCIATE LOCATORS or DESCRIBE PROCEDURE SQL
statement.
Notes
Dynamically prepared ALLOCATE CURSOR statements: The EXECUTE
statement with the USING clause must be used to execute a dynamically prepared
ALLOCATE CURSOR statement. In a dynamically prepared statement, references
to host variables are represented by parameter markers (question marks). In the
ALLOCATE CURSOR statement, rs-locator-variable is always a host variable. Thus,
for a dynamically prepared ALLOCATE CURSOR statement, the USING clause of
the EXECUTE statement must identify the host variable whose value is to be
substituted for the parameter marker that represents rs-locator-variable.
You cannot prepare an ALLOCATE CURSOR statement with a statement identifier
that has already been used in a DECLARE CURSOR statement. For example, the
following SQL statements are invalid because the PREPARE statement uses
STMT1 as an identifier for the ALLOCATE CURSOR statement and STMT1 has
already been used for a DECLARE CURSOR statement.
DECLARE CURSOR C1FOR STMT1;
PREPARE STMT1FROM INVALID
ALLOCATE C2 CURSOR FOR RESULT SET ? ;
Rules for using an allocated cursor: The following rules apply when you use an
allocated cursor:
v You cannot open an allocated cursor with the OPEN statement.
 ALLOCATE cursor-name CURSOR FOR RESULT SET rs-locator-variable 
ALLOCATE CURSOR
338 SQL Reference
v You can close an allocated cursor with the CLOSE statement. Closing an
allocated cursor closes the associated cursor defined in the stored procedure.
v You can allocate only one cursor to each result set.
The life of an allocated cursor: A rollback operation, an implicit close, or an
explicit close destroy allocated cursors. A commit operation destroys allocated
cursors that are not defined WITH HOLD by the stored procedure. Destroying an
allocated cursor closes the associated cursor defined in the stored procedure.
Example
The statement in the following example is assumed to be in a PL/I program.
Define and associate cursor C1 with the result set locator variable LOC1 and the
related result set returned by the stored procedure:
EXEC SQL ALLOCATE C1CURSOR FOR RESULT SET :LOC1;
ALLOCATE CURSOR
Chapter 5. Statements 339
ALTER DATABASE
The ALTER DATABASE statement changes the description of a database at the
current server.
Invocation
This statement can be embedded in an application program or issued interactively
.
It is an executable statement that can be dynamically prepared only if
DYNAMICRULES run behavior is implicitly or explicitly specified.
Authorization
The privilege set that is defined below must include at least one of the followi
ng:
v The DROP privilege on the database
v Ownership of the database
v DBADM or DBCTRL authority for the database
v SYSADM or SYSCTRL authority
Privilege set: If the statement is embedded in an application program, the privi
lege
set is the privileges that are held by the authorization ID of the owner of the
plan or
package. If the statement is dynamically prepared, the privilege set is the unio
n of
the privilege sets that are held by each authorization ID of the process.
Syntax
Description
DATABASE database-name
Identifies the database to be altered. The name must identify a database that
exists at the current server.
BUFFERPOOL bpname
Identifies the default buffer pool for the table spaces within the database. It
does not apply to table spaces that already exist within the database.
If the database is a work file database, 8KB and 16KB buffer pools cannot be
specified.
See “Naming conventions” on page 34 for more details about bpname.
INDEXBP bpname
Identifies the default buffer pool for the indexes within the database. It does
not
apply to indexes that already exist within the database. The name must identify
a 4KB buffer pool. See “Naming conventions” on page 34 for more details about
bpname.
 ALTER DATABASE database-name 
(1)
BUFFERPOOL bpname
INDEXBP bpname
STOGROUP stogroup-name
CCSID ccsid-value

Notes:
1 The same clause must not be specified more than once.
ALTER DATABASE
340 SQL Reference
INDEXBP cannot be specified for a work file database.
STOGROUP stogroup-name
Identifies the storage group to be used, as required, as a default storage group
to support DASD space requirements for table spaces and indexes within the
database. It does not apply to table spaces and indexes that already exist
within the database.
STOGROUP cannot be specified for a work file database.
CCSID ccsid-value
Identifies the default CCSID for table spaces within the database. It does not
apply to existing table spaces in the database. ccsid-value must identify a
CCSID value that is compatible with the current value of the CCSID for the
database. “Notes” contains a list that shows the CCSID to which a given CCSID
can be altered.
CCSID cannot be specified for a work file database or a TEMP database.
Notes
Altering the CCSID: The ability to alter the default CCSID enables you to change
to a CCSID that supports the Euro symbol. You can only convert between specific
CCSIDs that do and do not define the Euro symbol. In most cases, the codepoint
that supports the Euro symbol replaces an existing codepoint, such as the
International Currency Symbol (ICS).
Changing a CCSID can be disruptive to the system and requires several steps. For
each encoding scheme of a system (ASCII, EBCDIC, and Unicode), DB2 supports
SBCS, DBCS, and mixed CCSIDs. Therefore, the CCSIDs for all databases and all
table spaces within an encoding scheme should be altered at the same time.
Otherwise, unpredictable results might occur.
The recommended method for changing the CCSID requires that the data be
unloaded and reloaded. See Appendix A of DB2 Installation Guide for the steps
needed to change the CCSID, such as running an installation CLIST to modify the
CCSID data in DSNHDECP, when to drop and recreate views, and when to rebind
invalidated plans and packages.
The following lists show the CCSIDs that can be converted. The second CCSID in
each pair is the CCSID with the Euro symbol. The CCSID can be changed from the
CCSID that does not support the Euro symbol to the CCSID that does, and vice
versa. For example, if the current CCSID is 500, it can be changed to 1148.
EBCDIC CCSIDs
---------------
37 1140
273 1141
277 1142
278 1143
280 1144
284 1145
285 1146
297 1147
500 1148
871 1149
ALTER DATABASE
Chapter 5. Statements 341
|
|
|
|
|
ASCII CCSIDs
---------------
850 858
874 4970
1250 5346
1251 5347
1252 5348
1253 5349
1254 5350
1255 5351
1256 5352
1257 5353
Example
Change the default buffer pool for both table spaces and indexes within database
ABCDE to BP2.
ALTER DATABASE ABCDE
BUFFERPOOL BP2
INDEXBP BP2;
ALTER DATABASE
342 SQL Reference
ALTER FUNCTION (external scalar)
The ALTER FUNCTION statement changes the description of a user-defined
external scalar or external table function at the current server.
Invocation
This statement can be embedded in an application program or issued interactively
.
It is an executable statement that can be dynamically prepared only if
DYNAMICRULES run behavior is implicitly or explicitly specified.
Authorization
The privilege set defined below must include at least one of the following:
v Ownership of the function
v The ALTERIN privilege for the schema or all schemas
v SYSADM or SYSCTRL authority
The authorization ID that matches the schema name implicitly has the ALTERIN
privilege on the schema.
Privilege set: If the statement is embedded in an application program, the privi
lege
set is the privileges that are held by the authorization ID of the owner of the
plan or
package.
If the statement is dynamically prepared, the privilege set is the privileges th
at are
held by the authorization IDs of the process. The specified function name can
include a schema name (a qualifier). However, if the schema name is not the same
as one of these authorization IDs, one of the following conditions must be met:
v The privilege set includes SYSADM or SYSCTRL authority.
v An authorization ID of the process has the ALTERIN privilege on the schema.
If the environment in which the function is to be run is being changed, the
authorization ID must have authority to use the WLM environment specified. The
required authorization is obtained from an external security product, such as RA
CF.
For external scalar functions, when LANGUAGE is JAVA and a jar-name is specified
in the EXTERNAL NAME clause, the privilege set must include USAGE on the JAR,
the Java ARchive file.
Syntax
 ALTER

FUNCTION function-name
,
( )
parameter-type
SPECIFIC FUNCTION specific-name
option-list 
ALTER FUNCTION (external scalar)
Chapter 5. Statements 343
|
|
|
|
|
|
parameter-type:
 data-type
(1)
AS LOCATOR
TABLE LIKE table-name AS LOCATOR

Notes:
1 AS LOCATOR can be specified only for a LOB data type or a distinct type based
on a LOB data
type.
data-type:
 built-in-data-type
distinct-type-name

ALTER FUNCTION (external scalar)
344 SQL Reference
built-in-data-type:
 SMALLINT
INTEGER
INT
DECIMAL
DEC (1)
NUMERIC ( integer )
, integer
FLOAT
(2)
( integer )
REAL
PRECISION
DOUBLE
CHARACTER
CHAR (1) FOR SBCS DATA CCSID ASCII
( integer ) MIXED EBCDIC
(1) BIT UNICODE
CHARACTER VARYING ( integer )
CHAR
VARCHAR
CHARACTER LARGE OBJECT
CHAR (1) FOR SBCS DATA CCSID ASCII
CLOB ( integer ) MIXED EBCDIC
K UNICODE
M
G
BINARY LARGE OBJECT
BLOB (1)
( integer )
K
M
G
GRAPHIC
(1) CCSID ASCII
( integer ) EBCDIC
(1) UNICODE
VARGRAPHIC ( integer )
DBCLOB
(1)
( integer )
K
M
G
DATE
TIME
TIMESTAMP
ROWID

Notes:
1 The values that are specified for length, precision, or scale attributes must
match the values that
were specified when the function was created. Coding specific values is optional
. Empty
parentheses, (), can be used instead to indicate that DB2 is to ignore the attri
butes when
determining whether data types match.
2 The value that is specified does not have to match the value that was specifie
d when the function
was created because matching is based on data type (REAL or DOUBLE). 1<=integer<
= 21
indicates REAL and 22<=integer<=53 indicates DOUBLE. Coding a specific value is
optional.
Empty parentheses cannot be used.
ALTER FUNCTION (external scalar)
Chapter 5. Statements 345
option-list:

(1)
EXTERNAL
(2)
NAME ’string’
identifier
LANGUAGE ASSEMBLE
C
COBOL
(3) (4)
JAVA
PLI

 PARAMETER STYLE DB2SQL
(3) (4)
JAVA
(5)
NOT DETERMINISTIC
DETERMINISTIC


(6)
RETURNS NULL ON NULL INPUT
CALLED ON NULL INPUT
READS SQL DATA
CONTAINS SQL
(4)
MODIFIES SQL DATA
NO SQL
NO EXTERNAL ACTION
EXTERNAL ACTION

 NO SCRATCHPAD
SCRATCHPAD length
NO FINAL CALL
FINAL CALL
(4)
ALLOW PARALLEL
DISALLOW PARALLEL
NO DBINFO
DBINFO


(7)
CARDINALITY integer NO COLLID
COLLID collection-id
WLM ENVIRONMENT name
( name ,* )

 ASUTIME NO LIMIT
LIMIT integer
STAY RESIDENT NO
YES
PROGRAM TYPE SUB
MAIN

 SECURITY DB2
USER
DEFINER

 RUN OPTIONS run-time-options INHERIT SPECIAL REGISTERS
DEFAULT SPECIAL REGISTERS

Notes:
1 The clauses in the option-list can be specified in any order. The same clause
must not be
specified more than once.
2 If LANGUAGE is JAVA, EXTERNAL NAME must be specified with a ’string’ that is a val
id
external-java-routine-name. See the following figure.
3 When LANGUAGE JAVA is specified, PARAMETER STYLE JAVA must also be specified.
When
PARAMETER STYLE JAVA is specified, LANGUAGE JAVA must be also be specified.
4 LANGUAGE JAVA, PARAMETER STYLE JAVA, MODIFIES SQL DATA, and ALLOW PARALLEL
are not supported for external table functions.
5 Synonyms for this clause include VARIANT for NOT DETERMINISTIC, and NOT VARIAN
T for
DETERMINISTIC.
6 Synonyms for this clause include NOT NULL CALL for RETURNS NULL ON NULL INPUT,
and
NULL CALL for CALLED ON NULL INPUT.
7 CARDINALITY is not supported for external scalar functions.
ALTER FUNCTION (external scalar)
346 SQL Reference
Description
One of the following three clauses identifies the function to be changed.
FUNCTION function-name
Identifies the external function by its function name. The name is implicitly or
explicitly qualified with a schema name. If the name is not explicitly qualified
, it
is implicitly qualified with a schema name according to the following rules:
v If the statement is embedded in a program, the schema name is the
authorization ID in the QUALIFIER bind option when the plan or package
was created or last rebound. If QUALIFIER was not specified, the schema
name is the owner of the plan or package.
v If the statement is prepared dynamically, the schema name is the SQL
authorization ID in the CURRENT SQLID special register.
The identified function must be an external function. There must be exactly one
function with function-name in the schema. The function can have any number
external-java-routine-name:
jar-name:
method-name
method-signature
jar-name:
schema-name.
jar-id
method-name:

package-id .
(1)
/
class-id .
(2)
!
method-id
method-signature:

( )
,
java-datatype
Notes:
1 The slash (/) is supported for compatibility with DB2 for OS/390 Version 5 and
Version 6.
2 The exclamation point (!) is supported for compatibility with DB2 UWO.
ALTER FUNCTION (external scalar)
Chapter 5. Statements 347
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
of input parameters. If the schema does not contain a function with
function-name or contains more than one function with this name, an error
occurs.
FUNCTION function-name (parameter-type,...)
Identifies the external function by its function signature, which uniquely ident
ifies
the function.
function-name
Gives the function name of the external function. If the function name is not
qualified, it is implicitly qualified with a schema name as described in the
preceding description for FUNCTION function-name.
(parameter-type,...)
Identifies the number of input parameters of the function and their data
types.
The data type of each parameter must match the data type that was
specified in the CREATE FUNCTION statement for the parameter in the
corresponding position. The number of data types and the logical
concatenation of the data types are used to uniquely identify the function.
Therefore, you cannot change the number of parameters or the data types
of the parameters.
For data types that have a length, precision, or scale attribute, you can
specify a value or use a set of empty parentheses:
v Empty parentheses indicate that DB2 is to ignore the attribute when
determining whether the data types match.
FLOAT cannot be specified with empty parentheses because its
parameter value indicates different data types (REAL or DOUBLE).
v If you use a specific value for a length, precision, or scale attribute, the
value must exactly match the value that was specified (implicitly or
explicitly) in the CREATE FUNCTION statement.
The specific value for FLOAT(n) does not have to exactly match the
defined value of the source function because 1<=n<= 21 indicates REAL
and 22<=n<=53 indicates DOUBLE. Matching is based on whether the
data type is REAL or DOUBLE.
v If length, precision, or scale is not explicitly specified, and empty
parentheses are not specified, the default length of the data type is
implied. For example:
CHAR CHAR(1)
GRAPHIC GRAPHIC(1)
DECIMAL DECIMAL(5,0)
FLOAT DOUBLE (length of 8)
The implicit length must exactly match the value that was specified
(implicitly or explicitly) in the CREATE FUNCTION statement. For a
complete list of the default lengths of data types, see “CREATE TABLE”
on page 601.
For data types with a subtype or encoding scheme attribute, specifying the
FOR DATA clause or CCSID clause is optional. Omission of either clause
indicates that DB2 is to ignore the attribute when determining whether the
data types match. If you specify either clause, it must match the value that
was implicitly or explicitly specified in the CREATE FUNCTION statement.
ALTER FUNCTION (external scalar)
348 SQL Reference
See “CREATE FUNCTION” on page 481 for more information on the
specification of the parameter list.
A function with the function signature must exist in the explicitly or implicitl
y
specified schema; otherwise, an error occurs.
SPECIFIC FUNCTION specific-name
Identifies the external function by its specific name. The name is implicitly or
explicitly qualified with a schema name. A function with the specific name must
exist in the schema; otherwise, an error occurs.
If the specific name is not qualified, it is implicitly qualified with a schema
name
as described in the preceding description for FUNCTION function-name.
The following clauses change the description of the function that has been ident
ified
to be changed.
EXTERNAL
Identifies the program that runs when the function is invoked.
DB2 loads the load module when the function is invoked. The load module is
created when the program that contains the function body is compiled and
link-edited. The load module does not need to exist when the ALTER
FUNCTION statement is executed. However, it must exist and be accessible by
the current server when the function is invoked.
You can specify the EXTERNAL clause in one of the following ways:
EXTERNAL
EXTERNAL NAME PKJVSP1
EXTERNAL NAME PKJVSP1
If you specify an external program name, you must use the NAME keyword. For
example, this syntax is not valid:
EXTERNAL PKJVSP1
NAME ’string’ or identifier
Identifies the user-written code that implements the user-defined function.
If LANGUAGE is JAVA, ’string’ must be specified and enclosed in single
quotation marks, with no extraneous blanks within the single quotation
marks. It must specify a valid external-java-routine-name. If multiple ’string’s
are specified, the total length of all of them must not be greater than 1305
bytes and they must be separated by a space or a line break. Do not
specify a JAR for a JAVA function for which NO SQL is in effect.
An external-java-routine-name contains the following parts:
jar-name
Identifies the name given to the JAR when it was installed in the
database. The name contains jar-id, which can optionally be qualified
with a schema. Examples are ″myJar″ and ″mySchema.myJar.″ The
unqualified jar-id is implicitly qualified with a schema name according to
the following rules:
v If the statement is embedded in a program, the schema name is the
authorization ID in the QUALIFIER bind option when the package or
plan was created or last rebound. If the QUALIFIER was not
specified, the schema name is the owner of the package or plan.
ALTER FUNCTION (external scalar)
Chapter 5. Statements 349
|
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
#
#
|
|
|
|
|
|
|
|
|
|
|
v If the statement is dynamically prepared, the schema name is the
SQL authorization ID in the CURRENT SQLID special register.
If jar-name is specified, it must exist when the ALTER FUNCTION
statement is processed.
If jar-name is not specified, the function is loaded from the class file
directly instead of being loaded from a JAR file. DB2 for DB2 for
OS/390 and z/OS searches the directories in the CLASSPATH
associated with the WLM Environment. Environmental variables for
Java routines are specified in a dataset identified in a JAVAENV DD
card on the JCL used to start the address space for a WLM-managed
function.
method-name
Identifies the name of the method and must not be longer than 254
bytes. Its package, class, and method ID’s are specific to Java and as
such are not limited to 18 bytes. In addition, the rules for what these
can contain are not necessarily the same as the rules for an SQL
ordinary identifier.
package-id
Identifies the package list that the class identifier is part of. If the
class is part of a package, the method name must include the
complete package prefix, such as ″myPacks.UserFuncs.″ The Java
virtual machine looks in the directory ″/myPacks/UserFuncs/″ for the
classes.
class-id
Identifies the class identifier of the Java object.
method-id
Identifies the method identifier with the Java class to be invoked.
method-signature
Identifies a list of zero or more Java data types for the parameter list
and must not be longer than 1024 bytes. Specify the method-signature
if the user-defined function involves any input or output parameters that
can be NULL. When the function being created is called, DB2 searches
for a Java method with the exact method-signature. The number of
java-datatype elements specified indicates how many parameters that
the Java method must have.
A Java procedure can have no parameters. In this case, you code an
empty set of parentheses for method-signature. If a Java
method-signature is not specified, DB2 searches for a Java method with
a signature derived from the default JDBC types associated with the
SQL types specified in the parameter list of the ALTER FUNCTION
statement.
For other values of LANGUAGE, the name can be a string constant that is
no longer than 8 characters or a short identifier. It must conform to the
naming conventions for MVS load modules. Alphabetical extenders for
national languages can be used as the first character and as subsequent
characters in the load module name.
If you do not specify the NAME clause, ’NAME function-name’ is implicit. In
this case, function-name must not be longer than 8 characters.
ALTER FUNCTION (external scalar)
350 SQL Reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|<