Upload
others
View
21
Download
0
Embed Size (px)
Citation preview
IBM®
DB2 Universal Database™
SQL Reference Volume 1
Version 8
SC09-4844-00
���
IBM®
DB2 Universal Database™
SQL Reference Volume 1
Version 8
SC09-4844-00
���
Before using this information and the product it supports, be sure to read the general information under Notices.
This document contains proprietary information of IBM. It is provided under a license agreement and is protected bycopyright law. The information contained in this publication does not include any product warranties, and anystatements provided in this manual should not be interpreted as such.
You can order IBM publications online or through your local IBM representative.v To order publications online, go to the IBM Publications Center at www.ibm.com/shop/publications/order
v To find your local IBM representative, go to the IBM Directory of Worldwide Contacts atwww.ibm.com/planetwide
To order DB2 publications from DB2 Marketing and Sales in the United States or Canada, call 1-800-IBM-4YOU(426-4968).
When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in anyway it believes appropriate without incurring any obligation to you.
© Copyright International Business Machines Corporation 1993 - 2002. All rights reserved.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.
Contents
About this book . . . . . . . . . . xiWho should use this book . . . . . . . xiHow this book is structured . . . . . . . xi
A brief overview of Volume 2 . . . . . xiiHow to read the syntax diagrams . . . . xiiiCommon syntax elements . . . . . . . xv
Function designator . . . . . . . . xvMethod designator . . . . . . . . xviiProcedure designator . . . . . . . xviii
Conventions used in this manual . . . . . xxError conditions. . . . . . . . . . xxHighlighting conventions . . . . . . xx
Related documentation . . . . . . . . xxi
Chapter 1. Concepts . . . . . . . . . 1Relational databases. . . . . . . . . . 1Structured Query Language (SQL) . . . . . 1Authorization and privileges . . . . . . . 2Schemas. . . . . . . . . . . . . . 4Tables . . . . . . . . . . . . . . 5Views . . . . . . . . . . . . . . 6Aliases . . . . . . . . . . . . . . 7Indexes . . . . . . . . . . . . . . 7Keys . . . . . . . . . . . . . . . 7Constraints. . . . . . . . . . . . . 8
Unique constraints . . . . . . . . . 9Referential constraints . . . . . . . . 9Table check constraints . . . . . . . 12
Isolation levels . . . . . . . . . . . 13Queries . . . . . . . . . . . . . 16Table expressions . . . . . . . . . . 16Application processes, concurrency, andrecovery . . . . . . . . . . . . . 16DB2 Call level interface (CLI) and opendatabase connectivity (ODBC) . . . . . . 19Java database connectivity (JDBC) andembedded SQL for Java (SQLJ) programs . . 19Packages . . . . . . . . . . . . . 20Catalog views . . . . . . . . . . . 20Character conversion . . . . . . . . . 20Event monitors . . . . . . . . . . . 23Triggers . . . . . . . . . . . . . 24Table spaces and other storage structures . . 26Data partitioning across multiple partitions 28Distributed relational databases . . . . . 29
Remote unit of work . . . . . . . . 30Application-directed distributed unit ofwork . . . . . . . . . . . . . 33Data representation considerations . . . 38
DB2 federated systems . . . . . . . . 39Federated systems . . . . . . . . . 39Data sources . . . . . . . . . . . 41The federated database . . . . . . . 43The SQL Compiler and the queryoptimizer . . . . . . . . . . . . 44Compensation . . . . . . . . . . 45Pass-through sessions . . . . . . . . 46Wrappers and wrapper modules . . . . 48Server definitions and server options. . . 50User mappings and user options . . . . 51Nicknames and data source objects . . . 52Column options. . . . . . . . . . 53Data type mappings . . . . . . . . 54Function mappings and function templates 56Function mappings options . . . . . . 57Index specifications . . . . . . . . 58
Chapter 2. Language elements . . . . . 61Characters . . . . . . . . . . . . 61Tokens . . . . . . . . . . . . . . 63Identifiers . . . . . . . . . . . . . 65
Naming conventions and implicit objectname qualifications . . . . . . . . 65Aliases . . . . . . . . . . . . . 70Authorization IDs and authorizationnames . . . . . . . . . . . . . 71Column names . . . . . . . . . . 76References to host variables . . . . . . 83
Data types . . . . . . . . . . . . 92Data types . . . . . . . . . . . 92Numbers . . . . . . . . . . . . 94Character strings . . . . . . . . . 95Graphic strings . . . . . . . . . . 97Binary strings . . . . . . . . . . 98Large objects (LOBs) . . . . . . . . 99Datetime values . . . . . . . . . 101DATALINK values . . . . . . . . 105XML values . . . . . . . . . . . 107User-defined types . . . . . . . . 108Promotion of data types. . . . . . . 111
© Copyright IBM Corp. 1993 - 2002 iii
Casting between data types . . . . . 113Assignments and comparisons . . . . 117Rules for result data types . . . . . . 134Rules for string conversions . . . . . 140Partition-compatible data types . . . . 141
Constants . . . . . . . . . . . . 143Integer constants . . . . . . . . . 143Floating-point constants. . . . . . . 144Decimal constants. . . . . . . . . 144Character string constants . . . . . . 144Hexadecimal constants . . . . . . . 145Graphic string constants . . . . . . 145
Special registers . . . . . . . . . . 146Special registers . . . . . . . . . 146CLIENT ACCTNG . . . . . . . . 148CLIENT APPLNAME . . . . . . . 149CLIENT USERID . . . . . . . . . 150CLIENT WRKSTNNAME . . . . . . 151CURRENT DATE . . . . . . . . . 152CURRENT DBPARTITIONNUM . . . . 153CURRENT DEFAULT TRANSFORMGROUP . . . . . . . . . . . . 154CURRENT DEGREE . . . . . . . . 155CURRENT EXPLAIN MODE . . . . . 156CURRENT EXPLAIN SNAPSHOT . . . 157CURRENT MAINTAINED TABLE TYPESFOR OPTIMIZATION . . . . . . . 158CURRENT PATH . . . . . . . . . 159CURRENT QUERY OPTIMIZATION . . 160CURRENT REFRESH AGE. . . . . . 161CURRENT SCHEMA . . . . . . . 162CURRENT SERVER . . . . . . . . 163CURRENT TIME . . . . . . . . . 164CURRENT TIMESTAMP . . . . . . 165CURRENT TIMEZONE . . . . . . . 166USER . . . . . . . . . . . . . 167
Functions . . . . . . . . . . . . 168External, SQL, and sourced user-definedfunctions. . . . . . . . . . . . 168Scalar, column, row, and tableuser-defined functions . . . . . . . 168Function signatures . . . . . . . . 169Function resolution . . . . . . . . 170Function invocation . . . . . . . . 174Conservative binding semantics . . . . 175
Methods . . . . . . . . . . . . . 178External and SQL user-defined methods 178Method signatures . . . . . . . . 179Method resolution . . . . . . . . 180Method invocation . . . . . . . . 183
Dynamic dispatch of methods . . . . 184Expressions . . . . . . . . . . . . 187
Expressions without operators . . . . 188Expressions with the concatenationoperator . . . . . . . . . . . . 188Expressions with arithmetic operators . . 191Two-integer operands . . . . . . . 192Integer and decimal operands. . . . . 193Two-decimal operands . . . . . . . 193Decimal arithmetic in SQL . . . . . . 193Floating-point operands. . . . . . . 194User-defined types as operands . . . . 194Scalar fullselect . . . . . . . . . 194Datetime operations and durations . . . 194Datetime arithmetic in SQL . . . . . 196Precedence of operations . . . . . . 200CASE expressions. . . . . . . . . 201CAST specifications . . . . . . . . 203Dereference operations . . . . . . . 206OLAP functions . . . . . . . . . 207XML functions . . . . . . . . . . 214Method invocation . . . . . . . . 218Subtype treatment . . . . . . . . 219Sequence reference . . . . . . . . 220
Predicates . . . . . . . . . . . . 225Predicates . . . . . . . . . . . 225Search conditions . . . . . . . . . 226Basic predicate . . . . . . . . . . 229Quantified predicate . . . . . . . . 230BETWEEN predicate . . . . . . . . 233EXISTS predicate . . . . . . . . . 234IN predicate . . . . . . . . . . 235LIKE predicate . . . . . . . . . . 238NULL predicate . . . . . . . . . 243TYPE predicate . . . . . . . . . 244
Chapter 3. Functions . . . . . . . . 247Functions overview . . . . . . . . . 247Aggregate functions . . . . . . . . . 269AVG . . . . . . . . . . . . . . 270CORRELATION . . . . . . . . . . 272COUNT . . . . . . . . . . . . . 273COUNT_BIG . . . . . . . . . . . 275COVARIANCE. . . . . . . . . . . 277GROUPING . . . . . . . . . . . 278MAX . . . . . . . . . . . . . . 280MIN . . . . . . . . . . . . . . 282Regression functions . . . . . . . . . 284STDDEV . . . . . . . . . . . . . 288SUM . . . . . . . . . . . . . . 289
iv SQL Reference, Volume 1
VARIANCE . . . . . . . . . . . . 290Scalar functions . . . . . . . . . . 291ABS or ABSVAL . . . . . . . . . . 292ACOS. . . . . . . . . . . . . . 293ASCII . . . . . . . . . . . . . . 294ASIN . . . . . . . . . . . . . . 295ATAN. . . . . . . . . . . . . . 296ATAN2 . . . . . . . . . . . . . 297ATANH . . . . . . . . . . . . . 298BIGINT . . . . . . . . . . . . . 299BLOB . . . . . . . . . . . . . . 301CEILING or CEIL . . . . . . . . . . 302CHAR . . . . . . . . . . . . . 303CHR . . . . . . . . . . . . . . 309CLOB . . . . . . . . . . . . . . 310COALESCE . . . . . . . . . . . . 311CONCAT . . . . . . . . . . . . 312COS . . . . . . . . . . . . . . 313COSH. . . . . . . . . . . . . . 314COT . . . . . . . . . . . . . . 315DATE . . . . . . . . . . . . . . 316DAY . . . . . . . . . . . . . . 318DAYNAME . . . . . . . . . . . . 319DAYOFWEEK . . . . . . . . . . . 320DAYOFWEEK_ISO . . . . . . . . . 321DAYOFYEAR . . . . . . . . . . . 322DAYS . . . . . . . . . . . . . . 323DBCLOB. . . . . . . . . . . . . 324DBPARTITIONNUM . . . . . . . . . 325DECIMAL . . . . . . . . . . . . 330DECRYPT_BIN and DECRYPT_CHAR . . . 332DEGREES . . . . . . . . . . . . 334DEREF . . . . . . . . . . . . . 335DIFFERENCE . . . . . . . . . . . 336DIGITS . . . . . . . . . . . . . 337DLCOMMENT. . . . . . . . . . . 338DLLINKTYPE . . . . . . . . . . . 339DLNEWCOPY . . . . . . . . . . . 340DLPREVIOUSCOPY . . . . . . . . . 343DLREPLACECONTENT . . . . . . . 345DLURLCOMPLETE . . . . . . . . . 347DLURLCOMPLETEONLY . . . . . . . 348DLURLCOMPLETEWRITE. . . . . . . 349DLURLPATH . . . . . . . . . . . 350DLURLPATHONLY . . . . . . . . . 351DLURLPATHWRITE . . . . . . . . . 352DLURLSCHEME . . . . . . . . . . 353DLURLSERVER . . . . . . . . . . 354DLVALUE . . . . . . . . . . . . 355DOUBLE. . . . . . . . . . . . . 357
ENCRYPT . . . . . . . . . . . . 359EVENT_MON_STATE . . . . . . . . 362EXP . . . . . . . . . . . . . . 363FLOAT . . . . . . . . . . . . . 364FLOOR . . . . . . . . . . . . . 365GETHINT . . . . . . . . . . . . 366GENERATE_UNIQUE . . . . . . . . 367GRAPHIC . . . . . . . . . . . . 369HASHEDVALUE . . . . . . . . . . 371HEX . . . . . . . . . . . . . . 373HOUR . . . . . . . . . . . . . 375IDENTITY_VAL_LOCAL . . . . . . . 376INSERT . . . . . . . . . . . . . 382INTEGER . . . . . . . . . . . . 384JULIAN_DAY . . . . . . . . . . . 386LCASE or LOWER . . . . . . . . . 387LCASE (SYSFUN schema) . . . . . . . 388LEFT . . . . . . . . . . . . . . 389LENGTH . . . . . . . . . . . . 390LN. . . . . . . . . . . . . . . 392LOCATE . . . . . . . . . . . . . 393LOG . . . . . . . . . . . . . . 394LOG10 . . . . . . . . . . . . . 395LONG_VARCHAR . . . . . . . . . 396LONG_VARGRAPHIC . . . . . . . . 397LTRIM . . . . . . . . . . . . . 398LTRIM (SYSFUN schema) . . . . . . . 400MICROSECOND . . . . . . . . . . 401MIDNIGHT_SECONDS . . . . . . . . 402MINUTE. . . . . . . . . . . . . 403MOD . . . . . . . . . . . . . . 404MONTH . . . . . . . . . . . . . 405MONTHNAME . . . . . . . . . . 406MQPUBLISH . . . . . . . . . . . 407MQREAD . . . . . . . . . . . . 410MQREADCLOB . . . . . . . . . . 412MQRECEIVE . . . . . . . . . . . 414MQRECEIVECLOB . . . . . . . . . 416MQSEND . . . . . . . . . . . . 418MQSUBSCRIBE . . . . . . . . . . 420MQUNSUBSCRIBE . . . . . . . . . 422MULTIPLY_ALT . . . . . . . . . . 424NULLIF . . . . . . . . . . . . . 426POSSTR . . . . . . . . . . . . . 427POWER . . . . . . . . . . . . . 429QUARTER . . . . . . . . . . . . 430RADIANS . . . . . . . . . . . . 431RAISE_ERROR. . . . . . . . . . . 432RAND . . . . . . . . . . . . . 434REAL . . . . . . . . . . . . . . 435
Contents v
REC2XML . . . . . . . . . . . . 436REPEAT . . . . . . . . . . . . . 441REPLACE . . . . . . . . . . . . 442RIGHT . . . . . . . . . . . . . 443ROUND . . . . . . . . . . . . . 444RTRIM . . . . . . . . . . . . . 446RTRIM (SYSFUN schema) . . . . . . . 447SECOND . . . . . . . . . . . . 448SIGN . . . . . . . . . . . . . . 449SIN . . . . . . . . . . . . . . 450SINH . . . . . . . . . . . . . . 451SMALLINT . . . . . . . . . . . . 452SOUNDEX . . . . . . . . . . . . 453SPACE . . . . . . . . . . . . . 454SQRT . . . . . . . . . . . . . . 455SUBSTR . . . . . . . . . . . . . 456TABLE_NAME. . . . . . . . . . . 460TABLE_SCHEMA . . . . . . . . . . 461TAN . . . . . . . . . . . . . . 463TANH . . . . . . . . . . . . . 464TIME . . . . . . . . . . . . . . 465TIMESTAMP . . . . . . . . . . . 466TIMESTAMP_FORMAT . . . . . . . . 468TIMESTAMP_ISO . . . . . . . . . . 470TIMESTAMPDIFF. . . . . . . . . . 471TO_CHAR . . . . . . . . . . . . 473TO_DATE . . . . . . . . . . . . 474TRANSLATE . . . . . . . . . . . 475TRUNCATE or TRUNC . . . . . . . . 478TYPE_ID. . . . . . . . . . . . . 480TYPE_NAME . . . . . . . . . . . 481TYPE_SCHEMA . . . . . . . . . . 482UCASE or UPPER . . . . . . . . . 483VALUE . . . . . . . . . . . . . 484VARCHAR . . . . . . . . . . . . 485VARCHAR_FORMAT . . . . . . . . 487VARGRAPHIC. . . . . . . . . . . 489WEEK . . . . . . . . . . . . . 491WEEK_ISO . . . . . . . . . . . . 492YEAR . . . . . . . . . . . . . . 493Table functions. . . . . . . . . . . 494MQREADALL . . . . . . . . . . . 495MQREADALLCLOB . . . . . . . . . 497MQRECEIVEALL . . . . . . . . . . 499MQRECEIVEALLCLOB . . . . . . . . 502SNAPSHOT_AGENT . . . . . . . . 505SNAPSHOT_APPL . . . . . . . . . 506SNAPSHOT_APPL_INFO . . . . . . . 510SNAPSHOT_BP . . . . . . . . . . 512SNAPSHOT_CONTAINER. . . . . . . 514
SNAPSHOT_DATABASE . . . . . . . 516SNAPSHOT_DBM . . . . . . . . . 521SNAPSHOT_DYN_SQL . . . . . . . . 523SNAPSHOT_FCM . . . . . . . . . 525SNAPSHOT_FCMPARTITION . . . . . 526SNAPSHOT_LOCK . . . . . . . . . 527SNAPSHOT_LOCKWAIT . . . . . . . 529SNAPSHOT_QUIESCERS . . . . . . . 531SNAPSHOT_RANGES . . . . . . . . 532SNAPSHOT_STATEMENT . . . . . . . 533SNAPSHOT_SUBSECT . . . . . . . . 535SNAPSHOT_SWITCHES . . . . . . . 537SNAPSHOT_TABLE . . . . . . . . . 538SNAPSHOT_TBS . . . . . . . . . . 540SNAPSHOT_TBS_CFG . . . . . . . . 542SQLCACHE_SNAPSHOT . . . . . . . 544Procedures . . . . . . . . . . . . 545GET_ROUTINE_SAR . . . . . . . . 546PUT_ROUTINE_SAR . . . . . . . . 548User-defined functions . . . . . . . . 550
Chapter 4. Queries . . . . . . . . . 553SQL queries. . . . . . . . . . . . 553Subselect. . . . . . . . . . . . . 554
select-clause. . . . . . . . . . . 555from-clause . . . . . . . . . . . 560table-reference . . . . . . . . . . 561joined-table . . . . . . . . . . . 565where-clause . . . . . . . . . . 568group-by-clause . . . . . . . . . 569having-clause . . . . . . . . . . 576order-by-clause . . . . . . . . . 576fetch-first-clause . . . . . . . . . 579Examples of subselects . . . . . . . 580Examples of joins . . . . . . . . . 583Examples of grouping sets, cube, androllup . . . . . . . . . . . . . 586
Fullselect. . . . . . . . . . . . . 597Examples of a fullselect . . . . . . . 598
Select-statement . . . . . . . . . . 601common-table-expression . . . . . . 601update-clause . . . . . . . . . . 603read-only-clause . . . . . . . . . 604optimize-for-clause . . . . . . . . 605Examples of a select-statement . . . . 605
Appendix A. SQL limits . . . . . . . 607
Appendix B. SQLCA (SQLcommunications area) . . . . . . . 615
vi SQL Reference, Volume 1
SQLCA field descriptions . . . . . . . 615Error reporting. . . . . . . . . . . 619SQLCA usage in partitioned databasesystems . . . . . . . . . . . . . 620
Appendix C. SQLDA (SQL descriptorarea) . . . . . . . . . . . . . . 621SQLDA field descriptions . . . . . . . 621
Fields in the SQLDA header . . . . . 622Fields in an occurrence of a base SQLVAR 623Fields in an occurrence of a secondarySQLVAR . . . . . . . . . . . . 625
Effect of DESCRIBE on the SQLDA . . . . 627SQLTYPE and SQLLEN . . . . . . . . 629
Unrecognized and unsupportedSQLTYPEs . . . . . . . . . . . 631Packed decimal numbers . . . . . . 631SQLLEN field for decimal . . . . . . 632
Appendix D. Catalog views . . . . . . 633‘Road map’ to catalog views . . . . . . 633‘Road map’ to updatable catalog views . . 636System catalog views . . . . . . . . 636SYSIBM.SYSDUMMY1 . . . . . . . . 638SYSCAT.ATTRIBUTES . . . . . . . . 639SYSCAT.BUFFERPOOLDBPARTITIONS . . 641SYSCAT.BUFFERPOOLS . . . . . . . 642SYSCAT.CASTFUNCTIONS . . . . . . 643SYSCAT.CHECKS . . . . . . . . . . 644SYSCAT.COLAUTH . . . . . . . . . 645SYSCAT.COLCHECKS . . . . . . . . 646SYSCAT.COLDIST . . . . . . . . . 647SYSCAT.COLGROUPDIST . . . . . . . 648SYSCAT.COLGROUPDISTCOUNTS. . . . 649SYSCAT.COLGROUPS . . . . . . . . 650SYSCAT.COLOPTIONS . . . . . . . . 651SYSCAT.COLUMNS . . . . . . . . . 652SYSCAT.COLUSE . . . . . . . . . . 657SYSCAT.CONSTDEP . . . . . . . . . 658SYSCAT.DATATYPES . . . . . . . . 659SYSCAT.DBAUTH . . . . . . . . . 661SYSCAT.DBPARTITIONGROUPDEF . . . 663SYSCAT.DBPARTITIONGROUPS . . . . 664SYSCAT.EVENTMONITORS . . . . . . 665SYSCAT.EVENTS . . . . . . . . . . 667SYSCAT.EVENTTABLES . . . . . . . 668SYSCAT.FULLHIERARCHIES . . . . . . 669SYSCAT.FUNCMAPOPTIONS . . . . . 670SYSCAT.FUNCMAPPARMOPTIONS . . . 671SYSCAT.FUNCMAPPINGS. . . . . . . 672
SYSCAT.HIERARCHIES. . . . . . . . 673SYSCAT.INDEXAUTH . . . . . . . . 674SYSCAT.INDEXCOLUSE . . . . . . . 675SYSCAT.INDEXDEP . . . . . . . . . 676SYSCAT.INDEXES . . . . . . . . . 677SYSCAT.INDEXEXPLOITRULES . . . . . 682SYSCAT.INDEXEXTENSIONDEP . . . . 683SYSCAT.INDEXEXTENSIONMETHODS . . 684SYSCAT.INDEXEXTENSIONPARMS . . . 685SYSCAT.INDEXEXTENSIONS. . . . . . 686SYSCAT.INDEXOPTIONS . . . . . . . 687SYSCAT.KEYCOLUSE . . . . . . . . 688SYSCAT.NAMEMAPPINGS . . . . . . 689SYSCAT.PACKAGEAUTH . . . . . . . 690SYSCAT.PACKAGEDEP. . . . . . . . 691SYSCAT.PACKAGES . . . . . . . . . 693SYSCAT.PARTITIONMAPS . . . . . . 699SYSCAT.PASSTHRUAUTH. . . . . . . 700SYSCAT.PREDICATESPECS . . . . . . 701SYSCAT.PROCOPTIONS . . . . . . . 702SYSCAT.PROCPARMOPTIONS . . . . . 703SYSCAT.REFERENCES . . . . . . . . 704SYSCAT.REVTYPEMAPPINGS . . . . . 705SYSCAT.ROUTINEAUTH . . . . . . . 707SYSCAT.ROUTINEDEP . . . . . . . . 708SYSCAT.ROUTINEPARMS . . . . . . . 709SYSCAT.ROUTINES . . . . . . . . . 711SYSCAT.SCHEMAAUTH . . . . . . . 718SYSCAT.SCHEMATA . . . . . . . . 719SYSCAT.SEQUENCEAUTH . . . . . . 720SYSCAT.SEQUENCES . . . . . . . . 721SYSCAT.SERVEROPTIONS. . . . . . . 723SYSCAT.SERVERS. . . . . . . . . . 724SYSCAT.STATEMENTS . . . . . . . . 725SYSCAT.TABAUTH . . . . . . . . . 726SYSCAT.TABCONST . . . . . . . . . 728SYSCAT.TABDEP . . . . . . . . . . 729SYSCAT.TABLES . . . . . . . . . . 730SYSCAT.TABLESPACES . . . . . . . . 735SYSCAT.TABOPTIONS . . . . . . . . 736SYSCAT.TBSPACEAUTH . . . . . . . 737SYSCAT.TRANSFORMS. . . . . . . . 738SYSCAT.TRIGDEP . . . . . . . . . 739SYSCAT.TRIGGERS . . . . . . . . . 740SYSCAT.TYPEMAPPINGS . . . . . . . 741SYSCAT.USEROPTIONS . . . . . . . 743SYSCAT.VIEWS . . . . . . . . . . 744SYSCAT.WRAPOPTIONS . . . . . . . 745SYSCAT.WRAPPERS . . . . . . . . . 746SYSSTAT.COLDIST . . . . . . . . . 747
Contents vii
SYSSTAT.COLUMNS. . . . . . . . . 749SYSSTAT.INDEXES . . . . . . . . . 751SYSSTAT.ROUTINES. . . . . . . . . 755SYSSTAT.TABLES . . . . . . . . . . 757
Appendix E. Federated systems . . . . 759Valid server types in SQL statements . . . 759
CTLIB wrapper . . . . . . . . . 759DBLIB wrapper . . . . . . . . . 759DJXMSSQL3 wrapper . . . . . . . 759DRDA wrapper . . . . . . . . . 759Informix wrapper . . . . . . . . . 761MSSQLODBC3 wrapper . . . . . . 761NET8 wrapper . . . . . . . . . . 761ODBC wrapper . . . . . . . . . 761OLE DB wrapper . . . . . . . . . 761SQLNET wrapper. . . . . . . . . 761
Column options for federated systems . . . 762Function mapping options for federatedsystems . . . . . . . . . . . . . 763Server options for federated systems . . . 764User options for federated systems . . . . 773Wrapper options for federated systems . . 774Default forward data type mappings . . . 775
DB2 for z/OS and OS/390 data sources 776DB2 for iSeries data sources . . . . . 777DB2 Server for VM and VSE data sources 779DB2 for UNIX and Windows data sources 780Informix data sources . . . . . . . 781Oracle SQLNET data sources . . . . . 782Oracle NET8 data sources . . . . . . 783Microsoft SQL Server data sources . . . 785ODBC data sources . . . . . . . . 788Sybase data sources . . . . . . . . 789
Default reverse data type mappings. . . . 791DB2 for z/OS and OS/390 data sources 792DB2 for iSeries data sources . . . . . 793DB2 Server for VM and VSE data sources 795DB2 for UNIX and Windows data sources 796Informix data sources . . . . . . . 797Oracle SQLNET data sources . . . . . 798Oracle NET8 data sources . . . . . . 799Microsoft SQL Server data sources . . . 801Sybase data sources . . . . . . . . 801
Appendix F. The SAMPLE database . . . 803Creating the SAMPLE database . . . . . 803Erasing the SAMPLE database . . . . . 803CL_SCHED table . . . . . . . . . . 803DEPARTMENT table . . . . . . . . . 804
EMPLOYEE table . . . . . . . . . . 806EMP_ACT table . . . . . . . . . . 808EMP_PHOTO table . . . . . . . . . 810EMP_RESUME table . . . . . . . . . 810IN_TRAY table . . . . . . . . . . . 811ORG table . . . . . . . . . . . . 811PROJECT table . . . . . . . . . . . 811SALES table . . . . . . . . . . . 812STAFF table. . . . . . . . . . . . 814STAFFG table (double-byte code pages only) 815Sample files with BLOB and CLOB data type 816
Quintana photo . . . . . . . . . 816Quintana resume . . . . . . . . . 816Nicholls photo . . . . . . . . . . 818Nicholls resume . . . . . . . . . 818Adamson photo . . . . . . . . . 819Adamson resume . . . . . . . . . 819Walker photo . . . . . . . . . . 821Walker resume . . . . . . . . . . 821
Appendix G. Reserved schema namesand reserved words . . . . . . . . 823
Appendix H. Comparison of isolationlevels . . . . . . . . . . . . . 827
Appendix I. Interaction of triggers andconstraints . . . . . . . . . . . 829
Appendix J. Explain tables . . . . . . 833Explain tables . . . . . . . . . . . 833EXPLAIN_ARGUMENT table . . . . . . 834EXPLAIN_INSTANCE table . . . . . . 838EXPLAIN_OBJECT table . . . . . . . 841EXPLAIN_OPERATOR table . . . . . . 844EXPLAIN_PREDICATE table . . . . . . 846EXPLAIN_STATEMENT table . . . . . . 848EXPLAIN_STREAM table . . . . . . . 851ADVISE_INDEX table . . . . . . . . 853ADVISE_WORKLOAD table . . . . . . 856
Appendix K. Explain register values. . . 857
Appendix L. Recursion example: bill ofmaterials . . . . . . . . . . . . 861Example 1: Single level explosion . . . . 861Example 2: Summarized explosion . . . . 863Example 3: Controlling depth . . . . . . 864
viii SQL Reference, Volume 1
Appendix M. Exception tables . . . . . 867Rules for creating an exception table . . . 867Handling rows in an exception table . . . 869Querying exception tables . . . . . . . 870
Appendix N. SQL statements allowed inroutines . . . . . . . . . . . . 873
Appendix O. CALL invoked from acompiled statement . . . . . . . . 877
Appendix P. Japanese andtraditional-Chinese extended UNIX code(EUC) considerations . . . . . . . . 883Language elements . . . . . . . . . 883
Characters . . . . . . . . . . . 883Tokens . . . . . . . . . . . . 883Identifiers . . . . . . . . . . . 883Data types . . . . . . . . . . . 884Constants . . . . . . . . . . . 886Functions . . . . . . . . . . . 886Expressions . . . . . . . . . . . 887Predicates . . . . . . . . . . . 887
Functions . . . . . . . . . . . . 888LENGTH . . . . . . . . . . . 888SUBSTR . . . . . . . . . . . . 888TRANSLATE . . . . . . . . . . 888VARGRAPHIC. . . . . . . . . . 889
Statements . . . . . . . . . . . . 889CONNECT . . . . . . . . . . . 889PREPARE . . . . . . . . . . . 889
Appendix Q. Backus-Naur form (BNF)specifications for DATALINKs . . . . . 891
Appendix R. DB2 Universal Databasetechnical information . . . . . . . . 895Overview of DB2 Universal Databasetechnical information . . . . . . . . 895
Categories of DB2 technical information 896Printing DB2 books from PDF files . . . . 903Ordering printed DB2 books . . . . . . 904Accessing online help . . . . . . . . 904Finding topics by accessing the DB2Information Center from a browser . . . . 906Finding product information by accessingthe DB2 Information Center from theadministration tools . . . . . . . . . 908Viewing technical documentation onlinedirectly from the DB2 HTML DocumentationCD. . . . . . . . . . . . . . . 909Updating the HTML documentation installedon your machine . . . . . . . . . . 910Copying files from the DB2 HTMLDocumentation CD to a Web Server. . . . 912Troubleshooting DB2 documentation searchwith Netscape 4.x . . . . . . . . . . 912Searching the DB2 documentation . . . . 913Online DB2 troubleshooting information . . 914Accessibility . . . . . . . . . . . 915
Keyboard Input and Navigation . . . . 915Accessible Display . . . . . . . . 916Alternative Alert Cues . . . . . . . 916Compatibility with Assistive Technologies 916Accessible Documentation . . . . . . 916
DB2 tutorials . . . . . . . . . . . 916DB2 Information Center for topics . . . . 917
Appendix S. Notices . . . . . . . . 919Trademarks . . . . . . . . . . . . 922
Index . . . . . . . . . . . . . 925
Contacting IBM . . . . . . . . . . 945Product information . . . . . . . . . 945
Contents ix
x SQL Reference, Volume 1
About this book
The SQL Reference in its two volumes defines the SQL language used by DB2Universal Database Version 8, and includes:v Information about relational database concepts, language elements,
functions, and the forms of queries (Volume 1).v Information about the syntax and semantics of SQL statements (Volume 2).
Who should use this book
This book is intended for anyone who wants to use the Structured QueryLanguage (SQL) to access a database. It is primarily for programmers anddatabase administrators, but it can also be used by those who accessdatabases through the command line processor (CLP).
This book is a reference rather than a tutorial. It assumes that you will bewriting application programs and therefore presents the full functions of thedatabase manager.
How this book is structured
This book contains information about the following major topics:v Chapter 1, “Concepts” on page 1 discusses the basic concepts of relational
databases and SQL.v Chapter 2, “Language elements” on page 61 describes the basic syntax of
SQL and the language elements that are common to many SQL statements.v Chapter 3, “Functions” on page 247 contains syntax diagrams, semantic
descriptions, rules, and usage examples of SQL column and scalarfunctions.
v Chapter 4, “Queries” on page 553 describes the various forms of a query.v Appendix A, “SQL limits” on page 607 lists SQL limitations.v Appendix B, “SQLCA (SQL communications area)” on page 615 describes
the SQLCA structure.v Appendix C, “SQLDA (SQL descriptor area)” on page 621 describes the
SQLDA structure.v Appendix D, “Catalog views” on page 633 describes the database catalog
views.v Appendix E, “Federated systems” on page 759 describes options and type
mappings for Federated Systems.
© Copyright IBM Corp. 1993 - 2002 xi
v Appendix F, “The SAMPLE database” on page 803 describes the sampletables used in examples.
v Appendix G, “Reserved schema names and reserved words” on page 823contains the reserved schema names and the reserved words for the IBMSQL and ISO/ANS SQL99 standards.
v Appendix H, “Comparison of isolation levels” on page 827 contains asummary of the isolation levels.
v Appendix I, “Interaction of triggers and constraints” on page 829 discussesthe interaction of triggers and referential constraints.
v Appendix J, “Explain tables” on page 833 describes the Explain tables.v Appendix K, “Explain register values” on page 857 describes the interaction
of the CURRENT EXPLAIN MODE and CURRENT EXPLAIN SNAPSHOTspecial register values with each other and with the PREP and BINDcommands.
v Appendix L, “Recursion example: bill of materials” on page 861 contains anexample of a recursive query.
v Appendix M, “Exception tables” on page 867 contains information aboutuser-created tables that are used with the SET INTEGRITY statement.
v Appendix N, “SQL statements allowed in routines” on page 873 lists theSQL statements that are allowed to execute in routines with different SQLdata access contexts.
v Appendix O, “CALL invoked from a compiled statement” on page 877describes the CALL statement that can be invoked from a compiledstatement.
v Appendix P, “Japanese and traditional-Chinese extended UNIX code (EUC)considerations” on page 883 lists considerations when using extended UNIXcode (EUC) character sets.
v Appendix Q, “Backus-Naur form (BNF) specifications for DATALINKs” onpage 891 contains the Backus-Naur form (BNF) specifications forDATALINKs.
A brief overview of Volume 2The second volume of the SQL Reference contains information about thesyntax and semantics of SQL statements. The specific chapters in that volumeare briefly described here:v “SQL statements” contains syntax diagrams, semantic descriptions, rules,
and examples of all SQL statements.v “SQL control statements” contains syntax diagrams, semantic descriptions,
rules, and examples of SQL procedure statements.
How this book is structured
xii SQL Reference, Volume 1
How to read the syntax diagrams
Throughout this book, syntax is described using the structure defined asfollows:
Read the syntax diagrams from left to right and top to bottom, following thepath of the line.
The ��─── symbol indicates the beginning of a syntax diagram.
The ───� symbol indicates that the syntax is continued on the next line.
The �─── symbol indicates that the syntax is continued from the previous line.
The ──�� symbol indicates the end of a syntax diagram.
Syntax fragments start with the ├─── symbol and end with the ───┤ symbol.
Required items appear on the horizontal line (the main path).
�� required_item ��
Optional items appear below the main path.
�� required_itemoptional_item
��
If an optional item appears above the main path, that item has no effect onexecution, and is used only for readability.
�� required_itemoptional_item
��
If you can choose from two or more items, they appear in a stack.
If you must choose one of the items, one item of the stack appears on themain path.
�� required_item required_choice1required_choice2
��
If choosing one of the items is optional, the entire stack appears below themain path.
How to read the syntax diagrams
About this book xiii
�� required_itemoptional_choice1optional_choice2
��
If one of the items is the default, it will appear above the main path, and theremaining choices will be shown below.
�� required_itemdefault_choice
optional_choiceoptional_choice
��
An arrow returning to the left, above the main line, indicates an item that canbe repeated. In this case, repeated items must be separated by one or moreblanks.
�� required_item � repeatable_item ��
If the repeat arrow contains a comma, you must separate repeated items witha comma.
�� required_item �
,
repeatable_item ��
A repeat arrow above a stack indicates that you can make more than onechoice from the stacked items or repeat a single choice.
Keywords appear in uppercase (for example, FROM). They must be spelledexactly as shown. Variables appear in lowercase (for example, column-name).They represent user-supplied names or values in the syntax.
If punctuation marks, parentheses, arithmetic operators, or other such symbolsare shown, you must enter them as part of the syntax.
Sometimes a single variable represents a larger fragment of the syntax. Forexample, in the following diagram, the variable parameter-block representsthe whole syntax fragment that is labeled parameter-block:
�� required_item parameter-block ��
How to read the syntax diagrams
xiv SQL Reference, Volume 1
parameter-block:
parameter1parameter2 parameter3
parameter4
Adjacent segments occurring between “large bullets” (*) may be specified inany sequence.
�� required_item item1 * item2 * item3 * item4 ��
The above diagram shows that item2 and item3 may be specified in eitherorder. Both of the following are valid:
required_item item1 item2 item3 item4required_item item1 item3 item2 item4
Common syntax elements
The following sections describe a number of syntax fragments that are used insyntax diagrams. The fragments are referenced as follows:
�� fragment ��
Function designatorA function designator uniquely identifies a single function. Functiondesignators typically appear in DDL statements for functions (such as DROPor ALTER).
Syntax:
function-designator:
�
FUNCTION function-name( )
,
( data-type )SPECIFIC FUNCTION specific-name
Description:
FUNCTION function-nameIdentifies a particular function, and is valid only if there is exactly onefunction instance with the name function-name in the schema. Theidentified function can have any number of parameters defined for it. Indynamic SQL statements, the CURRENT SCHEMA special register is usedas a qualifier for an unqualified object name. In static SQL statements, the
How to read the syntax diagrams
About this book xv
QUALIFIER precompile/bind option implicitly specifies the qualifier forunqualified object names. If no function by this name exists in the namedor implied schema, an error (SQLSTATE 42704) is raised. If there is morethan one instance of the function in the named or implied schema, anerror (SQLSTATE 42725) is raised.
FUNCTION function-name (data-type,...)Provides the function signature, which uniquely identifies the function.The function resolution algorithm is not used.
function-nameSpecifies the name of the function. In dynamic SQL statements, theCURRENT SCHEMA special register is used as a qualifier for anunqualified object name. In static SQL statements, the QUALIFIERprecompile/bind option implicitly specifies the qualifier forunqualified object names.
(data-type,...)Values must match the data types that were specified (in thecorresponding position) on the CREATE FUNCTION statement. Thenumber of data types, and the logical concatenation of the data types,is used to identify the specific function instance.
If a data type is unqualified, the type name is resolved by searchingthe schemas on the SQL path. This also applies to data type namesspecified for a REFERENCE type.
It is not necessary to specify the length, precision, or scale for theparameterized data types. Instead, an empty set of parentheses can becoded to indicate that these attributes are to be ignored when lookingfor a data type match.
FLOAT() cannot be used (SQLSTATE 42601), because the parametervalue indicates different data types (REAL or DOUBLE).
If length, precision, or scale is coded, the value must exactly matchthat specified in the CREATE FUNCTION statement.
A type of FLOAT(n) does not need to match the defined value for n,because 0 < n < 25 means REAL, and 24 < n < 54 means DOUBLE.Matching occurs on the basis of whether the type is REAL orDOUBLE.
If no function with the specified signature exists in the named orimplied schema, an error (SQLSTATE 42883) is raised.
SPECIFIC FUNCTION specific-nameIdentifies a particular user-defined function, using the name that isspecified or defaulted to at function creation time. In dynamic SQLstatements, the CURRENT SCHEMA special register is used as a qualifierfor an unqualified object name. In static SQL statements, the QUALIFIER
Function designator
xvi SQL Reference, Volume 1
precompile/bind option implicitly specifies the qualifier for unqualifiedobject names. The specific-name must identify a specific function instancein the named or implied schema; otherwise, an error (SQLSTATE 42704) israised.
Method designatorA method designator uniquely identifies a single method. Method designatorstypically appear in DDL statements for methods (such as DROP or ALTER).
Syntax:
method-designator:
�
METHOD method-name FOR type-name( )
,
( data-type )SPECIFIC METHOD specific-name
Description:
METHOD method-nameIdentifies a particular method, and is valid only if there is exactly onemethod instance with the name method-name for the type type-name. Theidentified method can have any number of parameters defined for it. If nomethod by this name exists for the type, an error (SQLSTATE 42704) israised. If there is more than one instance of the method for the type, anerror (SQLSTATE 42725) is raised.
METHOD method-name (data-type,...)Provides the method signature, which uniquely identifies the method. Themethod resolution algorithm is not used.
method-nameSpecifies the name of the method for the type type-name.
(data-type,...)Values must match the data types that were specified (in thecorresponding position) on the CREATE TYPE statement. The numberof data types, and the logical concatenation of the data types, is usedto identify the specific method instance.
If a data type is unqualified, the type name is resolved by searchingthe schemas on the SQL path. This also applies to data type namesspecified for a REFERENCE type.
It is not necessary to specify the length, precision, or scale for theparameterized data types. Instead, an empty set of parentheses can becoded to indicate that these attributes are to be ignored when lookingfor a data type match.
Function designator
About this book xvii
FLOAT() cannot be used (SQLSTATE 42601), because the parametervalue indicates different data types (REAL or DOUBLE).
If length, precision, or scale is coded, the value must exactly matchthat specified in the CREATE TYPE statement.
A type of FLOAT(n) does not need to match the defined value for n,because 0 < n < 25 means REAL, and 24 < n < 54 means DOUBLE.Matching occurs on the basis of whether the type is REAL orDOUBLE.
If no method with the specified signature exists for the type in thenamed or implied schema, an error (SQLSTATE 42883) is raised.
FOR type-nameNames the type with which the specified method is to be associated.The name must identify a type already described in the catalog(SQLSTATE 42704). In dynamic SQL statements, the CURRENTSCHEMA special register is used as a qualifier for an unqualifiedobject name. In static SQL statements, the QUALIFIERprecompile/bind option implicitly specifies the qualifier forunqualified object names.
SPECIFIC METHOD specific-nameIdentifies a particular method, using the name that is specified ordefaulted to at method creation time. In dynamic SQL statements, theCURRENT SCHEMA special register is used as a qualifier for anunqualified object name. In static SQL statements, the QUALIFIERprecompile/bind option implicitly specifies the qualifier for unqualifiedobject names. The specific-name must identify a specific method instance inthe named or implied schema; otherwise, an error (SQLSTATE 42704) israised.
Procedure designatorA procedure designator uniquely identifies a single stored procedure.Procedure designators typically appear in DDL statements for procedures(such as DROP or ALTER).
Syntax:
procedure-designator:
�
PROCEDURE procedure-name( )
,
( data-type )SPECIFIC PROCEDURE specific-name
Description:
Method designator
xviii SQL Reference, Volume 1
PROCEDURE procedure-nameIdentifies a particular procedure, and is valid only if there is exactly oneprocedure instance with the name procedure-name in the schema. Theidentified procedure can have any number of parameters defined for it. Indynamic SQL statements, the CURRENT SCHEMA special register is usedas a qualifier for an unqualified object name. In static SQL statements, theQUALIFIER precompile/bind option implicitly specifies the qualifier forunqualified object names. If no procedure by this name exists in thenamed or implied schema, an error (SQLSTATE 42704) is raised. If there ismore than one instance of the procedure in the named or implied schema,an error (SQLSTATE 42725) is raised.
PROCEDURE procedure-name (data-type,...)Provides the procedure signature, which uniquely identifies theprocedure. The procedure resolution algorithm is not used.
procedure-nameSpecifies the name of the procedure. In dynamic SQL statements, theCURRENT SCHEMA special register is used as a qualifier for anunqualified object name. In static SQL statements, the QUALIFIERprecompile/bind option implicitly specifies the qualifier forunqualified object names.
(data-type,...)Values must match the data types that were specified (in thecorresponding position) on the CREATE PROCEDURE statement. Thenumber of data types, and the logical concatenation of the data types,is used to identify the specific procedure instance.
If a data type is unqualified, the type name is resolved by searchingthe schemas on the SQL path. This also applies to data type namesspecified for a REFERENCE type.
It is not necessary to specify the length, precision, or scale for theparameterized data types. Instead, an empty set of parentheses can becoded to indicate that these attributes are to be ignored when lookingfor a data type match.
FLOAT() cannot be used (SQLSTATE 42601), because the parametervalue indicates different data types (REAL or DOUBLE).
If length, precision, or scale is coded, the value must exactly matchthat specified in the CREATE PROCEDURE statement.
A type of FLOAT(n) does not need to match the defined value for n,because 0 < n < 25 means REAL, and 24 < n < 54 means DOUBLE.Matching occurs on the basis of whether the type is REAL orDOUBLE.
Procedure designator
About this book xix
If no procedure with the specified signature exists in the named orimplied schema, an error (SQLSTATE 42883) is raised.
SPECIFIC PROCEDURE specific-nameIdentifies a particular procedure, using the name that is specified ordefaulted to at procedure creation time. In dynamic SQL statements, theCURRENT SCHEMA special register is used as a qualifier for anunqualified object name. In static SQL statements, the QUALIFIERprecompile/bind option implicitly specifies the qualifier for unqualifiedobject names. The specific-name must identify a specific procedure instancein the named or implied schema; otherwise, an error (SQLSTATE 42704) israised.
Conventions used in this manual
This section specifies some conventions which are used consistentlythroughout this manual.
Error conditionsAn error condition is indicated within the text of the manual by listing theSQLSTATE associated with the error in parentheses. For example:
A duplicate signature raises an SQL error (SQLSTATE 42723).
Highlighting conventionsThe following conventions are used in this book.
Bold Indicates commands, keywords, and other items whose names arepredefined by the system.
Italics Indicates one of the following:
v Names or values (variables) that must be supplied by the user.
v General emphasis.
v The introduction of a new term.
v A reference to another source of information.
Monospace Indicates one of the following:
v Files and directories.
v Information that you are instructed to type at a command prompt orin a window.
v Examples of specific data values.
v Examples of text similar to what may be displayed by the system.
v Examples of system messages.
Procedure designator
xx SQL Reference, Volume 1
Related documentation
The following publications may prove useful in preparing applications:v Administration Guide
– Contains information required to design, implement, and maintain adatabase to be accessed either locally or in a client/server environment.
v Application Development Guide
– Discusses the application development process and how to code,compile, and execute application programs that use embedded SQL andAPIs to access the database.
v DB2 Universal Database for iSeries SQL Reference
– This book defines Structured Query Language (SQL) as supported byDB2 Query Manager and SQL Development Kit on iSeries (AS/400). Itcontains reference information for the tasks of system administration,database administration, application programming, and operation. Thismanual includes syntax, usage notes, keywords, and examples for eachof the SQL statements used on iSeries (AS/400) systems running DB2.
v DB2 Universal Database for z/OS and OS/390 SQL Reference
– This book defines Structured Query Language (SQL) used in DB2 forz/OS (OS/390). It provides query forms, SQL statements, SQL procedurestatements, DB2 limits, SQLCA, SQLDA, catalog tables, and SQLreserved words for z/OS (OS/390) systems running DB2.
v DB2 Spatial Extender User’s Guide and Reference
– This book discusses how to write applications to create and use ageographic information system (GIS). Creating and using a GIS involvessupplying a database with resources and then querying the data toobtain information such as locations, distances, and distributions withinareas.
v IBM SQL Reference
– This book contains all the common elements of SQL that span IBM’sdatabase products. It provides limits and rules that assist in preparingportable programs using IBM databases. This manual provides a list ofSQL extensions and incompatibilities among the following standards andproducts: SQL92E, XPG4-SQL, IBM-SQL and the IBM relational databaseproducts.
v American National Standard X3.135-1992, Database Language SQL
– Contains the ANSI standard definition of SQL.v ISO/IEC 9075:1992, Database Language SQL
– Contains the 1992 ISO standard definition of SQL.v ISO/IEC 9075-2:1999, Database Language SQL -- Part 2: Foundation
(SQL/Foundation)
– Contains a large portion of the 1999 ISO standard definition of SQL.
Related documentation
About this book xxi
v ISO/IEC 9075-4:1999, Database Language SQL -- Part 4: Persistent StoredModules (SQL/PSM)
– Contains the 1999 ISO standard definition for SQL procedure controlstatements.
v ISO/IEC 9075-5:1999, Database Language SQL -- Part 4: Host Language Bindings(SQL/Bindings)
– Contains the 1999 ISO standard definition for host language bindingsand dynamic SQL.
Related documentation
xxii SQL Reference, Volume 1
Chapter 1. Concepts
This chapter provides a high-level view of concepts that are important tounderstand when using Structured Query Language (SQL). The referencematerial contained in the rest of this manual provides a more detailed view.
Relational databases
A relational database is a database that is treated as a set of tables andmanipulated in accordance with the relational model of data. It contains a setof objects used to store, manage, and access data. Examples of such objects aretables, views, indexes, functions, triggers, and packages.
A partitioned relational database is a relational database whose data ismanaged across multiple partitions (also called nodes). This separation of dataacross partitions is transparent to users of most SQL statements. However,some data definition language (DDL) statements take partition informationinto consideration (for example, CREATE DATABASE PARTITION GROUP).(Data definition language is the subset of SQL statements used to describedata relationships in a database.)
A federated database is a relational database whose data is stored in multipledata sources (such as separate relational databases). The data appears as if itwere all in a single large database and can be accessed through traditionalSQL queries. Changes to the data can be explicitly directed to the appropriatedata source.
Structured Query Language (SQL)
SQL is a standardized language for defining and manipulating data in arelational database. In accordance with the relational model of data, thedatabase is treated as a set of tables, relationships are represented by values intables, and data is retrieved by specifying a result table that can be derivedfrom one or more base tables.
SQL statements are executed by a database manager. One of the functions ofthe database manager is to transform the specification of a result table into asequence of internal operations that optimize data retrieval. Thetransformation occurs in two phases: preparation and binding.
© Copyright IBM Corp. 1993 - 2002 1
All executable SQL statements must be prepared before they can be executed.The result of preparation is the executable or operational form of thestatement. The method of preparing an SQL statement and the persistence ofits operational form distinguish static SQL from dynamic SQL.
Authorization and privileges
An authorization allows a user or group to perform a general task, such asconnecting to a database, creating tables, or administering a system. A privilegegives a user or group the right to access one specific database object in aspecified way.
The database manager requires that a user be specifically authorized, eitherimplicitly or explicitly, to use each database function needed to perform aspecific task. Explicit authorities or privileges are granted to the user(GRANTEETYPE of U). Implicit authorities or privileges are granted to agroup to which the user belongs (GRANTEETYPE of G). Thus, to create atable, a user must be authorized to create tables; to alter a table, a user mustbe authorized to alter the table; and so on.
Persons with administrative authority have the task of controlling thedatabase manager and are responsible for the safety and integrity of the data.They control who will have access to the database manager and to whatextent each user has access.
The database manager provides two administrative authorities:v SYSADM - system administrator authority
SYSADM(System Administrator)
DBADM(Database Administrator)
Database Users with Privileges
SYSCTRL(System Resource Administrator)
SYSMAINT(System Maintenance Administrator)
Figure 1. Hierarchy of Authorities and Privileges
Structured Query Language (SQL)
2 SQL Reference, Volume 1
SYSADM authority is the highest level of authority and has control over allthe resources created and maintained by the database manager. SYSADMauthority includes all the authorities of DBADM, SYSCTRL, andSYSMAINT, and the authority to grant or revoke DBADM authorities.
v DBADM - database administrator authorityDBADM authority is the administrative authority specific to a singledatabase. This authority includes privileges to create objects, issue databasecommands, and access the data in any of its tables through SQL statements.DBADM authority also includes the authority to grant or revoke CONTROLand individual privileges.
The database manager also provides two system control authorities:v SYSCTRL - system control authority
SYSCTRL authority is the higher level of system control authority andapplies only to operations affecting system resources. It does not allowdirect access to data. This authority includes privileges to create, update, ordrop a database; to stop an instance or a database; and to create or drop atable space.
v SYSMAINT - system maintenance authoritySYSMAINT authority is the second level of system control authority. A userwith SYSMAINT authority can perform maintenance operations on alldatabases associated with an instance. It does not allow direct access todata. This authority includes privileges to update database configurationfiles; to back up a database or a table space; to restore an existing database;and to monitor a database.
Database authorities apply to activities that an administrator has allowed auser to perform within a database; they do not apply to a specific instance ofa database object. For example, a user may be granted the authority to createpackages but not to create tables.
Privileges apply to activities that an administrator or an object owner hasallowed a user to perform on database objects. Users with privileges cancreate objects, strictly defined by the privileges they hold. For example, a usermay have the privilege to create a view on a table but not a trigger on thesame table. Users with privileges have access to the objects they own, and canpass privileges on their own objects to other users through the GRANTstatement.
CONTROL privilege allows a user to access a specific database object, asrequired, and to grant and revoke privileges to and from other users on thatobject. DBADM authority is required to grant CONTROL privilege.
Authorization and privileges
Chapter 1. Concepts 3
Individual privileges and database authorities allow a specific function but donot include the right to grant the same privileges or authorities to other users.The right to grant table, view, or schema privileges to others can be extendedto other users through the WITH GRANT OPTION on the GRANT statement.
Schemas
A schema is a collection of named objects. Schemas provide a logicalclassification of objects in the database. A schema can contain tables, views,nicknames, triggers, functions, packages, and other objects.
A schema is also an object in the database. It is explicitly created using theCREATE SCHEMA statement with the current user recorded as the schemaowner. It can also be implicitly created when another object is created,provided that the user has IMPLICIT_SCHEMA authority.
A schema name is used as the high order part of a two-part object name. If theobject is specifically qualified with a schema name when created, the object isassigned to that schema. If no schema name is specified when the object iscreated, the default schema name is used.
For example, a user with DBADM authority creates a schema called C foruser A:
CREATE SCHEMA C AUTHORIZATION A
User A can then issue the following statement to create a table called X inschema C:
CREATE TABLE C.X (COL1 INT)
Some schema names are reserved. For example, built-in functions belong tothe SYSIBM schema, and the pre-installed user-defined functions belong to theSYSFUN schema.
When a database is created, all users have IMPLICIT_SCHEMA authority. Thisallows any user to create objects in any schema not already in existence. Animplicitly created schema allows any user to create other objects in thisschema.The ability to create aliases, distinct types, functions, and triggers isextended to implicitly created schemas. The default privileges on an implicitlycreated schema provide backward compatibility with previous versions.
If IMPLICIT_SCHEMA authority is revoked from PUBLIC, schemas can beexplicitly created using the CREATE SCHEMA statement, or implicitly createdby users (such as those with DBADM authority) who have been grantedIMPLICIT_SCHEMA authority. Although revoking IMPLICIT_SCHEMA
Authorization and privileges
4 SQL Reference, Volume 1
authority from PUBLIC increases control over the use of schema names, it canresult in authorization errors when existing applications attempt to createobjects.
Schemas also have privileges, allowing the schema owner to control whichusers have the privilege to create, alter, and drop objects in the schema. Aschema owner is initially given all of these privileges on the schema, with theability to grant them to others. An implicitly created schema is owned by thesystem, and all users are initially given the privilege to create objects in such aschema. A user with SYSADM or DBADM authority can change the privilegesheld by users on any schema. Therefore, access to create, alter, and dropobjects in any schema (even one that was implicitly created) can be controlled.
Tables
Tables are logical structures maintained by the database manager. Tables aremade up of columns and rows. The rows are not necessarily ordered within atable (order is determined by the application program). At the intersection ofevery column and row is a specific data item called a value. A column is a setof values of the same type or one of its subtypes. A row is a sequence ofvalues arranged so that the nth value is a value of the nth column of the table.
A base table is created with the CREATE TABLE statement and is used to holdpersistent user data. A result table is a set of rows that the database managerselects or generates from one or more base tables to satisfy a query.
A summary table is a table defined by a query that is also used to determinethe data in the table. Summary tables can be used to improve the performanceof queries. If the database manager determines that a portion of a query canbe resolved using a summary table, the database manager can rewrite thequery to use the summary table. This decision is based on databaseconfiguration settings, such as the CURRENT REFRESH AGE and theCURRENT QUERY OPTIMIZATION special registers.
A table can define the data type of each column separately, or base the typeson the attributes of a user-defined structured type. This is called a typed table.A user-defined structured type may be part of a type hierarchy. A subtypeinherits attributes from its supertype. Similarly, a typed table can be part of atable hierarchy. A subtable inherits columns from its supertable. Note that theterm subtype applies to a user-defined structured type and all user-definedstructured types that are below it in the type hierarchy. A proper subtype of astructured type T is a structured type below T in the type hierarchy. Similarly,the term subtable applies to a typed table and all typed tables that are below itin the table hierarchy. A proper subtable of a table T is a table below T in thetable hierarchy.
Schemas
Chapter 1. Concepts 5
A declared temporary table is created with a DECLARE GLOBAL TEMPORARYTABLE statement and is used to hold temporary data on behalf of a singleapplication. This table is dropped implicitly when the application disconnectsfrom the database.
Views
A view provides a different way of looking at the data in one or more tables; itis a named specification of a result table. The specification is a SELECTstatement that is run whenever the view is referenced in an SQL statement. Aview has columns and rows just like a base table. All views can be used justlike base tables for data retrieval. Whether a view can be used in an insert,update, or delete operation depends on its definition.
You can use views to control access to sensitive data, because views allowmultiple users to see different presentations of the same data. For example,several users may be accessing a table of data about employees. A managersees data about his or her employees but not employees in anotherdepartment. A recruitment officer sees the hire dates of all employees, but nottheir salaries; a financial officer sees the salaries, but not the hire dates. Eachof these users works with a view derived from the base table. Each viewappears to be a table and has its own name.
When the column of a view is directly derived from the column of a basetable, that view column inherits any constraints that apply to the base tablecolumn. For example, if a view includes a foreign key of its base table, insertand update operations using that view are subject to the same referentialconstraints as is the base table. Also, if the base table of a view is a parenttable, delete and update operations using that view are subject to the samerules as are delete and update operations on the base table.
A view can derive the data type of each column from the result table, or basethe types on the attributes of a user-defined structured type. This is called atyped view. Similar to a typed table, a typed view can be part of a viewhierarchy. A subview inherits columns from its superview. The term subviewapplies to a typed view and to all typed views that are below it in the viewhierarchy. A proper subview of a view V is a view below V in the typed viewhierarchy.
A view can become inoperative (for example, if the base table is dropped); ifthis occurs, the view is no longer available for SQL operations.
Tables
6 SQL Reference, Volume 1
Aliases
An alias is an alternative name for a table or a view. It can be used toreference a table or a view if an existing table or view can be referenced. Analias cannot be used in all contexts; for example, it cannot be used in thecheck condition of a check constraint. An alias cannot reference a declaredtemporary table.
Like tables or views, an alias can be created, dropped, and have commentsassociated with it. However, unlike tables, aliases can refer to each other in aprocess called chaining. Aliases are publicly referenced names, so no specialauthority or privilege is required to use them. Access to the table or the viewreferred to by an alias, however, does require the authorization associatedwith these objects.
There are other types of aliases, such as database and network aliases. Aliasescan also be created for nicknames that refer to data tables or views located onfederated systems.
Indexes
An index is an ordered set of pointers to rows in a base table. Each index isbased on the values of data in one or more table columns. An index is anobject that is separate from the data in the table. When an index is created,the database manager builds this object and maintains it automatically.
Indexes are used by the database manager to:v Improve performance. In most cases, access to data is faster with an index.
Although an index cannot be created for a view, an index created for thetable on which a view is based can sometimes improve the performance ofoperations on that view.
v Ensure uniqueness. A table with a unique index cannot have rows withidentical keys.
Keys
A key is a set of columns that can be used to identify or access a particularrow or rows. The key is identified in the description of a table, index, orreferential constraint. The same column can be part of more than one key.
A key that is composed of more than one column is called a composite key. In atable with a composite key, the order of the columns within the composite keyis not constrained by the order of the columns within the table. The value of acomposite key denotes a composite value. Thus, a rule such as “the value of
Aliases
Chapter 1. Concepts 7
the foreign key must be equal to the value of the primary key” means thateach component of the value of the foreign key must be equal to thecorresponding component of the value of the primary key.
A unique key is a key that is constrained so that no two of its values are equal.The columns of a unique key cannot contain null values. The constraint isenforced by the database manager during the execution of any operation thatchanges data values, such as INSERT or UPDATE. The mechanism used toenforce the constraint is called a unique index. Thus, every unique key is a keyof a unique index. Such an index is also said to have the UNIQUE attribute.
A primary key is a special case of a unique key. A table cannot have more thanone primary key.
A foreign key is a key that is specified in the definition of a referentialconstraint.
A partitioning key is a key that is part of the definition of a table in apartitioned database. The partitioning key is used to determine the partitionon which the row of data is stored. If a partitioning key is defined, uniquekeys and primary keys must include the same columns as the partitioningkey, but can have additional columns. A table cannot have more than onepartitioning key.
Constraints
A constraint is a rule that the database manager enforces.
There are three types of constraints:v A unique constraint is a rule that forbids duplicate values in one or more
columns within a table. Unique and primary keys are the supported uniqueconstraints. For example, a unique constraint can be defined on the supplieridentifier in the supplier table to ensure that the same supplier identifier isnot given to two suppliers.
v A referential constraint is a logical rule about values in one or more columnsin one or more tables. For example, a set of tables shares information abouta corporation’s suppliers. Occasionally, a supplier’s name changes. You candefine a referential constraint stating that the ID of the supplier in a tablemust match a supplier ID in the supplier information. This constraintprevents insert, update, or delete operations that would otherwise result inmissing supplier information.
v A table check constraint sets restrictions on data added to a specific table. Forexample, a table check constraint can ensure that the salary level for an
Keys
8 SQL Reference, Volume 1
employee is at least $20,000 whenever salary data is added or updated in atable containing personnel information.
Referential and table check constraints can be turned on or off. It is generallya good idea, for example, to turn off the enforcement of a constraint whenlarge amounts of data are loaded into a database.
Unique constraintsA unique constraint is the rule that the values of a key are valid only if theyare unique within a table. Unique constraints are optional and can be definedin the CREATE TABLE or ALTER TABLE statement using the PRIMARY KEYclause or the UNIQUE clause. The columns specified in a unique constraintmust be defined as NOT NULL. The database manager uses a unique index toenforce the uniqueness of the key during changes to the columns of theunique constraint.
A table can have an arbitrary number of unique constraints, with at most oneunique constraint defined as the primary key. A table cannot have more thanone unique constraint on the same set of columns.
A unique constraint that is referenced by the foreign key of a referentialconstraint is called the parent key.
When a unique constraint is defined in a CREATE TABLE statement, a uniqueindex is automatically created by the database manager and designated as aprimary or unique system-required index.
When a unique constraint is defined in an ALTER TABLE statement and anindex exists on the same columns, that index is designated as unique andsystem-required. If such an index does not exist, the unique index isautomatically created by the database manager and designated as a primaryor unique system-required index.
Note that there is a distinction between defining a unique constraint andcreating a unique index. Although both enforce uniqueness, a unique indexallows nullable columns and generally cannot be used as a parent key.
Referential constraintsReferential integrity is the state of a database in which all values of all foreignkeys are valid. A foreign keyis a column or a set of columns in a table whosevalues are required to match at least one primary key or unique key value ofa row in its parent table. A referential constraint is the rule that the values ofthe foreign key are valid only if one of the following conditions is true:v They appear as values of a parent key.v Some component of the foreign key is null.
Constraints
Chapter 1. Concepts 9
The table containing the parent key is called the parent table of the referentialconstraint, and the table containing the foreign key is said to be a dependent ofthat table.
Referential constraints are optional and can be defined in the CREATE TABLEstatement or the ALTER TABLE statement. Referential constraints are enforcedby the database manager during the execution of INSERT, UPDATE, DELETE,ALTER TABLE, ADD CONSTRAINT, and SET INTEGRITY statements.
Referential constraints with a delete or an update rule of RESTRICT areenforced before all other referential constraints. Referential constraints with adelete or an update rule of NO ACTION behave like RESTRICT in most cases.
Note that referential constraints, check constraints, and triggers can becombined.
Referential integrity rules involve the following concepts and terminology:
Parent keyA primary key or a unique key of a referential constraint.
Parent rowA row that has at least one dependent row.
Parent tableA table that contains the parent key of a referential constraint. A tablecan be a parent in an arbitrary number of referential constraints. Atable that is the parent in a referential constraint can also be thedependent in a referential constraint.
Dependent tableA table that contains at least one referential constraint in its definition.A table can be a dependent in an arbitrary number of referentialconstraints. A table that is the dependent in a referential constraint canalso be the parent in a referential constraint.
Descendent tableA table is a descendent of table T if it is a dependent of T or adescendent of a dependent of T.
Dependent rowA row that has at least one parent row.
Descendent rowA row is a descendent of row r if it is a dependent of r or adescendent of a dependent of r.
Referential cycleA set of referential constraints such that each table in the set is adescendent of itself.
Referential constraints
10 SQL Reference, Volume 1
Self-referencing tableA table that is a parent and a dependent in the same referentialconstraint. The constraint is called a self-referencing constraint.
Self-referencing rowA row that is a parent of itself.
Insert ruleThe insert rule of a referential constraint is that a non-null insert value of theforeign key must match some value of the parent key of the parent table. Thevalue of a composite foreign key is null if any component of the value is null.This rule is implicit when a foreign key is specified.
Update ruleThe update rule of a referential constraint is specified when the referentialconstraint is defined. The choices are NO ACTION and RESTRICT. Theupdate rule applies when a row of the parent or a row of the dependent tableis updated.
In the case of a parent row, when a value in a column of the parent key isupdated, the following rules apply:v If any row in the dependent table matches the original value of the key, the
update is rejected when the update rule is RESTRICT.v If any row in the dependent table does not have a corresponding parent
key when the update statement is completed (excluding AFTER triggers),the update is rejected when the update rule is NO ACTION.
In the case of a dependent row, the NO ACTION update rule is implicit whena foreign key is specified. NO ACTION means that a non-null update value ofa foreign key must match some value of the parent key of the parent tablewhen the update statement is completed.
The value of a composite foreign key is null if any component of the value isnull.
Delete ruleThe delete rule of a referential constraint is specified when the referentialconstraint is defined. The choices are NO ACTION, RESTRICT, CASCADE, orSET NULL. SET NULL can be specified only if some column of the foreignkey allows null values.
The delete rule of a referential constraint applies when a row of the parenttable is deleted. More precisely, the rule applies when a row of the parenttable is the object of a delete or propagated delete operation (defined below),and that row has dependents in the dependent table of the referentialconstraint. Consider an example where P is the parent table, D is the
Referential constraints
Chapter 1. Concepts 11
dependent table, and p is a parent row that is the object of a delete orpropagated delete operation. The delete rule works as follows:v With RESTRICT or NO ACTION, an error occurs and no rows are deleted.v With CASCADE, the delete operation is propagated to the dependents of p
in table D.v With SET NULL, each nullable column of the foreign key of each
dependent of p in table 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 deleteoperation. Thus, a row cannot be deleted if it has dependents in a referentialconstraint with a delete rule of RESTRICT or NO ACTION, or the deletioncascades to any of its descendents that are dependents in a referentialconstraint with the delete rule of RESTRICT or NO ACTION.
The deletion of a row from parent table P involves other tables and can affectrows of these tables:v If table D is a dependent of P and the delete rule is RESTRICT or NO
ACTION, then D is involved in the operation but is not affected by theoperation.
v If D is a dependent of P and the delete rule is SET NULL, then D isinvolved in the operation, and rows of D can be updated during theoperation.
v If D is a dependent of P and the delete rule is CASCADE, then D isinvolved in the operation and rows of D can be deleted during theoperation.If rows of D are deleted, then the delete operation on P is said to bepropagated to D. If D is also a parent table, then the actions described inthis list apply, in turn, to the dependents of D.
Any table that can be involved in a delete operation on P is said to bedelete-connected to P. Thus, a table is delete-connected to table P if it is adependent of P, or a dependent of a table to which delete operations from Pcascade.
Table check constraintsA table check constraint is a rule that specifies the values allowed in one ormore columns of every row in a table. A constraint is optional, and can bedefined using the CREATE TABLE or the ALTER TABLE statement. Specifyingtable check constraints is done through a restricted form of a search condition.One of the restrictions is that a column name in a table check constraint ontable T must identify a column of table T.
Delete rule
12 SQL Reference, Volume 1
A table can have an arbitrary number of table check constraints. A table checkconstraint is enforced by applying its search condition to each row that isinserted or updated. An error occurs if the result of the search condition isfalse for any row.
When one or more table check constraints is defined in the ALTER TABLEstatement for a table with existing data, the existing data is checked againstthe new condition before the ALTER TABLE statement completes. The SETINTEGRITY statement can be used to put the table in check pending state,which allows the ALTER TABLE statement to proceed without checking thedata.
Related reference:
v “SET INTEGRITY statement” in the SQL Reference, Volume 2
v Appendix I, “Interaction of triggers and constraints” on page 829
Isolation levels
The isolation level associated with an application process defines the degree ofisolation of that application process from other concurrently executingapplication processes. The isolation level of an application process thereforespecifies:v The degree to which the rows read and updated by the application are
available to other concurrently executing application processes.v The degree to which the update activity of other concurrently executing
application processes can affect the application.
The isolation level is specified as an attribute of a package and applies to theapplication processes that use the package. The isolation level is specified inthe program preparation process. Depending on the type of lock, this limits orprevents access to the data by concurrent application processes. (Declaredtemporary tables and their rows cannot be locked because they are onlyaccessible to the application that declared them.)
The database manager supports three general categories of locks:
Share Limits concurrent application processes to read-only operations on thedata.
UpdateLimits concurrent application processes to read-only operations on thedata, if these processes have not declared that they might update therow. The database manager assumes that the process currently lookingat a row may update it.
Table check constraints
Chapter 1. Concepts 13
ExclusivePrevents concurrent application processes from accessing the data inany way. Does not apply to application processes with an isolationlevel of uncommitted read, which can read but not modify the data.
Locking occurs at the base table row. The database manager, however, canreplace multiple row locks with a single table lock. This is called lockescalation. An application process is guaranteed at least the minimumrequested lock level.
The DB2® Universal Database database manager supports four isolationlevels. Regardless of the isolation level, the database manager places exclusivelocks on every row that is inserted, updated, or deleted. Thus, all isolationlevels ensure that any row that is changed by this application process duringa unit of work is not changed by any other application processes until theunit of work is complete. The isolation levels are:v Repeatable Read (RR)
This level ensures that:– Any row read during a unit of work is not changed by other application
processes until the unit of work is complete. The rows are read in thesame unit of work as the corresponding OPEN statement. Use of theoptional WITH RELEASE clause on the CLOSE statement means that anyguarantees against non-repeatable reads and phantom reads no longerapply to any previously accessed rows if the cursor is reopened.
– Any row changed by another application process cannot be read until itis committed by that application process.
The Repeatable Read level does not allow phantom rows to be viewed (seeRead Stability).
In addition to any exclusive locks, an application process running at the RRlevel acquires at least share locks on all the rows it references. Furthermore,the locking is performed so that the application process is completelyisolated from the effects of concurrent application processes.
v Read Stability (RS)Like the Repeatable Read level, the Read Stability level ensures that:– Any row read during a unit of work is not changed by other application
processes until the unit of work is complete. The rows are read in thesame unit of work as the corresponding OPEN statement. Use of theoptional WITH RELEASE clause on the CLOSE statement means that anyguarantees against non-repeatable reads no longer apply to anypreviously accessed rows if the cursor is reopened.
– Any row changed by another application process cannot be read until itis committed by that application process.
Isolation levels
14 SQL Reference, Volume 1
Unlike Repeatable Read, Read Stability does not completely isolate theapplication process from the effects of concurrent application processes. Atthe RS level, application processes that issue the same query more thanonce may see additional rows caused by other application processesappending new information to the database. These additional rows arecalled phantom rows.
For example, a phantom row can occur in the following situation:1. Application process P1 reads the set of rows n that satisfy some search
condition.2. Application process P2 then inserts one or more rows that satisfy the
search condition and commits those new inserts.3. P1 reads the set of rows again with the same search condition and
obtains both the original rows and the rows inserted by P2.
In addition to any exclusive locks, an application process running at the RSisolation level acquires at least share locks on all the qualifying rows.
v Cursor Stability (CS)Like the Repeatable Read level, the Cursor Stability level ensures that anyrow that was changed by another application process cannot be read until itis committed by that application process.Unlike Repeatable Read, Cursor Stability only ensures that the current rowof every updatable cursor is not changed by other application processes.Thus, the rows that were read during a unit of work can be changed byother application processes.In addition to any exclusive locks, an application process running at the CSisolation level acquires at least a share lock on the current row of everycursor.
v Uncommitted Read (UR)For SELECT INTO, FETCH with a read-only cursor, fullselect in an INSERT,row fullselect in an UPDATE, or scalar fullselect (wherever it is used), theUncommitted Read level allows:– Any row read during a unit of work to be changed by other application
processes.– Any row changed by another application process to be read, even if the
change has not been committed by that application process.
For other operations, rules associated with the CS level apply.
Related reference:
v “DECLARE CURSOR statement” in the SQL Reference, Volume 2
v Appendix H, “Comparison of isolation levels” on page 827
Isolation levels
Chapter 1. Concepts 15
Queries
A query is a component of certain SQL statements; it specifies a (temporary)result table.
Related reference:
v “SQL queries” on page 553
Table expressions
A table expression creates a temporary result table from a simple query. Clausesfurther refine the result table. For example, you can use a table expression asa query to select all of the managers from several departments, specify thatthey must have over 15 years of working experience, and be located at theNew York branch office.
A common table expression is like a temporary view within a complex query. Itcan be referenced in other places within the query, and can be used in place ofa view. Each use of a specific common table expression within a complexquery shares the same temporary view.
Recursive use of a common table expression within a query can be used tosupport applications such as airline reservation systems, bill of materials(BOM) generators, and network planning.
Related reference:
v Appendix L, “Recursion example: bill of materials” on page 861
Application processes, concurrency, and recovery
All SQL programs execute as part of an application process or agent. Anapplication process involves the execution of one or more programs, and isthe unit to which the database manager allocates resources and locks.Different application processes may involve the execution of differentprograms, or different executions of the same program.
More than one application process may request access to the same data at thesame time. Locking is the mechanism used to maintain data integrity undersuch conditions, preventing, for example, two application processes fromupdating the same row of data simultaneously.
The database manager acquires locks to prevent uncommitted changes madeby one application process from being accidentally perceived by any otherprocess. The database manager releases all locks it has acquired and retained
Queries
16 SQL Reference, Volume 1
on behalf of an application process when that process ends. However, anapplication process can explicitly request that locks be released sooner. This isdone using a commit operation, which releases locks acquired during the unitof work and also commits database changes made during the unit of work.
The database manager provides a means of backing out uncommitted changesmade by an application process. This might be necessary in the event of afailure on the part of an application process, or in the case of a deadlock, or alock time-out situation. An application process can explicitly request that itsdatabase changes be backed out. This is done using a rollback operation.
A unit of work is a recoverable sequence of operations within an applicationprocess. A unit of work is initiated when an application process is started, orwhen the previous unit of work is ended by something other than thetermination of the application process. A unit of work is ended by a commitoperation, a rollback operation, or the end of an application process. Acommit or rollback operation affects only the database changes made withinthe unit of work it is ending.
As long as these changes remain uncommitted, other application processes areunable to perceive them, and they can be backed out. This is not true,however, when the isolation level is uncommitted read (UR). Once committed,these database changes are accessible by other application processes and canno longer be backed out through a rollback.
Both DB2® call level interface (CLI) and embedded SQL allow for aconnection mode called concurrent transactions, which supports multipleconnections, each of which is an independent transaction. An application canhave multiple concurrent connections to the same database.
Locks acquired by the database manager on behalf of an application processare held until the end of a unit of work. This is not true, however, when theisolation level is cursor stability (CS, in which the lock is released as thecursor moves from row to row) or uncommitted read (UR, in which locks arenot obtained).
An application process is never prevented from performing operationsbecause of its own locks. However, if an application uses concurrenttransactions, the locks from one transaction may affect the operation of aconcurrent transaction.
The initiation and the termination of a unit of work define points ofconsistency within an application process. For example, a banking transactionmay involve the transfer of funds from one account to another. Such atransaction would require that these funds be subtracted from the firstaccount, and then added to the second account. Following the subtraction
Application processes, concurrency, and recovery
Chapter 1. Concepts 17
step, the data is inconsistent. Only after the funds have been added to thesecond account is consistency reestablished. When both steps are complete,the commit operation can be used to end the unit of work, thereby makingthe changes available to other application processes. If a failure occurs beforethe unit of work ends, the database manager will roll back uncommittedchanges to restore the data consistency that it assumes existed when the unitof work was initiated.
Related concepts:
v “Isolation levels” on page 13
Point ofconsistency
New point ofconsistency
Begin unitof work
CommitEnd unit of work
one unit of work
database updatesTIME LINE
Figure 2. Unit of Work with a COMMIT Statement
Point ofconsistency
New point ofconsistency
Begin unitof work
Failure;Begin rollback
Data is returned toits initial state;
End unit of work
one unit of work
databaseupdates
back outupdatesTIME LINE
Figure 3. Unit of Work with a ROLLBACK Statement
Application processes, concurrency, and recovery
18 SQL Reference, Volume 1
DB2 Call level interface (CLI) and open database connectivity (ODBC)
The DB2® call level interface is an application programming interface thatprovides functions for processing dynamic SQL statements to applicationprograms. CLI programs can also be compiled using an open databaseconnectivity Software Developer’s Kit (available from Microsoft® or othervendors), which enables access to ODBC data sources. Unlike embedded SQL,this interface requires no precompilation. Applications can be run against avariety of databases without having to be compiled against each of thesedatabases. Applications use procedure calls at run time to connect todatabases, issue SQL statements, and retrieve data and status information.
The DB2 CLI interface provides many features not available in embeddedSQL. For example:v CLI provides function calls that support a way of querying database
catalogs that is consistent across the DB2 family. This reduces the need towrite catalog queries that must be tailored to specific database servers.
v CLI provides the ability to scroll through a cursor:– Forward by one or more rows– Backward by one or more rows– Forward from the first row by one or more rows– Backward from the last row by one or more rows– From a previously stored location in the cursor.
v Stored procedures called from application programs that were written usingCLI can return result sets to those programs.
Java database connectivity (JDBC) and embedded SQL for Java (SQLJ)programs
DB2® Universal Database implements two standards-based Java™
programming APIs: Java database connectivity (JDBC) and embedded SQL forJava (SQLJ). Both can be used to create Java applications and applets thataccess DB2:v JDBC calls are translated into DB2 CLI calls through Java native methods.
JDBC requests flow from the DB2 client through DB2 CLI to the DB2 server.JDBC cannot use static SQL.
v SQLJ applications use JDBC as a foundation for such tasks as connecting todatabases and handling SQL errors, but can also contain embedded staticSQL statements in the SQLJ source files. An SQLJ source file must betranslated by the SQLJ translator before the resulting Java source code canbe compiled.
DB2 Call level interface (CLI) and open database connectivity (ODBC)
Chapter 1. Concepts 19
Packages
A package is an object produced during program preparation that contains allof the sections in a single source file. A section is the compiled form of an SQLstatement. Although every section corresponds to one statement, not everystatement has a section. The sections created for static SQL are comparable tothe bound, or operational, form of SQL statements. The sections created fordynamic SQL are comparable to placeholder control structures used at runtime.
Catalog views
The database manager maintains a set of base tables and views that containinformation about the data under its control. These base tables and views arecollectively known as the catalog. The catalog contains information about thelogical and physical structure of database objects such as tables, views,indexes, packages, and functions. It also contains statistical information. Thedatabase manager ensures that the descriptions in the catalog are alwaysaccurate.
The catalog views are like any other database view. SQL statements can beused to look at the data in the catalog views. A set of updatable catalog viewscan be used to modify certain values in the catalog.
Related reference:
v “System catalog views” on page 636
Character conversion
A string is a sequence of bytes that may represent characters. All thecharacters within a string have a common coding representation. In somecases, it may be necessary to convert these characters to a different codingrepresentation, a process known as character conversion. Character conversion,when required, is automatic, and when successful, it is transparent to theapplication.
Character conversion can occur when an SQL statement is executed remotely.Consider, for example, the following scenarios in which the codingrepresentations may be different at the sending and receiving systems:v The values of host variables are sent from the application requester to the
application server.v The values of result columns are sent from the application server to the
application requester.
Packages
20 SQL Reference, Volume 1
Following is a list of terms used when discussing character conversion:
character setA defined set of characters. For example, the following character setappears in several code pages:v 26 non-accented letters A through Zv 26 non-accented letters a through zv digits 0 through 9v . , : ; ? ( ) ' " / − _ & + % * = < >
code pageA set of assignments of characters to code points. In the ASCIIencoding scheme for code page 850, for example, "A" is assigned codepoint X'41', and "B" is assigned code point X'42'. Within a code page,each code point has only one specific meaning. A code page is anattribute of the database. When an application program connects tothe database, the database manager determines the code page of theapplication.
code pointA unique bit pattern that represents a character.
encoding schemeA set of rules used to represent character data, for example:v Single-Byte ASCIIv Single-Byte EBCDICv Double-Byte ASCIIv Mixed single- and double-byte ASCII
The following figure shows how a typical character set might map to differentcode points in two different code pages. Even with the same encodingscheme, there are many different code pages, and the same code point canrepresent a different character in different code pages. Furthermore, a byte ina character string does not necessarily represent a character from a single-bytecharacter set (SBCS). Character strings are also used for mixed and bit data.Mixed data is a mixture of single-byte, double-byte, or multi-byte characters.Bit data (columns defined as FOR BIT DATA, or BLOBs, or binary strings) isnot associated with any character set.
Character conversion
Chapter 1. Concepts 21
The database manager determines code page attributes for all character stringswhen an application is bound to a database. The possible code page attributesare:
Database code pageThe database code page is stored in the database configuration file.The value is specified when the database is created and cannot bealtered.
Application code pageThe code page under which the application runs. This is notnecessarily the same code page under which the application wasbound.
FE
Ä
Ã
Á
Å
Â
À
Ö
®
58
2 3 4 50
0
1
1
2
3
4
5
E
F
%
/
0
1
2
3
4
5
@
A
B
C
D
E
N
0
>.
*
P
Q
R
S
T
U
code page: pp1 (ASCII)
character set ss1(in code page pp1)
code point: 2F
0
1
2
3
4
5
E
F
FE0 1 A B
s
t
u
v
#
$
%
*
(
S
T
U
V
Â
C D
0
1
2
3
4
5
}
{ÁÀ ¢
! :
;
A
B
C
D
E
J
K
L
M
N
code page: pp2 (EBCDIC)
character set ss1(in code page pp2)
"
Figure 4. Mapping a Character Set in Different Code Pages
Character conversion
22 SQL Reference, Volume 1
Code Page 0This represents a string that is derived from an expression thatcontains a FOR BIT DATA value or a BLOB value.
Character string code pages have the following attributes:v Columns can be in the database code page or code page 0 (if defined as
character FOR BIT DATA or BLOB).v Constants and special registers (for example, USER, CURRENT SERVER)
are in the database code page. Constants are converted to the database codepage when an SQL statement is bound to the database.
v Input host variables are in the application code page. As of Version 8, stringdata in input host variables is converted, if necessary, from the applicationcode page to the database code page before being used. The exceptionoccurs when a host variable is used in a context where it is to beinterpreted as bit data; for example, when the host variable is to beassigned to a column that is defined as FOR BIT DATA.
A set of rules is used to determine code page attributes for operations thatcombine string objects, such as scalar operations, set operations, orconcatenation. Code page attributes are used to determine requirements forcode page conversion of strings at run time.
Related reference:
v “Assignments and comparisons” on page 117v “Rules for string conversions” on page 139
Event monitors
Event monitors are used to collect information about the database and anyconnected applications when specified events occur. Events representtransitions in database activity: for instance, connections, deadlocks,statements, and transactions. You can define an event monitor by the type ofevent or events you want it to monitor. For example, a deadlock eventmonitor waits for a deadlock to occur; when one does, it collects informationabout the applications involved and the locks in contention. Whereas thesnapshot monitor is typically used for preventative maintenance and problemanalysis, event monitors are used to alert administrators to immediateproblems or to track impending ones.
To create an event monitor, use the CREATE EVENT MONITOR SQLstatement. Event monitors collect event data only when they are active. Toactivate or deactivate an event monitor, use the SET EVENT MONITORSTATE SQL statement. The status of an event monitor (whether it is active orinactive) can be determined by the SQL function EVENT_MON_STATE.
Character conversion
Chapter 1. Concepts 23
When the CREATE EVENT MONITOR SQL statement is executed, thedefinition of the event monitor it creates is stored in the following databasesystem catalog tables:v SYSCAT.EVENTMONITORS: event monitors defined for the database.v SYSCAT.EVENTS: events monitored for the database.v SYSCAT.EVENTTABLES: target tables for table event monitors.
Each event monitor has its own private logical view of the instance’s data inthe data elements. If a particular event monitor is deactivated and thenreactivated, its view of these counters is reset. Only the newly activated eventmonitor is affected; all other event monitors will continue to use their view ofthe counter values (plus any new additions).
Event monitor output can be directed to SQL tables, a file, or a named pipe.
Related concepts:
v “Database system monitor” in the System Monitor Guide and Reference
Related tasks:
v “Collecting information about database system events” in the SystemMonitor Guide and Reference
v “Creating an event monitor” in the System Monitor Guide and Reference
Related reference:
v “Event monitor sample output” in the System Monitor Guide and Reference
v “Event types” in the System Monitor Guide and Reference
Triggers
A trigger defines a set of actions that are performed in response to an insert,update, or delete operation on a specified table. When such an SQL operationis executed, the trigger is said to have been activated.
Triggers are optional and are defined using the CREATE TRIGGER statement.
Triggers can be used, along with referential constraints and check constraints,to enforce data integrity rules. Triggers can also be used to cause updates toother tables, automatically generate or transform values for inserted orupdated rows, or invoke functions to perform tasks such as issuing alerts.
Triggers are a useful mechanism for defining and enforcing transitionalbusiness rules, which are rules that involve different states of the data (forexample, a salary that cannot be increased by more than 10 percent).
Event monitors
24 SQL Reference, Volume 1
Using triggers places the logic that enforces business rules inside the database.This means that applications are not responsible for enforcing these rules.Centralized logic that is enforced on all of the tables means easiermaintenance, because changes to application programs are not required whenthe logic changes.
The following are specified when creating a trigger:v The subject table specifies the table for which the trigger is defined.v The trigger event defines a specific SQL operation that modifies the subject
table. The event can be an insert, update, or delete operation.v The trigger activation time specifies whether the trigger should be activated
before or after the trigger event occurs.
The statement that causes a trigger to be activated includes a set of affectedrows. These are the rows of the subject table that are being inserted, updated,or deleted. The trigger granularity specifies whether the actions of the triggerare performed once for the statement or once for each of the affected rows.
The triggered action consists of an optional search condition and a set of SQLstatements that are executed whenever the trigger is activated. The SQLstatements are only executed if the search condition evaluates to true. If thetrigger activation time is before the trigger event, triggered actions can includestatements that select, set transition variables, or signal SQLstates. If thetrigger activation time is after the trigger event, triggered actions can includestatements that select, insert, update, delete, or signal SQLstates.
The triggered action can refer to the values in the set of affected rows usingtransition variables. Transition variables use the names of the columns in thesubject table, qualified by a specified name that identifies whether thereference is to the old value (before the update) or the new value (after theupdate). The new value can also be changed using the SET Variable statementin before, insert, or update triggers.
Another means of referring to the values in the set of affected rows is to usetransition tables. Transition tables also use the names of the columns in thesubject table, but specify a name to allow the complete set of affected rows tobe treated as a table. Transition tables can only be used in after triggers, andseparate transition tables can be defined for old and new values.
Multiple triggers can be specified for a combination of table, event, oractivation time. The order in which the triggers are activated is the same asthe order in which they were created. Thus, the most recently created triggeris the last trigger to be activated.
Triggers
Chapter 1. Concepts 25
The activation of a trigger may cause trigger cascading, which is the result ofthe activation of one trigger that executes SQL statements that cause theactivation of other triggers or even the same trigger again. The triggeredactions may also cause updates resulting from the application of referentialintegrity rules for deletions that can, in turn, result in the activation ofadditional triggers. With trigger cascading, a chain of triggers and referentialintegrity delete rules can be activated, causing significant change to thedatabase as a result of a single INSERT, UPDATE, or DELETE statement.
Table spaces and other storage structures
Storage structures contain database objects. The basic storage structure is thetable space; it contains tables, indexes, large objects, and data defined with aLONG data type. There are two types of table spaces:
Database managed space (DMS)A table space that is managed by the database manager.
System managed space (SMS)A table space that is managed by the operating system.
All table spaces consist of containers. A container describes where objects arestored. A subdirectory in a file system is an example of a container.
When data is read from table space containers, it is placed in an area ofmemory called a buffer pool. A buffer pool is associated with a specific tablespace, thereby allowing control over which data will share the same memoryareas for data buffering.
In a partitioned database, data is spread across different database partitions.Exactly which partitions are included is determined by the database partitiongroup that is assigned to the table space. A database partition group is a groupof one or more partitions that are defined as part of the database. A tablespace includes one or more containers for each partition in the databasepartition group. A partitioning map, associated with each database partitiongroup, is used by the database manager to determine on which partition agiven row of data is to be stored. The partitioning map is an array of 4096partition numbers. The partitioning map index produced by the partitioningfunction for each row in a table is used as an index into the partitioning mapto determine the partition on which a row is to be stored. As an example, thefollowing figure shows how a row with partitioning key value (c1, c2, c3) ismapped to partitioning map index 2 which, in turn, references partition p5.
Triggers
26 SQL Reference, Volume 1
The partitioning map can be changed, allowing the data distribution to bechanged without modifying the partitioning key or the actual data. The newpartitioning map is specified as part of the REDISTRIBUTE DATABASEPARTITION GROUP command or the sqludrdt application programminginterface (API), which use it to redistribute the tables in the database partitiongroup.
The DB2® Data Links Manager product provides functionality that supportsadditional storage capabilities. A normal user table can include columns(defined with the DATALINK data type) that register links to data stored inexternal files. DATALINK values point to data files that are stored on anexternal file server.
Related concepts:
v “Data partitioning across multiple partitions” on page 28
Related reference:
v “CREATE BUFFERPOOL statement” in the SQL Reference, Volume 2
v “CREATE DATABASE PARTITION GROUP statement” in the SQL Reference,Volume 2
v “CREATE TABLESPACE statement” in the SQL Reference, Volume 2
p0 p2 p5 p0 p2 p5 ... p0
0 1 3 4 52 4095...
Row
Partitioning Map
Nodegroup partitions are p0, p2, and p5
Note: Partition numbers start at 0.
(... c1, c2, c3 ...)
partitioning key
partitioning function maps (c1, c2, c3)to partitioning map index 2
Figure 5. Data Distribution
Table spaces and other storage structures
Chapter 1. Concepts 27
Data partitioning across multiple partitions
DB2® allows great flexibility in spreading data across multiple partitions(nodes) of a partitioned database. Users can choose how to partition their databy declaring partitioning keys, and can determine which and how manypartitions their table data can be spread across by selecting the databasepartition group and table space in which the data should be stored. Inaddition, a partitioning map (which is updatable) specifies the mapping ofpartitioning key values to partitions. This makes it possible for flexibleworkload parallelization across a partitioned database for large tables, whileallowing smaller tables to be stored on one or a small number of partitions ifthe application designer so chooses. Each local partition may have localindexes on the data it stores to provide high performance local data access.
A partitioned database supports a partitioned storage model, in which thepartitioning key is used to partition table data across a set of databasepartitions. Index data is also partitioned with its corresponding tables, andstored locally at each partition.
Before partitions can be used to store database data, they must be defined tothe database manager. Partitions are defined in a file called db2nodes.cfg.
The partitioning key for a table in a table space on a partitioned databasepartition group is specified in the CREATE TABLE statement or the ALTERTABLE statement. If not specified, a partitioning key for a table is created bydefault from the first column of the primary key. If no primary key is defined,the default partitioning key is the first column defined in that table that has adata type other than a long or a LOB data type. Partitioned tables must haveat least one column that is neither a long nor a LOB data type. A table in atable space that is in a single partition database partition group will have apartitioning key only if it is explicitly specified.
Hash partitioning is used to place a row in a partition as follows:1. A hashing algorithm (partitioning function) is applied to all of the columns
of the partitioning key, which results in the generation of a partitioningmap index value.
2. The partition number at that index value in the partitioning map identifiesthe partition in which the row is to be stored.
DB2 supports partial declustering, which means that a table can be partitionedacross a subset of partitions in the system (that is, a database partition group).Tables do not have to be partitioned across all of the partitions in the system.
DB2 has the capability of recognizing when data being accessed for a join or asubquery is located at the same partition in the same database partition
Data partitioning across multiple partitions
28 SQL Reference, Volume 1
group. This is known as table collocation. Rows in collocated tables with thesame partitioning key values are located on the same partition. DB2 canchoose to perform join or subquery processing at the partition in which thedata is stored. This can have significant performance advantages.
Collocated tables must:v Be in the same database partition group, one that is not being redistributed.
(During redistribution, tables in the database partition group may be usingdifferent partitioning maps – they are not collocated.)
v Have partitioning keys with the same number of columns.v Have the corresponding columns of the partitioning key be partition
compatible.v Be in a single partition database partition group defined on the same
partition.
Related reference:
v “Partition-compatible data types” on page 141
Distributed relational databases
A distributed relational database consists of a set of tables and other objects thatare spread across different but interconnected computer systems. Eachcomputer system has a relational database manager to manage the tables in itsenvironment. The database managers communicate and cooperate with eachother in a way that allows a given database manager to execute SQLstatements on another computer system.
Distributed relational databases are built on formal requester-server protocolsand functions. An application requester supports the application end of aconnection. It transforms a database request from the application intocommunication protocols suitable for use in the distributed database network.These requests are received and processed by a database server at the other endof the connection. Working together, the application requester and thedatabase server handle communication and location considerations, so that theapplication can operate as if it were accessing a local database.
An application process must connect to a database manager’s applicationserver before SQL statements that reference tables or views can be executed.The CONNECT statement establishes a connection between an applicationprocess and its server.
There are two types of CONNECT statements:v CONNECT (Type 1) supports the single database per unit of work (Remote
Unit of Work) semantics.
Data partitioning across multiple partitions
Chapter 1. Concepts 29
v CONNECT (Type 2) supports the multiple databases per unit of work(Application-Directed Distributed Unit of Work) semantics.
The DB2® call level interface (CLI) and embedded SQL support a connectionmode called concurrent transactions, which allows multiple connections, each ofwhich is an independent transaction. An application can have multipleconcurrent connections to the same database.
The application server can be local to or remote from the environment inwhich the process is initiated. An application server is present, even if theenvironment is not using distributed relational databases. This environmentincludes a local directory that describes the application servers that can beidentified in a CONNECT statement.
The application server runs the bound form of a static SQL statement thatreferences tables or views. The bound statement is taken from a package thatthe database manager has previously created through a bind operation.
For the most part, an application connected to an application server can usestatements and clauses that are supported by the application server’s databasemanager. This is true even if an application is running through the applicationrequester of a database manager that does not support some of thosestatements and clauses.
Remote unit of workThe remote unit of work facility provides for the remote preparation andexecution of SQL statements. An application process at computer system Acan connect to an application server at computer system B and, within one ormore units of work, execute any number of static or dynamic SQL statementsthat reference objects at B. After ending a unit of work at B, the applicationprocess can connect to an application server at computer system C, and so on.
Most SQL statements can be remotely prepared and executed, with thefollowing restrictions:v All objects referenced in a single SQL statement must be managed by the
same application server.v All of the SQL statements in a unit of work must be executed by the same
application server.
At any given time, an application process is in one of four possible connectionstates:v Connectable and connected
An application process is connected to an application server, andCONNECT statements can be executed.If implicit connect is available:
Distributed relational databases
30 SQL Reference, Volume 1
– The application process enters this state when a CONNECT TOstatement or a CONNECT without operands statement is successfullyexecuted from the connectable and unconnected state.
– The application process may enter this state from the implicitlyconnectable state if any SQL statement other than CONNECT RESET,DISCONNECT, SET CONNECTION, or RELEASE is issued.
Whether or not implicit connect is available, this state is entered when:– A CONNECT TO statement is successfully executed from the connectable
and unconnected state.– A COMMIT or ROLLBACK statement is successfully issued, or a forced
rollback occurs from the unconnectable and connected state.v Unconnectable and connected
An application process is connected to an application server, but aCONNECT TO statement cannot be successfully executed to changeapplication servers. The application process enters this state from theconnectable and connected state when it executes any SQL statement otherthan the following: CONNECT TO, CONNECT with no operand,CONNECT RESET, DISCONNECT, SET CONNECTION, RELEASE,COMMIT, or ROLLBACK.
v Connectable and unconnectedAn application process is not connected to an application server.CONNECT TO is the only SQL statement that can be executed; otherwise,an error (SQLSTATE 08003) is raised.Whether or not implicit connect is available, the application process entersthis state if an error occurs when a CONNECT TO statement is issued, oran error occurs within a unit of work, causing the loss of a connection anda rollback. An error that occurs because the application process is not in theconnectable state, or because the server name is not listed in the localdirectory, does not cause a transition to this state.If implicit connect is not available:– The application process is initially in this state– The CONNECT RESET and DISCONNECT statements cause a transition
to this state.v Implicitly connectable (if implicit connect is available).
If implicit connect is available, this is the initial state of an applicationprocess. The CONNECT RESET statement causes a transition to this state.Issuing a COMMIT or ROLLBACK statement in the unconnectable andconnected state, followed by a DISCONNECT statement in the connectableand connected state, also results in this state.
Availability of implicit connect is determined by installation options,environment variables, and authentication settings.
Remote unit of work
Chapter 1. Concepts 31
It is not an error to execute consecutive CONNECT statements, becauseCONNECT itself does not remove the application process from theconnectable state. It is, however, an error to execute consecutive CONNECTRESET statements. It is also an error to execute any SQL statement other thanCONNECT TO, CONNECT RESET, CONNECT with no operand, SETCONNECTION, RELEASE, COMMIT, or ROLLBACK, and then to execute aCONNECT TO statement. To avoid this error, a CONNECT RESET,DISCONNECT (preceded by a COMMIT or ROLLBACK statement),COMMIT, or ROLLBACK statement should be executed before the CONNECTTO statement.
ImplicitlyConnectable
Connectableand
Connected
Connectableand
Unconnected
Unconnectableand
Connected
Begin process
CONNECTRESET
CONNECTRESET
CONNECT TO,COMMIT,
or ROLLBACK
Failure ofimplicit connect
System failurewith rollback
ROLLBACK,successful COMMIT,
or deadlock
CONNECT TO,COMMIT, orROLLBACK
SQL statement otherthan CONNECT RESET,COMMIT or ROLLBACK
SQL statement other thanCONNECT TO, CONNECT RESET,
COMMIT or ROLLBACK
CONNECT TO with system failure
Successful CONNECT TO
Figure 6. Connection State Transitions If Implicit Connect Is Available
Remote unit of work
32 SQL Reference, Volume 1
Application-directed distributed unit of workThe application-directed distributed unit of work facility also provides for theremote preparation and execution of SQL statements. An application processat computer system A can connect to an application server at computersystem B by issuing a CONNECT or a SET CONNECTION statement. Theapplication process can then execute any number of static and dynamic SQLstatements that reference objects at B before ending the unit of work. Allobjects referenced in a single SQL statement must be managed by the sameapplication server. However, unlike the remote unit of work facility, anynumber of application servers can participate in the same unit of work. Acommit or a rollback operation ends the unit of work.
An application-directed distributed unit of work uses a type 2 connection. Atype 2 connection connects an application process to the identified applicationserver, and establishes the rules for application-directed distributed units ofwork.
Connectableand
Unconnected
Unconnectableand
Connected
Connectableand
Connected
Begin processCONNECT RESET
CONNECTRESET
CONNECTRESET
System failurewith rollback
CONNECT TO,COMMIT orROLLBACK
Successful CONNECT TO
CONNECT TOwith system failure
SQL statement otherthan CONNECT RESET,COMMIT or ROLLBACK
SQL statement other thanCONNECT TO, CONNECT RESET,
COMMIT or ROLLBACK
ROLLBACK,successful COMMIT,
or deadlock
Figure 7. Connection State Transitions If Implicit Connect Is Not Available
Application-directed distributed unit of work
Chapter 1. Concepts 33
A type 2 application process:v Is always connectablev Is either in the connected state or in the unconnected statev Has zero or more connections.
Each connection of an application process is uniquely identified by thedatabase alias of the application server for the connection.
An individual connection always has one of the following connection states:v current and heldv current and release-pendingv dormant and heldv dormant and release-pending
A type 2 application process is initially in the unconnected state, and does nothave any connections. A connection is initially in the current and held state.
Application-directed distributed unit of work
34 SQL Reference, Volume 1
Application process connection statesThe following rules apply to the execution of a CONNECT statement:v A context cannot have more than one connection to the same application
server at the same time.v When an application process executes a SET CONNECTION statement, the
specified location name must be an existing connection in the set ofconnections for the application process.
v When an application process executes a CONNECT statement, and theSQLRULES(STD) option is in effect, the specified server name must not bean existing connection in the set of connections for the application process.For a description of the SQLRULES option, see “Options that governdistributed unit of work semantics” on page 37.
Current
Current
Dormant
Dormant
HeldRelease-pending
States of a Connection
States of a Connection
RELEASE
Successful CONNECT orSET CONNECTION
specifying anexisting dormant connection
Successful CONNECT orSET CONNECTION
specifying another connection
The current connection is intentionally ended,or a failure occurs causing the loss
of the connection
Successful CONNECT orSET CONNECTION
Beginprocess
Figure 8. Application-Directed Distributed Unit of Work Connection State Transitions
Application process connection states
Chapter 1. Concepts 35
If an application process has a current connection, the application process isin the connected state. The CURRENT SERVER special register contains thename of the application server for the current connection. The applicationprocess can execute SQL statements that refer to objects managed by thatapplication server.
An application process that is in the unconnected state enters the connectedstate when it successfully executes a CONNECT or a SET CONNECTIONstatement. If there is no connection, but SQL statements are issued, an implicitconnect is made, provided the DB2DBDFT environment variable has been setwith the name of a default database.
If an application process does not have a current connection, the applicationprocess is in the unconnected state. The only SQL statements that can beexecuted are CONNECT, DISCONNECT ALL, DISCONNECT (specifying adatabase), SET CONNECTION, RELEASE, COMMIT, or ROLLBACK.
An application process in the connected state enters the unconnected state whenits current connection intentionally ends, or when an SQL statement fails,causing a rollback operation at the application server and loss of theconnection. Connections end intentionally following the successful executionof a DISCONNECT statement, or a COMMIT statement when the connectionis in release-pending state. (If the DISCONNECT precompiler option is set toAUTOMATIC, all connections end. If it is set to CONDITIONAL, allconnections that do not have open WITH HOLD cursors end.)
Connection statesIf an application process executes a CONNECT statement, and the servername is known to the application requester but is not in the set of existingconnections for the application process:v The current connection is placed into the dormant connection state, andv The server name is added to the set of connections, andv The new connection is placed into both the current connection state and the
held connection state.
If the server name is already in the set of existing connections for theapplication process, and the application is precompiled with theSQLRULES(STD) option, an error (SQLSTATE 08002) is raised.
Held and release-pending states. The RELEASE statement controls whether aconnection is in the held or the release-pending state. The release-pending statemeans that a disconnect is to occur at the next successful commit operation.(A rollback has no effect on connections.) The held state means that adisconnect is not to occur at the next commit operation.
Application process connection states
36 SQL Reference, Volume 1
All connections are initially in the held state and can be moved to therelease-pending state using the RELEASE statement. Once in therelease-pending state, a connection cannot be moved back to the held state. Aconnection remains in release-pending state across unit of work boundaries ifa ROLLBACK statement is issued, or if an unsuccessful commit operationresults in a rollback operation.
Even if a connection is not explicitly marked for release, it may still bedisconnected by a commit operation if the commit operation satisfies theconditions of the DISCONNECT precompiler option.
Current® and dormant states. Regardless of whether a connection is in theheld state or the release-pending state, it can also be in the current state or thedormant state. A connection in the current state is the connection being usedto execute SQL statements while in this state. A connection in the dormantstate is a connection that is not current.
The only SQL statements that can flow on a dormant connection areCOMMIT, ROLLBACK, DISCONNECT, or RELEASE. The SET CONNECTIONand CONNECT statements change the connection state of the specified serverto current, and any existing connections are placed or remain in dormantstate. At any point in time, only one connection can be in current state. If adormant connection becomes current in the same unit of work, the state of alllocks, cursors, and prepared statements is the same as the state they were inthe last time that the connection was current.
When a connection endsWhen a connection ends, all resources that were acquired by the applicationprocess through the connection, and all resources that were used to create andmaintain the connection are de-allocated. For example, if the applicationprocess executes a RELEASE statement, any open cursors are closed when theconnection ends during the next commit operation.
A connection can also end because of a communications failure. If thisconnection is in current state, the application process is placed in unconnectedstate.
All connections for an application process end when the process ends.
Options that govern distributed unit of work semanticsThe semantics of type 2 connection management are determined by a set ofprecompiler options. These options are summarized below with default valuesindicated by bold and underlined text.v CONNECT (1 | 2). Specifies whether CONNECT statements are to be
processed as type 1 or type 2.
Connection states
Chapter 1. Concepts 37
v SQLRULES (DB2 | STD). Specifies whether type 2 CONNECTs are to beprocessed according to the DB2 rules, which allow CONNECT to switch toa dormant connection, or the SQL92 Standard rules, which do not allowthis.
v DISCONNECT (EXPLICIT | CONDITIONAL | AUTOMATIC). Specifieswhat database connections are to be disconnected when a commit operationoccurs:– Those that have been explicitly marked for release by the SQL RELEASE
statement (EXPLICIT)– Those that have no open WITH HOLD cursors, and those that are
marked for release (CONDITIONAL)– All connections (AUTOMATIC).
v SYNCPOINT (ONEPHASE | TWOPHASE | NONE). Specifies howCOMMITs or ROLLBACKs are to be coordinated among multiple databaseconnections:– Updates can only occur against one database in the unit of work, and all
other databases are read-only (ONEPHASE). Any update attempts toother databases raise an error (SQLSTATE 25000).
– A transaction manager (TM) is used at run time to coordinate two-phaseCOMMITs among those databases that support this protocol(TWOPHASE).
– Does not use a TM to perform two-phase COMMITs, and does notenforce single updater, multiple reader (NONE). When a COMMIT or aROLLBACK statement is executed, individual COMMITs or ROLLBACKsare posted to all databases. If one or more ROLLBACKs fail, an error(SQLSTATE 58005) is raised. If one or more COMMITs fail, another error(SQLSTATE 40003) is raised.
To override any of the above options at run time, use the SET CLIENTcommand or the sqlesetc application programming interface (API). Theircurrent settings can be obtained using the QUERY CLIENT command or thesqleqryc API. Note that these are not SQL statements; they are APIs defined inthe various host languages and in the command line processor (CLP).
Data representation considerationsDifferent systems represent data in different ways. When data is moved fromone system to another, data conversion must sometimes be performed.Products supporting DRDA® automatically perform any necessaryconversions at the receiving system. To perform conversions of numeric data,the system needs to know the data type and how it is represented by thesending system. Additional information is needed to convert character strings.String conversion depends on both the code page of the data and theoperation that is to be performed on that data. Character conversions areperformed in accordance with the IBM® Character Data Representation
Options that govern distributed unit of work semantics
38 SQL Reference, Volume 1
Architecture (CDRA). For more information about character conversion, seethe Character Data Representation Architecture: Reference & Registry(SC09-2190-00) manual.
Related reference:
v “CONNECT (Type 1) statement” in the SQL Reference, Volume 2
v “CONNECT (Type 2) statement” in the SQL Reference, Volume 2
DB2 federated systems
Federated systems
A DB2® federated system is a special type of distributed database managementsystem (DBMS). A federated system consists of a DB2 instance that operatesas a federated server, a database that acts as the federated database, one ormore data sources, and clients (users and applications) that access thedatabase and data sources. With a federated system you can send distributedrequests to multiple data sources within a single SQL statement. For example,you can join data that is located in a DB2 Universal Database™ table, anOracle table, and a Sybase view in a single SQL statement.
Data representation considerations
Chapter 1. Concepts 39
The power of a DB2 federated system is in its ability to:v Join data from local tables and remote data sources, as if all the data is
local.v Take advantage of the data source processing strengths, by sending
distributed requests to the data sources for processing.v Compensate for SQL limitations at the data source by processing parts of a
distributed request at the federated server.
The DB2 server in a federated system is referred to as the federated server. Anynumber of DB2 instances can be configured to function as federated servers.You can use existing DB2 instances as your federated server, or you can createnew ones specifically for the federated system.
The DB2 federated instance that manages the federated system is called aserver because responds to requests from end users and client applications.The federated server often sends parts of the requests it receives to the datasources for processing. A pushdown operation is an operation that is processed
Figure 9. The components of a federated system and the supported data sources
DB2 federated systems
40 SQL Reference, Volume 1
remotely. The federated instance is referred to as the federated server, eventhough it acts as a client when it pushes down requests to the data sources.
Like any other application server, the federated server is a database managerinstance to which application processes connect and submit requests.However, two main features distinguish it from other application servers:v A federated server is configured to receive requests that might be partially
or entirely intended for data sources. The federated server distributes theserequests to the data sources.
v Like other application servers, a federated server uses DRDA®
communication protocols (such as SNA and TCP/IP) to communicate withDB2 family instances. However, unlike other application servers, afederated server uses other protocols to communicate with non-DB2 familyinstances.
Related concepts:
v “Data sources” on page 41v “The federated database” on page 43v “The SQL Compiler and the query optimizer” on page 44v “Compensation” on page 45v “Pushdown analysis” in the Federated Systems Guide
Data sources
Typically, a federated system data source is a relational DBMS instance (such asOracle or Sybase) and one or more databases that are supported by theinstance. However, there are other types of data sources (such as life sciencesdata sources and search algorithms) that you can include in your federatedsystem:v Spreadsheets, such as Microsoft® Excel.v Search algorithms, such as BLAST.v Table-structured files. These type of files have a regular structure that
consists of a series of records. Each record contains the same number offields that are separated by an arbitrary delimiter. Two sequential delimitersrepresent null values.
v Documentum document management software that includes a repository tostore document content, attributes, relationships, versions, renditions,formats, workflow, and security.
v XML tagged files.
In DB2® Universal Database for UNIX® and Windows, the supported datasources are:
DB2 federated systems
Chapter 1. Concepts 41
Table 1. Supported data source versions and access methods.
Data source Supported datasource versions
Access method Notes
DB2 UniversalDatabase™ for UNIXand Windows®
6.1, 7.1, 7.2, 8.1 DRDA® Directly integratedin DB2 Version 8
DB2 UniversalDatabase for z/OS™
and OS/390®
5 with PTF PQ07537(or later)
DRDA Directly integratedin DB2 Version 8
DB2 UniversalDatabase foriSeries™
4.2 (or later) DRDA Directly integratedin DB2 Version 8
DB2 Server for VMand VSE
3.3 (or later) DRDA Directly integratedin DB2 Version 8
Informix™ 7, 8, 9 Informix Client SDK Directly integratedin DB2 Version 8
ODBC ODBC 3.0 driver. Requires DB2Relational Connect
OLE DB OLE DB 2.0 (orlater)
Directly integratedin DB2 Version 8
Oracle 7.x, 8.x, 9.x SQL*Net or Net8client software
Requires DB2Relational Connect
Microsoft SQLServer
6.5, 7.0, 2000 On Windows theMicrosoft SQLServer Client ODBC3.0 (or higher)driver. On UNIX theData DirectTechnologies(formerly MERANT)Connect ODBC 3.6driver.
Requires DB2Relational Connect
Sybase 10.0, 11.0, 11.1, 11.5,11.9, 12.0
Sybase Open Client Requires DB2Relational Connect
BLAST 2.1.2 BLAST daemon(supplied with thewrapper)
Requires DB2 LifeSciences DataConnect
Documentum Documentumserver: EDMS 98(also referred to asversion 3) and 4i.
Documentum ClientAPI/Library
Requires DB2 LifeSciences DataConnect
DB2 federated systems
42 SQL Reference, Volume 1
Table 1. Supported data source versions and access methods. (continued)
Data source Supported datasource versions
Access method Notes
Microsoft Excel 97, 2000 none Requires DB2 LifeSciences DataConnect
table-structured files none Requires DB2 LifeSciences DataConnect
XML 1.0 specification none Requires DB2 LifeSciences DataConnect
Data sources are semi-autonomous. For example, the federated server cansend queries to Oracle data sources at the same time that Oracle applicationscan access these data sources. A DB2 federated system does not monopolizeor restrict access to the other data sources, beyond integrity and lockingconstraints.
The federated database
To end users and client applications, data sources appear as a single collectivedatabase in DB2. Users and applications interface with the federated databasemanaged by the federated server. The federated database contains catalogentries that identify data sources and their characteristics. The federatedserver consults the information stored in the federated database systemcatalog and the data source wrapper to determine the best plan for processingSQL statements.
The federated database system catalog contains information about the objectsin the federated database and information about objects at the data sources.The catalog in a federated database is called the global catalog because itcontains information about the entire federated system. DB2® query optimizeruses the information in the global catalog and the data source wrapper toplan the best way to process SQL statements. The information stored in theglobal catalog includes remote and local information, such as column names,column data types, column default values and index information.
Remote catalog information is the information or name used by the datasource. Local catalog information is the information or name used by thefederated database. For example, suppose a remote table includes a columnwith the name of EMPNO. The global catalog would store the remote columnname as EMPNO. Unless you designate a different name, the local columnname will be stored as EMPNO. You can change the local column name toEmployee_Number. Users submitting queries which include this column will
DB2 federated systems
Chapter 1. Concepts 43
use Employee_Number in their queries instead of EMPNO. You use columnoptions to change the local name of data source column.
For relational data sources, the information stored in the global catalogincludes both remote and local information. For non-relational data sources,the information stored in the global catalog varies from data source to datasource.
To see the data source table information that is stored in the global catalog,query the federated SYSCAT.TABLES, SYSCAT.TABOPTIONS,SYSCAT.COLUMNS, and SYSCAT.COLOPTIONS catalog views.
The federated system processes SQL statements as if the data sources wereordinary relational tables or views within the federated database. This enablesthe federated system to join relational data with data in non-relationalformats. This is true even when the data sources use different SQL dialects, ordo not support SQL at all.
The global catalog also includes other information about the data sources. Forexample, it includes information the federated server uses to connect to thedata source and map the federated user authorizations to the data source userauthorizations.
Related concepts:
v “Federated systems” on page 39v “The SQL Compiler and the query optimizer” on page 44v “Tuning query processing” in the Federated Systems Guide
Related reference:
v “Views in the global catalog table containing federated information” in theFederated Systems Guide
The SQL Compiler and the query optimizer
To obtain data from data sources, users and applications submit queries inDB2® SQL to the federated database. When a query is submitted, the DB2SQL Compiler consults information in the global catalog and the data sourcewrapper to help it process the query. This includes information aboutconnecting to the data source, server attributes, mappings, index information,and processing statistics.
As part of the SQL Compiler process, the query optimizer analyzes a query. TheCompiler develops alternative strategies, called access plans, for processing thequery. Access plans might call for the query to be:v Processed by the data sources.
DB2 federated systems
44 SQL Reference, Volume 1
v Processed by the federated server.v Processed partly by the data sources and partly by the federated server.
DB2 evaluates the access plans primarily on the basis of information about thedata source capabilities and the data. The wrapper and the global catalogcontain this information. DB2 decomposes the query into segments that arecalled query fragments. Typically it is more efficient to pushdown a queryfragment to a data source, if the data source can process the fragment.However, the query optimizer takes into account other factors such as:v The amount of data that needs to be processed.v The processing speed of the data source.v The amount of data that the fragment will return.v The communication bandwidth.
The query optimizer generates local and remote access plans for processing aquery fragment, based on resource cost. DB2 then chooses the plan it believeswill process the query with the least resource cost.
If any of the fragments are to be processed by data sources, DB2 submitsthese fragments to the data sources. After the data sources process thefragments, the results are retrieved and returned to DB2. If DB2 performedany part of the processing, it combines its results with the results retrievedfrom the data source. DB2 then returns all results to the client.
Related concepts:
v “Tuning query processing” in the Federated Systems Guide
v “Pushdown analysis” in the Federated Systems Guide
Related tasks:
v “Global optimization” in the Federated Systems Guide
Compensation
The DB2® federated server does not push down a query fragment if the datasource cannot process it, or if the federated server can process it faster thanthe data source can process it. For example, suppose that the SQL dialect of adata source does not support a CUBE grouping in the GROUP BY clause. Aquery that contains a CUBE grouping and references a table in that datasource is submitted to the federated server. DB2 does not pushdown theCUBE grouping to the data source, but processes the CUBE itself. The abilityby DB2 to process SQL that is not supported by a data source is calledcompensation.
DB2 federated systems
Chapter 1. Concepts 45
The federated server compensates for lack of functionality at the data sourcein two ways:v It can ask the data source to use one or more operations that are equivalent
to the DB2 function stated in the query. Suppose a data source does notsupport the cotangent (COT(x)) function, but supports the tangent (TAN(x))function. DB2 can ask the data source to perform the calculation(1/TAN(x)), which is equivalent to the cotangent (COT(x)) function.
v It can return the set of data to the federated server, and perform thefunction locally.
Each type of RDBMS supports a subset of the international SQL standard. Inaddition, some types of RDBMSs support SQL constructs that exceed thisstandard. An SQL dialect, is the totality of SQL that a type of RDBMSsupports. If an SQL construct is found in the DB2 SQL dialect, but not in adata source dialect, the federated server can implement this construct onbehalf of the data source.
The following examples show the ability of DB2 to compensate for differencesin SQL dialects:v DB2 SQL includes the clause, common-table-expression. In this clause, a
name can be specified by which all FROM clauses in a fullselect canreference a result set. The federated server will process acommon-table-expression for a data source, even though the SQL dialectused by the data source does not include common-table-expression.
v When connecting to a data source that does not support multiple opencursors within an application, the federated server can simulate thisfunction. The federated server does this by establishing separate,simultaneous connections to the data source. Similarly, the federated servercan simulate CURSOR WITH HOLD capability for a data source that doesnot provide that function.
With compensation, the federated server can support the full DB2 SQL dialectfor queries against data sources. Even data sources with weak SQL support orno SQL support. You must use the DB2 SQL dialect with a federated system,except in a pass-through session.
Related concepts:
v “The SQL Compiler and the query optimizer” on page 44v “Pass-through sessions” on page 46v “Function mappings and function templates” on page 56
Pass-through sessions
You can submit SQL statements directly to data sources by using a specialmode called pass-through. You submit SQL statements in the SQL dialect used
DB2 federated systems
46 SQL Reference, Volume 1
by the data source. Use a pass-through session when you want to perform anoperation that is not possible with the DB2® SQL/API. For example, use apass-through session to create a procedure, create an index, or performqueries in the native dialect of the data source.
Note: Currently, the data sources that support pass-through, supportpass-through using SQL. In the future, it is possible that data sources willsupport pass-though using a data source language other than SQL.
Similarly, you can use a pass-through session to perform actions that are notsupported by SQL, such as certain administrative tasks. However, you cannotuse a pass-through session to perform all administrative tasks. For example,you can create or drop tables at the data source, but you cannot start or stopthe remote database.
You can use both static and dynamic SQL in a pass-through session.
The federated server provides the following SQL statements to managepass-through sessions:
SET PASSTHRUOpens a pass-through session. When you issue another SETPASSTHRU statement to start a new pass-through session, the currentpass-through session is terminated.
SET PASSTHRU RESETTerminates the current pass-through session.
GRANT (Server Privileges)Grants a user, group, list of authorization IDs, or PUBLIC theauthority to initiate pass-through sessions to a specific data source.
REVOKE (Server Privileges)Revokes the authority to initiate pass-through sessions.
The following restrictions apply to pass-through sessions:v You must use the SQL dialect or language commands of the data source —
you cannot use the DB2 SQL dialect. As a result, you do not query anickname, but the data source objects directly.
v When performing UPDATE or DELETE operations in a pass-throughsession, you cannot use the WHERE CURRENT OF CURSOR condition.
Related concepts:
v “How client applications interact with data sources” in the Federated SystemsGuide
v “Using pass-through to query data sources directly” in the Federated SystemsGuide
DB2 federated systems
Chapter 1. Concepts 47
Related tasks:
v “Using pass-through with Oracle data sources” in the Federated SystemsGuide
v “Working with nicknames” in the Federated Systems Guide
Wrappers and wrapper modules
Wrappers are mechanisms by which the federated server interacts with datasources. The federated server uses routines stored in a library called a wrappermodule to implement a wrapper. These routines allow the federated server toperform operations such as connecting to a data source and retrieving datafrom it iteratively. Typically, the DB2® federated instance owner uses theCREATE WRAPPER statement to register a wrapper in the federated system.
You create one wrapper for each type of data source that you want to access.For example, suppose that you want to access three DB2 for z/OS™ databasetables, one DB2 for iSeries™ table, two Informix™ tables, and one Informixview. You need to create only two wrappers: one for the DB2 data sourceobjects and one for the Informix data source objects. Once these wrappers areregistered in the federated database, you can use these wrappers to accessother objects from those data sources. For example, you can use the DRDA®
wrapper with all DB2 family data source objects—DB2 for UNIX® andWindows, DB2 for z/OS and OS/390, DB2 for iSeries, and DB2 Server for VMand VSE.
You use the server definitions and nicknames to identify the specifics (name,location, and so forth) of each data source object.
There are wrappers for each supported data source. Some wrappers havedefault wrapper names. When you use the default name to create thewrapper, the federated server automatically picks up the data source libraryassociated with the wrapper.
Table 2. Default wrapper names for each data source.
Data source Default wrapper name(s)
DB2 Universal Database™ for UNIX andWindows®
DRDA
DB2 Universal Database for z/OS andOS/390®
DRDA
DB2 Universal Database for iSeries DRDA
DB2 Server for VM and VSE DRDA
Informix INFORMIX
Oracle SQLNet or Net8
DB2 federated systems
48 SQL Reference, Volume 1
Table 2. Default wrapper names for each data source. (continued)
Data source Default wrapper name(s)
Microsoft® SQL Server DJXMSSQL3, MSSQLODBC3
ODBC none
OLE DB OLEDB
Sybase CTLIB, DBLIB
BLAST none
Documentum none
Microsoft Excel none
Table-structured files none
XML none
A wrapper performs many tasks. Some of these tasks are:v It connects to the data source. The wrapper uses the standard connection
API of the data source.v It submits queries to the data source.
For data sources that do not support SQL, one of two actions will occur:– For data sources that support SQL, the query is submitted in SQL.– For data sources that do not support SQL, the query is translated into
the native query language of the source or into a series of source APIcalls.
v It receives results sets from the data source. The wrapper uses the datasource standard APIs for receiving results set.
v It responds to federated server queries about the default data typemappings for a data source. The wrapper contains the default typemappings that are used when nicknames are created for a data sourceobject. Data type mappings you create override the default data typemappings. User-defined data type mappings are stored in the globalcatalog.
v It responds to federated server queries about the default function mappingsfor a data source. The wrapper contains information the federated serverneeds to determine if DB2 functions are mapped to functions of the datasource, and how the functions are mapped. This information is used by theSQL Compiler to determine if the data source is able to perform the queryoperations. Function mappings you create override the default functiontype mappings. User-defined function mappings are stored in the globalcatalog.
Wrapper options are used to configure the wrapper or to define how DB2 usesthe wrapper. Currently there is only one wrapper option, DB2_FENCED. The
DB2 federated systems
Chapter 1. Concepts 49
DB2_FENCED wrapper option indicates if the wrapper is fenced or trusted byDB2. A fenced wrapper operates under some restrictions.
Related concepts:
v “Create the wrapper” in the Federated Systems Guide
v “Fast track to configuring your data sources” in the Federated Systems Guide
Related reference:
v “Wrapper options for federated systems” on page 774
Server definitions and server options
After wrappers are created for the data sources, the federated instance ownerdefines the data sources to the federated database. The instance ownersupplies a name to identify the data source, and other information thatpertains to the data source. If the data source is an RDBMS, this informationincludes:v The type and version of the RDBMS.v The database name for the data source on the RDBMS.v Metadata that is specific to the RDBMS
For example, a DB2® family data source can have multiple databases. Thedefinition must specify which database the federated server can connect to. Incontrast, an Oracle data source has one database, and the federated server canconnect to the database without knowing its name. The database name is notincluded in the federated server definition of an Oracle data source.
The name and other information that the instance owner supplies to thefederated server are collectively called a server definition. Data sources answerrequests for data and are servers in their own right.
The CREATE SERVER and ALTER SERVER statements are used to create andmodify a server definition.
Some of the information within a server definition is stored as server options.When you create server definitions, it is important to understand the optionsthat you can specify about the server. Some server options configure thewrapper and some affect the way DB2 uses the wrapper. Server options arespecified as parameters in the CREATE SERVER and ALTER SERVERstatements.
Server options are set to values that persist over successive connections to thedata source. These values are stored in the global catalog. For example, thename for the data source on the RDBMS is set in the NODE server option.
DB2 federated systems
50 SQL Reference, Volume 1
Some data sources have multiple databases on each instance. For these datasource, the name of the database which the federated server connects to is setin the DBNAME server option.
To set a server option value temporarily, use the SET SERVER OPTIONstatement, This statement overrides the value for the duration of a singleconnection to the federated database. The overriding value does not get storedin the global catalog.
Related concepts:
v “Supply the server definition” in the Federated Systems Guide
Related reference:
v “Server options for federated systems” on page 764
User mappings and user options
When a federated server needs to pushdown a request to a data source, theserver must first establish a connection to the data source. The server doesthis by using a valid user ID and password to that data source. By default, thefederated server attempts to access the data source with the user ID andpassword that are used to connect to DB2. If the user ID and password arethe same between the federated server and the data source, the connection isestablished. If the user ID and password to access the federated server differsfrom the user ID and password to access a data source, you must define anassociation between the two authorizations. Once you define the association,distributed requests can be sent to the data source. This association is called auser mapping.
You define and modify user mappings with the CREATE USER MAPPINGand ALTER USER MAPPING statements. These statements includeparameters, called user options, which values related to authorization areassigned to. For example, suppose that a user has the same ID, but differentpasswords, for the federated database and a data source. For the user toaccess the data source, it is necessary to map the passwords to one another.You use the CREATE USER MAPPING statement and the user optionREMOTE_PASSWORD to map the passwords. Use the ALTER USERMAPPING statement to modify an existing user mapping.
Related concepts:
v “Create the user mappings and test the connection to the data source” inthe Federated Systems Guide
Related reference:
v “ALTER USER MAPPING statement” in the SQL Reference, Volume 2
DB2 federated systems
Chapter 1. Concepts 51
v “CREATE USER MAPPING statement” in the SQL Reference, Volume 2
Nicknames and data source objects
After you create the server definitions and user mappings, the federatedinstance owner creates the nicknames. A nickname is an identifier that is usedto reference the object located at the data sources that you want to access. Theobjects that nicknames identify are referred to as data source objects.
The following table shows the data source objects you can reference when youcreate a nickname.
Table 3. Data sources and the objects that you can create a nickname for
Data source Objects you can reference
DB2® for UNIX® and Windows® nicknames, summary tables, tables, views
DB2 for z/OS™ and OS/390® tables, views
DB2 for iSeries™ tables, views
DB2 Server for VM and VSE tables, views
Informix™ tables, views, synonyms
Microsoft® SQL Server tables, views
ODBC tables, views
Oracle tables, views
Sybase tables, views
BLAST FASTA files indexed for BLAST searchalgorithms
document management software objects and registered tables in aDocumentum Docbase
Microsoft Excel .xls files (only the first sheet in theworkbook is accessed)
table-structured files .txt files (text files that meet a very specificformat)
XML-tagged files sets of items in an XML document
Nicknames are not alternative names for data source objects in the same waythat aliases are alternative names. They are pointers by which the federatedserver references these objects. Nicknames are typically defined with theCREATE NICKNAME statement.
When an end user or a client application submits a distributed request to thefederated server, the request does not need to specify the data sources.Instead, it references the data source objects by their nicknames. The
DB2 federated systems
52 SQL Reference, Volume 1
nicknames are mapped to specific objects at the data source. The mappingseliminate the need to qualify the nicknames by data source names. Thelocation of the data source objects is transparent to the end user or the clientapplication.
Suppose if you define the nickname DEPT to represent an Informix databasetable called NFX1.PERSON.DEPT. The statement SELECT * FROM DEPT isallowed from the federated server. However, the statement SELECT * FROMNFX1.PERSON.DEPT is not allowed from the federated server (except in apass-through session).
When you create a nickname for a data source object, metadata about theobject is added to the global catalog. The query optimizer uses this metadata,and the information in the wrapper, to facilitate access to the data sourceobject. For example, if the nickname is for a table that has an index, the globalcatalog contains information about the index. The wrapper contains themappings between the DB2 data types and the data source data types.
Currently, you cannot execute DB2 utility operations (LOAD, REORG,REORGCHK, IMPORT, RUNSTATS, and so on) on nicknames.
Related concepts:
v “Create nicknames for each data source object” in the Federated SystemsGuide
Related reference:
v “CREATE NICKNAME statement” in the SQL Reference, Volume 2
Column options
You can supply the global catalog with additional metadata information aboutthe nicknamed object. This metadata describes values in certain columns ofthe data source object. You assign this metadata to parameters that are calledcolumn options. The column options tell the wrapper to handle the data in acolumn differently than it normally would handle it. Column options are usedto provide other information to the wrapper as well. For example for XMLdata sources, a column option is used to tell the wrapper the XPathexpression to use when the wrapper parses the column out of the XMLdocument. The SQL Complier and query optimizer use the metadata todevelop better plans for accessing the data.
DB2® treats the object that a nickname references as if it is a table. As a result,you can set column options for any data source object that you create anickname for. Some column options are designed for specific types of datasources and can only be applied to those data sources.
DB2 federated systems
Chapter 1. Concepts 53
Suppose that a data source has a collating sequence that differs from thefederated database collating sequence. The federated server typically wouldnot sort any columns containing character data at the data source. It wouldreturn the data to the federated database and perform the sort locally.However, suppose that the column is a character data type (CHAR andVARCHAR) and contains only numeric characters (’0’,’1’,...,’9’). You canindicate this by assigning a value of ’Y’ to the NUMERIC_STRING columnoption. This gives the DB2 query optimizer the option of performing the sortat the data source. If the sort is performed remotely, you can avoid theoverhead of porting the data to the federated server and performing the sortlocally.
You can define column options in the CREATE NICKNAME and ALTERNICKNAME statements.
Related tasks:
v “Working with nicknames” in the Federated Systems Guide
Related reference:
v “Column options for federated systems” on page 762
Data type mappings
The data types at the data source must map to corresponding DB2® datatypes so that the federated server can retrieve data from data sources. Formost data sources, the default type mappings are in the wrappers. The defaulttype mappings for DB2 data sources are in the DRDA® wrapper. The defaulttype mappings for Informix™ are in the INFORMIX wrapper, and so forth.
For some non-relational data sources, you must specify data type informationin the CREATE NICKNAME statement.
The corresponding DB2 for UNIX® and Windows® data types must bespecified for each column of the data source object when the nickname iscreated. Each column must be mapped to a particular field or column in thedata source object.
For example:v The Oracle type FLOAT maps by default to the DB2 type DOUBLE.v The Oracle type DATE maps to the DB2 type DB2 TIMESTAMP.v The DB2 for z/OS™ type DATE maps by default to the DB2 type DATE.
When values from a data source column are returned to the federateddatabase, the values conform fully to the DB2 data type that the data sourcecolumn is mapped to. If this is a default mapping, the values also conform
DB2 federated systems
54 SQL Reference, Volume 1
fully to the data source type in the mapping. For example, suppose an Oracletable with a FLOAT column is defined to the federated database. The defaultmapping of Oracle FLOAT to DB2 DOUBLE automatically applies to thatcolumn. Consequently, the values that are returned from the column willconform fully to both FLOAT and DOUBLE.
For some wrappers, you can change the format or length of values that arereturned. You do this by changing the DB2 data type that the values mustconform to. For example, the Oracle data type DATE is used as a time stamp;the Oracle DATE data type contains century, year, month, day, hour, minute,and second. By default, the Oracle DATE data type maps to the DB2TIMESTAMP data type. Suppose that several Oracle table columns have adata type of DATE. You want queries of these columns to return only thehour, minute, and second. You can override the default data type mapping sothat the Oracle DATE data type maps to the DB2 TIME data type. WhenOracle DATE columns are queried, only the time portion of the time stampvalues is returned to DB2.
Use the CREATE TYPE MAPPING statement to create:v A data type mapping that overrides a default data type mappingv A data type mapping for which there currently is no mapping. For
example, when a new built-in type is available at the data source, or whenthere is a user-defined type at the data source that you want to map to.
In the CREATE TYPE MAPPING statement, you can specify if the mappingapplies each time that you access that data source, or if the mapping appliesto a specific server.
Use the ALTER TYPE MAPPING statement to change a type mapping thatyou originally created with the CREATE TYPE MAPPING statement. TheALTER TYPE MAPPING statement cannot be used to change the default typemappings.
To modify a data type mapping for a specific column of a specific data sourceobject, use the column option parameters in the ALTER NICKNAMEstatement. This statement enables you to specify data type mappings forindividual tables, views, or other data source objects.
If you change a type mapping, nicknames created before the type mappingchange do not reflect the new mapping.
Unsupported data types:
DB2 federated servers do not support:v LONG VARCHAR
DB2 federated systems
Chapter 1. Concepts 55
v LONG VARGRAPHICv DATALINKv User-defined data types (UDTs) created at the data source
You cannot create a user-defined mapping for these data types. However, youcreate a nickname for view at the data source that is identical to the table thatcontains the user-defined data types. The view must ’cast’ the user-definedtype column to the built-in, or system, type.
A nickname can be created for a remote table that contains LONG VARCHARcolumns. However, the results will be mapped to a local DB2 data type that isnot LONG VARCHAR.
Related concepts:
v “Modifying wrappers” in the Federated Systems Guide
Related tasks:
v “Modifying default data type mappings” in the Federated Systems Guide
Related reference:
v “ALTER NICKNAME statement” in the SQL Reference, Volume 2
v “CREATE TYPE MAPPING statement” in the SQL Reference, Volume 2
v “Default forward data type mappings” on page 775
Function mappings and function templates
For the federated server to recognize a data source function, the function mustbe mapped against an existing DB2® function. DB2 supplies default mappingsbetween existing built-in data source functions and built-in DB2 functions. Formost data sources, the default function mappings are in the wrappers. Thedefault function mappings from DB2 for UNIX® and Windows® functions toDB2 for z/OS™ functions are in the DRDA® wrapper. The default functionmappings from DB2 for UNIX and Windows functions to Sybase functions arein the CTLIB and DBLIB wrappers, and so forth.
To use a data source function that the federated server does not recognize,you must create a function mapping. The mapping you create is between thedata source function and a counterpart function at the federated database.Function mappings are typically used when a new built-in function and anew user-defined function becomes available at the data source. Functionmappings are also used when a DB2 counterpart function does not exist, youmust create one on the DB2 federated server that meets the followingrequirements:v If the data source function has input parameters:
DB2 federated systems
56 SQL Reference, Volume 1
– The DB2 counterpart function must have the same number of inputparameters that the data source function has.
– The data types of the input parameters for the DB2 counterpart functionmust be compatible with the corresponding data types of the inputparameters for data source function.
v If the data source function has no input parameters:– The DB2 counterpart function cannot have any input parameters.
Note: When you create a function mapping, it is possible that the returnvalues from a function evaluated at the data source will be different than thereturn values from a compatible function evaluated at the DB2 federateddatabase. DB2 will use the function mapping, but it might result in an SQLsyntax error or unexpected results.
The DB2 counterpart function can be either a complete function or a functiontemplate.
A function template is a DB2 function that you create to invoke a function on adata source. The federated server recognizes a data source function whenthere is a mapping between the data source function and a counterpartfunction at the federated database. You can create a function template to act asthe counterpart when no counterpart exists.
However, unlike a regular function, a function template has no executablecode. After you create a function template, you must then create the functionmapping between the template and the data source function. You creat afunction template with the CREATE FUNCTION statement, using the ASTEMPLATE parameter. You create a function mapping by using the CREATEFUNCTION MAPPING statement. When the federated server receives querieswhich specify the function template, the federated server will invoke the datasource function.
Related concepts:
v “Function mappings options” on page 57
Related reference:
v “Function mapping options for federated systems” on page 763
Function mappings options
The CREATE FUNCTION MAPPING statement includes parameters calledfunction mapping options. You can assign values that pertain to the mapping, orto the data source function within the mapping. For example, you can includeestimated statistics on the overhead that will be consumed when the data
DB2 federated systems
Chapter 1. Concepts 57
source function is invoked. The query optimizer uses these estimates to decideif the function should be invoked by the data source or by the DB2® federateddatabase.
Related reference:
v “Function mapping options for federated systems” on page 763
Index specifications
When you create a nickname for a data source table, information about anyindexes that the data source table has is added to the global catalog. Thequery optimizer uses this information to expedite the processing ofdistributed requests. The catalog information about a data source index is aset of metadata, and is called an index specification. A federated server does notcreate an index specification when you create a nickname for:v A table that has no indexes.v A view, which typically does not have any index information stored in the
remote catalog.v A data source object that does not have a remote catalog from which the
federated server can obtain the index information.
Note: You cannot create an index specification for an Informix™ view.
Suppose that a nickname is created for a table that has no index, but the tableacquires an index later. Suppose that a table acquires a new index, in additionto the ones it had when the nickname was created. Because index informationis supplied to the global catalog at the time the nickname is created, thefederated server is unaware of the new indexes. Similarly, when a nickname iscreated for a view, the federated server is unaware of the underlying table(and its indexes) from which the view was generated. In these circumstances,you can supply the necessary index information to the global catalog. You cancreate an index specification for tables that have no indexes. The indexspecification tells the query optimizer which column or columns in the tableto search on to find data quickly.
In a federated system, you use the CREATE INDEX statement against anickname to supply index specification information to the global catalog. If atable acquires a new index, the CREATE INDEX statement that you create willreference the nickname for the table and contain information about the indexof the data source table. If a nickname is created for a view, the CREATEINDEX statement that you create will reference the nickname for the view andcontain information about the index of the underlying table for the view.
Related concepts:
v “The SQL Compiler and the query optimizer” on page 44
DB2 federated systems
58 SQL Reference, Volume 1
v “Overview of the tasks to set up a federated system” in the FederatedSystems Guide
v “Modifying wrappers” in the Federated Systems Guide
Related reference:
v “CREATE INDEX statement” in the SQL Reference, Volume 2
DB2 federated systems
Chapter 1. Concepts 59
DB2 federated systems
60 SQL Reference, Volume 1
Chapter 2. Language elements
This chapter describes the language elements that are common to many SQLstatements:v “Characters”v “Tokens” on page 63v “Identifiers” on page 65v “Data types” on page 92v “Constants” on page 143v “Special registers” on page 146v “Functions” on page 168v “Methods” on page 178v “Expressions” on page 187v “Predicates” on page 225
Characters
The basic symbols of keywords and operators in the SQL language aresingle-byte characters that are part of all IBM character sets. Characters of thelanguage are classified as letters, digits, or special characters.
A letter is any of the 26 uppercase (A through Z) and 26 lowercase (a throughz) letters plus the three characters ($, #, and @), which are included forcompatibility with host database products (for example, in code page 850, $ isat X'24', # is at X'23', and @ is at X'40'). Letters also include the alphabeticsfrom the extended character sets. Extended character sets contain additionalalphabetic characters; for example, those with diacritical marks (u is anexample of a diacritical mark). The available characters depend on the codepage in use.
A digit is any of the characters 0 through 9.
A special character is any of the characters listed below:
blank − minus sign" double quotation
mark. period
% percent / slash& ampersand : colon
© Copyright IBM Corp. 1993 - 2002 61
' apostrophe or singlequotation mark
; semicolon
( left parenthesis < less than) right parenthesis = equals* asterisk > greater than+ plus sign ? question mark, comma _ underline or
underscore| vertical bar ^ caret! exclamation mark
All multi-byte characters are treated as letters, except for the double-byteblank, which is a special character.
Characters
62 SQL Reference, Volume 1
Tokens
Tokens are the basic syntactical units of SQL. A token is a sequence of one ormore characters. A token cannot contain blank characters, unless it is a stringconstant or a delimited identifier, which may contain blanks.
Tokens are classified as ordinary or delimiter:v An ordinary token is a numeric constant, an ordinary identifier, a host
identifier, or a keyword.Examples
1 .1 +2 SELECT E 3
v A delimiter token is a string constant, a delimited identifier, an operatorsymbol, or any of the special characters shown in the syntax diagrams. Aquestion mark is also a delimiter token when it serves as a parametermarker.Examples
, ’string’ "fld1" = .
Spaces: A space is a sequence of one or more blank characters. Tokens otherthan string constants and delimited identifiers must not include a space. Anytoken may be followed by a space. Every ordinary token must be followed bya space or a delimiter token if allowed by the syntax.
Comments: Static SQL statements may include host language comments orSQL comments. Either type of comment may be specified wherever a spacemay be specified, except within a delimiter token or between the keywordsEXEC and SQL. SQL comments are introduced by two consecutive hyphens(--) and ended by the end of the line.
Case sensitivity: Any token may include lowercase letters, but a lowercaseletter in an ordinary token is folded to uppercase, except for host variables inthe C language, which has case-sensitive identifiers. Delimiter tokens arenever folded to uppercase. Thus, the statement:
select * from EMPLOYEE where lastname = ’Smith’;
is equivalent, after folding, to:SELECT * FROM EMPLOYEE WHERE LASTNAME = ’Smith’;
Multi-byte alphabetic letters are not folded to uppercase. Single-bytecharacters (a to z) are folded to uppercase.
Related reference:
v “How SQL statements are invoked” in the SQL Reference, Volume 2
Tokens
Chapter 2. Language elements 63
v “PREPARE statement” in the SQL Reference, Volume 2
Tokens
64 SQL Reference, Volume 1
Identifiers
An identifier is a token that is used to form a name. An identifier in an SQLstatement is either an SQL identifier or a host identifier.v SQL identifiers
There are two types of SQL identifiers: ordinary and delimited.– An ordinary identifier is a letter followed by zero or more characters, each
of which is an uppercase letter, a digit, or the underscore character. Anordinary identifier should not be identical to a reserved word.Examples
WKLYSAL WKLY_SAL
– A delimited identifier is a sequence of one or more characters enclosed bydouble quotation marks. Two consecutive quotation marks are used torepresent one quotation mark within the delimited identifier. In this wayan identifier can include lowercase letters.Examples
"WKLY_SAL" "WKLY SAL" "UNION" "wkly_sal"
Character conversion of identifiers created on a double-byte code page, butused by an application or database on a multi-byte code page, may requirespecial consideration: After conversion, such identifiers may exceed thelength limit for an identifier.
v Host identifiersA host identifier is a name declared in the host program. The rules forforming a host identifier are the rules of the host language. A host identifiershould not be greater than 255 characters in length and should not beginwith SQL or DB2 (in uppercase or lowercase characters).
Naming conventions and implicit object name qualificationsThe rules for forming the name of an object depend on the object type.Database object names may be made up of a single identifier, or they may beschema-qualified objects made up of two identifiers. Schema-qualified objectnames may be specified without the schema name; in such cases, the schemaname is implicit.
In dynamic SQL statements, a schema-qualified object name implicitly usesthe CURRENT SCHEMA special register value as the qualifier for unqualifiedobject name references. By default it is set to the current authorization ID. Ifthe dynamic SQL statement is contained in a package that exhibits bind,define, or invoke behaviour, the CURRENT SCHEMA special register is notused for qualification. In a bind behaviour package, the package defaultqualifier is used as the value for implicit qualification of unqualified objectreferences. In a define behaviour package, the authorization ID of the routine
Identifiers
Chapter 2. Language elements 65
definer is used as the value for implicit qualification of unqualified objectreferences within that routine. In an invoke behaviour package, the statementauthorization ID in effect when the routine is invoked is used as the value forimplicit qualification of unqualified object references within dynamic SQLstatements within that routine. For more information, see “Dynamic SQLcharacteristics at run time” on page 73.
In static SQL statements, the QUALIFIER precompile/bind option implicitlyspecifies the qualifier for unqualified database object names. By default, thisvalue is set to the package authorization ID.
The following object names, when used in the context of an SQL procedure,are permitted to use only the characters allowed in an ordinary identifier,even if the names are delimited:v condition-namev labelv parameter-namev procedure-namev SQL-variable-namev statement-name
The syntax diagrams use different terms for different types of names. Thefollowing list defines these terms.
alias-name A schema-qualified name that designates analias.
attribute-name An identifier that designates an attribute of astructured data type.
authorization-name An identifier that designates a user or agroup:v Valid characters are A through Z, a through
z, 0 through 9, #, @, $, and _.v The name must not begin with the
characters 'SYS', 'IBM', or 'SQL'.v The name must not be: ADMINS, GUESTS,
LOCAL, PUBLIC, or USERS.v A delimited authorization ID must not
contain lowercase letters.
bufferpool-name An identifier that designates a bufferpool.
column-name A qualified or unqualified name thatdesignates a column of a table or view. The
Naming conventions and implicit object name qualifications
66 SQL Reference, Volume 1
qualifier is a table name, a view name, anickname, or a correlation name.
condition-name An identifier that designates a condition in anSQL procedure.
constraint-name An identifier that designates a referentialconstraint, primary key constraint, uniqueconstraint, or a table check constraint.
correlation-name An identifier that designates a result table.
cursor-name An identifier that designates an SQL cursor.For host compatibility, a hyphen charactermay be used in the name.
data-source-name An identifier that designates a data source.This identifier is the first part of a three-partremote object name.
descriptor-name A colon followed by a host identifier thatdesignates an SQL descriptor area (SQLDA).For the description of a host identifier, see“References to host variables” on page 83.Note that a descriptor name never includes anindicator variable.
distinct-type-name A qualified or unqualified name thatdesignates a distinct type. An unqualifieddistinct type name in an SQL statement isimplicitly qualified by the database manager,depending on context.
event-monitor-name An identifier that designates an event monitor.
function-mapping-name An identifier that designates a functionmapping.
function-name A qualified or unqualified name thatdesignates a function. An unqualified functionname in an SQL statement is implicitlyqualified by the database manager, dependingon context.
group-name An unqualified identifier that designates atransform group defined for a structured type.
host-variable A sequence of tokens that designates a hostvariable. A host variable includes at least onehost identifier, explained in “References tohost variables” on page 83.
Naming conventions and implicit object name qualifications
Chapter 2. Language elements 67
index-name A schema-qualified name that designates anindex or an index specification.
label An identifier that designates a label in an SQLprocedure.
method-name An identifier that designates a method. Theschema context for a method is determined bythe schema of the subject type (or a supertypeof the subject type) of the method.
nickname A schema-qualified name that designates afederated server reference to a table or a view.
db-partition-group-name An identifier that designates a databasepartition group.
package-name A schema-qualified name that designates apackage. If a package has a version ID that isnot the empty string, the package name alsoincludes the version ID at the end of thename, in the form: schema-id.package-id.version-id.
parameter-name An identifier that designates a parameter thatcan be referenced in a procedure, user-definedfunction, method, or index extension.
procedure-name A qualified or unqualified name thatdesignates a procedure. An unqualifiedprocedure name in an SQL statement isimplicitly qualified by the database manager,depending on context.
remote-authorization-name An identifier that designates a data sourceuser. The rules for authorization names varyfrom data source to data source.
remote-function-name A name that designates a function registeredto a data source database.
remote-object-name A three-part name that designates a datasource table or view, and that identifies thedata source in which the table or view resides.The parts of this name are data-source-name,remote-schema-name, and remote-table-name.
remote-schema-name A name that designates the schema to which adata source table or view belongs. This nameis the second part of a three-part remote objectname.
Naming conventions and implicit object name qualifications
68 SQL Reference, Volume 1
remote-table-name A name that designates a table or view at adata source. This name is the third part of athree-part remote object name.
remote-type-name A data type supported by a data sourcedatabase. Do not use the long form for built-intypes (use CHAR instead of CHARACTER, forexample).
savepoint-name An identifier that designates a savepoint.
schema-name An identifier that provides a logical groupingfor SQL objects. A schema name used as aqualifier for the name of an object may beimplicitly determined:v from the value of the CURRENT SCHEMA
special registerv from the value of the QUALIFIER
precompile/bind optionv on the basis of a resolution algorithm that
uses the CURRENT PATH special registerv on the basis of the schema name for another
object in the same SQL statement.
To avoid complications, it is recommendedthat the name SESSION not be used as aschema, except as the schema for declaredglobal temporary tables (which must use theschema name SESSION).
server-name An identifier that designates an applicationserver. In a federated system, the server namealso designates the local name of a datasource.
specific-name A qualified or unqualified name thatdesignates a specific name. An unqualifiedspecific name in an SQL statement isimplicitly qualified by the database manager,depending on context.
SQL-variable-name The name of a local variable in an SQLprocedure statement. SQL variable names canbe used in other SQL statements where a hostvariable name is allowed. The name can bequalified by the label of the compoundstatement that declared the SQL variable.
Naming conventions and implicit object name qualifications
Chapter 2. Language elements 69
statement-name An identifier that designates a prepared SQLstatement.
supertype-name A qualified or unqualified name thatdesignates the supertype of a type. Anunqualified supertype name in an SQLstatement is implicitly qualified by thedatabase manager, depending on context.
table-name A schema-qualified name that designates atable.
tablespace-name An identifier that designates a table space.
trigger-name A schema-qualified name that designates atrigger.
type-mapping-name An identifier that designates a data typemapping.
type-name A qualified or unqualified name thatdesignates a type. An unqualified type namein an SQL statement is implicitly qualified bythe database manager, depending on context.
typed-table-name A schema-qualified name that designates atyped table.
typed-view-name A schema-qualified name that designates atyped view.
view-name A schema-qualified name that designates aview.
wrapper-name An identifier that designates a wrapper.
AliasesA table alias can be thought of as an alternative name for a table or a view. Atable or view, therefore, can be referred to in an SQL statement by its name orby a table alias.
An alias can be used wherever a table or a view name can be used. An aliascan be created even if the object does not exist (although it must exist by thetime a statement referring to it is compiled). It can refer to another alias if nocircular or repetitive references are made along the chain of aliases. An aliascan only refer to a table, view, or alias within the same database. An aliasname cannot be used where a new table or view name is expected, such as inthe CREATE TABLE or CREATE VIEW statements; for example, if the aliasname PERSONNEL has been created, subsequent statements such as CREATETABLE PERSONNEL... will return an error.
Naming conventions and implicit object name qualifications
70 SQL Reference, Volume 1
The option of referring to a table or a view by an alias is not explicitly shownin the syntax diagrams, or mentioned in the descriptions of SQL statements.
A new unqualified alias cannot have the same fully-qualified name as anexisting table, view, or alias.
The effect of using an alias in an SQL statement is similar to that of textsubstitution. The alias, which must be defined by the time that the SQLstatement is compiled, is replaced at statement compilation time by thequalified base table or view name. For example, if PBIRD.SALES is an aliasfor DSPN014.DIST4_SALES_148, then at compilation time:
SELECT * FROM PBIRD.SALES
effectively becomesSELECT * FROM DSPN014.DIST4_SALES_148
In a federated system, the aforementioned uses and restrictions apply, notonly to table aliases, but also to aliases for nicknames. Thus, a nickname’salias can be used instead of the nickname in an SQL statement; an alias can becreated for a nickname that does not yet exist, provided that the nickname iscreated before statements that reference the alias are compiled; an alias for anickname can refer to another alias for that nickname; and so on.
For syntax toleration of applications running under other relational databasemanagement systems, SYNONYM can be used in place of ALIAS in theCREATE ALIAS and DROP ALIAS statements.
Authorization IDs and authorization namesAn authorization ID is a character string that is obtained by the databasemanager when a connection is established between the database manager andeither an application process or a program preparation process. It designates aset of privileges. It may also designate a user or a group of users, but thisproperty is not controlled by the database manager.
Authorization IDs are used by the database manager to provide:v Authorization checking of SQL statementsv A default value for the QUALIFIER precompile/bind option and the
CURRENT SCHEMA special register. The authorization ID is also includedin the default CURRENT PATH special register and the FUNCPATHprecompile/bind option.
An authorization ID applies to every SQL statement. The authorization IDthat applies to a static SQL statement is the authorization ID that is usedduring program binding. The authorization ID that applies to a dynamic SQL
Aliases
Chapter 2. Language elements 71
statement is based on the DYNAMICRULES option supplied at bind time, andon the current runtime environment for the package issuing the dynamic SQLstatement:v In a package that has bind behavior, the authorization ID used is the
authorization ID of the package owner.v In a package that has define behavior, the authorization ID used is the
authorization ID of the corresponding routine’s definer.v In a package that has run behavior, the authorization ID used is the current
authorization ID of the user executing the package.v In a package that has invoke behavior, the authorization ID used is the
authorization ID currently in effect when the routine is invoked. This iscalled the runtime authorization ID.
For more information, see “Dynamic SQL characteristics at run time” onpage 73.
An authorization name specified in an SQL statement should not be confusedwith the authorization ID of the statement. An authorization name is anidentifier that is used within various SQL statements. An authorization nameis used in the CREATE SCHEMA statement to designate the owner of theschema. An authorization name is used in the GRANT and REVOKEstatements to designate a target of the grant or revoke operation. Grantingprivileges to X means that X (or a member of the group X) will subsequentlybe the authorization ID of statements that require those privileges.
Examples:
v Assume that SMITH is the user ID and the authorization ID that thedatabase manager obtained when a connection was established with theapplication process. The following statement is executed interactively:
GRANT SELECT ON TDEPT TO KEENE
SMITH is the authorization ID of the statement. Therefore, in a dynamicSQL statement, the default value of the CURRENT SCHEMA specialregister is SMITH, and in static SQL, the default value of the QUALIFIERprecompile/bind option is SMITH. The authority to execute the statement ischecked against SMITH, and SMITH is the table-name implicit qualifierbased on qualification rules described in “Naming conventions and implicitobject name qualifications” on page 65.
KEENE is an authorization name specified in the statement. KEENE isgiven the SELECT privilege on SMITH.TDEPT.
v Assume that SMITH has administrative authority and is the authorizationID of the following dynamic SQL statements, with no SET SCHEMAstatement issued during the session:
DROP TABLE TDEPT
Authorization IDs and authorization names
72 SQL Reference, Volume 1
Removes the SMITH.TDEPT table.DROP TABLE SMITH.TDEPT
Removes the SMITH.TDEPT table.DROP TABLE KEENE.TDEPT
Removes the KEENE.TDEPT table. Note that KEENE.TDEPT andSMITH.TDEPT are different tables.
CREATE SCHEMA PAYROLL AUTHORIZATION KEENE
KEENE is the authorization name specified in the statement that creates aschema called PAYROLL. KEENE is the owner of the schema PAYROLL andis given CREATEIN, ALTERIN, and DROPIN privileges, with the ability togrant them to others.
Dynamic SQL characteristics at run timeThe BIND option DYNAMICRULES determines the authorization ID that isused for checking authorization when dynamic SQL statements are processed.In addition, the option also controls other dynamic SQL attributes, such as theimplicit qualifier that is used for unqualified object references, and whethercertain SQL statements can be invoked dynamically.
The set of values for the authorization ID and other dynamic SQL attributes iscalled the dynamic SQL statement behavior. The four possible behaviors arerun, bind, define, and invoke. As the following table shows, the combinationof the value of the DYNAMICRULES BIND option and the runtimeenvironment determines which of the behaviors is used. DYNAMICRULESRUN, which implies run behavior, is the default.
Table 4. How DYNAMICRULES and the runtime environment determine dynamic SQLstatement behavior
DYNAMICRULES value Behavior of dynamic SQL statements
Standalone programenvironment
Routine environment
BIND Bind behavior Bind behavior
RUN Run behavior Run behavior
DEFINEBIND Bind behavior Define behavior
DEFINERUN Run behavior Define behavior
INVOKEBIND Bind behavior Invoke behavior
INVOKERUN Run behavior Invoke behavior
Run behavior DB2 uses the authorization ID of the user (theID that initially connected to DB2) executingthe package as the value to be used for
Authorization IDs and authorization names
Chapter 2. Language elements 73
authorization checking of dynamic SQLstatements and for the initial value used forimplicit qualification of unqualified objectreferences within dynamic SQL statements.
Bind behavior At run time, DB2 uses all the rules that applyto static SQL for authorization andqualification. It takes the authorization ID ofthe package owner as the value to be used forauthorization checking of dynamic SQLstatements, and the package default qualifierfor implicit qualification of unqualified objectreferences within dynamic SQL statements.
Define behavior Define behavior applies only if the dynamicSQL statement is in a package that is runwithin a routine context, and the package wasbound with DYNAMICRULES DEFINEBINDor DYNAMICRULES DEFINERUN. DB2 usesthe authorization ID of the routine definer(not the routine’s package binder) as the valueto be used for authorization checking ofdynamic SQL statements, and for implicitqualification of unqualified object referenceswithin dynamic SQL statements within thatroutine.
Invoke behavior Invoke behavior applies only if the dynamicSQL statement is in a package that is runwithin a routine context, and the package wasbound with DYNAMICRULES INVOKEBINDor DYNAMICRULES INVOKERUN. DB2 usesthe statement authorization ID in effect whenthe routine is invoked as the value to be usedfor authorization checking of dynamic SQL,and for implicit qualification of unqualifiedobject references within dynamic SQLstatements within that routine. This issummarized by the following table.
Invoking Environment ID Used
any static SQL implicit or explicit value of the OWNER of thepackage the SQL invoking the routine camefrom
used in definition of view or trigger definer of the view or trigger
Dynamic SQL characteristics at run time
74 SQL Reference, Volume 1
Invoking Environment ID Used
dynamic SQL from a bind behavior package implicit or explicit value of the OWNER of thepackage the SQL invoking the routine camefrom
dynamic SQL from a run behavior package ID used to make the initial connection to DB2
dynamic SQL from a define behavior package definer of the routine that uses the packagethat the SQL invoking the routine came from
dynamic SQL from an invoke behavior package the current authorization ID invoking theroutine
Restricted statements when run behavior does not apply
When bind, define, or invoke behavior is in effect, you cannot use thefollowing dynamic SQL statements: GRANT, REVOKE, ALTER, CREATE,DROP, COMMENT, RENAME, SET INTEGRITY, SET EVENT MONITORSTATE; or queries that reference a nickname.
Considerations regarding the DYNAMICRULES option
The CURRENT SCHEMA special register cannot be used to qualifyunqualified object references within dynamic SQL statements executed frombind, define or invoke behavior packages. This is true even after you issue theSET CURRENT SCHEMA statement to change the CURRENT SCHEMAspecial register; the register value is changed but not used.
In the event that multiple packages are referenced during a single connection,all dynamic SQL statements prepared by those packages will exhibit thebehavior specified by the DYNAMICRULES option for that specific packageand the environment in which they are used.
It is important to keep in mind that when a package exhibits bind behavior,the binder of the package should not have any authorities granted that theuser of the package should not receive, because a dynamic statement will beusing the authorization ID of the package owner. Similarly, when a packageexhibits define behavior, the definer of the routine should not have anyauthorities granted that the user of the package should not receive.
Authorization IDs and statement preparationIf the VALIDATE BIND option is specified at bind time, the privilegesrequired to manipulate tables and views must also exist at bind time. If theseprivileges or the referenced objects do not exist, and the SQLERRORNOPACKAGE option is in effect, the bind operation will be unsuccessful. Ifthe SQLERROR CONTINUE option is specified, the bind operation will besuccessful, and any statements in error will be flagged. Any attempt toexecute such a statement will result in an error.
Dynamic SQL characteristics at run time
Chapter 2. Language elements 75
If a package is bound with the VALIDATE RUN option, all normal bindprocessing is completed, but the privileges required to use the tables andviews that are referenced in the application need not exist yet. If a requiredprivilege does not exist at bind time, an incremental bind operation isperformed whenever the statement is first executed in an application, and allprivileges required for the statement must exist. If a required privilege doesnot exist, execution of the statement is unsuccessful.
Authorization checking at run time is performed using the authorization ID ofthe package owner.
Column namesThe meaning of a column name depends on its context. A column name can beused to:v Declare the name of a column, as in a CREATE TABLE statement.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 columnin the group or intermediate result table to which the function is applied.For example, MAX(SALARY) applies the function MAX to all values ofthe column SALARY in a group.
– In a GROUP BY or ORDER BY clause, a column name specifies allvalues in the intermediate result table to which the clause is applied. Forexample, ORDER BY DEPT orders an intermediate result table by thevalues of the column DEPT.
– In an expression, a search condition, or a scalar function, a column namespecifies a value for each row or group to which the construct is applied.For example, when the search condition CODE = 20 is applied to somerow, the value specified by the column name CODE is the value of thecolumn CODE in that row.
v Temporarily rename a column, as in the correlation-clause of a table-referencein a FROM clause.
Qualified column namesA qualifier for a column name may be a table, view, nickname, alias, orcorrelation name.
Whether a column name may be qualified depends on its context:v Depending on the form of the COMMENT ON statement, a single column
name may need to be qualified. Multiple column names must beunqualified.
v Where the column name specifies values of the column, it may be qualifiedat the user’s option.
Authorization IDs and statement preparation
76 SQL Reference, Volume 1
v In the assignment-clause of an UPDATE statement, it may be qualified atthe user’s option.
v In all other contexts, a column name must not be qualified.
Where a qualifier is optional, it can serve two purposes. They are describedunder “Column name qualifiers to avoid ambiguity” on page 79 and “Columnname qualifiers in correlated references” on page 81.
Correlation namesA correlation name can be defined in the FROM clause of a query and in thefirst clause of an UPDATE or DELETE statement. For example, the clauseFROM X.MYTABLE Z establishes Z as a correlation name for X.MYTABLE.
FROM X.MYTABLE Z
With Z defined as a correlation name for X.MYTABLE, only Z can be used toqualify a reference to a column of that instance of X.MYTABLE in thatSELECT statement.
A correlation name is associated with a table, view, nickname, alias, nestedtable expression or table function only within the context in which it isdefined. Hence, the same correlation name can be defined for differentpurposes in different statements, or in different clauses of the same statement.
As a qualifier, a correlation name can be used to avoid ambiguity or toestablish a correlated reference. It can also be used merely as a shorter namefor a table, view, nickname, or alias. In the case of a nested table expression ortable function, a correlation name is required to identify the result table. In theexample, Z might have been used merely to avoid having to enterX.MYTABLE more than once.
If a correlation name is specified for a table, view, nickname, or alias name,any qualified reference to a column of that instance of the table, view,nickname, or alias must use the correlation name, rather than the table, view,nickname, or alias name. For example, the reference to EMPLOYEE.PROJECTin the following example is incorrect, because a correlation name has beenspecified for EMPLOYEE:
Example
FROM EMPLOYEE EWHERE EMPLOYEE.PROJECT=’ABC’ * incorrect*
The qualified reference to PROJECT should instead use the correlation name,″E″, as shown below:
FROM EMPLOYEE EWHERE E.PROJECT=’ABC’
Qualified column names
Chapter 2. Language elements 77
Names specified in a FROM clause are either exposed or non-exposed. A table,view, nickname, or alias name is said to be exposed in the FROM clause if acorrelation name is not specified. A correlation name is always an exposedname. For example, in the following FROM clause, a correlation name isspecified for EMPLOYEE but not for DEPARTMENT, so DEPARTMENT is anexposed name, and EMPLOYEE is not:
FROM EMPLOYEE E, DEPARTMENT
A table, view, nickname, or alias name that is exposed in a FROM clause maybe the same as any other table name, view name or nickname exposed in thatFROM clause or any correlation name in the FROM clause. This may result inambiguous column name references which returns an error (SQLSTATE42702).
The first two FROM clauses shown below are correct, because each onecontains no more than one reference to EMPLOYEE that is exposed:1. Given the FROM clause:
FROM EMPLOYEE E1, EMPLOYEE
a qualified reference such as EMPLOYEE.PROJECT denotes a column ofthe second instance of EMPLOYEE in the FROM clause. A qualifiedreference to the first instance of EMPLOYEE must use the correlationname “E1” (E1.PROJECT).
2. Given the FROM clause:FROM EMPLOYEE, EMPLOYEE E2
a qualified reference such as EMPLOYEE.PROJECT denotes a column ofthe first instance of EMPLOYEE in the FROM clause. A qualified referenceto the second instance of EMPLOYEE must use the correlation name “E2”(E2.PROJECT).
3. Given the FROM clause:FROM EMPLOYEE, EMPLOYEE
the two exposed table names included in this clause (EMPLOYEE andEMPLOYEE) are the same. This is allowed, but references to specificcolumn names would be ambiguous (SQLSTATE 42702).
4. Given the following statement:SELECT *
FROM EMPLOYEE E1, EMPLOYEE E2 * incorrect *WHERE EMPLOYEE.PROJECT = ’ABC’
Correlation names
78 SQL Reference, Volume 1
the qualified reference EMPLOYEE.PROJECT is incorrect, because bothinstances of EMPLOYEE in the FROM clause have correlation names.Instead, references to PROJECT must be qualified with either correlationname (E1.PROJECT or E2.PROJECT).
5. Given the FROM clause:FROM EMPLOYEE, X.EMPLOYEE
a reference to a column in the second instance of EMPLOYEE must useX.EMPLOYEE (X.EMPLOYEE.PROJECT). If X is the CURRENT SCHEMAspecial register value in dynamic SQL or the QUALIFIER precompile/bindoption in static SQL, then the columns cannot be referenced since any suchreference would be ambiguous.
The use of a correlation name in the FROM clause also allows the option ofspecifying a list of column names to be associated with the columns of theresult table. As with a correlation name, these listed column names becomethe exposed names of the columns that must be used for references to thecolumns throughout the query. If a column name list is specified, then thecolumn names of the underlying table become non-exposed.
Given the FROM clause:FROM DEPARTMENT D (NUM,NAME,MGR,ANUM,LOC)
a qualified reference such as D.NUM denotes the first column of theDEPARTMENT table that is defined in the table as DEPTNO. A reference toD.DEPTNO using this FROM clause is incorrect since the column nameDEPTNO is a non-exposed column name.
Column name qualifiers to avoid ambiguityIn the context of a function, a GROUP BY clause, ORDER BY clause, anexpression, or a search condition, a column name refers to values of a columnin some table, view, nickname, nested table expression or table function. Thetables, views, nicknames, nested table expressions and table functions thatmight contain the column are called the object tables of the context. Two ormore object tables might contain columns with the same name; one reason forqualifying a column name is to designate the table from which the columncomes. Qualifiers for column names are also useful in SQL procedures todistinguish column names from SQL variable names used in SQL statements.
A nested table expression or table function will consider table-references thatprecede it in the FROM clause as object tables. The table-references that followare not considered as object tables.
Table designators: A qualifier that designates a specific object table is calleda table designator. The clause that identifies the object tables also establishes the
Correlation names
Chapter 2. Language elements 79
table designators for them. For example, the object tables of an expression in aSELECT clause are named in the FROM clause that follows it:
SELECT CORZ.COLA, OWNY.MYTABLE.COLAFROM OWNX.MYTABLE CORZ, OWNY.MYTABLE
Table designators in the FROM clause are established as follows:v A name that follows a table, view, nickname, alias, nested table expression
or table function is both a correlation name and a table designator. Thus,CORZ is a table designator. CORZ is used to qualify the first column namein the select list.
v An exposed table, view name, nickname or alias is a table designator. Thus,OWNY.MYTABLE is a table designator. OWNY.MYTABLE is used to qualifythe second column name in the select list.
Each table designator should be unique within a particular FROM clause toavoid the possibility of ambiguous references to columns.
Avoiding undefined or ambiguous references: When a column name refersto values of a column, exactly one object table must include a column withthat 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
designated does not include a column with the specified name. Again thereference is undefined.
v The name is unqualified, and more than one object table includes a columnwith that name. The reference is ambiguous.
v The column name is qualified by a table designator, but the tabledesignated is not unique in the FROM clause and both occurrences of thedesignated table include the column. The reference is ambiguous.
v The column name is in a nested table expression which is not preceded bythe TABLE keyword or in a table function or nested table expression that isthe right operand of a right outer join or a full outer join and the columnname does not refer to a column of a table-reference within the nested tableexpression’s fullselect. The reference is undefined.
Avoid ambiguous references by qualifying a column name with a uniquelydefined table designator. If the column is contained in several object tableswith different names, the table names can be used as designators. Ambiguousreferences can also be avoided without the use of the table designator bygiving unique names to the columns of one of the object tables using thecolumn name list following the correlation name.
Table designators
80 SQL Reference, Volume 1
When qualifying a column with the exposed table name form of a tabledesignator, either the qualified or unqualified form of the exposed table namemay be used. However, the qualifier used and the table used must be thesame after fully qualifying the table name, view name or nickname and thetable designator.1. If the authorization ID of the statement is CORPDATA:
SELECT CORPDATA.EMPLOYEE.WORKDEPTFROM EMPLOYEE
is a valid statement.2. If the authorization ID of the statement is REGION:
SELECT CORPDATA.EMPLOYEE.WORKDEPTFROM EMPLOYEE * incorrect *
is invalid, because EMPLOYEE represents the table REGION.EMPLOYEE,but the qualifier for WORKDEPT represents a different table,CORPDATA.EMPLOYEE.
Column name qualifiers in correlated referencesA fullselect is a form of a query that may be used as a component of variousSQL statements. A fullselect used within a search condition of any statementis called a subquery. A fullselect used to retrieve a single value as anexpression within a statement is called a scalar fullselect or scalar subquery. Afullselect used in the FROM clause of a query is called a nested table expression.Subqueries in search conditions, scalar subqueries and nested tableexpressions are referred to as subqueries through the remainder of this topic.
A subquery may include subqueries of its own, and these may, in turn,include subqueries. Thus an SQL statement may contain a hierarchy ofsubqueries. Those elements of the hierarchy that contain subqueries are saidto be at a higher level than the subqueries they contain.
Every element of the hierarchy contains one or more table designators. Asubquery can reference not only the columns of the tables identified at itsown level in the hierarchy, but also the columns of the tables identifiedpreviously in the hierarchy, back to the highest level of the hierarchy. Areference to a column of a table identified at a higher level is called acorrelated reference.
For compatibility with existing standards for SQL, both qualified andunqualified column names are allowed as correlated references. However, it isgood practice to qualify all column references used in subqueries; otherwise,identical column names may lead to unintended results. For example, if atable in a hierarchy is altered to contain the same column name as thecorrelated reference and the statement is prepared again, the reference willapply to the altered table.
Avoiding undefined or ambiguous references
Chapter 2. Language elements 81
When a column name in a subquery is qualified, each level of the hierarchy issearched, starting at the same subquery as the qualified column name appearsand continuing to the higher levels of the hierarchy until a table designatorthat matches the qualifier is found. Once found, it is verified that the tablecontains the given column. If the table is found at a higher level than the levelcontaining column name, then it is a correlated reference to the level wherethe table designator was found. A nested table expression must be precededwith the optional TABLE keyword in order to search the hierarchy above thefullselect of the nested table expression.
When the column name in a subquery is not qualified, the tables referenced ateach level of the hierarchy are searched, starting at the same subquery wherethe column name appears and continuing to higher levels of the hierarchy,until a match for the column name is found. If the column is found in a tableat a higher level than the level containing column name, then it is a correlatedreference to the level where the table containing the column was found. If thecolumn name is found in more than one table at a particular level, thereference is ambiguous and considered an error.
In either case, T, used in the following example, refers to the table designatorthat contains column C. A column name, T.C (where T represents either animplicit or an explicit qualifier), is a correlated reference if, and only if, theseconditions are met:v T.C is used in an expression of a subquery.v T does not designate a table used in the from clause of the subquery.v T designates a table used at a higher level of the hierarchy that contains the
subquery.
Since the same table, view or nickname can be identified at many levels,unique correlation names are recommended as table designators. If T is usedto designate a table at more than one level (T is the table name itself or is aduplicate correlation name), T.C refers to the level where T is used that mostdirectly contains the subquery that includes T.C. If a correlation to a higherlevel is needed, a unique correlation name must be used.
The correlated reference T.C identifies a value of C in a row or group of T towhich two search conditions are being applied: condition 1 in the subquery,and condition 2 at some higher level. If condition 2 is used in a WHEREclause, the subquery is evaluated for each row to which condition 2 isapplied. If condition 2 is used in a HAVING clause, the subquery is evaluatedfor each group to which condition 2 is applied.
For example, in the following statement, the correlated referenceX.WORKDEPT (in the last line) refers to the value of WORKDEPT in tableEMPLOYEE at the level of the first FROM clause. (That clause establishes X as
Column name qualifiers in correlated references
82 SQL Reference, Volume 1
a correlation name for EMPLOYEE.) The statement lists employees who makeless than the average salary for their department.
SELECT EMPNO, LASTNAME, WORKDEPTFROM EMPLOYEE XWHERE SALARY < (SELECT AVG(SALARY)
FROM EMPLOYEEWHERE WORKDEPT = X.WORKDEPT)
The next example uses THIS as a correlation name. The statement deletesrows for departments that have no employees.
DELETE FROM DEPARTMENT THISWHERE NOT EXISTS(SELECT *
FROM EMPLOYEEWHERE WORKDEPT = THIS.DEPTNO)
References to host variablesA host variable is either:v A variable in a host language such as a C variable, a C++ variable, a
COBOL data item, a FORTRAN variable, or a Java variable
or:v A host language construct that was generated by an SQL precompiler from
a variable declared using SQL extensions
that is referenced in an SQL statement. Host variables are either directlydefined by statements in the host language or are indirectly defined usingSQL extensions.
A host variable in an SQL statement must identify a host variable described inthe program according to the rules for declaring host variables.
All host variables used in an SQL statement must be declared in an SQLDECLARE section in all host languages except REXX. No variables may bedeclared outside an SQL DECLARE section with names identical to variablesdeclared inside an SQL DECLARE section. An SQL DECLARE section beginswith BEGIN DECLARE SECTION and ends with END DECLARE SECTION.
The meta-variable host-variable, as used in the syntax diagrams, shows areference to a host variable. A host-variable in the VALUES INTO clause orthe INTO clause of a FETCH or a SELECT INTO statement, identifies a hostvariable to which a value from a column of a row or an expression isassigned. In all other contexts a host-variable specifies a value to be passed tothe database manager from the application program.
Host variables in dynamic SQLIn dynamic SQL statements, parameter markers are used instead of hostvariables. A parameter marker is a question mark (?) representing a position
Column name qualifiers in correlated references
Chapter 2. Language elements 83
in a dynamic SQL statement where the application will provide a value; thatis, where a host variable would be found if the statement string were a staticSQL statement. The following example shows a static SQL statement usinghost variables:
INSERT INTO DEPARTMENTVALUES (:hv_deptno, :hv_deptname, :hv_mgrno, :hv_admrdept)
This example shows a dynamic SQL statement using parameter markers:INSERT INTO DEPARTMENT VALUES (?, ?, ?, ?)
The meta-variable host-variable in syntax diagrams can generally be expandedto:
�� :host-identifierINDICATOR
:host-identifier
��
Each host-identifier must be declared in the source program. The variabledesignated by the second host-identifier must have a data type of smallinteger.
The first host-identifier designates the main variable. Depending on theoperation, it either provides a value to the database manager or is provided avalue from the database manager. An input host variable provides a value inthe runtime application code page. An output host variable is provided avalue that, if necessary, is converted to the runtime application code pagewhen the data is copied to the output application variable. A given hostvariable can serve as both an input and an output variable in the sameprogram.
The second host-identifier designates its indicator variable. The purposes of theindicator variable are to:v Specify the null value. A negative value of the indicator variable specifies
the null value. A value of -2 indicates a numeric conversion or arithmeticexpression error occurred in deriving the result
v Record the original length of a truncated string (if the source of the value isnot a large object type)
v Record the seconds portion of a time if the time is truncated on assignmentto a host variable.
For example, if :HV1:HV2 is used to specify an insert or update value, and ifHV2 is negative, the value specified is the null value. If HV2 is not negativethe value specified is the value of HV1.
Host variables in dynamic SQL
84 SQL Reference, Volume 1
Similarly, if :HV1:HV2 is specified in a VALUES INTO clause or in a FETCHor SELECT INTO statement, and if the value returned is null, HV1 is notchanged, and HV2 is set to a negative value. If the database is configuredwith DFT_SQLMATHWARN yes (or was during binding of a static SQLstatement), HV2 could be -2. If HV2 is -2, a value for HV1 could not bereturned because of an error converting to the numeric type of HV1, or anerror evaluating an arithmetic expression that is used to determine the valuefor HV1. When accessing a database with a client version earlier than DB2Universal Database Version 5, HV2 will be -1 for arithmetic exceptions. If thevalue returned is not null, that value is assigned to HV1 and HV2 is set tozero (unless the assignment to HV1 requires string truncation of a non-LOBstring; in which case HV2 is set to the original length of the string). If anassignment requires truncation of the seconds part of a time, HV2 is set to thenumber of seconds.
If the second host identifier is omitted, the host-variable does not have anindicator variable. The value specified by the host-variable reference :HV1 isalways the value of HV1, and null values cannot be assigned to the variable.Thus, this form should not be used in an INTO clause unless thecorresponding column cannot contain null values. If this form is used and thecolumn contains nulls, the database manager will generate an error at runtime.
An SQL statement that references host variables must be within the scope ofthe declaration of those host variables. For host variables referenced in theSELECT statement of a cursor, that rule applies to the OPEN statement ratherthan to the DECLARE CURSOR statement.
Example: Using the PROJECT table, set the host variable PNAME(VARCHAR(26)) to the project name (PROJNAME), the host variable STAFF(dec(5,2)) to the mean staffing level (PRSTAFF), and the host variableMAJPROJ (char(6)) to the major project (MAJPROJ) for project (PROJNO)‘IF1000’. Columns PRSTAFF and MAJPROJ may contain null values, soprovide indicator variables STAFF_IND (smallint) and MAJPROJ_IND(smallint).
SELECT PROJNAME, PRSTAFF, MAJPROJINTO :PNAME, :STAFF :STAFF_IND, :MAJPROJ :MAJPROJ_INDFROM PROJECTWHERE PROJNO = ’IF1000’
MBCS Considerations: Whether multi-byte characters can be used in a hostvariable name depends on the host language.
References to BLOB, CLOB, and DBCLOB host variablesRegular BLOB, CLOB, and DBCLOB variables, LOB locator variables (see“References to locator variables” on page 86), and LOB file reference variables(see “References to BLOB, CLOB, and DBCLOB file reference variables” onpage 87
Host variables in dynamic SQL
Chapter 2. Language elements 85
page 87) can be defined in all host languages. Where LOBs are allowed, theterm host-variable in a syntax diagram can refer to a regular host variable, alocator variable, or a file reference variable. Since these are not native datatypes, SQL extensions are used and the precompilers generate the hostlanguage constructs necessary to represent each variable. In the case of REXX,LOBs are mapped to strings.
It is sometimes possible to define a large enough variable to hold an entirelarge object value. If this is true and if there is no performance benefit to begained by deferred transfer of data from the server, a locator is not needed.However, since host language or space restrictions will often dictate againststoring an entire large object in temporary storage at one time and/or becauseof performance benefit, a large object may be referenced via a locator andportions of that object may be selected into or updated from host variablesthat contain only a portion of the large object at one time.
As with all other host variables, a large object locator variable may have anassociated indicator variable. Indicator variables for large object locator hostvariables behave in the same way as indicator variables for other data types.When a null value is returned from the database, the indicator variable is setand the locator host variable is unchanged. This means a locator can neverpoint to a null value.
References to locator variablesA locator variable is a host variable that contains the locator representing a LOBvalue on the application server.
A locator variable in an SQL statement must identify a locator variabledescribed in the program according to the rules for declaring locator variables.This is always indirectly through an SQL statement.
The term locator variable, as used in the syntax diagrams, shows a referenceto a locator variable. The meta-variable locator-variable can be expanded toinclude a host-identifier the same as that for host-variable.
When the indicator variable associated with a locator is null, the value of thereferenced LOB is null.
If a locator-variable that does not currently represent any value is referenced,an error is raised (SQLSTATE 0F001).
At transaction commit, or any transaction termination, all locators acquired bythat transaction are released.
References to BLOB, CLOB, and DBCLOB host variables
86 SQL Reference, Volume 1
References to BLOB, CLOB, and DBCLOB file reference variablesBLOB, CLOB, and DBCLOB file reference variables are used for direct fileinput and output for LOBs, and can be defined in all host languages. Sincethese are not native data types, SQL extensions are used and the precompilersgenerate the host language constructs necessary to represent each variable. Inthe case of REXX, LOBs are mapped to strings.
A file reference variable represents (rather than contains) the file, just as aLOB locator represents, rather than contains, the LOB bytes. Database queries,updates and inserts may use file reference variables to store or to retrievesingle column values.
A file reference variable has the following properties:
Data Type BLOB, CLOB, or DBCLOB. This property isspecified when the variable is declared.
Direction This must be specified by the applicationprogram at run time (as part of the FileOptions value). The direction is one of:v Input (used as a source of data on an
EXECUTE statement, an OPEN statement,an UPDATE statement, an INSERTstatement, or a DELETE statement).
v Output (used as the target of data on aFETCH statement or a SELECT INTOstatement).
File name This must be specified by the applicationprogram at run time. It is one of:v The complete path name of the file (which
is advised).v A relative file name. If a relative file name
is provided, it is appended to the currentpath of the client process.
Within an application, a file should only bereferenced in one file reference variable.
File Name Length This must be specified by the applicationprogram at run time. It is the length of the filename (in bytes).
File Options An application must assign one of a numberof options to a file reference variable before itmakes use of that variable. Options are set byan INTEGER value in a field in the file
References to BLOB, CLOB, and DBCLOB file reference variables
Chapter 2. Language elements 87
reference variable structure. One of thefollowing values must be specified for eachfile reference variable:v Input (from client to server)
SQL_FILE_READThis is a regular file thatcan be opened, read andclosed. (The option isSQL-FILE-READ in COBOL,sql_file_read in FORTRAN,and READ in REXX.)
v Output (from server to client)
SQL_FILE_CREATECreate a new file. If the filealready exists, an error isreturned. (The option isSQL-FILE-CREATE inCOBOL, sql_file_create inFORTRAN, and CREATE inREXX.)
SQL_FILE_OVERWRITE (Overwrite)If an existing file with thespecified name exists, it isoverwritten; otherwise anew file is created. (Theoption isSQL-FILE-OVERWRITE inCOBOL, sql_file_overwritein FORTRAN, andOVERWRITE in REXX.)
SQL_FILE_APPENDIf an existing file with thespecified name exists, theoutput is appended to it;otherwise a new file iscreated. (The option isSQL-FILE-APPEND inCOBOL, sql_file_append inFORTRAN, and APPEND inREXX.)
Data LengthThis is unused on input. On output,the implementation sets the data
References to BLOB, CLOB, and DBCLOB file reference variables
88 SQL Reference, Volume 1
length to the length of the new datawritten to the file. The length is inbytes.
As with all other host variables, a file reference variable may have anassociated indicator variable.
Example of an output file reference variable (in C): Given a declare sectioncoded as:
EXEC SQL BEGIN DECLARE SECTIONSQL TYPE IS CLOB_FILE hv_text_file;char hv_patent_title[64];
EXEC SQL END DECLARE SECTION
Following preprocessing this would be:EXEC SQL BEGIN DECLARE SECTION
/* SQL TYPE IS CLOB_FILE hv_text_file; */struct {
unsigned long name_length; // File Name Lengthunsigned long data_length; // Data Lengthunsigned long file_options; // File Optionschar name[255]; // File Name
} hv_text_file;char hv_patent_title[64];
EXEC SQL END DECLARE SECTION
Then, the following code can be used to select from a CLOB column in thedatabase into a new file referenced by :hv_text_file.
strcpy(hv_text_file.name, "/u/gainer/papers/sigmod.94");hv_text_file.name_length = strlen("/u/gainer/papers/sigmod.94");hv_text_file.file_options = SQL_FILE_CREATE;
EXEC SQL SELECT content INTO :hv_text_file from papersWHERE TITLE = ’The Relational Theory behind Juggling’;
Example of an input file reference variable (in C): Given the same declaresection as above, the following code can be used to insert the data from aregular file referenced by :hv_text_file into a CLOB column.
strcpy(hv_text_file.name, "/u/gainer/patents/chips.13");hv_text_file.name_length = strlen("/u/gainer/patents/chips.13");hv_text_file.file_options = SQL_FILE_READ:strcpy(:hv_patent_title, "A Method for Pipelining Chip Consumption");
EXEC SQL INSERT INTO patents( title, text )VALUES(:hv_patent_title, :hv_text_file);
References to structured type host variablesStructured type variables can be defined in all host languages exceptFORTRAN, REXX, and Java. Since these are not native data types, SQL
References to BLOB, CLOB, and DBCLOB file reference variables
Chapter 2. Language elements 89
extensions are used and the precompilers generate the host languageconstructs necessary to represent each variable.
As with all other host variables, a structured type variable may have anassociated indicator variable. Indicator variables for structured type hostvariables behave in the same way as indicator variables for other data types.When a null value is returned from the database, the indicator variable is setand the structured type host variable is unchanged.
The actual host variable for a structured type is defined as a built-in datatype. The built-in data type associated with the structured type must beassignable:v from the result of the FROM SQL transform function for the structured type
as defined by the specified TRANSFORM GROUP option of the precompilecommand; and
v to the parameter of the TO SQL transform function for the structured typeas defined by the specified TRANSFORM GROUP option of the precompilecommand.
If using a parameter marker instead of a host variable, the appropriateparameter type characteristics must be specified in the SQLDA. This requiresa ″doubled″ set of SQLVAR structures in the SQLDA, and theSQLDATATYPE_NAME field of the secondary SQLVAR must be filled withthe schema and type name of the structured type. If the schema is omitted inthe SQLDA structure, an error results (SQLSTATE 07002).
Example: Define the host variables hv_poly and hv_point (of type POLYGON,using built-in type BLOB(1048576)) in a C program.
EXEC SQL BEGIN DECLARE SECTION;static SQL
TYPE IS POLYGON AS BLOB(1M)hv_poly, hv_point;
EXEC SQL END DECLARE SECTION;
Related concepts:
v “Queries” on page 16
Related reference:
v “CREATE ALIAS statement” in the SQL Reference, Volume 2
v “PREPARE statement” in the SQL Reference, Volume 2
v “SET SCHEMA statement” in the SQL Reference, Volume 2
v Appendix A, “SQL limits” on page 607v Appendix C, “SQLDA (SQL descriptor area)” on page 621v Appendix G, “Reserved schema names and reserved words” on page 823
References to structured type host variables
90 SQL Reference, Volume 1
v Appendix P, “Japanese and traditional-Chinese extended UNIX code (EUC)considerations” on page 883
v “Large objects (LOBs)” on page 99
Example
Chapter 2. Language elements 91
Data types
Data types
The smallest unit of data that can be manipulated in SQL is called a value.Values are interpreted according to the data type of their source. Sourcesinclude:v Constantsv Columnsv Host variablesv Functionsv Expressionsv Special registers.
DB2 supports a number of built-in data types. It also provides support foruser-defined data types. Figure 10 on page 93 shows the supported built-indata types.
Data types
92 SQL Reference, Volume 1
All data types include the null value. The null value is a special value that isdistinct from all non-null values and thereby denotes the absence of a(non-null) value. Although all data types include the null value, columnsdefined as NOT NULL cannot contain null values.
Related reference:
v “User-defined types” on page 108
fixedlength
built-indatatypes
stringdatetime
floatingpoint
decimal
packed
DECIMAL
DATALINK
binaryinteger
time timestamp date
16 bit 32 bit 64 bit
singleprecision
doubleprecision
fixedlength
varyinglength
varyinglength
graphiccharactervaryinglengthbinary
externaldata
signednumeric
exact approximate
SMALLINT BIGINTINTEGER
REAL DOUBLE
TIME
GRAPHIC
VARGRAPHICVARCHAR DBCLOBCLOB
CHAR
TIMESTAMP DATE
BLOB
Figure 10. The DB2 Built-in Data Types
Data types
Chapter 2. Language elements 93
Numbers
All numbers have a sign and a precision. The sign is considered positive if thevalue of a number is zero. The precision is the number of bits or digitsexcluding the sign.
Small integer (SMALLINT)A small integer is a two-byte integer with a precision of 5 digits. The range ofsmall integers is -32 768 to 32 767.
Large integer (INTEGER)A large integer is a four-byte integer with a precision of 10 digits. The range oflarge integers is −2 147 483 648 to +2 147 483 647.
Big integer (BIGINT)A big integer is an eight-byte integer with a precision of 19 digits. The range ofbig integers is −9 223 372 036 854 775 808 to +9 223 372 036 854 775 807.
Single-precision floating-point (REAL)A single-precision floating-point number is a 32-bit approximation of a realnumber. The number can be zero or can range from -3.402E+38 to -1.175E-37,or from 1.175E-37 to 3.402E+38.
Double-precision floating-point (DOUBLE or FLOAT)A double-precision floating-point number is a 64-bit approximation of a realnumber. The number can be zero or can range from -1.79769E+308 to-2.225E-307, or from 2.225E-307 to 1.79769E+308.
Decimal (DECIMAL or NUMERIC)A decimal value is a packed decimal number with an implicit decimal point.The position of the decimal point is determined by the precision and the scaleof the number. The scale, which is the number of digits in the fractional partof the number, cannot be negative or greater than the precision. Themaximum precision is 31 digits.
All values in a decimal column have the same precision and scale. The rangeof a decimal variable or the numbers in a decimal column is −n to +n, wherethe absolute value of n is the largest number that can be represented with theapplicable precision and scale. The maximum range is -10**31+1 to 10**31-1.
Related reference:
v Appendix C, “SQLDA (SQL descriptor area)” on page 621
Numbers
94 SQL Reference, Volume 1
Character strings
A character string is a sequence of bytes. The length of the string is the numberof bytes in the sequence. If the length is zero, the value is called the emptystring. This value should not be confused with the null value.
Fixed-length character string (CHAR)All values in a fixed-length string column have the same length, which isdetermined by the length attribute of the column. The length attribute mustbe between 1 and 254, inclusive.
Varying-length character stringsThere are three types of varying-length character string:v A VARCHAR value can be up to 32 672 bytes long.v A LONG VARCHAR value can be up to 32 700 bytes long.v A CLOB (character large object) value can be up to 2 gigabytes
(2 147 483 647 bytes) long. A CLOB is used to store large SBCS or mixed(SBCS and MBCS) character-based data (such as documents written with asingle character set) and, therefore, has an SBCS or mixed code pageassociated with it.
Special restrictions apply to expressions resulting in a LONG VARCHAR orCLOB data type, and to structured type columns; such expressions andcolumns are not permitted in:v A SELECT list preceded by the DISTINCT clausev A GROUP BY clausev An ORDER BY clausev A column function with the DISTINCT clausev A subselect of a set operator other than UNION ALLv A basic, quantified, BETWEEN, or IN predicatev A column functionv VARGRAPHIC, TRANSLATE, and datetime scalar functionsv The pattern operand in a LIKE predicate, or the search string operand in a
POSSTR functionv The string representation of a datetime value.
In addition to the restrictions listed above, expressions resulting in LONGVARCHAR or CLOB data types or structured type columns are not permittedin:v A basic, quantified, BETWEEN, or IN predicatev A column functionv VARGRAPHIC, TRANSLATE, and datetime scalar functions
Character strings
Chapter 2. Language elements 95
v The pattern operand in a LIKE predicate or the search string operand in thePOSSTR function
v The string representation of a datetime value.
The functions in the SYSFUN schema taking a VARCHAR as an argumentwill not accept VARCHARs greater than 4 000 bytes long as an argument.However, many of these functions also have an alternative signature acceptinga CLOB(1M). For these functions, the user may explicitly cast the greater than4 000 VARCHAR strings into CLOBs and then recast the result back intoVARCHARs of desired length.
NUL-terminated character strings found in C are handled differently,depending on the standards level of the precompile option.
Each character string is further defined as one of:
Bit data Data that is not associated with a code page.
Single-byte character set (SBCS) dataData in which every character is represented by a single byte.
Mixed data Data that may contain a mixture of characters from asingle-byte character set and a multi-byte character set(MBCS).
SBCS data is supported only in an SBCS database. Mixed data is onlysupported in an MBCS database.
Varying-length character strings
96 SQL Reference, Volume 1
Graphic strings
A graphic string is a sequence of bytes that represents double-byte characterdata. The length of the string is the number of double-byte characters in thesequence. If the length is zero, the value is called the empty string. This valueshould not be confused with the null value.
Graphic strings are not checked to ensure that their values contain onlydouble-byte character code points. (The exception to this rule is an applicationprecompiled with the WCHARTYPE CONVERT option. In this case,validation does occur.) Rather, the database manager assumes that double-bytecharacter data is contained in graphic data fields. The database manager doescheck that a graphic string value is an even number of bytes long.
NUL-terminated graphic strings found in C are handled differently,depending on the standards level of the precompile option. This data typecannot be created in a table. It can only be used to insert data into andretrieve data from the database.
Fixed-length graphic strings (GRAPHIC)All values in a fixed-length graphic string column have the same length,which is determined by the length attribute of the column. The lengthattribute must be between 1 and 127, inclusive.
Varying-length graphic stringsThere are three types of varying-length graphic string:v A VARGRAPHIC value can be up to 16 336 double-byte characters long.v A LONG VARGRAPHIC value can be up to 16 350 double-byte characters
long.v A DBCLOB (double-byte character large object) value can be up to
1 073 741 823 double-byte characters long. A DBCLOB is used to store largeDBCS character-based data (such as documents written with a singlecharacter set) and, therefore, has a DBCS code page associated with it.
Special restrictions apply to an expression that results in a varying-lengthgraphic string whose maximum length is greater than 127 bytes. Theserestrictions are the same as those specified in “Varying-length characterstrings” on page 95.
Graphic strings
Chapter 2. Language elements 97
Binary strings
A binary string is a sequence of bytes. Unlike character strings, which usuallycontain text data, binary strings are used to hold non-traditional data such aspictures, voice, or mixed media. Character strings of the FOR BIT DATAsubtype may be used for similar purposes, but the two data types are notcompatible. The BLOB scalar function can be used to cast a FOR BIT DATAcharacter string to a binary string. Binary strings are not associated with acode page. They have the same restrictions as character strings (for details, see“Varying-length character strings” on page 95).
Binary large object (BLOB)A binary large object is a varying-length binary string that can be up to 2gigabytes (2 147 483 647 bytes) long. BLOBs can hold structured data forexploitation by user-defined types and user-defined functions. Like FOR BITDATA character strings, BLOB strings are not associated with a code page.
Binary strings
98 SQL Reference, Volume 1
Large objects (LOBs)
The term large object and the generic acronym LOB refer to the BLOB, CLOB,or DBCLOB data type. LOB values are subject to restrictions that apply toLONG VARCHAR values, as described in “Varying-length character strings”on page 95. These restrictions apply even if the length attribute of the LOBstring is 254 bytes or less.
LOB values can be very large, and the transfer of these values from thedatabase server to client application program host variables can be timeconsuming. Because application programs typically process LOB values onepiece at a time, rather than as a whole, applications can reference a LOB valueby using a large object locator.
A large object locator, or LOB locator, is a host variable whose value representsa single LOB value on the database server.
An application program can select a LOB value into a LOB locator. Then,using the LOB locator, the application program can request databaseoperations on the LOB value (such as applying the scalar functions SUBSTR,CONCAT, VALUE, or LENGTH; performing an assignment; searching theLOB with LIKE or POSSTR; or applying user-defined functions against theLOB) by supplying the locator value as input. The resulting output (dataassigned to a client host variable) would typically be a small subset of theinput LOB value.
LOB locators can represent more than just base values; they can also representthe value associated with a LOB expression. For example, a LOB locator mightrepresent the value associated with:
SUBSTR( <lob 1> CONCAT <lob 2> CONCAT <lob 3>, <start>, <length> )
When a null value is selected into a normal host variable, the indicatorvariable is set to -1, signifying that the value is null. In the case of LOBlocators, however, the meaning of indicator variables is slightly different.Because a locator host variable can itself never be null, a negative indicatorvariable value indicates that the LOB value represented by the LOB locator isnull. The null information is kept local to the client by virtue of the indicatorvariable value — the server does not track null values with valid locators.
It is important to understand that a LOB locator represents a value, not a rowor a location in the database. Once a value is selected into a locator, there isno operation that one can perform on the original row or table that will affectthe value which is referenced by the locator. The value associated with alocator is valid until the transaction ends, or until the locator is explicitlyfreed, whichever comes first. Locators do not force extra copies of the data toprovide this function. Instead, the locator mechanism stores a description of
Large objects (LOBs)
Chapter 2. Language elements 99
the base LOB value. The materialization of the LOB value (or expression, asshown above) is deferred until it is actually assigned to some location —either a user buffer in the form of a host variable, or another record in thedatabase.
A LOB locator is only a mechanism used to refer to a LOB value during atransaction; it does not persist beyond the transaction in which it was created.It is not a database type; it is never stored in the database and, as a result,cannot participate in views or check constraints. However, because a LOBlocator is a client representation of a LOB type, there are SQLTYPEs for LOBlocators so that they can be described within an SQLDA structure used byFETCH, OPEN, or EXECUTE statements.
Large objects (LOBs)
100 SQL Reference, Volume 1
Datetime values
The datetime data types include DATE, TIME, and TIMESTAMP. Althoughdatetime values can be used in certain arithmetic and string operations, andare compatible with certain strings, they are neither strings nor numbers.
DateA date is a three-part value (year, month, and day). The range of the year partis 0001 to 9999. The range of the month part is 1 to 12. The range of the daypart is 1 to x, where x depends on the month.
The internal representation of a date is a string of 4 bytes. Each byte consistsof 2 packed decimal digits. The first 2 bytes represent the year, the third bytethe month, and the last byte the day.
The length of a DATE column, as described in the SQLDA, is 10 bytes, whichis the appropriate length for a character string representation of the value.
TimeA time is a three-part value (hour, minute, and second) designating a time ofday under a 24-hour clock. The range of the hour part is 0 to 24. The range ofthe other parts is 0 to 59. If the hour is 24, the minute and secondspecifications are zero.
The internal representation of a time is a string of 3 bytes. Each byte consistsof 2 packed decimal digits. The first byte represents the hour, the second bytethe minute, and the last byte the second.
The length of a TIME column, as described in the SQLDA, is 8 bytes, which isthe appropriate length for a character string representation of the value.
TimestampA timestamp is a seven-part value (year, month, day, hour, minute, second, andmicrosecond) designating a date and time as defined above, except that thetime includes a fractional specification of microseconds.
The internal representation of a timestamp is a string of 10 bytes. Each byteconsists of 2 packed decimal digits. The first 4 bytes represent the date, thenext 3 bytes the time, and the last 3 bytes the microseconds.
The length of a TIMESTAMP column, as described in the SQLDA, is 26 bytes,which is the appropriate length for the character string representation of thevalue.
String representations of datetime valuesValues whose data types are DATE, TIME, or TIMESTAMP are represented inan internal form that is transparent to the user. Date, time, and timestamp
Datetime values
Chapter 2. Language elements 101
values can, however, also be represented by strings. This is useful becausethere are no constants or variables whose data types are DATE, TIME, orTIMESTAMP. Before it can be retrieved, a datetime value must be assigned toa string variable. The CHAR function or the GRAPHIC function (for Unicodedatabases only) can be used to change a datetime value to a stringrepresentation. The string representation is normally the default format ofdatetime values associated with the territory code of the application, unlessoverridden by specification of the DATETIME option when the program isprecompiled or bound to the database.
No matter what its length, a large object string, a LONG VARCHAR value, ora LONG VARGRAPHIC value cannot be used to represent a datetime value(SQLSTATE 42884).
When a valid string representation of a datetime value is used in an operationwith an internal datetime value, the string representation is converted to theinternal form of the date, time, or timestamp value before the operation isperformed.
Date, time and timestamp strings must contain only characters and digits.
Date strings: A string representation of a date is a string that starts with adigit and has a length of at least 8 characters. Trailing blanks may beincluded; leading zeros may be omitted from the month and day portions.
Valid string formats for dates are listed in the following table. Each format isidentified by name and associated abbreviation.
Table 5. Formats for String Representations of Dates
Format Name Abbreviation Date Format Example
International StandardsOrganization
ISO yyyy-mm-dd 1991-10-27
IBM USA standard USA mm/dd/yyyy 10/27/1991
IBM European standard EUR dd.mm.yyyy 27.10.1991
Japanese Industrial StandardChristian Era
JIS yyyy-mm-dd 1991-10-27
Site-defined LOC Depends on theterritory code ofthe application
—
Time strings: A string representation of a time is a string that starts with adigit and has a length of at least 4 characters. Trailing blanks may beincluded; a leading zero may be omitted from the hour part of the time, and
String representations of datetime values
102 SQL Reference, Volume 1
seconds may be omitted entirely. If seconds are omitted, an implicitspecification of 0 seconds is assumed. Thus, 13:30 is equivalent to 13:30:00.
Valid string formats for times are listed in the following table. Each format isidentified by name and associated abbreviation.
Table 6. Formats for String Representations of Times
Format Name Abbreviation Time Format Example
International StandardsOrganization2
ISO hh.mm.ss 13.30.05
IBM USA standard USA hh:mm AM orPM
1:30 PM
IBM European standard EUR hh.mm.ss 13.30.05
Japanese Industrial StandardChristian Era
JIS hh:mm:ss 13:30:05
Site-defined LOC Depends on theterritory code ofthe application
—
Notes:
1. In ISO, EUR, and JIS format, .ss (or :ss) is optional.2. The International Standards Organization changed the time format so that
it is identical with the Japanese Industrial Standard Christian Era format.Therefore, use the JIS format if an application requires the currentInternational Standards Organization format.
3. In the USA time string format, the minutes specification may be omitted,indicating an implicit specification of 00 minutes. Thus 1 PM is equivalentto 1:00 PM.
4. In the USA time format, the hour must not be greater than 12 and cannotbe 0 except for the special case of 00:00 AM. There is a single space beforethe AM and PM. Using the JIS format of the 24-hour clock, thecorrespondence between the USA format and the 24-hour clock is asfollows:
12:01 AM through 12:59 AM corresponds to 00:01:00 through 00:59:00.01:00 AM through 11:59 AM corresponds to 01:00:00 through 11:59:00.12:00 PM (noon) through 11:59 PM corresponds to 12:00:00 through23:59:00.12:00 AM (midnight) corresponds to 24:00:00 and 00:00 AM (midnight)corresponds to 00:00:00.
Timestamp strings: A string representation of a timestamp is a string thatstarts with a digit and has a length of at least 16 characters. The complete
Time strings
Chapter 2. Language elements 103
string representation of a timestamp has the form yyyy-mm-dd-hh.mm.ss.nnnnnn. Trailing blanks may be included. Leading zeros may beomitted from the month, day, and hour part of the timestamp, andmicroseconds may be truncated or entirely omitted. If any trailing zero digitsare omitted in the microseconds portion, an implicit specification of 0 isassumed for the missing digits. Thus, 1991-3-2-8.30.00 is equivalent to1991-03-02-08.30.00.000000.
SQL statements also support the ODBC string representation of a timestamp,but as an input value only. The ODBC string representation of a timestamphas the form yyyy-mm-dd hh:mm:ss.nnnnnn.
Timestamp strings
104 SQL Reference, Volume 1
DATALINK values
A DATALINK value is an encapsulated value that contains a logical referencefrom the database to a file stored outside of the database. The attributes ofthis encapsulated value are as follows:
link typeThe currently supported type of link is 'URL' (Uniform Resource Locator).
data locationThe location of a file linked with a reference within DB2, in the form of aURL. The allowed scheme names for this URL are:v HTTPv FILEv UNCv DFS
The other parts of the URL are:v the file server name for the HTTP, FILE, and UNC schemesv the cell name for the DFS schemev the full file path name within the file server or cell
commentUp to 200 bytes of descriptive information, including the data locationattribute. This is intended for application-specific uses, such as further oralternative identification of the location of the data.
Leading and trailing blank characters are trimmed while parsing data locationattributes as URLs. Also, the scheme names ('http', 'file', 'unc', 'dfs') and hostare case-insensitive and are always stored in the database in uppercase. Whena DATALINK value is fetched from a database, an access token is embeddedwithin the URL attribute, if the DATALINK column is defined with READPERMISSION DB or WRITE PERMISSION ADMIN. The token is generateddynamically, and is not a permanent part of the DATALINK value stored inthe database.
It is possible for a DATALINK value to have only a comment attribute and anempty data location attribute. Such a value may even be stored in a columnbut, of course, no file will be linked to such a column. The total length of thecomment and the data location attribute of a DATALINK value is currentlylimited to 200 bytes.
It is important to distinguish between DATALINK references to files and LOBfile reference variables. The similarity is that they both contain arepresentation of a file. However:
DATALINK values
Chapter 2. Language elements 105
v DATALINKs are retained in the database, and both the links and the datain the linked files can be considered to be a natural extension of data in thedatabase.
v File reference variables exist temporarily on the client and they can beconsidered to be an alternative to a host program buffer.
Use built-in scalar functions to build a DATALINK value (DLVALUE,DLNEWCOPY, DLPREVIOUSCOPY, and DLREPLACECONTENT) and toextract the encapsulated values from a DATALINK value (DLCOMMENT,DLLINKTYPE, DLURLCOMPLETE, DLURLPATH, DLURLPATHONLY,DLURLSCHEME, DLURLSERVER, DLURLCOMPLETEONLY,DLURLCOMPLETEWRITE, and DLURLPATHWRITE).
Related reference:
v “Identifiers” on page 65v Appendix Q, “Backus-Naur form (BNF) specifications for DATALINKs” on
page 891
DATALINK values
106 SQL Reference, Volume 1
XML values
The XML data type is an internal representation of XML, and can only beused as input to functions that accept this data type as input. XML is atransient data type that cannot be stored in the database, or returned to anapplication.
Valid values for the XML data type include:v An elementv A forest of elementsv The textual content of an elementv An empty XML value
Currently, the only supported operation is to serialize (by using theXML2CLOB function) the XML value into a string that is stored as a CLOBvalue.
XML values
Chapter 2. Language elements 107
User-defined types
There are three types of user-defined data type:v Distinct typev Structured typev Reference type
Each of these types is described in the following sections.
Distinct typesA distinct type is a user-defined data type that shares its internal representationwith an existing type (its “source” type), but is considered to be a separateand incompatible type for most operations. For example, one might want todefine a picture type, a text type, and an audio type, all of which have quitedifferent semantics, but which use the built-in data type BLOB for theirinternal representation.
The following example illustrates the creation of a distinct type namedAUDIO:
CREATE DISTINCT TYPE AUDIO AS BLOB (1M)
Although AUDIO has the same representation as the built-in data type BLOB,it is considered to be a separate type; this allows the creation of functionswritten specifically for AUDIO, and assures that these functions will not beapplied to values of any other data type (pictures, text, and so on).
Distinct types have qualified identifiers. If the schema name is not used toqualify the distinct type name when used in other than the CREATEDISTINCT TYPE, DROP DISTINCT TYPE, or COMMENT ON DISTINCTTYPE statements, the SQL path is searched in sequence for the first schemawith a distinct type that matches.
Distinct types support strong typing by ensuring that only those functionsand operators explicitly defined on a distinct type can be applied to itsinstances. For this reason, a distinct type does not automatically acquire thefunctions and operators of its source type, because these may not bemeaningful. (For example, the LENGTH function of the AUDIO type mightreturn the length of its object in seconds rather than in bytes.)
Distinct types sourced on LONG VARCHAR, LONG VARGRAPHIC, LOBtypes, or DATALINK are subject to the same restrictions as their source type.
However, certain functions and operators of the source type can be explicitlyspecified to apply to the distinct type. This can be done by creatinguser-defined functions that are sourced on functions defined on the sourcetype of the distinct type. The comparison operators are automatically
User-defined types
108 SQL Reference, Volume 1
generated for user-defined distinct types, except those using LONGVARCHAR, LONG VARGRAPHIC, BLOB, CLOB, DBCLOB, or DATALINK asthe source type. In addition, functions are generated to support casting fromthe source type to the distinct type, and from the distinct type to the sourcetype.
Structured typesA structured type is a user-defined data type that has a structure that is definedin the database. It contains a sequence of named attributes, each of which hasa data type. A structured type also includes a set of method specifications.
A structured type may be used as the type of a table, view, or column. Whenused as a type for a table or view, that table or view is known as a typed tableor typed view, respectively. For typed tables and typed views, the names anddata types of the attributes of the structured type become the names and datatypes of the columns of this typed table or typed view. Rows of the typedtable or typed view can be thought of as a representation of instances of thestructured type. When used as a data type for a column, the column containsvalues of that structured type (or values of any of that type’s subtypes, asdefined below). Methods are used to retrieve or manipulate attributes of astructured column object.
Terminology: A supertype is a structured type for which other structured types,called subtypes, have been defined. A subtype inherits all the attributes andmethods of its supertype and may have additional attributes and methodsdefined. The set of structured types that are related to a common supertype iscalled a type hierarchy and the type that does not have any supertype is calledthe root type of the type hierarchy.
The term subtype applies to a user-defined structured type and alluser-defined structured types that are below it in the type hierarchy.Therefore, a subtype of a structured type T is T and all structured types belowT in the hierarchy. A proper subtype of a structured type T is a structured typebelow T in the type hierarchy.
There are restrictions on having recursive type definitions in a type hierarchy.For this reason, it is necessary to develop a shorthand way of referring to thespecific type of recursive definitions that are allowed. The followingdefinitions are used:v Directly uses: A type A is said to directly use another type B, if and only if
one of the following is true:1. type A has an attribute of type B
2. type B is a subtype of A, or a supertype of A
v Indirectly uses: A type A is said to indirectly use a type B, if one of thefollowing is true:
Distinct types
Chapter 2. Language elements 109
1. type A directly uses type B
2. type A directly uses some type C, and type C indirectly uses type B
A type may not be defined so that one of its attribute types directly orindirectly uses itself. If it is necessary to have such a configuration, considerusing a reference as the attribute. For example, with structured type attributes,there cannot be an instance of ″employee″ with an attribute of ″manager″when ″manager″ is of type ″employee″. There can, however, be an attribute of″manager″ with a type of REF(employee).
A type cannot be dropped if certain other objects use the type, either directlyor indirectly. For example, a type cannot be dropped if a table or view columnmakes direct or indirect use of the type.
Reference typesA reference type is a companion type to a structured type. Similar to a distincttype, a reference type is a scalar type that shares a common representationwith one of the built-in data types. This same representation is shared for alltypes in the type hierarchy. The reference type representation is defined whenthe root type of a type hierarchy is created. When using a reference type, astructured type is specified as a parameter of the type. This parameter iscalled the target type of the reference.
The target of a reference is always a row in a typed table or a typed view.When a reference type is used, it may have a scope defined. The scopeidentifies a table (called the target table) or view (called the target view) thatcontains the target row of a reference value. The target table or view musthave the same type as the target type of the reference type. An instance of ascoped reference type uniquely identifies a row in a typed table or typedview, called the target row.
Related reference:
v “DROP statement” in the SQL Reference, Volume 2
v “CURRENT PATH” on page 159v “Character strings” on page 95v “Assignments and comparisons” on page 117
Structured types
110 SQL Reference, Volume 1
Promotion of data types
Data types can be classified into groups of related data types. Within suchgroups, a precedence order exists where one data type is considered toprecede another data type. This precedence is used to allow the promotion ofone data type to a data type later in the precedence ordering. For example,the data type CHAR can be promoted to VARCHAR; INTEGER can bepromoted to DOUBLE-PRECISION; but CLOB is NOT promotable toVARCHAR.
Promotion of data types is used when:v Performing function resolutionv Casting user-defined typesv Assigning user-defined types to built-in data types
Table 7 shows the precedence list (in order) for each data type and can beused to determine the data types to which a given data type can be promoted.The table shows that the best choice is always the same data type instead ofchoosing to promote to another data type.
Table 7. Data Type Precedence Table
Data Type Data Type Precedence List (in best-to-worst order)
CHAR CHAR, VARCHAR, LONG VARCHAR, CLOB
VARCHAR VARCHAR, LONG VARCHAR, CLOB
LONGVARCHAR
LONG VARCHAR, CLOB
GRAPHIC GRAPHIC, VARGRAPHIC, LONG VARGRAPHIC, DBCLOB
VARGRAPHIC VARGRAPHIC, LONG VARGRAPHIC, DBCLOB
LONGVARGRAPHIC
LONG VARGRAPHIC, DBCLOB
BLOB BLOB
CLOB CLOB
DBCLOB DBCLOB
SMALLINT SMALLINT, INTEGER, BIGINT, decimal, real, double
INTEGER INTEGER, BIGINT, decimal, real, double
BIGINT BIGINT, decimal, real, double
decimal decimal, real, double
real real, double
double double
DATE DATE
Promotion of data types
Chapter 2. Language elements 111
Table 7. Data Type Precedence Table (continued)
Data Type Data Type Precedence List (in best-to-worst order)
TIME TIME
TIMESTAMP TIMESTAMP
DATALINK DATALINK
udt udt (same name) or a supertype of udt
REF(T) REF(S) (provided that S is a supertype of T)
Notes:
1. The lowercase types above are defined as follows:
v decimal = DECIMAL(p,s) or NUMERIC(p,s)
v real = REAL or FLOAT(n), where n is not greater than 24
v double = DOUBLE, DOUBLE-PRECISION, FLOAT or FLOAT(n), where n isgreater than 24
v udt = a user-defined type
Shorter and longer form synonyms of the listed data types are considered to be thesame as the listed form.
2. For a Unicode database, the following are considered to be equivalent data types:
v CHAR and GRAPHIC
v VARCHAR and VARGRAPHIC
v LONG VARCHAR and LONG VARGRAPHIC
v CLOB and DBCLOB
Related reference:
v “Functions” on page 168v “Casting between data types” on page 113v “Assignments and comparisons” on page 117
Promotion of data types
112 SQL Reference, Volume 1
Casting between data types
There are many occasions where a value with a given data type needs to becast to a different data type or to the same data type with a different length,precision or scale. Data type promotion is one example where the promotionof one data type to another data type requires that the value be cast to thenew data type. A data type that can be cast to another data type is castablefrom the source data type to the target data type.
Casting between data types can be done explicitly using the CASTspecification but may also occur implicitly during assignments involvinguser-defined types. Also, when creating sourced user-defined functions, thedata types of the parameters of the source function must be castable to thedata types of the function that is being created.
The supported casts between built-in data types are shown in Table 8 onpage 115. The first column represents the data type of the cast operand (sourcedata type), and the data types across the top represent the target data type ofthe CAST specification.
In a Unicode database, if a truncation occurs when a character or graphicstring is cast to another data type, a warning returns if any nonblankcharacters are truncated. This truncation behavior is unlike the assignment ofcharacter or graphic strings to a target when an error occurs if any nonblankcharacters are truncated.
The following casts involving distinct types are supported:v Cast from distinct type DT to its source data type S
v Cast from the source data type S of distinct type DT to distinct type DT
v Cast from distinct type DT to the same distinct type DT
v Cast from a data type A to distinct type DT where A is promotable to thesource data type S of distinct type DT
v Cast from an INTEGER to distinct type DT with a source data typeSMALLINT
v Cast from a DOUBLE to distinct type DT with a source data type REALv Cast from a VARCHAR to distinct type DT with a source data type CHARv Cast from a VARGRAPHIC to distinct type DT with a source data type
GRAPHICv For a Unicode database, cast from a VARCHAR or a VARGRAPHIC to
distinct type DT with a source data type CHAR or GRAPHIC.
It is not possible to specify FOR BIT DATA when performing a cast to acharacter type.
Casting between data types
Chapter 2. Language elements 113
It is not possible to cast a structured type value to something else. Astructured type ST should not need to be cast to one of its supertypes,because all methods on the supertypes of ST are applicable to ST. If thedesired operation is only applicable to a subtype of ST, use thesubtype-treatment expression to treat ST as one of its subtypes.
When a user-defined data type involved in a cast is not qualified by a schemaname, the SQL path is used to find the first schema that includes theuser-defined data type by that name.
The following casts involving reference types are supported:v cast from reference type RT to its representation data type S
v cast from the representation data type S of reference type RT to referencetype RT
v cast from reference type RT with target type T to a reference type RS withtarget type S where S is a supertype of T.
v cast from a data type A to reference type RT, where A is promotable to therepresentation data type S of reference type RT.
When the target type of a reference data type involved in a cast is notqualified by a schema name, the SQL path is used to find the first schema thatincludes the user-defined data type by that name.
Casting between data types
114 SQL Reference, Volume 1
Table 8. Supported Casts between Built-in Data Types
Target Data Type →
Source Data Type ↓
SMALLINT
INTEGER
BIGINT
DECI
MAL
REAL
DOUBLE
CHAR
VARCHAR
LONGVARCHAR
CLOB
GRAPHIC
VARGRAPHIC
LONGVARG
DBCLOB
DATE
TI
ME
TI
MESTAMP
BLOB
SMALLINT Y Y Y Y Y Y Y - - - - - - - - - - -
INTEGER Y Y Y Y Y Y Y - - - - - - - - - - -
BIGINT 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 Y1 Y1 - - Y Y Y Y
VARCHAR Y Y Y Y - - Y Y Y Y Y1 Y1 - - Y Y Y Y
LONG VARCHAR - - - - - - Y Y Y Y - - Y1 Y1 - - - Y
CLOB - - - - - - Y Y Y Y - - - Y1 - - - Y
GRAPHIC - - - - - - Y1 Y1 - - Y Y Y Y Y1 Y1 Y1 Y
VARGRAPHIC - - - - - - Y1 Y1 - - Y Y Y Y Y1 Y1 Y1 Y
LONGVARGRAPHIC
- - - - - - - - Y1 Y1 Y Y Y Y - - - Y
DBCLOB - - - - - - - - - Y1 Y Y Y Y - - - Y
DATE - - - - - - Y Y - - Y1 Y1 - - Y - - -
TIME - - - - - - Y Y - - Y1 Y1 - - - Y - -
TIMESTAMP - - - - - - Y Y - - Y1 Y1 - - Y Y Y -
BLOB - - - - - - - - - - - - - - - - - Y
Notes
v See the description preceding the table for information on supported casts involving user-definedtypes and reference types.
v Only a DATALINK type can be cast to a DATALINK type.
v It is not possible to cast a structured type value to anything else.
1 Cast is only supported for Unicode databases.
Casting between data types
Chapter 2. Language elements 115
Related reference:
v “Expressions” on page 187v “CREATE FUNCTION statement” in the SQL Reference, Volume 2
v “CURRENT PATH” on page 159v “Promotion of data types” on page 111v “Assignments and comparisons” on page 117
Casting between data types
116 SQL Reference, Volume 1
Assignments and comparisons
The basic operations of SQL are assignment and comparison. Assignmentoperations are performed during the execution of INSERT, UPDATE, FETCH,SELECT INTO, VALUES INTO and SET transition-variable statements.Arguments of functions are also assigned when invoking a function.Comparison operations are performed during the execution of statements thatinclude predicates and other language elements such as MAX, MIN,DISTINCT, GROUP BY, and ORDER BY.
One basic rule for both operations is that the data type of the operandsinvolved must be compatible. The compatibility rule also applies to setoperations.
Another basic rule for assignment operations is that a null value cannot beassigned to a column that cannot contain null values, nor to a host variablethat does not have an associated indicator variable.
Assignments and comparisons involving both character and graphic data areonly supported when one of the strings is a literal.
Following is a compatibility matrix showing the data type compatibilities forassignment and comparison operations.
Table 9. Data Type Compatibility for Assignments and Comparisons
Operands BinaryInteger
DecimalNumber
FloatingPoint
CharacterString
GraphicString
Date Time Time-stamp
BinaryString
UDT
BinaryInteger
Yes Yes Yes No No No No No No 2
DecimalNumber
Yes Yes Yes No No No No No No 2
FloatingPoint
Yes Yes Yes No No No No No No 2
CharacterString
No No No Yes Yes 6,7 1 1 1 No 3 2
GraphicString
No No No Yes 6,7 Yes 1 1 1 No 2
Date No No No 1 1 Yes No No No 2
Time No No No 1 1 No Yes No No 2
Timestamp No No No 1 1 No No Yes No 2
BinaryString
No No No No 3 No No No No Yes 2
UDT 2 2 2 2 2 2 2 2 2 Yes
Assignments and comparisons
Chapter 2. Language elements 117
Table 9. Data Type Compatibility for Assignments and Comparisons (continued)
Operands BinaryInteger
DecimalNumber
FloatingPoint
CharacterString
GraphicString
Date Time Time-stamp
BinaryString
UDT
1 The compatibility of datetime values and strings is limited to assignment and comparison:
v Datetime values can be assigned to string columns and to string variables.
v A valid string representation of a date can be assigned to a date column or compared with a date.
v A valid string representation of a time can be assigned to a time column or compared with a time.
v A valid string representation of a timestamp can be assigned to a timestamp column or comparedwith a timestamp.
(Graphic string support is only available for Unicode databases.)
2 A user-defined distinct type value is only comparable to a value defined with the same user-defineddistinct type. In general, assignments are supported between a distinct type value and its source datatype. A user-defined structured type is not comparable and can only be assigned to an operand of thesame structured type or one of its supertypes. For additional information see “User-defined typeassignments” on page 127.
3 Note that this means that character strings defined with the FOR BIT DATA attribute are also notcompatible with binary strings.
4 A DATALINK operand can only be assigned to another DATALINK operand. The DATALINK valuecan only be assigned to a column if the column is defined with NO LINK CONTROL, or the file existsand is not already under file link control.
5 For information on assignment and comparison of reference types, see “Reference type assignments”on page 127 and “Reference type comparisons” on page 133.
6 Only supported for Unicode databases.
7 Bit data and graphic strings are not compatible.
Numeric assignmentsThe basic rule for numeric assignments is that the whole part of a decimal orinteger number is never truncated. If the scale of the target number is lessthan the scale of the assigned number the excess digits in the fractional partof a decimal number are truncated.
Decimal or integer to floating-point: Floating-point numbers areapproximations of real numbers. Hence, when a decimal or integer number isassigned to a floating-point column or variable, the result may not be identicalto the original number.
Floating-point or decimal to integer: When a floating-point or decimalnumber is assigned to an integer column or variable, the fractional part of thenumber is lost.
Assignments and comparisons
118 SQL Reference, Volume 1
Decimal to decimal: When a decimal number is assigned to a decimalcolumn or variable, the number is converted, if necessary, to the precision andthe scale of the target. The necessary number of leading zeros is appended oreliminated, and, in the fractional part of the number, the necessary number oftrailing zeros is appended, or the necessary number of trailing digits iseliminated.
Integer to decimal: When an integer is assigned to a decimal column orvariable, the number is converted first to a temporary decimal number andthen, if necessary, to the precision and scale of the target. The precision andscale of the temporary decimal number is 5,0 for a small integer, or 11,0 for alarge integer, or 19,0 for a big integer.
Floating-point to decimal: When a floating-point number is converted todecimal, the number is first converted to a temporary decimal number ofprecision 31, and then, if necessary, truncated to the precision and scale of thetarget. In this conversion, the number is rounded (using floating-pointarithmetic) to a precision of 31 decimal digits. As a result, a number less than0.5*10-31 is reduced to 0. The scale is given the largest possible value thatallows the whole part of the number to be represented without loss ofsignificance.
String assignmentsThere are two types of assignments:v storage assignment is when a value is assigned to a column or parameter of a
routinev retrieval assignment is when a value is assigned to a host variable.
The rules for string assignment differ based on the assignment type.
Storage assignment: The basic rule is that the length of the string assignedto a column or routine parameter must not be greater than the length attributeof the column or the routine parameter. If the length of the string is greaterthan the length attribute of the column or the routine parameter, the followingactions may occur:v The string is assigned with trailing blanks truncated (from all string types
except long strings) to fit the length attribute of the target column orroutine parameter
v An error is returned (SQLSTATE 22001) when:– Non-blank characters would be truncated from other than a long string– Any character (or byte) would be truncated from a long string.
If a string is assigned to a fixed-length column and the length of the string isless than the length attribute of the target, the string is padded to the rightwith the necessary number of single-byte, double-byte, or UCS-2 blanks. The
Decimal to decimal
Chapter 2. Language elements 119
pad character is always a blank, even for columns defined with the FOR BITDATA attribute. (UCS-2 defines several SPACE characters with differentproperties. For a Unicode database, the database manager always uses theASCII SPACE at position x’0020’ as UCS-2 blank. For an EUC database, theIDEOGRAPHIC SPACE at position x’3000’ is used for padding GRAPHICstrings.)
Retrieval assignment: The length of a string assigned to a host variable maybe longer than the length attribute of the host variable. When a string isassigned to a host variable and the length of the string is longer than thelength attribute of the variable, the string is truncated on the right by thenecessary number of characters (or bytes). When this occurs, a warning isreturned (SQLSTATE 01004) and the value ’W’ is assigned to the SQLWARN1field of the SQLCA.
Furthermore, if an indicator variable is provided, and the source of the valueis not a LOB, the indicator variable is set to the original length of the string.
If a character string is assigned to a fixed-length variable and the length of thestring is less than the length attribute of the target, the string is padded to theright with the necessary number of single-byte, double-byte, or UCS-2 blanks.The pad character is always a blank, even for strings defined with the FORBIT DATA attribute. (UCS-2 defines several SPACE characters with differentproperties. For a Unicode database, the database manager always uses theASCII SPACE at position x’0020’ as UCS-2 blank. For an EUC database, theIDEOGRAPHIC SPACE at position x’3000’ is used for padding GRAPHICstrings.)
Retrieval assignment of C NUL-terminated host variables is handled based onoptions specified with the PREP or BIND command.
Conversion rules for string assignments: A character string or graphic stringassigned to a column or host variable is first converted, if necessary, to thecode page of the target. Character conversion is necessary only if all of thefollowing are true:v The code pages are different.v The string is neither null nor empty.v Neither string has a code page value of 0 (FOR BIT DATA).
For Unicode databases, character strings can be assigned to a graphic column,and graphic strings can be assigned to a character column.
MBCS considerations for character string assignments: There are severalconsiderations when assigning character strings that could contain both single
Storage assignment
120 SQL Reference, Volume 1
and multi-byte characters. These considerations apply to all character strings,including those defined as FOR BIT DATA.v Blank padding is always done using the single-byte blank character (X'20').v Blank truncation is always done based on the single-byte blank character
(X'20'). The double-byte blank character is treated like any other characterwith respect to truncation.
v Assignment of a character string to a host variable may result infragmentation of MBCS characters if the target host variable is not largeenough to contain the entire source string. If an MBCS character isfragmented, each byte of the MBCS character fragment in the target is set toa single-byte blank character (X'20'), no further bytes are moved from thesource, and SQLWARN1 is set to ’W’ to indicate truncation. Note that thesame MBCS character fragment handling applies even when the characterstring is defined as FOR BIT DATA.
DBCS considerations for graphic string assignments: Graphic stringassignments are processed in a manner analogous to that for character strings.For non-Unicode databases, graphic string data types are compatible onlywith other graphic string data types, and never with numeric, character string,or datetime data types. For Unicode databases, graphic string data types arecompatible with character string data types.
If a graphic string value is assigned to a graphic string column, the length ofthe value must not be greater than the length of the column.
If a graphic string value (the ’source’ string) is assigned to a fixed lengthgraphic string data type (the ’target’, which can be a column or host variable),and the length of the source string is less than that of the target, the targetwill contain a copy of the source string which has been padded on the rightwith the necessary number of double-byte blank characters to create a valuewhose length equals that of the target.
If a graphic string value is assigned to a graphic string host variable and thelength of the source string is greater than the length of the host variable, thehost variable will contain a copy of the source string which has beentruncated on the right by the necessary number of double-byte characters tocreate a value whose length equals that of the host variable. (Note that for thisscenario, truncation need not be concerned with bisection of a double-bytecharacter; if bisection were to occur, either the source value or target hostvariable would be an ill-defined graphic string data type.) The warning flagSQLWARN1 in the SQLCA will be set to ’W’. The indicator variable, ifspecified, will contain the original length (in double-byte characters) of thesource string. In the case of DBCLOB, however, the indicator variable does notcontain the original length.
MBCS considerations for character string assignments
Chapter 2. Language elements 121
Retrieval assignment of C NUL-terminated host variables (declared usingwchar_t) is handled based on options specified with the PREP or BINDcommand.
Datetime assignmentsThe basic rule for datetime assignments is that a DATE, TIME, orTIMESTAMP value can only be assigned to a column with a matching datatype (whether DATE, TIME, or TIMESTAMP) or to a fixed- or varying-lengthstring variable or string column. The assignment must not be to a LONGVARCHAR, CLOB, LONG VARGRAPHIC, DBCLOB, or BLOB variable orcolumn.
When a datetime value is assigned to a string variable or string column,conversion to a string representation is automatic. Leading zeros are notomitted from any part of the date, time, or timestamp. The required length ofthe target will vary, depending on the format of the string representation. Ifthe length of the target is greater than required, and the target is afixed-length string, it is padded on the right with blanks. If the length of thetarget is less than required, the result depends on the type of datetime valueinvolved, and on the type of target.
When the target is a host variable, the following rules apply:v For a DATE: If the variable length is less than 10 characters, an error
occurs.v For a TIME: If the USA format is used, the length of the variable must not
be less than 8 characters; in other formats the length must not be less than 5characters.If ISO or JIS formats are used, and if the length of the host variable is lessthan 8 characters, the seconds part of the time is omitted from the resultand assigned to the indicator variable, if provided. The SQLWARN1 field ofthe SQLCA is set to indicate the omission.
v For a TIMESTAMP: If the host variable is less than 19 characters, an erroroccurs. If the length is less than 26 characters, but greater than or equal to19 characters, trailing digits of the microseconds part of the value areomitted. The SQLWARN1 field of the SQLCA is set to indicate the omission.
DATALINK assignmentsThe assignment of a value to a DATALINK column results in theestablishment of a link to a file unless the linkage attributes of the value areempty or the column is defined with NO LINK CONTROL. In cases where alinked value already exists in the column, that file is unlinked. Assigning anull value where a linked value already exists also unlinks the file associatedwith the old value.
DBCS considerations for graphic string assignments
122 SQL Reference, Volume 1
If the application provides the same data location as already exists in thecolumn, the link is retained. There are several reasons that this might be done:v The comment is being changed.v If the table is placed in Datalink Reconcile Not Possible (DRNP) state, the
links in the table can be reinstated by providing linkage attributes identicalto the ones in the column.
v If the column is defined with WRITE PERMISSION ADMIN and the filecontent is changed, a new version of the link can be established byproviding a DATALINK value constructed by using the DLURLNEWCOPYfunction with the same data location.
v If the column is defined with WRITE PERMISSION ADMIN and the filecontent is changed, but the change needs to be backed out, the existingversion of the link can be reinstated by providing a DATALINK valueconstructed by using the DLURLPREVIOUSCOPY function with the samedata location.
v The content of the referenced file is being replaced by another file specifiedin the DLURLREPLACECONTENT scalar function.
A DATALINK value may be assigned to a column in any of the followingways:v The DLVALUE scalar function can be used to create a new DATALINK
value and assign it to a column. Unless the value contains only a commentor the URL is exactly the same, the act of assignment will link the file.
v A DATALINK value can be constructed in a CLI parameter using the CLIfunction SQLBuildDataLink. This value can then be assigned to a column.Unless the value contains only a comment or the URL is exactly the same,the act of assignment will link the file.
v The DLURLNEWCOPY scalar function can be used to construct aDATALINK value and assign it to a column. The data location referencedby the constructed DATALINK value must be the same as the one thatalready exists in the column. The act of assignment by using an UPDATEstatement will re-establish the link to the file. A file backup will be taken ifthe column is defined with RECOVERY YES. This type of assignment isused to notify the database that the file has been updated. The database isthus made aware of the new file and will re-establish a new link to the file.
v The DLURLPREVIOUSCOPY scalar function can be used to construct aDATALINK value and assign it to a column. The data location referencedby the constructed DATALINK value must be the same as the one thatalready exists in the column. The act of assignment by using an UPDATEstatement will reinstate the link. It will also restore the file to the previousversion from the archive if the column is defined with RECOVERY YES.This type of assignment is used to back out any change to the file that wasmade since the previous committed version.
DATALINK assignments
Chapter 2. Language elements 123
v The DLURLREPLACECONTENT scalar function can be used to create anew DATALINK value and assign it to a column. The act of assignmentwill not only link the file, but also replace the content with another filespecified in the DLURLREPLACECONTENT scalar function.
When assigning a value to a DATALINK column, the following errorconditions return SQLSTATE 428D1:v Data Location (URL) format is invalid (reason code 21).v File server is not registered with this database (reason code 22).v Invalid link type specified (reason code 23).v Invalid length of comment or URL (reason code 27).
Note that the size of a URL parameter or function result is the same onboth input or output, and the size is bound by the length of theDATALINK column. However, in some cases the URL value is returnedwith an access token attached. In situations where this is possible, theoutput location must have sufficient storage space for the access token andthe length of the DATALINK column. Hence, the actual length of both thecomment and the URL (in its fully expanded form) provided on inputshould be restricted to accommodate the output storage space. If therestricted length is exceeded, this error is raised.
v Input data location does not contain a valid write token (reason code 32).The assignment requires a valid write token to be embedded in the datalocation. This requirement only applies when the column is defined withWRITE PERMISSION ADMIN REQUIRING TOKEN FOR UPDATE, and theDATALINK value is constructed by the DLURLNEWCOPY orDLURLPREVIOUSCOPY scalar function. On the other hand, a user has theoption to provide a write token for a DATALINK column defined withWRITE PERMISSION ADMIN NOT REQUIRING TOKEN FOR UPDATE.However, if the token is not valid, the same error is raised.This error can also occur when constructing a DATALINK value using theDLURLNEWCOPY or DLURLPREVIOUSCOPY scalar function with value’1’ specified in the second argument, but the value does not contain a validwrite token.
v The DATALINK value constructed by the DLURLPREVIOUSCOPY scalarfunction can be assigned only to a DATALINK column defined with WRITEPERMISSION ADMIN and RECOVERY YES (reason code 33).
v The DATALINK value constructed by the DLURLNEWCOPY orDLURLPREVIOUSCOPY scalar function does not match the value thatalready exists in the column (reason code 34).
v The DATALINK value constructed by the DLURLNEWCOPY orDLURLPREVIOUSCOPY scalar function cannot be used in an INSERTstatement to assign a new value (reason code 35).
DATALINK assignments
124 SQL Reference, Volume 1
v The DATALINK value with scheme DFS cannot be assigned to aDATALINK column defined with WRITE PERMISSION ADMIN (reasoncode 38).
v The DATALINK value constructed by the DLURLNEWCOPY scalarfunction cannot be assigned to a DATALINK column defined with WRITEPERMISSION BLOCKED (reason code 39).
v The same DATALINK value constructed by the DLURLNEWCOPY orDLURLPREVIOUSCOPY scalar function cannot be assigned multiple timeswithin the same transaction (reason code 41).
v The DATALINK value constructed by the DLURLREPLACECONTENTscalar function can be assigned to a DATALINK column defined with NOLINK CONTROL, only if the second argument is an empty string or a nullvalue (reason code 42).
v The unlink operation of the replacement file specified in theDLREPLACECONTENT scalar function has not committed (reason code43).
v The replacement file specified in the DLREPLACECONTENT scalarfunction is being used in another replacement process (reason code 44).
v The DATALINK-referenced file is being used as the replacement file inanother operation (reason code 45).
v The format of the replacement file specified in the DLREPLACECONTENTscalar function is not valid (reason code 46).
v The replacement file value specified in the DLREPLACECONTENT scalarfunction cannot be a directory or a symbolic link (reason code 47).
v The replacement file specified in the DLREPLACECONTENT scalarfunction is being linked to a database (reason code 48).
v The replacement file specified in the DLREPLACECONTENT scalarfunction cannot be found by a Data Links File Manager (reason code 49).
v The DATALINK value constructed by the DLURLNEWCOPY scalarfunction with a write token contained in the data location value can beassigned only to a DATALINK column with WRITE PERMISSION ADMIN(reason code 50).
When the assignment is also creating a link, the following errors can occur:v File server not currently available (SQLSTATE 57050).v File does not exist (SQLSTATE 428D1, reason code 24).v File already linked to another column (SQLSTATE 428D1, reason code 25).
Note that this error will be raised even if the link is to a different database.v Referenced file cannot be accessed for linking (reason code 26).v The write token embedded in the data location does not match the write
token used to open the file (SQLSTATE 428D1, reason code 36).
DATALINK assignments
Chapter 2. Language elements 125
v DATALINK value referenced file is in the update-in-progress state(SQLSTATE 428D1, reason code 37).
v The previous archive copy of the DATALINK value referenced file is notavailable (SQLSTATE 428D1, reason code 40).
In addition, when the assignment removes an existing link, the followingerrors can occur:v File server not currently available (SQLSTATE 57050).v File with referential integrity control is not in a correct state according to
the Data Links File Manager (SQLSTATE 58004).v DATALINK value referenced file is in the update-in-progress state
(SQLSTATE 428D1, reason code 37).
If, when retrieving a DATALINK value for write access (by using theDLURLCOMPLETEWRITE or DLURLPATHWRITE scalar function), theDATALINK column is defined with WRITE PERMISSION ADMIN, thedirectory access privilege is checked at the file server (DataLink FileManager). The user who issues the query must have the authority to write tothe files under the given directory before a write token is generated andembedded in the return DATALINK value. If the user does not have writeauthority, no write token will be generated, and the SELECT statement willfail (SQLSTATE 42511, reason code 1).
Portions of a DATALINK value can be assigned to host variables followingthe application of scalar functions such as DLLINKTYPE or DLURLPATH.
Note that usually no attempt is made to access the file server at retrieval time.It is therefore possible that subsequent attempts to access the file serverthrough file system commands might fail. It may be necessary to access thefile server to determine the prefix name associated with a path. This can bechanged at the file server when the mount point of a file system is moved.First access of a file on a server will cause the required values to be retrievedfrom the file server and cached at the database server for the subsequentretrieval of DATALINK values for that file server. An error is returned if thefile server cannot be accessed (SQLSTATE 57050).
If using the scalar functions DLURLCOMPLETEWRITE orDLURLPATHWRITE to retrieve a DATALINK value, it may be necessary toaccess the file server to determine the directory access privilege on a path fora user. An error is returned if the file server cannot be accessed (SQLSTATE57050).
When retrieving a DATALINK value, the registry of file servers at thedatabase server is checked to confirm that the file server is still registeredwith the database server (SQLSTATE 55022). In addition, a warning may be
DATALINK assignments
126 SQL Reference, Volume 1
returned when retrieving a DATALINK value because the table is in reconcilepending or reconcile not possible state (SQLSTATE 01627).
User-defined type assignmentsWith user-defined types, different rules are applied for assignments to hostvariables than are used for all other assignments.
Distinct Types: Assignment to host variables is done based on the source typeof the distinct type. That is, it follows the rule:v A value of a distinct type on the right hand side of an assignment is
assignable to a host variable on the left hand side if and only if the sourcetype of this distinct type is assignable to this host variable.
If the target of the assignment is a column based on a distinct type, the sourcedata type must be castable to the target data type.
Structured Types: Assignment to and from host variables is based on thedeclared type of the host variable; that is, it follows the rule:
A value of a structured type on the right hand side of an assignment isassignable to a host variable on the left hand side if and only if thedeclared type of the host variable is the structured type or a supertype ofthe structured type.
If the target of the assignment is a column of a structured type, the sourcedata type must be the target data type or a subtype of the target data type.
Reference type assignmentsA reference type with a target type of T can be assigned to a reference typecolumn that is also a reference type with target type of S where S is asupertype of T. If an assignment is made to a scoped reference column orvariable, no check is performed to ensure that the actual value being assignedexists in the target table or view defined by the scope.
Assignment to host variables is done based on the representation type of thereference type. That is, it follows the rule:v A value of a reference type on the right hand side of an assignment is
assignable to a host variable on the left hand side if and only if therepresentation type of this reference type is assignable to this host variable.
If the target of the assignment is a column, and the right hand side of theassignment is a host variable, the host variable must be explicitly cast to thereference type of the target column.
Numeric comparisonsNumbers are compared algebraically; that is, with regard to sign. Forexample, −2 is less than +1.
DATALINK assignments
Chapter 2. Language elements 127
If one number is an integer and the other is decimal, the comparison is madewith a temporary copy of the integer, which has been converted to decimal.
When decimal numbers with different scales are compared, the comparison ismade with a temporary copy of one of the numbers that has been extendedwith trailing zeros so that its fractional part has the same number of digits asthe other number.
If one number is floating-point and the other is integer or decimal, thecomparison is made with a temporary copy of the other number, which hasbeen converted to double-precision floating-point.
Two floating-point numbers are equal only if the bit configurations of theirnormalized forms are identical.
String comparisonsCharacter strings are compared according to the collating sequence specifiedwhen the database was created, except those with a FOR BIT DATA attributewhich are always compared according to their bit values.
When comparing character strings of unequal lengths, the comparison ismade using a logical copy of the shorter string which is padded on the rightwith single-byte blanks sufficient to extend its length to that of the longerstring. This logical extension is done for all character strings including thosetagged as FOR BIT DATA.
Character strings (except character strings tagged as FOR BIT DATA) arecompared according to the collating sequence specified when the databasewas created. For example, the default collating sequence supplied by thedatabase manager may give lowercase and uppercase versions of the samecharacter the same weight. The database manager performs a two-passcomparison to ensure that only identical strings are considered equal to eachother. In the first pass, strings are compared according to the databasecollating sequence. If the weights of the characters in the strings are equal, asecond ″tie-breaker″ pass is performed to compare the strings on the basis oftheir actual code point values.
Two strings are equal if they are both empty or if all corresponding bytes areequal. If either operand is null, the result is unknown.
Long strings and LOB strings are not supported in any comparison operationsthat use the basic comparison operators (=, <>, <, >, <=, and >=). They aresupported in comparisons using the LIKE predicate and the POSSTR function.
Numeric comparisons
128 SQL Reference, Volume 1
Portions of long strings and LOB strings of up to 4 000 bytes can be comparedusing the SUBSTR and VARCHAR scalar functions. For example, given thecolumns:
MY_SHORT_CLOB CLOB(300)MY_LONG_VAR LONG VARCHAR
then the following is valid:WHERE VARCHAR(MY_SHORT_CLOB) > VARCHAR(SUBSTR(MY_LONG_VAR,1,300))
Examples:
For these examples, ’A’, ’Á’, ’a’, and ’á’, have the code point values X’41’,X’C1’, X’61’, and X’E1’ respectively.
Consider a collating sequence where the characters ’A’, ’Á’, ’a’, ’á’ haveweights 136, 139, 135, and 138. Then the characters sort in the order of theirweights as follows:’a’ < ’A’ < ’á’ < ’Á’
Now consider four DBCS characters D1, D2, D3, and D4 with code points0xC141, 0xC161, 0xE141, and 0xE161, respectively. If these DBCS characters arein CHAR columns, they sort as a sequence of bytes according to the collationweights of those bytes. First bytes have weights of 138 and 139, therefore D3and D4 come before D2 and D1; second bytes have weights of 135 and 136.Hence, the order is as follows:D4 < D3 < D2 < D1
However, if the values being compared have the FOR BIT DATA attribute, orif these DBCS characters were stored in a GRAPHIC column, the collationweights are ignored, and characters are compared according to their codepoints as follows:
’A’ < ’a’ < ’Á’ < ’á’
The DBCS characters sort as sequence of bytes, in the order of code points asfollows:D1 < D2 < D3 < D4
Now consider a collating sequence where the characters ’A’, ’Á’, ’a’, ’á’ have(non-unique) weights 74, 75, 74, and 75. Considering collation weights alone(first pass), ’a’ is equal to ’A’, and ’á’ is equal to ’Á’. The code points of thecharacters are used to break the tie (second pass) as follows:’A’ < ’a’ < ’Á’ < ’á’
DBCS characters in CHAR columns sort a sequence of bytes, according totheir weights (first pass) and then according to their code points to break the
String comparisons
Chapter 2. Language elements 129
tie (second pass). First bytes have equal weights, so the code points (0xC1 and0xE1) break the tie. Therefore, characters D1 and D2 sort before characters D3and D4. Then the second bytes are compared in similar way, and the finalresult is as follows:D1 < D2 < D3 < D4
Once again, if the data in CHAR columns have the FOR BIT DATA attribute,or if the DBCS characters are stored in a GRAPHIC column, the collationweights are ignored, and characters are compared according to their codepoints:D1 < D2 < D3 < D4
For this particular example, the result happens to be the same as whencollation weights were used, but obviously this is not always the case.
Conversion rules for comparison: When two strings are compared, one ofthe strings is first converted, if necessary, to the encoding scheme and codepage of the other string.
Ordering of results: Results that require sorting are ordered based on thestring comparison rules discussed in “String comparisons” on page 128. Thecomparison is performed at the database server. On returning results to theclient application, code page conversion may be performed. This subsequentcode page conversion does not affect the order of the server-determined resultset.
MBCS considerations for string comparisons: Mixed SBCS/MBCS characterstrings are compared according to the collating sequence specified when thedatabase was created. For databases created with default (SYSTEM) collationsequence, all single-byte ASCII characters are sorted in correct order, butdouble-byte characters are not necessarily in code point sequence. Fordatabases created with IDENTITY sequence, all double-byte characters arecorrectly sorted in their code point order, but single-byte ASCII characters aresorted in their code point order as well. For databases created withCOMPATIBILITY sequence, a compromise order is used that sorts properly formost double-byte characters, and is almost correct for ASCII. This was thedefault collation table in DB2 Version 2.
Mixed character strings are compared byte-by-byte. This may result inunusual results for multi-byte characters that occur in mixed strings, becauseeach byte is considered independently.
Example:
For this example, ’A’, ’B’, ’a’, and ’b’ double-byte characters have the codepoint values X'8260', X'8261', X'8281', and X'8282', respectively.
String comparisons
130 SQL Reference, Volume 1
Consider a collating sequence where the code points X'8260', X'8261', X'8281',and X'8282' have weights 96, 65, 193, and 194. Then:
’B’ < ’A’ < ’a’ < ’b’
and’AB’ < ’AA’ < ’Aa’ < ’Ab’ < ’aB’ < ’aA’ < ’aa’ < ’ab’
Graphic string comparisons are processed in a manner analogous to that forcharacter strings.
Graphic string comparisons are valid between all graphic string data typesexcept LONG VARGRAPHIC. LONG VARGRAPHIC and DBCLOB data typesare not allowed in a comparison operation.
For graphic strings, the collating sequence of the database is not used. Instead,graphic strings are always compared based on the numeric (binary) values oftheir corresponding bytes.
Using the previous example, if the literals were graphic strings, then:’A’ < ’B’ < ’a’ < ’b’
and’AA’ < ’AB’ < ’Aa’ < ’Ab’ < ’aA’ < ’aB’ < ’aa’ < ’ab’
When comparing graphic strings of unequal lengths, the comparison is madeusing a logical copy of the shorter string which is padded on the right withdouble-byte blank characters sufficient to extend its length to that of thelonger string.
Two graphic values are equal if they are both empty or if all correspondinggraphics are equal. If either operand is null, the result is unknown. If twovalues are not equal, their relation is determined by a simple binary stringcomparison.
As indicated in this section, comparing strings on a byte by byte basis canproduce unusual results; that is, a result that differs from what would beexpected in a character by character comparison. The examples shown hereassume the same MBCS code page, however, the situation can be furthercomplicated when using different multi-byte code pages with the samenational language. For example, consider the case of comparing a string froma Japanese DBCS code page and a Japanese EUC code page.
Datetime comparisonsA DATE, TIME, or TIMESTAMP value may be compared either with anothervalue of the same data type or with a string representation of that data type.
MBCS considerations for string comparisons
Chapter 2. Language elements 131
All comparisons are chronological, which means the farther a point in time isfrom January 1, 0001, the greater the value of that point in time.
Comparisons involving TIME values and string representations of time valuesalways include seconds. If the string representation omits seconds, zeroseconds is implied.
Comparisons involving TIMESTAMP values are chronological without regardto representations that might be considered equivalent.
Example:TIMESTAMP(’1990-02-23-00.00.00’) > ’1990-02-22-24.00.00’
User-defined type comparisonsValues with a user-defined distinct type can only be compared with values ofexactly the same user-defined distinct type. The user-defined distinct typemust have been defined using the WITH COMPARISONS clause.
Example:
Given the following YOUTH distinct type and CAMP_DB2_ROSTER table:CREATE DISTINCT TYPE YOUTH AS INTEGER WITH COMPARISONS
CREATE TABLE CAMP_DB2_ROSTER( NAME VARCHAR(20),
ATTENDEE_NUMBER INTEGER NOT NULL,AGE YOUTH,HIGH_SCHOOL_LEVEL YOUTH)
The following comparison is valid:SELECT * FROM CAMP_DB2_ROSTER
WHERE AGE > HIGH_SCHOOL_LEVEL
The following comparison is not valid:SELECT * FROM CAMP_DB2_ROSTER
WHERE AGE > ATTENDEE_NUMBER
However, AGE can be compared to ATTENDEE_NUMBER by using afunction or CAST specification to cast between the distinct type and thesource type. The following comparisons are all valid:
SELECT * FROM CAMP_DB2_ROSTERWHERE INTEGER(AGE) > ATTENDEE_NUMBER
SELECT * FROM CAMP_DB2_ROSTERWHERE CAST( AGE AS INTEGER) > ATTENDEE_NUMBER
SELECT * FROM CAMP_DB2_ROSTERWHERE AGE > YOUTH(ATTENDEE_NUMBER)
Datetime comparisons
132 SQL Reference, Volume 1
SELECT * FROM CAMP_DB2_ROSTERWHERE AGE > CAST(ATTENDEE_NUMBER AS YOUTH)
Values with a user-defined structured type cannot be compared with anyother value (the NULL predicate and the TYPE predicate can be used).
Reference type comparisonsReference type values can be compared only if their target types have acommon supertype. The appropriate comparison function will only be foundif the schema name of the common supertype is included in the function path.The comparison is performed using the representation type of the referencetypes. The scope of the reference is not considered in the comparison.
Related reference:
v “Identifiers” on page 65v “LIKE predicate” on page 238v “POSSTR” on page 427v “Datetime values” on page 101v “Casting between data types” on page 113v “Rules for result data types” on page 134v “Rules for string conversions” on page 139
User-defined type comparisons
Chapter 2. Language elements 133
Rules for result data types
The data types of a result are determined by rules which are applied to theoperands in an operation. This section explains those rules.
These rules apply to:v Corresponding columns in fullselects of set operations (UNION,
INTERSECT and EXCEPT)v Result expressions of a CASE expressionv Arguments of the scalar function COALESCE (or VALUE)v Expression values of the in list of an IN predicatev Corresponding expressions of a multiple row VALUES clause.
These rules are applied subject to other restrictions on long strings for thevarious operations.
The rules involving various data types follow. In some cases, a table is used toshow the possible result data types.
These tables identify the data type of the result, including the applicablelength or precision and scale. The result type is determined by considering theoperands. If there is more than one pair of operands, start by considering thefirst pair. This gives a result type which is considered with the next operandto determine the next result type, and so on. The last intermediate result typeand the last operand determine the result type for the operation. Processing ofoperations is done from left to right so that the intermediate result types areimportant when operations are repeated. For example, consider a situationinvolving:
CHAR(2) UNION CHAR(4) UNION VARCHAR(3)
The first pair results in a type of CHAR(4). The result values always have 4characters. The final result type is VARCHAR(4). Values in the result from thefirst UNION operation will always have a length of 4.
Character stringsCharacter strings are compatible with other character strings. Character stringsinclude data types CHAR, VARCHAR, LONG VARCHAR, and CLOB.
If one operand is... And the other operandis...
The data type of the result is...
CHAR(x) CHAR(y) CHAR(z) where z = max(x,y)
CHAR(x) VARCHAR(y) VARCHAR(z) where z = max(x,y)
VARCHAR(x) CHAR(y) orVARCHAR(y)
VARCHAR(z) where z = max(x,y)
Rules for result data types
134 SQL Reference, Volume 1
If one operand is... And the other operandis...
The data type of the result is...
LONG VARCHAR CHAR(y),VARCHAR(y), orLONG VARCHAR
LONG VARCHAR
CLOB(x) CHAR(y),VARCHAR(y), orCLOB(y)
CLOB(z) where z = max(x,y)
CLOB(x) LONG VARCHAR CLOB(z) where z = max(x,32700)
The code page of the result character string will be derived based on the rulesfor string conversions.
Graphic stringsGraphic strings are compatible with other graphic strings. Graphic stringsinclude data types GRAPHIC, VARGRAPHIC, LONG VARGRAPHIC, andDBCLOB.
If one operand is... And the other operandis...
The data type of the result is...
GRAPHIC(x) GRAPHIC(y) GRAPHIC(z) where z = max(x,y)
VARGRAPHIC(x) GRAPHIC(y) ORVARGRAPHIC(y)
VARGRAPHIC(z) where z =max(x,y)
LONG VARGRAPHIC GRAPHIC(y),VARGRAPHIC(y), orLONG VARGRAPHIC
LONG VARGRAPHIC
DBCLOB(x) GRAPHIC(y),VARGRAPHIC(y), orDBCLOB(y)
DBCLOB(z) where z = max (x,y)
DBCLOB(x) LONG VARGRAPHIC DBCLOB(z) where z = max(x,16350)
The code page of the result graphic string will be derived based on the rulesfor string conversions.
Character and graphic strings in a Unicode databaseIn a Unicode database, character strings and graphic strings are compatible.
If one operand is... And the other operandis...
The data type of the result is...
GRAPHIC(x) CHAR(y) orGRAPHIC(y)
GRAPHIC(z) where z = max(x,y)
Character strings
Chapter 2. Language elements 135
If one operand is... And the other operandis...
The data type of the result is...
VARGRAPHIC(x) CHAR(y) orVARCHAR(y)
VARGRAPHIC(z) where z =max(x,y)
VARCHAR(x) GRAPHIC(y) orVARGRAPHIC
VARGRAPHIC(z) where z =max(x,y)
LONG VARGRAPHIC CHAR(y) orVARCHAR(y) or LONGVARCHAR
LONG VARGRAPHIC
LONG VARCHAR GRAPHIC(y) orVARGRAPHIC(y)
LONG VARGRAPHIC
DBCLOB(x) CHAR(y) orVARCHAR(y) orCLOB(y)
DBCLOB(z) where z = max(x,y)
DBCLOB(x) LONG VARCHAR DBCLOB(z) where z =max(x,16350)
CLOB(x) GRAPHIC(y) orVARGRAPHIC(y)
DBCLOB(z) where z = max(x,y)
CLOB(x) LONG VARGRAPHIC DBCLOB(z) where z =max(x,16350)
Binary large object (BLOB)A BLOB is compatible only with another BLOB and the result is a BLOB. TheBLOB scalar function can be used to cast from other types if they should betreated as BLOB types. The length of the result BLOB is the largest length ofall the data types.
NumericNumeric types are compatible with other numeric types. Numeric typesinclude SMALLINT, INTEGER, BIGINT, DECIMAL, REAL and DOUBLE.
If one operand is... And the other operandis...
The data type of the result is...
SMALLINT SMALLINT SMALLINT
INTEGER INTEGER INTEGER
INTEGER SMALLINT INTEGER
BIGINT BIGINT BIGINT
BIGINT INTEGER BIGINT
BIGINT SMALLINT BIGINT
DECIMAL(w,x) SMALLINT DECIMAL(p,x) wherep = x+max(w-x,5)1
Character and graphic strings in a Unicode database
136 SQL Reference, Volume 1
If one operand is... And the other operandis...
The data type of the result is...
DECIMAL(w,x) INTEGER DECIMAL(p,x) wherep = x+max(w-x,11)1
DECIMAL(w,x) BIGINT DECIMAL(p,x) wherep = x+max(w-x,19)1
DECIMAL(w,x) DECIMAL(y,z) DECIMAL(p,s) wherep = max(x,z)+max(w-x,y-z)1s
= max(x,z)
REAL REAL REAL
REAL DECIMAL, BIGINT,INTEGER, orSMALLINT
DOUBLE
DOUBLE any numeric DOUBLE1 Precision cannot exceed 31.
DATEA date is compatible with another date, or any CHAR or VARCHARexpression that contains a valid string representation of a date. The data typeof the result is DATE.
TIMEA time is compatible with another time, or any CHAR or VARCHARexpression that contains a valid string representation of a time. The data typeof the result is TIME.
TIMESTAMPA timestamp is compatible with another timestamp, or any CHAR orVARCHAR expression that contains a valid string representation of atimestamp. The data type of the result is TIMESTAMP.
DATALINKA datalink is compatible with another datalink. The data type of the result isDATALINK. The length of the result DATALINK is the largest length of allthe data types.
User-defined types
Distinct types: A user-defined distinct type is compatible only with the sameuser-defined distinct type. The data type of the result is the user-defineddistinct type.
Reference types: A reference type is compatible with another reference typeprovided that their target types have a common supertype. The data type of
Numeric
Chapter 2. Language elements 137
the result is a reference type having the common supertype as the target type.If all operands have the identical scope table, the result has that scope table.Otherwise the result is unscoped.
Structured types: A structured type is compatible with another structuredtype provided that they have a common supertype. The static data type of theresulting structured type column is the structured type that is the leastcommon supertype of either column.
For example, consider the following structured type hierarchy,A/ \B C/ \D E/ \F G
Structured types of the static type E and F are compatible with the resultingstatic type of B, which is the least common super type of E and F.
Nullable attribute of resultWith the exception of INTERSECT and EXCEPT, the result allows nulls unlessboth operands do not allow nulls.v For INTERSECT, if either operand does not allow nulls the result does not
allow nulls (the intersection would never be null).v For EXCEPT, if the first operand does not allow nulls the result does not
allow nulls (the result can only be values from the first operand).
Related reference:
v “BLOB” on page 301v “Rules for string conversions” on page 139
Reference types
138 SQL Reference, Volume 1
Rules for string conversions
The code page used to perform an operation is determined by rules which areapplied to the operands in that operation. This section explains those rules.
These rules apply to:v Corresponding string columns in fullselects with set operations (UNION,
INTERSECT and EXCEPT)v Operands of concatenationv Operands of predicates (with the exception of LIKE)v Result expressions of a CASE expressionv Arguments of the scalar function COALESCE (and VALUE)v Expression values of the in list of an IN predicatev Corresponding expressions of a multiple row VALUES clause.
In each case, the code page of the result is determined at bind time, and theexecution of the operation may involve conversion of strings to the code pageidentified by that code page. A character that has no valid conversion ismapped to the substitution character for the character set and SQLWARN10 isset to ’W’ in the SQLCA.
The code page of the result is determined by the code pages of the operands.The code pages of the first two operands determine an intermediate resultcode page, this code page and the code page of the next operand determine anew intermediate result code page (if applicable), and so on. The lastintermediate result code page and the code page of the last operanddetermine the code page of the result string or column. For each pair of codepages, the result is determined by the sequential application of the followingrules:v If the code pages are equal, the result is that code page.v If either code page is BIT DATA (code page 0), the result code page is BIT
DATA.v In a Unicode database, if one code page denotes data in an encoding
scheme that is different from the other code page, the result is UCS-2 overUTF-8 (that is, the graphic data type over the character data type). (In anon-Unicode database, conversion between different encoding schemes isnot supported.)
v For operands that are host variables (whose code page is not BIT DATA),the result code page is the database code page. Input data from such hostvariables is converted from the application code page to the database codepage before being used.
Conversions to the code page of the result are performed, if necessary, for:
Rules for string conversions
Chapter 2. Language elements 139
v An operand of the concatenation operatorv The selected argument of the COALESCE (or VALUE) scalar functionv The selected result expression of the CASE expressionv The expressions of the in list of the IN predicatev The corresponding expressions of a multiple row VALUES clausev The corresponding columns involved in set operations.
Character conversion is necessary if all of the following are true:v The code pages are differentv Neither string is BIT DATAv The string is neither null nor empty
Examples
Example 1: Given the following in a database created with code page 850:
Expression Type Code Page
COL_1 column 850
HV_2 host variable 437
When evaluating the predicate:COL_1 CONCAT :HV_2
the result code page of the two operands is 850, because the host variable datawill be converted to the database code page before being used.
Example 2: Using information from the previous example when evaluating thepredicate:
COALESCE(COL_1, :HV_2:NULLIND,)
the result code page is 850; therefore, the result code page for the COALESCEscalar function will be code page 850.
Rules for string conversions
140 SQL Reference, Volume 1
Partition-compatible data types
Partition compatibility is defined between the base data types of correspondingcolumns of partitioning keys. Partition-compatible data types have theproperty that two variables, one of each type, with the same value, aremapped to the same partitioning map index by the same partitioningfunction.
Table 10 shows the compatibility of data types in partitions.
Partition compatibility has the following characteristics:v Internal formats are used for DATE, TIME, and TIMESTAMP. They are not
compatible with each other, and none are compatible with CHAR.v Partition compatibility is not affected by columns with NOT NULL or FOR
BIT DATA definitions.v NULL values of compatible data types are treated identically. Different
results might be produced for NULL values of non-compatible data types.v Base data type of the UDT is used to analyze partition compatibility.v Decimals of the same value in the partitioning key are treated identically,
even if their scale and precision differ.v Trailing blanks in character strings (CHAR, VARCHAR, GRAPHIC or
VARGRAPHIC) are ignored by the system-provided hashing function.v CHAR or VARCHAR of different lengths are compatible data types.v REAL or DOUBLE values that are equal are treated identically even though
their precision differs.
Table 10. Partition Compatibilities
Operands BinaryInteger
DecimalNumber
FloatingPoint
CharacterString
GraphicString
Date Time Time-stamp
DistinctType
StructuredType
BinaryInteger
Yes No No No No No No No 1 No
DecimalNumber
No Yes No No No No No No 1 No
FloatingPoint
No No Yes No No No No No 1 No
CharacterString3
No No No Yes2 No No No No 1 No
GraphicString3
No No No No Yes No No No 1 No
Date No No No No No Yes No No 1 No
Time No No No No No No Yes No 1 No
Partition-compatible data types
Chapter 2. Language elements 141
Table 10. Partition Compatibilities (continued)
Operands BinaryInteger
DecimalNumber
FloatingPoint
CharacterString
GraphicString
Date Time Time-stamp
DistinctType
StructuredType
TimestampNo No No No No No No Yes 1 No
DistinctType
1 1 1 1 1 1 1 1 1 No
StructuredType3
No No No No No No No No No No
Note:1 A user-defined distinct type (UDT) value is partition compatible with the source type of the
UDT or any other UDT with a partition compatible source type.2 The FOR BIT DATA attribute does not affect the partition compatibility.3 Note that user-defined structured types and data types LONG VARCHAR, LONG
VARGRAPHIC, CLOB, DBCLOB, and BLOB are not applicable for partition compatibility sincethey are not supported in partitioning keys.
Partition-compatible data types
142 SQL Reference, Volume 1
Constants
A constant (sometimes called a literal) specifies a value. Constants are classifiedas string constants or numeric constants. Numeric constants are furtherclassified as integer, floating-point, or decimal.
All constants have the NOT NULL attribute.
A negative zero value in a numeric constant (-0) is the same value as a zerowithout the sign (0).
User-defined types have strong typing. This means that a user-defined type isonly compatible with its own type. A constant, however, has a built-in type.Therefore, an operation involving a user-defined type and a constant is onlypossible if the user-defined type has been cast to the constant’s built-in type,or if the constant has been cast to the user-defined type. For example, usingthe table and distinct type in “User-defined type comparisons” on page 132,the following comparisons with the constant 14 are valid:
SELECT * FROM CAMP_DB2_ROSTERWHERE AGE > CAST(14 AS YOUTH)
SELECT * FROM CAMP_DB2_ROSTERWHERE CAST(AGE AS INTEGER) > 14
The following comparison is not valid:SELECT * FROM CAMP_DB2_ROSTER
WHERE AGE > 14
Integer constantsAn integer constant specifies an integer as a signed or unsigned number with amaximum of 19 digits that does not include a decimal point. The data type ofan integer constant is large integer if its value is within the range of a largeinteger. The data type of an integer constant is big integer if its value isoutside the range of large integer but within the range of a big integer. Aconstant that is defined outside the range of big integer values is considered adecimal constant.
Note that the smallest literal representation of a large integer constant is-2 147 483 647, and not -2 147 483 648, which is the limit for integer values.Similarly, the smallest literal representation of a big integer constant is-9 223 372 036 854 775 807, and not -9 223 372 036 854 775 808, which is the limitfor big integer values.
Examples:64 -15 +100 32767 720176 12345678901
Constants
Chapter 2. Language elements 143
In syntax diagrams, the term 'integer' is used for a large integer constant thatmust not include a sign.
Floating-point constantsA floating-point constant specifies a floating-point number as two numbersseparated by an E. The first number may include a sign and a decimal point;the second number may include a sign but not a decimal point. The data typeof a floating-point constant is double-precision. The value of the constant isthe product of the first number and the power of 10 specified by the secondnumber; it must be within the range of floating-point numbers. The numberof characters in the constant must not exceed 30.
Examples:15E1 2.E5 2.2E-1 +5.E+2
Decimal constantsA decimal constant is a signed or unsigned number that consists of no morethan 31 digits and either includes a decimal point or is not within the range ofbinary integers. It must be within the range of decimal numbers. Theprecision is the total number of digits (including leading and trailing zeros);the scale is the number of digits to the right of the decimal point (includingtrailing zeros).
Examples:25.5 1000. -15. +37589.3333333333
Character string constantsA character string constant specifies a varying-length character string, andconsists of a sequence of characters that starts and ends with an apostrophe('). This form of string constant specifies the character string containedbetween the string delimiters. The length of the character string must not begreater than 32 672 bytes. Two consecutive string delimiters are used torepresent one string delimiter within the character string.
Examples:'12/14/1985''32''DON''T CHANGE'
The constant value is always converted to the database code page when it isbound to the database. It is considered to be in the database code page.Therefore, if used in an expression that combines a constant with a FOR BITDATA column, and whose result is FOR BIT DATA, the constant value willnot be converted from its database code page representation when used.
Integer constants
144 SQL Reference, Volume 1
Hexadecimal constantsA hexadecimal constant specifies a varying-length character string in the codepage of the application server.
The format of a hexadecimal constant is an X followed by a sequence ofcharacters that starts and ends with an apostrophe ('). The characters betweenthe apostrophes must be an even number of hexadecimal digits. The numberof hexadecimal digits must not exceed 16 336, otherwise an error is raised(SQLSTATE -54002). A hexadecimal digit represents 4 bits. It is specified as adigit or any of the letters A through F (uppercase or lowercase), where Arepresents the bit pattern '1010', B represents '1011', and so on. If ahexadecimal constant is improperly formatted (for example, if it contains aninvalid hexadecimal digit or an odd number of hexadecimal digits), an error israised (SQLSTATE 42606).
Examples:X'FFFF' representing the bit pattern '1111111111111111'
X'4672616E6B' representing the VARCHAR pattern of the ASCII string 'Frank'
Graphic string constantsA graphic string constant specifies a varying-length graphic string consisting ofa sequence of double-byte characters that starts and ends with a single-byteapostrophe ('), and that is preceded by a single-byte G or N. The charactersbetween the apostrophes must represent an even number of bytes, and thelength of the graphic string must not exceed 16 336 bytes.
Examples:G'double-byte character string'N'double-byte character string'
The apostrophe must not appear as part of an MBCS character to beconsidered a delimiter.
Related reference:
v “Expressions” on page 187v “Assignments and comparisons” on page 117
Hexadecimal constants
Chapter 2. Language elements 145
Special registers
Special registers
A special register is a storage area that is defined for an application process bythe database manager. It is used to store information that can be referenced inSQL statements. Special registers are in the database code page.
The name of a special register can be specified with the underscore character;for example, CURRENT_DATE.
Some special registers can be updated using the SET statement. The followingtable shows which of the special registers can be updated.
Table 11. Updatable Special Registers
Special Register Updatable
CLIENT ACCTNG Yes
CLIENT APPLNAME Yes
CLIENT USERID Yes
CLIENT WRKSTNNAME Yes
CURRENT DATE No
CURRENT DBPARTITIONNUM No
CURRENT DEFAULT TRANSFORM GROUP Yes
CURRENT DEGREE Yes
CURRENT EXPLAIN MODE Yes
CURRENT EXPLAIN SNAPSHOT Yes
CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION Yes
CURRENT PATH Yes
CURRENT QUERY OPTIMIZATION Yes
CURRENT REFRESH AGE Yes
CURRENT SCHEMA Yes
CURRENT SERVER No
CURRENT TIME No
CURRENT TIMESTAMP No
CURRENT TIMEZONE No
USER No
When a special register is referenced in a routine, the value of the specialregister in the routine depends on whether the special register is updatable or
Special registers
146 SQL Reference, Volume 1
not. For non-updatable special registers, the value is set to the default valuefor the special register. For updatable special registers, the initial value isinherited from the invoker of the routine and can be changed with asubsequent SET statement inside the routine.
Special registers
Chapter 2. Language elements 147
CLIENT ACCTNG
The CLIENT ACCTNG special register contains the value of the accountingstring from the client information specified for this connection. The data typeof the register is VARCHAR(255). The default value of this register is anempty string.
The value of the accounting string can be changed by using the Set ClientInformation (sqleseti) API.
Note that the value provided via the sqleseti API is in the application codepage, and the special register value is stored in the database code page.Depending on the data values used when setting the client information,truncation of the data value stored in the special register may occur duringcode page conversion.
Example: Get the current value of the accounting string for this connection.VALUES (CLIENT ACCTNG)
INTO :ACCT_STRING
CLIENT ACCTNG
148 SQL Reference, Volume 1
CLIENT APPLNAME
The CLIENT APPLNAME special register contains the value of the applicationname from the client information specified for this connection. The data typeof the register is VARCHAR(255). The default value of this register is anempty string.
The value of the application name can be changed by using the Set ClientInformation (sqleseti) API.
Note that the value provided via the sqleseti API is in the application codepage, and the special register value is stored in the database code page.Depending on the data values used when setting the client information,truncation of the data value stored in the special register may occur duringcode page conversion.
Example: Select which departments are allowed to use the application beingused in this connection.
SELECT DEPTFROM DEPT_APPL_MAPWHERE APPL_NAME = CLIENT APPLNAME
CLIENT APPLNAME
Chapter 2. Language elements 149
CLIENT USERID
The CLIENT USERID special register contains the value of the client user IDfrom the client information specified for this connection. The data type of theregister is VARCHAR(255). The default value of this register is an emptystring.
The value of the client user ID can be changed by using the Set ClientInformation (sqleseti) API.
Note that the value provided via the sqleseti API is in the application codepage, and the special register value is stored in the database code page.Depending on the data values used when setting the client information,truncation of the data value stored in the special register may occur duringcode page conversion.
Example: Find out in which department the current client user ID works.SELECT DEPT
FROM DEPT_USERID_MAPWHERE USER_ID = CLIENT USERID
CLIENT USERID
150 SQL Reference, Volume 1
CLIENT WRKSTNNAME
The CLIENT WRKSTNNAME special register contains the value of theworkstation name from the client information specified for this connection.The data type of the register is VARCHAR(255). The default value of thisregister is an empty string.
The value of the workstation name can be changed by using the Set ClientInformation (sqleseti) API.
Note that the value provided via the sqleseti API is in the application codepage, and the special register value is stored in the database code page.Depending on the data values used when setting the client information,truncation of the data value stored in the special register may occur duringcode page conversion.
Example: Get the workstation name being used for this connection.VALUES (CLIENT WRKSTNNAME)
INTO :WS_NAME
CLIENT WRKSTNNAME
Chapter 2. Language elements 151
CURRENT DATE
The CURRENT DATE (or CURRENT_DATE) special register specifies a datethat is based on a reading of the time-of-day clock when the SQL statement isexecuted at the application server. If this special register is used more thanonce within a single SQL statement, or used with CURRENT TIME orCURRENT TIMESTAMP within a single statement, all values are based on asingle clock reading.
When used in an SQL statement inside a routine, CURRENT DATE is notinherited from the invoking statement.
In a federated system, CURRENT DATE can be used in a query intended fordata sources. When the query is processed, the date returned will be obtainedfrom the CURRENT DATE register at the federated server, not from the datasources.
Example: Using the PROJECT table, set the project end date (PRENDATE) ofthe MA2111 project (PROJNO) to the current date.
UPDATE PROJECTSET PRENDATE = CURRENT DATEWHERE PROJNO = ’MA2111’
CURRENT DATE
152 SQL Reference, Volume 1
CURRENT DBPARTITIONNUM
The CURRENT DBPARTITIONNUM (or CURRENT_DBPARTITIONNUM)special register specifies an INTEGER value that identifies the coordinatornode number for the statement. For statements issued from an application, thecoordinator is the partition to which the application connects. For statementsissued from a routine, the coordinator is the partition from which the routineis invoked.
When used in an SQL statement inside a routine, CURRENTDBPARTITIONNUM is never inherited from the invoking statement.
CURRENT DBPARTITIONNUM returns 0 if the database instance is notdefined to support partitioning. (In other words, if there is no db2nodes.cfgfile. For partitioned databases, the db2nodes.cfg file exists and containspartition, or node, definitions.)
CURRENT DBPARTITIONNUM can be changed through the CONNECTstatement, but only under certain conditions.
For compatibility with versions earlier than Version 8, the keyword NODE canbe substituted for DBPARTITIONNUM.
Example: Set the host variable APPL_NODE (integer) to the number of thepartition to which the application is connected.
VALUES CURRENT DBPARTITIONNUMINTO :APPL_NODE
Related reference:
v “CONNECT (Type 1) statement” in the SQL Reference, Volume 2
CURRENT DBPARTITIONNUM
Chapter 2. Language elements 153
CURRENT DEFAULT TRANSFORM GROUP
The CURRENT DEFAULT TRANSFORM GROUP (orCURRENT_DEFAULT_TRANSFORM_GROUP) special register specifies aVARCHAR(18) value that identifies the name of the transform group used bydynamic SQL statements for exchanging user-defined structured type valueswith host programs. This special register does not specify the transformgroups used in static SQL statements, or in the exchange of parameters andresults with external functions or methods.
Its value can be set by the SET CURRENT DEFAULT TRANSFORM GROUPstatement. If no value is set, the initial value of the special register is theempty string (a VARCHAR with a length of zero).
In a dynamic SQL statement (that is, one which interacts with host variables),the name of the transform group used for exchanging values is the same asthe value of this special register, unless this register contains the empty string.If the register contains the empty string (no value was set by using the SETCURRENT DEFAULT TRANSFORM GROUP statement), the DB2_PROGRAMtransform group is used for the transform. If the DB2_PROGRAM transformgroup is not defined for the structured type subject, an error is raised at runtime (SQLSTATE 42741).
Examples:
Set the default transform group to MYSTRUCT1. The TO SQL and FROM SQLfunctions defined in the MYSTRUCT1 transform are used to exchangeuser-defined structured type variables with the host program.
SET CURRENT DEFAULT TRANSFORM GROUP = MYSTRUCT1
Retrieve the name of the default transform group assigned to this specialregister.
VALUES (CURRENT DEFAULT TRANSFORM GROUP)
CURRENT DEFAULT TRANSFORM GROUP
154 SQL Reference, Volume 1
CURRENT DEGREE
The CURRENT DEGREE (or CURRENT_DEGREE) special register specifiesthe degree of intra-partition parallelism for the execution of dynamic SQLstatements. (For static SQL, the DEGREE bind option provides the samecontrol.) The data type of the register is CHAR(5). Valid values are ANY orthe string representation of an integer between 1 and 32 767, inclusive.
If the value of CURRENT DEGREE represented as an integer is 1 when anSQL statement is dynamically prepared, the execution of that statement willnot use intra-partition parallelism.
If the value of CURRENT DEGREE represented as an integer is greater than 1and less than or equal to 32 767 when an SQL statement is dynamicallyprepared, the execution of that statement can involve intra-partitionparallelism with the specified degree.
If the value of CURRENT DEGREE is ANY when an SQL statement isdynamically prepared, the execution of that statement can involveintra-partition parallelism using a degree determined by the databasemanager.
The actual runtime degree of parallelism will be the lower of:v The value of the maximum query degree (max_querydegree) configuration
parameterv The application runtime degreev The SQL statement compilation degree.
If the intra_parallel database manager configuration parameter is set to NO,the value of the CURRENT DEGREE special register will be ignored for thepurpose of optimization, and the statement will not use intra-partitionparallelism.
The value can be changed by invoking the SET CURRENT DEGREEstatement.
The initial value of CURRENT DEGREE is determined by the dft_degreedatabase configuration parameter.
Related reference:
v “SET CURRENT DEGREE statement” in the SQL Reference, Volume 2
CURRENT DEGREE
Chapter 2. Language elements 155
CURRENT EXPLAIN MODE
The CURRENT EXPLAIN MODE (or CURRENT_EXPLAIN_MODE) specialregister holds a VARCHAR(254) value which controls the behavior of theExplain facility with respect to eligible dynamic SQL statements. This facilitygenerates and inserts Explain information into the Explain tables. Thisinformation does not include the Explain snapshot. Possible values are YES,NO, EXPLAIN, RECOMMEND INDEXES, and EVALUATE INDEXES. (Forstatic SQL, the EXPLAIN bind option provides the same control. In the case ofthe PREP and BIND commands, the EXPLAIN option values are: YES, NO,and ALL.)
YES Enables the Explain facility and causes Explain information for adynamic SQL statement to be captured when the statement iscompiled.
EXPLAINEnables the facility, but dynamic statements are not executed.
NO Disables the Explain facility.
RECOMMEND INDEXESRecommends a set of indexes for each dynamic query. Populates theADVISE_INDEX table with the set of indexes.
EVALUATE INDEXESExplains dynamic queries as though the recommended indexesexisted. The indexes are picked up from the ADVISE_INDEX table.
The initial value is NO. The value can be changed by invoking the SETCURRENT EXPLAIN MODE statement.
The CURRENT EXPLAIN MODE and CURRENT EXPLAIN SNAPSHOTspecial register values interact when the Explain facility is invoked. TheCURRENT EXPLAIN MODE special register also interacts with the EXPLAINbind option. RECOMMEND INDEXES and EVALUATE INDEXES can only beset for the CURRENT EXPLAIN MODE register, and must be set using theSET CURRENT EXPLAIN MODE statement.
Example: Set the host variable EXPL_MODE (VARCHAR(254)) to the valuecurrently in the CURRENT EXPLAIN MODE special register.
VALUES CURRENT EXPLAIN MODEINTO :EXPL_MODE
Related reference:
v “SET CURRENT EXPLAIN MODE statement” in the SQL Reference, Volume2
v Appendix K, “Explain register values” on page 857
CURRENT EXPLAIN MODE
156 SQL Reference, Volume 1
CURRENT EXPLAIN SNAPSHOT
The CURRENT EXPLAIN SNAPSHOT (or CURRENT_EXPLAIN_SNAPSHOT)special register holds a CHAR(8) value that controls the behavior of theExplain snapshot facility. This facility generates compressed information,including access plan information, operator costs, and bind-time statistics.
Only the following statements consider the value of this register: DELETE,INSERT, SELECT, SELECT INTO, UPDATE, VALUES, or VALUES INTO.Possible values are YES, NO, and EXPLAIN. (For static SQL, the EXPLSNAPbind option provides the same control. In the case of the PREP and BINDcommands, the EXPLSNAP option values are: YES, NO, and ALL.)
YES Enables the Explain snapshot facility and takes a snapshot of theinternal representation of a dynamic SQL statement as the statement iscompiled.
EXPLAINEnables the facility, but dynamic statements are not executed.
NO Disables the Explain snapshot facility.
The initial value is NO. The value can be changed by invoking the SETCURRENT EXPLAIN SNAPSHOT statement.
The CURRENT EXPLAIN SNAPSHOT and CURRENT EXPLAIN MODEspecial register values interact when the Explain facility is invoked. TheCURRENT EXPLAIN SNAPSHOT special register also interacts with theEXPLSNAP bind option.
Example: Set the host variable EXPL_SNAP (char(8)) to the value currently inthe CURRENT EXPLAIN SNAPSHOT special register.
VALUES CURRENT EXPLAIN SNAPSHOTINTO :EXPL_SNAP
Related reference:
v “SET CURRENT EXPLAIN SNAPSHOT statement” in the SQL Reference,Volume 2
v Appendix K, “Explain register values” on page 857
CURRENT EXPLAIN SNAPSHOT
Chapter 2. Language elements 157
CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION
The CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION specialregister specifies a VARCHAR(254) value that identifies the types of tablesthat can be considered when optimizing the processing of dynamic SQLqueries. Materialized query tables are never considered by static embeddedSQL queries.
The initial value of CURRENT MAINTAINED TABLE TYPES FOROPTIMIZATION is SYSTEM. Its value can be changed by the SET CURRENTMAINTAINED TABLE TYPES FOR OPTIMIZATION statement.
Related reference:
v “SET CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATIONstatement” in the SQL Reference, Volume 2
CURRENT MAINTAINED TABLE TYPES FOR OPTIMIZATION
158 SQL Reference, Volume 1
CURRENT PATH
The CURRENT PATH (or CURRENT_PATH) special register specifies aVARCHAR(254) value that identifies the SQL path to be used when resolvingfunction references and data type references in dynamically prepared SQLstatements. CURRENT FUNCTION PATH is a synonym for CURRENT PATH.CURRENT PATH is also used to resolve stored procedure references in CALLstatements. The initial value is the default value specified below. For staticSQL, the FUNCPATH bind option provides an SQL path that is used forfunction and data type resolution.
The CURRENT PATH special register contains a list of one or more schemanames that are enclosed by double quotation marks and separated bycommas. For example, an SQL path specifying that the database manager is tolook first in the FERMAT schema, then in the XGRAPHIC schema, and finallyin the SYSIBM schema, is returned in the CURRENT PATH special register as:"FERMAT","XGRAPHIC","SYSIBM"
The default value is “SYSIBM”,“SYSFUN”,“SYSPROC”,X, where X is thevalue of the USER special register, delimited by double quotation marks. Thevalue can be changed by invoking the SET CURRENT PATH statement. Theschema SYSIBM does not need to be specified. If it is not included in the SQLpath, it is implicitly assumed to be the first schema. SYSIBM does not take upany of the 254 characters if it is implicitly assumed.
A data type that is not qualified with a schema name will be implicitlyqualified with the first schema in the SQL path that contains a data type withthe same unqualified name. There are exceptions to this rule, as outlined inthe descriptions of the following statements: CREATE DISTINCT TYPE,CREATE FUNCTION, COMMENT, and DROP.
Example: Using the SYSCAT.VIEWS catalog view, find all views that werecreated with the same setting as the current value of the CURRENT PATHspecial register.
SELECT VIEWNAME, VIEWSCHEMA FROM SYSCAT.VIEWSWHERE FUNC_PATH = CURRENT PATH
Related reference:
v “Functions” on page 168v “SET PATH statement” in the SQL Reference, Volume 2
CURRENT PATH
Chapter 2. Language elements 159
CURRENT QUERY OPTIMIZATION
The CURRENT QUERY OPTIMIZATION (orCURRENT_QUERY_OPTIMIZATION) special register specifies an INTEGERvalue that controls the class of query optimization performed by the databasemanager when binding dynamic SQL statements. The QUERYOPT bindoption controls the class of query optimization for static SQL statements. Thepossible values range from 0 to 9. For example, if the query optimization classis set to 0 (minimal optimization), then the value in the special register is 0.The default value is determined by the dft_queryopt database configurationparameter. The value can be changed by invoking the SET CURRENT QUERYOPTIMIZATION statement.
Example: Using the SYSCAT.PACKAGES catalog view, find all plans that werebound with the same setting as the current value of the CURRENT QUERYOPTIMIZATION special register.
SELECT PKGNAME, PKGSCHEMA FROM SYSCAT.PACKAGESWHERE QUERYOPT = CURRENT QUERY OPTIMIZATION
Related reference:
v “SET CURRENT QUERY OPTIMIZATION statement” in the SQL Reference,Volume 2
CURRENT QUERY OPTIMIZATION
160 SQL Reference, Volume 1
CURRENT REFRESH AGE
The CURRENT REFRESH AGE special register specifies a timestamp durationvalue with a data type of DECIMAL(20,6). It is the maximum duration since aparticular timestamped event occurred to a cached data object (for example, aREFRESH TABLE statement processed on a system-maintained REFRESHDEFERRED materialized query table), such that the cached data object can beused to optimize the processing of a query. If CURRENT REFRESH AGE has avalue of 99 999 999 999 999 (ANY), and the query optimization class is 5 ormore, the types of tables specified in CURRENT MAINTAINED TABLETYPES FOR OPTIMIZATION are considered when optimizing the processingof a dynamic SQL query.
The initial value of CURRENT REFRESH AGE is zero. The value can bechanged by invoking the SET CURRENT REFRESH AGE statement.
Related reference:
v “SET CURRENT REFRESH AGE statement” in the SQL Reference, Volume 2
CURRENT REFRESH AGE
Chapter 2. Language elements 161
CURRENT SCHEMA
The CURRENT SCHEMA (or CURRENT_SCHEMA) special register specifies aVARCHAR(128) value that identifies the schema name used to qualifydatabase object references, where applicable, in dynamically prepared SQLstatements. For compatibility with DB2 for OS/390, CURRENT SQLID (orCURRENT_SQLID) is a synonym for CURRENT SCHEMA.
The initial value of CURRENT SCHEMA is the authorization ID of the currentsession user. The value can be changed by invoking the SET SCHEMAstatement.
The QUALIFIER bind option controls the schema name used to qualifydatabase object references, where applicable, for static SQL statements.
Example: Set the schema for object qualification to 'D123'.SET CURRENT SCHEMA = 'D123'
CURRENT SCHEMA
162 SQL Reference, Volume 1
CURRENT SERVER
The CURRENT SERVER (or CURRENT_SERVER) special register specifies aVARCHAR(18) value that identifies the current application server. The registercontains the actual name of the application server, not an alias.
CURRENT SERVER can be changed through the CONNECT statement, butonly under certain conditions.
When used in an SQL statement inside a routine, CURRENT SERVER is notinherited from the invoking statement.
Example: Set the host variable APPL_SERVE (VARCHAR(18)) to the name ofthe application server to which the application is connected.
VALUES CURRENT SERVER INTO :APPL_SERVE
Related reference:
v “CONNECT (Type 1) statement” in the SQL Reference, Volume 2
CURRENT SERVER
Chapter 2. Language elements 163
CURRENT TIME
The CURRENT TIME (or CURRENT_TIME) special register specifies a timethat is based on a reading of the time-of-day clock when the SQL statement isexecuted at the application server. If this special register is used more thanonce within a single SQL statement, or used with CURRENT DATE orCURRENT TIMESTAMP within a single statement, all values are based on asingle clock reading.
When used in an SQL statement inside a routine, CURRENT TIME is notinherited from the invoking statement.
In a federated system, CURRENT TIME can be used in a query intended fordata sources. When the query is processed, the time returned will be obtainedfrom the CURRENT TIME register at the federated server, not from the datasources.
Example: Using the CL_SCHED table, select all the classes (CLASS_CODE) thatstart (STARTING) later today. Today’s classes have a value of 3 in the DAYcolumn.
SELECT CLASS_CODE FROM CL_SCHEDWHERE STARTING > CURRENT TIME AND DAY = 3
CURRENT TIME
164 SQL Reference, Volume 1
CURRENT TIMESTAMP
The CURRENT TIMESTAMP (or CURRENT_TIMESTAMP) special registerspecifies a timestamp that is based on a reading of the time-of-day clock whenthe SQL statement is executed at the application server. If this special registeris used more than once within a single SQL statement, or used withCURRENT DATE or CURRENT TIME within a single statement, all values arebased on a single clock reading.
When used in an SQL statement inside a routine, CURRENT TIMESTAMP isnot inherited from the invoking statement.
In a federated system, CURRENT TIMESTAMP can be used in a queryintended for data sources. When the query is processed, the timestampreturned will be obtained from the CURRENT TIMESTAMP register at thefederated server, not from the data sources.
Example: Insert a row into the IN_TRAY table. The value of the RECEIVEDcolumn should be a timestamp that indicates when the row was inserted. Thevalues for the other three columns come from the host variables SRC (char(8)),SUB (char(64)), and TXT (VARCHAR(200)).
INSERT INTO IN_TRAYVALUES (CURRENT TIMESTAMP, :SRC, :SUB, :TXT)
CURRENT TIMESTAMP
Chapter 2. Language elements 165
CURRENT TIMEZONE
The CURRENT TIMEZONE (or CURRENT_TIMEZONE) special registerspecifies the difference between UTC (Coordinated Universal Time, formerlyknown as GMT) and local time at the application server. The difference isrepresented by a time duration (a decimal number in which the first twodigits are the number of hours, the next two digits are the number of minutes,and the last two digits are the number of seconds). The number of hours isbetween -24 and 24 exclusive. Subtracting CURRENT TIMEZONE from a localtime converts that local time to UTC. The time is calculated from theoperating system time at the moment the SQL statement is executed. (TheCURRENT TIMEZONE value is determined from C runtime functions.)
The CURRENT TIMEZONE special register can be used wherever anexpression of the DECIMAL(6,0) data type is used; for example, in time andtimestamp arithmetic.
When used in an SQL statement inside a routine, CURRENT TIMEZONE isnot inherited from the invoking statement.
Example: Insert a record into the IN_TRAY table, using a UTC timestamp forthe RECEIVED column.
INSERT INTO IN_TRAY VALUES (CURRENT TIMESTAMP - CURRENT TIMEZONE,:source,:subject,:notetext )
CURRENT TIMEZONE
166 SQL Reference, Volume 1
USER
The USER special register specifies the run-time authorization ID passed tothe database manager when an application starts on a database. The data typeof the register is VARCHAR(128).
When used in an SQL statement inside a routine, USER is not inherited fromthe invoking statement.
Example: Select all notes from the IN_TRAY table that were placed there by theuser.
SELECT * FROM IN_TRAYWHERE SOURCE = USER
USER
Chapter 2. Language elements 167
Functions
A database function is a relationship between a set of input data values and aset of result values. For example, the TIMESTAMP function can be passedinput data values of type DATE and TIME, and the result is a TIMESTAMP.Functions can either be built-in or user-defined.v Built-in functions are provided with the database manager. They return a
single result value and are identified as part of the SYSIBM schema. Suchfunctions include column functions (for example, AVG), operator functions(for example, +), and casting functions (for example, DECIMAL).
v User-defined functions are functions that are registered to a database inSYSCAT.ROUTINES (using the CREATE FUNCTION statement).User-defined functions are never part of the SYSIBM schema. One set ofsuch functions is provided with the database manager in a schema calledSYSFUN.User-defined functions extend the capabilities of the database system byadding function definitions (provided by users or third party vendors) thatcan be applied in the database engine itself. Extending database functionslets the database exploit the same functions in the engine that anapplication uses, providing more synergy between application anddatabase.
External, SQL, and sourced user-defined functionsA user-defined function can be an external function, an SQL function, or asourced function. An external function is defined to the database with areference to an object code library, and a function within that library that willbe executed when the function is invoked. External functions cannot becolumn functions. An SQL function is defined to the database using only theSQL RETURN statement. It can return either a scalar value, a row, or a table.SQL functions cannot be column functions. A sourced function is defined to thedatabase with a reference to another built-in or user-defined function that isalready known to the database. Sourced functions can be scalar functions orcolumn functions. They are useful for supporting existing functions withuser-defined types.
Scalar, column, row, and table user-defined functionsEach user-defined function is also categorized as a scalar, column, or tablefunction. A scalar function is a function that returns a single-valued answereach time it is called. For example, the built-in function SUBSTR() is a scalarfunction. Scalar UDFs can be either external or sourced.
A column function is one which conceptually is passed a set of like values (acolumn) and returns a single-valued answer. These are also sometimes calledaggregating functions in DB2. An example of a column function is the built-infunction AVG(). An external column UDF cannot be defined to DB2, but a
Functions
168 SQL Reference, Volume 1
column UDF, which is sourced upon one of the built-in column functions, canbe defined. This is useful for distinct types. For example, if there is a distincttype SHOESIZE defined with base type INTEGER, a UDF AVG(SHOESIZE),which is sourced on the built-in function AVG(INTEGER), could be defined,and it would be a column function.
A row function is a function that returns one row of values. It may only beused as a transform function, mapping attribute values of a structured typeinto values in a row. A row function must be defined as an SQL function.
A table function is a function that returns a table to the SQL statement whichreferences it. It may only be referenced in the FROM clause of a SELECTstatement. Such a function can be used to apply SQL language processingpower to data that is not DB2 data, or to convert such data into a DB2 table.It could, for example, take a file and convert it into a table, sample data fromthe World Wide Web and tabularize it, or access a Lotus Notes database andreturn information about mail messages, such as the date, sender, and the textof the message. This information can be joined with other tables in thedatabase. A table function can be defined as an external function or as an SQLfunction. (A table function cannot be a sourced function.)
Function signaturesA function is identified by its schema, a function name, the number ofparameters, and the data types of its parameters. This is called a functionsignature, which must be unique within the database. There can be more thanone function with the same name in a schema, provided that the number ofparameters or the data types of the parameters are different. A function namefor which there are multiple function instances is called an overloaded function.A function name can be overloaded within a schema, in which case there ismore than one function by that name in the schema. These functions musthave different parameter types. A function name can also be overloaded in anSQL path, in which case there is more than one function by that name in thepath. These functions do not necessarily have different parameter types.
A function can be invoked by referring (in an allowable context) to itsqualified name (schema and function name), followed by the list of argumentsenclosed in parentheses. A function can also be invoked without the schemaname, resulting in a choice of possible functions in different schemas with thesame or acceptable parameters. In this case, the SQL path is used to assist infunction resolution. The SQL path is a list of schemas that are searched toidentify a function with the same name, number of parameters and acceptabledata types. For static SQL statements, the SQL path is specified using theFUNCPATH bind option. For dynamic SQL statements, the SQL path is thevalue of the CURRENT PATH special register.
Scalar, column, row, and table user-defined functions
Chapter 2. Language elements 169
Access to functions is controlled through the EXECUTE privilege. GRANTand REVOKE statements are used to specify who can or cannot execute aspecific function or a set of functions. The EXECUTE privilege (or DBADMauthority) is needed to invoke a function. The definer of the functionautomatically receives the EXECUTE privilege. The definer of an externalfunction or an SQL function having the WITH GRANT option on allunderlying objects also receives the WITH GRANT option with the EXECUTEprivilege on the function. The definer (or SYSADM or DBADM) must thengrant it to the user who wants to invoke the function from any SQLstatement, reference the function in any DDL statement (such as CREATEVIEW, CREATE TRIGGER, or when defining a constraint), or create anotherfunction sourced on this function. If the EXECUTE privilege is not granted toa user, the function will not be considered by the function resolutionalgorithm, even if it is a better match. Built-in functions (SYSIBM functions)and SYSFUN functions have the EXECUTE privilege implicitly granted toPUBLIC.
Function resolutionAfter function invocation, the database manager must decide which of thepossible functions with the same name is the “best fit”. This includesresolving functions from the built-in and user-defined functions.
An argument is a value passed to a function upon invocation. When a functionis invoked in SQL, it is passed a list of zero or more arguments. They arepositional in that the semantics of an argument are determined by its positionin the argument list. A parameter is a formal definition of an input to afunction. When a function is defined to the database, either internally (abuilt-in function) or by a user (a user-defined function), its parameters (zeroor more) are specified, and the order of their definitions defines theirpositions and their semantics. Therefore, every parameter is a particularpositional input to a function. On invocation, an argument corresponds to aparticular parameter by virtue of its position in the list of arguments.
The database manager uses the name of the function given in the invocation,EXECUTE privilege on the function, the number and data types of thearguments, all the functions with the same name in the SQL path, and thedata types of their corresponding parameters as the basis for decidingwhether or not to select a function. The following are the possible outcomes ofthe decision process:v A particular function is deemed to be the best fit. For example, given the
functions named RISK in the schema TEST with signatures defined as:TEST.RISK(INTEGER)TEST.RISK(DOUBLE)
an SQL path including the TEST schema and the following functionreference (where DB is a DOUBLE column):
Function signatures
170 SQL Reference, Volume 1
SELECT ... RISK(DB) ...
then, the second RISK will be chosen.
The following function reference (where SI is a SMALLINT column):SELECT ... RISK(SI) ...
would choose the first RISK, because SMALLINT can be promoted toINTEGER and is a better match than DOUBLE which is further down theprecedence list.
When considering arguments that are structured types, the precedence listincludes the supertypes of the static type of the argument. The best fit isthe function defined with the supertype parameter that is closest in thestructured type hierarchy to the static type of the function argument.
v No function is deemed to be an acceptable fit. For example, given the sametwo functions in the previous case and the following function reference(where C is a CHAR(5) column):
SELECT ... RISK(C) ...
the argument is inconsistent with the parameter of both RISK functions.v A particular function is selected based on the SQL path and the number
and data types of the arguments passed on invocation. For example, givenfunctions named RANDOM with signatures defined as:
TEST.RANDOM(INTEGER)PROD.RANDOM(INTEGER)
and an SQL path of:"TEST","PROD"
the following function reference:SELECT ... RANDOM(432) ...
will choose TEST.RANDOM, because both RANDOM functions are equallygood matches (exact matches in this particular case), and both schemas arein the path, but TEST precedes PROD in the SQL path.
Determining the best fitA comparison of the data types of the arguments with the defined data typesof the parameters of the functions under consideration forms the basis for thedecision of which function in a group of like-named functions is the “best fit”.Note that the data types of the results of the functions, or the type of function(column, scalar, or table) under consideration do not enter into thisdetermination.
Function resolution
Chapter 2. Language elements 171
Function resolution is performed using the following steps:1. First, find all functions from the catalog (SYSCAT.ROUTINES), and built-in
functions, such that all of the following are true:v For invocations where the schema name was specified (a qualified
reference), the schema name and the function name match theinvocation name.
v For invocations where the schema name was not specified (anunqualified reference), the function name matches the invocation nameand has a schema name that matches one of the schemas in the SQLpath.
v The invoker has the EXECUTE privilege on the function.v The number of defined parameters matches the invocation.v Each invocation argument matches the function’s corresponding defined
parameter in data type, or is “promotable” to it.2. Next, consider each argument of the function invocation, from left to right.
For each argument, eliminate all functions that are not the best match forthat argument. The best match for a given argument is the first data typeappearing in the precedence list corresponding to the argument data typefor which there exists a function with a parameter of that data type.Lengths, precisions, scales and the FOR BIT DATA attribute are notconsidered in this comparison. For example, a DECIMAL(9,1) argument isconsidered an exact match for a DECIMAL(6,5) parameter, and aVARCHAR(19) argument is an exact match for a VARCHAR(6) parameter.The best match for a user-defined structured-type argument is itself; thenext best match is its immediate supertype, and so on for each supertypeof the argument. Note that only the static type (declared type) of thestructured-type argument is considered, not the dynamic type (mostspecific type).
3. If more than one candidate function remains after Step 2, all remainingcandidate functions must have identical signatures but be in differentschemas. Choose the function whose schema is earliest in the user’s SQLpath.
4. If there are no candidate functions remaining after step 2, an error isreturned (SQLSTATE 42884).
Function path considerations for built-in functionsBuilt-in functions reside in a special schema called SYSIBM. Additionalfunctions are available in the SYSFUN and SYSPROC schemas, but are notconsidered built-in functions since they are developed as user-definedfunctions and have no special processing considerations. Users cannot defineadditional functions in the SYSIBM, SYSFUN, or SYSPROC schemas (or in anyother schema whose name begins with the letters SYS).
Determining the best fit
172 SQL Reference, Volume 1
As already stated, the built-in functions participate in the function resolutionprocess exactly as do the user-defined functions. One difference betweenbuilt-in and user-defined functions, from a function resolution perspective, isthat the built-in functions must always be considered during functionresolution. Therefore, omission of SYSIBM from the path results in theassumption (for function and data type resolution) that SYSIBM is the firstschema on the path.
For example, if a user’s SQL path is defined as:"SHAREFUN","SYSIBM","SYSFUN"
and there is a LENGTH function defined in schema SHAREFUN with thesame number and types of arguments as SYSIBM.LENGTH, then anunqualified reference to LENGTH in this user’s SQL statement will result inselecting SHAREFUN.LENGTH. However, if the user’s SQL path is definedas:
"SHAREFUN","SYSFUN"
and the same SHAREFUN.LENGTH function exists, then an unqualifiedreference to LENGTH in this user’s SQL statement will result in selectingSYSIBM.LENGTH, because SYSIBM implicitly appears first in the path.
To minimize potential problems in this area:v Never use the names of built-in functions for user-defined functions.v If, for some reason, it is necessary to create a user-defined function with the
same name as a built-in function, be sure to qualify any references to it.
Example of function resolutionFollowing is an example of successful function resolution. (Note that not allrequired keywords are shown.)
There are seven ACT functions, in three different schemas, registered as:CREATE FUNCTION AUGUSTUS.ACT (CHAR(5), INT, DOUBLE) SPECIFIC ACT_1 ...CREATE FUNCTION AUGUSTUS.ACT (INT, INT, DOUBLE) SPECIFIC ACT_2 ...CREATE FUNCTION AUGUSTUS.ACT (INT, INT, DOUBLE, INT) SPECIFIC ACT_3 ...CREATE FUNCTION JULIUS.ACT (INT, DOUBLE, DOUBLE) SPECIFIC ACT_4 ...CREATE FUNCTION JULIUS.ACT (INT, INT, DOUBLE) SPECIFIC ACT_5 ...CREATE FUNCTION JULIUS.ACT (SMALLINT, INT, DOUBLE) SPECIFIC ACT_6 ...CREATE FUNCTION NERO.ACT (INT, INT, DEC(7,2)) SPECIFIC ACT_7 ...
The function reference is as follows (where I1 and I2 are INTEGER columns,and D is a DECIMAL column):
SELECT ... ACT(I1, I2, D) ...
Assume that the application making this reference has an SQL pathestablished as:
Function path considerations for built-in functions
Chapter 2. Language elements 173
"JULIUS","AUGUSTUS","CAESAR"
Following through the algorithm...v The function with specific name ACT_7 is eliminated as a candidate,
because the schema NERO is not included in the SQL path.v The function with specific name ACT_3 is eliminated as a candidate,
because it has the wrong number of parameters. ACT_1 and ACT_6 areeliminated because, in both cases, the first argument cannot be promoted tothe data type of the first parameter.
v Because there is more than one candidate remaining, the arguments areconsidered in order.
v For the first argument, the remaining functions, ACT_2, ACT_4, and ACT_5are an exact match with the argument type. No functions can be eliminatedfrom consideration; therefore the next argument must be examined.
v For this second argument, ACT_2 and ACT_5 are exact matches, but ACT_4is not, so it is eliminated from consideration. The next argument isexamined to determine some differentiation between ACT_2 and ACT_5.
v For the third and last argument, neither ACT_2 nor ACT_5 match theargument type exactly, but both are equally good.
v There are two functions remaining, ACT_2 and ACT_5, with identicalparameter signatures. The final tie-breaker is to see which function’sschema comes first in the SQL path, and on this basis, ACT_5 is thefunction chosen.
Function invocationOnce the function is selected, there are still possible reasons why the use ofthe function may not be permitted. Each function is defined to return a resultwith a specific data type.If this result data type is not compatible with thecontext in which the function is invoked, an error will occur. For example,given functions named STEP defined, this time, with different data types asthe result:
STEP(SMALLINT) returns CHAR(5)STEP(DOUBLE) returns INTEGER
and the following function reference (where S is a SMALLINT column):SELECT ... 3 + STEP(S) ...
then, because there is an exact match on argument type, the first STEP ischosen.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 additionoperator.
A couple of other examples where this can happen are as follows, both ofwhich will result in an error on the statement:
Example of function resolution
174 SQL Reference, Volume 1
v The function was referenced in a FROM clause, but the function selected bythe function resolution step was a scalar or column function.
v The reverse case, where the context calls for a scalar or column function,and function resolution selects a table function.
In cases where the arguments of the function invocation were not an exactmatch to the data types of the parameters of the selected function, thearguments are converted to the data type of the parameter at execution usingthe same rules as assignment to columns. This includes the case whereprecision, scale, or length differs between the argument and the parameter.
Conservative binding semanticsThere are instances in which routines and data types are resolved when astatement is processed, and the database manager must be able to repeat thisresolution. This is true in:v Static DML statements in packagesv Viewsv Triggersv Check constraintsv SQL routines
For static DML statements in packages, the routine and data type referencesare resolved during a bind operation. Routine and data type references inviews, triggers, SQL routines, and check constraints are resolved when thedatabase object is created.
If routine resolution is performed again on any routine references in theseobjects, it could change the behavior if:v A new routine has been added with a signature that is a better match, but
the actual executable performs different operations.v The definer has been granted the execute privilege on a routine with a
signature that is a better match, but the actual executable performs differentoperations.
Similarly, if resolution is performed again on any data type in these objects, itcould change the behavior if a new data type has been added with the samename in a different schema that is also on the SQL path. To avoid this, thedatabase manager applies conservative binding semantics wherever necessary.This ensures that routine and data type references will be resolved using thesame SQL path and the set of routines to which it previously resolved when itwas bound. The creation timestamp of routines and data types consideredduring resolution is not later than the time when the statement was bound.(Built-in functions added starting with Version 6.1 have a creation timestampthat is based on the time of database creation or migration.) In this way, onlythe routines and data types that were considered during routine and data
Function invocation
Chapter 2. Language elements 175
type resolution when the statement was originally processed will beconsidered. Hence, newly created routines, newly authorized routines, anddata types are not considered when conservative binding semantics areapplied.
Consider a database with two functions that have the signaturesSCHEMA1.BAR(INTEGER) and SCHEMA2.BAR(DOUBLE). Assume the SQLpath contains both schemas SCHEMA1 and SCHEMA2 (although their orderwithin the SQL path does not matter). USER1 has been granted the EXECUTEprivilege on the function SCHEMA2.BAR(DOUBLE). Suppose USER1 creates aview that calls BAR(INT_VAL). This will resolve to the functionSCHEMA2.BAR(DOUBLE). The view will always useSCHEMA2.BAR(DOUBLE), even if someone grants USER1 the EXECUTEprivilege on SCHEMA1.BAR(INTEGER) after the view has been created.
For static DML in packages, the packages can rebind implicitly, or byexplicitly issuing the REBIND command (or corresponding API), or the BINDcommand (or corresponding API). The implicit rebind is always performed toresolve routines and data types with conservative binding semantics. TheREBIND command provides the option to resolve with conservative bindingsemantics (RESOLVE CONSERVATIVE) or to resolve by considering any newroutines and data types (RESOLVE ANY, the default option).
Implicit rebind of a package always resolves the same routine. Even ifEXECUTE privilege on a better-matched routine was granted, that routine willnot be considered. Explicit rebind of a package can result in a different routinebeing selected. (But if RESOLVE CONSERVATIVE is specified, routineresolution will follow conservative binding semantics).
If a routine is specified during the creation of a view, trigger, constraint, orSQL routine body, the specific instance of the routine to be used is determinedby routine resolution at the time the object is created. Subsequent granting ofthe EXECUTE privilege after the object has been created will not change thespecific routine that the object uses.
Consider a database with two functions that have the signaturesSCHEMA1.BAR(INTEGER) and SCHEMA2.BAR(DOUBLE). USER1 has beengranted the EXECUTE privilege on the function SCHEMA2.BAR(DOUBLE).Suppose USER1 creates a view that calls BAR(INT_VAL). This will resolve tothe function SCHEMA2.BAR(DOUBLE). The view will always useSCHEMA2.BAR(DOUBLE), even if someone grants USER1 the EXECUTEprivilege on SCHEMA1.BAR(INTEGER) after the view has been created.
The same behavior occurs in other database objects. For example, if a packageis implicitly rebound (perhaps after dropping an index), the package will refer
Conservative binding semantics
176 SQL Reference, Volume 1
to the same specific routine both before and after the implicit rebind. Anexplicit rebind of a package, however, can result in a different routine beingselected.
Related reference:
v “CURRENT PATH” on page 159v “Promotion of data types” on page 111v “Assignments and comparisons” on page 117
Conservative binding semantics
Chapter 2. Language elements 177
Methods
A database method of a structured type is a relationship between a set ofinput data values and a set of result values, where the first input value (orsubject argument) has the same type, or is a subtype of the subject type (alsocalled the subject parameter), of the method. For example, a method calledCITY, of type ADDRESS, can be passed input data values of type VARCHAR,and the result is an ADDRESS (or a subtype of ADDRESS).
Methods are defined implicitly or explicitly, as part of the definition of auser-defined structured type.
Implicitly defined methods are created for every structured type. Observermethods are defined for each attribute of the structured type. Observermethods allow applications to get the value of an attribute for an instance ofthe type. Mutator methods are also defined for each attribute, allowingapplications to mutate the type instance by changing the value for an attributeof a type instance. The CITY method described above is an example of amutator method for the type ADDRESS.
Explicitly defined methods, or user-defined methods, are methods that areregistered to a database in SYSCAT.ROUTINES, by using a combination ofCREATE TYPE (or ALTER TYPE ADD METHOD) and CREATE METHODstatements. All methods defined for a structured type are defined in the sameschema as the type.
User-defined methods for structured types extend the function of the databasesystem by adding method definitions (provided by users or third partyvendors) that can be applied to structured type instances in the databaseengine. Defining database methods lets the database exploit the same methodsin the engine that an application uses, providing more synergy betweenapplication and database.
External and SQL user-defined methodsA user-defined method can be either external or based on an SQL expression.An external method is defined to the database with a reference to an objectcode library and a function within that library that will be executed when themethod is invoked. A method based on an SQL expression returns the resultof the SQL expression when the method is invoked. Such methods do notrequire any object code library, because they are written completely in SQL.
A user-defined method can return a single-valued answer each time it iscalled. This value can be a structured type. A method can be defined as typepreserving (using SELF AS RESULT), to allow the dynamic type of the subjectargument to be returned as the returned type of the method. All implicitlydefined mutator methods are type preserving.
Methods
178 SQL Reference, Volume 1
Method signaturesA method is identified by its subject type, a method name, the number ofparameters, and the data types of its parameters. This is called a methodsignature, and it must be unique within the database.
There can be more than one method with the same name for a structuredtype, provided that:v The number of parameters or the data types of the parameters are different,
orv The methods are part of the same method hierarchy (that is, the methods
are in an overriding relationship or override the same original method), orv The same function signature (using the subject type or any of its subtypes
or supertypes as the first parameter) does not exist.
A method name that has multiple method instances is called an overloadedmethod. A method name can be overloaded within a type, in which case thereis more than one method by that name for the type (all of which havedifferent parameter types). A method name can also be overloaded in thesubject type hierarchy, in which case there is more than one method by thatname in the type hierarchy. These methods must have different parametertypes.
A method can be invoked by referring (in an allowable context) to the methodname, preceded by both a reference to a structured type instance (the subjectargument), and the double dot operator. A list of arguments enclosed inparentheses must follow. Which method is actually invoked depends on thestatic type of the subject type, using the method resolution process describedin the following section. Methods defined WITH FUNCTION ACCESS canalso be invoked using function invocation, in which case the regular rules forfunction resolution apply.
If function resolution results in a method defined WITH FUNCTION ACCESS,all subsequent steps of method invocation are processed.
Access to methods is controlled through the EXECUTE privilege. GRANT andREVOKE statements are used to specify who can or cannot execute a specificmethod or a set of methods. The EXECUTE privilege (or DBADM authority)is needed to invoke a method. The definer of the method automaticallyreceives the EXECUTE privilege. The definer of an external method or an SQLmethod having the WITH GRANT option on all underlying objects alsoreceives the WITH GRANT option with the EXECUTE privilege on themethod. The definer (or SYSADM or DBADM) must then grant it to the userwho wants to invoke the method from any SQL statement, or reference themethod in any DDL statement (such as CREATE VIEW, CREATE TRIGGER,
Method signatures
Chapter 2. Language elements 179
or when defining a constraint). If the EXECUTE privilege is not granted to auser, the method will not be considered by the method resolution algorithm,even if it is a better match.
Method resolutionAfter method invocation, the database manager must decide which of thepossible methods with the same name is the “best fit”. Functions (built-in oruser-defined) are not considered during method resolution.
An argument is a value passed to a method upon invocation. When a methodis invoked in SQL, it is passed the subject argument (of some structured type)and a list of zero or more arguments. They are positional in that the semanticsof an argument are determined by its position in the argument list. Aparameter is a formal definition of an input to a method. When a method isdefined to the database, either implicitly (system-generated for a type) or by auser (a user-defined method), its parameters are specified (with the subjectparameter as the first parameter), and the order of their definitions definestheir positions and their semantics. Therefore, every parameter is a particularpositional input to a method. On invocation, an argument corresponds to aparticular parameter by virtue of its position in the list of arguments.
The database manager uses the name of the method given in the invocation,EXECUTE privilege on the method, the number and data types of thearguments, all the methods with the same name for the subject argument’sstatic type (and it’s supertypes), and the data types of their correspondingparameters as the basis for deciding whether or not to select a method. Thefollowing are the possible outcomes of the decision process:v A particular method is deemed to be the best fit. For example, given the
methods named RISK for the type SITE with signatures defined as:PROXIMITY(INTEGER) FOR SITEPROXIMITY(DOUBLE) FOR SITE
the following method invocation (where ST is a SITE column, DB is aDOUBLE column):
SELECT ST..PROXIMITY(DB) ...
then, the second PROXIMITY will be chosen.
The following method invocation (where SI is a SMALLINT column):SELECT ST..PROXIMITY(SI) ...
would choose the first PROXIMITY, because SMALLINT can be promotedto INTEGER and is a better match than DOUBLE, which is further downthe precedence list.
Method signatures
180 SQL Reference, Volume 1
When considering arguments that are structured types, the precedence listincludes the supertypes of the static type of the argument. The best fit isthe function defined with the supertype parameter that is closest in thestructured type hierarchy to the static type of the function argument.
v No method is deemed to be an acceptable fit. For example, given the sametwo functions in the previous case and the following function reference(where C is a CHAR(5) column):
SELECT ST..PROXIMITY(C) ...
the argument is inconsistent with the parameter of both PROXIMITYfunctions.
v A particular method is selected based on the methods in the type hierarchyand the number and data types of the arguments passed on invocation. Forexample, given methods named RISK for the types SITE and DRILLSITE (asubtype of SITE) with signatures defined as:
RISK(INTEGER) FOR DRILLSITERISK(DOUBLE) FOR SITE
and the following method invocation (where DRST is a DRILLSITE column,DB is a DOUBLE column):
SELECT DRST..RISK(DB) ...
the second RISK will be chosen, because DRILLSITE can be promoted toSITE.
The following method reference (where SI is a SMALLINT column):SELECT DRST..RISK(SI) ...
would choose the first RISK, because SMALLINT can be promoted toINTEGER, which is closer on the precedence list than DOUBLE, andDRILLSITE is a better match than SITE, which is a supertype.
Methods within the same type hierarchy cannot have the same signatures,considering parameters other than the subject parameter.
Determining the best fitA comparison of the data types of the arguments with the defined data typesof the parameters of the methods under consideration forms the basis for thedecision of which method in a group of like-named methods is the “best fit”.Note that the data types of the results of the methods under consideration donot enter into this determination.
Method resolution is performed using the following steps:1. First, find all methods from the catalog (SYSCAT.ROUTINES) such that all
of the following are true:
Method resolution
Chapter 2. Language elements 181
v The method name matches the invocation name, and the subjectparameter is the same type or is a supertype of the static type of thesubject argument.
v The invoker has the EXECUTE privilege on the method.v The number of defined parameters matches the invocation.v Each invocation argument matches the method’s corresponding defined
parameter in data type, or is “promotable” to it.2. Next, consider each argument of the method invocation, from left to right.
The leftmost argument (and thus the first argument) is the implicit SELFparameter. For example, a method defined for type ADDRESS_T has animplicit first parameter of type ADDRESS_T. For each argument, eliminateall functions that are not the best match for that argument. The best matchfor a given argument is the first data type appearing in the precedence listcorresponding to the argument data type for which there exists a functionwith a parameter of that data type. Length, precision, scale and the FORBIT DATA attribute are not considered in this comparison. For example, aDECIMAL(9,1) argument is considered an exact match for aDECIMAL(6,5) parameter, and a VARCHAR(19) argument is an exactmatch for a VARCHAR(6) parameter.The best match for a user-defined structured-type argument is itself; thenext best match is its immediate supertype, and so on for each supertypeof the argument. Note that only the static type (declared type) of thestructured-type argument is considered, not the dynamic type (mostspecific type).
3. At most, one candidate method remains after Step 2. This is the methodthat is chosen.
4. If there are no candidate methods remaining after step 2, an error isreturned (SQLSTATE 42884).
Example of method resolutionFollowing is an example of successful method resolution.
There are seven FOO methods for three structured types defined in ahierarchy of GOVERNOR as a subtype of EMPEROR as a subtype ofHEADOFSTATE, registered with the following signatures:
CREATE METHOD FOO (CHAR(5), INT, DOUBLE) FOR HEADOFSTATE SPECIFIC FOO_1 ...CREATE METHOD FOO (INT, INT, DOUBLE) FOR HEADOFSTATE SPECIFIC FOO_2 ...CREATE METHOD FOO (INT, INT, DOUBLE, INT) FOR HEADOFSTATE SPECIFIC FOO_3 ...CREATE METHOD FOO (INT, DOUBLE, DOUBLE) FOR EMPEROR SPECIFIC FOO_4 ...CREATE METHOD FOO (INT, INT, DOUBLE) FOR EMPEROR SPECIFIC FOO_5 ...CREATE METHOD FOO (SMALLINT, INT, DOUBLE) FOR EMPEROR SPECIFIC FOO_6 ...CREATE METHOD FOO (INT, INT, DEC(7,2)) FOR GOVERNOR SPECIFIC FOO_7 ...
The method reference is as follows (where I1 and I2 are INTEGER columns, Dis a DECIMAL column and E is an EMPEROR column):
Determining the best fit
182 SQL Reference, Volume 1
SELECT E..FOO(I1, I2, D) ...
Following through the algorithm...v FOO_7 is eliminated as a candidate, because the type GOVERNOR is a
subtype (not a supertype) of EMPEROR.v FOO_3 is eliminated as a candidate, because it has the wrong number of
parameters.v FOO_1 and FOO_6 are eliminated because, in both cases, the first argument
(not the subject argument) cannot be promoted to the data type of the firstparameter. Because there is more than one candidate remaining, thearguments are considered in order.
v For the subject argument, FOO_2 is a supertype, while FOO_4 and FOO_5match the subject argument.
v For the first argument, the remaining methods, FOO_4 and FOO_5, are anexact match with the argument type. No methods can be eliminated fromconsideration; therefore the next argument must be examined.
v For this second argument, FOO_5 is an exact match, but FOO_4 is not, so itis eliminated from consideration. This leaves FOO_5 as the method chosen.
Method invocationOnce the method is selected, there are still possible reasons why the use of themethod may not be permitted.
Each method is defined to return a result with a specific data type. If thisresult data type is not compatible with the context in which the method isinvoked, an error will occur. For example, assume that the following methodsnamed STEP are defined, each with a different data type as the result:
STEP(SMALLINT) FOR TYPEA RETURNS CHAR(5)STEP(DOUBLE) FOR TYPEA RETURNS INTEGER
and the following method reference (where S is a SMALLINT column and TAis a column of TYPEA):
SELECT 3 + TA..STEP(S) ...
then, because there is an exact match on argument type, the first STEP ischosen. 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 additionoperator.
Starting from the method that has been chosen, the algorithm described in“Dynamic dispatch of methods” is used to build the set of dispatchablemethods at compile time. Exactly which method is invoked is described in“Dynamic dispatch of methods”.
Note that when the selected method is a type preserving method:
Example of method resolution
Chapter 2. Language elements 183
v the static result type following function resolution is the same as the statictype of the subject argument of the method invocation
v the dynamic result type when the method is invoked is the same as thedynamic type of the subject argument of the method invocation.
This may be a subtype of the result type specified in the type preservingmethod definition, which in turn may be a supertype of the dynamic typethat is actually returned when the method is processed.
In cases where the arguments of the method invocation were not an exactmatch to the data types of the parameters of the selected method, thearguments are converted to the data type of the parameter at execution usingthe same rules as assignment to columns. This includes the case whereprecision, scale, or length differs between the argument and the parameter,but excludes the case where the dynamic type of the argument is a subtype ofthe parameter’s static type.
Dynamic dispatch of methodsMethods provide the functionality and encapsulate the data of a type. Amethod is defined for a type and can always be associated with this type. Oneof the method’s parameters is the implicit SELF parameter. The SELFparameter is of the type for which the method has been declared. Theargument that is passed as the SELF argument when the method is invoked ina DML statement is called subject.
When a method is chosen using method resolution (see “Method resolution”on page 180), or a method has been specified in a DDL statement, thismethod is known as the “most specific applicable authorized method”. If thesubject is of a structured type, that method could have one or more overridingmethods. DB2 must then determine which of these methods to invoke, basedon the dynamic type (most specific type) of the subject at run time. Thisdetermination is called “determining the most specific dispatchable method”.That process is described here.1. Find the original method in the method hierarchy that the most specific
applicable authorized method is part of. This is called the root method.2. Create the set of dispatchable methods, which includes the following:
v The most specific applicable authorized method.v Any method that overrides the most specific applicable authorized
method, and which is defined for a type that is a subtype of the subjectof this invocation.
3. Determine the most specific dispatchable method, as follows:a. Start with an arbitrary method that is an element of the set of
dispatchable methods and that is a method of the dynamic type of thesubject, or of one of its supertypes. This is the initial most specificdispatchable method.
Method invocation
184 SQL Reference, Volume 1
b. Iterate through the elements of the set of dispatchable methods. Foreach method: If the method is defined for one of the proper subtypesof the type for which the most specific dispatchable method is defined,and if it is defined for one of the supertypes of the most specific typeof the subject, then repeat step 2 with this method as the most specificdispatchable method; otherwise, continue iterating.
4. Invoke the most specific dispatchable method.
Example:
Given are three types, ″Person″, ″Employee″, and ″Manager″. There is anoriginal method ″income″, defined for ″Person″, which computes a person’sincome. A person is by default unemployed (a child, a retiree, and so on).Therefore, ″income″ for type ″Person″ always returns zero. For type″Employee″ and for type ″Manager″, different algorithms have to be appliedto calculate the income. Hence, the method ″income″ for type ″Person″ isoverridden in ″Employee″ and ″Manager″.
Create and populate a table as follows:CREATE TABLE aTable (id integer, personColumn Person);
INSERT INTO aTable VALUES (0, Person()), (1, Employee()), (2, Manager());
List all persons who have a minimum income of $40000:SELECT id, person, name
FROM aTableWHERE person..income() >= 40000;
The method ″income″ for type ″Person″ is chosen, using method resolution, tobe the most specific applicable authorized method.1. The root method is ″income″ for ″Person″ itself.2. The second step of the algorithm above is carried out to construct the set
of dispatchable methods:v The method ″income″ for type ″Person″ is included, because it is the
most specific applicable authorized method.v The method ″income″ for type ″Employee″, and ″income″ for ″Manager″
is included, because both methods override the root method, and both″Employee″ and ″Manager″ are subtypes of ″Person″.
Therefore, the set of dispatchable methods is: {″income″ for ″Person″,″income″ for ″Employee″, ″income″ for ″Manager″}.
3. Determine the most specific dispatchable method:v For a subject whose most specific type is ″Person″:
a. Let the initial most specific dispatchable method be ″income″ fortype ″Person″.
Dynamic dispatch of methods
Chapter 2. Language elements 185
b. Because there is no other method in the set of dispatchable methodsthat is defined for a proper subtype of ″Person″ and for a supertypeof the most specific type of the subject, ″income″ for type ″Person″ isthe most specific dispatchable method.
v For a subject whose most specific type is ″Employee″:a. Let the initial most specific dispatchable method be ″income″ for
type ″Person″.b. Iterate through the set of dispatchable methods. Because method
″income″ for type ″Employee″ is defined for a proper subtype of″Person″ and for a supertype of the most specific type of the subject(Note: A type is its own super- and subtype.), method ″income″ fortype ″Employee″ is a better match for the most specific dispatchablemethod. Repeat this step with method ″income″ for type ″Employee″as the most specific dispatchable method.
c. Because there is no other method in the set of dispatchable methodsthat is defined for a proper subtype of ″Employee″ and for asupertype of the most specific type of the subject, method ″income″for type ″Employee″ is the most specific dispatchable method.
v For a subject whose most specific type is ″Manager″:a. Let the initial most specific dispatchable method be ″income″ for
type ″Person″.b. Iterate through the set of dispatchable methods. Because method
″income″ for type ″Manager″ is defined for a proper subtype of″Person″ and for a supertype of the most specific type of the subject(Note: A type is its own super- and subtype.), method ″income″ fortype ″Manager″ is a better match for the most specific dispatchablemethod. Repeat this step with method ″income″ for type ″Manager″as the most specific dispatchable method.
c. Because there is no other method in the set of dispatchable methodsthat is defined for a proper subtype of ″Manager″ and for asupertype of the most specific type of the subject, method ″income″for type ″Manager″ is the most specific dispatchable method.
4. Invoke the most specific dispatchable method.
Related reference:
v “Promotion of data types” on page 111v “Assignments and comparisons” on page 117
Dynamic dispatch of methods
186 SQL Reference, Volume 1
Expressions
An expression specifies a value. It can be a simple value, consisting of only aconstant or a column name, or it can be more complex. When repeatedlyusing similar complex expressions, an SQL function to encapsulate a commonexpression can be considered.
In a Unicode database, an expression that accepts a character or graphic stringwill accept any string types for which conversion is supported.
expression:
�
operator
function+ (expression)− constant
column-namehost-variablespecial-register
(1)(scalar-fullselect)
(2)labeled-duration
(3)case-expression
(4)cast-specification
(5)dereference-operation
(6)OLAP-function
(7)XML-function
(8)method-invocation
(9)subtype-treatment
(10)sequence-reference
operator:
(11)CONCAT/*+−
Expressions
Chapter 2. Language elements 187
Notes:
1 See “Scalar fullselect” on page 194 for more information.
2 See “Labeled durations” on page 195 for more information.
3 See “CASE expressions” on page 201 for more information.
4 See “CAST specifications” on page 203 for more information.
5 See “Dereference operations” on page 206 for more information.
6 See “OLAP functions” on page 207 for more information.
7 See “XML functions” on page 214 for more information.
8 See “Method invocation” on page 218 for more information.
9 See “Subtype treatment” on page 219 for more information.
10 See “Sequence reference” on page 220 for more information.
11 || may be used as a synonym for CONCAT.
Expressions without operatorsIf no operators are used, the result of the expression is the specified value.
Examples:SALARY:SALARY’SALARY’MAX(SALARY)
Expressions with the concatenation operatorThe concatenation operator (CONCAT) links two string operands to form astring expression.
The operands of concatenation must be compatible strings. Note that a binarystring cannot be concatenated with a character string, including characterstrings defined as FOR BIT DATA (SQLSTATE 42884).
In a Unicode database, concatenation involving both character string operandsand graphic string operands will first convert the character operands tographic operands. Note that in a non-Unicode database, concatenation cannotinvolve both character and graphic operands.
If either operand can be null, the result can be null, and if either is null, theresult is the null value. Otherwise, the result consists of the first operandstring followed by the second. Note that no check is made for improperlyformed mixed data when doing concatenation.
The length of the result is the sum of the lengths of the operands.
The data type and length attribute of the result is determined from that of theoperands as shown in the following table:
Expressions
188 SQL Reference, Volume 1
Table 12. Data Type and Length of Concatenated Operands
Operands CombinedLengthAttributes
Result
CHAR(A) CHAR(B) <255 CHAR(A+B)
CHAR(A) CHAR(B) >254 VARCHAR(A+B)
CHAR(A) VARCHAR(B) <4001 VARCHAR(A+B)
CHAR(A) VARCHAR(B) >4000 LONG VARCHAR
CHAR(A) LONG VARCHAR - LONG VARCHAR
VARCHAR(A) VARCHAR(B) <4001 VARCHAR(A+B)
VARCHAR(A) VARCHAR(B) >4000 LONG VARCHAR
VARCHAR(A) LONG VARCHAR - LONG VARCHAR
LONG VARCHAR LONG VARCHAR - LONG VARCHAR
CLOB(A) CHAR(B) - CLOB(MIN(A+B, 2G))
CLOB(A) VARCHAR(B) - CLOB(MIN(A+B, 2G))
CLOB(A) LONG VARCHAR - CLOB(MIN(A+32K, 2G))
CLOB(A) CLOB(B) - CLOB(MIN(A+B, 2G))
GRAPHIC(A) GRAPHIC(B) <128 GRAPHIC(A+B)
GRAPHIC(A) GRAPHIC(B) >127 VARGRAPHIC(A+B)
GRAPHIC(A) VARGRAPHIC(B) <2001 VARGRAPHIC(A+B)
GRAPHIC(A) VARGRAPHIC(B) >2000 LONG VARGRAPHIC
GRAPHIC(A) LONG VARGRAPHIC - LONG VARGRAPHIC
VARGRAPHIC(A) VARGRAPHIC(B) <2001 VARGRAPHIC(A+B)
VARGRAPHIC(A) VARGRAPHIC(B) >2000 LONG VARGRAPHIC
VARGRAPHIC(A) LONG VARGRAPHIC - LONG VARGRAPHIC
LONG VARGRAPHIC LONGVARGRAPHIC
- LONG VARGRAPHIC
DBCLOB(A) GRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
Expressions with the concatenation operator
Chapter 2. Language elements 189
Table 12. Data Type and Length of Concatenated Operands (continued)
Operands CombinedLengthAttributes
Result
DBCLOB(A) VARGRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
DBCLOB(A) LONG VARGRAPHIC - DBCLOB(MIN(A+16K, 1G))
DBCLOB(A) DBCLOB(B) - DBCLOB(MIN(A+B, 1G))
BLOB(A) BLOB(B) - BLOB(MIN(A+B, 2G))
Note that, for compatibility with previous versions, there is no automaticescalation of results involving LONG data types to LOB data types. Forexample, concatenation of a CHAR(200) value and a completely full LONGVARCHAR value would result in an error rather than in a promotion to aCLOB data type.
The code page of the result is considered a derived code page and isdetermined by the code page of its operands.
One operand may be a parameter marker. If a parameter marker is used, thenthe data type and length attributes of that operand are considered to be thesame as those for the non-parameter marker operand. The order of operationsmust be considered to determine these attributes in cases with nestedconcatenation.
Example 1: If FIRSTNME is Pierre and LASTNAME is Fermat, then thefollowing:
FIRSTNME CONCAT ’ ’ CONCAT LASTNAME
returns the value Pierre Fermat.
Example 2: Given:v COLA defined as VARCHAR(5) with value ’AA’
v :host_var defined as a character host variable with length 5 and value’BB ’
v COLC defined as CHAR(5) with value ’CC’
v COLD defined as CHAR(5) with value ’DDDDD’
The value of COLA CONCAT :host_var CONCAT COLC CONCAT COLD is’AABB CC DDDDD’
Expressions with the concatenation operator
190 SQL Reference, Volume 1
The data type is VARCHAR, the length attribute is 17 and the result codepage is the database code page.
Example 3: Given:COLA defined as CHAR(10)COLB defined as VARCHAR(5)
The parameter marker in the expression:COLA CONCAT COLB CONCAT ?
is considered VARCHAR(15), because COLA CONCAT COLB is evaluated first,giving a result that is the first operand of the second CONCAT operation.
User-defined typesA user-defined type cannot be used with the concatenation operator, even if itis a distinct type with a source data type that is a string type. To concatenate,create a function with the CONCAT operator as its source. For example, ifthere were distinct types TITLE and TITLE_DESCRIPTION, both of which hadVARCHAR(25) data types, the following user-defined function, ATTACH,could be used to concatenate them.
CREATE FUNCTION ATTACH (TITLE, TITLE_DESCRIPTION)RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())
Alternately, the concatenation operator could be overloaded using auser-defined function to add the new data types.
CREATE FUNCTION CONCAT (TITLE, TITLE_DESCRIPTION)RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())
Expressions with arithmetic operatorsIf arithmetic operators are used, the result of the expression is a value derivedfrom the application of the operators to the values of the operands.
If any operand can be null, or the database is configured withDFT_SQLMATHWARN set to yes, the result can be null.
If any operand has the null value, the result of the expression is the nullvalue.
Arithmetic operators can be applied to signed numeric types and datetimetypes (see “Datetime arithmetic in SQL” on page 196). For example, USER+2 isinvalid. Sourced functions can be defined for arithmetic operations on distincttypes with a source type that is a signed numeric type.
The prefix operator + (unary plus) does not change its operand. The prefixoperator − (unary minus) reverses the sign of a nonzero operand; and if the
Expressions with the concatenation operator
Chapter 2. Language elements 191
data type of A is small integer, the data type of −A is large integer. The firstcharacter of the token following a prefix operator must not be a plus or minussign.
The infix operators +, −, *, and / specify addition, subtraction, multiplication,and division, respectively. The value of the second operand of division mustnot be zero. These operators can also be treated as functions. Thus, theexpression ″+″(a,b) is equivalent to the expression a+b. “operator” function.
Arithmetic errorsIf an arithmetic error such as zero divide or a numeric overflow occurs duringthe processing of an expression, an error is returned and the SQL statementprocessing the expression fails with an error (SQLSTATE 22003 or 22012).
A database can be configured (using DFT_SQLMATHWARN set to yes) sothat arithmetic errors return a null value for the expression, issue a warning(SQLSTATE 01519 or 01564), and proceed with processing of the SQLstatement. When arithmetic errors are treated as nulls, there are implicationson the results of SQL statements. The following are some examples of theseimplications.v An arithmetic error that occurs in the expression that is the argument of a
column function causes the row to be ignored in the determining the resultof the column function. If the arithmetic error was an overflow, this maysignificantly impact the result values.
v An arithmetic error that occurs in the expression of a predicate in aWHERE clause can cause rows to not be included in the result.
v An arithmetic error that occurs in the expression of a predicate in a checkconstraint results in the update or insert proceeding since the constraint isnot false.
If these types of impacts are not acceptable, additional steps should be takento handle the arithmetic error to produce acceptable results. Some examplesare:v add a case expression to check for zero divide and set the desired value for
such a situationv add additional predicates to handle nulls (like a check constraint on not
nullable columns could become:check (c1*c2 is not null and c1*c2>5000)
to cause the constraint to be violated on an overflow).
Two-integer operandsIf both operands of an arithmetic operator are integers, the operation isperformed in binary and the result is a large integer unless either (or both)operand is a big integer, in which case the result is a big integer. Any
Expressions with arithmetic operators
192 SQL Reference, Volume 1
remainder of division is lost. The result of an integer arithmetic operation(including unary minus) must be within the range of the result type.
Integer and decimal operandsIf one operand is an integer and the other is a decimal, the operation isperformed in decimal using a temporary copy of the integer that has beenconverted to a decimal number with precision p and scale 0; p is 19 for a biginteger, 11 for a large integer, and 5 for a small integer.
Two-decimal operandsIf both operands are decimal, the operation is performed in decimal. Theresult of any decimal arithmetic operation is a decimal number with aprecision and scale that are dependent on the operation and the precision andscale of the operands. If the operation is addition or subtraction and theoperands do not have the same scale, the operation is performed with atemporary copy of one of the operands. The copy of the shorter operand isextended with trailing zeros so that its fractional part has the same number ofdigits as the longer operand.
The result of a decimal operation must not have a precision greater than 31.The result of decimal addition, subtraction, and multiplication is derived froma temporary result which may have a precision greater than 31. If theprecision of the temporary result is not greater than 31, the final result is thesame as the temporary result.
Decimal arithmetic in SQLThe following formulas define the precision and scale of the result of decimaloperations in SQL. The symbols p and s denote the precision and scale of thefirst operand, and the symbols p' and s' denote the precision and scale of thesecond operand.
Addition and subtractionThe precision is min(31,max(p-s,p’-s’) +max(s,s’)+1). The scale of the result ofaddition and subtraction is max (s,s’).
MultiplicationThe precision of the result of multiplication is min (31,p+ p’) and the scale ismin(31,s+s’).
DivisionThe precision of the result of division is 31. The scale is 31-p+s-s'. The scalemust not be negative.
Note: The MIN_DEC_DIV_3 database configuration parameter alters the scalefor decimal arithmetic operations involving division. If the parametervalue is set to NO, the scale is calculated as 31-p+s-s'. If the parameter
Two-integer operands
Chapter 2. Language elements 193
is set to YES, the scale is calculated as MAX(3, 31-p+ s-s'). This ensuresthat the result of decimal division always has a scale of at least 3(precision is always 31).
Floating-point operandsIf either operand of an arithmetic operator is floating-point, the operation isperformed in floating-point, the operands having first been converted todouble-precision floating-point numbers, if necessary. Thus, if any element ofan expression is a floating-point number, the result of the expression is adouble-precision floating-point number.
An operation involving a floating-point number and an integer is performedwith a temporary copy of the integer which has been converted todouble-precision floating-point. An operation involving a floating-pointnumber and a decimal number is performed with a temporary copy of thedecimal number which has been converted to double-precision floating-point.The result of a floating-point operation must be within the range offloating-point numbers.
User-defined types as operandsA user-defined type cannot be used with arithmetic operators, even if itssource data type is numeric. To perform an arithmetic operation, create afunction with the arithmetic operator as its source. For example, if there weredistinct types INCOME and EXPENSES, both of which had DECIMAL(8,2)data types, then the following user-defined function, REVENUE, could beused to subtract one from the other.
CREATE FUNCTION REVENUE (INCOME, EXPENSES)RETURNS DECIMAL(8,2) SOURCE "-" (DECIMAL, DECIMAL)
Alternately, the - (minus) operator could be overloaded using a user-definedfunction to subtract the new data types.
CREATE FUNCTION "-" (INCOME, EXPENSES)RETURNS DECIMAL(8,2) SOURCE "-" (DECIMAL, DECIMAL)
Scalar fullselectA scalar fullselect, as supported in an expression, is a fullselect, enclosed inparentheses, that returns a single row consisting of a single column value. Ifthe fullselect does not return a row, the result of the expression is the nullvalue. If the select list element is an expression that is simply a column nameor a dereference operation, the result column name is based on the name ofthe column.
Datetime operations and durationsDatetime values can be incremented, decremented, and subtracted. Theseoperations may involve decimal numbers called durations. Following is adefinition of durations and a specification of the rules for datetime arithmetic.
Division
194 SQL Reference, Volume 1
A duration is a number representing an interval of time. There are four typesof durations.
Labeled durations
labeled-duration:
function(expression)constantcolumn-namehost-variable
YEARYEARSMONTHMONTHSDAYDAYSHOURHOURSMINUTEMINUTESSECONDSECONDSMICROSECONDMICROSECONDS
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 sevenduration keywords: YEARS, MONTHS, DAYS, HOURS, MINUTES,SECONDS, or MICROSECONDS. (The singular form of these keywords is alsoacceptable: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, andMICROSECOND.) The number specified is converted as if it were assigned toa DECIMAL(15,0) number. A labeled duration can only be used as an operandof an arithmetic operator in which the other operand is a value of data typeDATE, TIME, or TIMESTAMP. Thus, the expression HIREDATE + 2 MONTHS+ 14 DAYS is valid, whereas the expression HIREDATE + (2 MONTHS + 14DAYS) is not. In both of these expressions, the labeled durations are 2MONTHS and 14 DAYS.
Date durationA date duration represents a number of years, months, and days, expressed asa DECIMAL(8,0) number. To be properly interpreted, the number must havethe format yyyymmdd., where yyyy represents the number of years, mm thenumber of months, and dd the number of days. (The period in the formatindicates a DECIMAL data type.) The result of subtracting one date valuefrom another, as in the expression HIREDATE − BRTHDATE, is a dateduration.
Time durationA time duration represents a number of hours, minutes, and seconds, expressedas a DECIMAL(6,0) number. To be properly interpreted, the number musthave the format hhmmss., where hh represents the number of hours, mm the
Datetime operations and durations
Chapter 2. Language elements 195
number of minutes, and ss the number of seconds. (The period in the formatindicates a DECIMAL data type.) The result of subtracting one time valuefrom another is a time duration.
Timestamp durationA 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 formatyyyymmddhhmmss.zzzzzz, where yyyy, mm, dd, hh, mm, ss, and zzzzzz represent,respectively, the number of years, months, days, hours, minutes, seconds, andmicroseconds. The result of subtracting one timestamp value from another is atimestamp duration.
Datetime arithmetic in SQLThe only arithmetic operations that can be performed on datetime values areaddition and subtraction. If a datetime value is the operand of addition, theother operand must be a duration. The specific rules governing the use of theaddition 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
labeled 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.
The rules for the use of the subtraction operator on datetime values are notthe same as those for addition because a datetime value cannot be subtractedfrom a duration, and because the operation of subtracting two datetime valuesis not the same as the operation of subtracting a duration from a datetimevalue. The specific rules governing the use of the subtraction operator withdatetime 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,MONTHS, or DAYS.
v If the second operand is a date, the first operand must be a date, or a stringrepresentation of a date.
v If the first operand is a time, the second operand must be a time, a timeduration, 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 stringrepresentation of a time.
v If the first operand is a timestamp, the second operand must be atimestamp, a string representation of a timestamp, or a duration.
Time duration
196 SQL Reference, Volume 1
v If the second operand is a timestamp, the first operand must be atimestamp or a string representation of a timestamp.
v Neither operand of the subtraction operator can be a parameter marker.
Date arithmeticDates can be subtracted, incremented, or decremented.
Subtracting Dates: The result of subtracting one date (DATE2) from another(DATE1) is a date duration that specifies the number of years, months, anddays between the two dates. The data type of the result is DECIMAL(8,0). IfDATE1 is greater than or equal to DATE2, DATE2 is subtracted from DATE1.If DATE1 is less than DATE2, however, DATE1 is subtracted from DATE2, andthe sign of the result is made negative. The following procedural descriptionclarifies the steps involved in the operation result = DATE1 − DATE2.
If DAY(DATE2) <= DAY(DATE1)then DAY(RESULT) = DAY(DATE1) − DAY(DATE2).
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.
If MONTH(DATE2) <= MONTH(DATE1)then MONTH(RESULT) = MONTH(DATE1) - MONTH(DATE2).
If MONTH(DATE2) > MONTH(DATE1)then MONTH(RESULT) = 12 + MONTH(DATE1) − MONTH(DATE2).YEAR(DATE2) is then incremented by 1.
YEAR(RESULT) = YEAR(DATE1) − YEAR(DATE2).
For example, the result of DATE('3/15/2000') − '12/31/1999' is 00000215. (or, aduration of 0 years, 2 months, and 15 days).
Incrementing and decrementing dates: The result of adding a duration to adate, or of subtracting a duration from a date, is itself a date. (For thepurposes 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, startingwith the page on which the date appears.) The result must fall between thedates January 1, 0001 and December 31, 9999 inclusive.
If a duration of years is added or subtracted, only the year portion of the dateis affected. The month is unchanged, as is the day unless the result would beFebruary 29 of a non-leap-year. In this case, the day is changed to 28, and awarning indicator in the SQLCA is set to indicate the adjustment.
Similarly, if a duration of months is added or subtracted, only months and, ifnecessary, years are affected. The day portion of the date is unchanged unless
Datetime arithmetic in SQL
Chapter 2. Language elements 197
the result would be invalid (September 31, for example). In this case, the dayis set to the last day of the month, and a warning indicator in the SQLCA isset to indicate the adjustment.
Adding or subtracting a duration of days will, of course, affect the dayportion of the date, and potentially the month and year.
Date durations, whether positive or negative, may also be added to andsubtracted from dates. As with labeled durations, the result is a valid date,and a warning indicator is set in the SQLCA whenever an end-of-monthadjustment is necessary.
When a positive date duration is added to a date, or a negative date durationis subtracted from a date, the date is incremented by the specified number ofyears, months, and days, in that order. Thus, DATE1 + X, where X is apositive 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 dateduration is added to a date, the date is decremented by the specified numberof days, months, and years, in that order. Thus, DATE1 − X, where X is apositive DECIMAL(8,0) number, is equivalent to the expression:
DATE1 − DAY(X) DAYS − MONTH(X) MONTHS − YEAR(X) YEARS.
When adding durations to dates, adding one month to a given date gives thesame date one month later unless that date does not exist in the later month.In that case, the date is set to that of the last day of the later month. Forexample, January 28 plus one month gives February 28; and one month addedto January 29, 30, or 31 results in either February 28 or, for a leap year,February 29.
Note: If one or more months is added to a given date and then the samenumber of months is subtracted from the result, the final date is notnecessarily the same as the original date.
Time arithmeticTimes can be subtracted, incremented, or decremented.
Subtracting time values: The result of subtracting one time (TIME2) fromanother (TIME1) is a time duration that specifies the number of hours,minutes, and seconds between the two times. The data type of the result isDECIMAL(6,0).
If TIME1 is greater than or equal to TIME2, TIME2 is subtracted from TIME1.
Incrementing and decrementing dates
198 SQL Reference, Volume 1
If TIME1 is less than TIME2, however, TIME1 is subtracted from TIME2, andthe sign of the result is made negative. The following procedural descriptionclarifies the steps involved in the operation result = TIME1 − TIME2.
If SECOND(TIME2) <= SECOND(TIME1)then SECOND(RESULT) = SECOND(TIME1) − SECOND(TIME2).
If SECOND(TIME2) > SECOND(TIME1)then SECOND(RESULT) = 60 + SECOND(TIME1) − SECOND(TIME2).MINUTE(TIME2) is then incremented by 1.
If MINUTE(TIME2) <= MINUTE(TIME1)then MINUTE(RESULT) = MINUTE(TIME1) − MINUTE(TIME2).
If MINUTE(TIME1) > MINUTE(TIME1)then MINUTE(RESULT) = 60 + MINUTE(TIME1) − MINUTE(TIME2).HOUR(TIME2) is then incremented by 1.
HOUR(RESULT) = HOUR(TIME1) − HOUR(TIME2).
For example, the result of TIME(’11:02:26’) − ’00:32:56’ is 102930. (a durationof 10 hours, 29 minutes, and 30 seconds).
Incrementing and decrementing time values: The result of adding aduration to a time, or of subtracting a duration from a time, is itself a time.Any overflow or underflow of hours is discarded, thereby ensuring that theresult is always a time. If a duration of hours is added or subtracted, only thehours portion of the time is affected. The minutes and seconds are unchanged.
Similarly, if a duration of minutes is added or subtracted, only minutes and, ifnecessary, hours are affected. The seconds portion of the time is unchanged.
Adding or subtracting a duration of seconds will, of course, affect the secondsportion of the time, and potentially the minutes and hours.
Time durations, whether positive or negative, also can be added to andsubtracted from times. The result is a time that has been incremented ordecremented by the specified number of hours, minutes, and seconds, in thatorder. TIME1 + X, where “X” is a DECIMAL(6,0) number, is equivalent to theexpression:
TIME1 + HOUR(X) HOURS + MINUTE(X) MINUTES + SECOND(X) SECONDS
Note: Although the time ’24:00:00’ is accepted as a valid time, it is neverreturned as the result of time addition or subtraction, even if theduration operand is zero (for example, time(’24:00:00’)±0 seconds =’00:00:00’).
Timestamp arithmeticTimestamps can be subtracted, incremented, or decremented.
Subtracting time values
Chapter 2. Language elements 199
Subtracting timestamps: The result of subtracting one timestamp (TS2) fromanother (TS1) is a timestamp duration that specifies the number of years,months, days, hours, minutes, seconds, and microseconds between the twotimestamps. 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 lessthan TS2, however, TS1 is subtracted from TS2 and the sign of the result ismade negative. The following procedural description clarifies the stepsinvolved in the operation result = TS1 − TS2:
If MICROSECOND(TS2) <= MICROSECOND(TS1)then MICROSECOND(RESULT) = MICROSECOND(TS1) −MICROSECOND(TS2).
If MICROSECOND(TS2) > MICROSECOND(TS1)then MICROSECOND(RESULT) = 1000000 +MICROSECOND(TS1) − MICROSECOND(TS2)and SECOND(TS2) is incremented by 1.
The seconds and minutes part of the timestamps are subtracted as specified inthe rules for subtracting times.
If HOUR(TS2) <= HOUR(TS1)then HOUR(RESULT) = HOUR(TS1) − HOUR(TS2).
If HOUR(TS2) > HOUR(TS1)then HOUR(RESULT) = 24 + HOUR(TS1) − HOUR(TS2)and DAY(TS2) is incremented by 1.
The date part of the timestamps is subtracted as specified in the rules forsubtracting dates.
Incrementing and decrementing timestamps: The result of adding aduration to a timestamp, or of subtracting a duration from a timestamp isitself a timestamp. Date and time arithmetic is performed as previouslydefined, except that an overflow or underflow of hours is carried into the datepart of the result, which must be within the range of valid dates.Microseconds overflow into seconds.
Precedence of operationsExpressions within parentheses and dereference operations are evaluated firstfrom left to right. (Parentheses are also used in subselect statements, searchconditions, and functions. However, they should not be used to arbitrarilygroup sections within SQL statements.) When the order of evaluation is notspecified by parentheses, prefix operators are applied before multiplicationand division, and multiplication and division are applied before addition andsubtraction. Operators at the same precedence level are applied from left toright.
Subtracting timestamps
200 SQL Reference, Volume 1
CASE expressions
case-expression:
CASE searched-when-clausesimple-when-clause
ELSE NULL
ELSE result-expressionEND
searched-when-clause:
� WHEN search-condition THEN result-expressionNULL
simple-when-clause:
�expression WHEN expression THEN result-expressionNULL
CASE expressions allow an expression to be selected based on the evaluationof one or more conditions. In general, the value of the case-expression is thevalue of the result-expression following the first (leftmost) case that evaluates totrue. If no case evaluates to true and the ELSE keyword is present then theresult is the value of the result-expression or NULL. If no case evaluates to trueand the ELSE keyword is not present then the result is NULL. Note that whena case evaluates to unknown (because of NULLs), the case is not true andhence is treated the same way as a case that evaluates to false.
If the CASE expression is in a VALUES clause, an IN predicate, a GROUP BYclause, or an ORDER BY clause, the search-condition in a searched-when-clausecannot be a quantified predicate, IN predicate using a fullselect, or an EXISTSpredicate (SQLSTATE 42625).
When using the simple-when-clause, the value of the expression prior to the firstWHEN keyword is tested for equality with the value of the expressionfollowing the WHEN keyword. The data type of the expression prior to the
1 4 32
1.10 * (Salary + Bonus) + Salary / :VAR3
Figure 11. Precedence of Operations
CASE expressions
Chapter 2. Language elements 201
first WHEN keyword must therefore be comparable to the data types of eachexpression following the WHEN keyword(s). The expression prior to the firstWHEN keyword in a simple-when-clause cannot include a function that isvariant or has an external action (SQLSTATE 42845).
A result-expression is an expression following the THEN or ELSE keywords.There must be at least one result-expression in the CASE expression (NULLcannot be specified for every case) (SQLSTATE 42625). All result expressionsmust have compatible data types (SQLSTATE 42804).
Examples:
v If the first character of a department number is a division in theorganization, then a CASE expression can be used to list the full name ofthe 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 ’Accounting’WHEN ’D’ THEN ’Design’WHEN ’E’ THEN ’Operations’
ENDFROM EMPLOYEE;
v The number of years of education are used in the EMPLOYEE table to givethe education level. A CASE expression can be used to group these and toshow the level of education.
SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME,CASE
WHEN EDLEVEL < 15 THEN ’SECONDARY’WHEN EDLEVEL < 19 THEN ’COLLEGE’ELSE ’POST GRADUATE’
ENDFROM EMPLOYEE
v Another interesting example of CASE statement usage is in protecting fromdivision by 0 errors. For example, the following code finds the employeeswho earn more than 25% of their income from commission, but who are notfully paid on commission:
SELECT EMPNO, WORKDEPT, SALARY+COMM FROM EMPLOYEEWHERE (CASE WHEN SALARY=0 THEN NULL
ELSE COMM/SALARYEND) > 0.25;
v The following CASE expressions are the same:SELECT LASTNAME,
CASEWHEN LASTNAME = ’Haas’ THEN ’President’...
CASE expressions
202 SQL Reference, Volume 1
SELECT LASTNAME,CASE LASTNAMEWHEN ’Haas’ THEN ’President’...
There are two scalar functions, NULLIF and COALESCE, that are specializedto handle a subset of the functionality provided by CASE. Table 13 shows theequivalent expressions using CASE or these functions.
Table 13. Equivalent CASE Expressions
Expression Equivalent Expression
CASE WHEN e1=e2 THEN NULL ELSE e1 END NULLIF(e1,e2)
CASE WHEN e1 IS NOT NULL THEN e1 ELSE e2END
COALESCE(e1,e2)
CASE WHEN e1 IS NOT NULL THEN e1 ELSECOALESCE(e2,...,eN) END
COALESCE(e1,e2,...,eN)
CAST specifications
cast-specification:
CAST ( expressionNULLparameter-marker
AS data-type �
� )(1)
SCOPE typed-table-nametyped-view-name
Notes:
1 The SCOPE clause only applies to the REF data type.
The CAST specification returns the cast operand (the first operand) cast to thetype specified by the data type. If the cast is not supported, an error isreturned (SQLSTATE 42846).
expressionIf the cast operand is an expression (other than parameter marker orNULL), the result is the argument value converted to the specified targetdata type.
When casting character strings (other than CLOBs) to a character stringwith a different length, a warning (SQLSTATE 01004) is returned iftruncation of other than trailing blanks occurs. When casting graphiccharacter strings (other than DBCLOBs) to a graphic character string witha different length, a warning (SQLSTATE 01004) is returned if truncation
CASE expressions
Chapter 2. Language elements 203
of other than trailing blanks occurs. For BLOB, CLOB and DBCLOB castoperands, the warning is issued if any characters are truncated.
NULLIf the cast operand is the keyword NULL, the result is a null value thathas the specified data type.
parameter-markerA parameter marker (specified as a question mark character) is normallyconsidered an expression, but is documented separately in this casebecause it has a special meaning. If the cast operand is a parameter-marker,the specified data type is considered a promise that the replacement will beassignable to the specified data type (using store assignment for strings).Such a parameter marker is considered a typed parameter marker. Typedparameter markers will be treated like any other typed value for thepurpose of function resolution, DESCRIBE of a select list or for columnassignment.
data typeThe name of an existing data type. If the type name is not qualified, theSQL path is used to do data type resolution. A data type that has anassociated attributes like length or precision and scale should includethese attributes when specifying data type (CHAR defaults to a length of 1and DECIMAL defaults to a precision of 5 and scale of 0 if not specified).Restrictions on the supported data types are based on the specified castoperand.v For a cast operand that is an expression, the supported target data types
depend on the data type of the cast operand (source data type).v For a cast operand that is the keyword NULL, any existing data type
can be used.v For a cast operand that is a parameter marker, the target data type can
be any existing data type. If the data type is a user-defined distincttype, the application using the parameter marker will use the sourcedata type of the user-defined distinct type. If the data type is auser-defined structured type, the application using the parametermarker will use the input parameter type of the TO SQL transformfunction for the user-defined structured type.
SCOPEWhen the data type is a reference type, a scope may be defined thatidentifies the target table or target view of the reference.
typed-table-nameThe name of a typed table. The table must already exist (SQLSTATE42704). The cast must be to data-type REF(S), where S is the type oftyped-table-name (SQLSTATE 428DM).
CAST specifications
204 SQL Reference, Volume 1
typed-view-nameThe name of a typed view. The view must exist or have the samename as the view being created that includes the cast as part of theview definition (SQLSTATE 42704). The cast must be to data-typeREF(S), where S is the type of typed-view-name (SQLSTATE 428DM).
When numeric data is cast to character data, the result data type is afixed-length character string . When character data is cast to numeric data, theresult data type depends on the type of number specified. For example, if castto integer, it becomes a large integer .
Examples:
v An application is only interested in the integer portion of the SALARY(defined as decimal(9,2)) from the EMPLOYEE table. The following query,including the employee number and the integer value of SALARY, could beprepared.
SELECT EMPNO, CAST(SALARY AS INTEGER) FROM EMPLOYEE
v Assume the existence of a distinct type called T_AGE that is defined onSMALLINT and used to create column AGE in PERSONNEL table. Alsoassume the existence of a distinct type called R_YEAR that is defined onINTEGER and used to create column RETIRE_YEAR in PERSONNEL table.The following update statement could be prepared.
UPDATE PERSONNEL SET RETIRE_YEAR =?WHERE AGE = CAST( ? AS T_AGE)
The first parameter is an untyped parameter marker that would have a datatype of R_YEAR, although the application will use an integer for thisparameter marker. This does not require the explicit CAST specificationbecause it is an assignment.
The second parameter marker is a typed parameter marker that is cast as adistinct type T_AGE. This satisfies the requirement that the comparisonmust be performed with compatible data types. The application will use thesource data type (which is SMALLINT) for processing this parametermarker.
Successful processing of this statement assumes that the function pathincludes the schema name of the schema (or schemas) where the twodistinct types are defined.
v An application supplies a value that is a series of bits, for example an audiostream, and it should not undergo code page conversion before being usedin an SQL statement. The application could use the following CAST:
CAST( ? AS VARCHAR(10000) FOR BIT DATA)
CAST specifications
Chapter 2. Language elements 205
Dereference operations
dereference-operation:
scoped-ref-expression −> name1
�
( ),
expression
The scope of the scoped reference expression is a table or view called thetarget table or view. The scoped reference expression identifies a target row.The target row is the row in the target table or view (or in one of its subtablesor subviews) whose object identifier (OID) column value matches thereference expression. The dereference operation can be used to access acolumn of the target row, or to invoke a method, using the target row as thesubject of the method. The result of a dereference operation can always benull. The dereference operation takes precedence over all other operators.
scoped-ref-expressionAn expression that is a reference type that has a scope (SQLSTATE428DT). If the expression is a host variable, parameter marker or otherunscoped reference type value, a CAST specification with a SCOPE clauseis required to give the reference a scope.
name1Specifies an unqualified identifier.
If no parentheses follow name1, and name1 matches the name of anattribute of the target type, then the value of the dereference operation isthe value of the named column in the target row. In this case, the datatype of the column (made nullable) determines the result type of thedereference operation. If no target row exists whose object identifiermatches the reference expression, then the result of the dereferenceoperation is null. If the dereference operation is used in a select list and isnot included as part of an expression, name1 becomes the result columnname.
If parentheses follow name1, or if name1 does not match the name of anattribute of the target type, then the dereference operation is treated as amethod invocation. The name of the invoked method is name1. Thesubject of the method is the target row, considered as an instance of itsstructured type. If no target row exists whose object identifier matches thereference expression, the subject of the method is a null value of the targettype. The expressions inside parentheses, if any, provide the remainingparameters of the method invocation. The normal process is used for
Dereference operations
206 SQL Reference, Volume 1
resolution of the method invocation. The result type of the selectedmethod (made nullable) determines the result type of the dereferenceoperation.
The authorization ID of the statement that uses a dereference operation musthave SELECT privilege on the target table of the scoped-ref-expression(SQLSTATE 42501).
A dereference operation can never modify values in the database. If adereference operation is used to invoke a mutator method, the mutatormethod modifies a copy of the target row and returns the copy, leaving thedatabase unchanged.
Examples:
v Assume the existence of an EMPLOYEE table that contains a column calledDEPTREF which is a reference type scoped to a typed table based on a typethat includes the attribute DEPTNAME. The values of DEPTREF in thetable EMPLOYEE should correspond to the OID column values in the targettable of DEPTREF column.
SELECT EMPNO, DEPTREF−>DEPTNAMEFROM EMPLOYEE
v Using the same tables as in the previous example, use a dereferenceoperation to invoke a method named BUDGET, with the target row assubject parameter, and '1997' as an additional parameter.
SELECT EMPNO, DEPTREF−>BUDGET(’1997’) AS DEPTBUDGET97FROM EMPLOYEE
OLAP functions
OLAP-function:
ranking-functionnumbering-functionaggregation-function
ranking-function:
RANK ()DENSE_RANK ()
OVER (window-partition-clause
�
� window-order-clause )
numbering-function:
ROW_NUMBER () OVER (window-partition-clause
�
Dereference operations
Chapter 2. Language elements 207
� )window-order-clause
aggregation-function:
column-function OVER (window-partition-clause
�
�window-order-clause
window-aggregation-group-clause
�
�RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)window-aggregation-group-clause
window-partition-clause:
�
,
PARTITION BY partitioning-expression
window-order-clause:
ORDER BY �
,asc option
sort-key-expressiondesc option
ORDER OF table-designator
asc option:
NULLS LASTASC
NULLS FIRST
desc option:
NULLS FIRSTDESC
NULLS LAST
OLAP functions
208 SQL Reference, Volume 1
window-aggregation-group-clause:
ROWSRANGE
group-startgroup-betweengroup-end
group-start:
UNBOUNDED PRECEDINGunsigned-constant PRECEDINGCURRENT ROW
group-between:
BETWEEN group-bound1 AND group-bound2
group-bound1:
UNBOUNDED PRECEDINGunsigned-constant PRECEDINGunsigned-constant FOLLOWINGCURRENT ROW
group-bound2:
UNBOUNDED FOLLOWINGunsigned-constant PRECEDINGunsigned-constant FOLLOWINGCURRENT ROW
group-end:
UNBOUNDED FOLLOWINGunsigned-constant FOLLOWING
On-Line Analytical Processing (OLAP) functions provide the ability to returnranking, row numbering and existing column function information as a scalarvalue in a query result. An OLAP function can be included in expressions in aselect-list or the ORDER BY clause of a select-statement (SQLSTATE 42903).An OLAP function cannot be used as an argument of a column function(SQLSTATE 42607). The query result to which the OLAP function is applied isthe result table of the innermost subselect that includes the OLAP function.
When specifying an OLAP function, a window is specified that defines therows over which the function is applied, and in what order. When used witha column function, the applicable rows can be further refined, relative to thecurrent row, as either a range or a number of rows preceding and following
OLAP functions
Chapter 2. Language elements 209
the current row. For example, within a partition by month, an average can becalculated over the previous three month period.
The ranking function computes the ordinal rank of a row within the window.Rows that are not distinct with respect to the ordering within their windoware assigned the same rank. The results of ranking may be defined with orwithout gaps in the numbers resulting from duplicate values.
If RANK is specified, the rank of a row is defined as 1 plus the number ofrows that strictly precede the row. Thus, if two or more rows are not distinctwith respect to the ordering, then there will be one or more gaps in thesequential rank numbering.
If DENSE_RANK (or DENSERANK) is specified, the rank of a row is definedas 1 plus the number of preceding rows that are distinct with respect to theordering. Therefore, there will be no gaps in the sequential rank numbering.
The ROW_NUMBER (or ROWNUMBER) function computes the sequentialrow number of the row within the window defined by the ordering, startingwith 1 for the first row. If the ORDER BY clause is not specified in thewindow, the row numbers are assigned to the rows in arbitrary order, asreturned by the subselect (not according to any ORDER BY clause in theselect-statement).
The data type of the result of RANK, DENSE_RANK or ROW_NUMBER isBIGINT. The result cannot be null.
PARTITION BY (partitioning-expression,...)Defines the partition within which the function is applied. Apartitioning-expression is an expression used in defining the partitioning ofthe result set. Each column-name referenced in a partitioning-expressionmust unambiguously reference a result set column of the OLAP functionsubselect statement (SQLSTATE 42702 or 42703). A partitioning-expressioncannot include a scalar-fullselect (SQLSTATE 42822) or any function that isnot deterministic or has an external action (SQLSTATE 42845).
ORDER BY (sort-key-expression,...)Defines the ordering of rows within a partition that determines the valueof the OLAP function or the meaning of the ROW values in thewindow-aggregation-group-clause (it does not define the ordering of thequery result set).
sort-key-expressionAn expression used in defining the ordering of the rows within a windowpartition. Each column name referenced in a sort-key-expression mustunambiguously reference a column of the result set of the subselect,including the OLAP function (SQLSTATE 42702 or 42703). A
OLAP functions
210 SQL Reference, Volume 1
sort-key-expression cannot include a scalar fullselect (SQLSTATE 42822) orany function that is not deterministic or that has an external action(SQLSTATE 42845). This clause is required for the RANK andDENSE_RANK functions (SQLSTATE 42601).
ASCUses the values of the sort-key-expression in ascending order.
DESCUses the values of the sort-key-expression in descending order.
NULLS FIRSTThe window ordering considers null values before all non-null values inthe sort order.
NULLS LASTThe window ordering considers null values after all non-null values in thesort order.
ORDER OF table-designatorSpecifies that the same ordering used in table-designator should be appliedto the result table of the subselect. There must be a table referencematching table-designator in the FROM clause of the subselect that specifiesthis clause (SQLSTATE 42703). The subselect (or fullselect) correspondingto the specified table-designator must include an ORDER BY clause that isdependant on the data (SQLSTATE 428FI). The ordering that is applied isthe same as if the columns of the ORDER BY clause in the nestedsubselect (or fullselect) were included in the outer subselect (or fullselect),and these columns were specified in place of the ORDER OF clause.
window-aggregation-group-clauseThe aggregation group of a row R is a set of rows defined in relation to R(in the ordering of the rows of R’s partition). This clause specifies theaggregation group. If this clause is not specified, the default is the same asRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW,providing a cumulative aggregation result.
ROWSIndicates the aggregation group is defined by counting rows.
RANGEIndicates the aggregation group is defined by an offset from a sortkey.
group-startSpecifies the starting point for the aggregation group. The aggregationgroup end is the current row. Specification of the group-start clause isequivalent to a group-between clause of the form ″BETWEENgroup-start AND CURRENT ROW″.
OLAP functions
Chapter 2. Language elements 211
group-betweenSpecifies the aggregation group start and end based on either ROWSor RANGE.
group-endSpecifies the ending point for the aggregation group. The aggregationgroup start is the current row. Specification of the group-end clause isequivalent to a group-between clause of the form ″BETWEENCURRENT ROW AND group-end″.
UNBOUNDED PRECEDINGIncludes the entire partition preceding the current row. This can bespecified with either ROWS or RANGE. Also, this can be specifiedwith multiple sort-key-expressions in the window-order-clause.
UNBOUNDED FOLLOWINGIncludes the entire partition following the current row. This can bespecified with either ROWS or RANGE. Also, this can be specifiedwith multiple sort-key-expressions in the window-order-clause.
CURRENT ROWSpecifies the start or end of the aggregation group based on thecurrent row. If ROWS is specified, the current row is the aggregationgroup boundary. If RANGE is specified, the aggregation groupboundary includes the set of rows with the same values for thesort-key-expressions as the current row. This clause cannot be specifiedin group-bound2 if group-bound1 specifies value FOLLOWING.
value PRECEDINGSpecifies either the range or number of rows preceding the currentrow. If ROWS is specified, then value is a positive integer indicating anumber of rows. If RANGE is specified, then the data type of valuemust be comparable to the type of the sort-key-expression of thewindow-order-clause. There can only be one sort-key-expression, andthe data type of the sort-key-expression must allow subtraction. Thisclause cannot be specified in group-bound2 if group-bound1 isCURRENT ROW or value FOLLOWING.
value FOLLOWINGSpecifies either the range or number of rows following the currentrow. If ROWS is specified, then value is a positive integer indicating anumber of rows. If RANGE is specified, then the data type of valuemust be comparable to the type of the sort-key-expression of thewindow-order-clause. There can only be one sort-key-expression, andthe data type of the sort-key-expression must allow addition.
Examples:
OLAP functions
212 SQL Reference, Volume 1
v Display the ranking of employees, in order by surname, according to theirtotal salary (based on salary plus bonus) that have a total salary more than$30,000.
SELECT EMPNO, LASTNAME, FIRSTNME, SALARY+BONUS AS TOTAL_SALARY,RANK() OVER (ORDER BY SALARY+BONUS DESC) AS RANK_SALARY
FROM EMPLOYEE WHERE SALARY+BONUS > 30000ORDER BY LASTNAME
Note that if the result is to be ordered by the ranking, then replace ORDERBY LASTNAME with:
ORDER BY RANK_SALARY
orORDER BY RANK() OVER (ORDER BY SALARY+BONUS DESC)
v Rank the departments according to their average total salary.SELECT WORKDEPT, AVG(SALARY+BONUS) AS AVG_TOTAL_SALARY,
RANK() OVER (ORDER BY AVG(SALARY+BONUS) DESC) AS RANK_AVG_SALFROM EMPLOYEEGROUP BY WORKDEPTORDER BY RANK_AVG_SAL
v Rank the employees within a department according to their education level.Having multiple employees with the same rank in the department shouldnot increase the next ranking value.
SELECT WORKDEPT, EMPNO, LASTNAME, FIRSTNME, EDLEVEL,DENSE_RANK() OVER
(PARTITION BY WORKDEPT ORDER BY EDLEVEL DESC) AS RANK_EDLEVELFROM EMPLOYEEORDER BY WORKDEPT, LASTNAME
v Provide row numbers in the result of a query.SELECT ROW_NUMBER() OVER (ORDER BY WORKDEPT, LASTNAME) AS NUMBER,
LASTNAME, SALARYFROM EMPLOYEEORDER BY WORKDEPT, LASTNAME
v List the top five wage earners.SELECT EMPNO, LASTNAME, FIRSTNME, TOTAL_SALARY, RANK_SALARY
FROM (SELECT EMPNO, LASTNAME, FIRSTNME, SALARY+BONUS AS TOTAL_SALARY,RANK() OVER (ORDER BY SALARY+BONUS DESC) AS RANK_SALARYFROM EMPLOYEE) AS RANKED_EMPLOYEE
WHERE RANK_SALARY < 6ORDER BY RANK_SALARY
Note that a nested table expression was used to first compute the result,including the rankings, before the rank could be used in the WHEREclause. A common table expression could also have been used.
OLAP functions
Chapter 2. Language elements 213
XML functions
XML-function:
XML2CLOB ( xmlagg-function )xmlelement-function
xmlagg-function:
XMLAGG
�
( xmlelement-function ),
ASCORDER BY sort-key
DESC
sort-key:
column-namesort-key-expression
xmlelement-function:
XMLELEMENT ( NAME element-name �
�
�
�
xmlattributes-function,
element-content,
xmlattributes-function , element-content
)
xmlattributes-function:
XMLATTRIBUTES �
,
( attribute-value )AS attribute-name
XML2CLOBReturns the argument as a CLOB value. The schema is SYSIBM. Theargument must be an expression of data type XML. The result has theCLOB data type.
XMLAGGReturns the concatenation of a set of XML data. The schema is SYSIBM.The data type of the result is XML, and its length is set to 1 073 741 823. If
XML functions
214 SQL Reference, Volume 1
the XMLAGG function is applied to an empty set, the result is a nullvalue. Otherwise, the result is the concatenation of the values in the set.
ORDER BYSpecifies the order of the rows from the same grouping set that areprocessed in the aggregation. If the ORDER BY clause is omitted, or ifthe ORDER BY clause cannot distinguish the order of the columndata, the rows in the same grouping set are arbitrarily ordered.
sort-keyThe sort key can be a column name or a sort-key-expression. Notethat if the sort key is a constant, it does not refer to the position of theoutput column (as in the ordinary ORDER BY clause), but it is simplya constant, which implies no sort key.
Restrictions on using the XMLAGG function are:v Column functions cannot be used as direct input (SQLSTATE 42607).v XMLAGG cannot be used as a column function of an OLAP aggregate
function (SQLSTATE 42601).
XMLELEMENTConstructs an XML element from the arguments. The schema is SYSIBM.This function takes an element name, an optional collection of attributes,and zero or more arguments that will make up the element’s content. Theresult data type is XML.
NAMEThis keyword precedes the name of the XML element.
element-nameThe name of the XML element.
xmlattributes-functionXML attributes that are the result of the XMLATTRIBUTES function. Ifspecified, this must appear in the second argument of XMLELEMENTas the XMLATTRIBUTES function with the appropriate format.
element-contentThe content of the generated elements is specified by an expression ora list of expressions. The data type of the result of the expression mustbe one of SMALLINT, INTEGER, BIGINT, DECIMAL, NUMERIC,REAL, DOUBLE, CHAR, VARCHAR, LONG VARCHAR, CLOB,GRAPHIC, VARGRAPHIC, LONG VARGRAPHIC, DBCLOB, DATE,TIME, TIMESTAMP, XML, or any distinct type whose source type isone of the preceding data types. Character string data defined as FORBIT DATA is not allowed. The expressions can be any SQL expression,but cannot include a scalar fullselect, or a subquery.
XML functions
Chapter 2. Language elements 215
XMLATTRIBUTESConstructs XML attributes from the arguments. The schema is SYSIBM.The result has the same internal XML data type as the arguments.
attribute-valueThe attribute value is an expression. The data type of the result of theexpression must be one of: SMALLINT, INTEGER, BIGINT,DECIMAL, NUMERIC, REAL, DOUBLE, CHAR, VARCHAR, LONGVARCHAR, CLOB, GRAPHIC, VARGRAPHIC, LONG VARGRAPHIC,DBCLOB, DATE, TIME, TIMESTAMP, or any distinct type whosesource type is one of the preceding data types. Character string datadefined as FOR BIT DATA is not allowed. The expression can be anySQL expression but cannot include a scalar fullselect or a subquery. Ifthe expression is not a simple column reference, an attribute namemust be specified. Duplicate attribute names are not allowed(SQLSTATE 42713).
attribute-nameThe attribute name is an SQL identifier.
Examples:
v Construct a CLOB from the expression returned by the XMLELEMENTfunction. The query
SELECT e.empno, XML2CLOB(XMLELEMENT(NAME "Emp", e.firstnme || ’ ’ ||e.lastname))
AS "Result" FROM employee eWHERE e.edlevel = 12
produces the following result:EMPNO Result000290 <Emp>JOHN PARKER</Emp>000310 <Emp>MAUDE SETRIGHT</Emp>
v Produce a department element (for each department) with a list ofemployees, sorted by employee last name:
SELECT XML2CLOB(XMLELEMENT(NAME "Department",XMLATTRIBUTES(e.workdept AS "name"),XMLAGG(XMLELEMENT(NAME "emp", e.lastname)
ORDER BY e.lastname)
)) AS "dept_list"FROM employee eWHERE e.workdept IN (’C01’,’E21’)GROUP BY workdept
This query produces the following output. Note that no spaces or newlinecharacters are actually produced in the result; the following output hasbeen formatted for clarity.
XML functions
216 SQL Reference, Volume 1
dept_list<Department name = "C01">
<emp>KWAN</emp><emp>NICHOLLS</emp><emp>QUINTANA</emp>
</Department><Department name = "E21">
<emp>GOUNOT</emp><emp>LEE</emp><emp>MEHTA</emp><emp>SPENSER</emp>
</Department>
v For each department that reports to department A00, create an empty XMLelement named Mgr with an ID attribute equal to the MGRNO. The query
SELECT d.deptno, XML2CLOB(XMLELEMENT(NAME "Mgr",XMLATTRIBUTES(d.mgrno)))AS "Result" FROM department dWHERE d.admrdept = ’A00’
produces the following result:DEPTNO ResultA00 <Mgr ID="000010"/>B01 <Mgr ID="000020"/>C01 <Mgr ID="000030"/>D01 <Mgr/>
v Produce an XML element named Emp for each employee, with nestedelements for the employee’s full name and the date the employee washired. The query
SELECT e.empno, XML2CLOB(XMLELEMENT(NAME "Emp",XMLELEMENT(NAME "name", e.firstnme || ’ ’ || e.lastname),XMLELEMENT(NAME "hiredate", e.hiredate)))AS "Result" FROM employee eWHERE e.edlevel = 12
produces the following result (formatted here for convenience; the outputXML has no extraneous whitespace characters):
EMPNO Result000290 <Emp>
<name>JOHN PARKER</name><hiredate>1980-05-30</hiredate></Emp>
000310 <Emp><name>MAUDE SETRIGHT</name><hiredate>1964-09-12</hiredate></Emp>
v Using the XMLATTRIBUTES function, along with the XML2CLOB andXMLELEMENT functions, construct the XML attributes. The query
XML functions
Chapter 2. Language elements 217
SELECT XML2CLOB(XMLELEMENT(NAME "Emp:Exempt",XMLATTRIBUTES(e.firstnme, e.lastname AS "name:last", e."midinit")))
AS "result"FROM employee eWHERE e.lastname=’GEYER’
produces the following result:<Emp:Exempt
FIRSTNME="JOHN"name:last="GEYER"MIDINIT="B"
/>
Method invocation
method-invocation:
�
subject-expression..method-name( )
,
expression
Both system-generated observer and mutator methods, as well as user-definedmethods are invoked using the double-dot operator.
subject-expressionAn expression with a static result type that is a user-defined structuredtype.
method-nameThe unqualified name of a method. The static type of subject-expression orone of its supertypes must include a method with the specified name.
(expression,...)The arguments of method-name are specified within parentheses. Emptyparentheses can be used to indicate that there are no arguments. Themethod-name and the data types of the specified argument expressions areused to resolve to the specific method, based on the static type ofsubject-expression.
The double-dot operator used for method invocation is a high precedence leftto right infix operator. For example, the following two expressions areequivalent:
a..b..c + x..y..z
and((a..b)..c) + ((x..y)..z)
XML functions
218 SQL Reference, Volume 1
If a method has no parameters other than its subject, it can be invoked withor without parentheses. For example, the following two expressions areequivalent:
point1..xpoint1..x()
Null subjects in method calls are handled as follows:v If a system-generated mutator method is invoked with a null subject, an
error results (SQLSTATE 2202D)v If any method other than a system-generated mutator is invoked with a
null subject, the method is not executed, and its result is null. This ruleincludes user-defined methods with SELF AS RESULT.
When a database object (a package, view, or trigger, for example) is created,the best fit method that exists for each of its method invocations is found.
Note: Methods of types defined WITH FUNCTION ACCESS can also beinvoked using the regular function notation. Function resolutionconsiders all functions, as well as methods with function access ascandidate functions. However, functions cannot be invoked usingmethod invocation. Method resolution considers all methods and doesnot consider functions as candidate methods. Failure to resolve to anappropriate function or method results in an error (SQLSTATE 42884).
Example:
v Use the double-dot operator to invoke a method called AREA. Assume theexistence of a table called RINGS, with a column CIRCLE_COL ofstructured type CIRCLE. Also, assume that the method AREA has beendefined previously for the CIRCLE type as AREA() RETURNS DOUBLE.
SELECT CIRCLE_COL..AREA() FROM RINGS
Subtype treatment
subtype-treatment:
TREAT ( expression AS data-type )
The subtype-treatment is used to cast a structured type expression into one ofits subtypes. The static type of expression must be a user-defined structuredtype, and that type must be the same type as, or a supertype of, data-type. Ifthe type name in data-type is unqualified, the SQL path is used to resolve thetype reference. The static type of the result of subtype-treatment is data-type,and the value of the subtype-treatment is the value of the expression. At runtime, if the dynamic type of the expression is not data-type or a subtype ofdata-type, an error is returned (SQLSTATE 0D000).
Method invocation
Chapter 2. Language elements 219
Example:
v If an application knows that all column object instances in a columnCIRCLE_COL have the dynamic type COLOREDCIRCLE, use the followingquery to invoke the method RGB on such objects. Assume the existence of atable called RINGS, with a column CIRCLE_COL of structured typeCIRCLE. Also, assume that COLOREDCIRCLE is a subtype of CIRCLE andthat the method RGB has been defined previously for COLOREDCIRCLE asRGB() RETURNS DOUBLE.
SELECT TREAT (CIRCLE_COL AS COLOREDCIRCLE)..RGB()FROM RINGS
At run time, if there are instances of dynamic type CIRCLE, an error israised (SQLSTATE 0D000). This error can be avoided by using the TYPEpredicate in a CASE expression, as follows:
SELECT (CASEWHEN CIRCLE_COL IS OF (COLOREDCIRCLE)THEN TREAT (CIRCLE_COL AS COLOREDCIRCLE)..RGB()ELSE NULL
END)FROM RINGS
Sequence reference
sequence-reference:
nextval-expressionprevval-expression
nextval-expression:
NEXTVAL FOR sequence-name
prevval-expression:
PREVVAL FOR sequence-name
NEXTVAL FOR sequence-nameA NEXTVAL expression generates and returns the next value for thesequence specified by sequence-name.
PREVVAL FOR sequence-nameA PREVVAL expression returns the most recently generated value for thespecified sequence for a previous statement within the current applicationprocess. This value can be referenced repeatedly by using PREVVALexpressions that specify the name of the sequence. There may be multipleinstances of PREVVAL expressions specifying the same sequence namewithin a single statement; they all return the same value.
Subtype treatment
220 SQL Reference, Volume 1
A PREVVAL expression can only be used if a NEXTVAL expressionspecifying the same sequence name has already been referenced in thecurrent application process, in either the current or a previous transaction(SQLSTATE 51035).
Notes:
v A new value is generated for a sequence when a NEXTVAL expressionspecifies the name of that sequence. However, if there are multiple instancesof a NEXTVAL expression specifying the same sequence name within aquery, the counter for the sequence is incremented only once for each rowof the result, and all instances of NEXTVAL return the same value for a rowof the result.
v The same sequence number can be used as a unique key value in twoseparate tables by referencing the sequence number with a NEXTVALexpression for the first row (this generates the sequence value), and aPREVVAL expression for the other rows (the instance of PREVVAL refers tothe sequence value most recently generated in the current session), asshown below:
INSERT INTO order(orderno, cutno)VALUES (NEXTVAL FOR order_seq, 123456);
INSERT INTO line_item (orderno, partno, quantity)VALUES (PREVVAL FOR order_seq, 987654, 1);
v NEXTVAL and PREVVAL expressions can be specified in the followingplaces:– select-statement or SELECT INTO statement (within the select-clause,
provided that the statement does not contain a DISTINCT keyword, aGROUP BY clause, an ORDER BY clause, a UNION keyword, anINTERSECT keyword, or EXCEPT keyword)
– INSERT statement (within a VALUES clause)– INSERT statement (within the select-clause of the fullselect)– UPDATE statement (within the SET clause (either a searched or a
positioned UPDATE statement), except that NEXTVAL cannot bespecified in the select-clause of the fullselect of an expression in the SETclause)
– SET Variable statement (except within the select-clause of the fullselect ofan expression; a NEXTVAL expression can be specified in a trigger, but aPREVVAL expression cannot)
– VALUES INTO statement (within the select-clause of the fullselect of anexpression)
– CREATE PROCEDURE statement (within the routine-body of an SQLprocedure)
– CREATE TRIGGER statement within the triggered-action (a NEXTVALexpression may be specified, but a PREVVAL expression cannot)
Sequence reference
Chapter 2. Language elements 221
v NEXTVAL and PREVVAL expressions cannot be specified (SQLSTATE428F9) in the following places:– join condition of a full outer join– DEFAULT value for a column in a CREATE or ALTER TABLE statement– generated column definition in a CREATE OR ALTER TABLE statement– summary table definition in a CREATE TABLE or ALTER TABLE
statement– condition of a CHECK constraint– CREATE TRIGGER statement (a NEXTVAL expression may be specified,
but a PREVVAL expression cannot)– CREATE VIEW statement– CREATE METHOD statement– CREATE FUNCTION statement
v In addition, a NEXTVAL expression cannot be specified (SQLSTATE 428F9)in the following places:– CASE expression– parameter list of an aggregate function– subquery in a context other than those explicitly allowed above– SELECT statement for which the outer SELECT contains a DISTINCT
operator– join condition of a join– SELECT statement for which the outer SELECT contains a GROUP BY
clause– SELECT statement for which the outer SELECT is combined with
another SELECT statement using the UNION, INTERSECT, or EXCEPTset operator
– nested table expression– parameter list of a table function– WHERE clause of the outer-most SELECT statement, or a DELETE or
UPDATE statement– ORDER BY clause of the outer-most SELECT statement– select-clause of the fullselect of an expression, in the SET clause of an
UPDATE statement– IF, WHILE, DO ... UNTIL, or CASE statement in an SQL routine
v When a value is generated for a sequence, that value is consumed, and thenext time that a value is requested, a new value will be generated. This istrue even when the statement containing the NEXTVAL expression fails oris rolled back.If an INSERT statement includes a NEXTVAL expression in the VALUES listfor the column, and if an error occurs at some point during the execution of
Sequence reference
222 SQL Reference, Volume 1
the INSERT (it could be a problem in generating the next sequence value,or a problem with the value for another column), then an insertion failureoccurs (SQLSTATE 23505), and the value generated for the sequence isconsidered to be consumed. In some cases, reissuing the same INSERTstatement might lead to success.For example, consider an error that is the result of the existence of a uniqueindex for the column for which NEXTVAL was used and the sequencevalue generated already exists in the index. It is possible that the next valuegenerated for the sequence is a value that does not exist in the index and sothe subsequent INSERT would succeed.
v If in generating a value for a sequence, the maximum value for thesequence is exceeded (or the minimum value for a descending sequence)and cycles are not permitted, then an error occurs (SQLSTATE 23522). Inthis case, the user could ALTER the sequence to extend the range ofacceptable values, or enable cycles for the sequence, or DROP and CREATEa new sequence with a different data type that has a larger range of values.For example, a sequence may have been defined with a data type ofSMALLINT, and eventually the sequence runs out of assignable values.DROP and re-create the sequence with the new definition to redefine thesequence as INTEGER.
v A reference to a NEXTVAL expression in the select statement of a cursorrefers to a value that is generated for a row of the result table. A sequencevalue is generated for a NEXTVAL expression for each row that is fetchedfrom the database. If blocking is done at the client, the values may havebeen generated at the server prior to the processing of the FETCHstatement. This can occur when there is blocking of the rows of the resulttable. If the client application does not explicitly FETCH all the rows thatthe database has materialized, then the application will not see the resultsof all the generated sequence values (for the materialized rows that werenot returned).
v A reference to a PREVVAL expression in the select statement of a cursorrefers to a value that was generated for the specified sequence prior to theopening of the cursor. However, closing the cursor can affect the valuesreturned by PREVVAL for the specified sequence in subsequent statements,or even for the same statement in the event that the cursor is reopened.This would be the case when the select statement of the cursor included areference to NEXTVAL for the same sequence name.
Examples:
Assume that there is a table called ″order″, and that a sequence called″order_seq″ is created as follows:
Sequence reference
Chapter 2. Language elements 223
CREATE SEQUENCE order_seqSTART WITH 1INCREMENT BY 1NO MAXVALUENO CYCLECACHE 24
Following are some examples of how to generate an ″order_seq″ sequencenumber with a NEXTVAL expression:
INSERT INTO order(orderno, custno)VALUES (NEXTVAL FOR order_seq, 123456);
orUPDATE order
SET orderno = NEXTVAL FOR order_seqWHERE custno = 123456;
orVALUES NEXTVAL FOR order_seq INTO :hv_seq;
Related reference:
v “Identifiers” on page 65v “TYPE predicate” on page 244v “CHAR” on page 303v “INTEGER” on page 384v “Fullselect” on page 595v “CREATE TABLE statement” in the SQL Reference, Volume 2
v “Methods” on page 178v “CREATE FUNCTION (SQL Scalar, Table or Row) statement” in the SQL
Reference, Volume 2
v “Casting between data types” on page 113v “Assignments and comparisons” on page 117v “Rules for result data types” on page 134v “Rules for string conversions” on page 139
Sequence reference
224 SQL Reference, Volume 1
Predicates
Predicates
A predicate specifies a condition that is true, false, or unknown about a givenrow or group.
The following rules apply to all types of predicates:v All values specified in a predicate must be compatible.v An expression used in a basic, quantified, IN, or BETWEEN predicate must
not result in a character string with a length attribute greater than 4 000, agraphic string with a length attribute greater than 2 000, or a LOB string ofany size.
v The value of a host variable can be null (that is, the variable may have anegative indicator variable).
v The code page conversion of operands of predicates involving two or moreoperands, with the exception of LIKE, is done according to the rules forstring conversions.
v Use of a DATALINK value is limited to the NULL predicate.v Use of a structured type value is limited to the NULL predicate and the
TYPE predicate.v In a Unicode database, all predicates that accept a character or graphic
string will accept any string type for which conversion is supported.
A fullselect is a form of the SELECT statement that, when used in a predicate,is also called a subquery.
Related reference:
v “Fullselect” on page 595v “Rules for string conversions” on page 139
Predicates
Chapter 2. Language elements 225
Search conditions
search-condition:
NOTpredicate
SELECTIVITY numeric-constant(search-condition)
�
� �
AND predicateOR NOT SELECTIVITY numeric-constant
(search-condition)
A search condition specifies a condition that is “true,” “false,” or “unknown”about a given row.
The result of a search condition is derived by application of the specifiedlogical operators (AND, OR, NOT) to the result of each specified predicate. Iflogical operators are not specified, the result of the search condition is theresult of the specified predicate.
AND and OR are defined in Table 14, in which P and Q are any predicates:
Table 14. Truth Tables 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, NOT(false) is true, and NOT(unknown) is unknown.
Search conditions within parentheses are evaluated first. If the order ofevaluation is not specified by parentheses, NOT is applied before AND, andAND is applied before OR. The order in which operators at the same
Search conditions
226 SQL Reference, Volume 1
precedence level are evaluated is undefined to allow for optimization ofsearch conditions.
SELECTIVITY valueThe SELECTIVITY clause is used to indicate to DB2 what the expectedselectivity percentage is for the predicate. SELECTIVITY can be specifiedonly when the predicate is a user-defined predicate.
A user-defined predicate is a predicate that consists of a user-definedfunction invocation, in the context of a predicate specification thatmatches the predicate specification on the PREDICATES clause ofCREATE FUNCTION. For example, if the function foo is defined withPREDICATES WHEN=1..., then the following use of SELECTIVITY isvalid:
SELECT *FROM STORESWHERE foo(parm,parm) = 1 SELECTIVITY 0.004
The selectivity value must be a numeric literal value in the inclusive rangefrom 0 to 1 (SQLSTATE 42615). If SELECTIVITY is not specified, thedefault value is 0.01 (that is, the user-defined predicate is expected tofilter out all but one percent of all the rows in the table). TheSELECTIVITY default can be changed for any given function by updatingits SELECTIVITY column in the SYSSTAT.FUNCTIONS view. An error willbe returned if the SELECTIVITY clause is specified for a non user-definedpredicate (SQLSTATE 428E5).
A user-defined function (UDF) can be applied as a user-defined predicateand, hence, is potentially applicable for index exploitation if:v the predicate specification is present in the CREATE FUNCTION
statement
1
1
32
2 or 3 2 or 3
MAJPROJ = 'MA2100' DEPTNO = 'D11' DEPTNO = 'B03' DEPTNO = 'E11'AND OR OR
MAJPROJ = 'MA2100' (DEPTNO = 'D11' DEPTNO = 'B03') DEPTNO = 'E11'AND OR OR
Figure 12. Search Conditions Evaluation Order
Search conditions
Chapter 2. Language elements 227
v the UDF is invoked in a WHERE clause being compared (syntactically)in the same way as specified in the predicate specification
v there is no negation (NOT operator)
Examples:
In the following query, the within UDF specification in the WHERE clausesatisfies all three conditions and is considered a user-defined predicate.
SELECT *FROM customersWHERE within(location, :sanJose) = 1 SELECTIVITY 0.2
However, the presence of within in the following query is notindex-exploitable due to negation and is not considered a user-definedpredicate.
SELECT *FROM customersWHERE NOT(within(location, :sanJose) = 1) SELECTIVITY 0.3
In the next example, consider identifying customers and stores that are withina certain distance of each other. The distance from one store to another iscomputed by the radius of the city in which the customers live.
SELECT *FROM customers, storesWHERE distance(customers.loc, stores.loc) <
CityRadius(stores.loc) SELECTIVITY 0.02
In the above query, the predicate in the WHERE clause is considered auser-defined predicate. The result produced by CityRadius is used as a searchargument to the range producer function.
However, since the result produced by CityRadius is used as a range producerfunction, the above user-defined predicate will not be able to make use of theindex extension defined on the stores.loc column. Therefore, the UDF willmake use of only the index defined on the customers.loc column.
Related reference:
v “CREATE FUNCTION (External Scalar) statement” in the SQL Reference,Volume 2
Search conditions
228 SQL Reference, Volume 1
Basic predicate
�� expression =(1)
<><>
(1)<=
(1)>=
expression ��
Notes:
1 The following forms of the comparison operators are also supported inbasic and quantified predicates: ^=, ^<, ^>, !=, !<, and !>. In code pages437, 819, and 850, the forms ¬=, ¬<, and ¬> are supported.
All of these product-specific forms of the comparison operators areintended only to support existing SQL that uses these operators, and arenot recommended for use when writing new SQL statements.
A basic predicate compares two values.
If the value of either operand is null, the result of the predicate is unknown.Otherwise the result is either true or false.
For values x and y:
Predicate Is True If and Only If...x = y x is equal to yx <> y x is not equal to yx < y x is less than yx > y x is greater than yx >= y x is greater than or equal to yx <= y x is less than or equal to y
Examples:EMPNO=’528671’SALARY < 20000PRSTAFF <> :VAR1SALARY > (SELECT AVG(SALARY) FROM EMPLOYEE)
Basic predicate
Chapter 2. Language elements 229
Quantified predicate
��
�
expression1 = SOME (fullselect1)(1) ANY
<> ALL<><=>=
,
( expression2 ) = SOME (fullselect2)ANY
��
Notes:
1 The following forms of the comparison operators are also supported inbasic and quantified predicates: ^=, ^<, ^>, !=, !<, and !>. In code pages437, 819, and 850, the forms ¬=, ¬<, and ¬> are supported.
All of these product-specific forms of the comparison operators areintended only to support existing SQL that uses these operators, and arenot recommended for use when writing new SQL statements.
A quantified predicate compares a value or values with a collection of values.
The fullselect must identify a number of columns that is the same as thenumber of expressions specified to the left of the predicate operator(SQLSTATE 428C4). The fullselect may return any number of rows.
When ALL is specified:v The result of the predicate is true if the fullselect returns no values or if the
specified relationship is true for every value returned by the fullselect.v The result is false if the specified relationship is false for at least one value
returned by the fullselect.v The result is unknown if the specified relationship is not false for any
values returned by the fullselect and at least one comparison is unknownbecause of the null value.
When SOME or ANY is specified:v The result of the predicate is true if the specified relationship is true for
each value of at least one row returned by the fullselect.v The result is false if the fullselect returns no rows or if the specified
relationship is false for at least one value of every row returned by thefullselect.
v The result is unknown if the specified relationship is not true for any of therows and at least one comparison is unknown because of a null value.
Quantified predicate
230 SQL Reference, Volume 1
Examples: Use the following tables when referring to the following examples.
Example 1SELECT COLA FROM TBLAB
WHERE COLA = ANY(SELECT COLX FROM TBLXY)
Results in 2,3. The subselect returns (2,3). COLA in rows 2 and 3 equals atleast one of these values.
Example 2SELECT COLA FROM TBLAB
WHERE COLA > ANY(SELECT COLX FROM TBLXY)
Results in 3,4. The subselect returns (2,3). COLA in rows 3 and 4 is greaterthan at least one of these values.
Example 3SELECT COLA FROM TBLAB
WHERE COLA > ALL(SELECT COLX FROM TBLXY)
Results in 4. The subselect returns (2,3). COLA in row 4 is the only one that isgreater than both these values.
Example 4SELECT COLA FROM TBLAB
WHERE COLA > ALL(SELECT COLX FROM TBLXYWHERE COLX<0)
Results in 1,2,3,4, null. The subselect returns no values. Thus, the predicate istrue for all rows in TBLAB.
Example 5SELECT * FROM TBLAB
WHERE (COLA,COLB+10) = SOME (SELECT COLX, COLY FROM TBLXY)
TBL :AB TBL :XYCOLX
23
COLY
2223
COLA
1234-
COLB
12121314-
Figure 13.
Quantified predicate
Chapter 2. Language elements 231
The subselect returns all entries from TBLXY. The predicate is true for thesubselect, hence the result is as follows:COLA COLB----------- -----------
2 123 13
Example 6SELECT * FROM TBLAB
WHERE (COLA,COLB) = ANY (SELECT COLX,COLY-10 FROM TBLXY)
The subselect returns COLX and COLY-10 from TBLXY. The predicate is truefor the subselect, hence the result is as follows:COLA COLB----------- -----------
2 123 13
Quantified predicate
232 SQL Reference, Volume 1
BETWEEN predicate
�� expressionNOT
BETWEEN expression AND expression ��
The BETWEEN predicate compares a value with a range of values.
The BETWEEN predicate:value1 BETWEEN value2 AND value3
is equivalent to the search condition:value1 >= value2 AND value1 <= value3
The BETWEEN predicate:value1 NOT BETWEEN value2 AND value3
is equivalent to the search condition:NOT(value1 BETWEEN value2 AND value3); that is,value1 < value2 OR value1 > value3.
The first operand (expression) cannot include a function that is variant or hasan external action (SQLSTATE 426804).
Given a mixture of datetime values and string representations of datetimevalues, all values are converted to the data type of the datetime operand.
Examples:
Example 1EMPLOYEE.SALARY BETWEEN 20000 AND 40000
Results in all salaries between $20,000.00 and $40,000.00.
Example 2SALARY NOT BETWEEN 20000 + :HV1 AND 40000
Assuming :HV1 is 5000, results in all salaries below $25,000.00 and above$40,000.00.
BETWEEN predicate
Chapter 2. Language elements 233
EXISTS predicate
�� EXISTS (fullselect) ��
The EXISTS predicate tests for the existence of certain rows.
The fullselect may specify any number of columns, andv The result is true only if the number of rows specified by the fullselect is
not zero.v The result is false only if the number of rows specified is zerov The result cannot be unknown.
Example:EXISTS (SELECT * FROM TEMPL WHERE SALARY < 10000)
EXISTS predicate
234 SQL Reference, Volume 1
IN predicate
��
�
�
expression1 IN (fullselect1)NOT ,
( expression2 )expression2
,
( expression3 ) IN (fullselect2)NOT
��
The IN predicate compares a value or values with a collection of values.
The fullselect must identify a number of columns that is the same as thenumber of expressions specified to the left of the IN keyword (SQLSTATE428C4). The fullselect may return any number of rows.v An IN predicate of the form:
expression IN expression
is equivalent to a basic predicate of the form:expression = expression
v An IN predicate of the form:expression IN (fullselect)
is equivalent to a quantified predicate of the form:expression = ANY (fullselect)
v An IN predicate of the form:expression NOT IN (fullselect)
is equivalent to a quantified predicate of the form:expression <> ALL (fullselect)
v An IN predicate of the form:expression IN (expressiona, expressionb, ..., expressionk)
is equivalent to:expression = ANY (fullselect)
where fullselect in the values-clause form is:VALUES (expressiona), (expressionb), ..., (expressionk)
v An IN predicate of the form:(expressiona, expressionb,..., expressionk) IN (fullselect)
is equivalent to a quantified predicate of the form:
IN predicate
Chapter 2. Language elements 235
(expressiona, expressionb,..., expressionk) = ANY (fullselect)
The values for expression1 and expression2 or the column of fullselect1 in the INpredicate must be compatible. Each expression3 value and its correspondingcolumn of fullselect2 in the IN predicate must be compatible. The rules forresult data types can be used to determine the attributes of the result used inthe comparison.
The values for the expressions in the IN predicate (including correspondingcolumns of a fullselect) can have different code pages. If a conversion isnecessary, the code page is determined by applying rules for stringconversions to the IN list first, and then to the predicate, using the derivedcode page for the IN list as the second operand.
Examples:
Example 1: The following evaluates to true if the value in the row underevaluation in the DEPTNO column contains D01, B01, or C01:
DEPTNO IN (’D01’, ’B01’, ’C01’)
Example 2: The following evaluates to true only if the EMPNO (employeenumber) on the left side matches the EMPNO of an employee in departmentE11:
EMPNO IN (SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT = ’E11’)
Example 3: Given the following information, this example evaluates to true ifthe specific value in the row of the COL_1 column matches any of the valuesin the list:
Table 15. IN Predicate example
Expressions Type Code Page
COL_1 column 850HV_2 host variable 437HV_3 host variable 437CON_1 constant 850
When evaluating the predicate:COL_1 IN (:HV_2, :HV_3, CON_4)
the two host variables will be converted to code page 850, based on the rulesfor string conversions.
IN predicate
236 SQL Reference, Volume 1
Example 4: The following evaluates to true if the specified year in EMENDATE(the date an employee activity on a project ended) matches any of the valuesspecified in the list (the current year or the two previous years):
YEAR(EMENDATE) IN (YEAR(CURRENT DATE),YEAR(CURRENT DATE - 1 YEAR),YEAR(CURRENT DATE - 2 YEARS))
Example 5: The following evaluates to true if both ID and DEPT on the leftside match MANAGER and DEPTNUMB respectively for any row of the ORGtable.
(ID, DEPT) IN (SELECT MANAGER, DEPTNUMB FROM ORG)
Related reference:
v “Rules for result data types” on page 134v “Rules for string conversions” on page 139
IN predicate
Chapter 2. Language elements 237
LIKE predicate
�� match-expressionNOT
LIKE pattern-expression �
�ESCAPE escape-expression
��
The LIKE predicate searches for strings that have a certain pattern. Thepattern is specified by a string in which the underscore and the percent signmay have special meanings. Trailing blanks in a pattern are part of thepattern.
If the value of any of the arguments is null, the result of the LIKE predicate isunknown.
The values for match-expression, pattern-expression, and escape-expression arecompatible string expressions. There are slight differences in the types ofstring expressions supported for each of the arguments. The valid types ofexpressions are listed under the description of each argument.
None of the expressions can yield a distinct type. However, it can be afunction that casts a distinct type to its source type.
match-expressionAn expression that specifies the string that is to be examined to see if itconforms to a certain pattern of characters.
The expression can be specified by:v A constantv A special registerv A host variable (including a locator variable or a file reference variable)v A scalar functionv A large object locatorv A column namev An expression concatenating any of the above
pattern-expressionAn expression that specifies the string that is to be matched.
The expression can be specified by:v A constantv A special registerv A host variablev A scalar function whose operands are any of the above
LIKE predicate
238 SQL Reference, Volume 1
v An expression concatenating any of the above
with the following restrictions:v No element in the expression can be of type LONG VARCHAR, CLOB,
LONG VARGRAPHIC, or DBCLOB. In addition it cannot be a BLOBfile reference variable.
v The actual length of pattern-expression cannot be more than 32 672 bytes.
A simple description of the use of the LIKE pattern is that the pattern isused 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 itself.
If the pattern-expression needs to include either the underscore or thepercent character, the escape-expression is used to specify a character toprecede either the underscore or the percent character in the pattern.
A rigorous description of the use of the LIKE pattern follows. Note thatthis description ignores the use of the escape-expression; its use is coveredlater.v 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 theminimum number of substring specifiers so each character of p is partof exactly one substring specifier. A substring specifier is an underscore,a percent sign, or any non-empty sequence of characters other than anunderscore 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 pare both empty strings or there exists a partitioning of m into substringssuch that:– A substring of m is a sequence of zero or more contiguous characters
and each character of m is part of exactly one substring.– If the nth substring specifier is an underscore, the nth substring of m
is any single character.– If the nth substring specifier is a percent sign, the nth substring of m
is any sequence of zero or more characters.– If the nth substring specifier is neither an underscore nor a percent
sign, the nth substring of m is equal to that substring specifier andhas the same length as that substring specifier.
– The number of substrings of m is the same as the number ofsubstring specifiers.
LIKE predicate
Chapter 2. Language elements 239
Thus, if p is an empty string and m is not an empty string, the result isfalse. Similarly, it follows that if m is an empty string and p is not anempty string (except for a string containing only percent signs), theresult is false.
The predicate m NOT LIKE p is equivalent to the search condition NOT(m LIKE p).
When the escape-expression is specified, the pattern-expression must notcontain the escape character identified by the escape-expression exceptwhen immediately followed by the escape character, the underscorecharacter or the percent sign character (SQLSTATE 22025).
If the match-expression is a character string in an MBCS database then itcan contain mixed data. In this case, the pattern can include both SBCSand MBCS characters. The special characters in the pattern are interpretedas follows:v An SBCS underscore refers to one SBCS character.v A DBCS underscore refers to one MBCS character.v A percent (either SBCS or DBCS) refers to a string of zero or more SBCS
or MBCS characters.
escape-expressionThis optional argument is an expression that specifies a character to beused to modify the special meaning of the underscore (_) and percent (%)characters in the pattern-expression. This allows the LIKE predicate to beused to match values that contain the actual percent and underscorecharacters.
The expression can be specified by any one of:v a constantv a special registerv a host variablev a scalar function whose operands are any of the abovev an expression concatenating any of the above
with the restrictions that:v No element in the expression can be of type LONG VARCHAR, CLOB,
LONG VARGRAPHIC or DBCLOB. In addition, it cannot be a BLOBfile reference variable.
v The result of the expression must be one SBCS or DBCS character or abinary string containing exactly 1 byte (SQLSTATE 22019).
LIKE predicate
240 SQL Reference, Volume 1
When escape characters are present in the pattern string, an underscore,percent sign, or escape character can represent a literal occurrence of itself.This is true if the character in question is preceded by an odd number ofsuccessive escape characters. It is not true otherwise.
In a pattern, a sequence of successive escape characters is treated asfollows:v Let S be such a sequence, and suppose that S is not part of a larger
sequence of successive escape characters. Suppose also that S contains atotal of n characters. Then the rules governing S depend on the value ofn:– If n is odd, S must be followed by an underscore or percent sign
(SQLSTATE 22025). S and the character that follows it represent(n-1)/2 literal occurrences of the escape character followed by aliteral occurrence of the underscore or percent sign.
– If n is even, S represents n/2 literal occurrences of the escapecharacter. Unlike the case where n is odd, S could end the pattern. Ifit does not end the pattern, it can be followed by any character(except, of course, an escape character, which would violate theassumption that S is not part of a larger sequence of successiveescape characters). If S is followed by an underscore or percent sign,that character has its special meaning.
Following is a illustration of the effect of successive occurrences of theescape character (which, in this case, is the back slash (\) ).
Pattern string Actual Pattern
\% A percent sign
\\% A back slash followed by zero or more arbitrary characters
\\\% A back slash followed by a percent sign
The code page used in the comparison is based on the code page of thematch-expression value.v The match-expression value is never converted.v If the code page of pattern-expression is different from the code page of
match-expression, the value of pattern-expression is converted to the code pageof match-expression, unless either operand is defined as FOR BIT DATA (inwhich case there is no conversion).
v If the code page of escape-expression is different from the code page ofmatch-expression, the value of escape-expression is converted to the code pageof match-expression, unless either operand is defined as FOR BIT DATA (inwhich case there is no conversion).
LIKE predicate
Chapter 2. Language elements 241
Notes:
v The number of trailing blanks is significant in both the match-expression andthe pattern-expression. If the strings are not the same length, the shorterstring is not padded with blank spaces. For example, the expression’PADDED ’ LIKE ’PADDED’ would not result in a match.
v If the pattern specified in a LIKE predicate is a parameter marker, and afixed-length character host variable is used to replace the parameter marker,the value specified for the host variable must have the correct length. If thecorrect length is not specified, the select operation will not return theintended results.For example, if the host variable is defined as CHAR(10), and the valueWYSE% is assigned to that host variable, the host variable is padded withblanks on assignment. The pattern used is:’WYSE% ’
The database manager searches for all values that start with WYSE and thatend with five blank spaces. If you want to search only for values that startwith ’WYSE’, assign a value of ’WSYE%%%%%%’ to the host variable.
Examples:
v Search for the string ’SYSTEMS’ appearing anywhere within thePROJNAME column in the PROJECT table.SELECT PROJNAME FROM PROJECTWHERE PROJECT.PROJNAME LIKE ’%SYSTEMS%’
v Search for a string with a first character of ’J’ that is exactly two characterslong in the FIRSTNME column of the EMPLOYEE table.SELECT FIRSTNME FROM EMPLOYEEWHERE EMPLOYEE.FIRSTNME LIKE ’J_’
v Search for a string of any length, with a first character of ’J’, in theFIRSTNME column of the EMPLOYEE table.
SELECT FIRSTNME FROM EMPLOYEEWHERE EMPLOYEE.FIRSTNME LIKE ’J%’
v In the CORP_SERVERS table, search for a string in the LA_SERVERScolumn that matches the value in the CURRENT SERVER special register.
SELECT LA_SERVERS FROM CORP_SERVERSWHERE CORP_SERVERS.LA_SERVERS LIKE CURRENT SERVER
v Retrieve all strings that begin with the character sequence ’%_\’ in columnA of table T.
SELECT A FROM TWHERE T.A LIKE ’\%\_\\%’ ESCAPE ’\’
v Use the BLOB scalar function to obtain a one-byte escape character that iscompatible with the match and pattern data types (both BLOBs).
SELECT COLBLOB FROM TABLETWHERE COLBLOB LIKE :pattern_var ESCAPE BLOB(X’OE’)
LIKE predicate
242 SQL Reference, Volume 1
NULL predicate
�� expression ISNOT
NULL ��
The NULL predicate tests for null values.
The result of a NULL predicate cannot be unknown. If the value of theexpression is null, the result is true. If the value is not null, the result is false.If NOT is specified, the result is reversed.
Examples:PHONENO IS NULL
SALARY IS NOT NULL
NULL predicate
Chapter 2. Language elements 243
TYPE predicate
�� expression IS OFNOT
ISOF DYNAMIC TYPE
NOT
�
,
( typename )ONLY
��
A TYPE predicate compares the type of an expression with one or moreuser-defined structured types.
The dynamic type of an expression involving the dereferencing of a referencetype is the actual type of the referenced row from the target typed table orview. This may differ from the target type of an expression involving thereference which is called the static type of the expression.
If the value of expression is null, the result of the predicate is unknown. Theresult of the predicate is true if the dynamic type of the expression is a subtypeof one of the structured types specified by typename, otherwise the result isfalse. If ONLY precedes any typename the proper subtypes of that type are notconsidered.
If typename is not qualified, it is resolved using the SQL path. Each typenamemust identify a user-defined type that is in the type hierarchy of the statictype of expression (SQLSTATE 428DU).
The DEREF function should be used whenever the TYPE predicate has anexpression involving a reference type value. The static type for this form ofexpression is the target type of the reference.
The syntax IS OF and OF DYNAMIC TYPE are equivalent alternatives for theTYPE predicate. Similarly, IS NOT OF and NOT OF DYNAMIC TYPE areequivalent alternatives.
Examples:
A table hierarchy exists with root table EMPLOYEE of type EMP and subtableMANAGER of type MGR. Another table, ACTIVITIES, includes a columncalled WHO_RESPONSIBLE that is defined as REF(EMP) SCOPE EMPLOYEE.The following is a type predicate that evaluates to true when a rowcorresponding to WHO_RESPONSIBLE is a manager:
DEREF (WHO_RESPONSIBLE) IS OF (MGR)
TYPE predicate
244 SQL Reference, Volume 1
If a table contains a column EMPLOYEE of type EMP, EMPLOYEE maycontain values of type EMP as well as values of its subtypes like MGR. Thefollowing predicate
EMPL IS OF (MGR)
returns true when EMPL is not null and is actually a manager.
Related reference:
v “DEREF” on page 335
TYPE predicate
Chapter 2. Language elements 245
TYPE predicate
246 SQL Reference, Volume 1
Chapter 3. Functions
Functions overview
A function is an operation that is denoted by a function name followed by apair of parentheses enclosing the specification of arguments (there may be noarguments).
Built-in functions are provided with the database manager; they return a singleresult value, and are identified as part of the SYSIBM schema. Built-infunctions include column functions (such as AVG), operator functions (such as“+”), casting functions (such as DECIMAL), and others (such as SUBSTR).
User-defined functions are registered to a database in SYSCAT.ROUTINES(using the CREATE FUNCTION statement). User-defined functions are neverpart of the SYSIBM schema. One such set of functions is provided with thedatabase manager in a schema called SYSFUN, and another in a schemacalled SYSPROC.
Functions are classified as aggregate (column) functions, scalar functions, rowfunctions, or table functions.v The argument of an column function is a collection of like values. A column
function returns a single value (possibly null), and can be specified in anSQL statement wherever an expression can be used.
v The arguments of a scalar function are individual scalar values, which can beof different types and have different meanings. A scalar function returns asingle value (possibly null), and can be specified in an SQL statementwherever an expression can be used.
v The argument of a row function is a structured type. A row function returnsa row of built-in data types and can only be specified as a transformfunction for a structured type.
v The arguments of a table function are individual scalar values, which can beof different types and have different meanings. A table function returns atable to the SQL statement, and can be specified only within the FROMclause of a SELECT statement.
The function name, combined with the schema, gives the fully qualified nameof a function. The combination of schema, function name, and inputparameters make up a function signature.
© Copyright IBM Corp. 1993 - 2002 247
In some cases, the input parameter type is specified as a specific built-in datatype, and in other cases, it is specified through a general variable likeany-numeric-type. If a particular data type is specified, an exact match will onlyoccur with the specified data type. If a general variable is used, each of thedata types associated with that variable results in an exact match.
Additional functions may be available, because user-defined functions can becreated in different schemas, using one of the function signatures as a source.You can also create external functions in your applications.
Related concepts:
v “Aggregate functions” on page 269
Related reference:
v “Functions” on page 168v “Subselect” on page 554v “CREATE FUNCTION statement” in the SQL Reference, Volume 2
Functions overview
248 SQL Reference, Volume 1
The following table summarizes information about the supported functions.The function name, combined with the schema, gives the fully qualified nameof a function. The “Input parameters” column shows the expected data typefor each argument during function invocation. Many of the functions includevariations of the input parameters, allowing either different data types ordifferent numbers of arguments to be used. The combination of schema,function name and input parameters makes up a function signature. The“Returns” column shows the possible data types of values returned by thefunction.
Table 16. Supported functions
Function name Schema Description
Input parameters Returns
ABS or ABSVALSYSIBM Returns the absolute value of the argument.
Any expression that returns a built-in numeric data type. Same data type and lengthas the argument
ABS or ABSVAL
SYSFUN Returns the absolute value of the argument.
SMALLINT SMALLINT
INTEGER INTEGER
BIGINT BIGINT
DOUBLE DOUBLE
ACOSSYSFUN Returns the arccosine of the argument as an angle expressed in
radians.
DOUBLE DOUBLE
ASCII
SYSFUN Returns the ASCII code value of the leftmost character of the argumentas an integer.
CHAR INTEGER
VARCHAR(4000) INTEGER
CLOB(1M) INTEGER
ASINSYSFUN Returns the arcsine of the argument as an angle, expressed in radians.
DOUBLE DOUBLE
ATANSYSFUN Returns the arctangent of the argument as an angle, expressed in
radians.
DOUBLE DOUBLE
ATAN2SYSFUN Returns the arctangent of x and y coordinates, specified by the first and
second arguments respectively, as an angle, expressed in radians.
DOUBLE, DOUBLE DOUBLE
ATANHSYSIBM Returns the hyperbolic arctangent of the argument, where the
argument is an angle expressed in radians.
DOUBLE DOUBLE
AVGSYSIBM Returns the average of a set of numbers (column function).
numeric-type 4 numeric-type 1
Functions overview
Chapter 3. Functions 249
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
BIGINT
SYSIBM Returns a 64 bit integer representation of a number or character stringin the form of an integer constant.
numeric-type BIGINT
VARCHAR BIGINT
BLOB
SYSIBM Casts from source type to BLOB, with optional length.
string-type BLOB
string-type, INTEGER BLOB
CEIL or CEILING
SYSFUN Returns the smallest integer greater than or equal to the argument.
SMALLINT SMALLINT
INTEGER INTEGER
BIGINT BIGINT
DOUBLE DOUBLE
CHAR
SYSIBM Returns a string representation of the source type.
character-type CHAR
character-type, INTEGER CHAR(integer)
datetime-type CHAR
datetime-type, keyword 2 CHAR
SMALLINT CHAR(6)
INTEGER CHAR(11)
BIGINT CHAR(20)
DECIMAL CHAR(2+precision)
DECIMAL, VARCHAR CHAR(2+precision)
CHARSYSFUN Returns a character string representation of a floating-point number.
DOUBLE CHAR(24)
CHR
SYSFUN Returns the character that has the ASCII code value specified by theargument. The value of the argument should be between 0 and 255;otherwise, the return value is null.
INTEGER CHAR(1)
CLOB SYSIBM Casts from source type to CLOB, with optional length.
character-type CLOB
character-type, INTEGER CLOB
COALESCE 3SYSIBM Returns the first non-null argument in the set of arguments.
any-type, any-union-compatible-type, ... any-type
CONCAT or ||SYSIBM Returns the concatenation of 2 string arguments.
string-type, compatible-string-type max string-type
Functions overview
250 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
CORRELATION or CORRSYSIBM Returns the coefficient of correlation of a set of number pairs.
numeric-type, numeric-type DOUBLE
COSSYSFUN Returns the cosine of the argument, where the argument is an angle
expressed in radians.
DOUBLE DOUBLE
COSHSYSIBM Returns the hyperbolic cosine of the argument, where the argument is
an angle expressed in radians.
DOUBLE DOUBLE
COTSYSFUN Returns the cotangent of the argument, where the argument is an angle
expressed in radians.
DOUBLE DOUBLE
COUNTSYSIBM Returns the count of the number of rows in a set of rows or values
(column function).
any-builtin-type 4 INTEGER
COUNT_BIG
SYSIBM Returns the number of rows or values in a set of rows or values(column function). Result can be greater than the maximum value ofinteger.
any-builtin-type 4 DECIMAL(31,0)
COVARIANCE or COVARSYSIBM Returns the covariance of a set of number pairs.
numeric-type, numeric-type DOUBLE
DATE
SYSIBM Returns a date from a single input value.
DATE DATE
TIMESTAMP DATE
DOUBLE DATE
VARCHAR DATE
DAY
SYSIBM Returns the day part of a value.
VARCHAR INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
DAYNAME
SYSFUN Returns a mixed case character string containing the name of the day(for example, Friday) for the day portion of the argument based onwhat the locale was when db2start was issued.
VARCHAR(26) VARCHAR(100)
DATE VARCHAR(100)
TIMESTAMP VARCHAR(100)
Functions overview
Chapter 3. Functions 251
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
DAYOFWEEK
SYSFUN Returns the day of the week in the argument as an integer value in therange 1-7, where 1 represents Sunday.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DAYOFWEEK_ISO
SYSFUN Returns the day of the week in the argument as an integer value in therange 1-7, where 1 represents Monday.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DAYOFYEAR
SYSFUN Returns the day of the year in the argument as an integer value in therange 1-366.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DAYS
SYSIBM Returns an integer representation of a date.
VARCHAR INTEGER
TIMESTAMP INTEGER
DATE INTEGER
DBCLOB
SYSIBM Casts from source type to DBCLOB, with optional length.
graphic-type DBCLOB
graphic-type, INTEGER DBCLOB
DBPARTITIONNUM 3
SYSIBM Returns the database partition number of the row. The argument is acolumn name within a table.
any-type INTEGER
DECIMAL or DEC
SYSIBM Returns decimal representation of a number, with optional precisionand scale.
numeric-type DECIMAL
numeric-type, INTEGER DECIMAL
numeric-type INTEGER, INTEGER DECIMAL
DECIMAL or DEC
SYSIBM Returns decimal representation of a character string, with optionalprecision, scale, and decimal-character.
VARCHAR DECIMAL
VARCHAR, INTEGER DECIMAL
VARCHAR, INTEGER, INTEGER DECIMAL
VARCHAR, INTEGER, INTEGER, VARCHAR DECIMAL
Functions overview
252 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
DECRYPT_BIN
SYSIBM Returns a value that is the result of decrypting encrypted data using apassword string.
VARCHAR FOR BIT DATA VARCHAR FOR BIT DATA
VARCHAR FOR BIT DATA, VARCHAR VARCHAR FOR BIT DATA
DECRYPT_CHAR
SYSIBM Returns a value that is the result of decrypting encrypted data using apassword string.
VARCHAR FOR BIT DATA VARCHAR
VARCHAR FOR BIT DATA, VARCHAR VARCHAR
DEGREESSYSFUN Returns the number of degrees converted from the argument in
expressed in radians.
DOUBLE DOUBLE
DEREFSYSIBM Returns an instance of the target type of the reference type argument.
REF(any-structured-type) with defined scope any-structured-type (same asinput target type)
DIFFERENCE
SYSFUN Returns the difference between the sounds of the words in the twoargument strings as determined using the SOUNDEX function. A valueof 4 means the strings sound the same.
VARCHAR(4000), VARCHAR(4000) INTEGER
DIGITSSYSIBM Returns the character string representation of a number.
DECIMAL CHAR
DLCOMMENTSYSIBM Returns the comment attribute of a datalink value.
DATALINK VARCHAR(254)
DLLINKTYPESYSIBM Returns the link type attribute of a datalink value.
DATALINK VARCHAR(4)
DLNEWCOPYSYSIBM Returns a DATALINK value which has an attribute indicating that the
referenced file has changed.
DATALINK VARCHAR(254)
DLPREVIOUSCOPYSYSIBM Returns a DATALINK value which has an attribute indicating that the
previous version of the file should be restored.
DATALINK VARCHAR(254)
DLREPLACECONTENT
SYSIBM Returns a DATALINK value. When the function is on the right handside of a SET clause in an UPDATE statement, or is in a VALUESclause in an INSERT statement, the assignment of the returned valueresults in replacing the content of a file by another file and thencreating a link to it.
DATALINK VARCHAR(254)
DLURLCOMPLETESYSIBM Returns the complete URL (including access token) from a DATALINK
value.
DATALINK VARCHAR
Functions overview
Chapter 3. Functions 253
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
DLURLCOMPLETEONLYSYSIBM Returns the data location attribute from a DATALINK value with a
link type of URL.
DATALINK VARCHAR(254)
DLURLCOMPLETEWRITESYSIBM Returns the complete URL value from a DATALINK value with a link
type of URL.
DATALINK VARCHAR(254)
DLURLPATHSYSIBM Returns the path and file name (including access token) of a datalink
value.
DATALINK VARCHAR
DLURLPATHONLYSYSIBM Returns the path and file name (without any access token) of a
datalink value.
DATALINK VARCHAR
DLURLPATHWRITESYSIBM Returns the path and file name necessary to access a file within a given
server from a DATALINK value with a linktype of URL.
DATALINK VARCHAR(254)
DLURLSCHEMESYSIBM Returns the scheme from the URL attribute of a datalink value.
DATALINK VARCHAR
DLURLSERVERSYSIBM Returns the server from the URL attribute of a datalink value.
DATALINK VARCHAR
DLVALUE
SYSIBM Builds a datalink value from a data-location argument, link typeargument and optional comment-string argument.
VARCHAR DATALINK
VARCHAR, VARCHAR DATALINK
VARCHAR, VARCHAR, VARCHAR DATALINK
DOUBLE orDOUBLE_PRECISION
SYSIBM Returns the floating-point representation of a number.
numeric-type DOUBLE
DOUBLE
SYSFUN Returns the floating-point number corresponding to the characterstring representation of a number. Leading and trailing blanks inargument are ignored.
VARCHAR DOUBLE
ENCRYPT
SYSIBM Returns a value that is the result of encrypting a data stringexpression.
VARCHAR VARCHAR FOR BIT DATA
VARCHAR, VARCHAR VARCHAR FOR BIT DATA
VARCHAR, VARCHAR, VARCHAR VARCHAR FOR BIT DATA
EVENT_MON_STATESYSIBM Returns the operational state of particular event monitor.
VARCHAR INTEGER
Functions overview
254 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
EXPSYSFUN Returns the exponential function of the argument.
DOUBLE DOUBLE
FLOAT SYSIBM Same as DOUBLE.
FLOOR
SYSFUN Returns the largest integer less than or equal to the argument.
SMALLINT SMALLINT
INTEGER INTEGER
BIGINT BIGINT
DOUBLE DOUBLE
GETHINTSYSIBM Returns the password hint if one is found.
VARCHAR or CLOB VARCHAR
GENERATE_UNIQUESYSIBM Returns a bit data character string that is unique compared to any
other execution of the same function.
no argument CHAR(13) FOR BIT DATA
GET_ROUTINE_SAR
SYSFUN Returns the information necessary to install an identical routine onanother database server running at the same level and operatingsystem.
BLOB(3M), CHAR(2), VARCHAR(257) BLOB(3M)
GRAPHIC
SYSIBM Cast from source type to GRAPHIC, with optional length.
graphic-type GRAPHIC
graphic-type, INTEGER GRAPHIC
GROUPING
SYSIBM Used with grouping-sets and super-groups to indicate sub-total rowsgenerated by a grouping set (column function). The value returned is:
1 The value of the argument in the returned row is a nullvalue and the row was generated for a grouping set. Thisgenerated row provides a sub-total for a grouping set.
0 otherwise.
any-type SMALLINT
HASHEDVALUE 3
SYSIBM Returns the partitioning map index (0 to 4095) of the row. Theargument is a column name within a table.
any-type INTEGER
HEXSYSIBM Returns the hexadecimal representation of a value.
any-builtin-type VARCHAR
HOUR
SYSIBM Returns the hour part of a value.
VARCHAR INTEGER
TIME INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
Functions overview
Chapter 3. Functions 255
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
IDENTITY_VAL_LOCALSYSIBM Returns the most recently assigned value for an identity column.
DECIMAL
INSERT
SYSFUN Returns a string where argument3 bytes have been deleted fromargument1 beginning at argument2 and where argument4 has beeninserted into argument1 beginning at argument2.
VARCHAR(4000), INTEGER, INTEGER, VARCHAR(4000) VARCHAR(4000)
CLOB(1M), INTEGER, INTEGER, CLOB(1M) CLOB(1M)
BLOB(1M), INTEGER, INTEGER, BLOB(1M) BLOB(1M)
INTEGER or INT
SYSIBM Returns the integer representation of a number.
numeric-type INTEGER
VARCHAR INTEGER
JULIAN_DAY
SYSFUN Returns an integer value representing the number of days fromJanuary 1, 4712 B.C. (the start of the Julian date calendar) to the datevalue specified in the argument.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
LCASE or LOWER
SYSIBM Returns a string in which all the characters have been converted tolower case characters.
CHAR CHAR
VARCHAR VARCHAR
LCASE
SYSFUN Returns a string in which all the characters have been converted tolower case characters. LCASE will only handle characters in theinvariant set. Therefore, LCASE(UCASE(string)) will not necessarilyreturn the same result as LCASE(string).
VARCHAR(4000) VARCHAR(4000)
CLOB(1M) CLOB(1M)
LEFT
SYSFUN Returns a string consisting of the leftmost argument2 bytes inargument1.
VARCHAR(4000), INTEGER VARCHAR(4000)
CLOB(1M), INTEGER CLOB(1M)
BLOB(1M), INTEGER BLOB(1M)
LENGTHSYSIBM Returns the length of the operand in bytes (except for double byte
string types which return the length in characters).
any-builtin-type INTEGER
LNSYSFUN Returns the natural logarithm of the argument (same as LOG).
DOUBLE DOUBLE
Functions overview
256 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
LOCATE
SYSFUN Returns the starting position of the first occurrence of argument1 withinargument2. If the optional third argument is specified, it indicates thecharacter position in argument2 at which the search is to begin. Ifargument1 is not found within argument2, the value 0 is returned.
VARCHAR(4000), VARCHAR(4000) INTEGER
VARCHAR(4000), VARCHAR(4000), INTEGER INTEGER
CLOB(1M), CLOB(1M) INTEGER
CLOB(1M), CLOB(1M), INTEGER INTEGER
BLOB(1M), BLOB(1M) INTEGER
BLOB(1M), BLOB(1M), INTEGER INTEGER
LOGSYSFUN Returns the natural logarithm of the argument (same as LN).
DOUBLE DOUBLE
LOG10SYSFUN Returns the base 10 logarithm of the argument.
DOUBLE DOUBLE
LONG_VARCHARSYSIBM Returns a long string.
character-type LONG VARCHAR
LONG_VARGRAPHICSYSIBM Casts from source type to LONG_VARGRAPHIC.
graphic-type LONG VARGRAPHIC
LTRIM
SYSIBM Returns the characters of the argument with leading blanks removed.
CHAR VARCHAR
VARCHAR VARCHAR
GRAPHIC VARGRAPHIC
VARGRAPHIC VARGRAPHIC
LTRIM
SYSFUN Returns the characters of the argument with leading blanks removed.
VARCHAR(4000) VARCHAR(4000)
CLOB(1M) CLOB(1M)
MAXSYSIBM Returns the maximum value in a set of values (column function).
any-builtin-type 5 same as input type
MICROSECOND
SYSIBM Returns the microsecond (time-unit) part of a value.
VARCHAR INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
Functions overview
Chapter 3. Functions 257
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
MIDNIGHT_SECONDS
SYSFUN Returns an integer value in the range 0 to 86 400 representing thenumber of seconds between midnight and time value specified in theargument.
VARCHAR(26) INTEGER
TIME INTEGER
TIMESTAMP INTEGER
MINSYSIBM Returns the minimum value in a set of values (column function).
any-builtin-type 5 same as input type
MINUTE
SYSIBM Returns the minute part of a value.
VARCHAR INTEGER
TIME INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
MOD
SYSFUN Returns the remainder ( modulus) of argument1 divided by argument2.The result is negative only if argument1 is negative.
SMALLINT, SMALLINT SMALLINT
INTEGER, INTEGER INTEGER
BIGINT, BIGINT BIGINT
MONTH
SYSIBM Returns the month part of a value.
VARCHAR INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
MONTHNAME
SYSFUN Returns a mixed case character string containing the name of month(for example, January) for the month portion of the argument that is adate or timestamp, based on what the locale was when the databasewas started.
VARCHAR(26) VARCHAR(100)
DATE VARCHAR(100)
TIMESTAMP VARCHAR(100)
MQPUBLISHMQDB2 Publishes data to an MQSeries location.
VARCHAR(4000) INTEGER
MQREADMQDB2 Returns a message from an MQSeries location.
string-type VARCHAR(4000)
MQREADALL
MQDB2 Returns a table with messages and message metadata from anMQSeries location.
See “MQREADALL” on page 495.
Functions overview
258 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
MQRECEIVEMQDB2 Returns a message from an MQSeries location and removes the
message from the associated queue.
string-type VARCHAR(4000)
MQRECEIVEALL
MQDB2 Returns a table containing the messages and message metadata froman MQSeries location and removes the messages from the associatedqueue.
See “MQRECEIVEALL” on page 499
MQSENDMQDB2 Sends data to an MQSeries location.
VARCHAR(4000) INTEGER
MQSUBSCRIBEMQDB2 Subscribes to MQSeries messages published on a specific topic.
string-type INTEGER
MQUNSUBSCRIBEMQDB2 Unsubscribes to MQSeries messages published on a specific topic.
string-type INTEGER
MULTIPLY_ALT
SYSIBM Returns the product of two arguments as a decimal value. Thisfunction is useful when the sum of the argument precisions is greaterthan 31.
exact-numeric-type, exact-numeric-type DECIMAL
NULLIF 3
SYSIBM Returns NULL if the arguments are equal, else returns the firstargument.
any-type 5, any-comparable-type5 any-type
POSSTRSYSIBM Returns the position at which one string is contained in another.
string-type, compatible-string-type INTEGER
POWER
SYSFUN Returns the value of argument1 to the power of argument2.
INTEGER, INTEGER INTEGER
BIGINT, BIGINT BIGINT
DOUBLE, INTEGER DOUBLE
DOUBLE, DOUBLE DOUBLE
PUT_ROUTINE_SAR
SYSFUN Passes the information necessary to create and define an SQL routineat the database server.
BLOB(3M)
BLOB(3M), VARCHAR(128), INTEGER
QUARTER
SYSFUN Returns an integer value in the range 1 to 4 representing the quarter ofthe year for the date specified in the argument.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
Functions overview
Chapter 3. Functions 259
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
RADIANSSYSFUN Returns the number of radians converted from argument which is
expressed in degrees.
DOUBLE DOUBLE
RAISE_ERROR3
SYSIBM Raises an error in the SQLCA. The sqlstate returned is indicated byargument1. The second argument contains any text to be returned.
VARCHAR, VARCHAR any-type 6
RAND
SYSFUN Returns a random floating point value between 0 and 1 using theargument as the optional seed value.
no argument required DOUBLE
INTEGER DOUBLE
REALSYSIBM Returns the single-precision floating-point representation of a number.
numeric-type REAL
REC2XMLSYSIBM Returns a string formatted with XML tags and containing column
names and column data.
DECIMAL, VARCHAR, VARCHAR, any-type7 VARCHAR
REGR_AVGXSYSIBM Returns quantities used to compute diagnostic statistics.
numeric-type, numeric-type DOUBLE
REGR_AVGYSYSIBM Returns quantities used to compute diagnostic statistics.
numeric-type, numeric-type DOUBLE
REGR_COUNTSYSIBM Returns the number of non-null number pairs used to fit the regression
line.
numeric-type, numeric-type INTEGER
REGR_INTERCEPT orREGR_ICPT
SYSIBM Returns the y-intercept of the regression line.
numeric-type, numeric-type DOUBLE
REGR_R2SYSIBM Returns the coefficient of determination for the regression.
numeric-type, numeric-type DOUBLE
REGR_SLOPESYSIBM Returns the slope of the line.
numeric-type, numeric-type DOUBLE
REGR_SXXSYSIBM Returns quantities used to compute diagnostic statistics.
numeric-type, numeric-type DOUBLE
REGR_SXYSYSIBM Returns quantities used to compute diagnostic statistics.
numeric-type, numeric-type DOUBLE
REGR_SYYSYSIBM Returns quantities used to compute diagnostic statistics.
numeric-type, numeric-type DOUBLE
Functions overview
260 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
REPEAT
SYSFUN Returns a character string composed of argument1 repeated argument2times.
VARCHAR(4000), INTEGER VARCHAR(4000)
CLOB(1M), INTEGER CLOB(1M)
BLOB(1M), INTEGER BLOB(1M)
REPLACE
SYSFUN Replaces all occurrences of argument2 in argument1 with argument3.
VARCHAR(4000), VARCHAR(4000), VARCHAR(4000) VARCHAR(4000)
CLOB(1M), CLOB(1M), CLOB(1M) CLOB(1M)
BLOB(1M), BLOB(1M), BLOB(1M) BLOB(1M)
RIGHT
SYSFUN Returns a string consisting of the rightmost argument2 bytes inargument1.
VARCHAR(4000), INTEGER VARCHAR(4000)
CLOB(1M), INTEGER CLOB(1M)
BLOB(1M), INTEGER BLOB(1M)
ROUND
SYSFUN Returns the first argument rounded to argument2 places right of thedecimal point. If argument2 is negative, argument1 is rounded to theabsolute value of argument2 places to the left of the decimal point.
INTEGER, INTEGER INTEGER
BIGINT, INTEGER BIGINT
DOUBLE, INTEGER DOUBLE
RTRIM
SYSIBM Returns the characters of the argument with trailing blanks removed.
CHAR VARCHAR
VARCHAR VARCHAR
GRAPHIC VARGRAPHIC
VARGRAPHIC VARGRAPHIC
RTRIM
SYSFUN Returns the characters of the argument with trailing blanks removed.
VARCHAR(4000) VARCHAR(4000)
CLOB(1M) CLOB(1M)
SECOND
SYSIBM Returns the second (time-unit) part of a value.
VARCHAR INTEGER
TIME INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
Functions overview
Chapter 3. Functions 261
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
SIGN
SYSFUN Returns an indicator of the sign of the argument. If the argument isless than zero, -1 is returned. If argument equals zero, 0 is returned. Ifargument is greater than zero, 1 is returned.
SMALLINT SMALLINT
INTEGER INTEGER
BIGINT BIGINT
DOUBLE DOUBLE
SINSYSFUN Returns the sine of the argument, where the argument is an angle
expressed in radians.
DOUBLE DOUBLE
SINHSYSIBM Returns the hyperbolic sine of the argument, where the argument is an
angle expressed in radians.
DOUBLE DOUBLE
SMALLINT
SYSIBM Returns the small integer representation of a number.
numeric-type SMALLINT
VARCHAR SMALLINT
SOUNDEX
SYSFUN Returns a 4 character code representing the sound of the words in theargument. The result can be used to compare with the sound of otherstrings. See also DIFFERENCE.
VARCHAR(4000) CHAR(4)
SPACESYSFUN Returns a character string consisting of argument1 blanks.
INTEGER VARCHAR(4000)
SQLCACHE_SNAPSHOTSYSFUN Returns a table of the snapshot of the db2 dynamic SQL statement
cache (table function).
See “SQLCACHE_SNAPSHOT” on page 544.
SQRTSYSFUN Returns the square root of the argument.
DOUBLE DOUBLE
STDDEVSYSIBM Returns the standard deviation of a set of numbers (column function).
DOUBLE DOUBLE
SUBSTR
SYSIBM Returns a substring of a string argument1 starting at argument2 forargument3 characters. If argument3 is not specified, the remainder of thestring is assumed.
string-type, INTEGER string-type
string-type, INTEGER, INTEGER string-type
SUMSYSIBM Returns the sum of a set of numbers (column function).
numeric-type 4 max-numeric-type 1
Functions overview
262 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
TABLE_NAME
SYSIBM Returns an unqualified name of a table or view based on the objectname given in argument1 and the optional schema name given inargument2. It is used to resolve aliases.
VARCHAR VARCHAR(128)
VARCHAR, VARCHAR VARCHAR(128)
TABLE_SCHEMA
SYSIBM Returns the schema name portion of the two part table or view namegiven by the object name in argument1 and the optional schema namein argument2. It is used to resolve aliases.
VARCHAR VARCHAR(128)
VARCHAR, VARCHAR VARCHAR(128)
TANSYSFUN Returns the tangent of the argument, where the argument is an angle
expressed in radians.
DOUBLE DOUBLE
TANHSYSIBM Returns the hyperbolic tangent of the argument, where the argument is
an angle expressed in radians.
DOUBLE DOUBLE
TIME
SYSIBM Returns a time from a value.
TIME TIME
TIMESTAMP TIME
VARCHAR TIME
TIMESTAMP
SYSIBM Returns a timestamp from a value or a pair of values.
TIMESTAMP TIMESTAMP
VARCHAR TIMESTAMP
VARCHAR, VARCHAR TIMESTAMP
VARCHAR, TIME TIMESTAMP
DATE, VARCHAR TIMESTAMP
DATE, TIME TIMESTAMP
TIMESTAMP_FORMATSYSIBM Returns a timestamp from a character string (argument1) that has been
interpreted using a format template (argument2).
VARCHAR, VARCHAR TIMESTAMP
TIMESTAMP_ISO
SYSFUN Returns a timestamp value based on a date, time, or timestampargument. If the argument is a date, it inserts zero for all the timeelements. If the argument is a time, it inserts the value of CURRENTDATE for the date elements and zero for the fractional time element.
DATE TIMESTAMP
TIME TIMESTAMP
TIMESTAMP TIMESTAMP
VARCHAR(26) TIMESTAMP
Functions overview
Chapter 3. Functions 263
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
TIMESTAMPDIFF
SYSFUN Returns an estimated number of intervals of type argument1 based onthe difference between two timestamps. The second argument is theresult of subtracting two timestamp types and converting the result toCHAR. Valid values of interval (argument1) are:1 Fractions of a second2 Seconds4 Minutes8 Hours16 Days32 Weeks64 Months128 Quarters256 Years
INTEGER, CHAR(22) INTEGER
TO_CHARSYSIBM Returns a character representation of a timestamp.
Same as VARCHAR_FORMAT. Same asVARCHAR_FORMAT.
TO_DATESYSIBM Returns a timestamp from a character string.
Same as TIMESTAMP_FORMAT. Same asTIMESTAMP_FORMAT.
TRANSLATE
SYSIBM Returns a string in which one or more characters may have beentranslated into other characters.
CHAR CHAR
VARCHAR VARCHAR
CHAR, VARCHAR, VARCHAR CHAR
VARCHAR, VARCHAR, VARCHAR VARCHAR
CHAR, VARCHAR, VARCHAR, VARCHAR CHAR
VARCHAR, VARCHAR, VARCHAR, VARCHAR VARCHAR
GRAPHIC, VARGRAPHIC, VARGRAPHIC GRAPHIC
VARGRAPHIC, VARGRAPHIC, VARGRAPHIC VARGRAPHIC
GRAPHIC, VARGRAPHIC, VARGRAPHIC,VARGRAPHIC
GRAPHIC
VARGRAPHIC, VARGRAPHIC, VARGRAPHIC,VARGRAPHIC
VARGRAPHIC
TRUNC or TRUNCATE
SYSFUN Returns argument1 truncated to argument2 places right of the decimalpoint. If argument2 is negative, argument1 is truncated to the absolutevalue of argument2 places to the left of the decimal point.
INTEGER, INTEGER INTEGER
BIGINT, INTEGER BIGINT
DOUBLE, INTEGER DOUBLE
Functions overview
264 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
TYPE_ID 3
SYSIBM Returns the internal data type identifier of the dynamic data type ofthe argument. Note that the result of this function is not portableacross databases.
any-structured-type INTEGER
TYPE_NAME 3
SYSIBM Returns the unqualified name of the dynamic data type of theargument.
any-structured-type VARCHAR(18)
TYPE_SCHEMA 3SYSIBM Returns the schema name of the dynamic type of the argument.
any-structured-type VARCHAR(128)
UCASE or UPPER
SYSIBM Returns a string in which all the characters have been converted toupper case characters.
CHAR CHAR
VARCHAR VARCHAR
UCASESYSFUN Returns a string in which all the characters have been converted to
upper case characters.
VARCHAR VARCHAR
VALUE 3 SYSIBM Same as COALESCE.
VARCHAR
SYSIBM Returns a VARCHAR representation of the first argument. If a secondargument is present, it specifies the length of the result.
character-type VARCHAR
character-type, INTEGER VARCHAR
datetime-type VARCHAR
VARCHAR_FORMAT
SYSIBM Returns a character representation of a timestamp (argument1)formatted as indicated by a format template (argument2).
TIMESTAMP, VARCHAR VARCHAR
VARCHAR, VARCHAR VARCHAR
VARGRAPHIC
SYSIBM Returns a VARGRAPHIC representation of the first argument. If asecond argument is present, it specifies the length of the result.
graphic-type VARGRAPHIC
graphic-type, INTEGER VARGRAPHIC
VARCHAR VARGRAPHIC
VARIANCE or VARSYSIBM Returns the variance of a set of numbers (column function).
DOUBLE DOUBLE
WEEK
SYSFUN Returns the week of the year in of the argument as an integer value inthe range of 1-54.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
Functions overview
Chapter 3. Functions 265
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
WEEK_ISO
SYSFUN Returns the week of the year in of the argument as an integer value inthe range of 1-53. The first day of a week is Monday. Week 1 is thefirst week of the year to contain a Thursday.
VARCHAR(26) INTEGER
DATE INTEGER
TIMESTAMP INTEGER
YEAR
SYSIBM Returns the year part of a value.
VARCHAR INTEGER
DATE INTEGER
TIMESTAMP INTEGER
DECIMAL INTEGER
“+”SYSIBM Adds two numeric operands.
numeric-type, numeric-type max numeric-type
“+”SYSIBM Unary plus operator.
numeric-type numeric-type
“+”
SYSIBM Datetime plus operator.
DATE, DECIMAL(8,0) DATE
TIME, DECIMAL(6,0) TIME
TIMESTAMP, DECIMAL(20,6) TIMESTAMP
DECIMAL(8,0), DATE DATE
DECIMAL(6,0), TIME TIME
DECIMAL(20,6), TIMESTAMP TIMESTAMP
datetime-type, DOUBLE, labeled-duration-code datetime-type
“−”SYSIBM Subtracts two numeric operands.
numeric-type, numeric-type max numeric-type
“−”SYSIBM Unary minus operator.
numeric-type numeric-type 1
Functions overview
266 SQL Reference, Volume 1
Table 16. Supported functions (continued)
Function name Schema Description
Input parameters Returns
“−”
SYSIBM Datetime minus operator.
DATE, DATE DECIMAL(8,0)
TIME, TIME DECIMAL(6,0)
TIMESTAMP, TIMESTAMP DECIMAL(20,6)
DATE, VARCHAR DECIMAL(8,0)
TIME, VARCHAR DECIMAL(6,0)
TIMESTAMP, VARCHAR DECIMAL(20,6)
VARCHAR, DATE DECIMAL(8,0)
VARCHAR, TIME DECIMAL(6,0)
VARCHAR, TIMESTAMP DECIMAL(20,6)
DATE, DECIMAL(8,0) DATE
TIME, DECIMAL(6,0) TIME
TIMESTAMP, DECIMAL(20,6) TIMESTAMP
datetime-type, DOUBLE, labeled-duration-code datetime-type
“*”SYSIBM Multiplies two numeric operands.
numeric-type, numeric-type max numeric-type
“⁄”SYSIBM Divides two numeric operands.
numeric-type, numeric-type max numeric-type
“\” SYSIBM Same as CONCAT.
Notesv References to string data types that are not qualified by a length should be assumed to support the maximum
length for the data typev References to a DECIMAL data type without precision and scale should be assumed to allow any supported
precision and scale.
Functions overview
Chapter 3. Functions 267
Key to Tableany-builtin-type Any data type that is not a distinct type.any-type Any type defined to the database.any-structured-type
Any user-defined structured type defined to the database.any-comparable-type
Any type that is comparable with other argument types as defined in “Assignments andcomparisons” on page 117.
any-union-compatible-typeAny type that is compatible with other argument types as defined in “Rules for result datatypes” on page 134.
character-type Any of the character string types: CHAR, VARCHAR, LONG VARCHAR, CLOB.compatible-string-type
A string type that comes from the same grouping as the other argument (for example, if oneargument is a character-type the other must also be a character-type).
datetime-type Any of the datetime types: DATE, TIME, TIMESTAMP.exact-numeric-type
Any of the exact numeric types: SMALLINT, INTEGER, BIGINT, DECIMALgraphic-type Any of the double byte character string types: GRAPHIC, VARGRAPHIC, LONG
VARGRAPHIC, DBCLOB.labeled-duration-code
As a type this is a SMALLINT. If the function is invoked using the infix form of the plus orminus operator, labeled-durations as defined in “Labeled durations” on page 195 can be used.For a source function that does not use the plus or minus operator character as the name, thefollowing values must be used for the labeled-duration-code argument when invoking thefunction.1 YEAR or YEARS2 MONTH or MONTHS3 DAY or DAYS4 HOUR or HOURS5 MINUTE or MINUTES6 SECOND or SECONDS7 MICROSECOND or MICROSECONDS
LOB-type Any of the large object types: BLOB, CLOB, DBCLOB.max-numeric-type The maximum numeric type of the arguments where maximum is defined as the rightmost
numeric-type.max-string-type The maximum string type of the arguments where maximum is defined as the rightmost
character-type or graphic-type. If arguments are BLOB, the max-string-type is BLOB.numeric-type Any of the numeric types: SMALLINT, INTEGER, BIGINT, DECIMAL, REAL, DOUBLE.string-type Any type from character type, graphic-type or BLOB.
Table Footnotes1 When the input parameter is SMALLINT, the result type is INTEGER. When the input parameter is REAL,
the result type is DOUBLE.2 Keywords allowed are ISO, USA, EUR, JIS, and LOCAL. This function signature is not supported as a
sourced function.3 This function cannot be used as a source function.4 The keyword ALL or DISTINCT may be used before the first parameter. If DISTINCT is specified, the use
of user-defined structured types, long string types or a DATALINK type is not supported.5 The use of user-defined structured types, long string types or a DATALINK type is not supported.6 The type returned by RAISE_ERROR depends upon the context of its use. RAISE_ERROR, if not cast to a
particular type, will return a type appropriate to its invocation within a CASE expression.7 The use of graphic-type, LOB-type, long string types and DATALINK types is not supported.
Functions overview
268 SQL Reference, Volume 1
Aggregate functions
The argument of a column function is a set of values derived from anexpression. The expression can include columns, but cannot include ascalar-fullselect or another column function (SQLSTATE 42607). The scope ofthe set is a group or an intermediate result table.
If a GROUP BY clause is specified in a query, and the intermediate result ofthe FROM, WHERE, GROUP BY, and HAVING clauses is the empty set, thenthe column functions are not applied; the result of the query is the empty set;the SQLCODE is set to +100; and the SQLSTATE is set to ’02000’.
If a GROUP BY clause is not specified in a query, and the intermediate resultof the FROM, WHERE, and HAVING clauses is the empty set, then thecolumn functions are applied to the empty set.
For example, the result of the following SELECT statement is the number ofdistinct values of JOBCODE for employees in department D01:
SELECT COUNT(DISTINCT JOBCODE)FROM CORPDATA.EMPLOYEEWHERE WORKDEPT = ’D01’
The keyword DISTINCT is not considered an argument of the function, butrather a specification of an operation that is performed before the function isapplied. If DISTINCT is specified, duplicate values are eliminated. If ALL isimplicitly or explicitly specified, duplicate values are not eliminated.
Expressions can be used in column functions. For example:SELECT MAX(BONUS + 1000)
INTO :TOP_SALESREP_BONUSFROM EMPLOYEEWHERE COMM > 5000
Column functions can be qualified with a schema name (for example,SYSIBM.COUNT(*)).
Related concepts:
v “Queries” on page 16
Aggregate functions
Chapter 3. Functions 269
AVG
�� AVG (ALL
DISTINCTexpression ) ��
The schema is SYSIBM.
The AVG function returns the average of a set of numbers.
The argument values must be numbers (built-in types only) and their summust be within the range of the data type of the result, except for a decimalresult data type. For decimal results, their sum must be within the rangesupported by a decimal data type having a precision of 31 and a scaleidentical to the scale of the argument values. The result can be null.
The data type of the result is the same as the data type of the argumentvalues, except that:v The result is a large integer if the argument values are small integers.v The result is double-precision floating point if the argument values are
single-precision floating point.
If the data type of the argument values is decimal with precision p and scales, the precision of the result is 31 and the scale is 31-p+s.
The function is applied to the set of values derived from the argument valuesby the elimination of null values. If DISTINCT is specified, redundantduplicate values are eliminated.
If the function is applied to an empty set, the result is a null value. Otherwise,the result is the average value of the set.
The order in which the values are added is undefined, but every intermediateresult must be within the range of the result data type.
If the type of the result is integer, the fractional part of the average is lost.
Examples:v Using the PROJECT table, set the host variable AVERAGE (decimal(5,2)) to
the average staffing level (PRSTAFF) of projects in department (DEPTNO)’D11’.
SELECT AVG(PRSTAFF)INTO :AVERAGEFROM PROJECTWHERE DEPTNO = ’D11’
AVG
270 SQL Reference, Volume 1
Results in AVERAGE being set to 4.25 (that is 17/4) when using the sampletable.
v Using the PROJECT table, set the host variable ANY_CALC (decimal(5,2))to the average of each unique staffing level value (PRSTAFF) of projects indepartment (DEPTNO) ’D11’.
SELECT AVG(DISTINCT PRSTAFF)INTO :ANY_CALCFROM PROJECTWHERE DEPTNO = ’D11’
Results in ANY_CALC being set to 4.66 (that is 14/3) when using thesample table.
AVG
Chapter 3. Functions 271
CORRELATION
�� CORRELATIONCORR
( expression1 , expression2 ) ��
The schema is SYSIBM.
The CORRELATION function returns the coefficient of correlation of a set ofnumber pairs.
The argument values must be numbers.
The data type of the result is double-precision floating point. The result can benull. When not null, the result is between −1 and 1.
The function is applied to the set of (expression1, expression2) pairs derivedfrom the argument values by the elimination of all pairs for which eitherexpression1 or expression2 is null.
If the function is applied to an empty set, or if either STDDEV(expression1) orSTDDEV(expression2) is equal to zero, the result is a null value. Otherwise, theresult is the correlation coefficient for the value pairs in the set. The result isequivalent to the following expression:
COVARIANCE(expression1,expression2)/(STDDEV(expression1)*STDDEV(expression2))
The order in which the values are aggregated is undefined, but everyintermediate result must be within the range of the result data type.
Example:v Using the EMPLOYEE table, set the host variable CORRLN
(double-precision floating point) to the correlation between salary andbonus for those employees in department (WORKDEPT) ’A00’.
SELECT CORRELATION(SALARY, BONUS)INTO :CORRLNFROM EMPLOYEEWHERE WORKDEPT = ’A00’
CORRLN is set to approximately 9.99853953399538E-001 when using thesample table.
CORRELATION
272 SQL Reference, Volume 1
COUNT
�� COUNT (ALL
expressionDISTINCT
*
) ��
The schema is SYSIBM.
The COUNT function returns the number of rows or values in a set of rowsor values.
The data type of expression cannot be a LONG VARCHAR, LONGVARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, distinct type on any ofthese types, or structured type (SQLSTATE 42907).
The result of the function is a large integer. The result cannot be null.
The argument of COUNT(*) is a set of rows. The result is the number of rowsin the set. A row that includes only NULL values is included in the count.
The argument of COUNT(DISTINCT expression) is a set of values. Thefunction is applied to the set of values derived from the argument values bythe elimination of null and duplicate values. The result is the number ofdifferent non-null values in the set.
The argument of COUNT(expression) or COUNT(ALL expression) is a set ofvalues. The function is applied to the set of values derived from the argumentvalues by the elimination of null values. The result is the number of non-nullvalues in the set, including duplicates.
Examples:v Using the EMPLOYEE table, set the host variable FEMALE (int) to the
number of rows where the value of the SEX column is ’F’.SELECT COUNT(*)
INTO :FEMALEFROM EMPLOYEEWHERE SEX = ’F’
Results in FEMALE being set to 13 when using the sample table.v Using the EMPLOYEE table, set the host variable FEMALE_IN_DEPT (int)
to the number of departments (WORKDEPT) that have at least one femaleas a member.
COUNT
Chapter 3. Functions 273
SELECT COUNT(DISTINCT WORKDEPT)INTO :FEMALE_IN_DEPTFROM EMPLOYEEWHERE SEX = ’F’
Results in FEMALE_IN_DEPT being set to 5 when using the sample table.(There is at least one female in departments A00, C01, D11, D21, and E11.)
COUNT
274 SQL Reference, Volume 1
COUNT_BIG
�� COUNT_BIG (ALL
expressionDISTINCT
*
) ��
The schema is SYSIBM.
The COUNT_BIG function returns the number of rows or values in a set ofrows or values. It is similar to COUNT except that the result can be greaterthan the maximum value of integer.
The resulting data type of expression cannot be a LONG VARCHAR, LONGVARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, distinct type on any ofthese types, or structured type (SQLSTATE 42907).
The result of the function is a decimal with precision 31 and scale 0. Theresult cannot be null.
The argument of COUNT_BIG(*) is a set of rows. The result is the number ofrows in the set. A row that includes only NULL values is included in thecount.
The argument of COUNT_BIG(DISTINCT expression) is a set of values. Thefunction is applied to the set of values derived from the argument values bythe elimination of null and duplicate values. The result is the number ofdifferent non-null values in the set.
The argument of COUNT_BIG(expression) or COUNT_BIG(ALL expression) is aset of values. The function is applied to the set of values derived from theargument values by the elimination of null values. The result is the number ofnon-null values in the set, including duplicates.
Examples:v Refer to COUNT examples and substitute COUNT_BIG for occurrences of
COUNT. The results are the same except for the data type of the result.v Some applications may require the use of COUNT but need to support
values larger than the largest integer. This can be achieved by use ofsourced user-defined functions and setting the SQL path. The followingseries of statements shows how to create a sourced function to supportCOUNT(*) based on COUNT_BIG and returning a decimal value with aprecision of 15. The SQL path is set such that the sourced function based onCOUNT_BIG is used in subsequent statements such as the query shown.
COUNT_BIG
Chapter 3. Functions 275
CREATE FUNCTION RICK.COUNT() RETURNS DECIMAL(15,0)SOURCE SYSIBM.COUNT_BIG();
SET CURRENT FUNCTION PATH RICK, SYSTEM PATH;SELECT COUNT(*) FROM EMPLOYEE;
Note how the sourced function is defined with no parameters to supportCOUNT(*). This only works if you name the function COUNT and do notqualify the function with the schema name when it is used. To get the sameeffect as COUNT(*) with a name other than COUNT, invoke the functionwith no parameters. Thus, if RICK.COUNT had been defined asRICK.MYCOUNT instead, the query would have to be written as follows:
SELECT MYCOUNT() FROM EMPLOYEE;
If the count is taken on a specific column, the sourced function must specifythe type of the column. The following statements created a sourced functionthat will take any CHAR column as a argument and use COUNT_BIG toperform the counting.
CREATE FUNCTION RICK.COUNT(CHAR()) RETURNS DOUBLESOURCE SYSIBM.COUNT_BIG(CHAR());
SELECT COUNT(DISTINCT WORKDEPT) FROM EMPLOYEE;
COUNT_BIG
276 SQL Reference, Volume 1
COVARIANCE
�� COVARIANCECOVAR
( expression1 , expression2 ) ��
The schema is SYSIBM.
The COVARIANCE function returns the (population) covariance of a set ofnumber pairs.
The argument values must be numbers.
The data type of the result is double-precision floating point. The result can benull.
The function is applied to the set of (expression1,expression2) pairs derived fromthe argument values by the elimination of all pairs for which either expression1or expression2 is null.
If the function is applied to an empty set, the result is a null value. Otherwise,the result is the covariance of the value pairs in the set. The result isequivalent to the following:1. Let avgexp1 be the result of AVG(expression1) and let avgexp2 be the result
of AVG(expression2).2. The result of COVARIANCE(expression1, expression2) is AVG( (expression1 -
avgexp1) * (expression2 - avgexp2 )
The order in which the values are aggregated is undefined, but everyintermediate result must be within the range of the result data type.
Example:v Using the EMPLOYEE table, set the host variable COVARNCE
(double-precision floating point) to the covariance between salary andbonus for those employees in department (WORKDEPT) ’A00’.
SELECT COVARIANCE(SALARY, BONUS)INTO :COVARNCEFROM EMPLOYEEWHERE WORKDEPT = ’A00’
COVARNCE is set to approximately 1.68888888888889E+006 when using thesample table.
COVARIANCE
Chapter 3. Functions 277
GROUPING
�� GROUPING ( expression ) ��
The schema is SYSIBM.
Used in conjunction with grouping-sets and super-groups, the GROUPINGfunction returns a value that indicates whether or not a row returned in aGROUP BY answer set is a row generated by a grouping set that excludes thecolumn represented by expression.
The argument can be of any type, but must be an item of a GROUP BYclause.
The result of the function is a small integer. It is set to one of the followingvalues:
1 The value of expression in the returned row is a null value, and therow was generated by the super-group. This generated row can beused to provide sub-total values for the GROUP BY expression.
0 The value is other than the above.
Example:
The following query:SELECT SALES_DATE, SALES_PERSON,
SUM(SALES) AS UNITS_SOLD,GROUPING(SALES_DATE) AS DATE_GROUP,GROUPING(SALES_PERSON) AS SALES_GROUP
FROM SALESGROUP BY CUBE (SALES_DATE, SALES_PERSON)ORDER BY SALES_DATE, SALES_PERSON
results in:SALES_DATE SALES_PERSON UNITS_SOLD DATE_GROUP SALES_GROUP---------- --------------- ----------- ----------- -----------12/31/1995 GOUNOT 1 0 012/31/1995 LEE 6 0 012/31/1995 LUCCHESSI 1 0 012/31/1995 - 8 0 103/29/1996 GOUNOT 11 0 003/29/1996 LEE 12 0 003/29/1996 LUCCHESSI 4 0 003/29/1996 - 27 0 103/30/1996 GOUNOT 21 0 003/30/1996 LEE 21 0 003/30/1996 LUCCHESSI 4 0 003/30/1996 - 46 0 1
GROUPING
278 SQL Reference, Volume 1
03/31/1996 GOUNOT 3 0 003/31/1996 LEE 27 0 003/31/1996 LUCCHESSI 1 0 003/31/1996 - 31 0 104/01/1996 GOUNOT 14 0 004/01/1996 LEE 25 0 004/01/1996 LUCCHESSI 4 0 004/01/1996 - 43 0 1- GOUNOT 50 1 0- LEE 91 1 0- LUCCHESSI 14 1 0- - 155 1 1
An application can recognize a SALES_DATE sub-total row by the fact thatthe value of DATE_GROUP is 0 and the value of SALES_GROUP is 1. ASALES_PERSON sub-total row can be recognized by the fact that the value ofDATE_GROUP is 1 and the value of SALES_GROUP is 0. A grand total rowcan be recognized by the value 1 for both DATE_GROUP and SALES_GROUP.
Related reference:
v “Subselect” on page 554
GROUPING
Chapter 3. Functions 279
MAX
�� MAX (ALL
DISTINCTexpression ) ��
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 type other than a long string orDATALINK.
The resulting data type of expression cannot be a LONG VARCHAR, LONGVARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, distinct type on any ofthese types, or structured type (SQLSTATE 42907).
The data type, length and code page of the result are the same as the datatype, length and code page of the argument values. The result is considered tobe a derived value and can be null.
The function is applied to the set of values derived from the argument valuesby the elimination of null values.
If the function is applied to an empty set, the result is a null value. Otherwise,the result is the maximum value in the set.
The specification of DISTINCT has no effect on the result and therefore is notrecommended. It is included for compatibility with other relational systems.
Examples:v Using the EMPLOYEE table, set the host variable MAX_SALARY
(decimal(7,2)) to the maximum monthly salary (SALARY/12) value.SELECT MAX(SALARY) / 12
INTO :MAX_SALARYFROM EMPLOYEE
Results in MAX_SALARY being set to 4395.83 when using the sample table.v Using the PROJECT table, set the host variable LAST_PROJ(char(24)) to the
project name (PROJNAME) that comes last in the collating sequence.SELECT MAX(PROJNAME)
INTO :LAST_PROJFROM PROJECT
MAX
280 SQL Reference, Volume 1
Results in LAST_PROJ being set to ’WELD LINE PLANNING’ when usingthe sample table.
v Similar to the previous example, set the host variable LAST_PROJ (char(40))to the project name that comes last in the collating sequence when a projectname is concatenated with the host variable PROJSUPP. PROJSUPP is'_Support'; it has a char(8) data type.
SELECT MAX(PROJNAME CONCAT PROJSUPP)INTO :LAST_PROJFROM PROJECT
Results in LAST_PROJ being set to 'WELD LINE PLANNING_SUPPORT'when using the sample table.
MAX
Chapter 3. Functions 281
MIN
�� MIN (ALL
DISTINCTexpression ) ��
The MIN function returns the minimum value in a set of values.
The argument values can be of any built-in type other than a long string orDATALINK.
The resulting data type of expression cannot be a LONG VARCHAR, LONGVARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, distinct type on any ofthese types, or structured type (SQLSTATE 42907).
The data type, length, and code page of the result are the same as the datatype, length, and code page of the argument values. The result is consideredto be a derived value and can be null.
The function is applied to the set of values derived from the argument valuesby the elimination of null values.
If this function is applied to an empty set, the result of the function is a nullvalue. Otherwise, the result is the minimum value in the set.
The specification of DISTINCT has no effect on the result and therefore is notrecommended. It is included for compatibility with other relational systems.
Examples:v Using the EMPLOYEE table, set the host variable COMM_SPREAD
(decimal(7,2)) to the difference between the maximum and minimumcommission (COMM) for the members of department (WORKDEPT) ’D11’.
SELECT MAX(COMM) - MIN(COMM)INTO :COMM_SPREADFROM EMPLOYEEWHERE WORKDEPT = ’D11’
Results in COMM_SPREAD being set to 1118 (that is, 2580 - 1462) whenusing the sample table.
v Using the PROJECT table, set the host variable (FIRST_FINISHED (char(10))to the estimated ending date (PRENDATE) of the first project scheduled tobe completed.
SELECT MIN(PRENDATE)INTO :FIRST_FINISHEDFROM PROJECT
MIN
282 SQL Reference, Volume 1
Results in FIRST_FINISHED being set to ’1982-09-15’ when using thesample table.
MIN
Chapter 3. Functions 283
Regression functions
�� REGR_AVGXREGR_AVGYREGR_COUNT
REGR_INTERCEPTREGR_ICPT
REGR_R2REGR_SLOPEREGR_SXXREGR_SXYREGR_SYY
( expression1 , expression2 ) ��
The schema is SYSIBM.
The regression functions support the fitting of an ordinary-least-squaresregression line of the form y = a * x + b to a set of number pairs. The firstelement of each pair (expression1) is interpreted as a value of the dependentvariable (i.e., a ″y value″). The second element of each pair (expression2 ) isinterpreted as a value of the independent variable (i.e., an ″x value″).
The function REGR_COUNT returns the number of non-null number pairsused to fit the regression line (see below).
The function REGR_INTERCEPT (the short form is REGR_ICPT) returns they-intercept of the regression line (″b″ in the above equation)
The function REGR_R2 returns the coefficient of determination (also called″R-squared″ or ″goodness-of-fit″) for the regression.
The function REGR_SLOPE returns the slope of the line (the parameter ″a″ inthe above equation).
The functions REGR_AVGX, REGR_AVGY, REGR_SXX, REGR_SYY, andREGR_SXY return quantities that can be used to compute various diagnosticstatistics needed for the evaluation of the quality and statistical validity of theregression model (see below).
The argument values must be numbers.
The data type of the result of REGR_COUNT is integer. For the remainingfunctions, the data type of the result is double-precision floating point. Theresult can be null. When not null, the result of REGR_R2 is between 0 and 1and the result of both REGR_SXX and REGR_SYY is non-negative.
Regression functions
284 SQL Reference, Volume 1
Each function is applied to the set of (expression1, expression2) pairs derivedfrom the argument values by the elimination of all pairs for which eitherexpression1 or expression2 is null.
If the set is not empty and VARIANCE(expression2) is positive, REGR_COUNTreturns the number of non-null pairs in the set, and the remaining functionsreturn results that are defined as follows:REGR_SLOPE(expression1,expression2) =COVARIANCE(expression1,expression2)/VARIANCE(expression2)
REGR_INTERCEPT(expression1, expression2) =AVG(expression1) - REGR_SLOPE(expression1, expression2) * AVG(expression2)
REGR_R2(expression1, expression2) =POWER(CORRELATION(expression1, expression2), 2) if VARIANCE(expression1)>0REGR_R2(expression1, expression2) = 1 if VARIANCE(expression1)=0
REGR_AVGX(expression1, expression2) = AVG(expression2)
REGR_AVGY(expression1, expression2) = AVG(expression1)
REGR_SXX(expression1, expression2) =REGR_COUNT(expression1, expression2) * VARIANCE(expression2)
REGR_SYY(expression1, expression2) =REGR_COUNT(expression1, expression2) * VARIANCE(expression1)
REGR_SXY(expression1, expression2) =REGR_COUNT(expression1, expression2) * COVARIANCE(expression1, expression2)
If the set is not empty and VARIANCE(expression2) is equal to zero, then theregression line either has infinite slope or is undefined. In this case, thefunctions REGR_SLOPE, REGR_INTERCEPT, and REGR_R2 each return a nullvalue, and the remaining functions return values as defined above. If the set isempty, REGR_COUNT returns zero and the remaining functions return a nullvalue.
The order in which the values are aggregated is undefined, but everyintermediate result must be within the range of the result data type.
The regression functions are all computed simultaneously during a single passthrough the data. In general, it is more efficient to use the regression functionsto compute the statistics needed for a regression analysis than to perform theequivalent computations using ordinary column functions such as AVERAGE,VARIANCE, COVARIANCE, and so forth.
The usual diagnostic statistics that accompany a linear-regression analysis canbe computed in terms of the above functions. For example:
Adjusted R21 - ( (1 - REGR_R2) * ((REGR_COUNT - 1) / (REGR_COUNT - 2)) )
Regression functions
Chapter 3. Functions 285
Standard errorSQRT( (REGR_SYY-(POWER(REGR_SXY,2)/REGR_SXX))/(REGR_COUNT-2) )
Total sum of squaresREGR_SYY
Regression sum of squaresPOWER(REGR_SXY,2) / REGR_SXX
Residual sum of squares(Total sum of squares)-(Regression sum of squares)
t statistic for slopeREGR_SLOPE * SQRT(REGR_SXX) / (Standard error)
t statistic for y-interceptREGR_INTERCEPT/((Standard error) *SQRT((1/REGR_COUNT)+(POWER(REGR_AVGX,2)/REGR_SXX))
Example:v Using the EMPLOYEE table, compute an ordinary-least-squares regression
line that expresses the bonus of an employee in department (WORKDEPT)’A00’ as a linear function of the employee’s salary. Set the host variablesSLOPE, ICPT, RSQR (double-precision floating point) to the slope, intercept,and coefficient of determination of the regression line, respectively. Also setthe host variables AVGSAL and AVGBONUS to the average salary andaverage bonus, respectively, of the employees in department ’A00’, and setthe host variable CNT (integer) to the number of employees in department’A00’ for whom both salary and bonus data are available. Store theremaining regression statistics in host variables SXX, SYY, and SXY.SELECT REGR_SLOPE(BONUS,SALARY), REGR_INTERCEPT(BONUS,SALARY),REGR_R2(BONUS,SALARY), REGR_COUNT(BONUS,SALARY),REGR_AVGX(BONUS,SALARY), REGR_AVGY(BONUS,SALARY),REGR_SXX(BONUS,SALARY), REGR_SYY(BONUS,SALARY),REGR_SXY(BONUS,SALARY)INTO :SLOPE, :ICPT,:RSQR, :CNT,:AVGSAL, :AVGBONUS,:SXX, :SYY,:SXYFROM EMPLOYEEWHERE WORKDEPT = ’A00’
When using the sample table, the host variables are set to the followingapproximate values:SLOPE: +1.71002671916749E-002ICPT: +1.00871888623260E+002RSQR: +9.99707928128685E-001CNT: 3
Regression functions
286 SQL Reference, Volume 1
AVGSAL: +4.28333333333333E+004AVGBONUS: +8.33333333333333E+002SXX: +2.96291666666667E+008SYY: +8.66666666666667E+004SXY: +5.06666666666667E+006
Regression functions
Chapter 3. Functions 287
STDDEV
�� STDDEV (ALL
DISTINCTexpression ) ��
The schema is SYSIBM.
The STDDEV function returns the standard deviation of a set of numbers.
The argument values must be numbers.
The data type of the result is double-precision floating point. The result can benull.
The function is applied to the set of values derived from the argument valuesby the elimination of null values. If DISTINCT is specified, redundantduplicate values are eliminated.
If the function is applied to an empty set, the result is a null value. Otherwise,the result is the standard deviation of the values in the set.
The order in which the values are aggregated is undefined, but everyintermediate result must be within the range of the result data type.
Example:v Using the EMPLOYEE table, set the host variable DEV (double-precision
floating point) to the standard deviation of the salaries for those employeesin department (WORKDEPT) ’A00’.
SELECT STDDEV(SALARY)INTO :DEVFROM EMPLOYEEWHERE WORKDEPT = ’A00’
Results in DEV being set to approximately 9938.00 when using the sampletable.
STDDEV
288 SQL Reference, Volume 1
SUM
�� SUM (ALL
DISTINCTexpression ) ��
The schema is SYSIBM.
The SUM function returns the sum of a set of numbers.
The argument values must be numbers (built-in types only) and their summust 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 argumentvalues except that:v The result is a large integer if the argument values are small integers.v The result is double-precision floating point if the argument values are
single-precision floating point.
If the data type of the argument values is decimal, the precision of the resultis 31 and the scale is the same as the scale of the argument values. The resultcan be null.
The function is applied to the set of values derived from the argument valuesby the elimination of null values. If DISTINCT is specified, redundantduplicate values are also eliminated.
If the function is applied to an empty set, the result is a null value. Otherwise,the result is the sum of the values in the set.
Example:v Using the EMPLOYEE table, set the host variable JOB_BONUS
(decimal(9,2)) to the total bonus (BONUS) paid to clerks (JOB=’CLERK’).SELECT SUM(BONUS)
INTO :JOB_BONUSFROM EMPLOYEEWHERE JOB = ’CLERK’
Results in JOB_BONUS being set to 2800 when using the sample table.
SUM
Chapter 3. Functions 289
VARIANCE
�� VARIANCEVAR
(ALL
DISTINCTexpression ) ��
The schema is SYSIBM.
The VARIANCE function returns the variance of a set of numbers.
The argument values must be numbers.
The data type of the result is double-precision floating point. The result can benull.
The function is applied to the set of values derived from the argument valuesby the elimination of null values. If DISTINCT is specified, redundantduplicate values are eliminated.
If the function is applied to an empty set, the result is a 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 intermediateresult must be within the range of the result data type.
Example:v Using the EMPLOYEE table, set the host variable VARNCE
(double-precision floating point) to the variance of the salaries for thoseemployees in department (WORKDEPT) ’A00’.
SELECT VARIANCE(SALARY)INTO :VARNCEFROM EMPLOYEEWHERE WORKDEPT = ’A00’
Results in VARNCE being set to approximately 98763888.88 when using thesample table.
VARIANCE
290 SQL Reference, Volume 1
Scalar functions
A scalar function can be used wherever an expression can be used. However,the restrictions that apply to the use of expressions and column functions alsoapply when an expression or column function is used within a scalar function.For example, the argument of a scalar function can be a column function onlyif a column function is allowed in the context in which the scalar function isused.
The restrictions on the use of column functions do not apply to scalarfunctions, because a scalar function is applied to a single value rather than toa set of values.
The result of the following SELECT statement has as many rows as there areemployees in department D01:
SELECT EMPNO, LASTNAME, YEAR(CURRENT DATE - BRTHDATE)FROM EMPLOYEEWHERE WORKDEPT = ’D01’
Scalar functions can be qualified with a schema name (for example,SYSIBM.CHAR(123)).
In a Unicode database, all scalar functions that accept a character or graphicstring will accept any string types for which conversion is supported.
Scalar functions
Chapter 3. Functions 291
ABS or ABSVAL
�� ABSABSVAL
( expression ) ��
The schema is SYSIBM.
This function was first available in FixPak 2 of Version 7.1. The SYSFUNversion of the ABS (or ABSVAL) function continues to be available.
Returns the absolute value of the argument. The argument can be any built-innumeric data type.
The result has the same data type and length attribute as the argument. Theresult can be null; if the argument is null, the result is the null value. If theargument is the maximum negative value for SMALLINT, INTEGER orBIGINT, the result is an overflow error.
Example:ABS(-51234)
returns an INTEGER with a value of 51234.
ABS or ABSVAL
292 SQL Reference, Volume 1
ACOS
�� ACOS ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the ACOS function continuesto be available.)
Returns the arccosine of the argument as an angle expressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
Example:
Assume that the host variable ACOSINE is a DECIMAL(10,9) host variablewith a value of 0.070737202.
SELECT ACOS(:ACOSINE)FROM SYSIBM.SYSDUMMY1
This statement returns the approximate value 1.49.
ACOS
Chapter 3. Functions 293
ASCII
�� ASCII ( expression ) ��
The schema is SYSFUN.
Returns the ASCII code value of the leftmost character of the argument as aninteger.
The argument can be of any built-in character string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB the maximum length is1 048 576 bytes. LONG VARCHAR is converted to CLOB for processing by thefunction.
The result of the function is always INTEGER.
The result can be null; if the argument is null, the result is the null value.
ASCII
294 SQL Reference, Volume 1
ASIN
�� ASIN ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the ASIN function continuesto be available.)
Returns the arcsine on the argument as an angle expressed in radians.
The argument can be of any built-in numeric type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
ASIN
Chapter 3. Functions 295
ATAN
�� ATAN ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the ATAN function continuesto be available.)
Returns the arctangent of the argument as an angle expressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
ATAN
296 SQL Reference, Volume 1
ATAN2
�� ATAN2 ( expression , expression ) ��
The schema is SYSIBM. (The SYSFUN version of the ATAN2 functioncontinues to be available.)
Returns the arctangent of x and y coordinates as an angle expressed inradians. The x and y coordinates are specified by the first and secondarguments, respectively.
The first and the second arguments can be of any built-in numeric data type.Both are converted to a double-precision floating-point number for processingby the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
ATAN2
Chapter 3. Functions 297
ATANH
�� ATANH ( expression ) ��
The schema is SYSIBM.
Returns the hyperbolic arctangent of the argument, where the argument is anangle expressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
ATANH
298 SQL Reference, Volume 1
BIGINT
�� BIGINT ( numeric-expressioncharacter-expressiondatetime-expression
) ��
The schema is SYSIBM.
The BIGINT function returns a 64-bit integer representation of a number,character string, date, time, or timestamp in the form of an integer constant.
numeric-expressionAn expression that returns a value of any built-in numeric data type.
If the argument is a numeric-expression, the result is the same number thatwould occur if the argument were assigned to a big integer column orvariable. If the whole part of the argument is not within the range ofintegers, an error occurs. The decimal part of the argument is truncated ifpresent.
character-expressionAn expression that returns a character string value of length not greaterthan the maximum length of a character constant. Leading and trailingblanks are eliminated and the resulting string must conform to the rulesfor forming an SQL integer constant (SQLSTATE 22018). The characterstring cannot be a long string.
If the argument is a character-expression, the result is the same number thatwould occur if the corresponding integer constant were assigned to a biginteger column or variable.
datetime-expressionAn expression that is of one of the following data types:v DATE. The result is a BIGINT value representing the date as yyyymmdd.v TIME. The result is a BIGINT value representing the time as hhmmss.v TIMESTAMP. The result is a BIGINT value representing the timestamp
as yyyymmddhhmmss. The microseconds portion of the timestamp valueis not included in the result.
The result of the function is a big integer. If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
Examples:v From ORDERS_HISTORY table, count the number of orders and return the
result as a big integer value.SELECT BIGINT (COUNT_BIG(*))
FROM ORDERS_HISTORY
BIGINT
Chapter 3. Functions 299
v Using the EMPLOYEE table, select the EMPNO column in big integer formfor further processing in the application.
SELECT BIGINT (EMPNO) FROM EMPLOYEE
v Assume that the column RECEIVED (timestamp) has an internal valueequivalent to ’1988-12-22-14.07.21.136421’.
BIGINT(RECEIVED)
results in the value 19 881 222 140 721.v Assume that the column STARTTIME (time) has an internal value
equivalent to ’12:03:04’.BIGINT(STARTTIME)
results in the value 120 304.
BIGINT
300 SQL Reference, Volume 1
BLOB
�� BLOB ( string-expression, integer
) ��
The schema is SYSIBM.
The BLOB function returns a BLOB representation of a string of any type.
string-expressionA string-expression whose value can be a character string, graphic string, ora binary string.
integerAn integer value specifying the length attribute of the resulting BLOBdata type. If integer is not specified, the length attribute of the result is thesame as the length of the input, except where the input is graphic. In thiscase, the length attribute of the result is twice the length of the input.
The result of the function is a BLOB. If the argument can be null, the resultcan be null; if the argument is null, the result is the null value.
Examplesv Given a table with a BLOB column named TOPOGRAPHIC_MAP and a
VARCHAR column named MAP_NAME, locate any maps that contain thestring ’Pellow Island’ and return a single binary string with the map nameconcatenated in front of the actual map.
SELECT BLOB(MAP_NAME || ’: ’) || TOPOGRAPHIC_MAPFROM ONTARIO_SERIES_4WHERE TOPOGRAPHIC_MAP LIKE BLOB(’%Pellow Island%’)
BLOB
Chapter 3. Functions 301
CEILING or CEIL
�� CEILING ( expression )CEIL
��
The schema is SYSIBM. (The SYSFUN version of the CEILING or CEILfunction continues to be available.)
Returns the smallest integer value greater than or equal to the argument.
The argument can be of any built-in numeric type. The result of the functionhas the same data type and length attribute as the argument except that thescale is 0 if the argument is DECIMAL. For example, an argument with a datatype of DECIMAL(5,5) returns DECIMAL(5,0).
The result can be null if the argument can be null or the database isconfigured with DFT_SQLMATHWARN set to YES; the result is the null valueif the argument is null.
CEILING or CEIL
302 SQL Reference, Volume 1
CHAR
Datetime to Character:
�� CHAR ( datetime-expression, ISO
USAEURJISLOCAL
) ��
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 ), decimal-character
��
The schema is SYSIBM. The SYSFUN.CHAR(floating-point-expression) signaturecontinues to be available. In this case, the decimal character is locale sensitive,and therefore returns either a period or a comma, depending on the locale ofthe database server.
The CHAR function returns a fixed-length character string representation of:v A datetime value, if the first argument is a date, time, or timestampv A character string, if the first argument is any type of character stringv An integer number, if the first argument is a SMALLINT, INTEGER, or
BIGINTv A decimal number, if the first argument is a decimal numberv A double-precision floating-point number, if the first argument is a
DOUBLE or REAL.
CHAR
Chapter 3. Functions 303
The first argument must be of a built-in data type.
Note: The CAST expression can also be used to return a string-expression.
The result of the function is a fixed-length character string. If the firstargument can be null, the result can be null. If the first argument is null, theresult is the null value.
Datetime to Character
datetime-expressionAn expression that is one of the following three data types
date The result is the character string representation of the datein the format specified by the second argument. Thelength of the result is 10. An error occurs if the secondargument is specified and is not a valid value (SQLSTATE42703).
time The result is the character string representation of the timein the format specified by the second argument. Thelength of the result is 8. An error occurs if the secondargument is specified and is not a valid value (SQLSTATE42703).
timestampThe second argument is not applicable and must not bespecified (SQLSTATE 42815). The result is the characterstring representation of the timestamp. The length of theresult is 26.
The code page of the string is the code page of the database at theapplication server.
Character to Character
character-expressionAn expression that returns a value that is CHAR, VARCHAR,LONG VARCHAR, or CLOB data type.
integerthe length attribute for the resulting fixed length character string.The value must be between 0 and 254.
If the length of the character-expression is less than the lengthattribute of the result, the result is padded with blanks up to thelength of the result. If the length of the character-expression is greaterthan the length attribute of the result, truncation is performed. A
CHAR
304 SQL Reference, Volume 1
warning is returned (SQLSTATE 01004) unless the truncated characterswere all blanks and the character-expression was not a long string(LONG VARCHAR or CLOB).
Integer to Character
integer-expressionAn expression that returns a value that is an integer data type(either SMALLINT, INTEGER or BIGINT).
The result is the character string representation of the argument in theform of an SQL integer constant. The result consists of n charactersthat are the significant digits that represent the value of the argumentwith a preceding minus sign if the argument is negative. It is leftjustified.v If the first argument is a small integer:
The length of the result is 6. If the number of characters in theresult is less than 6, then the result is padded on the right withblanks to length 6.
v If the first argument is a large integer:The length of the result is 11. If the number of characters in theresult is less than 11, then the result is padded on the right withblanks to length 11.
v If the first argument is a big integer:The length of the result is 20. If the number of characters in theresult is less than 20, then the result is padded on the right withblanks to length 20.
The code page of the string is the code page of the database at theapplication server.
Decimal to Character
decimal-expressionAn expression that returns a value that is a decimal data type. If adifferent precision and scale is desired, the DECIMAL scalarfunction can be used first to make the change.
decimal-characterSpecifies the single-byte character constant that is used to delimitthe decimal digits in the result character string. The charactercannot be a digit, plus (’+’), minus (’-’) or blank (SQLSTATE42815). The default is the period (’.’) character.
The result is the fixed-length character-string representation of theargument. The result includes a decimal character and p digits, wherep is the precision of the decimal-expression with a preceding minus sign
CHAR
Chapter 3. Functions 305
if the argument is negative. The length of the result is 2+p, where p isthe precision of the decimal-expression. This means that a positive valuewill always include one trailing blank.
The code page of the string is the code page of the database at theapplication server.
Floating-point to Character
floating-point-expressionAn expression that returns a value that is a floating-point datatype (DOUBLE or REAL).
decimal-characterSpecifies the single-byte character constant that is used to delimitthe decimal digits in the result character string. The charactercannot be a digit, plus (+), minus (−), or blank character(SQLSTATE 42815). The default is the period (.) character.
The result is the fixed-length character-string representation of theargument in the form of a floating-point constant. The length of theresult is 24. If the argument is negative, the first character of the resultis a minus sign. Otherwise, the first character is a digit. If theargument value is zero, the result is 0E0. Otherwise, the resultincludes the smallest number of characters that can represent thevalue of the argument such that the mantissa consists of a single digitother than zero followed by the decimal-character and a sequence ofdigits. If the number of characters in the result is less than 24, theresult is padded on the right with blanks to length 24.
The code page of the string is the code page of the database at theapplication server.
Examples:v Assume the column PRSTDATE has an internal value equivalent to
1988-12-25.CHAR(PRSTDATE, USA)
Results in the value ‘12/25/1988’.v Assume the column STARTING has an internal value equivalent to 17:12:30,
the host variable HOUR_DUR (decimal(6,0)) is a time duration with a valueof 050000. (that is, 5 hours).
CHAR(STARTING, USA)
Results in the value ’5:12 PM’.CHAR(STARTING + :HOUR_DUR, USA)
CHAR
306 SQL Reference, Volume 1
Results in the value ’10:12 PM’.v Assume the column RECEIVED (timestamp) has an internal value
equivalent to the combination of the PRSTDATE and STARTING columns.CHAR(RECEIVED)
Results in the value ‘1988-12-25-17.12.30.000000’.v Use the CHAR function to make the type fixed length character and reduce
the length of the displayed results to 10 characters for the LASTNAMEcolumn (defined as VARCHAR(15)) of the EMPLOYEE table.
SELECT CHAR(LASTNAME,10) FROM EMPLOYEE
For rows having a LASTNAME with a length greater than 10 characters(excluding trailing blanks), a warning that the value is truncated isreturned.
v Use the CHAR function to return the values for EDLEVEL (defined assmallint) as a fixed length character string.
SELECT CHAR(EDLEVEL) FROM EMPLOYEE
An EDLEVEL of 18 would be returned as the CHAR(6) value ’18 ’ (18followed by four blanks).
v Assume that STAFF has a SALARY column defined as decimal withprecision of 9 and scale of 2. The current value is 18357.50 and it is to bedisplayed with a comma as the decimal character (18357,50).
CHAR(SALARY, ’,’)
returns the value ’00018357,50’.v Assume the same SALARY column subtracted from 20000.25 is to be
displayed with the default decimal character.CHAR(20000.25 - SALARY)
returns the value ’-0001642.75’.v Assume a host variable, SEASONS_TICKETS, has an integer data type and
a 10000 value.CHAR(DECIMAL(:SEASONS_TICKETS,7,2))
Results in the character value ’10000.00 ’.v Assume a host variable, DOUBLE_NUM has a double data type and a
value of -987.654321E-35.CHAR(:DOUBLE_NUM)
Results in the character value of ’-9.87654321E-33 ’. Because theresult data type is CHAR(24), there are 9 trailing blanks in the result.
CHAR
Chapter 3. Functions 307
Related reference:
v “Expressions” on page 187
CHAR
308 SQL Reference, Volume 1
CHR
�� CHR ( expression ) ��
The schema is SYSFUN.
Returns the character that has the ASCII code value specified by theargument.
The argument can be either INTEGER or SMALLINT. The value of theargument should be between 0 and 255; otherwise, the return value is null.
The result of the function is CHAR(1). The result can be null; if the argumentis null, the result is the null value.
CHR
Chapter 3. Functions 309
CLOB
�� CLOB ( character-string-expression, integer
) ��
The schema is SYSIBM.
The CLOB function returns a CLOB representation of a character string type.
character-string-expressionAn expression that returns a value that is a character string.
integerAn integer value specifying the length attribute of the resulting CLOBdata type. The value must be between 0 and 2 147 483 647. If integer is notspecified, the length of the result is the same as the length of the firstargument.
The result of the function is a CLOB. If the argument can be null, the resultcan be null; if the argument is null, the result is the null value.
CLOB
310 SQL Reference, Volume 1
COALESCE
�� �(1)
COALESCE ( expression , expression ) ��
Notes:
1 VALUE is a synonym for COALESCE.
The schema is SYSIBM.
COALESCE returns the first argument that is not null.
The arguments are evaluated in the order in which they are specified, and theresult of the function is the first argument that is not null. The result can benull only if all the arguments can be null, and the result is null only if all thearguments are null. The selected argument is converted, if necessary, to theattributes of the result.
The arguments must be compatible. They can be of either a built-in oruser-defined data type. (This function cannot be used as a source functionwhen creating a user-defined function. Because this function accepts anycompatible data types as arguments, it is not necessary to create additionalsignatures to support user-defined distinct types.)
Examples:v When selecting all the values from all the rows in the DEPARTMENT table,
if the department manager (MGRNO) is missing (that is, null), then return avalue of ’ABSENT’.
SELECT DEPTNO, DEPTNAME, COALESCE(MGRNO, ’ABSENT’), ADMRDEPTFROM DEPARTMENT
v When selecting the employee number (EMPNO) and salary (SALARY) fromall the rows in the EMPLOYEE table, if the salary is missing (that is, null),then return a value of zero.
SELECT EMPNO, COALESCE(SALARY, 0)FROM EMPLOYEE
Related reference:
v “Rules for result data types” on page 134
COALESCE
Chapter 3. Functions 311
CONCAT
��(1)
CONCAT ( expression1 , expression2 ) ��
Notes:
1 || may be used as a synonym for CONCAT.
The schema is SYSIBM.
Returns the concatenation of two string arguments. The two arguments mustbe compatible types.
The result of the function is a string. Its length is the sum of the lengths of thetwo arguments. If either argument can be null, the result can be null; if theargument is null, the result is the null value.
Related reference:
v “Expressions” on page 187
CONCAT
312 SQL Reference, Volume 1
COS
�� COS ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the COS function continuesto be available.)
Returns the cosine of the argument, where the argument is an angle expressedin radians.
The argument can be of any built-in numeric type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
COS
Chapter 3. Functions 313
COSH
�� COSH ( expression ) ��
The schema is SYSIBM.
Returns the hyperbolic cosine of the argument, where the argument is anangle expressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
COSH
314 SQL Reference, Volume 1
COT
�� COT ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the COT function continuesto be available.)
Returns the cotangent of the argument, where the argument is an angleexpressed in radians.
The argument can be of any built-in numeric type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
COT
Chapter 3. Functions 315
DATE
�� DATE ( expression ) ��
The schema is SYSIBM.
The DATE function returns a date from a value.
The argument must be a date, timestamp, a positive number less than orequal to 3 652 059, a valid string representation of a date or timestamp, or astring of length 7 that is not a CLOB, LONG VARCHAR, DBCLOB, or LONGVARGRAPHIC.
Only Unicode databases support an argument that is a graphic stringrepresentation of a date or a timestamp.
If the argument is a string of length 7, it must represent a valid date in theform yyyynnn, where yyyy are digits denoting a year, and nnn are digitsbetween 001 and 366, denoting a day of that year.
The result of the function is a date. If the argument can be null, the result canbe null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:v If the argument is a date, timestamp, or valid string representation of a date
or timestamp:– The result is the date part of the value.
v 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.v If the argument is a string with a length of 7:
– The result is the date represented by the string.
Examples:
Assume that the column RECEIVED (timestamp) has an internal valueequivalent to ‘1988-12-25-17.12.30.000000’.v This example results in an internal representation of ‘1988-12-25’.
DATE(RECEIVED)
v This example results in an internal representation of ‘1988-12-25’.DATE(’1988-12-25’)
v This example results in an internal representation of ‘1988-12-25’.
DATE
316 SQL Reference, Volume 1
DATE(’25.12.1988’)
v This example results in an internal representation of ‘0001-02-04’.DATE(35)
DATE
Chapter 3. Functions 317
DAY
�� DAY ( expression ) ��
The schema is SYSIBM.
The DAY function returns the day part of a value.
The argument must be a date, timestamp, date duration, timestamp duration,or a valid character string representation of a date or timestamp that is neithera CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a date, timestamp, or valid string representation of a date
or timestamp:– The result is the day part of the value, which is an integer between 1
and 31.v If the argument is a date duration or timestamp duration:
– The result is the day part of the value, which is an integer between −99and 99. A nonzero result has the same sign as the argument.
Examples:v Using the PROJECT table, set the host variable END_DAY (smallint) to the
day that the WELD LINE PLANNING project (PROJNAME) is scheduled tostop (PRENDATE).
SELECT DAY(PRENDATE)INTO :END_DAYFROM PROJECTWHERE PROJNAME = ’WELD LINE PLANNING’
Results in END_DAY being set to 15 when using the sample table.v Assume that the column DATE1 (date) has an internal value equivalent to
2000-03-15 and the column DATE2 (date) has an internal value equivalentto 1999-12-31.
DAY(DATE1 - DATE2)
Results in the value 15.
DAY
318 SQL Reference, Volume 1
DAYNAME
�� DAYNAME ( expression ) ��
The schema is SYSFUN.
Returns a mixed case character string containing the name of the day (e.g.Friday) for the day portion of the argument based on the locale when thedatabase was started.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is VARCHAR(100). The result can be null; if theargument is null, the result is the null value.
DAYNAME
Chapter 3. Functions 319
DAYOFWEEK
�� DAYOFWEEK ( expression ) ��
Returns the day of the week in the argument as an integer value in the range1-7, where 1 represents Sunday.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
DAYOFWEEK
320 SQL Reference, Volume 1
DAYOFWEEK_ISO
�� DAYOFWEEK_ISO ( expression ) ��
The schema is SYSFUN.
Returns the day of the week in the argument as an integer value in the range1-7, where 1 represents Monday.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
DAYOFWEEK_ISO
Chapter 3. Functions 321
DAYOFYEAR
�� DAYOFYEAR ( expression ) ��
The schema is SYSFUN.
Returns the day of the year in the argument as an integer value in the range1-366.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
DAYOFYEAR
322 SQL Reference, Volume 1
DAYS
�� DAYS ( expression ) ��
The schema is SYSIBM.
The DAYS function returns an integer representation of a date.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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 tothe argument.
Examples:v Using the PROJECT table, set the host variable EDUCATION_DAYS (int) to
the number of elapsed days (PRENDATE - PRSTDATE) estimated for theproject (PROJNO) ‘IF2000’.
SELECT DAYS(PRENDATE) - DAYS(PRSTDATE)INTO :EDUCATION_DAYSFROM PROJECTWHERE PROJNO = ’IF2000’
Results in EDUCATION_DAYS being set to 396.v Using the PROJECT table, set the host variable TOTAL_DAYS (int) to the
sum of elapsed days (PRENDATE - PRSTDATE) estimated for all projects indepartment (DEPTNO) ‘E21’.
SELECT SUM(DAYS(PRENDATE) − DAYS(PRSTDATE))INTO :TOTAL_DAYSFROM PROJECTWHERE DEPTNO = ’E21’
Results in TOTAL_DAYS being set to 1584 when using the sample table.
DAYS
Chapter 3. Functions 323
DBCLOB
�� DBCLOB ( graphic-expression, integer
) ��
The schema is SYSIBM.
The DBCLOB function returns a DBCLOB representation of a graphic stringtype.
graphic-expressionAn expression that returns a value that is a graphic string.
integerAn integer value specifying the length attribute of the resulting DBCLOBdata type. The value must be between 0 and 1 073 741 823. If integer is notspecified, the length of the result is the same as the length of the firstargument.
The result of the function is a DBCLOB. If the argument can be null, the resultcan be null; if the argument is null, the result is the null value.
DBCLOB
324 SQL Reference, Volume 1
DBPARTITIONNUM
�� DBPARTITIONNUM ( column-name ) ��
The schema is SYSIBM.
The DBPARTITIONNUM function returns the partition number of the row.For example, if used in a SELECT clause, it returns the partition number foreach row of the table that was used to form the result of the SELECTstatement.
The partition number returned on transition variables and tables is derivedfrom the current transition values of the partitioning key columns. Forexample, in a before insert trigger, the function will return the projectedpartition number given the current values of the new transition variables.However, the values of the partitioning key columns may be modified by asubsequent before insert trigger. Thus, the final partition number of the rowwhen it is inserted into the database may differ from the projected value.
The argument must be the qualified or unqualified name of a column in atable. The column can have any data type. (This function cannot be used as asource function when creating a user-defined function. Because it accepts anydata type as an argument, it is not necessary to create additional signatures tosupport user-defined distinct types.) If column-name references a column in aview, the expression in the view for the column must reference a column ofthe underlying base table, and the view must be deletable. A nested orcommon table expression follows the same rules as a view.
The specific row (and table) for which the partition number is returned by theDBPARTITIONNUM function is determined from the context of the SQLstatement that uses the function.
The data type of the result is INTEGER and is never null. Since row-levelinformation is returned, the results are the same, regardless of which columnis specified for the table. If there is no db2nodes.cfg file, the result is 0.
The DBPARTITIONNUM function cannot be used on replicated tables, withincheck constraints, or in the definition of generated columns (SQLSTATE42881).
For compatibility with versions earlier than Version 8, the keywordNODENUMBER can be substituted for DBPARTITIONNUM.
Examples:
DBPARTITIONNUM
Chapter 3. Functions 325
v Count the number of rows where the row for an EMPLOYEE is on adifferent partition from the employee’s department description inDEPARTMENT.
SELECT COUNT(*) FROM DEPARTMENT D, EMPLOYEE EWHERE D.DEPTNO=E.WORKDEPTAND DBPARTITIONNUM(E.LASTNAME) <> DBPARTITIONNUM(D.DEPTNO)
v Join the EMPLOYEE and DEPARTMENT tables where the rows of the twotables are on the same partition.
SELECT * FROM DEPARTMENT D, EMPLOYEE EWHERE DBPARTITIONNUM(E.LASTNAME) = DBPARTITIONNUM(D.DEPTNO)
v Log the employee number and the projected partition number of the newrow into a table called EMPINSERTLOG1 for any insertion of employees bycreating a before trigger on the table EMPLOYEE.
CREATE TRIGGER EMPINSLOGTRIG1BEFORE INSERT ON EMPLOYEEREFERENCING NEW AW NEWTABLEFOR EACH ROW MODE DB2SQLINSERT INTO EMPINSERTLOG1VALUES(NEWTABLE.EMPNO, DBPARTITIONNUM(NEWTABLE.EMPNO))
Related reference:
v “CREATE VIEW statement” in the SQL Reference, Volume 2
DBPARTITIONNUM
326 SQL Reference, Volume 1
DECIMAL
Numeric to Decimal:
�� DECIMALDEC
( numeric-expression �
�, precision-integer
, scale-integer
) ��
Character to Decimal:
�� DECIMALDEC
( character-expression �
�, precision-integer
, scale-integer, decimal-character
) ��
Datetime to Decimal:
�� DECIMALDEC
( datetime-expression �
�, precision-integer
, scale-integer
) ��
The schema is SYSIBM.
The DECIMAL function returns a decimal representation of:v A numberv A character string representation of a decimal numberv A character string representation of an integer numberv A character string representation of a floating-point numberv A datetime value if the argument is a date, time, or timestamp
The result of the function is a decimal number with precision p and scale s,where p and s are the second and third arguments, respectively. If the firstargument can be null, the result can be null; if the first argument is null, theresult is the null value.
Numeric to Decimal
DECIMAL
Chapter 3. Functions 327
numeric-expressionAn expression that returns a value of any numeric data type.
precision-integerAn integer constant with a value in the range of 1 to 31.
The default for precision-integer depends on the data type ofnumeric-expression:v 15 for floating-point and decimalv 19 for big integerv 11 for large integerv 5 for small integer.
scale-integerAn integer constant in the range of 0 to the precision-integer value.The default is zero.
The result is the same number that would occur if the first argumentwere assigned to a decimal column or variable with precision p andscale s, where p and s are the second and third arguments,respectively. An error occurs if the number of significant decimaldigits required to represent the whole part of the number is greaterthan p−s.
Character to Decimal
character-expressionAn expression that returns a value that is a character string with alength not greater than the maximum length of a characterconstant (4 000 bytes). It cannot have a CLOB or LONGVARCHAR data type. Leading and trailing blanks are eliminatedfrom the string. The resulting substring must conform to the rulesfor forming an SQL integer or decimal constant (SQLSTATE22018).
The character-expression is converted to the database code page ifrequired to match the code page of the constant decimal-character.
precision-integerAn integer constant with a value in the range 1 to 31 that specifiesthe precision of the result. If not specified, the default is 15.
scale-integerAn integer constant with a value in the range 0 to precision-integerthat specifies the scale of the result. If not specified, the default is0.
decimal-characterSpecifies the single-byte character constant used to delimit the
DECIMAL
328 SQL Reference, Volume 1
decimal digits in character-expression from the whole part of thenumber. The character cannot be a digit, plus (+), minus (−), orblank, and it can appear at most once in character-expression(SQLSTATE 42815).
The result is a decimal number with precision p and scale s, where pand s are the second and third arguments, respectively. Digits aretruncated from the end of the decimal number if the number of digitsto the right of the decimal character is greater than the scale. An erroroccurs if the number of significant digits to the left of the decimalcharacter (the whole part of the number) in character-expression isgreater than p−s (SQLSTATE 22003). The default decimal character isnot valid in the substring if a different value for the decimal-characterargument is specified (SQLSTATE 22018).
Datetime to Decimal
datetime-expressionAn expression that is of one of the following data types:v DATE. The result is a DECIMAL(8,0) value representing the
date as yyyymmdd.v TIME. The result is a DECIMAL(6,0) value representing the
time as hhmmss.v TIMESTAMP. The result is a DECIMAL(20,6) value representing
the timestamp as yyyymmddhhmmss.nnnnnn.
This function allows the user to specify a precision, or a precision anda scale. However, a scale cannot be specified without specifying aprecision. The default value for (precision,scale) is (8,0) for DATE,(6,0) for TIME, and (20,6) for TIMESTAMP.
The result is a decimal number with precision p and scale s, where pand s are the second and third arguments, respectively. Digits aretruncated from the end if the number of digits to the right of thedecimal character is greater than the scale. An error occurs if thenumber of significant digits to the left of the decimal character (thewhole part of the number) in datetime-expression is greater than p−s(SQLSTATE 22003).
Examples:v Use the DECIMAL function in order to force a DECIMAL data type (with a
precision of 5 and a scale of 2) to be returned in a select-list for theEDLEVEL column (data type = SMALLINT) in the EMPLOYEE table. TheEMPNO column should also appear in the select list.
SELECT EMPNO, DECIMAL(EDLEVEL,5,2)FROM EMPLOYEE
DECIMAL
Chapter 3. Functions 329
v Assume the host variable PERIOD is of type INTEGER. Then, in order touse its value as a date duration it must be ″cast″ as decimal(8,0).
SELECT PRSTDATE + DECIMAL(:PERIOD,8)FROM PROJECT
v Assume that updates to the SALARY column are input through a windowas a character string using comma as a decimal character (for example, theuser inputs 21400,50). Once validated by the application, it is assigned tothe host variable newsalary which is defined as CHAR(10).
UPDATE STAFFSET SALARY = DECIMAL(:newsalary, 9, 2, ’,’)WHERE ID = :empid;
The value of newsalary becomes 21400.50.v Add the default decimal character (.) to a value.
DECIMAL(’21400,50’, 9, 2, ’.’)
This fails because a period (.) is specified as the decimal character, but acomma (,) appears in the first argument as a delimiter.
v Assume that the column STARTING (time) has an internal value equivalentto ’12:10:00’.
DECIMAL(STARTING)
results in the value 121 000.v Assume that the column RECEIVED (timestamp) has an internal value
equivalent to ’1988-12-22-14.07.21.136421’.DECIMAL(RECEIVED)
results in the value 19 881 222 140 721.136421.v The following table shows the decimal result and resulting precision and
scale for various datetime input values.
DECIMAL(arguments) Precision andScale
Result
DECIMAL(2000-03-21) (8,0) 20000321
DECIMAL(2000-03-21, 10) (10,0) 20000321
DECIMAL(2000-03-21, 12, 2) (12,2) 20000321.00
DECIMAL(12:02:21) (6,0) 120221
DECIMAL(12:02:21, 10) (10,0) 120221
DECIMAL(12:02:21, 10, 2) (10,2) 120221.00
DECIMAL(2000-03-21-12.02.21.123456)
(20, 6) 20000321120221.123456
DECIMAL
330 SQL Reference, Volume 1
DECIMAL(arguments) Precision andScale
Result
DECIMAL(2000-03-21-12.02.21.123456, 23)
(23, 6) 20000321120221.123456
DECIMAL(2000-03-21-12.02.21.123456, 23, 4)
(23, 4) 20000321120221.1234
DECIMAL
Chapter 3. Functions 331
DECRYPT_BIN and DECRYPT_CHAR
�� DECRYPT_BINDECRYPT_CHAR
( encrypted-data ), password-string-expression
��
The schema is SYSIBM.
The DECRYPT_BIN and DECRYPT_CHAR functions both return a value thatis the result of decrypting encrypted-data. The password used for decryption iseither the password-string-expression value or the ENCRYPTION PASSWORDvalue assigned by the SET ENCRYPTION PASSWORD statement. TheDECRYPT_BIN and DECRYPT_CHAR functions can only decrypt values thatare encrypted using the ENCRYPT function (SQLSTATE 428FE).
encrypted-dataAn expression that returns a CHAR FOR BIT DATA or VARCHAR FORBIT DATA value as a complete, encrypted data string. The data stringmust have been encrypted using the ENCRYPT function.
password-string-expressionAn expression that returns a CHAR or VARCHAR value with at least 6bytes and no more than 127 bytes (SQLSTATE 428FC). This expressionmust be the same password used to encrypt the data or decryption willresult in an error (SQLSTATE 428FD). If the value of the passwordargument is null or not provided, the data will be encrypted using theENCRYPTION PASSWORD value, which must have been set for thesession (SQLSTATE 51039).
The result of the DECRYPT_BIN function is VARCHAR FOR BIT DATA. Theresult of the DECRYPT_CHAR function is VARCHAR. If the encrypted-dataincluded a hint, the hint is not returned by the function. The length attributeof the result is the length of the data type of the encrypted-data minus 8 bytes.The actual length of the value returned by the function will match the lengthof the original string that was encrypted. If the encrypted-data includes bytesbeyond the encrypted string, these bytes are not returned by the function.
If the first argument can be null, the result can be null. If the first argument isnull, the result is the null value.
If the data is decrypted on a different system that uses a code page differentfrom the code page in which the data was encrypted, then expansion mayoccur when converting the decrypted value to the database code page. In suchsituations, the encrypted-data value should be cast to a VARCHAR string witha larger number of bytes.
Examples:
DECRYPT_BIN and DECRYPT_CHAR
332 SQL Reference, Volume 1
Example 1: This example uses the ENCRYPTION PASSWORD value to holdthe encryption password.
SET ENCRYPTION PASSWORD = ’Ben123’;INSERT INTO EMP(SSN) VALUES ENCRYPT(’289-46-8832’);SELECT DECRYPT_CHAR(SSN)
FROM EMP;
This returns the value ’289-46-8832’.
Example 2: This example explicitly passes the encryption password.INSERT INTO EMP (SSN) VALUES ENCRYPT(’289-46-8832’,’Ben123’,’’);SELECT DECRYPT(SSN,’Ben123’)
FROM EMP;
This example returns the value ’289-46-8832’.
Related reference:
v “SET ENCRYPTION PASSWORD statement” in the SQL Reference, Volume 2
v “ENCRYPT” on page 359v “GETHINT” on page 366
DECRYPT_BIN and DECRYPT_CHAR
Chapter 3. Functions 333
DEGREES
�� DEGREES ( expression ) ��
The schema is SYSFUN.
Returns the number of degrees converted from the argument expressed inradians.
The argument can be of any built-in numeric type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
DEGREES
334 SQL Reference, Volume 1
DEREF
�� DEREF ( expression ) ��
The DEREF function returns an instance of the target type of the argument.
The argument can be any value with a reference data type that has a definedscope (SQLSTATE 428DT).
The static data type of the result is the target type of the argument. Thedynamic data type of the result is a subtype of the target type of theargument. The result can be null. The result is the null value if expression is anull value or if expression is a reference that has no matching OID in the targettable.
The result is an instance of the subtype of the target type of the reference. Theresult is determined by finding the row of the target table or target view ofthe reference that has an object identifier that matches the reference value. Thetype of this row determines the dynamic type of the result. Since the type ofthe result can be based on a row of a subtable or subview of the target tableor target view, the authorization ID of the statement must have SELECTprivilege on the target table and all of its subtables or the target view and allof its subviews (SQLSTATE 42501).
Examples:
Assume that EMPLOYEE is a table of type EMP, and that its object identifiercolumn is named EMPID. Then the following query returns an object of typeEMP (or one of its subtypes), for each row of the EMPLOYEE table (and itssubtables). This query requires SELECT privilege on EMPLOYEE and all itssubtables.
SELECT DEREF(EMPID) FROM EMPLOYEE
Related reference:
v “TYPE_NAME” on page 481
DEREF
Chapter 3. Functions 335
DIFFERENCE
�� DIFFERENCE ( expression , expression ) ��
The schema is SYSFUN.
Returns a value from 0 to 4 representing the difference between the sounds oftwo strings based on applying the SOUNDEX function to the strings. A valueof 4 is the best possible sound match.
The arguments can be character strings that are either CHAR or VARCHARup to 4 000 bytes.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
Example:VALUES (DIFFERENCE(’CONSTRAINT’,’CONSTANT’),SOUNDEX(’CONSTRAINT’),SOUNDEX(’CONSTANT’)),(DIFFERENCE(’CONSTRAINT’,’CONTRITE’),SOUNDEX(’CONSTRAINT’),SOUNDEX(’CONTRITE’))
This example returns the following.1 2 3----------- ---- ----4 C523 C5232 C523 C536
In the first row, the words have the same result from SOUNDEX while in thesecond row the words have only some similarity.
DIFFERENCE
336 SQL Reference, Volume 1
DIGITS
�� DIGITS ( expression ) ��
The schema is SYSIBM.
The DIGITS function returns a character-string representation of a number.
The argument must be an expression that returns a value of type SMALLINT,INTEGER, BIGINT or DECIMAL.
If the argument can be null, the result can be null; if the argument is null, theresult is the null value.
The result of the function is a fixed-length character string representing theabsolute value of the argument without regard to its scale. The result does notinclude a sign or a decimal character. Instead, it consists exclusively of digits,including, if necessary, leading zeros to fill out the string. The length of thestring is:v 5 if the argument is a small integerv 10 if the argument is a large integerv 19 if the argument is a big integerv p if the argument is a decimal number with a precision of p.
Examples:v Assume that a table called TABLEX contains an INTEGER column called
INTCOL containing 10-digit numbers. List all distinct four digitcombinations of the first four digits contained in column INTCOL.
SELECT DISTINCT SUBSTR(DIGITS(INTCOL),1,4)FROM TABLEX
v Assume that COLUMNX has the DECIMAL(6,2) data type, and that one ofits values is -6.28. Then, for this value:
DIGITS(COLUMNX)
returns the value '000628'.
The result is a string of length six (the precision of the column) withleading zeros padding the string out to this length. Neither sign nordecimal point appear in the result.
DIGITS
Chapter 3. Functions 337
DLCOMMENT
�� DLCOMMENT ( datalink-expression ) ��
The schema is SYSIBM.
The DLCOMMENT function returns the comment value, if it exists, from aDATALINK value.
The argument must be an expression that results in a value with data type ofDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
Example:v Prepare a statement to select the date, the description, and the comment
(from the link in the ARTICLES column) from the HOCKEY_GOALS table.The rows to be selected are those for goals scored by either of the Richardbrothers (Maurice or Henri).
stmtvar = "SELECT DATE_OF_GOAL, DESCRIPTION, DLCOMMENT(ARTICLES)FROM HOCKEY_GOALSWHERE BY_PLAYER = ’Maurice Richard’OR BY_PLAYER = ’Henri Richard’ ";
EXEC SQL PREPARE HOCKEY_STMT FROM :stmtvar;
v Given a DATALINK value that was inserted into column COLA of a row intable TBLA using the scalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’A comment’)
then the following function operating on that value:DLCOMMENT(COLA)
will return the value:A comment
DLCOMMENT
338 SQL Reference, Volume 1
DLLINKTYPE
�� DLLINKTYPE ( datalink-expression ) ��
The schema is SYSIBM.
The DLLINKTYPE function returns the linktype value from a DATALINKvalue.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(4). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
then the following function operating on that value:DLLINKTYPE(COLA)
will return the value:URL
DLLINKTYPE
Chapter 3. Functions 339
DLNEWCOPY
�� DLNEWCOPY ( data-location , has-token ) ��
The schema is SYSIBM.
The DLNEWCOPY function returns a DATALINK value which has anattribute indicating that the referenced file has changed. If such a value isassigned to a DATALINK column as a result of an SQL UPDATE statement,DB2 is notified that an update to the linked file has completed. If theDATALINK column is defined with RECOVERY YES, the new version of thelinked file is archived asynchronously. If such a value is assigned to aDATALINK column as a result of an SQL INSERT statement, an error(SQLSTATE 428D1) is returned.
data-locationA VARCHAR(200) expression that specifies a varying-length characterstring containing a complete URL value. The value may have beenobtained earlier by a SELECT statement through theDLURLCOMPLETEWRITE function.
has-tokenAn INTEGER value that indicates whether the data location contains awrite token.
0 The data location does not contain a write token.
1 The data location contains a write token.
An error occurs if the value is neither 0 nor 1 (SQLSTATE 42815), or thetoken embedded in the data location is not valid (SQLSTATE 428D1).
The result of the function is a DATALINK value without the write token.Neither data-location nor has-token can be null.
For a DATALINK column defined with WRITE PERMISSION ADMINREQUIRING TOKEN FOR UPDATE, the write token must be in the datalocation to complete the SQL UPDATE statement (SQLSTATE 428D1). On theother hand, for WRITE PERMISSION ADMIN NOT REQUIRING TOKENFOR UPDATE, the write token is not required, but is allowed in the datalocation.
For a DATALINK column defined with WRITE PERMISSION ADMINREQUIRING TOKEN FOR UPDATE, the write token must be the same as theone used to open the specified file, if it was opened (SQLSTATE 428D1).
DLNEWCOPY
340 SQL Reference, Volume 1
For any WRITE PERMISSION ADMIN column, even if the write token hasexpired, the token is still considered valid as long as the same token is used toopen the specified file for write access.
In a case where no file update has taken place, or the DATALINK file islinked with other options, such as WRITE PERMISSION BLOCKED/FS or NOLINK CONTROL, this function will behave like DLVALUE.
Examples:v Given a DATALINK value that was inserted into column COLA (defined
with WRITE PERMISSION ADMIN REQUIRING TOKEN FOR UPDATE) intable TBLA using the scalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
Use the scalar function DLURLCOMPLETEWRITE to fetch the value:SELECT DLURLCOMPLETEWRITE(COLA)
FROM TBLAWHERE ...
It returns:HTTP://DLFS.ALMADEN.IBM.COM/x/y/****************;a.b
where **************** represents the write token.
Use the above value to locate and update the content of the file. Issue thefollowing SQL UPDATE statement to indicate that the file has beensuccessfully changed:
UPDATE TBLASET COLA = DLNEWCOPY(’http://dlfs.almaden.ibm.com/x/y/********
********;a.b’, 1)WHERE ...
where **************** represents the same write token used to modifythe file referenced by the URL value. Note that if COLA is defined withWRITE PERMISSION ADMIN NOT REQUIRING TOKEN FOR UPDATE,the write token is not required in the above example.
v The value of the second argument (has-token) can be substituted by thefollowing CASE statement. Assume the URL value is contained in avariable named url_file. Issue the following SQL UPDATE statement toindicate that the file has been successfully changed:
EXEC SQL UPDATE TBLASET COLA = DLNEWCOPY(:url_file,
(CASEWHEN LENGTH(:url_file) = LENGTH(DLURLCOMPLETEONLY(COLA))
DLNEWCOPY
Chapter 3. Functions 341
THEN 0ELSE 1END))
WHERE ...
DLNEWCOPY
342 SQL Reference, Volume 1
DLPREVIOUSCOPY
�� DLPREVIOUSCOPY ( data-location , has-token ) ��
The schema is SYSIBM.
The DLPREVIOUSCOPY function returns a DATALINK value which has anattribute indicating that the previous version of the file should be restored. Ifsuch a value is assigned to a DATALINK column as a result of an SQLUPDATE statement, it triggers DB2 to restore the linked file from thepreviously committed version. If such a value is assigned to a DATALINKcolumn as a result of an SQL INSERT statement, an error (SQLSTATE 428D1)is returned.
data-locationA VARCHAR(200) expression that specifies a varying-length characterstring containing a complete URL value. The value may have beenobtained earlier by a SELECT statement through theDLURLCOMPLETEWRITE function.
has-tokenAn INTEGER value that indicates whether the data location contains awrite token.
0 The data location does not contain a write token.
1 The data location contains a write token.
An error occurs if the value is neither 0 nor 1 (SQLSTATE 42815), or thetoken embedded in the data location is not valid (SQLSTATE 428D1).
The result of the function is a DATALINK value without the write token.Neither data-location nor has-token can be null.
For a DATALINK column defined with WRITE PERMISSION ADMINREQUIRING TOKEN FOR UPDATE, the write token must be in the datalocation to complete the SQL UPDATE statement (SQLSTATE 428D1). On theother hand, for WRITE PERMISSION ADMIN NOT REQUIRING TOKENFOR UPDATE, the write token is not required, but is allowed in the datalocation.
For a DATALINK column defined with WRITE PERMISSION ADMINREQUIRING TOKEN FOR UPDATE, the write token must be the same as theone used to open the specified file, if it was opened (SQLSTATE 428D1).
DLPREVIOUSCOPY
Chapter 3. Functions 343
For any WRITE PERMISSION ADMIN column, even if the write token hasexpired, the token is still considered valid as long as the same token is used toopen the specified file for write access.
Examples:v Given a DATALINK value that was inserted into column COLA (defined
with WRITE PERMISSION ADMIN REQUIRING TOKEN FOR UPDATEand RECOVERY YES) in table TBLA using the scalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
Use the scalar function DLURLCOMPLETEWRITE to fetch the value:SELECT DLURLCOMPLETEWRITE(COLA)
FROM TBLAWHERE ...
It returns:HTTP://DLFS.ALMADEN.IBM.COM/x/y/****************;a.b
where **************** represents the write token.
Use the above value to locate and update the content of the file. Issue thefollowing SQL UPDATE statement to back out the file changes and restoreto the previous committed version:
UPDATE TBLASET COLA = DLPREVIOUSCOPY(’http://dlfs.almaden.ibm.com/x/y/********
********;a.b’, 1)WHERE ...
where **************** represents the same write token used to modifythe file referenced by the URL value. Note that if COLA is defined withWRITE PERMISSION ADMIN NOT REQUIRING TOKEN FOR UPDATE,the write token is not required in the above example.
v The value of the second argument (has-token) can be substituted by thefollowing CASE statement. Assume the URL value is contained in avariable named url_file. Issue the following SQL UPDATE statement to backout the file changes and restore to the previous committed version:
EXEC SQL UPDATE TBLASET COLA = DLPREVIOUSCOPY(:url_file,
(CASEWHEN LENGTH(:url_file) = LENGTH(DLURLCOMPLETEONLY(COLA))THEN 0ELSE 1END))
WHERE ...
DLPREVIOUSCOPY
344 SQL Reference, Volume 1
DLREPLACECONTENT
�� DLREPLACECONTENT ( data-location-target , data-location-source ), comment-string
��
The schema is SYSIBM.
The DLREPLACECONTENT function returns a DATALINK value. When thefunction is on the right hand side of a SET clause in an UPDATE statement, oris in a VALUES clause in an INSERT statement, the assignment of thereturned value results in replacing the content of a file by another file andthen creating a link to it. The actual file replacement process is done duringcommit processing of the current transaction.
data-location-targetA VARCHAR(200) expression that specifies a varying-length characterstring containing a complete URL value.
data-location-sourceA VARCHAR expression that specifies the data location of a file in URLformat. As a result of an assignment in an UPDATE or an INSERTstatement, this file is renamed to the name of the file that is pointed to bydata-location-target; the ownership and permission attributes of the targetfile are retained.
There is a restriction that data-location-source can only be one of thefollowing:v A zero-length valuev A NULL valuev The value of data-location-target plus a suffix string. The suffix string can
be up to 20 characters in length. The characters of the suffix string mustbelong to the URL character set. Moreover, the string cannot contain a“\” character under the UNC scheme, or the “/” character under othervalid schemes (SQLSTATE 428D1).
comment-stringAn optional VARCHAR value that contains a comment or additionallocation information.
The result of the function is a DATALINK value. If any argument can be null,the result can be null; if data-location-target is null, the result is the null value.
If data-location-source is null, a zero-length string, or exactly the same asdata-location-target, the effect of DLREPLACECONTENT is the same asDLVALUE.
Example:
DLREPLACECONTENT
Chapter 3. Functions 345
v Replace the content of a linked file by another file. Given a DATALINKvalue that was inserted into column PICT_FILE in table TBLA using thefollowing INSERT statement:
EXEC SQL INSERT INTO TBLA (PICT_ID, PICT_FILE)VALUES(1000, DLVALUE(’HTTP://HOSTA.COM/dlfs/image-data/pict1.gif’));
Replace the content of this file with another file by issuing the followingSQL UPDATE statement:
EXEC SQL UPDATE TBLASET PICT_FILE =
DLREPLACECONTENT(’HTTP://HOSTA.COM/dlfs/image-data/pict1.gif’,’HTTP://HOSTA.COM/dlfs/image-data/pict1.gif.new’)
WHERE PICT_ID = 1000;
DLREPLACECONTENT
346 SQL Reference, Volume 1
DLURLCOMPLETE
�� DLURLCOMPLETE ( datalink-expression ) ��
The DLURLCOMPLETE function returns the data location attribute from aDATALINK value with a link type of URL. When datalink-expression is aDATALINK column defined with the attribute READ PERMISSION DB, thevalue includes a file access token.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes the comment the result returned is azero length string.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
the following function operating on that value:DLURLCOMPLETE(COLA)
returns:HTTP://DLFS.ALMADEN.IBM.COM/x/y/****************;a.b
where **************** represents the access token.
DLURLCOMPLETE
Chapter 3. Functions 347
DLURLCOMPLETEONLY
�� DLURLCOMPLETEONLY ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLCOMPLETEONLY function returns the data location attributefrom a DATALINK value with a link type of URL. The value returned neverincludes a file access token.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes a comment, the result is a zero lengthstring.
Example:v Given a DATALINK value that was inserted into a DATALINK column
COLA (defined with READ PERMISSION DB) in table TBLA using thescalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
the following function operating on that value:DLURLCOMPLETEONLY(COLA)
returns:HTTP://DLFS.ALMADEN.IBM.COM/x/y/a.b
DLURLCOMPLETEONLY
348 SQL Reference, Volume 1
DLURLCOMPLETEWRITE
�� DLURLCOMPLETEWRITE ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLCOMPLETEWRITE function returns the complete URL value froma DATALINK value with a link type of URL. If the DATALINK valueproduced from datalink-expression comes from a DATALINK column definedwith WRITE PERMISSION ADMIN, a write token is included in the returnvalue. The returned value can be used to locate and update the linked file.
If the DATALINK column is defined with another WRITE PERMISSIONoption (not ADMIN) or NO LINK CONTROL, DLURLCOMPLETEWRITEreturns just the URL value without a write token. If the file reference isderived from a DATALINK column defined with WRITE PERMISSION FS, atoken is not required to write to the file, because write permission iscontrolled by the file system; if the file reference is derived from a DATALINKcolumn defined with WRITE PERMISSION BLOCKED, the file cannot bewritten to at all.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes a comment, the result is a zero lengthstring.
Example:v Given a DATALINK value that was inserted into a DATALINK column
COLA (defined with WRITE PERMISSION ADMIN) in table TBLA usingthe scalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
the following function operating on that value:DLURLCOMPLETEWRITE(COLA)
returns:HTTP://DLFS.ALMADEN.IBM.COM/x/y/****************;a.b
where **************** represents the write token. If COLA is not definedwith WRITE PERMISSION ADMIN, the write token will not be present.
DLURLCOMPLETEWRITE
Chapter 3. Functions 349
DLURLPATH
�� DLURLPATH ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLPATH function returns the path and file name necessary to accessa file within a given server from a DATALINK value with a linktype of URL.When datalink-expression is a DATALINK column defined with the attributeREAD PERMISSION DB, the value includes a file access token.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes the comment the result returned is azero length string.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
then the following function operating on that value:DLURLPATH(COLA)
will return the value:/x/y/****************;a.b
(where **************** represents the access token)
DLURLPATH
350 SQL Reference, Volume 1
DLURLPATHONLY
�� DLURLPATHONLY ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLPATHONLY function returns the path and file name necessary toaccess a file within a given server from a DATALINK value with a linktype ofURL. The value returned NEVER includes a file access token.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes the comment the result returned is azero length string.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
then the following function operating on that value:DLURLPATHONLY(COLA)
will return the value:/x/y/a.b
DLURLPATHONLY
Chapter 3. Functions 351
DLURLPATHWRITE
�� DLURLPATHWRITE ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLPATHWRITE function returns the path and file name necessary toaccess a file within a given server from a DATALINK value with a linktype ofURL. The value returned includes a write token if the DATALINK valueproduced from datalink_expression comes from a DATALINK column definedwith WRITE PERMISSION ADMIN.
If the DATALINK column is defined with other WRITE PERMISSION options(not ADMIN) or NO LINK CONTROL, DLURLPATHWRITE returns the pathand file name without a write token. If the file reference is derived from aDATALINK column defined with WRITE PERMISSION FS, a token is notrequired to write to the file, because write permission is controlled by the filesystem; if the file reference is derived from a DATALINK column definedwith WRITE PERMISSION BLOCKED, the file cannot be written to at all.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes a comment, the result is a zero lengthstring.
Example:v Given a DATALINK value that was inserted into a DATALINK column
COLA (defined with WRITE PERMISSION ADMIN) in table TBLA usingthe scalar function:
DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
the following function operating on that value:DLURLPATHWRITE(COLA)
returns:/x/y/****************;a.b
where **************** represents the write token. If COLA is not definedwith WRITE PERMISSION ADMIN, the write token will not be present.
DLURLPATHWRITE
352 SQL Reference, Volume 1
DLURLSCHEME
�� DLURLSCHEME ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLSCHEME function returns the scheme from a DATALINK valuewith a linktype of URL. The value will always be in upper case.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(20). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes the comment the result returned is azero length string.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
then the following function operating on that value:DLURLSCHEME(COLA)
will return the value:HTTP
DLURLSCHEME
Chapter 3. Functions 353
DLURLSERVER
�� DLURLSERVER ( datalink-expression ) ��
The schema is SYSIBM.
The DLURLSERVER function returns the file server from a DATALINK valuewith a linktype of URL. The value will always be in upper case.
The argument must be an expression that results in a value with data typeDATALINK.
The result of the function is VARCHAR(254). If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
If the DATALINK value only includes the comment the result returned is azero length string.
Example:v Given a DATALINK value that was inserted into column COLA of a row in
table TBLA using the scalar function:DLVALUE(’http://dlfs.almaden.ibm.com/x/y/a.b’,’URL’,’a comment’)
then the following function operating on that value:DLURLSERVER(COLA)
will return the value:DLFS.ALMADEN.IBM.COM
DLURLSERVER
354 SQL Reference, Volume 1
DLVALUE
�� DLVALUE ( data-location, linktype-string
, comment-string
) ��
The schema is SYSIBM.
The DLVALUE function returns a DATALINK value. When the function is onthe right hand side of a SET clause in an UPDATE statement or is in aVALUES clause in an INSERT statement, it usually also creates a link to a file.However, if only a comment is specified (in which case the data-location is azero-length string), the DATALINK value is created with empty linkageattributes so there is no file link.
data-locationIf the link type is URL, then this is an expression that yields a varyinglength character string containing a complete URL value.
linktype-stringAn optional VARCHAR expression that specifies the link type of theDATALINK value. The only valid value is ’URL’ (SQLSTATE 428D1).
comment-stringAn optional VARCHAR(254) value that provides a comment or additionallocation information. The length of data-location plus comment-string mustnot exceed 200 bytes.
The result of the function is a DATALINK value. If any argument of theDLVALUE function can be null, the result can be null; If the data-location isnull, the result is the null value.
When defining a DATALINK value using this function, consider themaximum length of the target of the value. For example, if a column isdefined as DATALINK(200), then the maximum length of the data-location plusthe comment is 200 bytes.
Example:v Insert a row into the table. The URL values for the first two links are
contained in the variables named url_article and url_snapshot. The variablenamed url_snapshot_comment contains a comment to accompany thesnapshot link. There is, as yet, no link for the movie, only a comment in thevariable named url_movie_comment.
EXEC SQLINSERT INTO HOCKEY_GOALS
VALUES(’Maurice Richard’,’Montreal Canadien’,
DLVALUE
Chapter 3. Functions 355
’?’,’Boston Bruins,’1952-04-24’,’Winning goal in game 7 of Stanley Cup final’,DLVALUE(:url_article),DLVALUE(:url_snapshot, ’URL’, :url_snapshot_comment),DLVALUE(’’, ’URL’, :url_movie_comment) );
DLVALUE
356 SQL Reference, Volume 1
DOUBLE
Numeric to Double:
�� DOUBLE ( numeric-expression )FLOATDOUBLE_PRECISION
��
Character String to Double:
�� DOUBLE ( string-expression ) ��
The schema is SYSIBM. However, the schema for DOUBLE(string-expression) isSYSFUN.
The DOUBLE function returns a floating-point number corresponding to a:v number if the argument is a numeric expressionv character string representation of a number if the argument is a string
expression.
Numeric to Double
numeric-expressionThe argument is an expression that returns a value of any built-innumeric data type.
The result of the function is a double-precision floating-pointnumber. If the argument can be null, the result can be null; if theargument is null, the result is the null value.
The result is the same number that would occur if the argumentwere assigned to a double-precision floating-point column orvariable.
Character String to Double
string-expressionThe argument can be of type CHAR or VARCHAR in the form ofa numeric constant. Leading and trailing blanks in argument areignored.
The result of the function is a double-precision floating-pointnumber. The result can be null; if the argument is null, the resultis the null value.
The result is the same number that would occur if the string wasconsidered a constant and assigned to a double-precisionfloating-point column or variable.
DOUBLE
Chapter 3. Functions 357
Example:
Using the EMPLOYEE table, find the ratio of salary to commission foremployees whose commission is not zero. The columns involved (SALARYand COMM) have DECIMAL data types. To eliminate the possibility ofout-of-range results, DOUBLE is applied to SALARY so that the division iscarried out in floating point:
SELECT EMPNO, DOUBLE(SALARY)/COMMFROM EMPLOYEEWHERE COMM > 0
DOUBLE
358 SQL Reference, Volume 1
ENCRYPT
�� ENCRYPT �
� ( data-string-expression ), password-string-expression
, hint-string-expression
��
The schema is SYSIBM.
The ENCRYPT function returns a value that is the result of encryptingdata-string-expression. The password used for encryption is either thepassword-string-expression value or the ENCRYPTION PASSWORD value (asassigned using the SET ENCRYPTION PASSWORD statement).
data-string-expressionAn expression that returns a CHAR or VARCHAR value to be encrypted.The length attribute for the data type of data-string-expression is limited to32663 without a hint-string-expression argument and 32631 when thehint-string-expression argument is specified (SQLSTATE 42815).
password-string-expressionAn expression that returns a CHAR or VARCHAR value with at least 6bytes and no more than 127 bytes (SQLSTATE 428FC). The valuerepresents the password used to encrypt the data-string-expression. If thevalue of the password argument is null or not provided, the data will beencrypted using the ENCRYPTION PASSWORD value, which must havebeen set for the session (SQLSTATE 51039).
hint-string-expressionAn expression that returns a CHAR or VARCHAR value up to 32 bytesthat will help data owners remember passwords (for example, ’Ocean’ asa hint to remember ’Pacific’). If a hint value is given, the hint is embeddedinto the result and can be retrieved using the GETHINT function. If thisargument is null or not provided, no hint will be embedded in the result.
The result data type of the function is VARCHAR FOR BIT DATA.
The length attribute of the result is:v When the optional hint parameter is specified, the length attribute of the
non-encrypted data + 8 bytes + the number of bytes to the next 8 byteboundary + 32 bytes for the hint length.
v With no hint parameter, the length attribute of the non-encrypted data + 8bytes + the number of bytes to the next 8 byte boundary.
If the first argument can be null, the result can be null; if the first argument isnull, the result is the null value.
ENCRYPT
Chapter 3. Functions 359
Notice that the encrypted result is longer than the data-string-expression value.Therefore, when assigning encrypted values, ensure that the target is declaredwith sufficient size to contain the entire encrypted value.
Notes:
v Encryption Algorithm: The internal encryption algorithm used is RC2 blockcipher with padding, the 128-bit secret key is derived from the passwordusing a MD2 message digest.
v Encryption Passwords and Data: It is the user’s responsibility to performpassword management. Once the data is encrypted only the password usedto encrypt it can be used to decrypt it (SQLSTATE 428FD). Be careful whenusing CHAR variables to set password values as they may be padded withblanks. The encrypted result may contain null terminator and othernon-printable characters.
v Table Column Definition: When defining columns and types to containencrypted data, always calculate the length attribute as follows.For encrypted data with no hint:Maximum length of the non-encrypted data + 8 bytes + the number ofbytes to the next 8 byte boundary = encrypted data column length.For encrypted data with an embedded hint:Maximum length of the non-encrypted data + 8 bytes + the number ofbytes to the next 8 byte boundary + 32 bytes for the hint length =encrypted data column length.Any assignment or cast to a length shorter than the suggested data lengthmay result in failed decryption in the future and lost data. Blanks are validencrypted data values that may be truncated when stored in a column thatis too short.Some sample column length calculations:
Maximum length of non-encrypted data 6 bytes8 bytes 8 bytesNumber of bytes to the next 8 byte boundary 2 bytes
---------Encrypted data column length 16 bytes
Maximum length of non-encrypted data 32 bytes8 bytes 8 bytesNumber of bytes to the next 8 byte boundary 8 bytes
---------Encrypted data column length 48 bytes
v Administration of encrypted data: Encrypted data can only be decrypted onservers that support the decryption functions that correspond to theENCRYPT function. Hence, replication of columns with encrypted datashould only be done to servers that support the DECRYPT_BIN orDECRYPT_CHAR function.
ENCRYPT
360 SQL Reference, Volume 1
Examples:
Example 1: This example uses the ENCRYPTION PASSWORD value to holdthe encryption password.
SET ENCRYPTION PASSWORD = ’Ben123’;INSERT INTO EMP(SSN) VALUES ENCRYPT(’289-46-8832’);
Example 2: This example explicitly passes the encryption password.INSERT INTO EMP(SSN) VALUES ENCRYPT(’289-46-8832’,’Ben123’);
Example 3: The hint ’Ocean’ is stored to help the user remember theencryption password of ’Pacific’.
INSERT INTO EMP(SSN) VALUES ENCRYPT(’289-46-8832’,’Pacific’,’Ocean’);
Related reference:
v “DECRYPT_BIN and DECRYPT_CHAR” on page 332v “GETHINT” on page 366
ENCRYPT
Chapter 3. Functions 361
EVENT_MON_STATE
�� EVENT_MON_STATE ( string-expression ) ��
The schema is SYSIBM.
The EVENT_MON_STATE function returns the current state of an eventmonitor.
The argument is a string expression with a resulting type of CHAR orVARCHAR and a value that is the name of an event monitor. If the namedevent monitor does not exist in the SYSCAT.EVENTMONITORS catalog table,SQLSTATE 42704 will be returned.
The result is an integer with one of the following values:v
0 The event monitor is inactive.
1 The event monitor is active.
If the argument can be null, the result can be null; if the argument is null, theresult is the null value.
Example:v The following example selects all of the defined event monitors, and
indicates whether each is active or inactive:SELECT EVMONNAME,
CASEWHEN EVENT_MON_STATE(EVMONNAME) = 0 THEN ’Inactive’WHEN EVENT_MON_STATE(EVMONNAME) = 1 THEN ’Active’
ENDFROM SYSCAT.EVENTMONITORS
EVENT_MON_STATE
362 SQL Reference, Volume 1
EXP
�� EXP ( expression ) ��
The schema is SYSFUN.
Returns the exponential function of the argument.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
EXP
Chapter 3. Functions 363
FLOAT
�� FLOAT ( numeric-expression ) ��
The schema is SYSIBM.
The FLOAT function returns a floating-point representation of a number.FLOAT is a synonym for DOUBLE.
Related reference:
v “DOUBLE” on page 357
FLOAT
364 SQL Reference, Volume 1
FLOOR
�� FLOOR ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the FLOOR functioncontinues to be available.)
Returns the largest integer value less than or equal to the argument.
The result of the function has the same data type and length attribute as theargument except that the scale is 0 if the argument is DECIMAL. For example,an argument with a data type of DECIMAL(5,5) returns DECIMAL(5,0).
The result can be null if the argument can be null or the database isconfigured with DFT_SQLMATHWARN set to YES; the result is the null valueif the argument is null.
FLOOR
Chapter 3. Functions 365
GETHINT
�� GETHINT ( encrypted-data ) ��
The schema is SYSIBM.
The GETHINT function will return the password hint if one is found in theencrypted-data. A password hint is a phrase that will help data ownersremember passwords (For example, ’Ocean’ as a hint to remember ’Pacific’).
encrypted-data
An expression that returns a CHAR FOR BIT DATA or VARCHAR FORBIT DATA value that is a complete, encrypted data string. The data stringmust have been encrypted using the ENCRYPT function (SQLSTATE428FE).
The result of the function is VARCHAR(32). The result can be null; if the hintparameter was not added to the encrypted-data by the ENCRYPT function orthe first argument is null, the result is the null value.
Example:
In this example the hint ’Ocean’ is stored to help the user remember theencryption password ’Pacific’.
INSERT INTO EMP (SSN) VALUES ENCRYPT(’289-46-8832’, ’Pacific’,’Ocean’);SELECT GETHINT(SSN)
FROM EMP;
The value returned is ’Ocean’.
Related reference:
v “DECRYPT_BIN and DECRYPT_CHAR” on page 332v “ENCRYPT” on page 359
GETHINT
366 SQL Reference, Volume 1
GENERATE_UNIQUE
�� GENERATE_UNIQUE ( ) ��
The schema is SYSIBM.
The GENERATE_UNIQUE function returns a bit data character string 13 byteslong (CHAR(13) FOR BIT DATA) that is unique compared to any otherexecution of the same function. (The system clock is used to generate theinternal Universal Time, Coordinated (UTC) timestamp along with thepartition number on which the function executes. Adjustments that move theactual system clock backward could result in duplicate values.) The functionis defined as not-deterministic.
There are no arguments to this function (the empty parentheses must bespecified).
The result of the function is a unique value that includes the internal form ofthe Universal Time, Coordinated (UTC) and the partition number where thefunction was processed. The result cannot be null.
The result of this function can be used to provide unique values in a table.Each successive value will be greater than the previous value, providing asequence that can be used within a table. The value includes the partitionnumber where the function executed so that a table partitioned acrossmultiple partitions also has unique values in some sequence. The sequence isbased on the time the function was executed.
This function differs from using the special register CURRENT TIMESTAMPin that a unique value is generated for each row of a multiple row insertstatement or an insert statement with a fullselect.
The timestamp value that is part of the result of this function can bedetermined using the TIMESTAMP scalar function with the result ofGENERATE_UNIQUE as an argument.
Examples:v Create a table that includes a column that is unique for each row. Populate
this column using the GENERATE_UNIQUE function. Notice that theUNIQUE_ID column has ″FOR BIT DATA″ specified to identify the columnas a bit data character string.
CREATE TABLE EMP_UPDATE(UNIQUE_ID CHAR(13) FOR BIT DATA,EMPNO CHAR(6),TEXT VARCHAR(1000))
GENERATE_UNIQUE
Chapter 3. Functions 367
INSERT INTO EMP_UPDATEVALUES (GENERATE_UNIQUE(), ’000020’, ’Update entry...’),(GENERATE_UNIQUE(), ’000050’, ’Update entry...’)
This table will have a unique identifier for each row provided that theUNIQUE_ID column is always set using GENERATE_UNIQUE. This can bedone by introducing a trigger on the table.
CREATE TRIGGER EMP_UPDATE_UNIQUENO CASCADE BEFORE INSERT ON EMP_UPDATEREFERENCING NEW AS NEW_UPDFOR EACH ROW MODE DB2SQLSNEW_UPD.UNIQUE_ID = GENERATE_UNIQUE()
With this trigger defined, the previous INSERT statement could be issuedwithout the first column as follows.
INSERT INTO EMP_UPDATE (EMPNO, TEXT)VALUES (’000020’, ’Update entry 1...’),(’000050’, ’Update entry 2...’)
The timestamp (in UTC) for when a row was added to EMP_UPDATE canbe returned using:
SELECT TIMESTAMP (UNIQUE_ID), EMPNO, TEXTFROM EMP_UPDATE
Therefore, there is no need to have a timestamp column in the table torecord when a row is inserted.
GENERATE_UNIQUE
368 SQL Reference, Volume 1
GRAPHIC
�� GRAPHIC ( graphic-expression, integer
) ��
The schema is SYSIBM.
The GRAPHIC function returns a fixed-length graphic string representation of:v A graphic string, if the first argument is any type of graphic stringv A datetime value (Unicode database only), if the first argument is a date,
time, or timestamp.
graphic-expressionAn expression that returns a value that is a graphic string.
integerAn integer value specifying the length attribute of the resulting GRAPHICdata type. The value must be between 1 and 127. If integer is not specified,the length of the result is the same as the length of the first argument.
The result of the function is a GRAPHIC. If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
Datetime to Graphic:
�� GRAPHIC ( datetime-expression, ISO
USAEURJISLOCAL
) ��
Datetime to Graphic
datetime-expressionAn expression that is one of the following three data types
date The result is the graphic string representation of the datein the format specified by the second argument. Thelength of the result is 10. An error occurs if the secondargument is specified and is not a valid value (SQLSTATE42703).
time The result is the graphic string representation of the timein the format specified by the second argument. Thelength of the result is 8. An error occurs if the secondargument is specified and is not a valid value (SQLSTATE42703).
GRAPHIC
Chapter 3. Functions 369
timestampThe second argument is not applicable and must not bespecified (SQLSTATE 42815). The result is the graphicstring representation of the timestamp. The length of theresult is 26.
The code page of the string is the code page of the database at theapplication server.
GRAPHIC
370 SQL Reference, Volume 1
HASHEDVALUE
�� HASHEDVALUE ( column-name ) ��
The schema is SYSIBM.
The HASHEDVALUE function returns the partitioning map index of the rowobtained by applying the partitioning function on the partitioning key valueof the row. For example, if used in a SELECT clause, it returns the partitioningmap index for each row of the table that was used to form the result of theSELECT statement.
The partitioning map index returned on transition variables and tables isderived from the current transition values of the partitioning key columns.For example, in a before insert trigger, the function will return the projectedpartitioning map index given the current values of the new transitionvariables. However, the values of the partitioning key columns may bemodified by a subsequent before insert trigger. Thus, the final partitioningmap index of the row when it is inserted into the database may differ fromthe projected value.
The argument must be the qualified or unqualified name of a column in atable. The column can have any data type. (This function cannot be used as asource function when creating a user-defined function. Because it accepts anydata type as an argument, it is not necessary to create additional signatures tosupport user-defined distinct types.) If column-name references a column of aview the expression in the view for the column must reference a column ofthe underlying base table and the view must be deletable. A nested orcommon table expression follows the same rules as a view.
The specific row (and table) for which the partitioning map index is returnedby the HASHEDVALUE function is determined from the context of the SQLstatement that uses the function.
The data type of the result is INTEGER in the range 0 to 4095. For a tablewith no partitioning key, the result is always 0. A null value is never returned.Since row-level information is returned, the results are the same, regardless ofwhich column is specified for the table.
The HASHEDVALUE function cannot be used on replicated tables, withincheck constraints, or in the definition of generated columns (SQLSTATE42881).
For compatibility with versions earlier than Version 8, the function namePARTITION can be substituted for HASHEDVALUE.
HASHEDVALUE
Chapter 3. Functions 371
Example:v List the employee numbers (EMPNO) from the EMPLOYEE table for all
rows with a partitioning map index of 100.SELECT EMPNO FROM EMPLOYEE
WHERE HASHEDVALUE(PHONENO) = 100
v Log the employee number and the projected partitioning map index of thenew row into a table called EMPINSERTLOG2 for any insertion ofemployees by creating a before trigger on the table EMPLOYEE.
CREATE TRIGGER EMPINSLOGTRIG2BEFORE INSERT ON EMPLOYEEREFERENCING NEW AW NEWTABLEFOR EACH MODE ROW MODE DB2SQLINSERT INTO EMPINSERTLOG2
VALUES(NEWTABLE.EMPNO, HASHEDVALUE(NEWTABLE.EMPNO))
Related reference:
v “CREATE VIEW statement” in the SQL Reference, Volume 2
HASHEDVALUE
372 SQL Reference, Volume 1
HEX
�� HEX ( expression ) ��
The schema is SYSIBM.
The HEX function returns a hexadecimal representation of a value as acharacter string.
The argument can be an expression that is a value of any built-in data typewith a maximum length of 16 336 bytes.
The result of the function is a character string. If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
The code page is the database code page.
The result is a string of hexadecimal digits. The first two represent the firstbyte of the argument, the next two represent the second byte of the argument,and so forth. If the argument is a datetime value or a numeric value the resultis the hexadecimal representation of the internal form of the argument. Thehexadecimal representation that is returned may be different depending onthe application server where the function is executed. Cases where differenceswould be evident include:v Character string arguments when the HEX function is performed on an
ASCII client with an EBCDIC server or on an EBCDIC client with an ASCIIserver.
v Numeric arguments (in some cases) when the HEX function is performedwhere client and server systems have different byte orderings for numericvalues.
The type and length of the result vary based on the type and length ofcharacter string arguments.v Character string
– Fixed length not greater than 127- Result is a character string of fixed length twice the defined length of
the argument.– Fixed length greater than 127
- Result is a character string of varying length twice the defined lengthof the argument.
– Varying length- Result is a character string of varying length with maximum length
twice the defined maximum length of the argument.
HEX
Chapter 3. Functions 373
v Graphic string– Fixed length not greater than 63
- Result is a character string of fixed length four times the definedlength of the argument.
v Fixed length greater than 63– Result is a character string of varying length four times the defined
length of the argument.v Varying length
– Result is a character string of varying length with maximum length fourtimes the defined maximum length of the argument.
Examples:
Assume the use of a DB2 for AIX application server for the followingexamples.v Using the DEPARTMENT table set the host variable HEX_MGRNO
(char(12)) to the hexadecimal representation of the manager number(MGRNO) for the ‘PLANNING’ department (DEPTNAME).
SELECT HEX(MGRNO)INTO :HEX_MGRNOFROM DEPARTMENTWHERE DEPTNAME = ’PLANNING’
HEX_MGRNO will be set to ’303030303230’ when using the sample table(character value is ’000020’).
v Suppose COL_1 is a column with a data type of char(1) and a value of 'B'.The hexadecimal representation of the letter 'B' is X'42'. HEX(COL_1)returns a two-character string '42'.
v Suppose COL_3 is a column with a data type of decimal(6,2) and a value of40.1. An eight-character string '0004010C' is the result of applying the HEXfunction to the internal representation of the decimal value, 40.1.
HEX
374 SQL Reference, Volume 1
HOUR
�� HOUR ( expression ) ��
The schema is SYSIBM.
The HOUR function returns the hour part of a value.
The argument must be a time, timestamp, time duration, timestamp durationor a valid character string representation of a time or timestamp that isneither a CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a time, timestamp or valid string representation of a time
or timestamp:– The result is the hour part of the value, which is an integer between 0
and 24.v If the argument is a time duration or timestamp duration:
– The result is the hour part of the value, which is an integer between −99and 99. A nonzero result has the same sign as the argument.
Example:
Using the CL_SCHED sample table, select all the classes that start in theafternoon.
SELECT * FROM CL_SCHEDWHERE HOUR(STARTING) BETWEEN 12 AND 17
HOUR
Chapter 3. Functions 375
IDENTITY_VAL_LOCAL
�� IDENTITY_VAL_LOCAL ( ) ��
The schema is SYSIBM.
The IDENTITY_VAL_LOCAL function is a non-deterministic function thatreturns the most recently assigned value for an identity column, where theassignment occurred as a result of a single row INSERT statement using aVALUES clause. The function has no input parameters.
The result is a DECIMAL(31,0), regardless of the actual data type of thecorresponding identity column.
The value returned by the function is the value assigned to the identitycolumn of the table identified in the most recent single row INSERTstatement. The INSERT statement must contain a VALUES clause on a tablecontaining an identity column. The INSERT statement must also be issued atthe same level; that is, the value must available locally at the level it wasassigned, until it is replaced by the next assigned value. (A new level isinitiated each time a trigger or routine is invoked.)
The assigned value is either a value supplied by the user (if the identitycolumn is defined as GENERATED BY DEFAULT), or an identity valuegenerated by DB2.
The function returns a null value in the following situations:v When a single row INSERT statement with a VALUES clause has not been
issued at the current processing level for a table containing an identitycolumn.
v When a COMMIT or ROLLBACK of a unit of work has occurred since themost recent INSERT statement that assigned a value. (Unless automaticcommit is turned off, interfaces that automatically commit after eachstatement will return a null value when the function is invoked in separatestatements.)
The result of the function is not affected by the following:v A single row INSERT statement with a VALUES clause for a table without
an identity column.v A multiple row INSERT statement with a VALUES clause.v An INSERT statement with a fullselect.v A ROLLBACK TO SAVEPOINT statement.
Notes:
IDENTITY_VAL_LOCAL
376 SQL Reference, Volume 1
v Expressions in the VALUES clause of an INSERT statement are evaluatedprior to the assignments for the target columns of the INSERT statement.Thus, an invocation of an IDENTITY_VAL_LOCAL function inside theVALUES clause of an INSERT statement will use the most recently assignedvalue for an identity column from a previous INSERT statement. Thefunction returns the null value if no previous single row INSERT statementwith a VALUES clause for a table containing an identity column has beenexecuted within the same level as the IDENTITY_VAL_LOCAL function.
v The identity column value of the table for which the trigger is defined canbe determined within a trigger, by referencing the trigger transition variablefor the identity column.
v The result of invoking the IDENTITY_VAL_LOCAL function from withinthe trigger condition of an insert trigger is a null value.
v It is possible that multiple before or after insert triggers exist for a table. Inthis case, each trigger is processed separately, and identity values assignedby one triggered action are not available to other triggered actions using theIDENTITY_VAL_LOCAL function. This is true even though the multipletriggered actions are conceptually defined at the same level.
v It is not generally recommended to use the IDENTITY_VAL_LOCALfunction in the body of a before insert trigger. The result of invoking theIDENTITY_VAL_LOCAL function from within the triggered action of abefore insert trigger is the null value. The value for the identity column ofthe table for which the trigger is defined cannot be obtained by invokingthe IDENTITY_VAL_LOCAL function within the triggered action of abefore insert trigger. However, the value for the identity column can beobtained in the triggered action, by referencing the trigger transitionvariable for the identity column.
v The result of invoking the IDENTITY_VAL_LOCAL function from withinthe triggered action of an after insert trigger is the value assigned to anidentity column of the table identified in the most recent single rowINSERT statement invoked in the same triggered action that had a VALUESclause for a table containing an identity column. (This applies to both FOREACH ROW and FOR EACH STATEMENT after insert triggers.) If a singlerow INSERT statement with a VALUES clause for a table containing anidentity column was not executed within the same triggered action, prior tothe invocation of the IDENTITY_VAL_LOCAL function, then the functionreturns a null value.
v Since the results of the IDENTITY_VAL_LOCAL function are notdeterministic, the result of an invocation of the IDENTITY_VAL_LOCALfunction within the SELECT statement of a cursor can vary for each FETCHstatement.
v The assigned value is the value actually assigned to the identity column(that is, the value that would be returned on a subsequent SELECTstatement). This value is not necessarily the value provided in the VALUES
IDENTITY_VAL_LOCAL
Chapter 3. Functions 377
clause of the INSERT statement, or a value generated by DB2. The assignedvalue could be a value specified in a SET transition variable statement,within the body of a before insert trigger, for a trigger transition variableassociated with the identity column.
v The value returned by the function is unpredictable following a failedsingle row INSERT with a VALUES clause into a table with an identitycolumn. The value may be the value that would have been returned fromthe function had it been invoked prior to the failed INSERT, or it may bethe value that would have been assigned had the INSERT succeeded. Theactual value returned depends on the point of failure and is thereforeunpredictable.
Examples:
Example 1: Set the variable IVAR to the value assigned to the identity columnin the EMPLOYEE table. If this insert is the first into the EMPLOYEE table,then IVAR would have a value of 1.
CREATE TABLE EMPLOYEE(EMPNO INTEGER GENERATED ALWAYS AS IDENTITY,NAME CHAR(30),SALARY DECIMAL(5,2),DEPTNO SMALLINT)
Example 2: An IDENTITY_VAL_LOCAL function invoked in an INSERTstatement returns the value associated with the previous single row INSERTstatement, with a VALUES clause for a table with an identity column. Assumefor this example that there are two tables, T1 and T2. Both T1 and T2 have anidentity column named C1. DB2 generates values in sequence, starting with 1,for the C1 column in table T1, and values in sequence, starting with 10, forthe C1 column in table T2.
CREATE TABLE T1(C1 INTEGER GENERATED ALWAYS AS IDENTITY,C2 INTEGER)
CREATE TABLE T2(C1 DECIMAL(15,0) GENERATED BY DEFAULT AS IDENTITY
(START WITH 10),C2 INTEGER)
INSERT INTO T1 (C2) VALUES (5)
INSERT INTO T1 (C2) VALUES (6)
SELECT * FROM T1
which gives a result of:
IDENTITY_VAL_LOCAL
378 SQL Reference, Volume 1
C1 C2----------- ----------
1 52 6
and now, declaring the function for the variable IVAR:VALUES IDENTITY_VAL_LOCAL() INTO :IVAR
At this point, the IDENTITY_VAL_LOCAL function would return a value of 2in IVAR, because that was the value most recently assigned by DB2. Thefollowing INSERT statement inserts a single row into T2, where column C2gets a value of 2 from the IDENTITY_VAL_LOCAL function.
INSERT INTO T2 (C2) VALUES (IDENTITY_VAL_LOCAL())
SELECT * FROM T2WHERE C1 = DECIMAL(IDENTITY_VAL_LOCAL(),15,0)
returning a result of:C1 C2----------------- ----------
10. 2
Invoking the IDENTITY_VAL_LOCAL function after this insert results in avalue of 10, which is the value generated by DB2 for column C1 of T2.
In a nested environment involving a trigger, use the IDENTITY_VAL_LOCALfunction to retrieve the identity value assigned at a particular level, eventhough there might have been identity values assigned at lower levels.Assume that there are three tables, EMPLOYEE, EMP_ACT, and ACCT_LOG.There is an after insert trigger defined on EMPLOYEE that results inadditional inserts into the EMP_ACT and ACCT_LOG tables.
CREATE TABLE EMPLOYEE(EMPNO SMALLINT GENERATED ALWAYS AS IDENTITY (START WITH 1000),NAME CHAR(30),SALARY DECIMAL(5,2),DEPTNO SMALLINT);
CREATE TABLE EMP_ACT(ACNT_NUM SMALLINT GENERATED ALWAYS AS IDENTITY (START WITH 1),EMPNO SMALLINT);
CREATE TABLE ACCT_LOG(ID SMALLINT GENERATED ALWAYS AS IDENTITY (START WITH 100),ACNT_NUM SMALLINT,EMPNO SMALLINT);
CREATE TRIGGER NEW_HIREAFTER INSERT ON EMPLOYEEREFERENCING NEW AS NEW_EMPFOR EACH ROW MODE DB2SQL
IDENTITY_VAL_LOCAL
Chapter 3. Functions 379
BEGIN ATOMICINSERT INTO EMP_ACT (EMPNO)VALUES (NEW_EMP.EMPNO);INSERT INTO ACCT_LOG (ACNT_NUM EMPNO)VALUES (IDENTITY_VAL_LOCAL(), NEW_EMP.EMPNO);
END
The first triggered INSERT statement inserts a row into the EMP_ACT table.This INSERT statement uses a trigger transition variable for the EMPNOcolumn of the EMPLOYEE table, to indicate that the identity value for theEMPNO column of the EMPLOYEE table is to be copied to the EMPNOcolumn of the EMP_ACT table. The IDENTITY_VAL_LOCAL function couldnot be used to obtain the value assigned to the EMPNO column of theEMPLOYEE table. This is because an INSERT statement has not been issuedat this level of the nesting, and as such, if the IDENTITY_VAL_LOCALfunction were invoked in the VALUES clause of the INSERT for EMP_ACT,then it would return a null value. This INSERT statement for the EMP_ACTtable also results in the generation of a new identity column value for theACNT_NUM column.
A second triggered INSERT statement inserts a row into the ACCT_LOG table.This statement invokes the IDENTITY_VAL_LOCAL function to indicate thatthe identity value assigned to the ACNT_NUM column of the EMP_ACT tablein the previous INSERT statement in the triggered action is to be copied to theACNT_NUM column of the ACCT_LOG table. The EMPNO column isassigned the same value as the EMPNO column of EMPLOYEE table.
From the invoking application (that is, the level at which the INSERT toEMPLOYEE is issued), set the variable IVAR to the value assigned to theEMPNO column of the EMPLOYEE table by the original INSERT statement.
INSERT INTO EMPLOYEE (NAME, SALARY, DEPTNO)VALUES (’Rupert’, 989.99, 50);
The contents of the three tables after processing the original INSERT statementand all of the triggered actions are:
SELECT EMPNO, SUBSTR(NAME,10) AS NAME, SALARY, DEPTNOFROM EMPLOYEE;
EMPNO NAME SALARY DEPTNO----------- ----------- ---------------------------------- -----------
1000 Rupert 989.99 50
SELECT ACNT_NUM, EMPNOFROM EMP_ACT;
ACNT_NUM EMPNO----------- -----------
1 1000
IDENTITY_VAL_LOCAL
380 SQL Reference, Volume 1
SELECT * FROM ACCT_LOG;
ID ACNT_NUM EMPNO----------- ----------- -----------
100 1 1000
The result of the IDENTITY_VAL_LOCAL function is the most recentlyassigned value for an identity column at the same nesting level. Afterprocessing the original INSERT statement and all of the triggered actions, theIDENTITY_VAL_LOCAL function returns a value of 1000, because this is thevalue assigned to the EMPNO column of the EMPLOYEE table. The followingVALUES statement results in setting IVAR to 1000. The insert into theEMP_ACT table (which occurred after the insert into the EMPLOYEE tableand at a lower nesting level) has no affect on what is returned by thisinvocation of the IDENTITY_VAL_LOCAL function.
VALUES IDENTITY_VAL_LOCAL() INTO :IVAR;
Related samples:
v “fnuse.out -- HOW TO USE BUILT-IN SQL FUNCTIONS (C)”v “fnuse.sqc -- How to use built-in SQL functions (C)”v “fnuse.out -- HOW TO USE FUNCTIONS (C++)”v “fnuse.sqC -- How to use built-in SQL functions (C++)”
IDENTITY_VAL_LOCAL
Chapter 3. Functions 381
INSERT
�� INSERT ( expression1 , expression2 , expression3 , expression4 ) ��
The schema is SYSFUN.
Returns a string where expression3 bytes have been deleted from expression1beginning at expression2 and where expression4 has been inserted intoexpression1 beginning at expression2. If the length of the result string exceedsthe maximum for the return type, an error occurs (SQLSTATE 38552).
The first argument is a character string or a binary string type. The secondand third arguments must be a numeric value with a data type of SMALLINTor INTEGER. If the first argument is a character string, then the fourthargument must also be a character string. If the first argument is a binarystring, then the fourth argument must be a binary string. For a VARCHAR themaximum length is 4 000 bytes and for a CLOB or a binary string themaximum length is 1 048 576 bytes. For the first and fourth arguments, CHARis converted to VARCHAR and LONG VARCHAR to CLOB(1M), for secondand third arguments SMALLINT is converted to INTEGER for processing bythe function.
The result is based on the argument types as follows:v VARCHAR(4000) if both the first and fourth arguments are VARCHAR (not
exceeding 4 000 bytes) or CHARv CLOB(1M) if either the first or fourth argument is CLOB or LONG
VARCHARv BLOB(1M) if both first and fourth arguments are BLOB.
The result can be null; if any argument is null, the result is the null value.
Example:v Delete one character from the word ’DINING’ and insert ’VID’, both
beginning at the third character.VALUES CHAR(INSERT(’DINING’, 3, 1, ’VID’), 10)
This example returns the following:1----------DIVIDING
INSERT
382 SQL Reference, Volume 1
As mentioned, the output of the INSERT function is VARCHAR(4000). Inthis example, the function CHAR has been used to limit the output ofINSERT to 10 bytes. The starting location of a particular string can be foundusing the LOCATE function.
Related reference:
v “LOCATE” on page 393
INSERT
Chapter 3. Functions 383
INTEGER
�� INTEGERINT
( numeric-expressioncharacter-expressiondate-expressiontime-expression
) ��
The schema is SYSIBM.
The INTEGER function returns an integer representation of a number,character string, date, or time in the form of an integer constant.
numeric-expressionAn expression that returns a value of any built-in numeric data type.
If the argument is a numeric-expression, the result is the same number thatwould occur if the argument were assigned to a large integer column orvariable. If the whole part of the argument is not within the range ofintegers, an error occurs. The decimal part of the argument is truncated ifpresent.
character-expressionAn expression that returns a character string value of length not greaterthan the maximum length of a character constant. Leading and trailingblanks are eliminated and the resulting string must conform to the rulesfor forming an SQL integer constant (SQLSTATE 22018). The characterstring cannot be a long string.
If the argument is a character-expression, the result is the same number thatwould occur if the corresponding integer constant were assigned to alarge integer column or variable.
date-expressionAn expression that returns a value of the DATE data type. The result is anINTEGER value representing the date as yyyymmdd.
time-expressionAn expression that returns a value of the TIME data type. The result is anINTEGER value representing the time as hhmmss.
The result of the function is a large integer. If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
Examples:v Using the EMPLOYEE table, select a list containing salary (SALARY)
divided by education level (EDLEVEL). Truncate any decimal in the
INTEGER
384 SQL Reference, Volume 1
calculation. The list should also contain the values used in the calculationand employee number (EMPNO). The list should be in descending order ofthe calculated value.
SELECT INTEGER (SALARY / EDLEVEL), SALARY, EDLEVEL, EMPNOFROM EMPLOYEEORDER BY 1 DESC
v Using the EMPLOYEE table, select the EMPNO column in integer form forfurther processing in the application.
SELECT INTEGER(EMPNO) FROM EMPLOYEE
v Assume that the column BIRTHDATE (date) has an internal valueequivalent to ’1964-07-20’.
INTEGER(BIRTHDATE)
results in the value 19 640 720.v Assume that the column STARTTIME (time) has an internal value
equivalent to ’12:03:04’.INTEGER(STARTTIME)
results in the value 120 304.
INTEGER
Chapter 3. Functions 385
JULIAN_DAY
�� JULIAN_DAY ( expression ) ��
The schema is SYSFUN.
Returns an integer value representing the number of days from January 1,4712B.C. (the start of Julian date calendar) to the date value specified in theargument.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
JULIAN_DAY
386 SQL Reference, Volume 1
LCASE or LOWER
�� LCASE ( string-expression )LOWER
��
The schema is SYSIBM. (The SYSFUN version of this function continues to beavailable with support for LONG VARCHAR and CLOB arguments.)
The LCASE or LOWER function returns a string in which all the SBCScharacters have been converted to lowercase characters (that is, the charactersA-Z will be translated to the characters a-z, and characters with diacriticalmarks will be translated to their lower case equivalents if they exist. Forexample, in code page 850, É maps to é). Since not all characters aretranslated, LCASE(UCASE(string-expression)) does not necessarily return thesame result as LCASE(string-expression).
The argument must be an expression whose value is a CHAR or VARCHARdata type.
The result of the function has the same data type and length attribute of theargument. If the argument can be null, the result can be null; if the argumentis null, the result is the null value.
Notes:
This function has been extended to recognize the lowercase and uppercaseproperties of a Unicode character. In a Unicode database, all Unicodecharacters correctly convert to lowercase.
Example:
Ensure that the characters in the value of column JOB in the EMPLOYEE tableare returned in lowercase characters.
SELECT LCASE(JOB)FROM EMPLOYEE WHERE EMPNO = ’000020’;
The result is the value ’manager’.
Related reference:
v “LCASE (SYSFUN schema)” on page 388
LCASE or LOWER
Chapter 3. Functions 387
LCASE (SYSFUN schema)
�� LCASE ( expression ) ��
The schema is SYSFUN.
Returns a string in which all the characters A-Z have been converted to thecharacters a-z (characters with diacritical marks are not converted). Note thatLCASE(UCASE(string)) will therefore not necessarily return the same result asLCASE(string).
The argument can be of any built-in character string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB the maximum length is1 048 576 bytes.
The result of the function is:v VARCHAR(4000) if the argument is VARCHAR (not exceeding 4 000 bytes)
or CHARv CLOB(1M) if the argument is CLOB or LONG VARCHAR
The result can be null; if the argument is null, the result is the null value.
LCASE (SYSFUN schema)
388 SQL Reference, Volume 1
LEFT
�� LEFT ( expression1 , expression2 ) ��
The schema is SYSFUN.
Returns a string consisting of the leftmost expression2 bytes in expression1. Theexpression1 value is effectively padded on the right with the necessary numberof blank characters so that the specified substring of expression1 always exists.
The first argument is a character string or binary string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB or a binary string themaximum length is 1 048 576 bytes. The second argument must be of datatype INTEGER or SMALLINT.
The result of the function is:v VARCHAR(4000) if the argument is VARCHAR (not exceeding 4 000 bytes)
or CHARv CLOB(1M) if the argument is CLOB or LONG VARCHARv BLOB(1M) if the argument is BLOB.
The result can be null; if any argument is null, the result is the null value.
LEFT
Chapter 3. Functions 389
LENGTH
�� LENGTH ( expression ) ��
The schema is SYSIBM.
The LENGTH function returns the length of a value.
The argument can be an expression that returns a value of any built-in datatype.
The result of the function is a large integer. If the argument can be null, theresult 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 nullindicator byte of column arguments that allow null values. The length ofstrings includes blanks but does not include the length control field ofvarying-length strings. The length of a varying-length string is the actuallength, not the maximum length.
The length of a graphic string is the number of DBCS characters. The lengthof all other values is the number of bytes used to represent the value:v 2 for small integerv 4 for large integerv (p/2)+1 for decimal numbers with precision p
v The length of the string for binary stringsv The length of the string for character stringsv 4 for single-precision floating-pointv 8 for double-precision floating-pointv 4 for datev 3 for timev 10 for timestamp
Examples:v Assume the host variable ADDRESS is a varying length character string
with a value of '895 Don Mills Road'.LENGTH(:ADDRESS)
Returns the value 18.v Assume that START_DATE is a column of type DATE.
LENGTH(START_DATE)
LENGTH
390 SQL Reference, Volume 1
Returns the value 4.v This example returns the value 10.
LENGTH(CHAR(START_DATE, EUR))
LENGTH
Chapter 3. Functions 391
LN
�� LN ( expression ) ��
The schema is SYSFUN.
Returns the natural logarithm of the argument (same as LOG).
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
LN
392 SQL Reference, Volume 1
LOCATE
�� LOCATE ( expression1 , expression2 ), expression3
��
The schema is SYSFUN.
Returns the starting position of the first occurrence of expression1 withinexpression2. If the optional expression3 is specified, it indicates the characterposition in expression2 at which the search is to begin. If expression1 is notfound within expression2, the value 0 is returned.
If the first argument is a character string, then the second argument must be acharacter string. For a VARCHAR the maximum length is 4 000 bytes and fora CLOB the maximum length is 1 048 576 bytes. If the first argument is abinary string, then the second argument must be a binary string with amaximum length of 1 048 576 bytes. The third argument must be is INTEGERor SMALLINT.
The result of the function is INTEGER. The result can be null; if any argumentis null, the result is the null value.
Example:v Find the location of the letter ’N’ (first occurrence) in the word ’DINING’.
VALUES LOCATE (’N’, ’DINING’)
This example returns the following:1-----------
3
LOCATE
Chapter 3. Functions 393
LOG
�� LOG ( expression ) ��
The schema is SYSFUN.
Returns the natural logarithm of the argument (same as LN).
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
LOG
394 SQL Reference, Volume 1
LOG10
�� LOG10 ( expression ) ��
The schema is SYSFUN.
Returns the base 10 logarithm of the argument.
The argument can be of any built-in numeric type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
LOG10
Chapter 3. Functions 395
LONG_VARCHAR
�� LONG_VARCHAR ( character-string-expression ) ��
The schema is SYSIBM.
The LONG_VARCHAR function returns a LONG VARCHAR representation ofa character string data type.
character-string-expressionAn expression that returns a value that is a character string with amaximum length of 32 700 bytes.
The result of the function is a LONG VARCHAR. If the argument can be null,the result can be null; if the argument is null, the result is the null value.
LONG_VARCHAR
396 SQL Reference, Volume 1
LONG_VARGRAPHIC
�� LONG_VARGRAPHIC ( graphic-expression ) ��
The schema is SYSIBM.
The LONG_VARGRAPHIC function returns a LONG VARGRAPHICrepresentation of a double-byte character string.
graphic-expressionAn expression that returns a value that is a graphic string with a maximumlength of 16 350 double byte characters.
The result of the function is a LONG VARGRAPHIC. If the argument can benull, the result can be null; if the argument is null, the result is the null value.
LONG_VARGRAPHIC
Chapter 3. Functions 397
LTRIM
�� LTRIM ( string-expression ) ��
The schema is SYSIBM. (The SYSFUN version of this function continues to beavailable with support for LONG VARCHAR and CLOB arguments.)
The LTRIM function removes blanks from the beginning of string-expression.
The argument can be a CHAR, VARCHAR, GRAPHIC, or VARGRAPHIC datatype.v If the argument is a graphic string in a DBCS or EUC database, then the
leading double byte blanks are removed.v If the argument is a graphic string in a Unicode database, then the leading
UCS-2 blanks are removed.v Otherwise, the leading single byte blanks are removed.
The result data type of the function is:v VARCHAR if the data type of string-expression is VARCHAR or CHARv VARGRAPHIC if the data type of string-expression is VARGRAPHIC or
GRAPHIC
The length parameter of the returned type is the same as the length parameterof the argument data type.
The actual length of the result for character strings is the length ofstring-expression minus the number of bytes removed for blank characters. Theactual length of the result for graphic strings is the length (in number ofdouble byte characters) of string-expression minus the number of double byteblank characters removed. If all of the characters are removed, the result is anempty, varying-length string (length is zero).
If the argument can be null, the result can be null; if the argument is null, theresult is the null value.
Example:
Assume that host variable HELLO is defined as CHAR(9) and has a value of ’Hello’.
VALUES LTRIM(:HELLO)
The result is ’Hello’.
Related reference:
LTRIM
398 SQL Reference, Volume 1
v “LTRIM (SYSFUN schema)” on page 400
LTRIM
Chapter 3. Functions 399
LTRIM (SYSFUN schema)
�� LTRIM ( expression ) ��
The schema is SYSFUN.
Returns the characters of the argument with leading blanks removed.
The argument can be of any built-in character string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB the maximum length is1 048 576 bytes.
The result of the function is:v VARCHAR(4000) if the argument is VARCHAR (not exceeding 4 000 bytes)
or CHARv CLOB(1M) if the argument is CLOB or LONG VARCHAR.
The result can be null; if the argument is null, the result is the null value.
LTRIM (SYSFUN schema)
400 SQL Reference, Volume 1
MICROSECOND
�� MICROSECOND ( expression ) ��
The schema is SYSIBM.
The MICROSECOND function returns the microsecond part of a value.
The argument must be a timestamp, timestamp duration or a valid characterstring representation of a timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a timestamp or a valid string representation of a
timestamp:– The integer ranges from 0 through 999 999.
v If the argument is a duration:– The result reflects the microsecond part of the value which is an integer
between −999 999 through 999 999. A nonzero result has the same sign asthe argument.
Example:v Assume a table TABLEA contains two columns, TS1 and TS2, of type
TIMESTAMP. Select all rows in which the microseconds portion of TS1 isnot zero and the seconds portion of TS1 and TS2 are identical.
SELECT * FROM TABLEAWHERE MICROSECOND(TS1) <> 0
ANDSECOND(TS1) = SECOND(TS2)
MICROSECOND
Chapter 3. Functions 401
MIDNIGHT_SECONDS
�� MIDNIGHT_SECONDS ( expression ) ��
The schema is SYSFUN.
Returns an integer value in the range 0 to 86 400 representing the number ofseconds between midnight and the time value specified in the argument.
The argument must be a time, timestamp, or a valid character stringrepresentation of a time or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
Examples:v Find the number of seconds between midnight and 00:10:10, and midnight
and 13:10:10.VALUES (MIDNIGHT_SECONDS(’00:10:10’), MIDNIGHT_SECONDS(’13:10:10’))
This example returns the following:1 2----------- -----------
610 47410
Since a minute is 60 seconds, there are 610 seconds between midnight andthe specified time. The same follows for the second example. There are 3600seconds in an hour, and 60 seconds in a minute, resulting in 47410 secondsbetween the specified time and midnight.
v Find the number of seconds between midnight and 24:00:00, and midnightand 00:00:00.
VALUES (MIDNIGHT_SECONDS(’24:00:00’), MIDNIGHT_SECONDS(’00:00:00’))
This example returns the following:1 2----------- -----------
86400 0
Note that these two values represent the same point in time, but returndifferent MIDNIGHT_SECONDS values.
MIDNIGHT_SECONDS
402 SQL Reference, Volume 1
MINUTE
�� MINUTE ( expression ) ��
The schema is SYSIBM.
The MINUTE function returns the minute part of a value.
The argument must be a time, timestamp, time duration, timestamp durationor a valid character string representation of a time or timestamp that isneither a CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a time, timestamp or valid string representation of a time
or timestamp:– The result is the minute part of the value, which is an integer between 0
and 59.v 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:v Using the CL_SCHED sample table, select all classes with a duration less
than 50 minutes.SELECT * FROM CL_SCHED
WHERE HOUR(ENDING - STARTING) = 0AND
MINUTE(ENDING - STARTING) < 50
MINUTE
Chapter 3. Functions 403
MOD
�� MOD ( expression , expression ) ��
The schema is SYSFUN.
Returns the remainder of the first argument divided by the second argument.The result is negative only if first argument is negative.
The result of the function is:v SMALLINT if both arguments are SMALLINTv INTEGER if one argument is INTEGER and the other is INTEGER or
SMALLINTv BIGINT if one argument is BIGINT and the other argument is BIGINT,
INTEGER or SMALLINT.
The result can be null; if any argument is null, the result is the null value.
MOD
404 SQL Reference, Volume 1
MONTH
�� MONTH ( expression ) ��
The schema is SYSIBM.
The MONTH function returns the month part of a value.
The argument must be a date, timestamp, date duration, timestamp durationor a valid character string representation of a date or timestamp that is neithera CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a date, timestamp, or a valid string representation of a
date or timestamp:– The result is the month part of the value, which is an integer between 1
and 12.v 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:v Select all rows from the EMPLOYEE table for people who were born
(BIRTHDATE) in DECEMBER.SELECT * FROM EMPLOYEE
WHERE MONTH(BIRTHDATE) = 12
MONTH
Chapter 3. Functions 405
MONTHNAME
�� MONTHNAME ( expression ) ��
The schema is SYSFUN.
Returns a mixed case character string containing the name of month (e.g.January) for the month portion of the argument, based on the locale when thedatabase was started.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is VARCHAR(100). The result can be null; if theargument is null, the result is the null value.
MONTHNAME
406 SQL Reference, Volume 1
MQPUBLISH
�� MQPUBLISH (publisher-service ,
service-policy ,
msg-data �
�, topic
(1), correl-id
) ��
Notes:
1 The correl-id cannot be specified unless a service and a policy are alsospecified.
The schema is DB2MQ.
The MQPUBLISH function publishes data to MQSeries. This function requiresthe installation of either MQSeries Publish/Subscribe or MQSeries Integrator.For more details, visit http://www.ibm.com/software/MQSeries.
The MQPUBLISH function publishes the data contained in msg-data to theMQSeries publisher specified in publisher-service, and using the quality ofservice policy defined by service-policy. An optional topic for the message canbe specified, and an optional user-defined message correlation identifier mayalso be specified. The function returns a value of ’1’ if successful or a ’0’ ifunsuccessful.
publisher-serviceA string containing the logical MQSeries destination where the message isto be sent. If specified, the publisher-service must refer to a publisherService Point defined in the AMT.XML repository file. A service point is alogical end-point from which a message is sent or received. Service pointdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifpublisher-service is not specified, the DB2.DEFAULT.PUBLISHER will beused. The maximum size of publisher-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy to be used inhandling of this message. If specified, the service-policy must refer to aPolicy defined in the AMT.XML repository file. A Service Policy defines aset of quality of service options that should be applied to this messagingoperation. These options include message priority and messagepersistence. See the MQSeries Application Messaging Interface manual for
MQPUBLISH
Chapter 3. Functions 407
further details. If service-policy is not specified, the defaultDB2.DEFAULT.POLICY will be used. The maximum size of service-policy is48 bytes.
msg-dataA string expression containing the data to be sent via MQSeries. Themaximum size if the string of type VARCHAR is 4000 bytes. If the stringis a CLOB, it can be up to 1MB in size.
topicA string expression containing the topic for the message publication. If notopic is specified, none will be associated with the message. Themaximum size of topic is 40 bytes. Multiple topics can be specified in onestring (up to 40 characters long). Each topic must be separated by a colon.For example, ″t1:t2:the third topic″ indicates that the message is associatedwith all three topics: t1, t2, and ″the third topic″.
correl-idAn optional string expression containing a correlation identifier to beassociated with this message. The correl-id is often specified in request andreply scenarios to associate requests with replies. If not specified, nocorrelation ID will be added to the message. The maximum size ofcorrel-id is 24 bytes.
Examples
Example 1: This example publishes the string ″Testing 123″ to the defaultpublisher service (DB2.DEFAULT.PUBLISHER) using the default policy(DB2.DEFAULT.POLICY). No correlation identifier or topic is specified for themessage.
VALUES MQPUBLISH(’Testing 123’)
Example 2: This example publishes the string ″Testing 345″ to the publisherservice ″MYPUBLISHER″ under the topic ″TESTS″. The default policy is usedand no correlation identifier is specified.
VALUES MQPUBLISH(’MYPUBLISHER’,’Testing 345’, ’TESTS’)
Example 3: This example publishes the string ″Testing 678″ to the publisherservice ″MYPUBLISHER″ using the policy ″MYPOLICY″ with a correlationidentifier of ″TEST1″. The message is published with topic ″TESTS″.
VALUES MQPUBLISH(’MYPUBLISHER’,’MYPOLICY’,’Testing 678’,’TESTS’,’TEST1’)
Example 4: This example publishes the string ″Testing 901″ to the publisherservice ″MYPUBLISHER″ under the topic ″TESTS″ using the default policy(DB2.DEFAULT.POLICY) and no correlation identifier.
VALUES MQPUBLISH(’Testing 901’,’TESTS’)
MQPUBLISH
408 SQL Reference, Volume 1
All examples return the value ’1’ if successful.
MQPUBLISH
Chapter 3. Functions 409
MQREAD
�� MQREAD (receive-service
, service-policy
) ��
The schema is MQDB2.
The MQREAD function returns a message from the MQSeries locationspecified by receive-service, using the quality of service policy defined inservice-policy. Executing this operation does not remove the message from thequeue associated with receive-service, but instead returns the message at thehead of the queue. The result of the function is VARCHAR(4000). If nomessages are available to be returned, the result is the null value.
receive-serviceA string containing the logical MQSeries destination from where themessage is to be received. If specified, the receive-service must refer to aService Point defined in the AMT.XML repository file. A service point is alogical end-point from where a message is sent or received. Service pointsdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, then the DB2.DEFAULT.SERVICE will beused. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in handlingthis message. If specified, the service-policy must refer to a Policy definedin the AMT.XML repository file. A Service Policy defines a set of qualityof service options that should be applied to this messaging operation.These options include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
Examples:
Example 1: This example reads the message at the head of the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY).
VALUES MQREAD()
Example 2: This example reads the message at the head of the queue specifiedby the service ″MYSERVICE″ using the default policy(DB2.DEFAULT.POLICY).
VALUES MQREAD(’MYSERVICE’)
MQREAD
410 SQL Reference, Volume 1
Example 3: This example reads the message at the head of the queue specifiedby the service ″MYSERVICE″, and using the policy ″MYPOLICY″.
VALUES MQREAD(’MYSERVICE’,’MYPOLICY’)
All of these examples return the contents of the message as aVARCHAR(4000) if successful. If no messages are available, the result is thenull value.
MQREAD
Chapter 3. Functions 411
MQREADCLOB
�� MQREADCLOB (receive-service
, service-policy
) ��
The schema is DB2MQ.
The MQREADCLOB function returns a message from the MQSeries locationspecified by receive-service, using the quality of service policy defined inservice-policy. Executing this operation does not remove the message from thequeue associated with receive-service, but instead returns the message at thehead of the queue. The return value is a CLOB of 1MB maximum length,containing the message. If no messages are available to be returned, a NULLis returned.
receive-serviceA string containing the logical MQSeries destination from where themessage is to be received. If specified, the receive-service must refer to aService Point defined in the AMT.XML repository file. A service point is alogical end-point from where a message is sent or received. Service pointsdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, then the DB2.DEFAULT.SERVICE will beused. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in handlingthis message. If specified, the service-policy must refer to a Policy definedin the AMT.XML repository file. A Service Policy defines a set of qualityof service options that should be applied to this messaging operation.These options include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
Examples:
Example 1: This example reads the message at the head of the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY).
VALUES MQREADCLOB()
Example 2: This example reads the message at the head of the queue specifiedby the service ″MYSERVICE″ using the default policy(DB2.DEFAULT.POLICY).
MQREADCLOB
412 SQL Reference, Volume 1
VALUES MQREADCLOB(’MYSERVICE’)
Example 3: This example reads the message at the head of the queue specifiedby the service ″MYSERVICE″, and using the policy ″MYPOLICY″.
VALUES MQREADCLOB(’MYSERVICE’,’MYPOLICY’)
All of these examples return the contents of the message as a CLOB with amaximum size of 1MB, if successful. If no messages are available, then aNULL is returned.
MQREADCLOB
Chapter 3. Functions 413
MQRECEIVE
�� MQRECEIVE ( )receive-service
, service-policy, correl-id
��
The schema is MQDB2.
The MQRECEIVE function returns a message from the MQSeries locationspecified by receive-service, using the quality of service policy service-policy.Performing this operation removes the message from the queue associatedwith receive-service. If the correl-id is specified, then the first message with amatching correlation identifier will be returned. If correl-id is not specified,then the message at the head of the queue will be returned. The result of thefunction is VARCHAR(4000). If no messages are available to be returned, theresult is the null value.
receive-serviceA string containing the logical MQSeries destination from which themessage is received. If specified, the receive-service must refer to a ServicePoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointsdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, the DB2.DEFAULT.SERVICE is used. Themaximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy to be used in thehandling of this message. If specified, service-policy must refer to a policydefined in the AMT XML repository file. (A service policy defines a set ofquality of service options that should be applied to this messagingoperation. These options include message priority and messagepersistence. See the MQSeries Application Messaging Interface manual forfurther details.) If service-policy is not specified, the defaultDB2.DEFAULT.POLICY is used. The maximum size of service-policy is 48bytes.
correl-idA string containing an optional correlation identifier to be associated withthis message. The correl-id is often specified in request and reply scenariosto associate requests with replies. If not specified, no correlation id will bespecified. The maximum size of correl-id is 24 bytes.
Examples:
MQRECEIVE
414 SQL Reference, Volume 1
Example 1: This example receives the message at the head of the queuespecified by the default service (DB2.DEFAULT.SERVICE), using the defaultpolicy (DB2.DEFAULT.POLICY).
VALUES MQRECEIVE()
Example 2: This example receives the message at the head of the queuespecified by the service ″MYSERVICE″ using the default policy(DB2.DEFAULT.POLICY).
VALUES MQRECEIVE(’MYSERVICE’)
Example 3: This example receives the message at the head of the queuespecified by the service ″MYSERVICE″ using the policy ″MYPOLICY″.
VALUES MQRECEIVE(’MYSERVICE’,’MYPOLICY’)
Example 4: This example receives the first message with a correlation id thatmatches ’1234’ from the head of the queue specified by the service″MYSERVICE″ using the policy ″MYPOLICY″.
VALUES MQRECEIVE(’MYSERVICE’,’MYPOLICY’,’1234’)
All these examples return the contents of the message as a VARCHAR(4000) ifsuccessful. If no messages are available, a NULL will be returned.
MQRECEIVE
Chapter 3. Functions 415
MQRECEIVECLOB
�� MQRECEIVECLOB �
� ( )receive-service
, service-policy, correl-id
��
The schema is DB2MQ.
The MQRECEIVECLOB function returns a message from the MQSerieslocation specified by receive-service, using the quality of service policyservice-policy. Performing this operation removes the message from the queueassociated with receive-service. If the correl-id is specified, then the first messagewith a matching correlation identifier will be returned. If correl-id is notspecified, then the message at the head of the queue will be returned. Thereturn value is a CLOB with a maximum length of 1MB containing themessage. If no messages are available to be returned, a NULL is returned.
receive-serviceA string containing the logical MQSeries destination from which themessage is received. If specified, the receive-service must refer to a ServicePoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointsdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, the DB2.DEFAULT.SERVICE is used. Themaximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy to be used in thehandling of this message. If specified, the service-policy must refer to apolicy defined in the AMT.XML repository file. (A service policy defines aset of quality of service options that should be applied to this messagingoperation. These options include message priority and messagepersistence. See the MQSeries Application Messaging Interface manual forfurther details.) If service-policy is not specified, the defaultDB2.DEFAULT.POLICY is used. The maximum size of service-policy is 48bytes.
correl-idA string containing an optional correlation identifier to be associated withthis message. The correl-id is often specified in request and reply scenariosto associate requests with replies. If not specified, no correlation id will beused. The maximum size of correl-id is 24 bytes.
MQRECEIVECLOB
416 SQL Reference, Volume 1
Examples:
Example 1: This example receives the message at the head of the queuespecified by the default service (DB2.DEFAULT.SERVICE), using the defaultpolicy (DB2.DEFAULT.POLICY).
VALUES MQRECEIVECLOB()
Example 2: This example receives the message at the head of the queuespecified by the service ″MYSERVICE″ using the default policy(DB2.DEFAULT.POLICY).
VALUES MQRECEIVECLOB(’MYSERVICE’)
Example 3: This example receives the message at the head of the queuespecified by the service ″MYSERVICE″ using the policy ″MYPOLICY″.
VALUES MQRECEIVECLOB(’MYSERVICE’,’MYPOLICY’)
Example 4: This example receives the first message with a correlation ID thatmatches ’1234’ from the head of the queue specified by the service″MYSERVICE″ using the policy ″MYPOLICY″.
VALUES MQRECEIVECLOB(’MYSERVICE’,MYPOLICY’,’1234’)
All these examples return the contents of the message as a CLOB with amaximum size of 1MB, if successful. If no messages are available, a NULLwill be returned.
MQRECEIVECLOB
Chapter 3. Functions 417
MQSEND
�� MQSEND (send-service ,
service-policy ,
msg-data �
�(1)
, correl-id
) ��
Notes:
1 The correl-id cannot be specified unless a service and a policy are alsospecified.
The schema is DB2MQ.
The MQSEND function sends the data contained in msg-data to the MQSerieslocation specified by send-service, using the quality of service policy defined byservice-policy. An optional user defined message correlation identifier may bespecified by correl-id. The function returns a value of ’1’ if successful or a ’0’ ifunsuccessful.
msg-dataA string expression containing the data to be sent via MQSeries. Themaximum size is 4000 bytes if the data is of type VARCHAR, and 1MB ifthe data is of type CLOB.
send-serviceA string containing the logical MQSeries destination where the message isto be sent. If specified, the send-service refers to a service point defined inthe AMT.XML repository file. A service point is a logical end-point fromwhich a message may be sent or received. Service point definitionsinclude the name of the MQSeries Queue Manager and Queue. See theMQSeries Application Messaging Interface manual for further details. Ifsend-service is not specified, the value of DB2.DEFAULT.SERVICE is used.The maximum size of send-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in handling ofthis message. If specified, the service-policy must refer to a service policydefined in the AMT XML repository file. A Service Policy defines a set ofquality of service options that should be applied to this messagingoperation. These options include message priority and messagepersistence. See the MQSeries Application Messaging Interface manual forfurther details. If service-policy is not specified, a default value ofDB2.DEFAULT.POLICY will be used. The maximum size of service-policy is48 bytes.
MQSEND
418 SQL Reference, Volume 1
correl-idAn optional string containing a correlation identifier associated with thismessage. The correl-id is often specified in request and reply scenarios toassociate requests with replies. If not specified, no correlation ID will besent. The maximum size of correl-id is 24 bytes.
Examples:
Example 1: This example sends the string ″Testing 123″ to the default service(DB2.DEFAULT.SERVICE), using the default policy (DB2.DEFAULT.POLICY),with no correlation identifier.
VALUES MQSEND(’Testing 123’)
Example 2: This example sends the string ″Testing 345″ to the service″MYSERVICE″, using the policy ″MYPOLICY″, with no correlation identifier.
VALUES MQSEND(’MYSERVICE’,’MYPOLICY’,’Testing 345’)
Example 3: This example sends the string ″Testing 678″ to the service″MYSERVICE″, using the policy ″MYPOLICY″, with correlation identifier″TEST3″.
VALUES MQSEND(’MYSERVICE’,’MYPOLICY’,’Testing 678’,’TEST3’)
Example 4: This example sends the string ″Testing 901″ to the service″MYSERVICE″, using the default policy (DB2.DEFAULT.POLICY), and nocorrelation identifier.
VALUES MQSEND(’MYSERVICE’,’Testing 901’)
All examples return a scalar value of ’1’ if successful.
MQSEND
Chapter 3. Functions 419
MQSUBSCRIBE
�� MQSUBSCRIBE (subscriber-service ,
service-policy ,
topic ) ��
The schema is MQDB2.
The MQSUBSCRIBE function is used to register interest in MQSeries messagespublished on a specified topic. The subscriber-service specifies a logicaldestination for messages that match the specified topic. Messages that matchtopic will be placed on the queue defined by subscriber-service and can be reador received through a subsequent call to MQREAD, MQRECEIVE,MQREADALL, or MQRECEIVEALL. This function requires the installationand configuration of an MQSeries based publish and subscribe system, suchas MQSeries Integrator or MQSeries Publish/Subscribe. For more details, visithttp://www.ibm.com/software/MQSeries.
The function returns a value of ’1’ if successful or a ’0’ if unsuccessful.Successfully executing this function will cause the publish and subscribeserver to forward messages matching the topic to the service point defined bysubscriber-service.
subscriber-serviceA string containing the logical MQSeries subscription point to wheremessages matching topic will be sent. If specified, the subscriber-servicemust refer to a Subscribers Service Point defined in the AMT.XMLrepository file. Service points definitions include the name of theMQSeries Queue Manager and Queue. See the MQSeries ApplicationMessaging Interface manual for further details. If subscriber-service is notspecified, then the DB2.DEFAULT.SUBSCRIBER will be used instead. Themaximum size of subscriber-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy to be used inhandling the message. If specified, the service-policy must refer to a Policydefined in the AMT.XML repository file. A Service Policy defines a set ofquality of service options to be applied to this messaging operation. Theseoptions include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used instead. The maximum size of service-policy is 48 bytes.
topicA string defining the types of messages to receive. Only messagespublished with the specified topics will be received by this subscription.Multiple subscriptions may coexist. The maximum size of topic is 40
MQSUBSCRIBE
420 SQL Reference, Volume 1
bytes. Multiple topics can be specified in one string (up to 40 bytes long).Each topic must be separated by a colon. For example, ″t1:t2:the thirdtopic″ indicates that the message is associated with all three topics: t1, t2,and ″the third topic″.
Examples:
Example 1: This example registers an interest in messages containing the topic″Weather″. The default subscriber-service (DB2.DEFAULT.SUBSCRIBER) isregistered as the subscriber and the default service-policy(DB2.DEFAULT.POLICY) specifies the quality of service.
VALUES MQSUBSCRIBE(’Weather’)
Example 2: This example demonstrates a subscriber registering interest inmessages containing ″Stocks″. The subscriber registers as″PORTFOLIO-UPDATES″ with policy ″BASIC-POLICY″.
VALUES MQSUBSCRIBE(’PORTFOLIO-UPDATES’,’BASIC-POLICY’,’Stocks’)
All examples return a scalar value of ’1’ if successful.
MQSUBSCRIBE
Chapter 3. Functions 421
MQUNSUBSCRIBE
�� MQUNSUBSCRIBE (subscriber-service ,
service-policy ,
topic ) ��
The schema is MQDB2.
The MQUNSUBSCRIBE function is used to unregister an existing messagesubscription. The subscriber-service, service-policy, and topic are used to identifywhich subscription is canceled. This function requires the installation andconfiguration of an MQSeries based publish and subscribe system, such asMQSeries Integrator or MQSeries Publish/Subscribe. For more details, visithttp://www.ibm.com/software/MQSeries.
The function returns a value of ’1’ if successful or a ’0’ if unsuccessful. Theresult of successfully executing this function is that the publish and subscribeserver will remove the subscription defined by the given parameters.Messages with the specified topic will no longer be sent to the logicaldestination defined by subscriber-service.
subscriber-serviceIf specified, the subscriber-service must refer to a Subscriber Service Pointdefined in the AMT.XML repository file. Service point definitions includethe name of the MQSeries Queue Manager and Queue. See the MQSeriesApplication Messaging Interface manual for further details. Ifsubscriber-service is not specified, then the DB2.DEFAULT.SUBSCRIBERvalue is used. The maximum size of subscriber-service is 48 bytes.
service-policyIf specified, the service-policy must refer to a Policy defined in theAMT.XML repository file. A Service Policy defines a set of quality ofservice options to be applied to this messaging operation. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
topicA string specifying the subject of messages that are not to be received. Themaximum size of topic is 40 bytes. Multiple topics can be specified in onestring (up to 40 bytes long). Each topic must be separated by a colon. Forexample, ″t1:t2:the third topic″ indicates that the message is associatedwith all three topics: t1, t2, and ″the third topic″.
Examples:
MQUNSUBSCRIBE
422 SQL Reference, Volume 1
Example 1: This example cancels an interest in messages containing the topic″Weather″. The default subscriber-service (DB2.DEFAULT.SUBSCRIBER) isregistered as the unsubscriber and the default service-policy(DB2.DEFAULT.POLICY) specifies the quality of service.
VALUES MQUNSUBSCRIBE(’Weather’)
Example 2: This example demonstrates a subscriber canceling an interest inmessages containing ″Stocks″. The subscriber is registered as″PORTFOLIO-UPDATES″ with policy ″BASIC-POLICY″.
VALUES MQUNSUBSCRIBE(’PORTFOLIO-UPDATES’,’BASIC-POLICY’,’Stocks’)
These examples return a scalar value of ’1’ if successful and a scalar value of’0’ if unsuccessful.
MQUNSUBSCRIBE
Chapter 3. Functions 423
MULTIPLY_ALT
�� MULTIPLY_ALT ( exact_numeric_expression , exact_numeric_expression ) ��
The schema is SYSIBM.
The MULTIPLY_ALT scalar function returns the product of the two argumentsas a decimal value. It is provided as an alternative to the multiplicationoperator, especially when the sum of the precisions of the arguments exceeds31.
The arguments can be any built-in exact numeric data type (DECIMAL,BIGINT, INTEGER, or SMALLINT).
The result of the function is a DECIMAL. The precision and scale of the resultare determined as follows, using the symbols p and s to denote the precisionand scale of the first argument, and the symbols p' and s' to denote theprecision and scale of the second argument.
The precision is MIN(31, p + p')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, or if the databaseis configured with DFT_SQLMATHWARN set to YES; the result is the nullvalue if one of the arguments is null.
The MULTIPLY_ALT function is a preferable choice to the multiplicationoperator when performing decimal arithmetic where a scale of at least 3 isrequired and the sum of the precisions exceeds 31. In these cases, the internalcomputation is performed so that overflows are avoided. The final result isthen assigned to the result data type, using truncation where necessary tomatch the scale. Note that overflow of the final result is still possible whenthe scale is 3.
The following is a sample comparing the result types using MULTIPLY_ALTand the multiplication operator.
Type of argument 1 Type of argument 2 Result usingMULTIPLY_ALT
Result usingmultiplicationoperator
DECIMAL(31,3) DECIMAL(15,8) DECIMAL(31,3) DECIMAL(31,11)
MULTIPLY_ALT
424 SQL Reference, Volume 1
Type of argument 1 Type of argument 2 Result usingMULTIPLY_ALT
Result usingmultiplicationoperator
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)
Example:
Multiply two values where the data type of the first argument isDECIMAL(26,3) and the data type of the second argument is DECIMAL(9,8).The data type of the result is DECIMAL(31,7).values multiply_alt(98765432109876543210987.654,5.43210987)1---------------------------------536504678578875294857887.5277415
Note that the complete product of these two numbers is536504678578875294857887.52774154498, but the last 4 digits are truncated tomatch the scale of the result data type. Using the multiplication operator withthe same values will cause an arithmetic overflow, since the result data type isDECIMAL(31,11) and the result value has 24 digits left of the decimal, but theresult data type only supports 20 digits.
MULTIPLY_ALT
Chapter 3. Functions 425
NULLIF
�� NULLIF ( expression , expression ) ��
The schema is SYSIBM.
The NULLIF function returns a null value if the arguments are equal,otherwise it returns the value of the first argument.
The arguments must be comparable. They can be of either a built-in (otherthan a long string or DATALINK) or distinct data type (other than based on along string or DATALINK). (This function cannot be used as a source functionwhen creating a user-defined function. Because this function accepts anycompatible data types as arguments, it is not necessary to create additionalsignatures to support user-defined distinct types.) The attributes of the resultare the attributes of the first argument.
The result of using NULLIF(e1,e2) is the same as using the expressionCASE WHEN e1=e2 THEN NULL ELSE e1 END
Note that when e1=e2 evaluates to unknown (because one or both argumentsis NULL), CASE expressions consider this not true. Therefore, in this situation,NULLIF returns the value of the first argument.
Example:v Assume host variables PROFIT, CASH, and LOSSES have DECIMAL data
types with the values 4500.00, 500.00, and 5000.00 respectively:NULLIF (:PROFIT + :CASH , :LOSSES )
Returns a null value.
Related reference:
v “Assignments and comparisons” on page 117
NULLIF
426 SQL Reference, Volume 1
POSSTR
�� POSSTR ( source-string , search-string ) ��
The schema is SYSIBM.
The POSSTR function returns the starting position of the first occurrence ofone string (called the search-string) within another string (called thesource-string). Numbers for the search-string position start at 1 (not 0).
The result of the function is a large integer. If either of the arguments can benull, the result can be null; if either of the arguments is null, the result is thenull value.
source-stringAn expression that specifies the source string in which the search is totake place.
The expression can be specified by any one of:v a constantv a special registerv a host variable (including a locator variable or a file reference variable)v a scalar functionv a large object locatorv a column namev an expression concatenating any of the above
search-stringAn expression that specifies the string that is to be searched for.
The expression can be specified by any one of:v a constantv a special registerv a host variablev a scalar function whose operands are any of the abovev an expression concatenating any of the above
with the restrictions that:v No element in the expression can be of type LONG VARCHAR, CLOB,
LONG VARGRAPHIC or DBCLOB. In addition, it cannot be a BLOBfile reference variable.
v The actual length of search-string cannot be more than 4 000 bytes.
POSSTR
Chapter 3. Functions 427
Both search-string and source-string have zero or more contiguous positions. Ifthe strings are character or binary strings, a position is a byte. If the stringsare graphic strings, a position is a graphic (DBCS) character.
The POSSTR function accepts mixed data strings. However, POSSTR operateson a strict byte-count basis, oblivious to changes between single andmulti-byte characters.
The following rules apply:v The data types of source-string and search-string must be compatible,
otherwise an error is raised (SQLSTATE 42884).– If source-string is a character string, then search-string must be a character
string, but not a CLOB or LONG VARCHAR, with an actual length of32 672 bytes or less.
– If source-string is a graphic string, then search-string must be a graphicstring, but not a DBCLOB or LONG VARGRAPHIC, with an actuallength of 16 336 double-byte characters or less.
– If source-string is a binary string, then search-string must be a binarystring with an actual length of 32 672 bytes or less.
v If search-string has a length of zero, the result returned by the function is 1.v Otherwise:
– If source-string has a length of zero, the result returned by the function iszero.
– Otherwise:- If the value of search-string is equal to an identical length substring of
contiguous positions from the value of source-string, then the resultreturned by the function is the starting position of the first suchsubstring within the source-string value.
- Otherwise, the result returned by the function is 0.
Examplev Select RECEIVED and SUBJECT columns as well as the starting position of
the words ’GOOD BEER’ within the NOTE_TEXT column for all entries inthe IN_TRAY table that contain these words.
SELECT RECEIVED, SUBJECT, POSSTR(NOTE_TEXT, ’GOOD BEER’)FROM IN_TRAYWHERE POSSTR(NOTE_TEXT, ’GOOD BEER’) <> 0
POSSTR
428 SQL Reference, Volume 1
POWER
�� POWER ( expression1 , expression2 ) ��
The schema is SYSFUN.
Returns the value of expression1 to the power of expression2.
The arguments can be of any built-in numeric data type. DECIMAL andREAL arguments are converted to a double-precision floating-point number.
The result of the function is:v INTEGER if both arguments are INTEGER or SMALLINTv BIGINT if one argument is BIGINT and the other argument is BIGINT,
INTEGER or SMALLINTv DOUBLE otherwise.
The result can be null; if any argument is null, the result is the null value.
POWER
Chapter 3. Functions 429
QUARTER
�� QUARTER ( expression ) ��
The schema is SYSFUN.
Returns an integer value in the range 1 to 4 representing the quarter of theyear for the date specified in the argument.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
QUARTER
430 SQL Reference, Volume 1
RADIANS
�� RADIANS ( expression ) ��
The schema is SYSFUN.
Returns the number of radians converted from argument which is expressedin degrees.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
RADIANS
Chapter 3. Functions 431
RAISE_ERROR
�� RAISE_ERROR ( sqlstate , diagnostic-string ) ��
The schema is SYSIBM.
The RAISE_ERROR function causes the statement that includes the function toreturn an error with the specified SQLSTATE, SQLCODE -438 anddiagnostic-string. The RAISE_ERROR function always returns NULL with anundefined data type.
sqlstateA character string containing exactly 5 characters. It must be of typeCHAR defined with a length of 5 or type VARCHAR defined with alength of 5 or greater. The sqlstate value must follow the rules forapplication-defined SQLSTATEs as follows:v Each character must be from the set of digits (’0’ through ’9’) or
non-accented upper case letters (’A’ through ’Z’)v The SQLSTATE class (first two characters) cannot be ’00’, ’01’ or ’02’
since these are not error classes.v If the SQLSTATE class (first two characters) starts with the character ’0’
through ’6’ or ’A’ through ’H’, then 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’, then the subclass (last three characters) can beany of ’0’ through ’9’ or ’A’ through ’Z’.
If the SQLSTATE does not conform to these rules an error occurs(SQLSTATE 428B3).
diagnostic-stringAn expression of type CHAR or VARCHAR that returns a character stringof up to 70 bytes that describes the error condition. If the string is longerthan 70 bytes, it will be truncated.
To use this function in a context where the rules for result data types do notapply (such as alone in a select list), a cast specification must be used to givethe null returned value a data type. A CASE expression is where theRAISE_ERROR function will be most useful.
Example:
List employee numbers and education levels as Post Graduate, Graduate andDiploma. If an education level is greater than 20, raise an error.
RAISE_ERROR
432 SQL Reference, Volume 1
SELECT EMPNO,CASE WHEN EDUCLVL < 16 THEN ’Diploma’
WHEN EDUCLVL < 18 THEN ’Graduate’WHEN EDUCLVL < 21 THEN ’Post Graduate’ELSE RAISE_ERROR(’70001’,
’EDUCLVL has a value greater than 20’)END
FROM EMPLOYEE
RAISE_ERROR
Chapter 3. Functions 433
RAND
�� RAND ( )expression
��
The schema is SYSFUN.
Returns a random floating point value between 0 and 1 using the argument asthe optional seed value. The function is defined as not-deterministic.
An argument is not required, but if it is specified it can be either INTEGER orSMALLINT.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
RAND
434 SQL Reference, Volume 1
REAL
�� REAL ( numeric-expression ) ��
The schema is SYSIBM.
The REAL function returns a single-precision floating-point representation of anumber.
The argument is an expression that returns a value of any built-in numericdata type.
The result of the function is a single-precision floating-point number. If theargument can be null, the result can be null; if the argument is null, the resultis the null value.
The result is the same number that would occur if the argument wereassigned to a single-precision floating-point column or variable.
Example:
Using the EMPLOYEE table, find the ratio of salary to commission foremployees whose commission is not zero. The columns involved (SALARYand COMM) have DECIMAL data types. The result is desired insingle-precision floating point. Therefore, REAL is applied to SALARY so thatthe division is carried out in floating point (actually double-precision) andthen REAL is applied to the complete expression to return the result insingle-precision floating point.
SELECT EMPNO, REAL(REAL(SALARY)/COMM)FROM EMPLOYEEWHERE COMM > 0
REAL
Chapter 3. Functions 435
REC2XML
�� REC2XML ( decimal-constant , format-string , row-tag-string �
� � , column-name ) ��
The schema is SYSIBM.
The REC2XML function returns a string formatted with XML tags andcontaining column names and column data.
decimal-constantThe expansion factor for replacing column data characters. The decimalvalue must be greater than 0.0 and less than or equal to 6.0. (SQLSTATE42820).
The decimal-constant value is used to calculate the result length of thefunction. For every column with a character data type, the length attributeof the column is multiplied by this expansion factor before it is added into the result length.
To specify no expansion, use a value of 1.0. Specifying a value less than1.0 reduces the calculated result length. If the actual length of the resultstring is greater than the calculated result length of the function, then anerror is raised (SQLSTATE 22001).
format-stringThe string constant that specifies which format the function is to useduring execution.
The format-string is case-sensitive, so the following values must bespecified in uppercase to be recognized.
COLATTVAL or COLATTVAL_XMLThese formats return a string with columns as attribute values.
�� < row-tag-string > �
� � < column-name = "column-name" > column-value </ column >null="true" />
�
REC2XML
436 SQL Reference, Volume 1
� </ row-tag-string > ��
Column names may or may not be valid XML attribute values. Forcolumn names which are not valid XML attribute values, characterreplacement is performed on the column name before it is included in theresult string.
Column values may or may not be valid XML element names. If theformat-string COLATTVAL is specified, then for the column names whichare not valid XML element values, character replacement is performed onthe column value before it is included in the result string. If theformat-string COLATTVAL_XML is specified, then character replacement isnot performed on column values (although character replacement is stillperformed on column names).
row-tag-stringA string constant that specifies the tag used for each row. If an emptystring is specified, then a value of ’row’ is assumed.
If a string of one or more blank characters is specified, then no beginningrow-tag-string or ending row-tag-string (including the angle bracketdelimiters) will appear in the result string.
column-nameA qualified or unqualified name of a table column. The column must haveone of the following data types (SQLSTATE 42815):v numeric (SMALLINT, INTEGER, BIGINT, DECIMAL, REAL, DOUBLE)v character string (CHAR, VARCHAR; a character string with a subtype
of BIT DATA is not allowed)v datetime (DATE, TIME, TIMESTAMP)v a user-defined type based on one of the above types
The same column name cannot be specified more than once (SQLSTATE42734).
The result of the function is VARCHAR. The maximum length is 32 672 bytes(SQLSTATE 54006).
Consider the following invocation:REC2XML (dc, fs, rt, c1, c2, ..., cn)
If the value of ″fs″ is either ″COLATTVAL″ or ″COLATTVAL_XML″, then theresult is the same as this expression:'<' CONCAT rt CONCAT '>' CONCAT y1 CONCAT y2CONCAT ... CONCAT yn CONCAT '</' CONCAT rt CONCAT '>'
REC2XML
Chapter 3. Functions 437
where yn is equivalent to:'<column name="' CONCAT xvcn CONCAT vn
and vn is equivalent to:'">' CONCAT rn CONCAT '</column>'
if the column is not null, and'" null="true"/>'
if the column value is null.
xvcn is equivalent to a string representation of the column name of cn, whereany characters appearing in Table 18 on page 439 are replaced with thecorresponding representation. This ensures that the resulting string is a validXML attribute or element value token.
The rn is equivalent to a string representation as indicated in Table 17
Table 17. Column Values String Result
Data type of cn rn
CHAR, VARCHAR The value is a string. If the format-stringdoes not end in the characters ″_XML″,then each character in cn is replaced withthe corresponding replacementrepresentation from Table 18 on page 439,as indicated. The length attribute is: dc *the length attribute of cn.
SMALLINT, INTEGER, BIGINT,DECIMAL, NUMERIC, REAL, DOUBLE
The value is LTRIM(RTRIM(CHAR(cn))).The length attribute is the result length ofCHAR(cn). The decimal character isalways the period (’.’) character.
DATE The value is CHAR(cn,ISO). The lengthattribute is the result length ofCHAR(cn,ISO).
TIME The value is CHAR(cn,JIS). The lengthattribute is the result length ofCHAR(cn,JIS)
TIMESTAMP The value is CHAR(cn). The lengthattribute is the result length of CHAR(cn).
Character replacement:
Depending on the value specified for the format-string, certain characters incolumn names and column values will be replaced to ensure that the column
REC2XML
438 SQL Reference, Volume 1
names form valid XML attribute values and the column values form validXML element values.
Table 18. Character Replacements for XML Attribute Values and Element Values
Character Replacement
< <
> >
" "
& &
’ '
Examples:
Note: REC2XML does not insert new line characters in the output. Allexample output is formatted for the sake of readability.
v Using the DEPARTMENT table in the sample database, format thedepartment table row, except the DEPTNAME and LOCATION columns,for department ’D01’ into an XML string. Since the data does not containany of the characters which require replacement, the expansion factor willbe 1.0 (no expansion). Also note that the MGRNO value is null for this row.
SELECT REC2XML (1.0, ’COLATTVAL’, ’’, DEPTNO, MGRNO, ADMRDEPT)FROM DEPARTMENTWHERE DEPTNO = ’D01’
This example returns the following VARCHAR(117) string:<row><column name="DEPTNO">D01</column><column name="MGRNO" null="true"/><column name="ADMRDEPT">A00</column></row>
v A 5-day university schedule introduces a class named ’&43<FIE’ to a tablecalled CL_SCHED, with a new format for the CLASS_CODE column. Usingthe REC2XML function, this example formats an XML string with this newclass data, except for the class end time.The length attribute for the REC2XML call (see below) with an expansionfactor of 1.0 would be 128 (11 for the ’<row>’ and ’</row>’ overhead, 21for the column names, 75 for the ’<column name=’, ’>’, ’</column>’ anddouble quotes, 7 for the CLASS_CODE data, 6 for the DAY data, and 8 forthe STARTING data). Since the ’&’ and ’<’ characters will be replaced, anexpansion factor of 1.0 will not be sufficient. The length attribute of thefunction will need to support an increase from 7 to 14 characters for thenew format CLASS_CODE data.
REC2XML
Chapter 3. Functions 439
However, since it is known that the DAY value will never be more than 1digit long, an unused extra 5 units of length are added to the total.Therefore, the expansion only needs to handle an increase of 2. SinceCLASS_CODE is the only character string column in the argument list, thisis the only column data to which the expansion factor applies. To get anincrease of 2 for the length, an expansion factor of 9/7 (approximately1.2857) would be needed. An expansion factor of 1.3 will be used.
SELECT REC2XML (1.3, ’COLATTVAL’, ’record’, CLASS_CODE, DAY, STARTING)FROM CL_SCHEDWHERE CLASS_CODE = ’&43<FIE’
This example returns the following VARCHAR(167) string:<record><column name="CLASS_CODE">&43<FIE</column><column name="DAY">5</column><column name="STARTING">06:45:00</column></record>
v Assume that new rows have been added to the EMP_RESUME table in thesample database. The new rows store the resumes as strings of valid XML.The COLATTVAL_XML format-string is used so character replacement willnot be carried out. None of the resumes are more than 3500 characters inlength. The following query is used to select the XML version of theresumes from the EMP_RESUME table and format it into an XMLdocument fragment.
SELECT REC2XML (1.0, ’COLATTVAL_XML’, ’row’, EMPNO, RESUME_XML)FROM (SELECT EMPNO, CAST(RESUME AS VARCHAR(3500)) AS RESUME_XML
FROM EMP_RESUMEWHERE RESUME_FORMAT = ’XML’)
AS EMP_RESUME_XML
This example returns a row for each employee who has a resume in XMLformat. Each returned row will be a string with the following format:
<row><column name="EMPNO">{employee number}</column><column name="RESUME_XML">{resume in XML}</column></row>
Where ″{employee number}″ is the actual EMPNO value for the columnand ″{resume in XML}″ is the actual XML fragment string value that is theresume.
REC2XML
440 SQL Reference, Volume 1
REPEAT
�� REPEAT ( expression , expression ) ��
The schema is SYSFUN.
Returns a character string composed of the first argument repeated thenumber of times specified by the second argument.
The first argument is a character string or binary string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB or a binary string themaximum length is 1 048 576 bytes. The second argument can be SMALLINTor INTEGER.
The result of the function is:v VARCHAR(4000) if the first argument is VARCHAR (not exceeding 4 000
bytes) or CHARv CLOB(1M) if the first argument is CLOB or LONG VARCHARv BLOB(1M) if the first argument is BLOB.
The result can be null; if any argument is null, the result is the null value.
Example:v List the phrase ’REPEAT THIS’ five times.
VALUES CHAR(REPEAT(’REPEAT THIS’, 5), 60)
This example return the following:1------------------------------------------------------------REPEAT THISREPEAT THISREPEAT THISREPEAT THISREPEAT THIS
As mentioned, the output of the REPEAT function is VARCHAR(4000). Forthis example, the CHAR function has been used to limit the output ofREPEAT to 60 bytes.
REPEAT
Chapter 3. Functions 441
REPLACE
�� REPLACE ( expression1 , expression2 , expression3 ) ��
The schema is SYSFUN.
Replaces all occurrences of expression2 in expression1 with expression3.
The first argument can be of any built-in character string or binary stringtype. For a VARCHAR the maximum length is 4 000 bytes and for a CLOB ora binary string the maximum length is 1 048 576 bytes. CHAR is converted toVARCHAR and LONG VARCHAR is converted to CLOB(1M). The secondand third arguments are identical to the first argument.
The result of the function is:v VARCHAR(4000) if the first, second and third arguments are VARCHAR or
CHARv CLOB(1M) if the first, second and third arguments are CLOB or LONG
VARCHARv BLOB(1M) if the first, second and third arguments are BLOB.
The result can be null; if any argument is null, the result is the null value.
Example:v Replace all occurrence of the letter ’N’ in the word ’DINING’ with ’VID’.
VALUES CHAR (REPLACE (’DINING’, ’N’, ’VID’), 10)
This example returns the following:1----------DIVIDIVIDG
As mentioned, the output of the REPLACE function is VARCHAR(4000).For this example, the CHAR function has been used to limit the output ofREPLACE to 10 bytes.
REPLACE
442 SQL Reference, Volume 1
RIGHT
�� RIGHT ( expression1 , expression2 ) ��
Returns a string consisting of the rightmost expression2 bytes in expression1.The expression1 value is effectively padded on the right with the necessarynumber of blank characters so that the specified substring of expression1always exists.
The first argument is a character string or binary string type. For a VARCHARthe maximum length is 4 000 bytes and for a CLOB or a binary string themaximum length is 1 048 576 bytes. The second argument can be INTEGER orSMALLINT.
The result of the function is:v VARCHAR(4000) if the first argument is VARCHAR (not exceeding 4 000
bytes) or CHARv CLOB(1M) if the first argument is CLOB or LONG VARCHARv BLOB(1M) if the first argument is BLOB.
The result can be null; if any argument is null, the result is the null value.
RIGHT
Chapter 3. Functions 443
ROUND
�� ROUND ( expression1 , expression2 ) ��
The schema is SYSIBM. (The SYSFUN version of the ROUND functioncontinues to be available.)
The ROUND function returns expression1 rounded to expression2 places to theright of the decimal point if expression2 is positive, or to the left of the decimalpoint if expression2 is zero or negative.
If expression1 is positive, a digit value of 5 or greater is an indication to roundto the next higher positive number. For example, ROUND(3.5,0) = 4. Ifexpression1 is negative, a digit value of 5 or greater is an indication to roundto the next lower negative number. For example, ROUND(-3.5,0) = -4.
expression1An expression that returns a value of any built-in numeric data type.
expression2An expression that returns a small or large integer. When the value ofexpression2 is not negative, it specifies rounding to that number of placesto the right of the decimal separator. When the value of expression2 isnegative, it specifies rounding to the absolute value of expression2 placesto the left of the decimal separator.
If expression2 is not negative, expression1 is rounded to the absolute valueof expression2 number of places to the right of the decimal point. If thevalue of expression2 is greater than the scale of expression1 then the value isunchanged except that the result value has a precision that is larger by 1.For example, ROUND(748.58,5) = 748.58 where the precision is now 6 andthe scale remains 2.
If expression2 is negative, expression1 is rounded to the absolute value ofexpression2+1 number of places to the left of the decimal point.
If the absolute value of a negative expression2 is larger than the number ofdigits to the left of the decimal point, the result is 0. For example,ROUND(748.58,-4) = 0.
The data type and length attribute of the result are the same as the data typeand length attribute of the first argument, except that the precision isincreased by one if the expression1 is DECIMAL and the precision is less than31.
For example, an argument with a data type of DECIMAL(5,2) results inDECIMAL(6,2). An argument with a data type of DECIMAL(31,2) results inDECIMAL(31,2). The scale is the same as the scale of the first argument.
ROUND
444 SQL Reference, Volume 1
If either argument can be null or the database is configured withDFT_SQLMATHWARN set to YES, the result can be null. If either argument isnull, the result is the null value.
Examples:
Calculate the value of 873.726, rounded to 2, 1, 0, -1, -2, -3, and -4 decimalplaces, respectively.
VALUES (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) )
This example returns:1 2 3 4 5 6 7--------- --------- --------- --------- --------- --------- ---------
873.730 873.700 874.000 870.000 900.000 1000.000 0.000
Calculate using both positive and negative numbers.VALUES (
ROUND(3.5, 0),ROUND(3.1, 0),ROUNDROUND(-3.1, 0),ROUND(-3.5,0) )
This example returns:1 2 3 4---- ---- ---- ----4.0 3.0 -3.0 -4.0
ROUND
Chapter 3. Functions 445
RTRIM
�� RTRIM ( string-expression ) ��
The schema is SYSIBM. (The SYSFUN version of this function continues to beavailable with support for LONG VARCHAR and CLOB arguments.)
The RTRIM function removes blanks from the end of string-expression.
The argument can be a CHAR, VARCHAR, GRAPHIC, or VARGRAPHIC datatype.v If the argument is a graphic string in a DBCS or EUC database, then the
trailing double byte blanks are removed.v If the argument is a graphic string in a Unicode database, then the trailing
UCS-2 blanks are removed.v Otherwise, the trailing single byte blanks are removed.
The result data type of the function is:v VARCHAR if the data type of string-expression is VARCHAR or CHARv VARGRAPHIC if the data type of string-expression is VARGRAPHIC or
GRAPHIC
The length parameter of the returned type is the same as the length parameterof the argument data type.
The actual length of the result for character strings is the length ofstring-expression minus the number of bytes removed for blank characters. Theactual length of the result for graphic strings is the length (in number ofdouble byte characters) of string-expression minus the number of double byteblank characters removed. If all of the characters are removed, the result is anempty, varying-length string (length is zero).
If the argument can be null, the result can be null; if the argument is null, theresult is the null value.
Example: Assume that host variable HELLO is defined as CHAR(9) and has avalue of ’Hello’.
VALUES RTRIM(:HELLO)
The result is ’Hello’.
Related reference:
v “RTRIM (SYSFUN schema)” on page 447
RTRIM
446 SQL Reference, Volume 1
RTRIM (SYSFUN schema)
�� RTRIM ( expression ) ��
The schema is SYSFUN.
Returns the characters of the argument with trailing blanks removed.
The argument can be of any built-in character string data types. For aVARCHAR the maximum length is 4 000 bytes and for a CLOB the maximumlength is 1 048 576 bytes.
The result of the function is:v VARCHAR(4000) if the argument is VARCHAR (not exceeding 4 000 bytes)
or CHARv CLOB(1M) if the argument is CLOB or LONG VARCHAR.
The result can be null; if the argument is null, the result is the null
RTRIM (SYSFUN schema)
Chapter 3. Functions 447
SECOND
�� SECOND ( expression ) ��
The schema is SYSIBM.
The SECOND function returns the seconds part of a value.
The argument must be a time, timestamp, time duration, timestamp durationor a valid character string representation of a time or timestamp that isneither a CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a time, timestamp or valid string representation of a time
or timestamp:– The result is the seconds part of the value, which is an integer between 0
and 59.v 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.
Examples:v Assume that the host variable TIME_DUR (decimal(6,0)) has the value
153045.SECOND(:TIME_DUR)
Returns the value 45.v Assume that the column RECEIVED (timestamp) has an internal value
equivalent to 1988-12-25-17.12.30.000000.SECOND(RECEIVED)
Returns the value 30.
SECOND
448 SQL Reference, Volume 1
SIGN
�� SIGN ( expression ) ��
Returns an indicator of the sign of the argument. If the argument is less thanzero, −1 is returned. If argument equals zero, 0 is returned. If argument isgreater than zero, 1 is returned.
The argument can be of any built-in numeric data type. DECIMAL and REALvalues are converted to double-precision floating-point numbers forprocessing by the function.
The result of the function is:v SMALLINT if the argument is SMALLINTv INTEGER if the argument is INTEGERv BIGINT if the argument is BIGINTv DOUBLE otherwise.
The result can be null; if the argument is null, the result is the null value.
SIGN
Chapter 3. Functions 449
SIN
�� SIN ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the SIN function continues tobe available.)
Returns the sine of the argument, where the argument is an angle expressedin radians.
The argument can be of any built-in numeric data type. It is converted todouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
SIN
450 SQL Reference, Volume 1
SINH
�� SINH ( expression ) ��
The schema is SYSIBM.
Returns the hyperbolic sine of the argument, where the argument is an angleexpressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
SINH
Chapter 3. Functions 451
SMALLINT
�� SMALLINT ( numeric-expressioncharacter-expression
) ��
The schema is SYSIBM.
The SMALLINT function returns a small integer representation of a numberor character string in the form of a small integer constant.
numeric-expressionAn expression that returns a value of any built-in numeric data type.
If the argument is a numeric-expression, the result is the same number thatwould occur if the argument were assigned to a small integer column orvariable. If the whole part of the argument is not within the range ofsmall integers, an error occurs. The decimal part of the argument istruncated if present.
character-expressionAn expression that returns a character string value of length not greaterthan the maximum length of a character constant. Leading and trailingblanks are eliminated and the resulting string must conform to the rulesfor forming an SQL integer constant (SQLSTATE 22018). However, thevalue of the constant must be in the range of small integers (SQLSTATE22003). The character string cannot be a long string.
If the argument is a character-expression, the result is the same number thatwould occur if the corresponding integer constant were assigned to asmall integer column or variable.
The result of the function is a small integer. If the argument can be null, theresult can be null; if the argument is null, the result is the null value.
SMALLINT
452 SQL Reference, Volume 1
SOUNDEX
�� SOUNDEX ( expression ) ��
The schema is SYSFUN.
Returns a 4 character code representing the sound of the words in theargument. The result can be used to compare with the sound of other strings.
The argument can be a character string that is either a CHAR or VARCHARnot exceeding 4 000 bytes.
The result of the function is CHAR(4). The result can be null; if the argumentis null, the result is the null value.
The SOUNDEX function is useful for finding strings for which the sound isknown but the precise spelling is not. It makes assumptions about the waythat letters and combinations of letters sound that can help to search outwords with similar sounds. The comparison can be done directly or bypassing the strings as arguments to the DIFFERENCE function .
Example:
Using the EMPLOYEE table, find the EMPNO and LASTNAME of theemployee with a surname that sounds like ’Loucesy’.
SELECT EMPNO, LASTNAME FROM EMPLOYEEWHERE SOUNDEX(LASTNAME) = SOUNDEX(’Loucesy’)
This example returns the following:EMPNO LASTNAME------ ---------------000110 LUCCHESSI
Related reference:
v “DIFFERENCE” on page 336
SOUNDEX
Chapter 3. Functions 453
SPACE
�� SPACE ( expression ) ��
The schema is SYSFUN.
Returns a character string consisting of blanks with length specified by thesecond argument.
The argument can be SMALLINT or INTEGER.
The result of the function is VARCHAR(4000). The result can be null; if theargument is null, the result is the null value.
SPACE
454 SQL Reference, Volume 1
SQRT
�� SQRT ( expression ) ��
The schema is SYSFUN.
Returns the square root of the argument.
The argument can be any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null; if the argument is null, the result is the null value.
SQRT
Chapter 3. Functions 455
SUBSTR
�� SUBSTR ( string , start, length
) ��
The SUBSTR function returns a substring of a string.
If string is a character string, the result of the function is a character stringrepresented in the code page of its first argument. If it is a binary string, theresult of the function is a binary string. If it is a graphic string, the result ofthe function is a graphic string represented in the code page of its firstargument. If the first argument is a host variable, the code page of the resultis the database code page. If any argument of the SUBSTR function can benull, the result can be null; if any argument is null, the result is the null value.
stringAn expression that specifies the string from which the result is derived.
If string is either a character string or a binary string, a substring of stringis zero or more contiguous bytes of string. If string is a graphic string, asubstring of string is zero or more contiguous double-byte characters ofstring.
startAn expression that specifies the position of the first byte of the result for acharacter string or a binary string or the position of the first character ofthe result for a graphic string. start must be an integer between 1 and thelength or maximum length of string, depending on whether string isfixed-length or varying-length (SQLSTATE 22011, if out of range). It mustbe specified as number of bytes in the context of the database code pageand not the application code page.
lengthAn expression that specifies the length of the result. If specified, lengthmust be a binary integer in the range 0 to n, where n equals (the lengthattribute of string) − start + 1 (SQLSTATE 22011, if out of range).
If length is explicitly specified, string is effectively padded on the rightwith the necessary number of blank characters (single-byte for characterstrings; double-byte for graphic strings) or hexadecimal zero characters(for BLOB strings) so that the specified substring of string always exists.The default for length is the number of bytes from the byte specified bythe start to the last byte of string in the case of character string or binarystring or the number of double-byte characters from the characterspecified by the start to the last character of string in the case of a graphicstring. However, if string is a varying-length string with a length less thanstart, the default is zero and the result is the empty string. It must bespecified as number of bytes in the context of the database code page and
SUBSTR
456 SQL Reference, Volume 1
not the application code page. (For example, the column NAME with adata type of VARCHAR(18) and a value of 'MCKNIGHT' will yield anempty string with SUBSTR(NAME,10)).
Table 19 shows that the result type and length of the SUBSTR function dependon the type and attributes of its inputs.
Table 19. Data Type and Length of SUBSTR Result
String Argument DataType
Length Argument Result Data Type
CHAR(A) constant (l<255) CHAR(l)
CHAR(A) not specified but start argument is aconstant
CHAR(A-start+1)
CHAR(A) not a constant VARCHAR(A)
VARCHAR(A) constant (l<255) CHAR(l)
VARCHAR(A) constant (254<l<32673) VARCHAR(l)
VARCHAR(A) not a constant or not specified VARCHAR(A)
LONG VARCHAR constant (l<255) CHAR(l)
LONG VARCHAR constant (254<l<4001) VARCHAR(l)
LONG VARCHAR constant (l>4000) LONG VARCHAR
LONG VARCHAR not a constant or not specified LONG VARCHAR
CLOB(A) constant (l) CLOB(l)
CLOB(A) not a constant or not specified CLOB(A)
GRAPHIC(A) constant (l<128) GRAPHIC(l)
GRAPHIC(A) not specified but start argument is aconstant
GRAPHIC(A-start+1)
GRAPHIC(A) not a constant VARGRAPHIC(A)
VARGRAPHIC(A) constant (l<128) GRAPHIC(l)
VARGRAPHIC(A) constant (127<l<16337) VARGRAPHIC(l)
VARGRAPHIC(A) not a constant VARGRAPHIC(A)
SUBSTR
Chapter 3. Functions 457
Table 19. Data Type and Length of SUBSTR Result (continued)
String Argument DataType
Length Argument Result Data Type
LONG VARGRAPHIC constant (l<128) GRAPHIC(l)
LONG VARGRAPHIC constant (127<l<2001) VARGRAPHIC(l)
LONG VARGRAPHIC constant (l>2000) LONG VARGRAPHIC
LONG VARGRAPHIC not a constant or not specified LONG VARGRAPHIC
DBCLOB(A) constant (l) DBCLOB(l)
DBCLOB(A) not a constant or not specified DBCLOB(A)
BLOB(A) constant (l) BLOB(l)
BLOB(A) not a constant or not specified BLOB(A)
If string is a fixed-length string, omission of length is an implicit specificationof LENGTH(string) - start + 1. If string is a varying-length string, omission oflength is an implicit specification of zero or LENGTH(string) - start + 1,whichever is greater.
Examples:v Assume the host variable NAME (VARCHAR(50)) has a value of ’BLUE
JAY’ and the host variable SURNAME_POS (int) has a value of 6.SUBSTR(:NAME, :SURNAME_POS)
Returns the value 'JAY'SUBSTR(:NAME, :SURNAME_POS,1)
Returns the value 'J'.v Select all rows from the PROJECT table for which the project name
(PROJNAME) starts with the word ’OPERATION’.SELECT * FROM PROJECT
WHERE SUBSTR(PROJNAME,1,10) = ’OPERATION ’
The space at the end of the constant is necessary to preclude initial wordssuch as ’OPERATIONS’.
SUBSTR
458 SQL Reference, Volume 1
Notes:
1. In dynamic SQL, string, start, and length may be represented by aparameter marker (?). If a parameter marker is used for string, the datatype of the operand will be VARCHAR, and the operand will be nullable.
2. Though not explicitly stated in the result definitions above, it follows fromthese semantics that if string is a mixed single- and multi-byte characterstring, the result may contain fragments of multi-byte characters,depending upon the values of start and length. That is, the result couldpossibly begin with the second byte of a double-byte character, and/orend with the first byte of a double-byte character. The SUBSTR functiondoes not detect such fragments, nor provides any special processingshould they occur.
SUBSTR
Chapter 3. Functions 459
TABLE_NAME
�� TABLE_NAME ( objectname ), objectschema
��
The schema is SYSIBM.
The TABLE_NAME function returns an unqualified name of the object foundafter any alias chains have been resolved. The specified objectname (andobjectschema) are used as the starting point of the resolution. If the startingpoint does not refer to an alias, the unqualified name of the starting point isreturned. The resulting name may be of a table, view, or undefined object.
objectnameA character expression representing the unqualified name (usually of anexisting alias) to be resolved. objectname must have a data type of CHARor VARCHAR and a length greater than 0 and less than 129 characters.
objectschemaA character expression representing the schema used to qualify thesupplied objectname value before resolution. objectschema must have a datatype of CHAR or VARCHAR and a length greater than 0 and less than129 characters.
If objectschema is not supplied, the default schema is used for the qualifier.
The data type of the result of the function is VARCHAR(128). If objectname canbe null, the result can be null; if objectname is null, the result is the null value.If objectschema is the null value, the default schema name is used. The result isthe character string representing an unqualified name. The result name couldrepresent one of the following:
table The value for objectname was either a table name (the input value isreturned) or an alias name that resolved to the table whose name isreturned.
view The value for objectname was either a view name (the input value isreturned) or an alias name that resolved to the view whose name isreturned.
undefined object
The value for objectname was either an undefined object (the inputvalue is returned) or an alias name that resolved to the undefinedobject whose name is returned.
Therefore, if a non-null value is given to this function, a value is alwaysreturned, even if no object with the result name exists.
TABLE_NAME
460 SQL Reference, Volume 1
TABLE_SCHEMA
�� TABLE_SCHEMA ( objectname, objectschema
) ��
The schema is SYSIBM.
The TABLE_SCHEMA function returns the schema name of the object foundafter any alias chains have been resolved. The specified objectname (andobjectschema) are used as the starting point of the resolution. If the startingpoint does not refer to an alias, the schema name of the starting point isreturned. The resulting schema name may be of a table, view, or undefinedobject.
objectnameA character expression representing the unqualified name (usually of anexisting alias) to be resolved. objectname must have a data type of CHARor VARCHAR and a length greater than 0 and less than 129 characters.
objectschemaA character expression representing the schema used to qualify thesupplied objectname value before resolution. objectschema must have a datatype of CHAR or VARCHAR and a length greater than 0 and less than129 characters.
If objectschema is not supplied, the default schema is used for the qualifier.
The data type of the result of the function is VARCHAR(128). If objectname canbe null, the result can be null; if objectname is null, the result is the null value.If objectschema is the null value, the default schema name is used. The result isthe character string representing a schema name. The result schema couldrepresent the schema name for one of the following:
table The value for objectname was either a table name (the input or defaultvalue of objectschema is returned) or an alias name that resolved to atable for which the schema name is returned.
view The value for objectname was either a view name (the input or defaultvalue of objectschema is returned) or an alias name that resolved to aview for which the schema name is returned.
undefined object
The value for objectname was either an undefined object (the input ordefault value of objectschema is returned) or an alias name thatresolved to an undefined object for which the schema name isreturned.
TABLE_SCHEMA
Chapter 3. Functions 461
Therefore, if a non-null objectname value is given to this function, a value isalways returned, even if the object name with the result schema name doesnot exist. For example, TABLE_SCHEMA(’DEPT’, ’PEOPLE’) returns 'PEOPLE ' ifthe catalog entry is not found.
Examples:v PBIRD tries to select the statistics for a given table from SYSCAT.TABLES
using an alias PBIRD.A1 defined on the table HEDGES.T1.SELECT NPAGES, CARD FROM SYSCAT.TABLESWHERE TABNAME = TABLE_NAME (’A1’)AND TABSCHEMA = TABLE_SCHEMA (’A1’)
The requested statistics for HEDGES.T1 are retrieved from the catalog.v Select the statistics for an object called HEDGES.X1 from SYSCAT.TABLES
using HEDGES.X1. Use TABLE_NAME and TABLE_SCHEMA since it is notknown whether HEDGES.X1 is an alias or a table.
SELECT NPAGES, CARD FROM SYSCAT.TABLESWHERE TABNAME = TABLE_NAME (’X1’,’HEDGES’)AND TABSCHEMA = TABLE_SCHEMA (’X1’,’HEDGES’)
Assuming that HEDGES.X1 is a table, the requested statistics forHEDGES.X1 are retrieved from the catalog.
v Select the statistics for a given table from SYSCAT.TABLES using an aliasPBIRD.A2 defined on HEDGES.T2 where HEDGES.T2 does not exist.
SELECT NPAGES, CARD FROM SYSCAT.TABLESWHERE TABNAME = TABLE_NAME (’A2’,’PBIRD’)AND TABSCHEMA = TABLE_SCHEMA (’A2’,PBIRD’)
The statement returns 0 records as no matching entry is found inSYSCAT.TABLES where TABNAME = ’T2’ and TABSCHEMA = ’HEDGES’.
v Select the qualified name of each entry in SYSCAT.TABLES along with thefinal referenced name for any alias entry.
SELECT TABSCHEMA AS SCHEMA, TABNAME AS NAME,TABLE_SCHEMA (BASE_TABNAME, BASE_TABSCHEMA) AS REAL_SCHEMA,TABLE_NAME (BASE_TABNAME, BASE_TABSCHEMA) AS REAL_NAMEFROM SYSCAT.TABLES
The statement returns the qualified name for each object in the catalog andthe final referenced name (after alias has been resolved) for any aliasentries. For all non-alias entries, BASE_TABNAME andBASE_TABSCHEMA are null so the REAL_SCHEMA and REAL_NAMEcolumns will contain nulls.
TABLE_SCHEMA
462 SQL Reference, Volume 1
TAN
�� TAN ( expression ) ��
The schema is SYSIBM. (The SYSFUN version of the TAN function continuesto be available.)
Returns the tangent of the argument, where the argument is an angleexpressed in radians.
The argument can be any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
TAN
Chapter 3. Functions 463
TANH
�� TANH ( expression ) ��
The schema is SYSIBM.
Returns the hyperbolic tangent of the argument, where the argument is anangle expressed in radians.
The argument can be of any built-in numeric data type. It is converted to adouble-precision floating-point number for processing by the function.
The result of the function is a double-precision floating-point number. Theresult can be null if the argument can be null or the database is configuredwith DFT_SQLMATHWARN set to YES; the result is the null value if theargument is null.
TANH
464 SQL Reference, Volume 1
TIME
�� TIME ( expression ) ��
The schema is SYSIBM.
The TIME function returns a time from a value.
The argument must be a time, timestamp, or a valid string representation of atime or timestamp that is not a CLOB, LONG VARCHAR, DBCLOB, or LONGVARGRAPHIC.
Only Unicode databases support an argument that is a graphic stringrepresentation of a time or a timestamp.
The result of the function is a time. If the argument can be null, the result canbe null; if the argument is null, the result is the null value.
The other rules depend on the data type of the argument:v If the argument is a time:
– The result is that time.v If the argument is a timestamp:
– The result is the time part of the timestamp.v If the argument is a string:
– The result is the time represented by the string.
Example:v Select all notes from the IN_TRAY sample table that were received at least
one hour later in the day (any day) than the current time.SELECT * FROM IN_TRAY
WHERE TIME(RECEIVED) >= CURRENT TIME + 1 HOUR
TIME
Chapter 3. Functions 465
TIMESTAMP
�� TIMESTAMP ( expression ),expression
��
The schema is SYSIBM.
The TIMESTAMP function returns a timestamp from a value or a pair ofvalues.
Only Unicode databases support an argument that is a graphic stringrepresentation of a date, a time, or a timestamp.
The rules for the arguments depend on whether the second argument isspecified.v If only one argument is specified:
– It must be a timestamp, a valid string representation of a timestamp, or astring of length 14 that is not a CLOB, LONG VARCHAR, DBCLOB, orLONG VARGRAPHIC.A string of length 14 must be a string of digits that represents a validdate and time in the form yyyyxxddhhmmss, where yyyy is the year, xx isthe month, dd is the day, hh is the hour, mm is the minute, and ss is theseconds.
v 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 stringrepresentation of a time.
The result of the function is a timestamp. If either argument can be null, theresult 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:v If both arguments are specified:
– The result is a timestamp with the date specified by the first argumentand the time specified by the second argument. The microsecond part ofthe timestamp is zero.
v If only one argument is specified and it is a timestamp:– The result is that timestamp.
v If only one argument is specified and it is a string:– The result is the timestamp represented by that string. If the argument is
a string of length 14, the timestamp has a microsecond part of zero.
TIMESTAMP
466 SQL Reference, Volume 1
Example:v Assume the column START_DATE (date) has a value equivalent to
1988-12-25, and the column START_TIME (time) has a value equivalent to17.12.30.
TIMESTAMP(START_DATE, START_TIME)
Returns the value ’1988-12-25-17.12.30.000000’.
TIMESTAMP
Chapter 3. Functions 467
TIMESTAMP_FORMAT
�� TIMESTAMP_FORMAT ( string-expression ,format-string ) ��
The schema is SYSIBM.
The TIMESTAMP_FORMAT function returns a timestamp from a characterstring that has been interpreted using a character template.
string-expressionA character expression representing a timestamp value in the formatspecified by format-string. (If string-expression is an untyped parametermarker, the type is assumed to be VARCHAR with a maximum length of254.) The string expression returns a CHAR or a VARCHAR value whosemaximum length is not greater than 254 (SQLSTATE 42815). Leading andtrailing blanks are removed from string-expression, and the resultingsubstring is interpreted as a timestamp using the format specified byformat-string. Leading zeros can be omitted from any timestampcomponents except the year. Blanks can be used in place of leading zerosfor these components. For example, with a format string of ’YYYY-MM-DDHH24:MI:SS’, each of the following strings is an acceptable specificationfor 9 a.m. on January 1, 2000:
’2000-1-01 09:00:00’ (single digit for month)’2000- 1-01 09:00:00’ (single digit - preceded by a blank -
for month)’2000-1-1 09:00:00’ (single digits for month and day)’2000-01-01 9:00:00’ (single digit for hour)’2000-01-01 09:0:0’ (single digits for minutes and seconds)’2000- 1- 1 09: 0: 0’ (single digit - preceded by a blank -
for month, day, minutes, and seconds)’2000-01-01 09:00:00’ (maximum number of digits for each element)
format-stringA character constant that contains a template for how the stringexpression is to be interpreted as a timestamp value. The length of theformat string must not be greater than 254 (SQLSTATE 42815). Leadingand trailing blanks are removed from format-string, and the resultingsubstring must be a valid template for a timestamp value (SQLSTATE42815). The content of format-string can be specified in mixed case.
Valid format strings are:’YYYY-MM-DD HH24:MI:SS’
where YYYY represents a 4-digit year value; MM represents a 2-digitmonth value (01-12; January=01); DD represents a 2-digit day of themonth value (01-31); HH24 represents a 2-digit hour of the day value
TIMESTAMP_FORMAT
468 SQL Reference, Volume 1
(00-24; If the hour is 24, the minutes and seconds values are zero.); MIrepresents a 2-digit minute value (00-59); and SS represents a 2-digitseconds value (00-59).
The result of the function is a timestamp. If the first argument can be null, theresult can be null; if the first argument is null, the result is the null value.
Example:v Insert a row into the in_tray table with a receiving timestamp that is equal
to one second before the beginning of the year 2000 (December 31, 1999 at23:59:59).
INSERT INTO in_tray (received)VALUES (TIMESTAMP_FORMAT(’1999-12-31 23:59:59’,
’YYYY-MM-DD HH24:MI:SS’))
TIMESTAMP_FORMAT
Chapter 3. Functions 469
TIMESTAMP_ISO
�� TIMESTAMP_ISO ( expression ) ��
The schema is SYSFUN.
Returns a timestamp value based on date, time or timestamp argument. If theargument is a date, it inserts zero for all the time elements. If the argument isa time, it inserts the value of CURRENT DATE for the date elements and zerofor the fractional time element.
The argument must be a date, time or timestamp, or a valid character stringrepresentation of a date, time or timestamp that is neither a CLOB nor aLONG VARCHAR.
The result of the function is TIMESTAMP. The result can be null; if theargument is null, the result is the null value.
TIMESTAMP_ISO
470 SQL Reference, Volume 1
TIMESTAMPDIFF
�� TIMESTAMPDIFF ( expression , expression ) ��
The schema is SYSFUN.
Returns an estimated number of intervals of the type defined by the firstargument, based on the difference between two timestamps.
The first argument can be either INTEGER or SMALLINT. Valid values ofinterval (the first argument) are:
1 Fractions of a second
2 Seconds
4 Minutes
8 Hours
16 Days
32 Weeks
64 Months
128 Quarters
256 Years
The second argument is the result of subtracting two timestamps andconverting the result to CHAR(22).
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
The following assumptions may be used in estimating a difference:v There are 365 days in a year.v There are 30 days in a month.v There are 24 hours in a day.v There are 60 minutes in an hour.v There are 60 seconds in a minute.
These assumptions are used when converting the information in the secondargument, which is a timestamp duration, to the interval type specified in thefirst argument. The returned estimate may vary by a number of days. Forexample, if the number of days (interval 16) is requested for the differencebetween ’1997-03-01-00.00.00’ and ’1997-02-01-00.00.00’, the result is 30. This is
TIMESTAMPDIFF
Chapter 3. Functions 471
because the difference between the timestamps is 1 month, and theassumption of 30 days in a month applies.
Example:
The following example returns 4277, the number of minutes between twotimestamps:
TIMESTAMPDIFF(4,CHAR(TIMESTAMP(’2001-09-29-11.25.42.483219’) -TIMESTAMP(’2001-09-26-12.07.58.065497’)))
TIMESTAMPDIFF
472 SQL Reference, Volume 1
TO_CHAR
�� TO_CHAR ( timestamp-expression ,format-string ) ��
The schema is SYSIBM.
The TO_CHAR function returns a character representation of a timestamp thathas been formatted using a character template.
TO_CHAR is a synonym for VARCHAR_FORMAT.
Related reference:
v “VARCHAR_FORMAT” on page 487
TO_CHAR
Chapter 3. Functions 473
TO_DATE
�� TO_DATE ( string-expression ,format-string ) ��
The schema is SYSIBM.
The TO_DATE function returns a timestamp from a character string that hasbeen interpreted using a character template.
TO_DATE is a synonym for TIMESTAMP_FORMAT.
Related reference:
v “TIMESTAMP_FORMAT” on page 468
TO_DATE
474 SQL Reference, Volume 1
TRANSLATE
character string expression:
�� TRANSLATE ( char-string-exp �
�, ’ ’
, to-string-exp , from-string-exp, pad-char
) ��
graphic string expression:
�� TRANSLATE ( graphic-string-exp , to-string-exp , from-string-exp �
�, ’ ’
, pad-char) ��
The schema is SYSIBM.
The TRANSLATE function returns a value in which one or more characters ina string expression may have been translated into other characters.
The result of the function has the same data type and code page as the firstargument. If the first argument is a host variable, the code page of the resultis the database code page. The length attribute of the result is the same as thatof the first argument. If any specified expression can be NULL, the result canbe NULL. If any specified expression is NULL, the result will be NULL.
char-string-exp or graphic-string-expA string to be translated.
to-string-expIs a string of characters to which certain characters in the char-string-expwill be translated.
If the to-string-exp is not present, and the data type is not graphic, allcharacters in char-string-exp will be in monocase; that is, the characters a-zwill be translated to the characters A-Z, and characters with diacriticalmarks will be translated to their uppercase equivalents, if they exist. Forexample, in code page 850, é maps to É, but ÿ is not mapped, becausecode page 850 does not include Ÿ.
from-string-expIs a string of characters which, if found in the char-string-exp, will betranslated to the corresponding character in the to-string-exp. If the
TRANSLATE
Chapter 3. Functions 475
from-string-exp contains duplicate characters, the first one found will beused, and the duplicates will be ignored. If the to-string-exp is longer thanthe from-string-exp, the surplus characters will be ignored. If theto-string-exp is present, the from-string-exp must also be present.
pad-char-expIs a single character that will be used to pad the to-string-exp if theto-string-exp is shorter than the from-string-exp. The pad-char-exp must havea length attribute of one, or an error is returned. If not present, it will betaken to be a single-byte blank.
The arguments may be either strings of data type CHAR or VARCHAR, orgraphic strings of data type GRAPHIC or VARGRAPHIC. They may not havedata type LONG VARCHAR, LONG VARGRAPHIC, BLOB, CLOB, orDBCLOB.
With graphic-string-exp, only the pad-char-exp is optional (if not provided, itwill be taken to be the double-byte blank), and each argument, including thepad character, must be of graphic data type.
The result is the string that occurs after translating all the characters in thechar-string-exp or graphic-string-exp that occur in the from-string-exp to thecorresponding character in the to-string-exp or, if no corresponding characterexists, to the pad character specified by the pad-char-exp.
The code page of the result of TRANSLATE is the same as the code page ofthe first operand. As of Version 8, if the first operand is a host variable, thecode page of the result is the database code page. Each of the other operandsis converted to the result code page unless it or the first operand is defined asFOR BIT DATA (in which case there is no conversion).
If the arguments are of data type CHAR or VARCHAR, the correspondingcharacters of the to-string-exp and the from-string-exp must have the samenumber of bytes. For example, it is not valid to translate a single-bytecharacter to a multi-byte character or vice versa. An error will result if anattempt is made to do this. The pad-char-exp must not be the first byte of avalid multi-byte character, or SQLSTATE 42815 is returned. If the pad-char-expis not present, it will be taken to be a single-byte blank.
If only the char-string-exp is specified, single-byte characters will bemonocased and multi-byte characters will remain unchanged.
Examples:v Assume the host variable SITE (VARCHAR(30)) has a value of ’Hanauma
Bay’.TRANSLATE(:SITE)
TRANSLATE
476 SQL Reference, Volume 1
Returns the value ’HANAUMA BAY’.TRANSLATE(:SITE ’j’,’B’)
Returns the value ’Hanauma jay’.TRANSLATE(:SITE,’ei’,’aa’)
Returns the value ’Heneume Bey’.TRANSLATE(:SITE,’bA’,’Bay’,’%’)
Returns the value ’HAnAumA bA%’.TRANSLATE(:SITE,’r’,’Bu’)
Returns the value ’Hana ma ray’.
TRANSLATE
Chapter 3. Functions 477
TRUNCATE or TRUNC
�� TRUNCATETRUNC
( expression1 , expression2 ) ��
The schema is SYSIBM. (The SYSFUN version of the TRUNCATE or TRUNCfunction continues to be available.)
Returns expression1 truncated to expression2 places to the right of the decimalpoint if expression2 is positive, or to the left of the decimal point if expression2is zero or negative.
expression1An expression that returns a value of any built-in numeric data type.
expression2An expression that returns a small or a large integer. The absolute valueof the integer specifies the number of places to the right of the decimalpoint for the result if expression2 is not negative, or to left of the decimalpoint if expression2 is negative.
If the absolute value of expression2 is larger than the number of digits tothe left of the decimal point, the result is 0. For example:
TRUNCATE(748.58,-4) = 0
The data type and length attribute of the result are the same as the data typeand length attribute of the first argument.
The result can be null if the argument can be null or the database isconfigured with DFT_SQLMATHWARN set to YES; the result is the null valueif the argument is null.
Examples:v Using the EMPLOYEE table, calculate the average monthly salary for the
highest paid employee. Truncate the result two places to the right of thedecimal point.
SELECT TRUNCATE(MAX(SALARY)/12,2)FROM EMPLOYEE;
Because the highest paid employee earns $52750.00 per year, the examplereturns 4395.83.
v Display the number 873.726 truncated 2, 1, 0, -1, and -2 decimal places,respectively.
VALUES (TRUNC(873.726,2),TRUNC(873.726,1),
TRUNCATE or TRUNC
478 SQL Reference, Volume 1
TRUNC(873.726,0),TRUNC(873.726,-1),TRUNC(873.726,-2),TRUNC(873.726,-3) );
This example returns 873.720, 873.700, 873.000, 870.000, 800.000, and 0.000.
TRUNCATE or TRUNC
Chapter 3. Functions 479
TYPE_ID
�� TYPE_ID ( expression ) ��
The schema is SYSIBM.
The TYPE_ID function returns the internal type identifier of the dynamic datatype of the expression.
The argument must be a user-defined structured type. (This function cannotbe used as a source function when creating a user-defined function. Because itaccepts any structured data type as an argument, it is not necessary to createadditional signatures to support different user-defined types.)
The data type of the result of the function is INTEGER. If expression can benull, the result can be null; if expression is null, the result is the null value.
The value returned by the TYPE_ID function is not portable across databases.The value may be different, even though the type schema and type name ofthe dynamic data type are the same. When coding for portability, use theTYPE_SCHEMA and TYPE_NAME functions to determine the type schemaand type name.
Examples:v A table hierarchy exists having root table EMPLOYEE of type EMP and
subtable MANAGER of type MGR. Another table ACTIVITIES includes acolumn called WHO_RESPONSIBLE that is defined as REF(EMP) SCOPEEMPLOYEE. For each reference in ACTIVITIES, display the internal typeidentifier of the row that corresponds to the reference.
SELECT TASK, WHO_RESPONSIBLE−>NAME,TYPE_ID(DEREF(WHO_RESPONSIBLE))
FROM ACTIVITIES
The DEREF function is used to return the object corresponding to the row.
TYPE_ID
480 SQL Reference, Volume 1
TYPE_NAME
�� TYPE_NAME ( expression ) ��
The schema is SYSIBM.
The TYPE_NAME function returns the unqualified name of the dynamic datatype of the expression.
The argument must be a user-defined structured type. (This function cannotbe used as a source function when creating a user-defined function. Because itaccepts any structured data type as an argument, it is not necessary to createadditional signatures to support different user-defined types.)
The data type of the result of the function is VARCHAR(18). If expression canbe null, the result can be null; if expression is null, the result is the null value.Use the TYPE_SCHEMA function to determine the schema name of the typename returned by TYPE_NAME.
Examples:v A table hierarchy exists having root table EMPLOYEE of type EMP and
subtable MANAGER of type MGR. Another table ACTIVITIES includes acolumn called WHO_RESPONSIBLE that is defined as REF(EMP) SCOPEEMPLOYEE. For each reference in ACTIVITIES, display the type of the rowthat corresponds to the reference.
SELECT TASK, WHO_RESPONSIBLE−>NAME,TYPE_NAME(DEREF(WHO_RESPONSIBLE)),TYPE_SCHEMA(DEREF(WHO_RESPONSIBLE))
FROM ACTIVITIES
The DEREF function is used to return the object corresponding to the row.
TYPE_NAME
Chapter 3. Functions 481
TYPE_SCHEMA
�� TYPE_SCHEMA ( expression ) ��
The schema is SYSIBM.
The TYPE_SCHEMA function returns the schema name of the dynamic datatype of the expression.
The argument must be a user-defined structured type. This function cannot beused as a source function when creating a user-defined function. Because itaccepts any structured data type as an argument, it is not necessary to createadditional signatures to support different user-defined types.
The data type of the result of the function is VARCHAR(128). If expression canbe null, the result can be null; if expression is null, the result is the null value.Use the TYPE_NAME function to determine the type name associated withthe schema name returned by TYPE_SCHEMA.
Related reference:
v “TYPE_NAME” on page 481
TYPE_SCHEMA
482 SQL Reference, Volume 1
UCASE or UPPER
�� UCASE ( expression )UPPER
��
The schema is SYSIBM. (The SYSFUN version of this function continues to beavailable for upward compatibility. See Version 5 documentation for adescription.)
The UCASE or UPPER function is identical to the TRANSLATE functionexcept that only the first argument (char-string-exp) is specified.
Notes:
This function has been extended to recognize the lowercase and uppercaseproperties of a Unicode character. In a Unicode database, all Unicodecharacters correctly convert to uppercase.
Related reference:
v “TRANSLATE” on page 475
UCASE or UPPER
Chapter 3. Functions 483
VALUE
�� VALUE ( expression � ,expression ) ��
The schema is SYSIBM.
The VALUE function returns the first argument that is not null.
VALUE is a synonym for COALESCE.
Related reference:
v “COALESCE” on page 311
VALUE
484 SQL Reference, Volume 1
VARCHAR
Character to Varchar:
�� VARCHAR ( character-string-expression, integer
) ��
Datetime to Varchar:
�� VARCHAR ( datetime-expression ) ��
Graphic to Varchar:
�� VARCHAR ( graphic-string-expression ), integer
��
The schema is SYSIBM.
The VARCHAR function returns a varying-length character stringrepresentation of:v A character string, if the first argument is any type of character stringv A graphic string (Unicode databases only), if the first argument is any type
of graphic stringv A datetime value, if the argument is a date, time, or timestamp.
Character to Varchar
character-string-expressionAn expression whose value must be of a character-string data type otherthan LONG VARGRAPHIC and DBCLOB, with a maximum length of32 672 bytes.
integerThe length attribute for the resulting varying-length character string. Thevalue must be between 0 and 32 672. If this argument is not specified, thelength of the result is the same as the length of the argument.
Datetime to Varchar
datetime-expressionAn expression whose value must be of a date, time, or timestamp datatype.
Graphic to Varchar
VARCHAR
Chapter 3. Functions 485
graphic-string-expressionAn expression whose value must be of a graphic-string data type otherthan LONG VARGRAPHIC and DBCLOB, with a maximum length of16 336 bytes.
integerThe length attribute for the resulting varying-length character string. Thevalue must be between 0 and 32 672. If this argument is not specified, thelength of the result is the same as the length of the argument.
Example:v Using the EMPLOYEE table, set the host variable JOB_DESC
(VARCHAR(8)) to the VARCHAR equivalent of the job description (JOBdefined as CHAR(8)) for employee Dolores Quintana.
SELECT VARCHAR(JOB)INTO :JOB_DESCFROM EMPLOYEEWHERE LASTNAME = ’QUINTANA’
VARCHAR
486 SQL Reference, Volume 1
VARCHAR_FORMAT
�� VARCHAR_FORMAT ( timestamp-expression ,format-string ) ��
The schema is SYSIBM.
The VARCHAR_FORMAT function returns a character representation of atimestamp that has been formatted using a character template.
timestamp-expressionAn expression that results in a timestamp. The argument must be atimestamp or a string representation of a timestamp that is neither aCLOB nor a LONG VARCHAR. (If string-expression is an untypedparameter marker, the type is assumed to be TIMESTAMP.) The stringexpression returns a CHAR or a VARCHAR value whose maximumlength is not greater than 254 (SQLSTATE 42815). Leading and trailingblanks are removed from string-expression, and the resulting substring isinterpreted as a timestamp using the format specified by format-string.Leading zeros can be omitted from any timestamp components except theyear. Blanks can be used in place of leading zeros for these components.For example, with a format string of ’YYYY-MM-DD HH24:MI:SS’, each ofthe following strings is an acceptable specification for 9 a.m. on January 1,2000:
’2000-1-01 09:00:00’ (single digit for month)’2000- 1-01 09:00:00’ (single digit - preceded by a blank - for month)’2000-1-1 09:00:00’ (single digits for month and day)’2000-01-01 9:00:00’ (single digit for hour)’2000-01-01 09:0:0’ (single digits for minutes and seconds)’2000- 1- 1 09: 0: 0’ (single digit - preceded by a blank - for month,
day, minutes, and seconds)’2000-01-01 09:00:00’ (maximum number of digits for each element)
format-stringA character constant that contains a template for how the result is to beformatted. The length of the format string must not be greater than 254(SQLSTATE 42815). Leading and trailing blanks are removed fromformat-string, and the resulting substring must be a valid template for atimestamp value (SQLSTATE 42815). The content of format-string can bespecified in mixed case.
Valid format strings are:’YYYY-MM-DD HH24:MI:SS’
where YYYY represents a 4-digit year value; MM represents a 2-digitmonth value (01-12; January=01); DD represents a 2-digit day of themonth value (01-31); HH24 represents a 2-digit hour of the day value
VARCHAR_FORMAT
Chapter 3. Functions 487
(00-24; If the hour is 24, the minutes and seconds values are zero.); MIrepresents a 2-digit minute value (00-59); and SS represents a 2-digitseconds value (00-59).
The result of the function is a varying-length character string containing aformatted timestamp expression. The format string also determines the lengthattribute and the actual length of the result. If format-string is ’YYYY-MM-DDHH24:MI:SS’, the length attribute is 19. The result is 19 characters of the form:
YYYY-MM-DD HH:MI:SS
For example, with format ’YYYY-MM-DD HH24:MI:SS’ and a time and date of 10a.m. on January 1, 2000, the following is returned:
’2000-01-01 10:00:00’
Even though the values for month and day only require a single digit, in thisexample, each significant digit is preceded with a leading zero. And, eventhough the minutes and seconds values are both zero, the maximum numberof digits are used for each, and ’00’ is returned for each of these parts in theresult.
If the first argument can be null, the result can be null; if the first argument isnull, the result is the null value. The CCSID of the result is the SBCS CCSIDof the system.
Example:v Display the table names and creation timestamps for all of the system tables
whose name starts with ’SYSU’.SELECT VARCHAR(name, 20) AS TABLE_NAME,
VARCHAR_FORMAT(ctime, ’YYYY-MM-DD HH24:MI:SS’) AS CREATION_TIMEFROM SYSCAT.TABLESWHERE name LIKE ’SYSU%’
This example returns the following:TABLE_NAME CREATION_TIME-------------------- -------------------SYSUSERAUTH 2000-05-19 08:18:56SYSUSEROPTIONS 2000-05-19 08:18:56
VARCHAR_FORMAT
488 SQL Reference, Volume 1
VARGRAPHIC
Character to Vargraphic:
�� VARGRAPHIC ( character-string-expression ) ��
Datetime to Vargraphic:
�� VARGRAPHIC ( datetime-expression ) ��
Graphic to Vargraphic:
�� VARGRAPHIC ( graphic-string-expression, integer
) ��
The schema is SYSIBM.
The VARGRAPHIC function returns a varying-length graphic stringrepresentation of:v A character string, converting single-byte characters to double-byte
characters, if the first argument is any type of character stringv A graphic string, if the first argument is any type of graphic stringv A datetime value (Unicode databases only), if the argument is a date, time,
or timestamp.
The result of the function is a varying length graphic string (VARGRAPHICdata type). If the first argument can be null, the result can be null; if the firstargument is null, the result is the null value.
Character to Vargraphic
character-string-expressionAn expression whose value must be of a character string data type otherthan LONG VARCHAR or CLOB, and whose maximum length must notbe greater than 16 336 bytes.
The length attribute of the result is equal to the length attribute of theargument.
Let S denote the value of the character-string-expression. Each single-bytecharacter in S is converted to its equivalent double-byte representation or tothe double-byte substitution character in the result; each double-byte characterin S is mapped ’as-is’. If the first byte of a double-byte character appears as
VARGRAPHIC
Chapter 3. Functions 489
the last byte of S, it is converted into the double-byte substitution character.The sequential order of the characters in S is preserved.
The following are additional considerations for the conversion.v For a Unicode database, this function converts the character string from the
code page of the operand to UCS-2. Every character of the operand,including double-byte characters, is converted. If the second argument isgiven, it specifies the desired length of the resulting string (in UCS-2characters).
v The conversion to double-byte code points by the VARGRAPHIC functionis based on the code page of the operand.
v Double-byte characters of the operand are not converted. All othercharacters are converted to their corresponding double-byte equivalent. Ifthere is no corresponding double-byte equivalent, the double-bytesubstitution character for the code page is used.
v No warning or error code is generated if one or more double-bytesubstitution characters are returned in the result.
Datetime to Vargraphic
datetime-expressionAn expression whose value must be of the DATE, TIME, or TIMESTAMPdata type.
Graphic to Vargraphic
graphic-string-expressionAn expression that returns a value that is a graphic string.
integerThe length attribute for the resulting varying length graphic string. Thevalue must be between 0 and 16 336. If this argument is not specified, thelength of the result is the same as the length of the argument.
If the length of the graphic-string-expression is greater than the length attributeof the result, truncation is performed and a warning is returned (SQLSTATE01004), unless the truncated characters were all blanks and thegraphic-string-expression was not a long string (LONG VARGRAPHIC orDBCLOB).
Related reference:
v Appendix P, “Japanese and traditional-Chinese extended UNIX code (EUC)considerations” on page 883
VARGRAPHIC
490 SQL Reference, Volume 1
WEEK
�� WEEK ( expression ) ��
Returns the week of the year of the argument as an integer value in range1-54. The week starts with Sunday.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
WEEK
Chapter 3. Functions 491
WEEK_ISO
�� WEEK_ISO ( expression ) ��
The schema is SYSFUN.
Returns the week of the year of the argument as an integer value in the range1-53. The week starts with Monday and always includes 7 days. Week 1 is thefirst week of the year to contain a Thursday, which is equivalent to the firstweek containing January 4. It is therefore possible to have up to 3 days at thebeginning of a year appear in the last week of the previous year. Conversely,up to 3 days at the end of a year may appear in the first week of the nextyear.
The argument must be a date, timestamp, or a valid character stringrepresentation of a date or timestamp that is neither a CLOB nor a LONGVARCHAR.
The result of the function is INTEGER. The result can be null; if the argumentis null, the result is the null value.
Example:
The following list shows examples of the result of WEEK_ISO andDAYOFWEEK_ISO.DATE WEEK_ISO DAYOFWEEK_ISO---------- ----------- -------------1997-12-28 52 71997-12-31 1 31998-01-01 1 41999-01-01 53 51999-01-04 1 11999-12-31 52 52000-01-01 52 62000-01-03 1 1
WEEK_ISO
492 SQL Reference, Volume 1
YEAR
�� YEAR ( expression ) ��
The schema is SYSIBM.
The YEAR function returns the year part of a value.
The argument must be a date, timestamp, date duration, timestamp durationor a valid character string representation of a date or timestamp that is neithera CLOB nor a LONG VARCHAR.
The result of the function is a large integer. If the argument can be null, theresult 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:v If the argument is a date, timestamp, or valid string representation of a date
or timestamp:– The result is the year part of the value, which is an integer between 1
and 9 999.v If the argument is a date duration or timestamp duration:
– The result is the year part of the value, which is an integer between−9 999 and 9 999. A nonzero result has the same sign as the argument.
Examples:v Select all the projects in the PROJECT table that are scheduled to start
(PRSTDATE) and end (PRENDATE) in the same calendar year.SELECT * FROM PROJECT
WHERE YEAR(PRSTDATE) = YEAR(PRENDATE)
v Select all the projects in the PROJECT table that are scheduled to take lessthan one year to complete.
SELECT * FROM PROJECTWHERE YEAR(PRENDATE - PRSTDATE) < 1
YEAR
Chapter 3. Functions 493
Table functions
A table function can be used only in the FROM clause of a statement. Tablefunctions return columns of a table, resembling a table created through asimple CREATE TABLE statement. Table functions can be qualified with aschema name.
Table functions
494 SQL Reference, Volume 1
MQREADALL
�� MQREADALL (receive-service
, service-policynum-rows
) ��
The schema is MQDB2.
The MQREADALL function returns a table containing the messages andmessage metadata from the MQSeries location specified by receive-service,using the quality of service policy service-policy. Performing this operationdoes not remove the messages from the queue associated with receive-service.
If num-rows is specified, then a maximum of num-rows messages will bereturned. If num-rows is not specified, then all available messages will bereturned. The table returned contains the following columns:v MSG - a VARCHAR(4000) column containing the contents of the MQSeries
message.v CORRELID - a VARCHAR(24) column holding a correlation ID used to
relate messages.v TOPIC - a VARCHAR(40) column holding the topic that the message was
published with, if available.v QNAME - a VARCHAR(48) column holding the queue name where the
message was received.v MSGID - a CHAR(24) column holding the assigned MQSeries unique
identifier for this message.v MSGFORMAT - a VARCHAR(8) column holding the format of the message,
as defined by MQSeries. Typical strings have a MQSTR format.
receive-serviceA string containing the logical MQSeries destination from which themessage is read. If specified, the receive-service must refer to a servicepoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, then the DB2.DEFAULT.SERVICE will beused. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in the handlingof this message. If specified, the service-policy refers to a Policy defined inthe AMT.XML repository file. A service policy defines a set of quality ofservice options that should be applied to this messaging operation. Theseoptions include message priority and message persistence. See the
MQREADALL
Chapter 3. Functions 495
MQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
num-rowsA positive integer containing the maximum number of messages to bereturned by the function.
Examples:
Example 1: This example receives all the messages from the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). The messages and all the metadata are returned asa table.SELECT *
FROM table (MQREADALL()) T
Example 2: This example receives all the messages from the head of the queuespecified by the service MYSERVICE, using the default policy(DB2.DEFAULT.POLICY). Only the MSG and CORRELID columns arereturned.SELECT T.MSG, T.CORRELID
FROM table (MQREADALL(’MYSERVICE’)) T
Example 3: This example reads the head of the queue specified by the defaultservice (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). Only messages with a CORRELID of ’1234’ arereturned. All columns are returned.SELECT *
FROM table (MQREADALL()) TWHERE T.CORRELID = ’1234’
Example 4: This example receives the first 10 messages from the head of thequeue specified by the default service (DB2.DEFAULT.SERVICE), using thedefault policy (DB2.DEFAULT.POLICY). All columns are returned.SELECT *
FROM table (MQREADALL(10)) T
MQREADALL
496 SQL Reference, Volume 1
MQREADALLCLOB
�� MQREADALLCLOB (receive-service
, service-policynum-rows
) ��
The schema is DB2MQ.
The MQREADALLCLOB function returns a table containing the messages andmessage metadata from the MQSeries location specified by receive-service,using the quality of service policy service-policy. Performing this operationdoes not remove the messages from the queue associated with receive-service.
If num-rows is specified, then a maximum of num-rows messages will bereturned. If num-rows is not specified, then all available messages will bereturned. The table returned contains the following columns:v MSG - a CLOB column containing the contents of the MQSeries message.v CORRELID - a VARCHAR(24) column holding a correlation ID used to
relate messages.v TOPIC - a VARCHAR(40) column holding the topic that the message was
published with, if available.v QNAME - a VARCHAR(48) column holding the queue name where the
message was received.v MSGID - a CHAR(24) column holding the assigned MQSeries unique
identifier for this message.v MSGFORMAT - a VARCHAR(8) column holding the format of the message,
as defined by MQSeries. Typical strings have an MQSTR format.
receive-serviceA string containing the logical MQSeries destination from which themessage is read. If specified, the receive-service must refer to a servicepoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface for further details. Ifreceive-service is not specified, then the DB2.DEFAULT.SERVICE will beused. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in the handlingof this message. If specified, the service-policy refers to a Policy defined inthe AMT XML repository file. A service policy defines a set of quality ofservice options that should be applied to this messaging operation. Theseoptions include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. If
MQREADALLCLOB
Chapter 3. Functions 497
service-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
num-rowsA positive integer containing the maximum number of messages to bereturned by the function.
Examples:
Example 1: This example receives all the messages from the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). The messages and all the metadata are returned asa table.
SELECT *FROM table (MQREADALLCLOB()) T
Example 2: This example receives all the messages from the head of the queuespecified by the service MYSERVICE, using the default policy(DB2.DEFAULT.POLICY). Only the MSG and CORRELID columns arereturned.
SELECT T.MSG, T.CORRELIDFROM table (MQREADALLCLOB(’MYSERVICE’)) T
Example 3: This example reads the head of the queue specified by the defaultservice (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). Only messages with a CORRELID of ’1234’ arereturned. All columns are returned.
SELECT *FROM table (MQREADALLCLOB()) TWHERE T.CORRELID = ’1234’
Example 4: This example receives the first 10 messages from the head of thequeue specified by the default service (DB2.DEFAULT.SERVICE), using thedefault policy (DB2.DEFAULT.POLICY). All columns are returned.
SELECT *FROM table (MQREADALLCLOB(10)) T
MQREADALLCLOB
498 SQL Reference, Volume 1
MQRECEIVEALL
�� MQRECEIVEALL (receive-service
, service-policy, correl-id
�
�num-rows
,
) ��
The schema is MQDB2.
The MQRECEIVEALL function returns a table containing the messages andmessage metadata from the MQSeries location specified by receive-service,using the quality of service policy service-policy. Performing this operationremoves the messages from the queue associated with receive-service.
If a correl-id is specified, then only those messages with a matching correlationidentifier will be returned. If correl-id is not specified, then the message at thehead of the queue will be returned.
If num-rows is specified, then a maximum of num-rows messages will bereturned. If num-rows is not specified, then all available messages are returned.The table returned contains the following columns:v MSG - a VARCHAR(4000) column containing the contents of the MQSeries
message.v CORRELID - a VARCHAR(24) column holding a correlation ID used to
relate messages.v TOPIC - a VARCHAR(40) column holding the topic that the message was
published with, if available.v QNAME - a VARCHAR(48) column holding the queue name where the
message was received.v MSGID - a CHAR(24) column holding the assigned MQSeries unique
identifier for this message.v MSGFORMAT - a VARCHAR(8) column holding the format of the message,
as defined by MQSeries. Typical strings have a MQSTR format.
receive-serviceA string containing the logical MQSeries destination from which themessage is received. If specified, the receive-service must refer to a servicepoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface manual for further
MQRECEIVEALL
Chapter 3. Functions 499
details. If receive-service is not specified, then the DB2.DEFAULT.SERVICEwill be used. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in the handlingof this message. If specified, the service-policy refers to a Policy defined inthe AMT.XML repository file. A service policy defines a set of quality ofservice options that should be applied to this messaging operation. Theseoptions include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
correl-idAn optional string containing a correlation identifier associated with thismessage. The correl-id is often specified in request and reply scenarios toassociate requests with replies. If not specified, no correlation id isspecified. The maximum size of correl-id is 24 bytes.
num-rowsA positive integer containing the maximum number of messages to bereturned by the function.
Examples:
Example 1: This example receives all the messages from the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). The messages and all the metadata are returned asa table.SELECT *
FROM table (MQRECEIVEALL()) T
Example 2: This example receives all the messages from the head of the queuespecified by the service MYSERVICE, using the default policy(DB2.DEFAULT.POLICY). Only the MSG and CORRELID columns arereturned.SELECT T.MSG, T.CORRELID
FROM table (MQRECEIVEALL(’MYSERVICE’)) T
Example 3: This example receives all of the message from the head of thequeue specified by the service ″MYSERVICE″, using the policy ″MYPOLICY″.Only messages with a CORRELID of ’1234’ are returned. Only the MSG andCORRELID columns are returned.SELECT T.MSG, T.CORRELID
FROM table (MQRECEIVEALL(’MYSERVICE’,’MYPOLICY’,’1234’)) T
MQRECEIVEALL
500 SQL Reference, Volume 1
Example 4: This example receives the first 10 messages from the head of thequeue specified by the default service (DB2.DEFAULT.SERVICE), using thedefault policy (DB2.DEFAULT.POLICY). All columns are returned.SELECT *
FROM table (MQRECEIVEALL(10)) T
MQRECEIVEALL
Chapter 3. Functions 501
MQRECEIVEALLCLOB
�� MQRECEIVEALLCLOB ( �
�receive-service
, service-policy, correl-id
num-rows,
�
� ) ��
The schema is DB2MQ.
The MQRECEIVEALLCLOB function returns a table containing the messagesand message metadata from the MQSeries location specified by receive-service,using the quality of service policy service-policy. Performing this operationremoves the messages from the queue associated with receive-service.
If a correl-id is specified, then only those messages with a matching correlationidentifier will be returned. If correl-id is not specified, then the message at thehead of the queue will be returned.
If num-rows is specified, then a maximum of num-rows messages will bereturned. If num-rows is not specified, then all available messages are returned.The table returned contains the following columns:v MSG - a CLOB column containing the contents of the MQSeries message.v CORRELID - a VARCHAR(24) column holding a correlation ID used to
relate messages.v TOPIC - a VARCHAR(40) column holding the topic that the message was
published with, if available.v QNAME - a VARCHAR(48) column holding the queue name where the
message was received.v MSGID - a CHAR(24) column holding the assigned MQSeries unique
identifier for this message.v MSGFORMAT - a VARCHAR(8) column holding the format of the message,
as defined by MQSeries. Typical strings have an MQSTR format.
receive-serviceA string containing the logical MQSeries destination from which themessage is received. If specified, the receive-service must refer to a servicepoint defined in the AMT.XML repository file. A service point is a logicalend-point from which a message is sent or received. Service pointdefinitions include the name of the MQSeries Queue Manager and Queue.See the MQSeries Application Messaging Interface manual for further
MQRECEIVEALLCLOB
502 SQL Reference, Volume 1
details. If receive-service is not specified, then the DB2.DEFAULT.SERVICEwill be used. The maximum size of receive-service is 48 bytes.
service-policyA string containing the MQSeries AMI Service Policy used in the handlingof this message. If specified, the service-policy refers to a Policy defined inthe AMT XML repository file. A service policy defines a set of quality ofservice options that should be applied to this messaging operation. Theseoptions include message priority and message persistence. See theMQSeries Application Messaging Interface manual for further details. Ifservice-policy is not specified, then the default DB2.DEFAULT.POLICY willbe used. The maximum size of service-policy is 48 bytes.
correl-idAn optional string containing a correlation identifier associated with thismessage. The correl-id is often specified in request and reply scenarios toassociate requests with replies. If not specified, no correlation id isspecified. The maximum size of correl-id is 24 bytes.
num-rowsA positive integer containing the maximum number of messages to bereturned by the function.
Examples:
Example 1: This example receives all the messages from the queue specifiedby the default service (DB2.DEFAULT.SERVICE), using the default policy(DB2.DEFAULT.POLICY). The messages and all the metadata are returned asa table.
SELECT *FROM table (MQRECEIVEALLCLOB()) T
Example 2: This example receives all the messages from the head of the queuespecified by the service MYSERVICE, using the default policy(DB2.DEFAULT.POLICY). Only the MSG and CORRELID columns arereturned.
SELECT T.MSG, T.CORRELIDFROM table (MQRECEIVEALLCLOB(’MYSERVICE’)) T
Example 3: This example receives all of the message from the head of thequeue specified by the service ″MYSERVICE″, using the policy ″MYPOLICY″.Only messages with a CORRELID of ’1234’ are returned. Only the MSG andCORRELID columns are returned.
SELECT T.MSG, T.CORRELIDFROM table (MQRECEIVEALLCLOB(’MYSERVICE’,’MYPOLICY’,’1234’)) T
MQRECEIVEALLCLOB
Chapter 3. Functions 503
Example 4: This example receives the first 10 messages from the head of thequeue specified by the default service (DB2.DEFAULT.SERVICE), using thedefault policy (DB2.DEFAULT.POLICY). All columns are returned.
SELECT *FROM table (MQRECEIVEALLCLOB(10)) T
MQRECEIVEALLCLOB
504 SQL Reference, Volume 1
SNAPSHOT_AGENT
�� SNAPSHOT_AGENT ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_AGENT function returns information about agents from anapplication snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR APPLICATIONS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_APPLS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 20. Column names and data types of the table returned by theSNAPSHOT_AGENT table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
AGENT_PID BIGINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_AGENT
Chapter 3. Functions 505
SNAPSHOT_APPL
�� SNAPSHOT_APPL ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_APPL function returns general information from anapplication snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR APPLICATIONS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_APPLS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 21. Column names and data types of the table returned by theSNAPSHOT_APPL table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
UOW_LOG_SPACE_USED BIGINT
ROWS_READ BIGINT
ROWS_WRITTEN BIGINT
POOL_DATA_L_READS BIGINT
POOL_DATA_P_READS BIGINT
POOL_DATA_WRITES BIGINT
POOL_INDEX_L_READS BIGINT
SNAPSHOT_APPL
506 SQL Reference, Volume 1
Table 21. Column names and data types of the table returned by theSNAPSHOT_APPL table function (continued)
Column name Data type
POOL_INDEX_P_READS BIGINT
POOL_INDEX_WRITES BIGINT
POOL_READ_TIME BIGINT
POOL_WRITE_TIME BIGINT
DIRECT_READS BIGINT
DIRECT_WRITES BIGINT
DIRECT_READ_REQS BIGINT
DIRECT_WRITE_REQS BIGINT
DIRECT_READ_TIME BIGINT
DIRECT_WRITE_TIME BIGINT
POOL_DATA_TO_ESTORE BIGINT
POOL_INDEX_TO_ESTORE BIGINT
POOL_INDEX_FROM_ESTORE BIGINT
POOL_DATA_FROM_ESTORE BIGINT
UNREAD_PREFETCH_PAGES BIGINT
LOCKS_HELD BIGINT
LOCK_WAITS BIGINT
LOCK_WAIT_TIME BIGINT
LOCK_ESCALS BIGINT
X_LOCK_ESCALS BIGINT
DEADLOCKS BIGINT
TOTAL_SORTS BIGINT
TOTAL_SORT_TIME BIGINT
SORT_OVERFLOWS BIGINT
COMMIT_SQL_STMTS BIGINT
ROLLBACK_SQL_STMTS BIGINT
DYNAMIC_SQL_STMTS BIGINT
STATIC_SQL_STMTS BIGINT
FAILED_SQL_STMTS BIGINT
SELECT_SQL_STMTS BIGINT
DDL_SQL_STMTS BIGINT
SNAPSHOT_APPL
Chapter 3. Functions 507
Table 21. Column names and data types of the table returned by theSNAPSHOT_APPL table function (continued)
Column name Data type
UID_SQL_STMTS BIGINT
INT_AUTO_REBINDS BIGINT
INT_ROWS_DELETED BIGINT
INT_ROWS_UPDATED BIGINT
INT_COMMITS BIGINT
INT_ROLLBACKS BIGINT
INT_DEADLOCK_ROLLBACKS BIGINT
ROWS_DELETED BIGINT
ROWS_INSERTED BIGINT
ROWS_UPDATED BIGINT
ROWS_SELECTED BIGINT
BINDS_PRECOMPILES BIGINT
OPEN_REM_CURS BIGINT
OPEN_REM_CURS_BLK BIGINT
REJ_CURS_BLK BIGINT
ACC_CURS_BLK BIGINT
SQL_REQS_SINCE_COMMIT BIGINT
LOCK_TIMEOUTS BIGINT
INT_ROWS_INSERTED BIGINT
OPEN_LOC_CURS BIGINT
OPEN_LOC_CURS_BLK BIGINT
PKG_CACHE_LOOKUPS BIGINT
PKG_CACHE_INSERTS BIGINT
CAT_CACHE_LOOKUPS BIGINT
CAT_CACHE_INSERTS BIGINT
CAT_CACHE_OVERFLOWS BIGINT
CAT_CACHE_HEAP_FULL BIGINT
NUM_AGENTS BIGINT
AGENTS_STOLEN BIGINT
ASSOCIATED_AGENTS_TOP BIGINT
APPL_PRIORITY BIGINT
SNAPSHOT_APPL
508 SQL Reference, Volume 1
Table 21. Column names and data types of the table returned by theSNAPSHOT_APPL table function (continued)
Column name Data type
APPL_PRIORITY_TYPE BIGINT
PREFETCH_WAIT_TIME BIGINT
APPL_SECTION_LOOKUPS BIGINT
APPL_SECTION_INSERTS BIGINT
LOCKS_WAITING BIGINT
TOTAL_HASH_JOINS BIGINT
TOTAL_HASH_LOOPS BIGINT
HASH_JOIN_OVERFLOWS BIGINT
HASH_JOIN_SMALL_OVERFLOWS BIGINT
APPL_IDLE_TIME BIGINT
UOW_LOCK_WAIT_TIME BIGINT
UOW_COMP_STATUS BIGINT
AGENT_USR_CPU_TIME_S BIGINT
AGENT_USR_CPU_TIME_MS BIGINT
AGENT_SYS_CPU_TIME_S BIGINT
AGENT_SYS_CPU_TIME_MS BIGINT
APPL_CON_TIME TIMESTAMP
CONN_COMPLETE_TIME TIMESTAMP
LAST_RESET TIMESTAMP
UOW_START_TIME TIMESTAMP
UOW_STOP_TIME TIMESTAMP
PREV_UOW_STOP_TIME TIMESTAMP
UOW_ELAPSED_TIME_S BIGINT
UOW_ELAPSED_TIME_MS BIGINT
ELAPSED_EXEC_TIME_S BIGINT
ELAPSED_EXEC_TIME_MS BIGINT
INBOUND_COMM_ADDRESS VARCHAR(SQLM_COMM_ADDR_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_APPL
Chapter 3. Functions 509
SNAPSHOT_APPL_INFO
�� SNAPSHOT_APPL_INFO ( INT, VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_APPL_INFO function returns general information from anapplication snapshot.
The arguments must be:v A valid snapshot API request type, as defined in sqllib\function\sqlmon.h.v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
For the save to file option, if both the database name and the partitionnumber are NULLs, the result of the snapshot will be returned only if asnapshot of the same request type has previously been taken through theSYSPROC.SNAPSHOT_FILEW stored procedure; otherwise, a new snapshotwill be taken for the currently connected database and the current partitionnumber (as though the partition number had been set to -1).
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 22. Column names and data types of the table returned by theSNAPSHOT_APPL_INFO table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
APPL_STATUS BIGINT
CODEPAGE_ID BIGINT
NUM_ASSOC_AGENTS BIGINT
COORD_PARTITION_NUM SMALLINT
AUTHORITY_LVL BIGINT
CLIENT_PID BIGINT
SNAPSHOT_APPL_INFO
510 SQL Reference, Volume 1
Table 22. Column names and data types of the table returned by theSNAPSHOT_APPL_INFO table function (continued)
Column name Data type
COORD_AGENT_PID BIGINT
STATUS_CHANGE_TIME TIMESTAMP
CLIENT_PLATFORM SMALLINT
CLIENT_PROTOCOL SMALLINT
COUNTRY_CODE SMALLINT
APPL_NAME VARCHAR(255)
APPL_ID VARCHAR(32)
SEQUENCE_NO VARCHAR(4)
AUTH_ID VARCHAR(30)
CLIENT_NNAME VARCHAR(20)
CLIENT_PRDID VARCHAR(20)
INPUT_DB_ALIAS VARCHAR(20)
CLIENT_DB_ALIAS VARCHAR(20)
DB_NAME VARCHAR(8)
DB_PATH VARCHAR(256)
EXECUTION_ID VARCHAR(20)
CORR_TOKEN VARCHAR(32)
TPMON_CLIENT_USERID VARCHAR(20)
TPMON_CLIENT_WKSTN VARCHAR(20)
TPMON_CLIENT_APP VARCHAR(20)
TPMON_ACC_STR VARCHAR(100)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_APPL_INFO
Chapter 3. Functions 511
SNAPSHOT_BP
�� SNAPSHOT_BP ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_BP function returns information from a buffer pool snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR BUFFERPOOLS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_BUFFERPOOLS, and
iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 23. Column names and data types of the table returned by the SNAPSHOT_BPtable function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
POOL_DATA_L_READS BIGINT
POOL_DATA_P_READS BIGINT
POOL_DATA_WRITES BIGINT
POOL_INDEX_L_READS BIGINT
POOL_INDEX_P_READS BIGINT
POOL_INDEX_WRITES BIGINT
POOL_READ_TIME BIGINT
POOL_WRITE_TIME BIGINT
POOL_ASYNC_DATA_READS BIGINT
SNAPSHOT_BP
512 SQL Reference, Volume 1
Table 23. Column names and data types of the table returned by the SNAPSHOT_BPtable function (continued)
Column name Data type
POOL_ASYNC_DATA_WRITES BIGINT
POOL_ASYNC_INDEX_WRITES BIGINT
POOL_ASYNC_READ_TIME BIGINT
POOL_ASYNC_WRITE_TIME BIGINT
POOL_ASYNC_DATA_READ_REQS BIGINT
DIRECT_READS BIGINT
DIRECT_WRITES BIGINT
DIRECT_READ_REQS BIGINT
DIRECT_WRITE_REQS BIGINT
DIRECT_READ_TIME BIGINT
DIRECT_WRITE_TIME BIGINT
POOL_ASYNC_INDEX_READS BIGINT
POOL_DATA_TO_ESTORE BIGINT
POOL_INDEX_TO_ESTORE BIGINT
POOL_INDEX_FROM_ESTORE BIGINT
POOL_DATA_FROM_ESTORE BIGINT
UNREAD_PREFETCH_PAGES BIGINT
FILES_CLOSED BIGINT
BP_NAME VARCHAR(SQLM_IDENT_SZ)
DB_NAME VARCHAR(SQL_DBNAME_SZ)
DB_PATH VARCHAR(SQLM_DBPATH_SZ)
INPUT_DB_ALIAS VARCHAR(SQL_DBNAME_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_BP
Chapter 3. Functions 513
SNAPSHOT_CONTAINER
�� SNAPSHOT_CONTAINER ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_CONTAINER function returns container configurationinformation from a tablespace snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR TABLESPACE ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_TABLESPACES, and
iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 24. Column names and data types of the table returned by theSNAPSHOT_CONTAINER table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
TABLESPACE_ID BIGINT
TABLESPACE_NAME VARCHAR(128)
CONTAINER_ID BIGINT
CONTAINER_NAME VARCHAR(255)
CONTAINER_TYPE SMALLINT
TOTAL_PAGES BIGINT
USABLE_PAGES BIGINT
ACCESSIBLE BIGINT
SNAPSHOT_CONTAINER
514 SQL Reference, Volume 1
Table 24. Column names and data types of the table returned by theSNAPSHOT_CONTAINER table function (continued)
Column name Data type
STRIPE_SET BIGINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_CONTAINER
Chapter 3. Functions 515
SNAPSHOT_DATABASE
�� SNAPSHOT_DATABASE ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_DATABASE function returns information from a databasesnapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR DATABASE ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE, and iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 25. Column names and data types of the table returned by theSNAPSHOT_DATABASE table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
SEC_LOG_USED_TOP BIGINT
TOT_LOG_USED_TOP BIGINT
TOTAL_LOG_USED BIGINT
TOTAL_LOG_AVAILABLE BIGINT
ROWS_READ BIGINT
POOL_DATA_L_READS BIGINT
POOL_DATA_P_READS BIGINT
POOL_DATA_WRITES BIGINT
POOL_INDEX_L_READS BIGINT
SNAPSHOT_DATABASE
516 SQL Reference, Volume 1
Table 25. Column names and data types of the table returned by theSNAPSHOT_DATABASE table function (continued)
Column name Data type
POOL_INDEX_P_READS BIGINT
POOL_INDEX_WRITES BIGINT
POOL_READ_TIME BIGINT
POOL_WRITE_TIME BIGINT
POOL_ASYNC_INDEX_READS BIGINT
POOL_DATA_TO_ESTORE BIGINT
POOL_INDEX_TO_ESTORE BIGINT
POOL_INDEX_FROM_ESTORE BIGINT
POOL_DATA_FROM_ESTORE BIGINT
POOL_ASYNC_DATA_READS BIGINT
POOL_ASYNC_DATA_WRITES BIGINT
POOL_ASYNC_INDEX_WRITES BIGINT
POOL_ASYNC_READ_TIME BIGINT
POOL_ASYNC_WRITE_TIME BIGINT
POOL_ASYNC_DATA_READ_REQS BIGINT
DIRECT_READS BIGINT
DIRECT_WRITES BIGINT
DIRECT_READ_REQS BIGINT
DIRECT_WRITE_REQS BIGINT
DIRECT_READ_TIME BIGINT
DIRECT_WRITE_TIME BIGINT
UNREAD_PREFETCH_PAGES BIGINT
FILES_CLOSED BIGINT
POOL_LSN_GAP_CLNS BIGINT
POOL_DRTY_PG_STEAL_CLNS BIGINT
POOL_DRTY_PG_THRSH_CLNS BIGINT
LOCKS_HELD BIGINT
LOCK_WAITS BIGINT
LOCK_WAIT_TIME BIGINT
LOCK_LIST_IN_USE BIGINT
DEADLOCKS BIGINT
SNAPSHOT_DATABASE
Chapter 3. Functions 517
Table 25. Column names and data types of the table returned by theSNAPSHOT_DATABASE table function (continued)
Column name Data type
LOCK_ESCALS BIGINT
X_LOCK_ESCALS BIGINT
LOCKS_WAITING BIGINT
SORT_HEAP_ALLOCATED BIGINT
TOTAL_SORTS BIGINT
TOTAL_SORT_TIME BIGINT
SORT_OVERFLOWS BIGINT
ACTIVE_SORTS BIGINT
COMMIT_SQL_STMTS BIGINT
ROLLBACK_SQL_STMTS BIGINT
DYNAMIC_SQL_STMTS BIGINT
STATIC_SQL_STMTS BIGINT
FAILED_SQL_STMTS BIGINT
SELECT_SQL_STMTS BIGINT
DDL_SQL_STMTS BIGINT
UID_SQL_STMTS BIGINT
INT_AUTO_REBINDS BIGINT
INT_ROWS_DELETED BIGINT
INT_ROWS_UPDATED BIGINT
INT_COMMITS BIGINT
INT_ROLLBACKS BIGINT
INT_DEADLOCK_ROLLBACKS BIGINT
ROWS_DELETED BIGINT
ROWS_INSERTED BIGINT
ROWS_UPDATED BIGINT
ROWS_SELECTED BIGINT
BINDS_PRECOMPILES BIGINT
TOTAL_CONS BIGINT
APPLS_CUR_CONS BIGINT
APPLS_IN_DB2 BIGINT
SEC_LOGS_ALLOCATED BIGINT
SNAPSHOT_DATABASE
518 SQL Reference, Volume 1
Table 25. Column names and data types of the table returned by theSNAPSHOT_DATABASE table function (continued)
Column name Data type
DB_STATUS BIGINT
LOCK_TIMEOUTS BIGINT
CONNECTIONS_TOP BIGINT
DB_HEAP_TOP BIGINT
INT_ROWS_INSERTED BIGINT
LOG_READS BIGINT
LOG_WRITES BIGINT
PKG_CACHE_LOOKUPS BIGINT
PKG_CACHE_INSERTS BIGINT
CAT_CACHE_LOOKUPS BIGINT
CAT_CACHE_INSERTS BIGINT
CAT_CACHE_OVERFLOWS BIGINT
CAT_CACHE_HEAP_FULL BIGINT
CATALOG_PARTITION SMALLINT
TOTAL_SEC_CONS BIGINT
NUM_ASSOC_AGENTS BIGINT
AGENTS_TOP BIGINT
COORD_AGENTS_TOP BIGINT
PREFETCH_WAIT_TIME BIGINT
APPL_SECTION_LOOKUPS BIGINT
APPL_SECTION_INSERTS BIGINT
TOTAL_HASH_JOINS BIGINT
TOTAL_HASH_LOOPS BIGINT
HASH_JOIN_OVERFLOWS BIGINT
HASH_JOIN_SMALL_OVERFLOWS BIGINT
PKG_CACHE_NUM_OVERFLOWS BIGINT
PKG_CACHE_SIZE_TOP BIGINT
DB_CONN_TIME TIMESTAMP
SQLM_ELM_LAST_RESET TIMESTAMP
SQLM_ELM_LAST_BACKUP TIMESTAMP
APPL_CON_TIME TIMESTAMP
SNAPSHOT_DATABASE
Chapter 3. Functions 519
Table 25. Column names and data types of the table returned by theSNAPSHOT_DATABASE table function (continued)
Column name Data type
DB_LOCATION INTEGER
SERVER_PLATFORM INTEGER
APPL_ID_OLDEST_XACT BIGINT
CATALOG_PARTITION_NAME VARCHAR(SQL_NNAME_SZ)
INPUT_DB_ALIAS VARCHAR(SQL_DBNAME_SZ)
DB_NAME VARCHAR(SQL_DBNAME_SZ)
DB_PATH VARCHAR(SQLM_DBPATH_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_DATABASE
520 SQL Reference, Volume 1
SNAPSHOT_DBM
�� SNAPSHOT_DBM ( INT ) ��
The schema is SYSPROC.
The SNAPSHOT_DBM function returns information from a snapshot of theDB2 database manager.
The argument must be a valid partition number. Specify -1 for the currentpartition, -2 for all partitions. If NULL is specified, -1 is set implicitly.
If NULL is specified, the snapshot will be taken only if a file has notpreviously been created by either:v A GET SNAPSHOT FOR DBM ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DB2, and iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 26. Column names and data types of the table returned by the SNAPSHOT_DBMtable function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
SORT_HEAP_ALLOCATED BIGINT
POST_THRESHOLD_SORTS BIGINT
PIPED_SORTS_REQUESTED BIGINT
PIPED_SORTS_ACCEPTED BIGINT
REM_CONS_IN BIGINT
REM_CONS_IN_EXEC BIGINT
LOCAL_CONS BIGINT
LOCAL_CONS_IN_EXEC BIGINT
CON_LOCAL_DBASES BIGINT
AGENTS_REGISTERED BIGINT
AGENTS_WAITING_ON_TOKEN BIGINT
DB2_STATUS BIGINT
AGENTS_REGISTERED_TOP BIGINT
SNAPSHOT_DBM
Chapter 3. Functions 521
Table 26. Column names and data types of the table returned by the SNAPSHOT_DBMtable function (continued)
Column name Data type
AGENTS_WAITING_TOP BIGINT
COMM_PRIVATE_MEM BIGINT
IDLE_AGENTS BIGINT
AGENTS_FROM_POOL BIGINT
AGENTS_CREATED_EMPTY_POOL BIGINT
COORD_AGENTS_TOP BIGINT
MAX_AGENT_OVERFLOWS BIGINT
AGENTS_STOLEN BIGINT
GW_TOTAL_CONS BIGINT
GW_CUR_CONS BIGINT
GW_CONS_WAIT_HOST BIGINT
GW_CONS_WAIT_CLIENT BIGINT
POST_THRESHOLD_HASH_JOINS BIGINT
INACTIVE_GW_AGENTS BIGINT
NUM_GW_CONN_SWITCHES BIGINT
DB2START_TIME TIMESTAMP
LAST_RESET TIMESTAMP
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_DBM
522 SQL Reference, Volume 1
SNAPSHOT_DYN_SQL
�� SNAPSHOT_DYN_SQL ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_DYN_SQL function returns information from a dynamic SQLsnapshot. It replaces the SQLCACHE_SNAPSHOT function, which is stillavailable for compatibility reasons.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR LOCKS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_LOCKS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 27. Column names and data types of the table returned by theSNAPSHOT_DYN_SQL table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
ROWS_READ BIGINT
ROWS_WRITTEN BIGINT
NUM_EXECUTIONS BIGINT
NUM_COMPILATIONS BIGINT
PREP_TIME_WORST BIGINT
PREP_TIME_BEST BIGINT
INT_ROWS_DELETED BIGINT
INT_ROWS_INSERTED BIGINT
SNAPSHOT_DYN_SQL
Chapter 3. Functions 523
Table 27. Column names and data types of the table returned by theSNAPSHOT_DYN_SQL table function (continued)
Column name Data type
INT_ROWS_UPDATED BIGINT
STMT_SORTS BIGINT
TOTAL_EXEC_TIME BIGINT
TOTAL_SYS_CPU_TIME BIGINT
TOTAL_USR_CPU_TIME BIGINT
STMT_TEXT CLOB(65536)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_DYN_SQL
524 SQL Reference, Volume 1
SNAPSHOT_FCM
�� SNAPSHOT_FCM ( INT ) ��
The schema is SYSPROC.
The SNAPSHOT_FCM function returns database manager level informationregarding the fast communication manager (FCM).
The function returns a table as shown below.
Table 28. Column names and data types of the table returned by the SNAPSHOT_FCMtable function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
BUFF_FREE BIGINT
BUFF_FREE_BOTTOM BIGINT
MA_FREE BIGINT
MA_FREE_BOTTOM BIGINT
CE_FREE BIGINT
CE_FREE_BOTTOM BIGINT
RB_FREE BIGINT
RB_FREE_BOTTOM BIGINT
PARTITION_NUMBER SMALLINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_FCM
Chapter 3. Functions 525
SNAPSHOT_FCMPARTITION
�� SNAPSHOT_FCMPARTITION ( INT ) ��
The schema is SYSPROC.
The SNAPSHOT_FCMPARTITION function returns information from asnapshot of the fast communication manager in the database manager.
The argument must be a valid partition number. Specify -1 for the currentpartition, -2 for all partitions. If NULL is specified, -1 is set implicitly.
If NULL is specified, the snapshot will be taken only if a file has notpreviously been created by either:v A GET SNAPSHOT FOR DBM ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DB2, and iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 29. Column names and data types of the table returned by theSNAPSHOT_FCMPARTITION table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
CONNECTION_STATUS BIGINT
TOTAL_BUFFERS_SENT BIGINT
TOTAL_BUFFERS_RCVD BIGINT
PARTITION_NUMBER SMALLINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_FCMPARTITION
526 SQL Reference, Volume 1
SNAPSHOT_LOCK
�� SNAPSHOT_LOCK ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_LOCK function returns information from a lock snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR LOCKS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_LOCKS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 30. Column names and data types of the table returned by theSNAPSHOT_LOCK table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
TABLE_FILE_ID BIGINT
LOCK_OBJECT_TYPE BIGINT
LOCK_MODE BIGINT
LOCK_STATUS BIGINT
LOCK_OBJECT_NAME BIGINT
PARTITION_NUMBER SMALLINT
LOCK_ESCALATION SMALLINT
SNAPSHOT_LOCK
Chapter 3. Functions 527
Table 30. Column names and data types of the table returned by theSNAPSHOT_LOCK table function (continued)
Column name Data type
TABLE_NAME VARCHAR(SQL_MAX_TABLE_NAME_LEN)
TABLE_SCHEMA VARCHAR(SQL_MAX_SCHEMA_NAME_LEN)
TABLESPACE_NAME VARCHAR(SQLB_MAX_TBS_NAME_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_LOCK
528 SQL Reference, Volume 1
SNAPSHOT_LOCKWAIT
�� SNAPSHOT_LOCKWAIT ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_LOCKWAIT function returns lock waits information from anapplication snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR APPLICATIONS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_APPLS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 31. Column names and data types of the table returned by theSNAPSHOT_LOCKWAIT table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
SUBSECTION_NUMBER BIGINT
LOCK_MODE BIGINT
LOCK_OBJECT_TYPE BIGINT
AGENT_ID_HOLDING_LK BIGINT
LOCK_WAIT_START_TIME TIMESTAMP
LOCK_MODE_REQUESTED BIGINT
PARTITION_NUMBER SMALLINT
SNAPSHOT_LOCKWAIT
Chapter 3. Functions 529
Table 31. Column names and data types of the table returned by theSNAPSHOT_LOCKWAIT table function (continued)
Column name Data type
LOCK_ESCALLATION SMALLINT
TABLE_NAME VARCHAR(SQL_MAX_TABLE_NAME_LEN)
TABLE_SCHEMA VARCHAR(SQL_MAX_SCHEMA_NAME_LEN)
TABLESPACE_NAME VARCHAR(SQLB_MAX_TBS_NAME_SZ)
APPL_ID_HOLDING_LK VARCHAR(SQLM_APPLID_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_LOCKWAIT
530 SQL Reference, Volume 1
SNAPSHOT_QUIESCERS
�� SNAPSHOT_QUIESCERS ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
The function returns a table as shown below.
Table 32. Column names and data types of the table returned by theSNAPSHOT_QUIESCERS table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
TABLESPACE_NAME VARCHAR(128)
QUIESCER_TBS_ID BIGINT
QUIESCER_OBJ_ID BIGINT
QUIESCER_AUTH_ID BIGINT
QUIESCER_AGENT_ID BIGINT
QUIESCER_STATE BIGINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_QUIESCERS
Chapter 3. Functions 531
SNAPSHOT_RANGES
�� SNAPSHOT_RANGES ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_RANGES function returns information from a rangesnapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
The function returns a table as shown below.
Table 33. Column names and data types of the table returned by theSNAPSHOT_RANGES table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
TABLESPACE_ID BIGINT
TABLESPACE_NAME VARCHAR(128)
RANGE_NUMBER BIGINT
RANGE_STRIPE_SET_NUMBER BIGINT
RANGE_OFFSET BIGINT
RANGE_MAX_PAGE BIGINT
RANGE_MAX_EXTENT BIGINT
RANGE_START_STRIPE BIGINT
RANGE_END_STRIPE BIGINT
RANGE_ADJUSTMENT BIGINT
RANGE_NUM_CONTAINER BIGINT
RANGE_CONTAINER_ID BIGINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_RANGES
532 SQL Reference, Volume 1
SNAPSHOT_STATEMENT
�� SNAPSHOT_STATEMENT ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_STATEMENT function returns information about statementsfrom an application snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR APPLICATIONS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_APPLS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 34. Column names and data types of the table returned by theSNAPSHOT_STATEMENT table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
AGENT_ID BIGINT
ROWS_READ BIGINT
ROWS_WRITTEN BIGINT
NUM_AGENTS BIGINT
AGENTS_TOP BIGINT
STMT_TYPE BIGINT
STMT_OPERATION BIGINT
SECTION_NUMBER BIGINT
SNAPSHOT_STATEMENT
Chapter 3. Functions 533
Table 34. Column names and data types of the table returned by theSNAPSHOT_STATEMENT table function (continued)
Column name Data type
QUERY_COST_ESTIMATE BIGINT
QUERY_CARD_ESTIMATE BIGINT
DEGREE_PARALLELISM BIGINT
STMT_SORTS BIGINT
TOTAL_SORT_TIME BIGINT
SORT_OVERFLOWS BIGINT
INT_ROWS_DELETED BIGINT
INT_ROWS_UPDATED BIGINT
INT_ROWS_INSERTED BIGINT
FETCH_COUNT BIGINT
STMT_START TIMESTAMP
STMT_STOP TIMESTAMP
STMT_USR_CPU_TIME_S BIGINT
STMT_USR_CPU_TIME_MS BIGINT
STMT_SYS_CPU_TIME_S BIGINT
STMT_SYS_CPU_TIME_MS BIGINT
STMT_ELAPSED_TIME_S BIGINT
STMT_ELAPSED_TIME_MS BIGINT
BLOCKING_CURSOR SMALLINT
STMT_PARTITION_NUMBER SMALLINT
CURSOR_NAME VARCHAR(SQL_MAX_CURSOR_NAME_LEN)
CREATOR VARCHAR(SQL_MAX_SCHEMA_NAME_LEN)
PACKAGE_NAME VARCHAR(SQLM_IDENT_SZ)
STMT_TEXT CLOB(65536)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_STATEMENT
534 SQL Reference, Volume 1
SNAPSHOT_SUBSECT
�� SNAPSHOT_SUBSECT ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_SUBSECT function returns information about subsections ofaccess plans from an application snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR APPLICATIONS ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_APPLS, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 35. Column names and data types of the table returned by theSNAPSHOT_SUBSECT table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
STMT_TEXT CLOB(65536)
SS_EXEC_TIME BIGINT
TQ_TOT_SEND_SPILLS BIGINT
TQ_CUR_SEND_SPILLS BIGINT
TQ_MAX_SEND_SPILLS BIGINT
TQ_ROWS_READ BIGINT
TQ_ROWS_WRITTEN BIGINT
ROWS_READ BIGINT
SNAPSHOT_SUBSECT
Chapter 3. Functions 535
Table 35. Column names and data types of the table returned by theSNAPSHOT_SUBSECT table function (continued)
Column name Data type
ROWS_WRITTEN BIGINT
SS_USR_CPU_TIME BIGINT
SS_SYS_CPU_TIME BIGINT
SS_NUMBER INTEGER
SS_STATUS INTEGER
SS_PARTITION_NUMBER SMALLINT
TQ_PARTITION_WAITED_FOR SMALLINT
TQ_WAIT_FOR_ANY INTEGER
TQ_ID_WAITING_ON INTEGER
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_SUBSECT
536 SQL Reference, Volume 1
SNAPSHOT_SWITCHES
�� SNAPSHOT_SWITCHES ( INT ) ��
The schema is SYSPROC.
The SNAPSHOT_SWITCHES function returns information about the databasesnapshot switch state. The function returns a table as shown below.
Table 36. Column names and data types of the table returned by theSNAPSHOT_SWITCHES table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
UOW_SW_STATE SMALLINT
UOW_SW_TIME TIMESTAMP
STATEMENT_SW_STATE SMALLINT
STATEMENT_SW_TIME TIMESTAMP
TABLE_SW_STATE SMALLINT
TABLE_SW_TIME TIMESTAMP
BUFFPOOL_SW_STATE SMALLINT
BUFFPOOL_SW_TIME TIMESTAMP
LOCK_SW_STATE SMALLINT
LOCK_SW_TIME TIMESTAMP
SORT_SW_STATE SMALLINT
SORT_SW_TIME TIMESTAMP
PARTITION_NUMBER SMALLINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_SWITCHES
Chapter 3. Functions 537
SNAPSHOT_TABLE
�� SNAPSHOT_TABLE ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_TABLE function returns activity information from a tablesnapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR TABLES ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_TABLES, and iStoreResult set
to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 37. Column names and data types of the table returned by theSNAPSHOT_TABLE table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
ROWS_WRITTEN BIGINT
ROWS_READ BIGINT
OVERFLOW_ACCESSES BIGINT
TABLE_FILE_ID BIGINT
TABLE_TYPE BIGINT
PAGE_REORGS BIGINT
TABLE_NAME VARCHAR(SQL_MAX_TABLE_NAME_LEN)
SNAPSHOT_TABLE
538 SQL Reference, Volume 1
Table 37. Column names and data types of the table returned by theSNAPSHOT_TABLE table function (continued)
Column name Data type
TABLE_SCHEMA VARCHAR(SQL_MAX_SCHEMA_NAME_LEN)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_TABLE
Chapter 3. Functions 539
SNAPSHOT_TBS
�� SNAPSHOT_TBS ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_TBS function returns activity information from a table spacesnapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR TABLESPACE ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_TABLESPACES, and
iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 38. Column names and data types of the table returned by the SNAPSHOT_TBStable function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
POOL_DATA_L_READS BIGINT
POOL_DATA_P_READS BIGINT
POOL_ASYNC_DATA_READS BIGINT
POOL_DATA_WRITES BIGINT
POOL_ASYNC_DATA_WRITES BIGINT
POOL_INDEX_L_READS BIGINT
POOL_INDEX_P_READS BIGINT
POOL_INDEX_WRITES BIGINT
SNAPSHOT_TBS
540 SQL Reference, Volume 1
Table 38. Column names and data types of the table returned by the SNAPSHOT_TBStable function (continued)
Column name Data type
POOL_ASYNC_INDEX_WRITES BIGINT
POOL_READ_TIME BIGINT
POOL_WRITE_TIME BIGINT
POOL_ASYNC_READ_TIME BIGINT
POOL_ASYNC_WRITE_TIME BIGINT
POOL_ASYNC_DATA_READ_REQS BIGINT
DIRECT_READS BIGINT
DIRECT_WRITES BIGINT
DIRECT_READ_REQS BIGINT
DIRECT_WRITE_REQS BIGINT
DIRECT_READ_TIME BIGINT
DIRECT_WRITE_TIME BIGINT
UNREAD_PREFETCH_PAGES BIGINT
POOL_ASYNC_INDEX_READS BIGINT
POOL_DATA_TO_ESTORE BIGINT
POOL_INDEX_TO_ESTORE BIGINT
POOL_INDEX_FROM_ESTORE BIGINT
POOL_DATA_FROM_ESTORE BIGINT
FILES_CLOSED BIGINT
TABLESPACE_NAME VARCHAR(SQLB_MAX_TBS_NAME_SZ)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_TBS
Chapter 3. Functions 541
SNAPSHOT_TBS_CFG
�� SNAPSHOT_TBS_CFG ( VARCHAR(255), INT ) ��
The schema is SYSPROC.
The SNAPSHOT_TBS_CFG function returns configuration information from atable space snapshot.
The arguments must be:v A valid database name in the same instance as the currently connected
database when calling this UDF. Specify NULL to take the snapshot fromthe currently connected database.
v A valid partition number. Specify -1 for the current partition, -2 for allpartitions. If NULL is specified, -1 is set implicitly.
If both parameters are set to NULL, the snapshot will be taken only if a filehas not previously been created by either:v A GET SNAPSHOT FOR TABLESPACE ... WRITE TO FILE command, orv A db2GetSnapshot API with SQLMA_DBASE_TABLESPACES, and
iStoreResult set to TRUE.
Writing snapshots to files is only valid with an existing connection. Thesnapshot UDF must then be used within the same session. The file is removedafter the connection is closed.
The function returns a table as shown below.
Table 39. Column names and data types of the table returned by theSNAPSHOT_TBS_CFG table function
Column name Data type
SNAPSHOT_TIMESTAMP TIMESTAMP
TABLESPACE_ID BIGINT
TABLESPACE_NAME VARCHAR(128)
TABLESPACE_TYPE SMALLINT
TABLESPACE_STATE BIGINT
NUM_QUIESCERS BIGINT
STATE_CHANGE_OBJ_ID BIGINT
STATE_CHANGE_TBS_ID BIGINT
MIN_RECOVERY_TIME TIMESTAMP
SNAPSHOT_TBS_CFG
542 SQL Reference, Volume 1
Table 39. Column names and data types of the table returned by theSNAPSHOT_TBS_CFG table function (continued)
Column name Data type
TBS_CONTENTS_TYPE SMALLINT
BUFFERPOOL_ID BIGINT
NEXT_BUFFERPOOL_ID BIGINT
PAGE_SIZE BIGINT
EXTENT_SIZE BIGINT
PREFETCH_SIZE BIGINT
TOTAL_PAGES BIGINT
USABLE_PAGES BIGINT
USED_PAGES BIGINT
FREE_PAGES BIGINT
PENDING_FREE_PAGES BIGINT
HIGH_WATER_MARK BIGINT
REBALANCER_MODE BIGINT
REBALANCER_EXTENTS_REMAINING BIGINT
REBALANCER_EXTENTS_PROCESSED BIGINT
REBALANCER_PRIORITY BIGINT
REBALANCER_START_TIME TIMESTAMP
REBALANCER_RESTART_TIME TIMESTAMP
LAST_EXTENT_MOVED BIGINT
NUM_RANGES BIGINT
NUM_CONTAINERS BIGINT
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SNAPSHOT_TBS_CFG
Chapter 3. Functions 543
SQLCACHE_SNAPSHOT
�� SQLCACHE_SNAPSHOT ( ) ��
The schema is SYSPROC.
The SQLCACHE_SNAPSHOT function returns the results of a snapshot of theDB2 dynamic SQL statement cache.
The function does not take any arguments. It returns a table, as shown below.
Table 40. Column names and data types of the table returned bySQLCACHE_SNAPSHOT table function
Column name Data type
NUM_EXECUTIONS INTEGER
NUM_COMPILATIONS INTEGER
PREP_TIME_WORST INTEGER
PREP_TIME_BEST INTEGER
INT_ROWS_DELETED INTEGER
INT_ROWS_INSERTED INTEGER
ROWS_READ INTEGER
INT_ROWS_UPDATED INTEGER
ROWS_WRITE INTEGER
STMT_SORTS INTEGER
TOTAL_EXEC_TIME_S INTEGER
TOTAL_EXEC_TIME_MS INTEGER
TOT_U_CPU_TIME_S INTEGER
TOT_U_CPU_TIME_MS INTEGER
TOT_S_CPU_TIME_S INTEGER
TOT_S_CPU_TIME_MS INTEGER
DB_NAME VARCHAR(8)
STMT_TEXT CLOB(64K)
Related reference:
v “Snapshot monitor logical data groups and data elements” in the SystemMonitor Guide and Reference
SQLCACHE_SNAPSHOT
544 SQL Reference, Volume 1
Procedures
A procedure is an application program that can be started through the SQLCALL statement. The procedure is specified by a procedure name, which maybe followed by arguments that are enclosed within parentheses.
The argument or arguments of a procedure are individual scalar values, whichcan be of different types and can have different meanings. The arguments canbe used to pass values into the procedure, receive return values from theprocedure, or both.
User-defined procedures are procedures that are registered to a database inSYSCAT.ROUTINES, using the CREATE PROCEDURE statement. One suchset of functions is provided with the database manager, in a schema calledSYSFUN, and another in a schema called SYSPROC.
Procedures can be qualified with the schema name.
Procedures
Chapter 3. Functions 545
GET_ROUTINE_SAR
�� GET_ROUTINE_SAR �
� ( sarblob , type , routine_name_string ), hide_body_flag
��
The schema is SYSFUN.
The GET_ROUTINE_SAR procedure retrieves the necessary information toinstall the same routine in another database server running the same level onthe same operating system. The information is retrieved into a single BLOBstring representing an SQL archive file. The invoker of theGET_ROUTINE_SAR procedure must have DBADM authority.
sarblobAn output argument of type BLOB(3M) that contains the routine SAR filecontents.
typeAn input argument of type CHAR(2) that specifies whether the type ofroutine, using one of the following values:v P for a procedure.v SP for the specific name of a procedure.
routine_name_stringAn input argument of type VARCHAR(257) that specifies a qualifiedname of the routine. If no schema name is specified, the default is theCURRENT SCHEMA when the routine is processed. Theroutine_name_string cannot include double quotation marks (").
hide_body_flagAn input argument of type INTEGER that specifies (using one of thefollowing values) whether or not the routine body should be hidden whenthe routine text is extracted from the catalogs. Valid values are:
0 Leave the routine text intact. This is the default value.
1 Replace the routine body with an empty body when the routinetext is extracted from the catalogs.
The qualified name of the routine is used to determine which routine toretrieve. The routine that is found must be an SQL routine. Not using aspecific name may result in more than one routine, and an error is raised(SQLSTATE 42725). If this occurs, the specific name of the desired routinemust be used.
GET_ROUTINE_SAR
546 SQL Reference, Volume 1
The SAR file must include a bind file, which may not be available at theserver. If the bind file cannot be found and stored in the SAR file, an error israised (SQLSTATE 55045).
GET_ROUTINE_SAR
Chapter 3. Functions 547
PUT_ROUTINE_SAR
�� PUT_ROUTINE_SAR ( sarblob, new_owner , use_register_flag
) ��
The schema is SYSFUN.
The PUT_ROUTINE_SAR procedure passes the necessary file to create an SQLroutine at the server and then defines the routine. The invoker of thePUT_ROUTINE_SAR procedure must have DBADM authority.
sarblobAn input argument of type BLOB(3M) that contains the routine SAR filecontents.
new_ownerAn input argument of type VARCHAR(128) that contains anauthorization-name used for authorization checking of the routine. Thenew-owner must have the necessary privileges for the routine to bedefined. If new-owner is not specified, the authorization-name of theoriginal routine definer is used.
use_register_flagAn input argument of type INTEGER that indicates whether or not theCURRENT SCHEMA and CURRENT PATH special registers are used todefine the routine. If the special registers are not used, the settings for thedefault schema and SQL path are the settings used when the routine wasoriginally defined. Possible values for use-register-flag:
0 Do not use the special registers of the current environment
1 Use the CURRENT SCHEMA and CURRENT PATH special registers.
If the value is 1, CURRENT SCHEMA is used for unqualified objectnames in the routine definition (including the name of the routine) andCURRENT PATH is used to resolve unqualified routines and data types inthe routine definition. If the use-registers-flag is not specified, the behavioris the same as if a value of 0 was specified.
The identification information contained in sarblob is checked to confirm thatthe inputs are appropriate for the environment, otherwise an error is raised(SQLSTATE 55046). The PUT_ROUTINE_SAR procedure then uses thecontents of the sarblob to define the routine at the server.
The contents of the sarblob argument are extracted into the separate files thatmake up the SQL archive file. The shared library and bind files are written tofiles in a temporary directory. The environment is set so that the routinedefinition statement processing is aware that compiling and linking are not
PUT_ROUTINE_SAR
548 SQL Reference, Volume 1
required, and that the location of the shared library and bind files is available.The contents of the DDL file are then used to dynamically execute the routinedefinition statement.
Note: No more than one procedure can be concurrently installed under agiven schema.
Processing of this statement may result in the same errors as executing theroutine definition statement using other interfaces. During routine definitionprocessing, the presence of the shared library and bind files is noted and theprecompile, compile and link steps are skipped. The bind file is used duringbind processing and the contents of both files are copied to the usualdirectory for an SQL routine.
Note: If a GET ROUTINE or a PUT ROUTINE operation (or theircorresponding procedure) fails to execute successfully, it will alwaysreturn an error (SQLSTATE 38000), along with diagnostic text providinginformation about the cause of the failure. For example, if theprocedure name provided to GET ROUTINE does not identify an SQLprocedure, diagnostic ″-204, 42704″ text will be returned, where ″-204″and ″42704″ are the SQLCODE and SQLSTATE, respectively, thatidentify the cause of the problem. The SQLCODE and SQLSTATE inthis example indicate that the procedure name provided in the GETROUTINE command is undefined.
PUT_ROUTINE_SAR
Chapter 3. Functions 549
User-defined functions
�� function-name (
�
,
expression
) ��
User-defined functions (UDFs) are extensions or additions to the existing built-infunctions of the SQL language. A user-defined function can be a scalarfunction, which returns a single value each time it is called; a columnfunction, which is passed a set of like values and returns a single value forthe set; a row function, which returns one row; or a table function, whichreturns a table.
A number of user-defined functions are provided in the SYSFUN andSYSPROC schemas.
A UDF can be a column function only if it is sourced on an existing columnfunction. A UDF is referenced by means of a qualified or unqualified functionname, followed by parentheses enclosing the function arguments (if any). Auser-defined column or scalar function registered with the database can bereferenced in the same contexts in which any built-in function can appear. Auser-defined row function can be referenced only implicitly when registeredas a transform function for a user-defined type. A user-defined table functionregistered with the database can be referenced only in the FROM clause of aSELECT statement.
Function arguments must correspond in number and position to theparameters specified for the user-defined function when it was registered withthe database. In addition, the arguments must be of data types that arepromotable to the data types of the corresponding defined parameters.
The result of the function is specified in the RETURNS clause. The RETURNSclause, defined when the UDF was registered, determines whether or not afunction is a table function. If the RETURNS NULL ON NULL INPUT clauseis specified (or defaulted to) when the function is registered, the result is nullif any argument is null. In the case of table functions, this is interpreted tomean a return table with no rows (that is, an empty table).
Following are some examples of user-defined functions:v A scalar UDF called ADDRESS extracts the home address from resumes
stored in script format. The ADDRESS function expects a CLOB argumentand returns a VARCHAR(4000) value:
SELECT EMPNO, ADDRESS(RESUME) FROM EMP_RESUMEWHERE RESUME_FORMAT = ’SCRIPT’
User-defined functions
550 SQL Reference, Volume 1
v Table T2 has a numeric column A. Invoking the scalar UDF calledADDRESS from the previous example:
SELECT ADDRESS(A) FROM T2
raises an error (SQLSTATE 42884), because no function with a matchingname and with a parameter that is promotable from the argument exists.
v A table UDF called WHO returns information about the sessions on theserver machine that were active at the time that the statement is executed.The WHO function is invoked from within a FROM clause that includes thekeyword TABLE and a mandatory correlation variable. The column namesof the WHO() table were defined in the CREATE FUNCTION statement.
SELECT ID, START_DATE, ORIG_MACHINEFROM TABLE( WHO() ) AS QQWHERE START_DATE LIKE ’MAY%’
Related reference:
v “Subselect” on page 554v “CREATE FUNCTION statement” in the SQL Reference, Volume 2
User-defined functions
Chapter 3. Functions 551
User-defined functions
552 SQL Reference, Volume 1
Chapter 4. Queries
SQL queries
A query specifies a result table. A query is a component of certain SQLstatements. The three forms of a query are:v subselectv fullselectv select-statement.
Authorization
For each table, view, or nickname referenced in the query, the authorization IDof the statement must have at least one of the following:v SYSADM or DBADM authorityv CONTROL privilegev SELECT privilege.
Group privileges, with the exception of PUBLIC, are not checked for queriesthat are contained in static SQL statements.
For nicknames, authorization requirements of the data source for the objectreferenced by the nickname are applied when the query is processed. Theauthorization ID of the statement may be mapped to a different authorizationID at the data source.
Related reference:
v “SELECT INTO statement” in the SQL Reference, Volume 2
© Copyright IBM Corp. 1993 - 2002 553
Subselect
�� select-clause from-clausewhere-clause group-by-clause
�
�having-clause order-by-clause fetch-first-clause
��
The subselect is a component of the fullselect.
A subselect specifies a result table derived from the tables, views ornicknames identified in the FROM clause. The derivation can be described asa sequence of operations in which the result of each operation is input for thenext. (This is only a way of describing the subselect. The method used toperform the derivation may be quite different from this description.)
The clauses of the subselect are processed in the following sequence:1. FROM clause2. WHERE clause3. GROUP BY clause4. HAVING clause5. SELECT clause6. ORDER BY clause7. FETCH FIRST clause
A subselect that contains an ORDER BY or FETCH FIRST clause cannot bespecified:v In the outermost fullselect of a view.v In a materialized query table.v Unless the subselect is enclosed in parenthesis.
For example, the following is not valid (SQLSTATE 428FJ):SELECT * FROM T1
ORDER BY C1UNIONSELECT * FROM T2
ORDER BY C1
The following example is valid:(SELECT * FROM T1
ORDER BY C1)UNION(SELECT * FROM T2
ORDER BY C1)
Subselect
554 SQL Reference, Volume 1
Note: An ORDER BY clause in a subselect does not affect the order of therows returned by a query. An ORDER BY clause only affects the orderof the rows returned if it is specified in the outermost fullselect.
select-clause
�� SELECTALL
DISTINCT
�
*,
expressionAS
new-column-nameexposed-name.*
��
The SELECT clause specifies the columns of the final result table. The columnvalues are produced by the application of the select list to R. The select list isthe names or expressions specified in the SELECT clause, and R is the resultof the previous operation of the subselect. For example, if the only clausesspecified are SELECT, FROM, and WHERE, R is the result of that WHEREclause.
ALLRetains all rows of the final result table, and does not eliminate redundantduplicates. This is the default.
DISTINCTEliminates all but one of each set of duplicate rows of the final resulttable. If DISTINCT is used, no string column of the result table can be aLONG VARCHAR, LONG VARGRAPHIC, DATALINK, LOB type, distincttype on any of these types, or structured type. DISTINCT may be usedmore than once in a subselect. This includes SELECT DISTINCT, the useof DISTINCT in a column function of the select list or HAVING clause,and subqueries of the subselect.
Two rows are duplicates of one another only if each value in the first isequal to the corresponding value of the second. For determiningduplicates, two null values are considered equal.
Select list notation:
* Represents a list of names that identify the columns of table R. The firstname in the list identifies the first column of R, the second name identifiesthe second column of R, and so on.
The list of names is established when the program containing the SELECTclause is bound. Hence * (the asterisk) does not identify any columns thathave been added to a table after the statement containing the tablereference has been bound.
Subselect
Chapter 4. Queries 555
expressionSpecifies the values of a result column. Can be any expression that is avalid SQL language element, but commonly includes column names. Eachcolumn name used in the select list must unambiguously identify acolumn of R.
new-column-name or AS new-column-nameNames or renames the result column. The name must not be qualifiedand does not have to be unique. Subsequent usage of column-name islimited as follows:v A new-column-name specified in the AS clause can be used in the
order-by-clause, provided the name is unique.v A new-column-name specified in the AS clause of the select list
cannot be used in any other clause within the subselect(where-clause, group-by-clause or having-clause).
v A new-column-name specified in the AS clause cannot be used inthe update-clause.
v A new-column-name specified in the AS clause is known outsidethe fullselect of nested table expressions, common table expressionsand CREATE VIEW.
name.*Represents the list of names that identify the columns of the result tableidentified by exposed-name. The exposed-name may be a table name, viewname, nickname, or correlation name, and must designate a table, view ornickname named in the FROM clause. The first name in the list identifiesthe first column of the table, view or nickname, the second name in thelist identifies the second column of the table, view or nickname, and soon.
The list of names is established when the statement containing theSELECT clause is bound. Therefore, * does not identify any columns thathave been added to a table after the statement has been bound.
The number of columns in the result of SELECT is the same as thenumber of expressions in the operational form of the select list (that is, thelist established when the statement is prepared), and cannot exceed 500for a 4K page size or 1012 for an 8K, 16K, or 32K page size.
Limitations on string columnsFor limitations on the select list, see “Restrictions Using Varying-LengthCharacter Strings”.
Applying the select listSome of the results of applying the select list to R depend on whether or notGROUP BY or HAVING is used. The results are described in two separatelists:
Select list notation:
556 SQL Reference, Volume 1
If GROUP BY or HAVING is used:
v An expression X (not a column function) used in the select list must have aGROUP BY clause with:– a grouping-expression in which each column-name unambiguously
identifies a column of R (see “group-by-clause” on page 569) or– each column of R referenced in X as a separate grouping-expression.
v The select list is applied to each group of R, and the result contains asmany rows as there are groups in R. When the select list is applied to agroup of R, that group is the source of the arguments of the columnfunctions in the select list.
If neither GROUP BY nor HAVING is used:
v Either the select list must not include any column functions, or eachcolumn-name in the select list must be specified within a column function ormust be a correlated column reference.
v If the select does not include column functions, then the select list isapplied to each row of R and the result contains as many rows as there arerows in R.
v If the select list is a list of column functions, then R is the source of thearguments of the functions and the result of applying the select list is onerow.
In either case the nth column of the result contains the values specified byapplying the nth expression in the operational form of the select list.
Null attributes of result columns: Result columns do not allow null values ifthey are derived from:v A column that does not allow null valuesv A constantv The COUNT or COUNT_BIG functionv A host variable that does not have an indicator variablev A scalar function or expression that does not include an operand that
allows nulls.
Result columns allow null values if they are derived from:v Any column function except COUNT or COUNT_BIGv A column that allows null valuesv A scalar function or expression that includes an operand that allows nullsv A NULLIF function with arguments containing equal values.v A host variable that has an indicator variable.v A result of a set operation if at least one of the corresponding items in the
select list is nullable.
If GROUP BY or HAVING is used
Chapter 4. Queries 557
v An arithmetic expression or view column that is derived from an arithmeticexpression and the database is configured with DFT_SQLMATHWARN setto yes
v A dereference operation.
Names of result columns:
v If the AS clause is specified, the name of the result column is the namespecified on the AS clause.
v If the AS clause is not specified and the result column is derived from acolumn, then the result column name is the unqualified name of thatcolumn.
v If the AS clause is not specified and the result column is derived using adereference operation, then the result column name is the unqualified nameof the target column of the dereference operation.
v All other result column names are unnamed. The system assigns temporarynumbers (as character strings) to these columns.
Data types of result columns: Each column of the result of SELECT acquiresa data type from the expression from which it is derived.
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 forDECIMAL columns.
an integer constant INTEGER.
a decimal constant DECIMAL, with the precision and scale ofthe constant.
a floating-point constant DOUBLE.
the name of any numeric variable the same as the data type of the variable,with the same precision and scale forDECIMAL variables.
a hexadecimal constant representing nbytes
VARCHAR(n); the code page is thedatabase code page.
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 variable the same as the data type of the variable,with the same length attribute; if the datatype of the variable is not identical to anSQL data type (for example, aNUL-terminated string in C), the resultcolumn is a varying-length string.
a character string constant of length n VARCHAR(n).
Null attributes of result columns
558 SQL Reference, Volume 1
When the expression is ... The data type of the result column is ...
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 user-defined type column the same as the data type of the column.
the name of a reference type column the same as the data type of the column.
Data types of result columns
Chapter 4. Queries 559
from-clause
�� �
,
FROM table-reference ��
The FROM clause specifies an intermediate result table.
If one table-reference is specified, the intermediate result table is simply theresult of that table-reference. If more than one table-reference is specified, theintermediate result table consists of all possible combinations of the rows ofthe specified table-references (the Cartesian product). Each row of the result isa row from the first table-reference concatenated with a row from the secondtable-reference, concatenated in turn with a row from the third, and so on.The number of rows in the result is the product of the number of rows in allthe individual table-references. For a description of table-reference, see“table-reference” on page 561.
from-clause
560 SQL Reference, Volume 1
table-reference
��
�
nicknametable-name correlation-clauseview-nameONLY ( table-name )OUTER view-name
TABLE ( function-name ( ) ) correlation-clause,
expression(fullselect) correlation-clause
TABLEjoined-table
��
correlation-clause:
�
AScorrelation-name
,
( column-name )
Each table-name, view-name or nickname specified as a table-reference mustidentify an existing table, view or nickname at the application server or thetable-name of a common table expression defined preceding the fullselectcontaining the table-reference. If the table-name references a typed table, thename denotes the UNION ALL of the table with all its subtables, with onlythe columns of the table-name. Similarly, if the view-name references a typedview, the name denotes the UNION ALL of the view with all its subviews,with only the columns of the view-name.
The use of ONLY(table-name) or ONLY(view-name) means that the rows of theproper subtables or subviews are not included. If the table-name used withONLY does not have subtables, then ONLY(table-name) is equivalent tospecifying table-name. If the view-name used with ONLY does not havesubviews, then ONLY(view-name) is equivalent to specifying view-name.
The use of OUTER(table-name) or OUTER(view-name) represents a virtual table.If the table-name or view-name used with OUTER does not have subtables orsubviews, then specifying OUTER is equivalent to not specifying OUTER.OUTER(table-name) is derived from table-name as follows:v The columns include the columns of table-name followed by the additional
columns introduced by each of its subtables (if any). The additionalcolumns are added on the right, traversing the subtable hierarchy indepth-first order. Subtables that have a common parent are traversed increation order of their types.
table-reference
Chapter 4. Queries 561
v The rows include all the rows of table-name and all the rows of its subtables.Null values are returned for columns that are not in the subtable for therow.
The previous points also apply to OUTER(view-name), substituting view-namefor table-name and subview for subtable.
The use of ONLY or OUTER requires the SELECT privilege on every subtableof table-name or subview of view-name.
Each function-name together with the types of its arguments, specified as atable reference must resolve to an existing table function at the applicationserver.
A fullselect in parentheses followed by a correlation name is called a nestedtable expression.
A joined-table specifies an intermediate result set that is the result of one ormore join operations. For more information, see “joined-table” on page 565.
The exposed names of all table references should be unique. An exposedname is:v A correlation-name,v A table-name that is not followed by a correlation-name,v A view-name that is not followed by a correlation-name,v A nickname that is not followed by a correlation-name,v An alias-name that is not followed by a correlation-name.
Each correlation-name is defined as a designator of the immediately precedingtable-name, view-name, nickname, function-name reference or nested tableexpression. Any qualified reference to a column for a table, view, tablefunction or nested table expression must use the exposed name. If the sametable name, view or nickname name is specified twice, at least onespecification should be followed by a correlation-name. The correlation-name isused to qualify references to the columns of the table, view or nickname.When a correlation-name is specified, column-names can also be specified to givenames to the columns of the table-name, view-name, nickname, function-namereference or nested table expression.
In general, table functions and nested table expressions can be specified onany from-clause. Columns from the table functions and nested tableexpressions can be referenced in the select list and in the rest of the subselectusing the correlation name which must be specified. The scope of thiscorrelation name is the same as correlation names for other table, view ornickname in the FROM clause. A nested table expression can be used:
table-reference
562 SQL Reference, Volume 1
v in place of a view to avoid creating the view (when general use of the viewis not required)
v when the desired result table is based on host variables.
Table function referencesIn general, a table function together with its argument values can bereferenced in the FROM clause of a SELECT in exactly the same way as atable or view. There are, however, some special considerations which apply.v Table Function Column Names
Unless alternate column names are provided following the correlation-name,the column names for the table function are those specified in theRETURNS clause of the CREATE FUNCTION statement. This is analogousto the names of the columns of a table, which are defined in the CREATETABLE statement.
v Table Function ResolutionThe arguments specified in a table function reference, together with thefunction name, are used by an algorithm called function resolution todetermine the exact function to be used. This is no different from whathappens with other functions (such as scalar functions), used in astatement.
v Table Function ArgumentsAs with scalar function arguments, table function arguments can in generalbe any valid SQL expression. So the following examples are valid syntax:Example 1: SELECT c1
FROM TABLE( tf1(’Zachary’) ) AS zWHERE c2 = ’FLORIDA’;
Example 2: SELECT c1FROM TABLE( tf2 (:hostvar1, CURRENT DATE) ) AS z;
Example 3: SELECT c1FROM tWHERE c2 IN
(SELECT c3 FROMTABLE( tf5(t.c4) ) AS z -- correlated reference) -- to previous FROM clause
Correlated references in table-referencesCorrelated references can be used in nested table expressions or as argumentsto table functions. The basic rule that applies for both these cases is that thecorrelated reference must be from a table-reference at a higher level in thehierarchy of subqueries. This hierarchy includes the table-references that havealready been resolved in the left-to-right processing of the FROM clause. Fornested table expressions, the TABLE keyword must appear before thefullselect. So the following examples are valid syntax:
table-reference
Chapter 4. Queries 563
Example 1: SELECT t.c1, z.c5FROM t, TABLE( tf3(t.c2) ) AS z -- t precedes tf3WHERE t.c3 = z.c4; -- in FROM, so t.c2
-- is known
Example 2: SELECT t.c1, z.c5FROM t, TABLE( tf4(2 * t.c2) ) AS z -- t precedes tf3WHERE t.c3 = z.c4; -- in FROM, so t.c2
-- is known
Example 3: SELECT d.deptno, d.deptname,empinfo.avgsal, empinfo.empcount
FROM department d,TABLE (SELECT AVG(e.salary) AS avgsal,
COUNT(*) AS empcountFROM employee e -- department precedesWHERE e.workdept=d.deptno -- and TABLE is) AS empinfo; -- specified, so
-- d.deptno is known
But the following examples are not valid:Example 4: SELECT t.c1, z.c5
FROM TABLE( tf6(t.c2) ) AS z, t -- cannot resolve t in t.c2!WHERE t.c3 = z.c4; -- compare to Example 1 above.
Example 5: SELECT a.c1, b.c5FROM TABLE( tf7a(b.c2) ) AS a, TABLE( tf7b(a.c6) ) AS bWHERE a.c3 = b.c4; -- cannot resolve b in b.c2!
Example 6: SELECT d.deptno, d.deptname,empinfo.avgsal, empinfo.empcount
FROM department d,(SELECT AVG(e.salary) AS avgsal,
COUNT(*) AS empcountFROM employee e -- department precedesWHERE e.workdept=d.deptno -- but TABLE is not) AS empinfo; -- specified, so
-- d.deptno is unknown
Correlated references in table-references
564 SQL Reference, Volume 1
joined-table
��INNER
table-reference JOIN table-reference ON join-conditionouter
( joined-table )
��
outer:
OUTERLEFTRIGHTFULL
A joined table specifies an intermediate result table that is the result of eitheran inner join or an outer join. The table is derived by applying one of the joinoperators: INNER, LEFT OUTER, RIGHT OUTER, or FULL OUTER to itsoperands.
Inner joins can be thought of as the cross product of the tables (combine eachrow of the left table with every row of the right table), keeping only the rowswhere the join condition is true. The result table may be missing rows fromeither or both of the joined tables. Outer joins include the inner join andpreserve these missing rows. There are three types of outer joins:v left outer join includes rows from the left table that were missing from the
inner join.v right outer join includes rows from the right table that were missing from
the inner join.v full outer join includes rows from both the left and right tables that were
missing from the inner join.
If a join-operator is not specified, INNER is implicit. The order in whichmultiple joins are performed can affect the result. Joins can be nested withinother joins. The order of processing for joins is generally from left to right, butbased on the position of the required join-condition. Parentheses arerecommended to make the order of nested joins more readable. For example:
TB1 LEFT JOIN TB2 ON TB1.C1=TB2.C1RIGHT JOIN TB3 LEFT JOIN TB4 ON TB3.C1=TB4.C1
ON TB1.C1=TB3.C1
is the same as:(TB1 LEFT JOIN TB2 ON TB1.C1=TB2.C1)
RIGHT JOIN (TB3 LEFT JOIN TB4 ON TB3.C1=TB4.C1)ON TB1.C1=TB3.C1
joined-table
Chapter 4. Queries 565
A joined table can be used in any context in which any form of the SELECTstatement is used. A view or a cursor is read-only if its SELECT statementincludes a joined table.
A join-condition is a search-condition except that:v it cannot contain any subqueries, scalar or otherwisev it cannot include any dereference operations or the DEREF function where
the reference value is other than the object identifier column.v it cannot include an SQL functionv any column referenced in an expression of the join-condition must be a
column of one of the operand tables of the associated join (in the scope ofthe same joined-table clause)
v any function referenced in an expression of the join-condition of a full outerjoin must be deterministic and have no external action.
An error occurs if the join condition does not comply with these rules(SQLSTATE 42972).
Column references are resolved using the rules for resolution of column namequalifiers. The same rules that apply to predicates apply to join conditions.
Join operationsA join-condition specifies pairings of T1 and T2, where T1 and T2 are the leftand right operand tables of the JOIN operator of the join-condition. For allpossible combinations of rows of T1 and T2, a row of T1 is paired with a rowof 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 withthe values of that row of T2. The execution might involve the generation of anull row. The null row of a table consists of a null value for each column ofthe table, regardless of whether the columns allow null values.
The following summarizes the result of the join operations:v The result of T1 INNER JOIN T2 consists of their paired rows where the
join-condition is true.v The result of T1 LEFT OUTER JOIN T2 consists of their paired rows where
the join-condition is true and, for each unpaired row of T1, theconcatenation of that row with the null row of T2. All columns derivedfrom T2 allow null values.
v The result of T1 RIGHT OUTER JOIN T2 consists of their paired rowswhere the join-condition is true and, for each unpaired row of T2, theconcatenation of that row with the null row of T1. All columns derivedfrom T1 allow null values.
v The result of T1 FULL OUTER JOIN T2 consists of their paired rows and,for each unpaired row of T2, the concatenation of that row with the null
joined-table
566 SQL Reference, Volume 1
row of T1 and, for each unpaired row of T1, the concatenation of that rowwith the null row of T2. All columns derived from T1 and T2 allow nullvalues.
Join operations
Chapter 4. Queries 567
where-clause
�� WHERE search-condition ��
The WHERE clause specifies an intermediate result table that consists of thoserows of R for which the search-condition is true. R is the result of the FROMclause 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 acolumn of a table-reference in an outer subselect.
v A column function must not be specified unless the WHERE clause isspecified in a subquery of a HAVING clause and the argument of thefunction is a correlated reference to a group.
Any subquery in the search-condition is effectively executed for each row of R,and the results are used in the application of the search-condition to the givenrow of R. A subquery is actually executed for each row of R only if it includesa correlated reference. In fact, a subquery with no correlated references maybe executed just once, whereas a subquery with a correlated reference mayhave to be executed once for each row.
where-clause
568 SQL Reference, Volume 1
group-by-clause
�� �
,
GROUP BY grouping-expressiongrouping-setssuper-groups
��
The GROUP BY clause specifies an intermediate result table that consists of agrouping of the rows of R. R is the result of the previous clause of thesubselect.
In its simplest form, a GROUP BY clause contains a grouping expression. Agrouping expression is an expression used in defining the grouping of R. Eachcolumn name included in grouping-expression must unambiguously identify acolumn of R (SQLSTATE 42702 or 42703). A grouping expression cannotinclude a scalar-fullselect (SQLSTATE 42822) or any function that is variant orhas an external action (SQLSTATE 42845).
More complex forms of the GROUP BY clause include grouping-sets andsuper-groups. For a description of these forms, see “grouping-sets” on page 570and “super-groups” on page 571, respectively.
The result of GROUP BY is a set of groups of rows. Each row in this resultrepresents the set of rows for which the grouping-expression is equal. Forgrouping, all null values from a grouping-expression are considered equal.
A grouping-expression can be used in a search condition in a HAVING clause,in an expression in a SELECT clause or in a sort-key-expression of an ORDERBY clause (see “order-by-clause” on page 576 for details). In each case, thereference specifies only one value for each group. For example, if thegrouping-expression is col1+col2, then an allowed expression in the select listwould be col1+col2+3. Associativity rules for expressions would disallow thesimilar expression, 3+col1+col2, unless parentheses are used to ensure that thecorresponding expression is evaluated in the same order. Thus, 3+(col1+col2)would also be allowed in the select list. If the concatenation operator is used,the grouping-expression must be used exactly as the expression was specified inthe select list.
If the grouping-expression contains varying-length strings with trailing blanks,the values in the group can differ in the number of trailing blanks and maynot all have the same length. In that case, a reference to the grouping-expressionstill specifies only one value for each group, but the value for a group ischosen arbitrarily from the available set of values. Thus, the actual length ofthe result value is unpredictable.
group-by-clause
Chapter 4. Queries 569
As noted, there are some cases where the GROUP BY clause cannot referdirectly to a column that is specified in the SELECT clause as an expression(scalar-fullselect, variant or external action functions). To group using such anexpression, use a nested table expression or a common table expression to firstprovide a result table with the expression as a column of the result. For anexample using nested table expressions, see “Example A9” on page 582.
grouping-sets
�� �
�
,
GROUPING SETS ( grouping-expression )super-groups
,
( grouping-expression )super-groups
��
A grouping-sets specification allows multiple grouping clauses to be specifiedin a single statement. This can be thought of as the union of two or moregroups of rows into a single result set. It is logically equivalent to the union ofmultiple subselects with the group by clause in each subselect correspondingto one grouping set. A grouping set can be a single element or can be a list ofelements delimited by parentheses, where an element is either agrouping-expression or a super-group. Using grouping-sets allows the groupsto be computed with a single pass over the base table.
The grouping-sets specification allows either a simple grouping-expression to beused, or the more complex forms of super-groups. For a description ofsuper-groups, see “super-groups” on page 571.
Note that grouping sets are the fundamental building blocks for GROUP BYoperations. A simple GROUP BY with a single column can be considered agrouping set with one element. For example:
GROUP BY a
is the same asGROUP BY GROUPING SETS((a))
andGROUP BY a,b,c
is the same asGROUP BY GROUPING SETS((a,b,c))
group-by-clause
570 SQL Reference, Volume 1
Non-aggregation columns from the select list of the subselect that areexcluded from a grouping set will return a null for such columns for each rowgenerated for that grouping set. This reflects the fact that aggregation wasdone without considering the values for those columns.
“Example C2” on page 587 through “Example C7” on page 591 illustrate theuse of grouping sets.
super-groups
��(1)
ROLLUP ( grouping-expression-list )(2)
CUBE ( grouping-expression-list )grand-total
��
grouping-expression-list:
�
�
,
grouping-expression,
( grouping-expression )
grand-total:
( )
Notes:
1 Alternate specification when used alone in group-by-clause is:grouping-expression-list WITH ROLLUP.
2 Alternate specification when used alone in group-by-clause is:grouping-expression-list WITH CUBE.
ROLLUP ( grouping-expression-list )A ROLLUP grouping is an extension to the GROUP BY clause thatproduces a result set containing sub-total rows in addition to the “regular”grouped rows. Sub-total rows are “super-aggregate” rows that containfurther aggregates whose values are derived by applying the samecolumn functions that were used to obtain the grouped rows. These rowsare called sub-total rows, because that is their most common use;however, any column function can be used for the aggregation. Forinstance, MAX and AVG are used in “Example C8” on page 593.
A ROLLUP grouping is a series of grouping-sets. The general specificationof a ROLLUP with n elements
grouping-sets
Chapter 4. Queries 571
GROUP BY ROLLUP(C1,C2,...,Cn-1,Cn)
is equivalent toGROUP BY GROUPING SETS((C1,C2,...,Cn-1,Cn)
(C1,C2,...,Cn-1)...(C1,C2)(C1)() )
Note that the n elements of the ROLLUP translate to n+1 grouping sets.Note also that the order in which the grouping-expressions is specified issignificant for ROLLUP. For example:GROUP BY ROLLUP(a,b)
is equivalent toGROUP BY GROUPING SETS((a,b)
(a)() )
whileGROUP BY ROLLUP(b,a)
is the same asGROUP BY GROUPING SETS((b,a)
(b)() )
The ORDER BY clause is the only way to guarantee the order of the rowsin the result set. “Example C3” on page 587 illustrates the use of ROLLUP.
CUBE ( grouping-expression-list )A CUBE grouping is an extension to the GROUP BY clause that produces aresult set that contains all the rows of a ROLLUP aggregation and, inaddition, contains ″cross-tabulation″ rows. Cross-tabulation rows areadditional ″super-aggregate″ rows that are not part of an aggregation withsub-totals.
Like a ROLLUP, a CUBE grouping can also be thought of as a series ofgrouping-sets. In the case of a CUBE, all permutations of the cubedgrouping-expression-list are computed along with the grand total. Therefore,the n elements of a CUBE translate to 2**n (2 to the power n) grouping-sets.For instance, a specification ofGROUP BY CUBE(a,b,c)
is equivalent to
super-groups
572 SQL Reference, Volume 1
GROUP BY GROUPING SETS((a,b,c)(a,b)(a,c)(b,c)(a)(b)(c)() )
Notice that the 3 elements of the CUBE translate to 8 grouping sets.
The order of specification of elements does not matter for CUBE. ’CUBE(DayOfYear, Sales_Person)’ and ’CUBE (Sales_Person, DayOfYear)’ yieldthe same result sets. The use of the word ’same’ applies to content of theresult set, not to its order. The ORDER BY clause is the only way toguarantee the order of the rows in the result set. “Example C4” onpage 588 illustrates the use of CUBE.
grouping-expression-listA grouping-expression-list is used within a CUBE or ROLLUP clause todefine the number of elements in the CUBE or ROLLUP operation. This iscontrolled by using parentheses to delimit elements with multiplegrouping-expressions.
The rules for a grouping-expression are described in “group-by-clause” onpage 569. For example, suppose that a query is to return the totalexpenses for the ROLLUP of City within a Province but not within aCounty. However the clause:GROUP BY ROLLUP(Province, County, City)
results in unwanted sub-total rows for the County. In the clauseGROUP BY ROLLUP(Province, (County, City))
the composite (County, City) forms one element in the ROLLUP and,therefore, a query that uses this clause will yield the desired result. Inother words, the two element ROLLUP
GROUP BY ROLLUP(Province, (County, City))
generatesGROUP BY GROUPING SETS((Province, County, City)
(Province)() )
while the 3 element ROLLUP would generateGROUP BY GROUPING SETS((Province, County, City)
(Province, County)(Province)() )
super-groups
Chapter 4. Queries 573
“Example C2” on page 587 also utilizes composite column values.
grand-totalBoth CUBE and ROLLUP return a row which is the overall (grand total)aggregation. This may be separately specified with empty parentheseswithin the GROUPING SET clause. It may also be specified directly in theGROUP BY clause, although there is no effect on the result of the query.“Example C4” on page 588 uses the grand-total syntax.
Combining grouping setsThis can be used to combine any of the types of GROUP BY clauses. Whensimple grouping-expression fields are combined with other groups, they are″appended″ to the beginning of the resulting grouping sets. When ROLLUP orCUBE expressions are combined, they operate like ″multipliers″ on theremaining expression, forming additional grouping set entries according to thedefinition of either ROLLUP or CUBE.
For instance, combining grouping-expression elements acts as follows:GROUP BY a, ROLLUP(b,c)
is equivalent toGROUP BY GROUPING SETS((a,b,c)
(a,b)(a) )
Or similarly,GROUP BY a, b, ROLLUP(c,d)
is equivalent toGROUP BY GROUPING SETS((a,b,c,d)
(a,b,c)(a,b) )
Combining of ROLLUP elements acts as follows:GROUP BY ROLLUP(a), ROLLUP(b,c)
is equivalent toGROUP BY GROUPING SETS((a,b,c)
(a,b)(a)(b,c)(b)() )
Similarly,GROUP BY ROLLUP(a), CUBE(b,c)
super-groups
574 SQL Reference, Volume 1
is equivalent toGROUP BY GROUPING SETS((a,b,c)
(a,b)(a,c)(a)(b,c)(b)(c)() )
Combining of CUBE and ROLLUP elements acts as follows:GROUP BY CUBE(a,b), ROLLUP(c,d)
is equivalent toGROUP BY GROUPING SETS((a,b,c,d)
(a,b,c)(a,b)(a,c,d)(a,c)(a)(b,c,d)(b,c)(b)(c,d)(c)() )
Like a simple grouping-expression, combining grouping sets also eliminatesduplicates within each grouping set. For instance,
GROUP BY a, ROLLUP(a,b)
is equivalent toGROUP BY GROUPING SETS((a,b)
(a) )
A more complete example of combining grouping sets is to construct a resultset that eliminates certain rows that would be returned for a full CUBEaggregation.
For example, consider the following GROUP BY clause:GROUP BY Region,
ROLLUP(Sales_Person, WEEK(Sales_Date)),CUBE(YEAR(Sales_Date), MONTH (Sales_Date))
The column listed immediately to the right of GROUP BY is simply grouped,those within the parenthesis following ROLLUP are rolled up, and thosewithin the parenthesis following CUBE are cubed. Thus, the above clauseresults in a cube of MONTH within YEAR which is then rolled up within
Combining grouping sets
Chapter 4. Queries 575
WEEK within Sales_Person within the Region aggregation. It does not resultin any grand total row or any cross-tabulation rows on Region, Sales_Personor WEEK(Sales_Date) so produces fewer rows than the clause:
GROUP BY ROLLUP (Region, Sales_Person, WEEK(Sales_Date),YEAR(Sales_Date), MONTH(Sales_Date) )
having-clause
�� HAVING search-condition ��
The HAVING clause specifies an intermediate result table that consists ofthose groups of R for which the search-condition is true. R is the result of theprevious clause of the subselect. If this clause is not GROUP BY, R isconsidered to be a single group with no grouping columns.
Each column-name in the search condition must do one of the following:v Unambiguously identify a grouping column of R.v Be specified within a column function.v Be a correlated reference. A column-name is a correlated reference if it
identifies a column of a table-reference in an outer subselect.
A group of R to which the search condition is applied supplies the argumentfor each column function in the search condition, except for any functionwhose argument is a correlated reference.
If the search condition contains a subquery, the subquery can be thought of asbeing executed each time the search condition is applied to a group of R, andthe results used in applying the search condition. In actuality, the subquery isexecuted for each group only if it contains a correlated reference. For anillustration of the difference, see “Example A6” on page 581 and “ExampleA7” on page 581.
A correlated reference to a group of R must either identify a grouping columnor be contained within a column function.
When HAVING is used without GROUP BY, the select list can only be acolumn name within a column function, a correlated column reference, aliteral, or a special register.
order-by-clause
�� ORDER BY �
,ASC
sort-keyDESC
ORDER OF table-designator
��
Combining grouping sets
576 SQL Reference, Volume 1
sort-key:
simple-column-namesimple-integersort-key-expression
The ORDER BY clause specifies an ordering of the rows of the result table. Ifa single sort specification (one sort-key with associated direction) is identified,the rows are ordered by the values of that sort specification. If more than onesort specification is identified, the rows are ordered by the values of the firstidentified sort specification, then by the values of the second identified sortspecification, and so on. Each sort-key cannot have a data type of LONGVARCHAR, CLOB, LONG VARGRAPHIC, DBCLOB, BLOB, DATALINK,distinct type on any of these types, or structured type (SQLSTATE 42907).
A named column in the select list may be identified by a sort-key that is asimple-integer or a simple-column-name. An unnamed column in the select listmust be identified by an simple-integer or, in some cases, by asort-key-expression that matches the expression in the select list (see details ofsort-key-expression). A column is unnamed if the AS clause is not specified andit is derived from a constant, an expression with operators, or a function.
Ordering is performed in accordance with comparison rules. The null value ishigher than all other values. If the ORDER BY clause does not completelyorder the rows, rows with duplicate values of all identified columns aredisplayed in an arbitrary order.
simple-column-nameUsually identifies a column of the result table. In this case,simple-column-name must be the column name of a named column in theselect list.
The simple-column-name may also identify a column name of a table, view,or nested table identified in the FROM clause if the query is a subselect.An error occurs if the subselect:v Specifies DISTINCT in the select-clause (SQLSTATE 42822)v Produces a grouped result and the simple-column-name is not a
grouping-expression (SQLSTATE 42803).
Determining which column is used for ordering the result is describedunder “Column names in sort keys” below.
simple-integerMust be greater than 0 and not greater than the number of columns in theresult table (SQLSTATE 42805). The integer n identifies the nth column ofthe result table.
order-by-clause
Chapter 4. Queries 577
sort-key-expressionAn expression that is not simply a column name or an unsigned integerconstant. The query to which ordering is applied must be a subselect touse this form of sort-key. The sort-key-expression cannot include acorrelated scalar-fullselect (SQLSTATE 42703) or a function with anexternal action (SQLSTATE 42845).
Any column-name within a sort-key-expression must conform to the rulesdescribed under “Column names in sort keys” below.
There are a number of special cases that further restrict the expressionsthat can be specified.v DISTINCT is specified in the SELECT clause of the subselect
(SQLSTATE 42822).The sort-key-expression must match exactly with an expression in theselect list of the subselect (scalar-fullselects are never matched).
v The subselect is grouped (SQLSTATE 42803).The sort-key-expression can:– be an expression in the select list of the subselect,– include a grouping-expression from the GROUP BY clause of the
subselect– include a column function, constant or host variable.
ASCUses the values of the column in ascending order. This is the default.
DESCUses the values of the column in descending order.
ORDER OF table-designatorSpecifies that the same ordering used in table-designator should be appliedto the result table of the subselect. There must be a table referencematching table-designator in the FROM clause of the subselect that specifiesthis clause (SQLSTATE 42703). The subselect (or fullselect) correspondingto the specified table-designator must include an ORDER BY clause that isdependant on the data (SQLSTATE 428FI). The ordering that is applied isthe same as if the columns of the ORDER BY clause in the nestedsubselect (or fullselect) were included in the outer subselect (or fullselect),and these columns were specified in place of the ORDER OF clause.
Note that this form is not allowed in a fullselect (other than thedegenerative form of a fullselect). For example, the following is not valid:(SELECT C1 FROM T1
ORDER BY C1)UNIONSELECT C1 FROM T2
ORDER BY ORDER OF T1
order-by-clause
578 SQL Reference, Volume 1
The following example is valid:SELECT C1 FROM
(SELECT C1 FROM T1UNION
SELECT C1 FROM T2ORDER BY C1 ) AS UTABLE
ORDER BY ORDER OF UTABLE
Notes:
v Column names in sort keys:– The column name is qualified.
The query must be a subselect (SQLSTATE 42877). The column namemust unambiguously identify a column of some table, view or nestedtable in the FROM clause of the subselect (SQLSTATE 42702). The valueof the column is used to compute the value of the sort specification.
– The column name is unqualified.- The query is a subselect.
If the column name is identical to the name of more than one columnof the result table, the column name must unambiguously identify acolumn of some table, view or nested table in the FROM clause of theordering subselect (SQLSTATE 42702). If the column name is identicalto one column, that column is used to compute the value of the sortspecification. If the column name is not identical to a column of theresult table, then it must unambiguously identify a column of sometable, view or nested table in the FROM clause of the fullselect in theselect-statement (SQLSTATE 42702).
- The query is not a subselect (it includes set operations such as union,except or intersect).The column name must not be identical to the name of more than onecolumn of the result table (SQLSTATE 42702). The column name mustbe identical to exactly one column of the result table (SQLSTATE42707), and this column is used to compute the value of the sortspecification.
v Limits: The use of a sort-key-expression or a simple-column-name where thecolumn is not in the select list may result in the addition of the column orexpression to the temporary table used for sorting. This may result inreaching the limit of the number of columns in a table or the limit on thesize of a row in a table. Exceeding these limits will result in an error if atemporary table is required to perform the sorting operation.
fetch-first-clause
��1
FETCH FIRSTinteger
ROWROWS
ONLY ��
order-by-clause
Chapter 4. Queries 579
The fetch-first-clause sets a maximum number of rows that can be retrieved. Itlets the database manager know that the application does not want to retrievemore than integer rows, regardless of how many rows there might be in theresult table when this clause is not specified. An attempt to fetch beyondinteger rows is handled the same way as normal end of data (SQLSTATE02000). The value of integer must be a positive integer (not zero).
Limiting the result table to the first integer rows can improve performance.The database manager will cease processing the query once it has determinedthe first integer rows. If both the fetch-first-clause and the optimize-for-clause arespecified, the lower of the integer values from these clauses will be used toinfluence the communications buffer size. The values are consideredindependently for optimization purposes.
Examples of subselectsExample A1: Select all columns and rows from the EMPLOYEE table.
SELECT * FROM EMPLOYEE
Example A2: Join the EMP_ACT and EMPLOYEE tables, select all thecolumns from the EMP_ACT table and add the employee’s surname(LASTNAME) from the EMPLOYEE table to each row of the result.
SELECT EMP_ACT.*, LASTNAMEFROM EMP_ACT, EMPLOYEEWHERE EMP_ACT.EMPNO = EMPLOYEE.EMPNO
Example A3: Join the EMPLOYEE and DEPARTMENT tables, select theemployee number (EMPNO), employee surname (LASTNAME), departmentnumber (WORKDEPT in the EMPLOYEE table and DEPTNO in theDEPARTMENT table) and department name (DEPTNAME) of all employeeswho were born (BIRTHDATE) earlier than 1930.
SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAMEFROM EMPLOYEE, DEPARTMENTWHERE WORKDEPT = DEPTNOAND YEAR(BIRTHDATE) < 1930
Example A4: Select the job (JOB) and the minimum and maximum salaries(SALARY) for each group of rows with the same job code in the EMPLOYEEtable, but only for groups with more than one row and with a maximumsalary greater than or equal to 27000.
SELECT JOB, MIN(SALARY), MAX(SALARY)FROM EMPLOYEEGROUP BY JOBHAVING COUNT(*) > 1AND MAX(SALARY) >= 27000
fetch-first-clause
580 SQL Reference, Volume 1
Example A5: Select all the rows of EMP_ACT table for employees (EMPNO)in department (WORKDEPT) ‘E11’. (Employee department numbers areshown in the EMPLOYEE table.)
SELECT *FROM EMP_ACTWHERE EMPNO IN
(SELECT EMPNOFROM EMPLOYEEWHERE WORKDEPT = ’E11’)
Example A6: From the EMPLOYEE table, select the department number(WORKDEPT) and maximum departmental salary (SALARY) for alldepartments whose maximum salary is less than the average salary for allemployees.
SELECT WORKDEPT, MAX(SALARY)FROM EMPLOYEEGROUP BY WORKDEPTHAVING MAX(SALARY) < (SELECT AVG(SALARY)
FROM EMPLOYEE)
The subquery in the HAVING clause would only be executed once in thisexample.
Example A7: Using the EMPLOYEE table, select the department number(WORKDEPT) and maximum departmental salary (SALARY) for alldepartments whose maximum salary is less than the average salary in allother departments.
SELECT WORKDEPT, MAX(SALARY)FROM EMPLOYEE EMP_CORGROUP BY WORKDEPTHAVING MAX(SALARY) < (SELECT AVG(SALARY)
FROM EMPLOYEEWHERE NOT WORKDEPT = EMP_COR.WORKDEPT)
In contrast to “Example A6”, the subquery in the HAVING clause would needto be executed for each group.
Example A8: Determine the employee number and salary of salesrepresentatives along with the average salary and head count of theirdepartments.
This query must first create a nested table expression (DINFO) in order to getthe AVGSALARY and EMPCOUNT columns, as well as the DEPTNO columnthat is used in the WHERE clause.SELECT THIS_EMP.EMPNO, THIS_EMP.SALARY, DINFO.AVGSALARY, DINFO.EMPCOUNTFROM EMPLOYEE THIS_EMP,
(SELECT OTHERS.WORKDEPT AS DEPTNO,AVG(OTHERS.SALARY) AS AVGSALARY,
Examples of subselects
Chapter 4. Queries 581
COUNT(*) AS EMPCOUNTFROM EMPLOYEE OTHERSGROUP BY OTHERS.WORKDEPT) AS DINFO
WHERE THIS_EMP.JOB = ’SALESREP’AND THIS_EMP.WORKDEPT = DINFO.DEPTNO
Using a nested table expression for this case saves the overhead of creatingthe DINFO view as a regular view. During statement preparation, accessingthe catalog for the view is avoided and, because of the context of the rest ofthe query, only the rows for the department of the sales representatives needto be considered by the view.
Example A9: Display the average education level and salary for 5 randomgroups of employees.
This query requires the use of a nested table expression to set a random valuefor each employee so that it can subsequently be used in the GROUP BYclause.
SELECT RANDID , AVG(EDLEVEL), AVG(SALARY)FROM ( SELECT EDLEVEL, SALARY, INTEGER(RAND()*5) AS RANDID
FROM EMPLOYEE) AS EMPRAND
GROUP BY RANDID
Example A10: Query the EMP_ACT table and return those project numbersthat have an employee whose salary is in the top 10 of all employees.
SELECT EMP_ACT.EMPNO,PROJNOFROM EMP_ACTWHERE EMP_ACT.EMPNO IN
(SELECT EMPLOYEE.EMPNOFROM EMPLOYEEORDER BY SALARY DESCFETCH FIRST 10 ROWS ONLY)
Examples of subselects
582 SQL Reference, Volume 1
Examples of joinsExample B1: This example illustrates the results of the various joins usingtables J1 and J2. These tables contain rows as shown.
SELECT * FROM J1
W X--- ------A 11B 12C 13
SELECT * FROM J2
Y Z--- ------A 21C 22D 23
The following query does an inner join of J1 and J2 matching the first columnof both tables.
SELECT * FROM J1 INNER JOIN J2 ON W=Y
W X Y Z--- ------ --- ------A 11 A 21C 13 C 22
In this inner join example the row with column W=’C’ from J1 and the rowwith column Y=’D’ from J2 are not included in the result because they do nothave a match in the other table. Note that the following alternative form of aninner join query produces the same result.
SELECT * FROM J1, J2 WHERE W=Y
The following left outer join will get back the missing row from J1 with nullsfor the columns of J2. Every row from J1 is included.
SELECT * FROM J1 LEFT OUTER JOIN J2 ON W=Y
W X Y Z--- ------ --- ------A 11 A 21B 12 - -C 13 C 22
The following right outer join will get back the missing row from J2 withnulls for the columns of J1. Every row from J2 is included.
SELECT * FROM J1 RIGHT OUTER JOIN J2 ON W=Y
W X Y Z
Examples of joins
Chapter 4. Queries 583
--- ------ --- ------A 11 A 21C 13 C 22- - D 23
The following full outer join will get back the missing rows from both J1 andJ2 with nulls where appropriate. Every row from both J1 and J2 is included.
SELECT * FROM J1 FULL OUTER JOIN J2 ON W=Y
W X Y Z--- ------ --- ------A 11 A 21C 13 C 22- - D 23B 12 - -
Example B2: Using the tables J1 and J2 from the previous example, examinewhat happens when and additional predicate is added to the search condition.
SELECT * FROM J1 INNER JOIN J2 ON W=Y AND X=13
W X Y Z--- ------ --- ------C 13 C 22
The additional condition caused the inner join to select only 1 row comparedto the inner join in “Example B1” on page 583.
Notice what the impact of this is on the full outer join.SELECT * FROM J1 FULL OUTER JOIN J2 ON W=Y AND X=13
W X Y Z--- ------ --- ------- - A 21C 13 C 22- - D 23A 11 - -B 12 - -
The result now has 5 rows (compared to 4 without the additional predicate)since there was only 1 row in the inner join and all rows of both tables mustbe returned.
The following query illustrates that placing the same additional predicate inWHERE clause has completely different results.
SELECT * FROM J1 FULL OUTER JOIN J2 ON W=YWHERE X=13
W X Y Z--- ------ --- ------C 13 C 22
Examples of joins
584 SQL Reference, Volume 1
The WHERE clause is applied after the intermediate result of the full outerjoin. This intermediate result would be the same as the result of the full outerjoin query in “Example B1” on page 583. The WHERE clause is applied to thisintermediate result and eliminates all but the row that has X=13. Choosing thelocation of a predicate when performing outer joins can have significantimpact on the results. Consider what happens if the predicate was X=12instead of X=13. The following inner join returns no rows.
SELECT * FROM J1 INNER JOIN J2 ON W=Y AND X=12
Hence, the full outer join would return 6 rows, 3 from J1 with nulls for thecolumns of J2 and 3 from J2 with nulls for the columns of J1.
SELECT * FROM J1 FULL OUTER JOIN J2 ON W=Y AND X=12
W X Y Z--- ------ --- ------- - A 21- - C 22- - D 23A 11 - -B 12 - -C 13 - -
If the additional predicate is in the WHERE clause instead, 1 row is returned.SELECT * FROM J1 FULL OUTER JOIN J2 ON W=Y
WHERE X=12
W X Y Z--- ------ --- ------B 12 - -
Example B3: List every department with the employee number and last nameof the manager, including departments without a manager.
SELECT DEPTNO, DEPTNAME, EMPNO, LASTNAMEFROM DEPARTMENT LEFT OUTER JOIN EMPLOYEE
ON MGRNO = EMPNO
Example B4: List every employee number and last name with the employeenumber and last name of their manager, including employees without amanager.
SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAMEFROM EMPLOYEE E LEFT OUTER JOIN
DEPARTMENT INNER JOIN EMPLOYEE MON MGRNO = M.EMPNOON E.WORKDEPT = DEPTNO
The inner join determines the last name for any manager identified in theDEPARTMENT table and the left outer join guarantees that each employee islisted even if a corresponding department is not found in DEPARTMENT.
Examples of joins
Chapter 4. Queries 585
Examples of grouping sets, cube, and rollupThe queries in “Example C1” through “Example C4” on page 588 use a subsetof the rows in the SALES tables based on the predicate ’WEEK(SALES_DATE)= 13’.
SELECT WEEK(SALES_DATE) AS WEEK,DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SALES_PERSON, SALES AS UNITS_SOLD
FROM SALESWHERE WEEK(SALES_DATE) = 13
which results in:WEEK DAY_WEEK SALES_PERSON UNITS_SOLD----------- ----------- --------------- -----------
13 6 LUCCHESSI 313 6 LUCCHESSI 113 6 LEE 213 6 LEE 213 6 LEE 313 6 LEE 513 6 GOUNOT 313 6 GOUNOT 113 6 GOUNOT 713 7 LUCCHESSI 113 7 LUCCHESSI 213 7 LUCCHESSI 113 7 LEE 713 7 LEE 313 7 LEE 713 7 LEE 413 7 GOUNOT 213 7 GOUNOT 1813 7 GOUNOT 1
Example C1: Here is a query with a basic GROUP BY clause over 3 columns:SELECT WEEK(SALES_DATE) AS WEEK,
DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SALES_PERSON, SUM(SALES) AS UNITS_SOLD
FROM SALESWHERE WEEK(SALES_DATE) = 13GROUP BY WEEK(SALES_DATE), DAYOFWEEK(SALES_DATE), SALES_PERSONORDER BY WEEK, DAY_WEEK, SALES_PERSON
This results in:WEEK DAY_WEEK SALES_PERSON UNITS_SOLD----------- ----------- --------------- -----------
13 6 GOUNOT 1113 6 LEE 1213 6 LUCCHESSI 413 7 GOUNOT 2113 7 LEE 2113 7 LUCCHESSI 4
Examples of grouping sets, cube, and rollup
586 SQL Reference, Volume 1
Example C2: Produce the result based on two different grouping sets of rowsfrom the SALES table.
SELECT WEEK(SALES_DATE) AS WEEK,DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SALES_PERSON, SUM(SALES) AS UNITS_SOLD
FROM SALESWHERE WEEK(SALES_DATE) = 13GROUP BY GROUPING SETS ( (WEEK(SALES_DATE), SALES_PERSON),
(DAYOFWEEK(SALES_DATE), SALES_PERSON))ORDER BY WEEK, DAY_WEEK, SALES_PERSON
This results in:WEEK DAY_WEEK SALES_PERSON UNITS_SOLD----------- ----------- --------------- -----------
13 - GOUNOT 3213 - LEE 3313 - LUCCHESSI 8- 6 GOUNOT 11- 6 LEE 12- 6 LUCCHESSI 4- 7 GOUNOT 21- 7 LEE 21- 7 LUCCHESSI 4
The rows with WEEK 13 are from the first grouping set and the other rowsare from the second grouping set.
Example C3: If you use the 3 distinct columns involved in the grouping setsof “Example C2” and perform a ROLLUP, you can see grouping sets for(WEEK,DAY_WEEK,SALES_PERSON), (WEEK, DAY_WEEK), (WEEK) andgrand total.SELECT WEEK(SALES_DATE) AS WEEK,
DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SALES_PERSON, SUM(SALES) AS UNITS_SOLD
FROM SALESWHERE WEEK(SALES_DATE) = 13GROUP BY ROLLUP ( WEEK(SALES_DATE), DAYOFWEEK(SALES_DATE), SALES_PERSON )ORDER BY WEEK, DAY_WEEK, SALES_PERSON
This results in:WEEK DAY_WEEK SALES_PERSON UNITS_SOLD----------- ----------- --------------- -----------
13 6 GOUNOT 1113 6 LEE 1213 6 LUCCHESSI 413 6 - 2713 7 GOUNOT 2113 7 LEE 2113 7 LUCCHESSI 4
Examples of grouping sets, cube, and rollup
Chapter 4. Queries 587
13 7 - 4613 - - 73- - - 73
Example C4: If you run the same query as “Example C3” on page 587 onlyreplace ROLLUP with CUBE, you can see additional grouping sets for(WEEK,SALES_PERSON), (DAY_WEEK,SALES_PERSON), (DAY_WEEK),(SALES_PERSON) in the result.
SELECT WEEK(SALES_DATE) AS WEEK,DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SALES_PERSON, SUM(SALES) AS UNITS_SOLD
FROM SALESWHERE WEEK(SALES_DATE) = 13GROUP BY CUBE ( WEEK(SALES_DATE), DAYOFWEEK(SALES_DATE), SALES_PERSON )ORDER BY WEEK, DAY_WEEK, SALES_PERSON
This results in:WEEK DAY_WEEK SALES_PERSON UNITS_SOLD----------- ----------- --------------- -----------
13 6 GOUNOT 1113 6 LEE 1213 6 LUCCHESSI 413 6 - 2713 7 GOUNOT 2113 7 LEE 2113 7 LUCCHESSI 413 7 - 4613 - GOUNOT 3213 - LEE 3313 - LUCCHESSI 813 - - 73- 6 GOUNOT 11- 6 LEE 12- 6 LUCCHESSI 4- 6 - 27- 7 GOUNOT 21- 7 LEE 21- 7 LUCCHESSI 4- 7 - 46- - GOUNOT 32- - LEE 33- - LUCCHESSI 8- - - 73
Example C5: Obtain a result set which includes a grand-total of selected rowsfrom the SALES table together with a group of rows aggregated bySALES_PERSON and MONTH.
SELECT SALES_PERSON,MONTH(SALES_DATE) AS MONTH,SUM(SALES) AS UNITS_SOLD
FROM SALES
Examples of grouping sets, cube, and rollup
588 SQL Reference, Volume 1
GROUP BY GROUPING SETS ( (SALES_PERSON, MONTH(SALES_DATE)),()
)ORDER BY SALES_PERSON, MONTH
This results in:SALES_PERSON MONTH UNITS_SOLD--------------- ----------- -----------GOUNOT 3 35GOUNOT 4 14GOUNOT 12 1LEE 3 60LEE 4 25LEE 12 6LUCCHESSI 3 9LUCCHESSI 4 4LUCCHESSI 12 1- - 155
Example C6: This example shows two simple ROLLUP queries followed by aquery which treats the two ROLLUPs as grouping sets in a single result setand specifies row ordering for each column involved in the grouping sets.
Example C6-1:SELECT WEEK(SALES_DATE) AS WEEK,
DAYOFWEEK(SALES_DATE) AS DAY_WEEK,SUM(SALES) AS UNITS_SOLD
FROM SALESGROUP BY ROLLUP ( WEEK(SALES_DATE), DAYOFWEEK(SALES_DATE) )ORDER BY WEEK, DAY_WEEK
results in:WEEK DAY_WEEK UNITS_SOLD----------- ----------- -----------
13 6 2713 7 4613 - 7314 1 3114 2 4314 - 7453 1 853 - 8- - 155
Example C6-2:SELECT MONTH(SALES_DATE) AS MONTH,
REGION,SUM(SALES) AS UNITS_SOLD
FROM SALESGROUP BY ROLLUP ( MONTH(SALES_DATE), REGION );ORDER BY MONTH, REGION
Examples of grouping sets, cube, and rollup
Chapter 4. Queries 589
results in:MONTH REGION UNITS_SOLD----------- --------------- -----------
3 Manitoba 223 Ontario-North 83 Ontario-South 343 Quebec 403 - 1044 Manitoba 174 Ontario-North 14 Ontario-South 144 Quebec 114 - 4312 Manitoba 212 Ontario-South 412 Quebec 212 - 8- - 155
Example C6-3:SELECT WEEK(SALES_DATE) AS WEEK,
DAYOFWEEK(SALES_DATE) AS DAY_WEEK,MONTH(SALES_DATE) AS MONTH,REGION,SUM(SALES) AS UNITS_SOLD
FROM SALESGROUP BY GROUPING SETS ( ROLLUP( WEEK(SALES_DATE), DAYOFWEEK(SALES_DATE) ),
ROLLUP( MONTH(SALES_DATE), REGION ) )ORDER BY WEEK, DAY_WEEK, MONTH, REGION
results in:WEEK DAY_WEEK MONTH REGION UNITS_SOLD----------- ----------- ----------- --------------- -----------
13 6 - - 2713 7 - - 4613 - - - 7314 1 - - 3114 2 - - 4314 - - - 7453 1 - - 853 - - - 8- - 3 Manitoba 22- - 3 Ontario-North 8- - 3 Ontario-South 34- - 3 Quebec 40- - 3 - 104- - 4 Manitoba 17- - 4 Ontario-North 1- - 4 Ontario-South 14- - 4 Quebec 11- - 4 - 43- - 12 Manitoba 2- - 12 Ontario-South 4
Examples of grouping sets, cube, and rollup
590 SQL Reference, Volume 1
- - 12 Quebec 2- - 12 - 8- - - - 155- - - - 155
Using the two ROLLUPs as grouping sets causes the result to includeduplicate rows. There are even two grand total rows.
Observe how the use of ORDER BY has affected the results:v In the first grouped set, week 53 has been repositioned to the end.v In the second grouped set, month 12 has now been positioned to the end
and the regions now appear in alphabetic order.v Null values are sorted high.
Example C7: In queries that perform multiple ROLLUPs in a single pass (suchas “Example C6-3” on page 590) you may want to be able to indicate whichgrouping set produced each row. The following steps demonstrate how toprovide a column (called GROUP) which indicates the origin of each row inthe result set. By origin, we mean which one of the two grouping setsproduced the row in the result set.
Step 1: Introduce a way of ″generating″ new data values, using a query whichselects from a VALUES clause (which is an alternate form of a fullselect). Thisquery shows how a table can be derived called ″X″ having 2 columns ″R1″and ″R2″ and 1 row of data.SELECT R1,R2FROM (VALUES(’GROUP 1’,’GROUP 2’)) AS X(R1,R2);
results in:R1 R2------- -------GROUP 1 GROUP 2
Step 2: Form the cross product of this table ″X″ with the SALES table. Thisadd columns ″R1″ and ″R2″ to every row.SELECT R1, R2, WEEK(SALES_DATE) AS WEEK,
DAYOFWEEK(SALES_DATE) AS DAY_WEEK,MONTH(SALES_DATE) AS MONTH,REGION,SALES AS UNITS_SOLD
FROM SALES,(VALUES(’GROUP 1’,’GROUP 2’)) AS X(R1,R2)
This add columns ″R1″ and ″R2″ to every row.
Step 3: Now we can combine these columns with the grouping sets to includethese columns in the rollup analysis.
Examples of grouping sets, cube, and rollup
Chapter 4. Queries 591
SELECT R1, R2,WEEK(SALES_DATE) AS WEEK,DAYOFWEEK(SALES_DATE) AS DAY_WEEK,MONTH(SALES_DATE) AS MONTH,REGION, SUM(SALES) AS UNITS_SOLD
FROM SALES,(VALUES(’GROUP 1’,’GROUP 2’)) AS X(R1,R2)GROUP BY GROUPING SETS ((R1, ROLLUP(WEEK(SALES_DATE),
DAYOFWEEK(SALES_DATE))),(R2,ROLLUP( MONTH(SALES_DATE), REGION ) ) )
ORDER BY WEEK, DAY_WEEK, MONTH, REGION
results in:R1 R2 WEEK DAY_WEEK MONTH REGION UNITS_SOLD------- ------- -------- --------- --------- --------------- -----------GROUP 1 - 13 6 - - 27GROUP 1 - 13 7 - - 46GROUP 1 - 13 - - - 73GROUP 1 - 14 1 - - 31GROUP 1 - 14 2 - - 43GROUP 1 - 14 - - - 74GROUP 1 - 53 1 - - 8GROUP 1 - 53 - - - 8- GROUP 2 - - 3 Manitoba 22- GROUP 2 - - 3 Ontario-North 8- GROUP 2 - - 3 Ontario-South 34- GROUP 2 - - 3 Quebec 40- GROUP 2 - - 3 - 104- GROUP 2 - - 4 Manitoba 17- GROUP 2 - - 4 Ontario-North 1- GROUP 2 - - 4 Ontario-South 14- GROUP 2 - - 4 Quebec 11- GROUP 2 - - 4 - 43- GROUP 2 - - 12 Manitoba 2- GROUP 2 - - 12 Ontario-South 4- GROUP 2 - - 12 Quebec 2- GROUP 2 - - 12 - 8- GROUP 2 - - - - 155GROUP 1 - - - - - 155
Step 4: Notice that because R1 and R2 are used in different grouping sets,whenever R1 is non-null in the result, R2 is null and whenever R2 is non-nullin the result, R1 is null. That means you can consolidate these columns into asingle column using the COALESCE function. You can also use this column inthe ORDER BY clause to keep the results of the two grouping sets together.
SELECT COALESCE(R1,R2) AS GROUP,WEEK(SALES_DATE) AS WEEK,DAYOFWEEK(SALES_DATE) AS DAY_WEEK,MONTH(SALES_DATE) AS MONTH,REGION, SUM(SALES) AS UNITS_SOLD
FROM SALES,(VALUES(’GROUP 1’,’GROUP 2’)) AS X(R1,R2)GROUP BY GROUPING SETS ((R1, ROLLUP(WEEK(SALES_DATE),
Examples of grouping sets, cube, and rollup
592 SQL Reference, Volume 1
DAYOFWEEK(SALES_DATE))),(R2,ROLLUP( MONTH(SALES_DATE), REGION ) ) )
ORDER BY GROUP, WEEK, DAY_WEEK, MONTH, REGION;
results in:GROUP WEEK DAY_WEEK MONTH REGION UNITS_SOLD------- ----------- ----------- ----------- --------------- -----------GROUP 1 13 6 - - 27GROUP 1 13 7 - - 46GROUP 1 13 - - - 73GROUP 1 14 1 - - 31GROUP 1 14 2 - - 43GROUP 1 14 - - - 74GROUP 1 53 1 - - 8GROUP 1 53 - - - 8GROUP 1 - - - - 155GROUP 2 - - 3 Manitoba 22GROUP 2 - - 3 Ontario-North 8GROUP 2 - - 3 Ontario-South 34GROUP 2 - - 3 Quebec 40GROUP 2 - - 3 - 104GROUP 2 - - 4 Manitoba 17GROUP 2 - - 4 Ontario-North 1GROUP 2 - - 4 Ontario-South 14GROUP 2 - - 4 Quebec 11GROUP 2 - - 4 - 43GROUP 2 - - 12 Manitoba 2GROUP 2 - - 12 Ontario-South 4GROUP 2 - - 12 Quebec 2GROUP 2 - - 12 - 8GROUP 2 - - - - 155
Example C8: The following example illustrates the use of various columnfunctions when performing a CUBE. The example also makes use of castfunctions and rounding to produce a decimal result with reasonable precisionand scale.
SELECT MONTH(SALES_DATE) AS MONTH,REGION,SUM(SALES) AS UNITS_SOLD,MAX(SALES) AS BEST_SALE,CAST(ROUND(AVG(DECIMAL(SALES)),2) AS DECIMAL(5,2)) AS AVG_UNITS_SOLD
FROM SALESGROUP BY CUBE(MONTH(SALES_DATE),REGION)ORDER BY MONTH, REGION
This results in:MONTH REGION UNITS_SOLD BEST_SALE AVG_UNITS_SOLD----------- --------------- ----------- ----------- --------------
3 Manitoba 22 7 3.143 Ontario-North 8 3 2.673 Ontario-South 34 14 4.253 Quebec 40 18 5.00
Examples of grouping sets, cube, and rollup
Chapter 4. Queries 593
3 - 104 18 4.004 Manitoba 17 9 5.674 Ontario-North 1 1 1.004 Ontario-South 14 8 4.674 Quebec 11 8 5.504 - 43 9 4.7812 Manitoba 2 2 2.0012 Ontario-South 4 3 2.0012 Quebec 2 1 1.0012 - 8 3 1.60- Manitoba 41 9 3.73- Ontario-North 9 3 2.25- Ontario-South 52 14 4.00- Quebec 53 18 4.42- - 155 18 3.87
Related reference:
v “Identifiers” on page 65v “Functions” on page 168v “GROUPING” on page 278v “Fullselect” on page 595v “Select-statement” on page 601v “CREATE FUNCTION (SQL Scalar, Table or Row) statement” in the SQL
Reference, Volume 2
v “CREATE FUNCTION (External Table) statement” in the SQL Reference,Volume 2
v “Character strings” on page 95v “Assignments and comparisons” on page 117v “Predicates” on page 225
Examples of grouping sets, cube, and rollup
594 SQL Reference, Volume 1
Fullselect
�� subselect(fullselect)
values-clause
�
UNION subselectUNION ALL (fullselect)EXCEPT values-clauseEXCEPT ALLINTERSECTINTERSECT ALL
�
�order-by-clause fetch-first-clause
��
values-clause:
VALUES �
,
values-row
values-row:
�
expressionNULL
,
( expression )NULL
The fullselect is a component of the select-statement, the INSERT statement,and the CREATE VIEW statement. It is also a component of certain predicateswhich, in turn, are components of a statement. A fullselect that is acomponent of a predicate is called a subquery, and a fullselect that is enclosedin parentheses is sometimes called a subquery.
The set operators UNION, EXCEPT, and INTERSECT correspond to therelational operators union, difference, and intersection.
A fullselect specifies a result table. If a set operator is not used, the result ofthe fullselect is the result of the specified subselect or values-clause.
values-clauseDerives a result table by specifying the actual values, using expressions,for each column of a row in the result table. Multiple rows may bespecified.
Fullselect
Chapter 4. Queries 595
NULL can only be used with multiple specifications of values-row, and atleast one row in the same column must not be NULL (SQLSTATE 42826).
A values-row is specified by:v A single expression for a single column result table or,v n expressions (or NULL) separated by commas and enclosed in
parentheses, where n is the number of columns in the result table.
A multiple row VALUES clause must have the same number ofexpressions in each values-row (SQLSTATE 42826).
The following are examples of values-clauses and their meaning.VALUES (1),(2),(3) - 3 rows of 1 columnVALUES 1, 2, 3 - 3 rows of 1 columnVALUES (1, 2, 3) - 1 row of 3 columnsVALUES (1,21),(2,22),(3,23) - 3 rows of 2 columns
A values-clause that is composed of n specifications of values-row, RE1 toREn, where n is greater than 1, is equivalent to:
RE1 UNION ALL RE2 ... UNION ALL REn
This means that the corresponding expressions of each values-row must becomparable (SQLSTATE 42825).
UNION or UNION ALLDerives a result table by combining two other result tables (R1 and R2). IfUNION ALL is specified, the result consists of all rows in R1 and R2. IfUNION is specified without the ALL option, the result is the set of allrows in either R1 or R2, with the duplicate rows eliminated. In either case,however, each row of the UNION table is either a row from R1 or a rowfrom R2.
EXCEPT or EXCEPT ALLDerives a result table by combining two other result tables (R1 and R2). IfEXCEPT ALL is specified, the result consists of all rows that do not have acorresponding row in R2, where duplicate rows are significant. If EXCEPTis specified without the ALL option, the result consists of all rows that areonly in R1, with duplicate rows in the result of this operation eliminated.
INTERSECT or INTERSECT ALLDerives a result table by combining two other result tables (R1 and R2). IfINTERSECT ALL is specified, the result consists of all rows that are inboth R1 and R2. If INTERSECT is specified without the ALL option, theresult consists of all rows that are in both R1 and R2, with the duplicaterows eliminated.
Fullselect
596 SQL Reference, Volume 1
order-by-clauseA fullselect that contains an ORDER BY or FETCH FIRST clause cannot bespecified in:v A materialized query tablev The outermost fullselect of a view (SQLSTATE 428FJ).
Note: An ORDER BY clause in a fullselect does not affect the order of therows returned by a query. An ORDER BY clause only affects theorder of the rows returned if it is specified in the outermostfullselect.
The number of columns in the result tables R1 and R2 must be the same(SQLSTATE 42826). If the ALL keyword is not specified, R1 and R2 must notinclude any columns having a data type of LONG VARCHAR, CLOB, LONGVARGRAPHIC, DBCLOB, BLOB, DATALINK, distinct type on any of thesetypes, or structured type (SQLSTATE 42907).
The columns of the result are named as follows:v If the nth column of R1 and the nth column of R2 have the same result
column name, then the nth column of R has the result column name.v If the nth column of R1 and the nth column of R2 have different result
column names, a name is generated. This name cannot be used as thecolumn name in an ORDER BY or UPDATE clause.
The generated name can be determined by performing a DESCRIBE of theSQL statement and consulting the SQLNAME field.
Two rows are duplicates of one another if each value in the first is equal tothe corresponding value of the second. (For determining duplicates, two nullvalues are considered equal.)
When multiple operations are combined in an expression, operations withinparentheses are performed first. If there are no parentheses, the operations areperformed from left to right with the exception that all INTERSECToperations are performed before UNION or EXCEPT operations.
In the following example, the values of tables R1 and R2 are shown on theleft. The other headings listed show the values as a result of various setoperations on R1 and R2.
R1 R2 UNIONALL
UNION EXCEPTALL
EXCEPT INTER-SECTALL
INTER-SECT
1 1 1 1 1 2 1 1
Fullselect
Chapter 4. Queries 597
R1 R2 UNIONALL
UNION EXCEPTALL
EXCEPT INTER-SECTALL
INTER-SECT
1 1 1 2 2 5 1 3
1 3 1 3 2 3 4
2 3 1 4 2 4
2 3 1 5 4
2 3 2 5
3 4 2
4 2
4 3
5 3
3
3
3
4
4
4
5
Examples of a fullselectExample 1: Select all columns and rows from the EMPLOYEE table.
SELECT * FROM EMPLOYEE
Example 2: List the employee numbers (EMPNO) of all employees in theEMPLOYEE table whose department number (WORKDEPT) either beginswith 'E' or who are assigned to projects in the EMP_ACT table whose projectnumber (PROJNO) equals 'MA2100', 'MA2110', or 'MA2112'.
SELECT EMPNOFROM EMPLOYEEWHERE WORKDEPT LIKE ’E%’
UNIONSELECT EMPNO
FROM EMP_ACTWHERE PROJNO IN(’MA2100’, ’MA2110’, ’MA2112’)
Example 3: Make the same query as in example 2, and, in addition, “tag” therows from the EMPLOYEE table with 'emp' and the rows from the EMP_ACT
Fullselect
598 SQL Reference, Volume 1
table with 'emp_act'. Unlike the result from example 2, this query may returnthe same EMPNO more than once, identifying which table it came from bythe associated “tag”.
SELECT EMPNO, ’emp’FROM EMPLOYEEWHERE WORKDEPT LIKE ’E%’
UNIONSELECT EMPNO, ’emp_act’ FROM EMP_ACT
WHERE PROJNO IN(’MA2100’, ’MA2110’, ’MA2112’)
Example 4: Make the same query as in example 2, only use UNION ALL sothat no duplicate rows are eliminated.
SELECT EMPNOFROM EMPLOYEEWHERE WORKDEPT LIKE ’E%’
UNION ALLSELECT EMPNO
FROM EMP_ACTWHERE PROJNO IN(’MA2100’, ’MA2110’, ’MA2112’)
Example 5: Make the same query as in Example 3, only include an additionaltwo employees currently not in any table and tag these rows as ″new″.
SELECT EMPNO, ’emp’FROM EMPLOYEEWHEREWORKDEPTLIKE ’E%’
UNIONSELECT EMPNO, ’emp_act’
FROM EMP_ACTWHERE PROJNO IN(’MA2100’, ’MA2110’, ’MA2112’)
UNIONVALUES (’NEWAAA’, ’new’), (’NEWBBB’, ’new’)
Example 6: This example of EXCEPT produces all rows that are in T1 but notin T2.
(SELECT * FROM T1)EXCEPT ALL(SELECT * FROM T2)
If no NULL values are involved, this example returns the same results asSELECT ALL *
FROM T1WHERE NOT EXISTS (SELECT * FROM T2
WHERE T1.C1 = T2.C1 AND T1.C2 = T2.C2 AND...)
Example 7: This example of INTERSECT produces all rows that are in bothtables T1 and T2, removing duplicates.
(SELECT * FROM T1)INTERSECT(SELECT * FROM T2)
Examples of a fullselect
Chapter 4. Queries 599
If no NULL values are involved, this example returns the same result asSELECT DISTINCT * FROM T1
WHERE EXISTS (SELECT * FROM T2WHERE T1.C1 = T2.C1 AND T1.C2 = T2.C2 AND...)
where C1, C2, and so on represent the columns of T1 and T2.
Related reference:
v “Rules for result data types” on page 134v “Rules for string conversions” on page 139
Examples of a fullselect
600 SQL Reference, Volume 1
Select-statement
��
�
,
WITH common-table-expression
fullselect *read-only-clause
(1)update-clause
�
� * *optimize-for-clause WITH RR
RSCSUR
��
Notes:
1 The update-clause cannot be specified if the fullselect contains anorder-by-clause or a fetch-first-clause.
The select-statement is the form of a query that can be directly specified in aDECLARE CURSOR statement, or prepared and then referenced in aDECLARE CURSOR statement. It can also be issued through the use ofdynamic SQL statements using the command line processor (or similar tools),causing a result table to be displayed on the user’s screen. In either case, thetable specified by a select-statement is the result of the fullselect.
The optional WITH clause specifies the isolation level at which the selectstatement is executed.v RR - Repeatable Readv RS - Read Stabilityv CS - Cursor Stabilityv UR - Uncommitted Read
The default isolation level of the statement is the isolation level of the packagein which the statement is bound.
common-table-expression
��
�
table-name AS ( fullselect )(1)
( ),
column-name
��
Notes:
1 If a common table expression is recursive, or if the fullselect results induplicate column names, column names must be specified.
Select-statement
Chapter 4. Queries 601
A common table expression permits defining a result table with a table-name thatcan be specified as a table name in any FROM clause of the fullselect thatfollows. Multiple common table expressions can be specified following thesingle WITH keyword. Each common table expression specified can also bereferenced by name in the FROM clause of subsequent common tableexpressions.
If a list of columns is specified, it must consist of as many names as there arecolumns in the result table of the fullselect. Each column-name must be uniqueand unqualified. If these column names are not specified, the names arederived from the select list of the fullselect used to define the common tableexpression.
The table-name of a common table expression must be different from any othercommon table expression table-name in the same statement (SQLSTATE 42726).If the common table expression is specified in an INSERT statement thetable-name cannot be the same as the table or view name that is the object ofthe insert (SQLSTATE 42726). A common table expression table-name can bespecified as a table name in any FROM clause throughout the fullselect. Atable-name of a common table expression overrides any existing table, view oralias (in the catalog) with the same qualified name.
If more than one common table expression is defined in the same statement,cyclic references between the common table expressions are not permitted(SQLSTATE 42835). A cyclic reference occurs when two common tableexpressions dt1 and dt2 are created such that dt1 refers to dt2 and dt2 refers todt1.
The common table expression is also optional prior to the fullselect in theCREATE VIEW and INSERT statements.
A common table expression can be used:v In place of a view to avoid creating the view (when general use of the view
is not required and positioned updates or deletes are not used)v To enable grouping by a column that is derived from a scalar subselect or
function that is not deterministic or has external actionv When the desired result table is based on host variablesv When the same result table needs to be shared in a fullselect
v When the result needs to be derived using recursion.
If a fullselect of a common table expression contains a reference to itself in aFROM clause, the common table expression is a recursive common tableexpression. Queries using recursion are useful in supporting applications suchas bill of materials (BOM), reservation systems, and network planning.
common-table-expression
602 SQL Reference, Volume 1
The following must be true of a recursive common table expression:v Each fullselect that is part of the recursion cycle must start with SELECT or
SELECT ALL. Use of SELECT DISTINCT is not allowed (SQLSTATE 42925).Furthermore, the unions must use UNION ALL (SQLSTATE 42925).
v The column names must be specified following the table-name of thecommon table expression (SQLSTATE 42908).
v The first fullselect of the first union (the initialization fullselect) must notinclude a reference to any column of the common table expression in anyFROM clause (SQLSTATE 42836).
v If a column name of the common table expression is referred to in theiterative fullselect, the data type, length, and code page for the column aredetermined based on the initialization fullselect. The corresponding columnin the iterative fullselect must have the same data type and length as thedata type and length determined based on the initialization fullselect andthe code page must match (SQLSTATE 42825). However, for character stringtypes, the length of the two data types may differ. In this case, the columnin the iterative fullselect must have a length that would always beassignable to the length determined from the initialization fullselect.
v Each fullselect that is part of the recursion cycle must not include anycolumn functions, group-by-clauses, or having-clauses (SQLSTATE 42836).The FROM clauses of these fullselects can include at most one reference to acommon table expression that is part of a recursion cycle (SQLSTATE42836).
v The iterative fullselect and the overall recursive fullselect must not includean order-by-clause (SQLSTATE 42836).
v Subqueries (scalar or quantified) must not be part of any recursion cycles(SQLSTATE 42836).
When developing recursive common table expressions, remember that aninfinite recursion cycle (loop) can be created. Check that recursion cycles willterminate. This is especially important if the data involved is cyclic. Arecursive common table expression is expected to include a predicate that willprevent an infinite loop. The recursive common table expression is expected toinclude:v In the iterative fullselect, an integer column incremented by a constant.v A predicate in the where clause of the iterative fullselect in the form
″counter_col < constant″ or ″counter _col < :hostvar″.
A warning is issued if this syntax is not found in the recursive common tableexpression (SQLSTATE 01605).
update-clause
common-table-expression
Chapter 4. Queries 603
�� FOR UPDATE
�
,
OF column-name
��
The FOR UPDATE clause identifies the columns that can be updated in asubsequent Positioned UPDATE statement. Each column-name must beunqualified and must identify a column of the table or view identified in thefirst FROM clause of the fullselect. If the FOR UPDATE clause is specifiedwithout column names, all updatable columns of the table or view identifiedin the first FROM clause of the fullselect are included.
The FOR UPDATE clause cannot be used if one of the following is true:v The cursor associated with the select-statement is not deletable .v One of the selected columns is a non-updatable column of a catalog table
and the FOR UPDATE clause has not been used to exclude that column.
read-only-clause
�� FOR READFETCH
ONLY ��
The FOR READ ONLY clause indicates that the result table is read-only andtherefore the cursor cannot be referred to in Positioned UPDATE and DELETEstatements. FOR FETCH ONLY has the same meaning.
Some result tables are read-only by nature. (For example, a table based on aread-only view.) FOR READ ONLY can still be specified for such tables, butthe specification has no effect.
For result tables in which updates and deletes are allowed, specifying FORREAD ONLY (or FOR FETCH ONLY) can possibly improve the performanceof FETCH operations by allowing the database manager to do blocking andavoid exclusive locks. For example, in programs that contain dynamic SQLstatements without the FOR READ ONLY or ORDER BY clause, the databasemanager might open cursors as if the FOR UPDATE clause was specified. It isrecommended, therefore, that the FOR READ ONLY clause be used toimprove performance except in cases where queries will be used in aPositioned UPDATE or DELETE statements.
A read-only result table must not be referred to in a Positioned UPDATE orDELETE statement, whether it is read-only by nature or specified as FORREAD ONLY (FOR FETCH ONLY).
update-clause
604 SQL Reference, Volume 1
optimize-for-clause
�� OPTIMIZE FOR integer ROWSROW
��
The OPTIMIZE FOR clause requests special processing of the select statement.If the clause is omitted, it is assumed that all rows of the result table will beretrieved; if it is specified, it is assumed that the number of rows retrievedwill probably not exceed n, where n is the value of integer. The value of nmust be a positive integer. Use of the OPTIMIZE FOR clause influences queryoptimization, based on the assumption that n rows will be retrieved. Inaddition, for cursors that are blocked, this clause will influence the number ofrows that will be returned in each block (that is, no more than n rows will bereturned in each block). If both the fetch-first-clause and the optimize-for-clauseare specified, the lower of the integer values from these clauses will be usedto influence the communications buffer size. The values are consideredindependently for optimization purposes.
This clause does not limit the number of rows that can be fetched, or affectthe result in any other way than performance. Using OPTIMIZE FOR n ROWScan improve performance if no more than n rows are retrieved, but maydegrade performance if more than n rows are retrieved.
If the value of n multiplied by the size of the row exceeds the size of thecommunication buffer, the OPTIMIZE FOR clause will have no impact on thedata buffers. The size of the communication buffer is defined by theRQRIOBLK or the ASLHEAPSZ configuration parameter.
Examples of a select-statementExample 1: Select all columns and rows from the EMPLOYEE table.
SELECT * FROM EMPLOYEE
Example 2: Select the project name (PROJNAME), start date (PRSTDATE), andend date (PRENDATE) from the PROJECT table. Order the result table by theend date with the most recent dates appearing first.
SELECT PROJNAME, PRSTDATE, PRENDATEFROM PROJECTORDER BY PRENDATE DESC
Example 3: Select the department number (WORKDEPT) and averagedepartmental salary (SALARY) for all departments in the EMPLOYEE table.Arrange the result table in ascending order by average departmental salary.
SELECT WORKDEPT, AVG(SALARY)FROM EMPLOYEEGROUP BY WORKDEPTORDER BY 2
optimize-for-clause
Chapter 4. Queries 605
Example 4: Declare a cursor named UP_CUR to be used in a C program toupdate the start date (PRSTDATE) and the end date (PRENDATE) columns inthe PROJECT table. The program must receive both of these values togetherwith the project number (PROJNO) value for each row.
EXEC SQL DECLARE UP_CUR CURSOR FORSELECT PROJNO, PRSTDATE, PRENDATE
FROM PROJECTFOR UPDATE OF PRSTDATE, PRENDATE;
Example 5: This example names the expression SAL+BONUS+COMM asTOTAL_PAY
SELECT SALARY+BONUS+COMM AS TOTAL_PAYFROM EMPLOYEEORDER BY TOTAL_PAY
Example 6: Determine the employee number and salary of salesrepresentatives along with the average salary and head count of theirdepartments. Also, list the average salary of the department with the highestaverage salary.
Using a common table expression for this case saves the overhead of creatingthe DINFO view as a regular view. During statement preparation, accessingthe catalog for the view is avoided and, because of the context of the rest ofthe fullselect, only the rows for the department of the sales representativesneed to be considered by the view.WITH
DINFO (DEPTNO, AVGSALARY, EMPCOUNT) AS(SELECT OTHERS.WORKDEPT, AVG(OTHERS.SALARY), COUNT(*)
FROM EMPLOYEE OTHERSGROUP BY OTHERS.WORKDEPT
),DINFOMAX AS
(SELECT MAX(AVGSALARY) AS AVGMAX FROM DINFO)SELECT THIS_EMP.EMPNO, THIS_EMP.SALARY,
DINFO.AVGSALARY, DINFO.EMPCOUNT, DINFOMAX.AVGMAXFROM EMPLOYEE THIS_EMP, DINFO, DINFOMAXWHERE THIS_EMP.JOB = ’SALESREP’AND THIS_EMP.WORKDEPT = DINFO.DEPTNO
Related reference:
v “Subselect” on page 554v “DECLARE CURSOR statement” in the SQL Reference, Volume 2
v Appendix L, “Recursion example: bill of materials” on page 861
Examples of a select-statement
606 SQL Reference, Volume 1
Appendix A. SQL limits
The following tables describe certain SQL limits. Adhering to the mostrestrictive case can help the programmer design application programs that areeasily portable.
Table 41. Identifier Length Limits
Description Limit in Bytes
Longest authorization name (can only be single-bytecharacters)
30
Longest constraint name 18
Longest correlation name 128
Longest condition name 64
Longest cursor name 18
Longest data source column name 128
Longest data source index name 128
Longest data source name 128
Longest data source table name (remote-table-name) 128
Longest external program name 8
Longest host identifier a 255
Longest identifier of a data source user(remote-authorization-name)
30
Longest label name 64
Longest method name 18
Longest parameter name b 128
Longest password to access a data source 32
Longest savepoint name 128
Longest schema name c 30
Longest server (database alias) name 8
Longest SQL variable name 64
Longest statement name 18
Longest transform group name 18
Longest unqualified column name 30
Longest unqualified package name 8
© Copyright IBM Corp. 1993 - 2002 607
Table 41. Identifier Length Limits (continued)
Description Limit in Bytes
Longest unqualified user-defined type, user-definedfunction, user-defined method, buffer pool, table space,database partition group, trigger, index, or indexspecification name
18
Longest unqualified table name, view name, storedprocedure name, sequence name, nickname, or alias
128
Longest wrapper name 128
Notes:
1. a Individual host language compilers may have a more restrictive limit on variablenames.
2. b Parameter names in an SQL procedure are limited to 64 bytes.
3. c The schema name for a user-defined type is limited to 8 bytes.
Table 42. Numeric Limits
Description Limit
Smallest INTEGER value −2 147 483 648
Largest INTEGER value +2 147 483 647
Smallest BIGINT value −9 223 372 036 854 775 808
Largest BIGINT value +9 223 372 036 854 775 807
Smallest SMALLINT value −32 768
Largest SMALLINT value +32 767
Largest decimal precision 31
Smallest DOUBLE value −1.79769E+308
Largest DOUBLE value +1.79769E+308
Smallest positive DOUBLE value +2.225E−307
Largest negative DOUBLE value −2.225E−307
Smallest REAL value −3.402E+38
Largest REAL value +3.402E+38
Smallest positive REAL value +1.175E−37
Largest negative REAL value −1.175E−37
Table 43. String Limits
Description Limit
Maximum length of CHAR (in bytes) 254
SQL limits
608 SQL Reference, Volume 1
Table 43. String Limits (continued)
Description Limit
Maximum length of VARCHAR (in bytes) 32 672
Maximum length of LONG VARCHAR (in bytes) 32 700
Maximum length of CLOB (in bytes) 2 147 483 647
Maximum length of GRAPHIC (in characters) 127
Maximum length of VARGRAPHIC (in characters) 16 336
Maximum length of LONG VARGRAPHIC (incharacters)
16 350
Maximum length of DBCLOB (in characters) 1 073 741 823
Maximum length of BLOB (in bytes) 2 147 483 647
Maximum length of character constant 32 672
Maximum length of graphic constant 16 336
Maximum length of concatenated character string 2 147 483 647
Maximum length of concatenated graphic string 1 073 741 823
Maximum length of concatenated binary string 2 147 483 647
Maximum number of hex constant digits 16 336
Maximum size of a catalog comment (in bytes) 254
Largest instance of a structured type column object atrun time
1 GB
Table 44. Datetime Limits
Description Limit
Smallest DATE value 0001-01-01
Largest DATE value 9999-12-31
Smallest TIME value 00:00:00
Largest TIME value 24:00:00
Smallest TIMESTAMP value 0001-01-01-00.00.00.000000
Largest TIMESTAMP value 9999-12-31-24.00.00.000000
Table 45. Database Manager Limits
Description Limit
Most columns in a table g 1 012
Most columns in a view a 5 000
Maximum length of a row including all overhead b g 32 677
SQL limits
Appendix A. SQL limits 609
Table 45. Database Manager Limits (continued)
Description Limit
Maximum size of a table per partition (in gigabytes) c g 512
Maximum size of an index per partition (in gigabytes) 512
Most rows in a table per partition 4 x 10 9
Longest index key including all overhead (in bytes) 1 024
Most columns in an index key 16
Most indexes on a table 32 767 or storage
Most tables referenced in an SQL statement or a view storage
Most host variable declarations in a precompiledprogram c
storage
Most host variable references in an SQL statement 32 767
Longest host variable value used for insert or update (inbytes)
2 147 483 647
Longest SQL statement (in bytes) 65 535
Most elements in a select list g 1 012
Most predicates in a WHERE or HAVING clause storage
Maximum number of columns in a GROUP BY clause g 1 012
Maximum total length of columns in a GROUP BYclause (in bytes) g
32 677
Maximum number of columns in an ORDER BY clause g 1 012
Maximum total length of columns in an ORDER BYclause (in bytes) g
32 677
Maximum size of an SQLDA (in bytes) storage
Maximum number of prepared statements storage
Most declared cursors in a program storage
Maximum number of cursors opened at one time storage
Most tables in an SMS table space 65 534
Maximum number of constraints on a table storage
Maximum level of subquery nesting storage
Maximum number of subqueries in a single statement storage
Most values in an INSERT statement g 1 012
Most SET clauses in a single UPDATE statement g 1 012
Most columns in a UNIQUE constraint (supported via aUNIQUE index)
16
SQL limits
610 SQL Reference, Volume 1
Table 45. Database Manager Limits (continued)
Description Limit
Maximum combined length of columns in a UNIQUEconstraint (supported via a UNIQUE index) (in bytes)
1 024
Most referencing columns in a foreign key 16
Maximum combined length of referencing columns in aforeign key (in bytes)
1 024
Maximum length of a check constraint specification (inbytes)
65 535
Maximum number of columns in a partitioning key e 500
Maximum number of rows changed in a unit of work storage
Maximum number of packages storage
Most constants in a statement storage
Maximum concurrent users of server d 64 000
Maximum number of parameters in a stored procedure 32 767
Maximum number of parameters in a user definedfunction
90
Maximum run-time depth of cascading triggers 16
Maximum number of simultaneously active eventmonitors
32
Maximum size of a regular DMS table space (ingigabytes) c g
512
Maximum size of a long DMS table space (in terabytes) c 2
Maximum size of a temporary DMS table space (interabytes) c
2
Maximum number of databases per instanceconcurrently in use
256
Maximum number of concurrent users per instance 64 000
Maximum number of concurrent applications perdatabase
60 000
Maximum number of connections per process within aDB2 client
512
Maximum depth of cascaded triggers 16
Maximum partition number 999
Most table objects in DMS table space f 51 000
Longest variable index key part (in bytes) h 1022 or storage
Maximum number of columns in a data source table orview that is referenced by a nickname
5 000
SQL limits
Appendix A. SQL limits 611
Table 45. Database Manager Limits (continued)
Description Limit
Maximum NPAGES in a buffer pool for 32-bit releases 524 288
Maximum NPAGES in a buffer pool for 64-bit releases 2 147 483 647
Maximum total size of all buffer pool slots (4K) 2 147 483 646
Maximum number of nested levels for stored procedures 16
Maximum number of tablespaces in a database 4096
Maximum number of attributes in a structured type 4082
Maximum number of simultaneously opened LOBlocators in a transaction
32 100
Notes:
1. a This maximum can be achieved using a join in the CREATE VIEW statement.Selecting from such a view is subject to the limit of most elements in a select list.
2. b The actual data for BLOB, CLOB, LONG VARCHAR, DBCLOB, and LONGVARGRAPHIC columns is not included in this count. However, information aboutthe location of that data does take up some space in the row.
3. c The numbers shown are architectural limits and approximations. The practicallimits may be less.
4. d The actual value will be the value of the MAXAGENTS configuration parameter.
5. e This is an architectural limit. The limit on the most columns in an index keyshould be used as the practical limit.
6. f Table objects include data, indexes, LONG VARCHAR or VARGRAPHIC columns,and LOB columns. Table objects that are in the same table space as the table datado not count extra toward the limit. However, each table object that is in a differenttable space than the table data does contribute one toward the limit for each tableobject type per table in the table space in which the table object resides.
7. g For page size-specific values, see Table 46.
8. h This is limited only by the longest index key, including all overhead (in bytes). Asthe number of index key parts increases, the maximum length of each key partdecreases.
Table 46. Database Manager Page Size Specific Limits
Description 4K page sizelimit
8K page sizelimit
16K page sizelimit
32K page sizelimit
Most columns in a table 500 1 012 1 012 1 012
Maximum length of a rowincluding all overhead
4 005 8 101 16 293 32 677
Maximum size of a table perpartition (in gigabytes)
64 128 256 512
SQL limits
612 SQL Reference, Volume 1
Table 46. Database Manager Page Size Specific Limits (continued)
Description 4K page sizelimit
8K page sizelimit
16K page sizelimit
32K page sizelimit
Maximum size of an index perpartition (in gigabytes)
64 128 256 512
Most elements in a select list 500 1 012 1 012 1 012
Maximum number of columnsin a GROUP BY clause
500 1 012 1 012 1 012
Maximum total length ofcolumns in a GROUP BY clause(in bytes)
4 005 8 101 16 293 32 677
Maximum number of columnsin an ORDER BY clause
500 1 012 1 012 1 012
Maximum total length ofcolumns in an ORDER BY clause(in bytes)
4 005 8 101 16 293 32 677
Most values in an INSERTstatement
500 1 012 1 012 1 012
Most SET clauses in a singleUPDATE statement
500 1 012 1 012 1 012
Maximum size of a regular DMStable space (in gigabytes)
64 128 256 512
Related reference:
v “Maximum Number of Agents configuration parameter - maxagents” in theAdministration Guide: Performance
SQL limits
Appendix A. SQL limits 613
SQL limits
614 SQL Reference, Volume 1
Appendix B. SQLCA (SQL communications area)
An SQLCA is a collection of variables that is updated at the end of theexecution of every SQL statement. A program that contains executable SQLstatements and is precompiled with option LANGLEVEL SAA1 (the default)or MIA must provide exactly one SQLCA, though more than one SQLCA ispossible by having one SQLCA per thread in a multi-threaded application.
When a program is precompiled with option LANGLEVEL SQL92E, anSQLCODE or SQLSTATE variable may be declared in the SQL declare sectionor an SQLCODE variable can be declared somewhere in the program.
An SQLCA should not be provided when using LANGLEVEL SQL92E. TheSQL INCLUDE statement can be used to provide the declaration of theSQLCA in all languages but REXX. The SQLCA is automatically provided inREXX.
To display the SQLCA after each command executed through the commandline processor, issue the command db2 -a. The SQLCA is then provided aspart of the output for subsequent commands. The SQLCA is also dumped inthe db2diag.log file.
SQLCA field descriptions
Table 47. Fields of the SQLCA. The field names shown are those present in an SQLCAthat is obtained via an INCLUDE statement.
Name Data Type Field Values
sqlcaid CHAR(8) An "eye catcher" for storage dumps containing'SQLCA'. The sixth byte is 'L' if line numberinformation is returned from parsing an SQL procedurebody.
sqlcabc INTEGER Contains the length of the SQLCA, 136.
© Copyright IBM Corp. 1993 - 2002 615
Table 47. Fields of the SQLCA (continued). The field names shown are those presentin an SQLCA that is obtained via an INCLUDE statement.
Name Data Type Field Values
sqlcode INTEGER Contains the SQL return code.
Code Means
0 Successful execution (although one or moreSQLWARN indicators may be set).
positiveSuccessful execution, but with a warningcondition.
negativeError condition.
sqlerrml SMALLINT Length indicator for sqlerrmc, in the range 0 through 70.0 means that the value of sqlerrmc is not relevant.
sqlerrmc VARCHAR(70)
Contains one or more tokens, separated by X'FF', whichare substituted for variables in the descriptions of errorconditions.
This field is also used when a successful connection iscompleted.
When a NOT ATOMIC compound SQL statement isissued, it may contain information on up to 7 errors.
sqlerrp CHAR(8) Begins with a three-letter identifier indicating theproduct, followed by five digits indicating the version,release, and modification level of the product. Forexample, SQL08010 means DB2 Universal DatabaseVersion 8 Release 1 Modification level 0.
If SQLCODE indicates an error condition, this fieldidentifies the module that returned the error.
This field is also used when a successful connection iscompleted.
sqlerrd ARRAY Six INTEGER variables that provide diagnosticinformation. These values are generally empty if thereare no errors, except for sqlerrd(6) from a partitioneddatabase.
SQLCA field descriptions
616 SQL Reference, Volume 1
Table 47. Fields of the SQLCA (continued). The field names shown are those presentin an SQLCA that is obtained via an INCLUDE statement.
Name Data Type Field Values
sqlerrd(1) INTEGER If connection is invoked and successful, contains themaximum expected difference in length of mixedcharacter data (CHAR data types) when converted tothe database code page from the application code page.A value of 0 or 1 indicates no expansion; a valuegreater than 1 indicates a possible expansion in length;a negative value indicates a possible contraction.
On successful return from an SQL procedure, containsthe return status value from the SQL procedure.
sqlerrd(2) INTEGER If connection is invoked and successful, contains themaximum expected difference in length of mixedcharacter data (CHAR data types) when converted tothe application code page from the database code page.A value of 0 or 1 indicates no expansion; a valuegreater than 1 indicates a possible expansion in length;a negative value indicates a possible contraction. If theSQLCA results from a NOT ATOMIC compound SQLstatement that encountered one or more errors, thevalue is set to the number of statements that failed.
sqlerrd(3) INTEGER If PREPARE is invoked and successful, contains anestimate of the number of rows that will be returned.After INSERT, UPDATE, and DELETE, contains theactual number of rows that qualified for the operation.If compound SQL is invoked, contains an accumulationof all sub-statement rows. If CONNECT is invoked,contains 1 if the database can be updated; 2 if thedatabase is read only.
If CREATE PROCEDURE for an SQL procedure isinvoked and an error is encountered parsing the SQLprocedure body, contains the line number where theerror was encountered. The sixth byte of sqlcaid mustbe ’L’ for this to be a valid line number.
sqlerrd(4) INTEGER If PREPARE is invoked and successful, contains arelative cost estimate of the resources required toprocess the statement. If compound SQL is invoked,contains a count of the number of successfulsub-statements. If CONNECT is invoked, contains 0 fora one-phase commit from a down-level client; 1 for aone-phase commit; 2 for a one-phase, read-only commit;and 3 for a two-phase commit.
SQLCA field descriptions
Appendix B. SQLCA (SQL communications area) 617
Table 47. Fields of the SQLCA (continued). The field names shown are those presentin an SQLCA that is obtained via an INCLUDE statement.
Name Data Type Field Values
sqlerrd(5) INTEGER Contains the total number of rows deleted, inserted, orupdated as a result of both:v The enforcement of constraints after a successful
delete operationv The processing of triggered SQL statements from
activated triggers.
If compound SQL is invoked, contains an accumulationof the number of such rows for all substatements. Insome cases when an error is encountered, this fieldcontains a negative value that is an internal errorpointer. If CONNECT is invoked, contains anauthentication type value of 0 for a serverauthentication; 1 for client authentication; 2 forauthentication using DB2 Connect; 3 for DCE securityservices authentication; 255 for unspecifiedauthentication.
sqlerrd(6) INTEGER For a partitioned database, contains the partitionnumber of the partition that encountered the error orwarning. If no errors or warnings were encountered,this field contains the partition number of thecoordinator node. The number in this field is the sameas that specified for the partition in the db2nodes.cfgfile.
sqlwarn Array A set of warning indicators, each containing a blank orW. If compound SQL is invoked, contains anaccumulation of the warning indicators set for allsubstatements.
sqlwarn0 CHAR(1) Blank if all other indicators are blank; contains W if atleast one other indicator is not blank.
sqlwarn1 CHAR(1) Contains W if the value of a string column wastruncated when assigned to a host variable. Contains Nif the null terminator was truncated.
Contains A if the CONNECT or ATTACH is successful,and the authorization name for the connection is longerthan 8 bytes.
sqlwarn2 CHAR(1) Contains W if null values were eliminated from theargument of a function. a
sqlwarn3 CHAR(1) Contains W if the number of columns is not equal tothe number of host variables.
sqlwarn4 CHAR(1) Contains W if a prepared UPDATE or DELETEstatement does not include a WHERE clause.
SQLCA field descriptions
618 SQL Reference, Volume 1
Table 47. Fields of the SQLCA (continued). The field names shown are those presentin an SQLCA that is obtained via an INCLUDE statement.
Name Data Type Field Values
sqlwarn5 CHAR(1) Reserved for future use.
sqlwarn6 CHAR(1) Contains W if the result of a date calculation wasadjusted to avoid an impossible date.
sqlwarn7 CHAR(1) Reserved for future use.
If CONNECT is invoked and successful, contains ’E’ ifthe DYN_QUERY_MGMT database configurationparameter is enabled.
sqlwarn8 CHAR(1) Contains W if a character that could not be convertedwas replaced with a substitution character.
sqlwarn9 CHAR(1) Contains W if arithmetic expressions with errors wereignored during column function processing.
sqlwarn10 CHAR(1) Contains W if there was a conversion error whenconverting a character data value in one of the fields inthe SQLCA.
sqlstate CHAR(5) A return code that indicates the outcome of the mostrecently executed SQL statement.
a Some functions may not set SQLWARN2 to W, even though null values wereeliminated, because the result was not dependent on the elimination of null values.
Error reporting
The order of error reporting is as follows:1. Severe error conditions are always reported. When a severe error is
reported, there are no additions to the SQLCA.2. If no severe error occurs, a deadlock error takes precedence over other
errors.3. For all other errors, the SQLCA for the first negative SQL code is returned.4. If no negative SQL codes are detected, the SQLCA for the first warning
(that is, positive SQL code) is returned.In a partitioned database system, the exception to this rule occurs if a datamanipulation operation is invoked against a table that is empty on onepartition, but has data on other partitions. SQLCODE +100 is onlyreturned to the application if agents from all partitions return SQL0100W,either because the table is empty on all partitions, or there are no morerows that satisfy the WHERE clause in an UPDATE statement.
SQLCA field descriptions
Appendix B. SQLCA (SQL communications area) 619
SQLCA usage in partitioned database systems
In partitioned database systems, one SQL statement may be executed by anumber of agents on different partitions, and each agent may return adifferent SQLCA for different errors or warnings. The coordinator agent alsohas its own SQLCA.
To provide a consistent view for applications, all SQLCA values are mergedinto one structure, and SQLCA fields indicate global counts, such that:v For all errors and warnings, the sqlwarn field contains the warning flags
received from all agents.v Values in the sqlerrd fields indicating row counts are accumulations from all
agents.
Note that SQLSTATE 09000 may not be returned every time an error occursduring the processing of a triggered SQL statement.
SQLCA usage in partitioned database systems
620 SQL Reference, Volume 1
Appendix C. SQLDA (SQL descriptor area)
An SQLDA is a collection of variables that is required for execution of theSQL DESCRIBE statement. The SQLDA variables are options that can be usedby the PREPARE, OPEN, FETCH, and EXECUTE statements. An SQLDAcommunicates with dynamic SQL; it can be used in a DESCRIBE statement,modified with the addresses of host variables, and then reused in a FETCH orEXECUTE statement.
SQLDAs are supported for all languages, but predefined declarations areprovided only for C, REXX, FORTRAN, and COBOL.
The meaning of the information in an SQLDA depends on its use. InPREPARE and DESCRIBE, an SQLDA provides information to an applicationprogram about a prepared statement. In OPEN, EXECUTE, and FETCH, anSQLDA describes host variables.
In DESCRIBE and PREPARE, if any one of the columns being described iseither a LOB type (LOB locators and file reference variables do not requiredoubled SQLDAs), reference type, or a user-defined type, the number ofSQLVAR entries for the entire SQLDA will be doubled. For example:v When describing a table with 3 VARCHAR columns and 1 INTEGER
column, there will be 4 SQLVAR entriesv When describing a table with 2 VARCHAR columns, 1 CLOB column, and 1
integer column, there will be 8 SQLVAR entries
In EXECUTE, FETCH, and OPEN, if any one of the variables being describedis a LOB type (LOB locators and file reference variables do not requiredoubled SQLDAs) or a structured type, the number of SQLVAR entries for theentire SQLDA must be doubled. (Distinct types and reference types are notrelevant in these cases, because the additional information in the doubleentries is not required by the database.)
SQLDA field descriptions
An SQLDA consists of four variables followed by an arbitrary number ofoccurrences of a sequence of variables collectively named SQLVAR. In OPEN,FETCH, and EXECUTE, each occurrence of SQLVAR describes a host variable.In DESCRIBE and PREPARE, each occurrence of SQLVAR describes a columnof a result table or a parameter marker. There are two types of SQLVARentries:
© Copyright IBM Corp. 1993 - 2002 621
v Base SQLVARs: These entries are always present. They contain the baseinformation about the column, parameter marker, or host variable such asdata type code, length attribute, column name, host variable address, andindicator variable address.
v Secondary SQLVARs: These entries are only present if the number ofSQLVAR entries is doubled as per the rules outlined above. Foruser-defined types (distinct or structured), they contain the user-definedtype name. For reference types, they contain the target type of the reference.For LOBs, they contain the length attribute of the host variable and apointer to the buffer that contains the actual length. (The distinct type andLOB information does not overlap, so distinct types can be based on LOBswithout forcing the number of SQLVAR entries on a DESCRIBE to betripled.) If locators or file reference variables are used to represent LOBs,these entries are not necessary.
In SQLDAs that contain both types of entries, the base SQLVARs are in ablock before the block of secondary SQLVARs. In each, the number of entriesis equal to the value in SQLD (even though many of the secondary SQLVARentries may be unused).
The circumstances under which the SQLVAR entries are set by DESCRIBE isdetailed in “Effect of DESCRIBE on the SQLDA” on page 627.
Fields in the SQLDA header
Table 48. Fields in the SQLDA Header
C Name SQL DataType
Usage in DESCRIBE and PREPARE(set by the database manager exceptfor SQLN)
Usage in FETCH, OPEN, andEXECUTE (set by the applicationprior to executing the statement)
sqldaid CHAR(8) The seventh byte of this field is a flagbyte named SQLDOUBLED. Thedatabase manager setsSQLDOUBLED to the character ’2’ iftwo SQLVAR entries have beencreated for each column; otherwise itis set to a blank (X'20' in ASCII, X'40'in EBCDIC). See “Effect of DESCRIBEon the SQLDA” on page 627 fordetails on when SQLDOUBLED isset.
The seventh byte of this field is usedwhen the number of SQLVARs isdoubled. It is named SQLDOUBLED.If any of the host variables beingdescribed is a structured type, BLOB,CLOB, or DBCLOB, the seventh bytemust be set to the character ’2’;otherwise it can be set to anycharacter but the use of a blank isrecommended.
sqldabc INTEGER For 32 bit, the length of the SQLDA,equal to SQLN*44+16. For 64 bit, thelength of the SQLDA, equal toSQLN*56+16
For 32 bit, the length of the SQLDA,>= to SQLN*44+16. For 64 bit, thelength of the SQLDA, >= toSQLN*56+16.
SQLDA field descriptions
622 SQL Reference, Volume 1
Table 48. Fields in the SQLDA Header (continued)
C Name SQL DataType
Usage in DESCRIBE and PREPARE(set by the database manager exceptfor SQLN)
Usage in FETCH, OPEN, andEXECUTE (set by the applicationprior to executing the statement)
sqln SMALLINT Unchanged by the database manager.Must be set to a value greater than orequal to zero before the DESCRIBEstatement is executed. Indicates thetotal number of occurrences ofSQLVAR.
Total number of occurrences ofSQLVAR provided in the SQLDA.SQLN must be set to a value greaterthan or equal to zero.
sqld SMALLINT Set by the database manager to thenumber of columns in the result tableor to the number of parametermarkers.
The number of host variablesdescribed by occurrences of SQLVAR.
Fields in an occurrence of a base SQLVAR
Table 49. Fields in a Base SQLVAR
Name Data Type Usage in DESCRIBE and PREPARE Usage in FETCH, OPEN, andEXECUTE
sqltype SMALLINT Indicates the data type of the columnor parameter marker, and whether itcan contain nulls. Table 51 onpage 629 lists the allowable valuesand their meanings.
Note that for a distinct or referencetype, the data type of the base type isplaced into this field. For astructured type, the data type of theresult of the FROM SQL transformfunction of the transform group(based on the CURRENT DEFAULTTRANSFORM GROUP specialregister) for the type is placed intothis field. There is no indication inthe base SQLVAR that it is part of thedescription of a user-defined type orreference type.
Same for host variable. Hostvariables for datetime values must becharacter string variables. ForFETCH, a datetime type code meansa fixed-length character string. Ifsqltype is an even number value, thesqlind field is ignored.
Fields in the SQLDA header
Appendix C. SQLDA (SQL descriptor area) 623
Table 49. Fields in a Base SQLVAR (continued)
Name Data Type Usage in DESCRIBE and PREPARE Usage in FETCH, OPEN, andEXECUTE
sqllen SMALLINT The length attribute of the column orparameter marker. For datetimecolumns and parameter markers, thelength of the string representation ofthe values. See Table 51 on page 629.
Note that the value is set to 0 forlarge object strings (even for thosewhose length attribute is smallenough to fit into a two byte integer).
The length attribute of the hostvariable. See Table 51 on page 629.
Note that the value is ignored by thedatabase manager for CLOB,DBCLOB, and BLOB columns. Thelen.sqllonglen field in the SecondarySQLVAR is used instead.
sqldata pointer For string SQLVARS, sqldata containsthe code page. For character-stringSQLVARs where the column isdefined with the FOR BIT DATAattribute, sqldata contains 0. Forother character-string SQLVARS,sqldata contains either the SBCS codepage for SBCS data, or the SBCS codepage associated with the compositeMBCS code page for MBCS data. ForJapanese EUC, Traditional ChineseEUC, and Unicode UTF-8character-string SQLVARS, sqldatacontains 954, 964, and 1208respectively.
For all other column types, sqldata isundefined.
Contains the address of the hostvariable (where the fetched data willbe stored).
sqlind pointer For character-string SQLVARS, sqlindcontains 0, except for MBCS data,when sqlind contains the DBCS codepage associated with the compositeMBCS code page.
For all other types, sqlind isundefined.
Contains the address of an associatedindicator variable, if there is one;otherwise, not used. If sqltype is aneven number value, the sqlind fieldis ignored.
Fields in an occurrence of a base SQLVAR
624 SQL Reference, Volume 1
Table 49. Fields in a Base SQLVAR (continued)
Name Data Type Usage in DESCRIBE and PREPARE Usage in FETCH, OPEN, andEXECUTE
sqlname VARCHAR(30)
Contains the unqualified name of thecolumn or parameter marker.
For columns and parameter markersthat have a system-generated name,the thirtieth byte is set to X'FF'. Forcolumn names specified by the ASclause, this byte is X'00'.
When using DB2 Connect to accessthe server, sqlname can be set toindicate a FOR BIT DATA string asfollows:
v the length of sqlname is 8
v the first four bytes of sqlname areX'00000000'
v the remaining four bytes ofsqlname are reserved (andcurrently ignored).
Fields in an occurrence of a secondary SQLVAR
Table 50. Fields in a Secondary SQLVAR
Name Data Type Usage in DESCRIBEand PREPARE
Usage in FETCH, OPEN, andEXECUTE
len.sqllonglen INTEGER The length attribute of aBLOB, CLOB, orDBCLOB column orparameter marker.
The length attribute of a BLOB,CLOB, or DBCLOB host variable.The database manager ignoresthe SQLLEN field in the BaseSQLVAR for the data types. Thelength attribute stores thenumber of bytes for a BLOB orCLOB, and the number ofcharacters for a DBCLOB.
reserve2 CHAR(3) for 32bit, andCHAR(11) for 64bit.
Not used. Not used.
sqlflag4 CHAR(1) The value is X’01’ if theSQLVAR represents areference type with atarget type named insqldatatype_name. Thevalue is X’12’ if theSQLVAR represents astructured type, with theuser-defined type namein sqldatatype_name.Otherwise, the value isX’00’.
Set to X’01’ if the SQLVARrepresents a reference type witha target type named insqldatatype_name. Set to X’12’ ifthe SQLVAR represents astructured type, with theuser-defined type name insqldatatype_name. Otherwise,the value is X’00’.
Fields in an occurrence of a base SQLVAR
Appendix C. SQLDA (SQL descriptor area) 625
Table 50. Fields in a Secondary SQLVAR (continued)
Name Data Type Usage in DESCRIBEand PREPARE
Usage in FETCH, OPEN, andEXECUTE
sqldatalen pointer Not used. Used for BLOB, CLOB, andDBCLOB host variables only.
If this field is NULL, then theactual length (in characters)should be stored in the 4 bytesimmediately before the start ofthe data and SQLDATA shouldpoint to the first byte of the fieldlength.
If this field is not NULL, itcontains a pointer to a 4 bytelong buffer that contains theactual length in bytes (even forDBCLOB) of the data in thebuffer pointed to from theSQLDATA field in the matchingbase SQLVAR.
Note that, whether or not thisfield is used, the len.sqllonglenfield must be set.
sqldatatype_name VARCHAR(27) For a user-defined type,the database managersets this to the fullyqualified user-definedtype name.1 For areference type, thedatabase manager setsthis to the fully qualifiedtype name of the targettype of the reference.
For structured types, set to thefully qualified user-defined typename in the format indicated inthe table note.1
reserved CHAR(3) Not used. Not used.
Fields in an occurrence of a secondary SQLVAR
626 SQL Reference, Volume 1
Table 50. Fields in a Secondary SQLVAR (continued)
Name Data Type Usage in DESCRIBEand PREPARE
Usage in FETCH, OPEN, andEXECUTE
1 The first 8 bytes contain the schema name of the type (extended to the right with spaces, if necessary).Byte 9 contains a dot (.). Bytes 10 to 27 contain the low order portion of the type name, which is notextended to the right with spaces.
Note that, although the prime purpose of this field is for the name of user-defined types, the field is alsoset for IBM predefined data types. In this case, the schema name is SYSIBM, and the low order portionof the name is the name stored in the TYPENAME column of the DATATYPES catalog view. Forexample:
type name length sqldatatype_name--------- ------ ----------------A.B 10 A .BINTEGER 16 SYSIBM .INTEGER"Frank’s".SMINT 13 Frank’s .SMINTMY."type " 15 MY .type
Effect of DESCRIBE on the SQLDA
For a DESCRIBE OUTPUT or PREPARE OUTPUT INTO statement, thedatabase manager always sets SQLD to the number of columns in the resultset, or the number of output parameter markers. For a DESCRIBE INPUT orPREPARE INPUT INTO statement, the database manager always sets SQLD tothe number of input parameter markers in the statement. Note that aparameter marker that corresponds to an INOUT parameter in a CALLstatement is described in both the input and output descriptors.
The SQLVARs in the SQLDA are set in the following cases:v SQLN >= SQLD and no entry is either a LOB, user-defined type or
reference typeThe first SQLD SQLVAR entries are set and SQLDOUBLED is set to blank.
v SQLN >= 2*SQLD and at least one entry is a LOB, user-defined type orreference typeTwo times SQLD SQLVAR entries are set, and SQLDOUBLED is set to ’2’.
v SQLD <= SQLN < 2*SQLD and at least one entry is a distinct type orreference type, but there are no LOB entries or structured type entriesThe first SQLD SQLVAR entries are set and SQLDOUBLED is set to blank.If the SQLWARN bind option is YES, a warning SQLCODE +237(SQLSTATE 01594) is issued.
The SQLVARs in the SQLDA are NOT set (requiring allocation of additionalspace and another DESCRIBE) in the following cases:
Fields in an occurrence of a secondary SQLVAR
Appendix C. SQLDA (SQL descriptor area) 627
v SQLN < SQLD and no entry is either a LOB, user-defined type or referencetypeNo SQLVAR entries are set and SQLDOUBLED is set to blank. If theSQLWARN bind option is YES, a warning SQLCODE +236 (SQLSTATE01005) is issued.Allocate SQLD SQLVARs for a successful DESCRIBE.
v SQLN < SQLD and at least one entry is a distinct type or reference type,but there are no LOB entries or structured type entriesNo SQLVAR entries are set and SQLDOUBLED is set to blank. If theSQLWARN bind option is YES, a warning SQLCODE +239 (SQLSTATE01005) is issued.Allocate 2*SQLD SQLVARs for a successful DESCRIBE including the namesof the distinct types and target types of reference types.
v SQLN < 2*SQLD and at least one entry is a LOB or a structured typeNo SQLVAR entries are set and SQLDOUBLED is set to blank. A warningSQLCODE +238 (SQLSTATE 01005) is issued (regardless of the setting ofthe SQLWARN bind option).Allocate 2*SQLD SQLVARs for a successful DESCRIBE.
References in the above lists to LOB entries include distinct type entrieswhose source type is a LOB type.
The SQLWARN option of the BIND or PREP command is used to controlwhether the DESCRIBE (or PREPARE INTO) will return the warningSQLCODEs +236, +237, +239. It is recommended that your application codealways consider that these SQLCODEs could be returned. The warningSQLCODE +238 is always returned when there are LOB or structured typeentries in the select list and there are insufficient SQLVARs in the SQLDA.This is the only way the application can know that the number of SQLVARsmust be doubled because of a LOB or structured type entry in the result set.
If a structured type entry is being described, but no FROM SQL transform isdefined (either because no TRANSFORM GROUP was specified using theCURRENT DEFAULT TRANSFORM GROUP special register (SQLSTATE42741), or because the name group does not have a FROM SQL transformfunction defined (SQLSTATE 42744), the DESCRIBE will return an error. Thiserror is the same error returned for a DESCRIBE of a table with a structuredtype entry.
Effect of DESCRIBE on the SQLDA
628 SQL Reference, Volume 1
SQLTYPE and SQLLEN
Table 51 shows the values that may appear in the SQLTYPE and SQLLENfields of the SQLDA. In DESCRIBE and PREPARE INTO, an even value ofSQLTYPE means that the column does not allow nulls, and an odd valuemeans the column does allow nulls. In FETCH, OPEN, and EXECUTE, aneven value of SQLTYPE means that no indicator variable is provided, and anodd value means that SQLIND contains the address of an indicator variable.
Table 51. SQLTYPE and SQLLEN values for DESCRIBE, FETCH, OPEN, and EXECUTE
For DESCRIBE and PREPARE INTO For FETCH, OPEN, and EXECUTE
SQLTYPE Column Data Type SQLLEN Host Variable DataType
SQLLEN
384/385 date 10 fixed-lengthcharacter stringrepresentation of adate
length attribute ofthe host variable
388/389 time 8 fixed-lengthcharacter stringrepresentation of atime
length attribute ofthe host variable
392/393 timestamp 26 fixed-lengthcharacter stringrepresentation of atimestamp
length attribute ofthe host variable
396/397 DATALINK length attribute ofthe column
DATALINK length attribute ofthe host variable
400/401 N/A N/A NUL-terminatedgraphic string
length attribute ofthe host variable
404/405 BLOB 0 * BLOB Not used. *
408/409 CLOB 0 * CLOB Not used. *
412/413 DBCLOB 0 * DBCLOB Not used. *
448/449 varying-lengthcharacter string
length attribute ofthe column
varying-lengthcharacter string
length attribute ofthe host variable
452/453 fixed-lengthcharacter string
length attribute ofthe column
fixed-lengthcharacter string
length attribute ofthe host variable
456/457 long varying-lengthcharacter string
length attribute ofthe column
long varying-lengthcharacter string
length attribute ofthe host variable
460/461 N/A N/A NUL-terminatedcharacter string
length attribute ofthe host variable
464/465 varying-lengthgraphic string
length attribute ofthe column
varying-lengthgraphic string
length attribute ofthe host variable
SQLTYPE and SQLLEN
Appendix C. SQLDA (SQL descriptor area) 629
Table 51. SQLTYPE and SQLLEN values for DESCRIBE, FETCH, OPEN, and EXECUTE (continued)
For DESCRIBE and PREPARE INTO For FETCH, OPEN, and EXECUTE
SQLTYPE Column Data Type SQLLEN Host Variable DataType
SQLLEN
468/469 fixed-lengthgraphic string
length attribute ofthe column
fixed-lengthgraphic string
length attribute ofthe host variable
472/473 long varying-lengthgraphic string
length attribute ofthe column
long graphic string length attribute ofthe host variable
480/481 floating point 8 for doubleprecision, 4 forsingle precision
floating point 8 for doubleprecision, 4 forsingle precision
484/485 packed decimal precision in byte 1;scale in byte 2
packed decimal precision in byte 1;scale in byte 2
492/493 big integer 8 big integer 8
496/497 large integer 4 large integer 4
500/501 small integer 2 small integer 2
916/917 Not applicable Not applicable BLOB file referencevariable.
267
920/921 Not applicable Not applicable CLOB file referencevariable.
267
924/925 Not applicable Not applicable DBCLOB filereference variable.
267
960/961 Not applicable Not applicable BLOB locator 4
964/965 Not applicable Not applicable CLOB locator 4
968/969 Not applicable Not applicable DBCLOB locator 4
Note:
v The len.sqllonglen field in the secondary SQLVAR contains the length attribute of the column.
v The SQLTYPE has changed from the previous version for portability in DB2. The values from theprevious version (see previous version SQL Reference) will continue to be supported.
Unrecognized and unsupported SQLTYPEsThe values that appear in the SQLTYPE field of the SQLDA are dependent onthe level of data type support available at the sender as well as at the receiverof the data. This is particularly important as new data types are added to theproduct.
New data types may or may not be supported by the sender or receiver of thedata and may or may not even be recognized by the sender or receiver of thedata. Depending on the situation, the new data type may be returned, or a
SQLTYPE and SQLLEN
630 SQL Reference, Volume 1
compatible data type agreed upon by both the sender and receiver of the datamay be returned or an error may result.
When the sender and receiver agree to use a compatible data type, thefollowing indicates the mapping that will take place. This mapping will takeplace when at least one of the sender or the receiver does not support thedata type provided. The unsupported data type can be provided by either theapplication or the database manager.
Data Type Compatible Data Type
BIGINT DECIMAL(19, 0)
ROWID1 VARCHAR(40) FOR BIT DATA1 ROWID is supported by DB2 Universal Database for z/OS and OS/390 Version 6.
Note that no indication is given in the SQLDA that the data type issubstituted.
Packed decimal numbersPacked decimal numbers are stored in a variation of Binary Coded Decimal(BCD) notation. In BCD, each nybble (four bits) represents one decimal digit.For example, 0001 0111 1001 represents 179. Therefore, read a packed decimalvalue nybble by nybble. Store the value in bytes and then read those bytes inhexadecimal representation to return to decimal. For example, 0001 0111 1001becomes 00000001 01111001 in binary representation. By reading this numberas hexadecimal, it becomes 0179.
The decimal point is determined by the scale. In the case of a DEC(12,5)column, for example, the rightmost 5 digits are to the right of the decimalpoint.
Sign is indicated by a nybble to the right of the nybbles representing thedigits. A positive or negative sign is indicated as follows:
Table 52. Values for Sign Indicator of a Packed Decimal Number
Sign
Representation
Binary Decimal Hexadecimal
Positive (+) 1100 12 C
Negative (-) 1101 13 D
In summary:v To store any value, allocate p/2+1 bytes, where p is precision.
Unrecognized and unsupported SQLTYPEs
Appendix C. SQLDA (SQL descriptor area) 631
v Assign the nybbles from left to right to represent the value. If a number hasan even precision, a leading zero nybble is added. This assignment includesleading (insignificant) and trailing (significant) zero digits.
v The sign nybble will be the second nybble of the last byte.
For example:
Column Value Nybbles in Hexadecimal Grouped by Bytes
DEC(8,3) 6574.23 00 65 74 23 0C
DEC(6,2) -334.02 00 33 40 2D
DEC(7,5) 5.2323 05 23 23 0C
DEC(5,2) -23.5 02 35 0D
SQLLEN field for decimalThe SQLLEN field contains the precision (first byte) and scale (second byte) ofthe decimal column. If writing a portable application, the precision and scalebytes should be set individually, versus setting them together as a shortinteger. This will avoid integer byte reversal problems.
For example, in C:((char *)&(sqlda->sqlvar[i].sqllen))[0] = precision;((char *)&(sqlda->sqlvar[i].sqllen))[1] = scale;
Related reference:
v “CHAR” on page 303
Packed decimal numbers
632 SQL Reference, Volume 1
Appendix D. Catalog views
This appendix contains a description of each system catalog view, includingcolumn names and data types.
‘Road map’ to catalog views
Description Catalog View Page
attributes of structured data types SYSCAT.ATTRIBUTES 639
authorities on database SYSCAT.DBAUTH 661
buffer pool configuration on databasepartition group
SYSCAT.BUFFERPOOLS 642
buffer pool size on database partition SYSCAT.BUFFERPOOLDBPARTITIONS 641
cast functions SYSCAT.CASTFUNCTIONS 643
check constraints SYSCAT.CHECKS 644
column privileges SYSCAT.COLAUTH 645
columns SYSCAT.COLUMNS 652
columns referenced by checkconstraints
SYSCAT.COLCHECKS 646
columns used in dimensions SYSCAT.COLUSE 657
columns used in keys SYSCAT.KEYCOLUSE 688
detailed column options SYSCAT.COLOPTIONS 651
detailed column statistics SYSCAT.COLDIST 647
detailed column group statistics SYSCAT.COLGROUPDIST 648
detailed column group statistics SYSCAT.COLGROUPDISTCOUNTS 649
detailed column group statistics SYSCAT.COLGROUPS 650
constraint dependencies SYSCAT.CONSTDEP 658
data types SYSCAT.DATATYPES 659
event monitor definitions SYSCAT.EVENTMONITORS 665
events currently monitored SYSCAT.EVENTS 667
events currently monitored SYSCAT.EVENTTABLES 668
function dependencies1 SYSCAT.ROUTINEDEP 708
function mapping SYSCAT.FUNCMAPPINGS 672
function mapping options SYSCAT.FUNCMAPOPTIONS 670
© Copyright IBM Corp. 1993 - 2002 633
Description Catalog View Page
function parameter mapping options SYSCAT.FUNCMAPPARMOPTIONS 671
function parameters1 SYSCAT.ROUTINEPARMS 709
functions1 SYSCAT.ROUTINES 711
hierarchies (types, tables, views) SYSCAT.HIERARCHIES 673
hierarchies (types, tables, views) SYSCAT.FULLHIERARCHIES 669
index privileges SYSCAT.INDEXAUTH 674
index columns SYSCAT.INDEXCOLUSE 675
index dependencies SYSCAT.INDEXDEP 676
indexes SYSCAT.INDEXES 677
index exploitation SYSCAT.INDEXEXPLOITRULES 682
index extension dependencies SYSCAT.INDEXEXTENSIONDEP 683
index extension search methods SYSCAT.INDEXEXTENSIONMETHODS 684
index extension parameters SYSCAT.INDEXEXTENSIONPARMS 685
index extensions SYSCAT.INDEXEXTENSIONS 686
method dependencies1 SYSCAT.ROUTINEDEP 708
method parameters1 SYSCAT.ROUTINES 711
methods1 SYSCAT.ROUTINES 711
database partition group definitions SYSCAT.DBPARTITIONGROUPS 664
database partition group databasepartitions
SYSCAT.DBPARTITIONGROUPDEF 663
object mapping SYSCAT.NAMEMAPPINGS 689
package dependencies SYSCAT.PACKAGEDEP 691
package privileges SYSCAT.PACKAGEAUTH 690
packages SYSCAT.PACKAGES 693
partitioning maps SYSCAT.PARTITIONMAPS 699
pass-through privileges SYSCAT.PASSTHRUAUTH 700
predicate specifications SYSCAT.PREDICATESPECS 701
procedure options SYSCAT.PROCOPTIONS 702
procedure parameter options SYSCAT.PROCPARMOPTIONS 703
procedure parameters1 SYSCAT.ROUTINEPARMS 709
procedures1 SYSCAT.ROUTINES 711
provides DB2 Universal Database forz/OS and OS/390 compatibility
SYSIBM.SYSDUMMY1 638
referential constraints SYSCAT.REFERENCES 704
‘Road map’ to catalog views
634 SQL Reference, Volume 1
Description Catalog View Page
remote table options SYSCAT.TABOPTIONS 736
reverse data type mapping SYSCAT.REVTYPEMAPPINGS 705
routine dependencies SYSCAT.ROUTINEDEP 708
routine parameters1 SYSCAT.ROUTINEPARMS 709
routine privileges SYSCAT.ROUTINEAUTH 707
routines1 SYSCAT.ROUTINES 711
schema privileges SYSCAT.SCHEMAAUTH 718
schemas SYSCAT.SCHEMATA 719
sequence privileges SYSCAT.SEQUENCEAUTH 720
sequences SYSCAT.SEQUENCES 721
server options SYSCAT.SERVEROPTIONS 723
server options values SYSCAT.USEROPTIONS 743
statements in packages SYSCAT.STATEMENTS 725
stored procedures SYSCAT.ROUTINES 711
system servers SYSCAT.SERVERS 724
table constraints SYSCAT.TABCONST 728
table dependencies SYSCAT.TABDEP 729
table privileges SYSCAT.TABAUTH 726
tables SYSCAT.TABLES 730
table spaces SYSCAT.TABLESPACES 735
table spaces use privileges SYSCAT.TBSPACEAUTH 737
transforms SYSCAT.TRANSFORMS 738
trigger dependencies SYSCAT.TRIGDEP 739
triggers SYSCAT.TRIGGERS 740
type mapping SYSCAT.TYPEMAPPINGS 741
user-defined functions SYSCAT.ROUTINES 711
views SYSCAT.TABLES 730
SYSCAT.VIEWS 744
wrapper options SYSCAT.WRAPOPTIONS 745
wrappers SYSCAT.WRAPPERS 746
‘Road map’ to catalog views
Appendix D. Catalog views 635
Description Catalog View Page1 The catalog views for functions, methods, and procedures from DB2 Version 7.1 andearlier still exist. These views, however, do not reflect any changes since DB2 Version7.1. The views are:
Functions: SYSCAT.FUNCTIONS, SYSCAT.FUNCDEP, SYSCAT.FUNCPARMSMethods: SYSCAT.FUNCTIONS, SYSCAT.FUNCDEP, SYSCAT.FUNCPARMSProcedures: SYSCAT.PROCEDURES, SYSCAT.PROCPARMS
‘Road map’ to updatable catalog views
Description Catalog View Page
columns SYSSTAT.COLUMNS 749
detailed column statistics SYSSTAT.COLDIST 747
indexes SYSSTAT.INDEXES 751
routines1 SYSSTAT.ROUTINES 755
tables SYSSTAT.TABLES 7571 The SYSSTAT.FUNCTIONS catalog view still exists for updating the statistics forfunctions and methods. This view, however, does not reflect any changes since DB2Version 7.1.
System catalog views
The database manager creates and maintains two sets of system catalog viewsthat are defined on top of the base system catalog tables.v SYSCAT views are read-only catalog views that are found in the SYSCAT
schema. SELECT privilege on these views is granted to PUBLIC by default.v SYSSTAT views are updatable catalog views that are found in the SYSSTAT
schema. The updatable views contain statistical information that is used bythe optimizer. The values in some columns in these views can be changedto test performance. (Before changing any statistics, it is recommended thatthe RUNSTATS command be invoked so that all the statistics reflect thecurrent state.) Applications should be written to the SYSSTAT views ratherthan the base catalog tables.
All the system catalog views are created at database creation time. The catalogviews cannot be explicitly created or dropped. The views are updated duringnormal operation in response to SQL data definition statements, environmentroutines, and certain utilities. Data in the system catalog views is available
‘Road map’ to catalog views
636 SQL Reference, Volume 1
through normal SQL query facilities. The system catalog views (with theexception of some updatable catalog views) cannot be modified using normalSQL data manipulation statements.
An object (table, column, function, or index) will appear in a user’s updatablecatalog view only if that user created the object, holds CONTROL privilege onthe object, or holds explicit DBADM authority.
The order of columns in the views may change from release to release. Toprevent this from affecting programming logic, specify the columns in a selectlist explicitly, and avoid using SELECT *. Columns have consistent namesbased on the types of objects that they describe.
Described Object Column Names
Table TABSCHEMA, TABNAME
Index INDSCHEMA, INDNAME
View VIEWSCHEMA, VIEWNAME
Constraint CONSTSCHEMA, CONSTNAME
Trigger TRIGSCHEMA, TRIGNAME
Package PKGSCHEMA, PKGNAME
Type TYPESCHEMA, TYPENAME, TYPEID
Function ROUTINESCHEMA, ROUTINENAME,ROUTINEID
Method ROUTINESCHEMA, ROUTINENAME,ROUTINEID
Procedure ROUTINESCHEMA, ROUTINENAME,ROUTINEID
Column COLNAME
Schema SCHEMANAME
Table Space TBSPACE
Database partition group NGNAME
Buffer pool BPNAME
Event Monitor EVMONNAME
Creation Timestamp CREATE_TIME
System catalog views
Appendix D. Catalog views 637
SYSIBM.SYSDUMMY1
Contains one row. This view is available for applications that requirecompatibility with DB2 Universal Database for z/OS and OS/390.
Table 53. SYSCAT.DUMMY1 Catalog View
Column Name Data Type Nullable Description
IBMREQD CHAR(1) Y
SYSIBM.SYSDUMMY1
638 SQL Reference, Volume 1
SYSCAT.ATTRIBUTES
Contains one row for each attribute (including inherited attributes whereapplicable) that is defined for a user-defined structured data type.
Table 54. SYSCAT.ATTRIBUTES Catalog View
Column Name Data Type Nullable Description
TYPESCHEMA VARCHAR(128) Qualified name of the structured data typethat includes the attribute.TYPENAME VARCHAR(128)
ATTR_NAME VARCHAR(128) Attribute name.
ATTR_TYPESCHEMA VARCHAR(128) Qualified name of the type of the attribute.
ATTR_TYPENAME VARCHAR(128)
TARGET_TYPESCHEMA VARCHAR(128) Yes Qualified name of the target type, if the typeof the attribute is REFERENCE. Null value ifthe type of the attribute is not REFERENCE.TARGET_TYPENAME VARCHAR(128) Yes
SOURCE_TYPESCHEMA VARCHAR(128) Qualified name of the data type in the datatype hierarchy where the attribute wasintroduced. For non-inherited attributes,these columns are the same asTYPESCHEMA and TYPENAME.
SOURCE_TYPENAME VARCHAR(128)
ORDINAL SMALLINT Position of the attribute in the definition ofthe structured data type, starting with zero.
LENGTH INTEGER Maximum length of data; 0 for distinct types.The LENGTH column indicates precision forDECIMAL fields.
SCALE SMALLINT Scale for DECIMAL fields; 0 if notDECIMAL.
CODEPAGE SMALLINT Code page of the attribute. Forcharacter-string attributes not defined withFOR BIT DATA, the value is the databasecode page. For graphic-string attributes, thevalue is the DBCS code page implied by the(composite) database code page. Otherwise,the value is 0.
LOGGED CHAR(1) Applies only to attributes whose type is LOBor distinct based on LOB; otherwise blank.
Y = Attribute is logged.
N = Attribute is not logged.
COMPACT CHAR(1) Applies only to attributes whose type is LOBor distinct based on LOB; otherwise blank).
Y = Attribute is compacted in storage.
N = Attribute is not compacted.
SYSCAT.ATTRIBUTES
Appendix D. Catalog views 639
Table 54. SYSCAT.ATTRIBUTES Catalog View (continued)
Column Name Data Type Nullable Description
DL_FEATURES CHAR(10) Applies to DATALINK type attributes only.Blank for REFERENCE type attributes;otherwise null. Encodes various DATALINKfeatures such as linktype, control mode,recovery, and unlink properties.
SYSCAT.ATTRIBUTES
640 SQL Reference, Volume 1
SYSCAT.BUFFERPOOLDBPARTITIONS
Contains a row for each database partition in the buffer pool for which thesize of the buffer pool on the database partition is different from the defaultsize in SYSCAT.BUFFERPOOLS column NPAGES.
Table 55. SYSCAT.BUFFERPOOLDBPARTITIONS Catalog View
Column Name Data Type Nullable Description
BUFFERPOOLID INTEGER Internal buffer pool identifier
DBPARTITIONNUM SMALLINT Database partition number
NPAGES INTEGER Number of pages in this buffer pool on thisdatabase partition
SYSCAT.BUFFERPOOLDBPARTITIONS
Appendix D. Catalog views 641
SYSCAT.BUFFERPOOLS
Contains a row for every buffer pool in every database partition group.
Table 56. SYSCAT.BUFFERPOOLS Catalog View
Column Name Data Type Nullable Description
BPNAME VARCHAR(128) Name of the buffer pool
BUFFERPOOLID INTEGER Internal buffer pool identifier
NGNAME VARCHAR(128) Yes Database partition group name (NULL if thebuffer pool exists on all database partitionsin the database)
NPAGES INTEGER Number of pages in the buffer pool
PAGESIZE INTEGER Page size for this buffer pool
ESTORE CHAR(1) N = This buffer pool does not useextended storage.
Y = This buffer pool uses extendedstorage.
SYSCAT.BUFFERPOOLS
642 SQL Reference, Volume 1
SYSCAT.CASTFUNCTIONS
Contains a row for each cast function. It does not include built-in castfunctions.
Table 57. SYSCAT.CASTFUNCTIONS Catalog View
Column Name Data Type Nullable Description
FROM_TYPESCHEMA VARCHAR(128) Qualified name of the data type of theparameter.FROM_TYPENAME VARCHAR(18)
TO_TYPESCHEMA VARCHAR(128) Qualified name of the data type of the resultafter casting.TO_TYPENAME VARCHAR(18)
FUNCSCHEMA VARCHAR(128) Qualified name of the function.
FUNCNAME VARCHAR(18)
SPECIFICNAME VARCHAR(18) The name of the function instance.
ASSIGN_FUNCTION CHAR(1) Y = Implicit assignment function
N = Not an assignment function
SYSCAT.CASTFUNCTIONS
Appendix D. Catalog views 643
SYSCAT.CHECKS
Contains one row for each CHECK constraint.
Table 58. SYSCAT.CHECKS Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the check constraint (unique withina table.)
DEFINER VARCHAR(128) Authorization ID under which the checkconstraint was defined.
TABSCHEMA VARCHAR(128) Qualified name of the table to which thisconstraint applies.TABNAME VARCHAR(128)
CREATE_TIME TIMESTAMP The time at which the constraint wasdefined. Used in resolving functions that areused in this constraint. No functions will bechosen that were created after the definitionof the constraint.
QUALIFIER VARCHAR(128) Value of the default schema at time of objectdefinition. Used to complete any unqualifiedreferences.
TYPE CHAR(1) Type of check constraint:
A = System generated check constraintfor GENERATED ALWAYS column
C = Check constraint
FUNC_PATH VARCHAR(254) The current SQL path that was used whenthe constraint was created.
TEXT CLOB(64K) The text of the CHECK clause.
SYSCAT.CHECKS
644 SQL Reference, Volume 1
SYSCAT.COLAUTH
Contains one or more rows for each user or group who is granted a columnlevel privilege, indicating the type of privilege and whether or not it isgrantable.
Table 59. SYSCAT.COLAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privileges or SYSIBM.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
TABSCHEMA VARCHAR(128) Qualified name of the table or view.
TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of the column to which this privilegeapplies.
COLNO SMALLINT Number of this column in the table or view.
PRIVTYPE CHAR(1) Indicates the type of privilege held on thetable or view:
U = Update privilege
R = Reference privilege
GRANTABLE CHAR(1) Indicates if the privilege is grantable.
G = Grantable
N = Not grantable
SYSCAT.COLAUTH
Appendix D. Catalog views 645
SYSCAT.COLCHECKS
Each row represents some column that is referenced by a CHECK constraint.
Table 60. SYSCAT.COLCHECKS Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the check constraint. (Uniquewithin a table. May be system generated.)
TABSCHEMA VARCHAR(128) Qualified name of table containingreferenced column.TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of column.
USAGE CHAR(1) R = Column is referenced in the checkconstraint.
S = Column is a source column in thesystem generated check constraint thatsupports a generated column.
T = Column is a target column in thesystem generated check constraint thatsupports a generated column.
SYSCAT.COLCHECKS
646 SQL Reference, Volume 1
SYSCAT.COLDIST
Contains detailed column statistics for use by the optimizer. Each rowdescribes the Nth-most-frequent value of some column.
Table 61. SYSCAT.COLDIST Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified name of the table to which thisentry applies.TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of the column to which this entryapplies.
TYPE CHAR(1) F = Frequency (most frequent value)
Q = Quantile value
SEQNO SMALLINT v If TYPE = F, then N in this columnidentifies the Nth most frequent value.
v If TYPE = Q, then N in this columnidentifies the Nth quantile value.
COLVALUE VARCHAR(254) Yes The data value, as a character literal or anull value.
VALCOUNT BIGINT v If TYPE = F, then VALCOUNT is thenumber of occurrences of COLVALUE inthe column.
v If TYPE = Q, then VALCOUNT is thenumber of rows whose value is less thanor equal to COLVALUE.
DISTCOUNT BIGINT Yes If TYPE = Q, this column records thenumber of distinct values that are less thanor equal to COLVALUE (null if unavailable).
SYSCAT.COLDIST
Appendix D. Catalog views 647
SYSCAT.COLGROUPDIST
Contains a row for every value of a column in a column group that makes upthe nth most frequent value of the column group or the nth quantile of thecolumn group.
Table 62. SYSCAT.COLGROUPDIST Catalog View
Column Name Data Type Nullable Description
COLGROUPID INTEGER Internal identifier of the column group.
TYPE CHAR(1) F = Frequency value
Q = Quantile value
ORDINAL SMALLINT Ordinal number of the column in the group.
SEQNO SMALLINT Sequence number n representing the nthTYPE value.
COLVALUE VARCHAR(254) Yes Data value as a character literal or a nullvalue.
SYSCAT.COLGROUPDIST
648 SQL Reference, Volume 1
SYSCAT.COLGROUPDISTCOUNTS
Contains a row for the distribution statistics that apply to the nth mostfrequent value of a column group, or the nth quantile of a column group.
Table 63. SYSCAT.COLGROUPDISTCOUNTS Catalog View
Column Name Data Type Nullable Description
COLGROUPID INTEGER Internal identifier of the column group.
TYPE CHAR(1) F = Frequency value
Q = Quantile value
SEQNO SMALLINT Sequence number n representing the nthTYPE value.
VALCOUNT BIGINT If TYPE = F, VALCOUNT is the number ofoccurrences of COLVALUE for the columngroup with this SEQNO. If TYPE = Q,VALCOUNT is the number of rows whosevalue is less than or equal to COLVALUEfor the column group with this SEQNO.
DISTCOUNT BIGINT Yes If TYPE = Q, this column records thenumber of distinct values that are less thanor equal to COLVALUE for the columngroup with this SEQNO (null ifunavailable).
SYSCAT.COLGROUPDISTCOUNTS
Appendix D. Catalog views 649
SYSCAT.COLGROUPS
Contains a row for every column group, and statistics that apply to the entirecolumn group.
Table 64. SYSCAT.COLGROUPS Catalog View
Column Name Data Type Nullable Description
COLGROUPSCHEMA VARCHAR(128) Qualified name of the column group.
COLGROUPNAME VARCHAR(128)
COLGROUPID INTEGER Internal identifier of the column group.
COLGROUPCARD BIGINT Cardinality of the column group.
NUMFREQ_VALUES SMALLINT Number of frequent values collected for thecolumn group.
NUMQUANTILES SMALLINT Number of quantiles collected for thecolumn group.
SYSCAT.COLGROUPS
650 SQL Reference, Volume 1
SYSCAT.COLOPTIONS
Each row contains column specific option values.
Table 65. SYSCAT.COLOPTIONS Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified nickname for the column.
TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Local column name.
OPTION VARCHAR(128) Name of the column option.
SETTING VARCHAR(255) Value for the column option.
SYSCAT.COLOPTIONS
Appendix D. Catalog views 651
SYSCAT.COLUMNS
Contains one row for each column (including inherited columns whereapplicable) that is defined for a table or view. All of the catalog views haveentries in the SYSCAT.COLUMNS table.
Table 66. SYSCAT.COLUMNS Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified name of the table or view thatcontains the column.TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Column name.
COLNO SMALLINT Numerical place of column in table or view,beginning at zero.
TYPESCHEMA VARCHAR(128) Contains the qualified name of the type, ifthe data type of the column is distinct.Otherwise TYPESCHEMA contains the valueSYSIBM and TYPENAME contains the datatype of the column (in long form, forexample, CHARACTER). If FLOAT orFLOAT(n) with n greater than 24 is specified,TYPENAME is renamed to DOUBLE. IfFLOAT(n) with n less than 25 is specified,TYPENAME is renamed to REAL. Also,NUMERIC is renamed to DECIMAL.
TYPENAME VARCHAR(18)
LENGTH INTEGER Maximum length of data. 0 for distinct types.The LENGTH column indicates precision forDECIMAL fields.
SCALE SMALLINT Scale for DECIMAL fields; 0 if notDECIMAL.
DEFAULT VARCHAR(254) Yes Default value for the column of a tableexpressed as a constant, special register, orcast-function appropriate for the data type ofthe column. May also be the keyword NULL.
Values may be converted from what wasspecified as a default value. For example,date and time constants are presented in ISOformat and cast-function names are qualifiedwith schema name and the identifiers aredelimited (see Note 3).
Null value if a DEFAULT clause was notspecified or the column is a view column.
SYSCAT.COLUMNS
652 SQL Reference, Volume 1
Table 66. SYSCAT.COLUMNS Catalog View (continued)
Column Name Data Type Nullable Description
NULLS CHAR(1) Y = Column is nullable.
N = Column is not nullable.
The value can be N for a view column that isderived from an expression or function.Nevertheless, such a column allows nullswhen the statement using the view isprocessed with warnings for arithmeticerrors.
See Note 1.
CODEPAGE SMALLINT Code page of the column. Forcharacter-string columns not defined with theFOR BIT DATA attribute, the value is thedatabase code page. For graphic-stringcolumns, the value is the DBCS code pageimplied by the (composite) database codepage. Otherwise, the value is 0.
LOGGED CHAR(1) Applies only to columns whose type is LOBor distinct based on LOB (blank otherwise).
Y=Column is logged.
N=Column is not logged.
COMPACT CHAR(1) Applies only to columns whose type is LOBor distinct based on LOB (blank otherwise).
Y = Column is compacted in storage.
N = Column is not compacted.
COLCARD BIGINT Number of distinct values in the column; −1if statistics are not gathered; −2 for inheritedcolumns and columns of H-tables.
HIGH2KEY VARCHAR(254) Yes Second highest value of the column. Thisfield is empty if statistics are not gatheredand for inherited columns and columns ofH-tables. See Note 2.
LOW2KEY VARCHAR(254) Yes Second lowest value of the column. This fieldis empty if statistics are not gathered and forinherited columns and columns of H-tables.See Note 2.
AVGCOLLEN INTEGER Average space required for the columnlength. −1 if a long field or LOB, or statisticshave not been collected; −2 for inheritedcolumns and columns of H-tables.
SYSCAT.COLUMNS
Appendix D. Catalog views 653
Table 66. SYSCAT.COLUMNS Catalog View (continued)
Column Name Data Type Nullable Description
KEYSEQ SMALLINT Yes The column’s numerical position within thetable’s primary key. This field is null forsubtables and hierarchy tables.
PARTKEYSEQ SMALLINT Yes The column’s numerical position within thetable’s partitioning key. This field is null or 0if the column is not part of the partitioningkey. This field is also null for subtables andhierarchy tables.
NQUANTILES SMALLINT Number of quantile values recorded inSYSCAT.COLDIST for this column; −1 if nostatistics; −2 for inherited columns andcolumns of H-tables.
NMOSTFREQ SMALLINT Number of most-frequent values recorded inSYSCAT.COLDIST for this column; −1 if nostatistics; −2 for inherited columns andcolumns of H-tables.
NUMNULLS BIGINT Contains the number of nulls in a column. −1if statistics are not gathered.
TARGET_TYPESCHEMA VARCHAR(128) Yes Qualified name of the target type, if the typeof the column is REFERENCE. Null value ifthe type of the column is not REFERENCE.TARGET_TYPENAME VARCHAR(18) Yes
SCOPE_TABSCHEMA VARCHAR(128) Yes Qualified name of the scope (target table), ifthe type of the column is REFERENCE. Nullvalue if the type of the column is notREFERENCE or the scope is not defined.
SCOPE_TABNAME VARCHAR(128) Yes
SOURCE_TABSCHEMA VARCHAR(128) Qualified name of the table or view in therespective hierarchy where the column wasintroduced. For non-inherited columns, thevalues are the same as TBCREATOR andTBNAME. Null for columns of non-typedtables and views
SOURCE_TABNAME VARCHAR(128)
SYSCAT.COLUMNS
654 SQL Reference, Volume 1
Table 66. SYSCAT.COLUMNS Catalog View (continued)
Column Name Data Type Nullable Description
DL_FEATURES CHAR(10) Yes Applies to DATALINK type columns only.Null otherwise. Each character position isdefined as follows:
1. Link type (U for URL)
2. Link control (F for file, N for no)
3. Integrity (A for all, N for none)
4. Read permission (F for file system, D fordatabase)
5. Write permission (F for file system, B forblocked, A for admin requiring token forupdate, N for admin not requiring tokenfor update)
6. Recovery (Y for yes, N for no)
7. On unlink (R for restore, D for delete, Nfor not applicable)
Characters 8 through 10 are reserved forfuture use.
SPECIAL_PROPS CHAR(8) Yes Applies to REFERENCE type columns only.Null otherwise. Each character position isdefined as follows:
Object identifier (OID) column (Y for yes,N for no)
User generated or system generated (Ufor user, S for system)
HIDDEN CHAR(1) Type of hidden column
S = System managed hidden column
Blank if column is not hidden
INLINE_LENGTH INTEGER Length of structured type column that can bekept with base table row. 0 if no valueexplicitly set by ALTER/CREATE TABLEstatement.
IDENTITY CHAR(1) ’Y’ indicates that the column is an identitycolumn; ’N’ indicates that the column is notan identity column.
GENERATED CHAR(1) Type of generated column
A = Column value is always generated
D = Column value is generated by default
Blank if column is not generated
SYSCAT.COLUMNS
Appendix D. Catalog views 655
Table 66. SYSCAT.COLUMNS Catalog View (continued)
Column Name Data Type Nullable Description
COMPRESS CHAR(1) S = Compress system default values
O = Compress off
TEXT CLOB(64K) Contains the text of the generated column,starting with the keyword AS.
REMARKS VARCHAR(254) Yes User-supplied comment.
AVGDISTINCTPERPAGE DOUBLE Yes For future use.
PAGEVARIANCERATIO DOUBLE Yes For future use.
SUB_COUNT SMALLINT Average number of sub-elements. Onlyapplicable for character columns. Forexample, consider the following string:’database simulation analytical businessintelligence’. In this example, SUB_COUNT =5, because there are 5 sub-elements in thestring.
SUB_DELIM_LENGTH SMALLINT Average length of each delimiter separatingeach sub-element. Only applicable forcharacter columns. For example, consider thefollowing string: ’database simulationanalytical business intelligence’. In thisexample, SUB_DELIM_LENGTH = 1, becauseeach delimiter is a single blank.
Notes:
1. Starting with Version 2, value D (indicating not null with a default) is no longer used. Instead, use ofWITH DEFAULT is indicated by a non-null value in the DEFAULT column.
2. Starting with Version 2, representation of numeric data has been changed to character literals. Thesize has been enlarged from 16 to 33 bytes.
3. For Version 2.1.0, cast-function names were not delimited and may still appear this way in theDEFAULT column. Also, some view columns included default values which will still appear in theDEFAULT column.
SYSCAT.COLUMNS
656 SQL Reference, Volume 1
SYSCAT.COLUSE
Contains a row for every column that participates in the DIMENSIONS clauseof the CREATE TABLE statement.
Table 67. SYSCAT.COLUSE Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified name of the table containing thecolumnTABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of the column
DIMENSION SMALLINT Dimension number, based on the order ofdimensions specified in the DIMENSIONSclause (initial position = 0). For a compositedimension, this value will be the same foreach component of the dimension.
COLSEQ SMALLINT Numeric position of the column in thedimension to which it belongs (initialposition = 0). The value is 0 for the singlecolumn in a noncomposite dimension.
TYPE CHAR(1) Type of dimension.
C = clustering/multi-dimensionalclustering (MDC)
SYSCAT.COLUSE
Appendix D. Catalog views 657
SYSCAT.CONSTDEP
Contains a row for every dependency of a constraint on some other object.
Table 68. SYSCAT.CONSTDEP Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the constraint.
TABSCHEMA VARCHAR(128) Qualified name of the table to which theconstraint applies.TABNAME VARCHAR(128)
BTYPE CHAR(1) Type of object that the constraint dependson. Possible values:
F = Function instance
I = Index instance
R = Structured type
BSCHEMA VARCHAR(128) Qualified name of object that the constraintdepends on.BNAME VARCHAR(18)
SYSCAT.CONSTDEP
658 SQL Reference, Volume 1
SYSCAT.DATATYPES
Contains a row for every data type, including built-in and user-defined types.
Table 69. SYSCAT.DATATYPES Catalog View
Column Name Data Type Nullable Description
TYPESCHEMA VARCHAR(128) Qualified name of the data type (forbuilt-in types, TYPESCHEMA isSYSIBM).TYPENAME VARCHAR(18)
DEFINER VARCHAR(128) Authorization ID under which type wascreated.
SOURCESCHEMA VARCHAR(128) Yes Qualified name of the source type fordistinct types. Qualified name of thebuiltin type used as the reference typethat is used as the representation forreferences to structured types. Null forother types.
SOURCENAME VARCHAR(18) Yes
METATYPE CHAR(1) S = System predefined type
T = Distinct type
R = Structured type
TYPEID SMALLINT The system generated internal identifierof the data type.
SOURCETYPEID SMALLINT Yes Internal type ID of source type (null forbuilt-in types). For user-definedstructured types, this is the internaltype ID of the reference representationtype.
LENGTH INTEGER Maximum length of the type. 0 forsystem predefined parameterized types(for example, DECIMAL andVARCHAR). For user-definedstructured types, this indicates thelength of the reference representationtype.
SCALE SMALLINT Scale for distinct types or referencerepresentation types based on thesystem predefined DECIMAL type. 0for all other types (including DECIMALitself). For user-defined structuredtypes, this indicates the length of thereference representation type.
CODEPAGE SMALLINT Code page for character and graphicdistinct types or referencerepresentation types; 0 otherwise.
SYSCAT.DATATYPES
Appendix D. Catalog views 659
Table 69. SYSCAT.DATATYPES Catalog View (continued)
Column Name Data Type Nullable Description
CREATE_TIME TIMESTAMP Creation time of the data type.
ATTRCOUNT SMALLINT Number of attributes in data type.
INSTANTIABLE CHAR(1) Y = Type can be instantiated.
N = Type can not be instantiated.
WITH_FUNC_ACCESS CHAR(1) Y = All the methods for this typecan be invoked using functionnotation.
N = Methods for this type can notbe invoked using function notation.
FINAL CHAR(1) Y = User-defined type can not havesubtypes.
N = User-defined type can havesubtypes.
INLINE_LENGTH INTEGER Length of structured type that can bekept with base table row. 0 if no valueexplicitly set by CREATE TYPEstatement.
NATURAL_INLINE_LENGTH INTEGER System-calculated inline length of thestructured type.
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
SYSCAT.DATATYPES
660 SQL Reference, Volume 1
SYSCAT.DBAUTH
Records the database authorities held by users.
Table 70. SYSCAT.DBAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) SYSIBM or authorization ID of the userwho granted the privileges.
GRANTEE VARCHAR(128) Authorization ID of the user or groupwho holds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
DBADMAUTH CHAR(1) Whether grantee holds DBADMauthority over the database:
Y = Authority is held.
N = Authority is not held.
CREATETABAUTH CHAR(1) Whether grantee can create tables in thedatabase (CREATETAB):
Y = Privilege is held.
N = Privilege is not held.
BINDADDAUTH CHAR(1) Whether grantee can create newpackages in the database (BINDADD):
Y = Privilege is held.
N = Privilege is not held.
CONNECTAUTH CHAR(1) Whether grantee can connect to thedatabase (CONNECT):
Y = Privilege is held.
N = Privilege is not held.
NOFENCEAUTH CHAR(1) Whether grantee holds privilege tocreate non-fenced functions.
Y = Privilege is held.
N = Privilege is not held.
IMPLSCHEMAAUTH CHAR(1) Whether grantee can implicitly createschemas in the database(IMPLICIT_SCHEMA):
Y = Privilege is held.
N = Privilege is not held.
SYSCAT.DBAUTH
Appendix D. Catalog views 661
Table 70. SYSCAT.DBAUTH Catalog View (continued)
Column Name Data Type Nullable Description
LOADAUTH CHAR(1) Whether grantee holds LOAD authorityover the database:
Y = Authority is held.
N = Authority is not held.
EXTERNALROUTINEAUTH CHAR(1) Whether grantee can create externalroutines(CREATE_EXTERNAL_ROUTINE):
Y = Authority is held.
N = Authority is not held.
QUIESCECONNECTAUTH CHAR(1) Whether grantee can connect to adatabase (QUIESCE_CONNECT):
Y = Authority is held.
N = Authority is not held.
SYSCAT.DBAUTH
662 SQL Reference, Volume 1
SYSCAT.DBPARTITIONGROUPDEF
Contains a row for each partition that is contained in a database partitiongroup.
Table 71. SYSCAT.DBPARTITIONGROUPDEF Catalog View
Column Name Data Type Nullable Description
DBPGNAME VARCHAR(18) The name of the database partition groupthat contains the database partition.
DBPARTITIONNUM SMALLINT The partition number of a partitioncontained in the database partition group. Avalid partition number is between 0 and 999inclusive.
IN_USE CHAR(1) Status of the database partition.
A = The newly added partition is not inthe partitioning map but the containersfor the table spaces in the databasepartition group are created. The partitionis added to the partitioning map when aredistribute database partition groupoperation is successfully completed.
D = The partition will be dropped whena redistribute database partition groupoperation is completed.
T = The newly added partition is not inthe partitioning map and it was addedusing the WITHOUT TABLESPACESclause. Containers must be specificallyadded to the table spaces for thedatabase partition group.
Y = The partition is in the partitioningmap.
SYSCAT.DBPARTITIONGROUPDEF
Appendix D. Catalog views 663
SYSCAT.DBPARTITIONGROUPS
Contains a row for each database partition group.
Table 72. SYSCAT.DBPARTITIONGROUPS Catalog View
Column Name Data Type Nullable Description
DBPGNAME VARCHAR(18) Name of the database partition group.
DEFINER VARCHAR(128) Authorization ID of the database partitiongroup definer.
PMAP_ID SMALLINT Identifier of the partitioning map inSYSCAT.PARTITIONMAPS.
REDISTRIBUTE_PMAP_ID SMALLINT Identifier of the partitioning map currentlybeing used for redistribution. Value is -1 ifredistribution is currently not in progress.
CREATE_TIME TIMESTAMP Creation time of database partition group.
REMARKS VARCHAR(254) Yes User-provided comment.
SYSCAT.DBPARTITIONGROUPS
664 SQL Reference, Volume 1
SYSCAT.EVENTMONITORS
Contains a row for every event monitor that has been defined.
Table 73. SYSCAT.EVENTMONITORS Catalog View
Column Name Data Type Nullable Description
EVMONNAME VARCHAR(18) Name of event monitor.
DEFINER VARCHAR(128) Authorization ID of definer of eventmonitor.
TARGET_TYPE CHAR(1) The type of target to which event data iswritten. Values:
F = File
P = Pipe
T = Table
TARGET VARCHAR(246) Name of the target to which event data iswritten. Absolute pathname of file, orabsolute name of pipe.
MAXFILES INTEGER Yes Maximum number of event files that thisevent monitor permits in an event path.Null if there is no maximum, or if thetarget-type is not FILE.
MAXFILESIZE INTEGER Yes Maximum size (in 4K pages) that each eventfile can reach before the event monitorcreates a new file. Null if there is nomaximum, or if the target-type is not FILE.
BUFFERSIZE INTEGER Yes Size of buffers (in 4K pages) used by eventmonitors with file targets; otherwise null.
IO_MODE CHAR(1) Yes Mode of file I/O.
B = Blocked
N = Not blocked
Null if target-type is not FILE.
WRITE_MODE CHAR(1) Yes Indicates how this monitor handles existingevent data when the monitor is activated.Values:
A = Append
R = Replace
Null if target-type is not FILE.
AUTOSTART CHAR(1) The event monitor will be activatedautomatically when the database starts.
Y = Yes
N = No
SYSCAT.EVENTMONITORS
Appendix D. Catalog views 665
Table 73. SYSCAT.EVENTMONITORS Catalog View (continued)
Column Name Data Type Nullable Description
DBPARTITIONNUM SMALLINT The number of the database partition onwhich the event monitor runs and logsevents.
MONSCOPE CHAR(1) Monitoring scope:
L = Local
G = Global
T = Per node where table space exists
A blank character, valid only for WRITETO TABLE event monitors.
EVMON_ACTIVATES INTEGER The number of times this event monitor hasbeen activated.
REMARKS VARCHAR(254) Yes Reserved for future use.
SYSCAT.EVENTMONITORS
666 SQL Reference, Volume 1
SYSCAT.EVENTS
Contains a row for every event that is being monitored. An event monitor, ingeneral, monitors multiple events.
Table 74. SYSCAT.EVENTS Catalog View
Column Name Data Type Nullable Description
EVMONNAME VARCHAR(18) Name of event monitor that is monitoringthis event.
TYPE VARCHAR(18) Type of event being monitored. Possiblevalues:
DATABASE
CONNECTIONS
TABLES
STATEMENTS
TRANSACTIONS
DEADLOCKS
DETAILDEADLOCKS
TABLESPACES
FILTER CLOB(32K) Yes The full text of the WHERE-clause thatapplies to this event.
SYSCAT.EVENTS
Appendix D. Catalog views 667
SYSCAT.EVENTTABLES
Contains a row for every target table of an event monitor that writes to SQLtables.
Table 75. SYSCAT.EVENTTABLES Catalog View
Column Name Data Type Nullable Description
EVMONNAME VARCHAR(128) Name of event monitor.
LOGICAL_GROUP VARCHAR(18) Name of the logical data group. This can beone of:
BUFFERPOOL
CONN
CONNHEADER
CONTROL
DB
DEADLOCK
DLCONN
DLLOCK
STMT
SUBSECTION
TABLE
TABLESPACE
XACT
TABSCHEMA VARCHAR(128) Qualified name of the target table.
TABNAME VARCHAR(128)
PCTDEACTIVATE SMALLINT A percent value that specifies how full aDMS table space must be before an eventmonitor automatically deactivates. Set to 100for SMS table spaces.
SYSCAT.EVENTTABLES
668 SQL Reference, Volume 1
SYSCAT.FULLHIERARCHIES
Each row represents the relationship between a subtable and a supertable, asubtype and a supertype, or a subview and a superview. All hierarchicalrelationships, including immediate ones, are included in this view
Table 76. SYSCAT.FULLHIERARCHIES Catalog View
Column Name Data Type Nullable Description
METATYPE CHAR(1) Encodes the type of relationship:
R = Between structured types
U = Between typed tables
W = Between typed views
SUB_SCHEMA VARCHAR(128) Qualified name of subtype, subtable orsubview.SUB_NAME VARCHAR(128)
SUPER_SCHEMA VARCHAR(128) Qualified name of supertype, supertable orsuperview.SUPER_NAME VARCHAR(128)
ROOT_SCHEMA VARCHAR(128) Qualified name of the table, view or typethat is at the root of the hierarchy.ROOT_NAME VARCHAR(128)
SYSCAT.FULLHIERARCHIES
Appendix D. Catalog views 669
SYSCAT.FUNCMAPOPTIONS
Each row contains function mapping option values.
Table 77. SYSCAT.FUNCMAPOPTIONS Catalog View
Column Name Data Type Nullable Description
FUNCTION_MAPPING VARCHAR(18) Function mapping name.
OPTION VARCHAR(128) Name of the function mapping option.
SETTING VARCHAR(255) Value of the function mapping option.
SYSCAT.FUNCMAPOPTIONS
670 SQL Reference, Volume 1
SYSCAT.FUNCMAPPARMOPTIONS
Each row contains function mapping parameter option values.
Table 78. SYSCAT.FUNCMAPPARMOPTIONS Catalog View
Column Name Data Type Nullable Description
FUNCTION_MAPPING VARCHAR(18) Name of function mapping.
ORDINAL SMALLINT Position of parameter
LOCATION CHAR(1) L = Local
R = Remote
OPTION VARCHAR(128) Name of the function mappingparameter option.
SETTING VARCHAR(255) Value of the function mappingparameter option.
SYSCAT.FUNCMAPPARMOPTIONS
Appendix D. Catalog views 671
SYSCAT.FUNCMAPPINGS
Each row contains function mappings.
Table 79. SYSCAT.FUNCMAPPINGS Catalog View
Column Name Data Type Nullable Description
FUNCTION_MAPPING
VARCHAR(18) Name of function mapping (may be systemgenerated).
FUNCSCHEMA VARCHAR(128) Yes Function schema. Null if system built-infunction.
FUNCNAME VARCHAR(1024) Yes Name of the local function (built-in oruser-defined).
FUNCID INTEGER Yes Internally assigned identifier.
SPECIFICNAME VARCHAR(18) Yes Name of the local function instance.
DEFINER VARCHAR(128) Authorization ID under which this mappingwas created.
WRAPNAME VARCHAR(128) Yes Wrapper name to which the mapping isapplied.
SERVERNAME VARCHAR(128) Yes Name of the data source.
SERVERTYPE VARCHAR(30) Yes Type of data source to which mapping isapplied.
SERVERVERSION VARCHAR(18) Yes Version of the server type to which mappingis applied.
CREATE_TIME TIMESTAMP Yes Time at which the mapping is created.
REMARKS VARCHAR(254) Yes User supplied comment, or null.
SYSCAT.FUNCMAPPINGS
672 SQL Reference, Volume 1
SYSCAT.HIERARCHIES
Each row represents the relationship between a subtable and its immediatesupertable, a subtype and its immediate supertype, or a subview and itsimmediate superview. Only immediate hierarchical relationships are includedin this view.
Table 80. SYSCAT.HIERARCHIES Catalog View
Column Name Data Type Nullable Description
METATYPE CHAR(1) Encodes the type of relationship:
R = Between structured types
U = Between typed tables
W = Between typed views
SUB_SCHEMA VARCHAR(128) Qualified name of subtype, subtable, orsubview.SUB_NAME VARCHAR(128)
SUPER_SCHEMA VARCHAR(128) Qualified name of supertype, supertable, orsuperview.SUPER_NAME VARCHAR(128)
ROOT_SCHEMA VARCHAR(128) Qualified name of the table, view or typethat is at the root of the hierarchy.ROOT_NAME VARCHAR(128)
SYSCAT.HIERARCHIES
Appendix D. Catalog views 673
SYSCAT.INDEXAUTH
Contains a row for every privilege held on an index.
Table 81. SYSCAT.INDEXAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privileges.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
INDSCHEMA VARCHAR(128) Qualified name of the index.
INDNAME VARCHAR(18)
CONTROLAUTH CHAR(1) Whether grantee holds CONTROL privilegeover the index:
Y = Privilege is held.
N = Privilege is not held.
SYSCAT.INDEXAUTH
674 SQL Reference, Volume 1
SYSCAT.INDEXCOLUSE
Lists all columns that participate in an index.
Table 82. SYSCAT.INDEXCOLUSE Catalog View
Column Name Data Type Nullable Description
INDSCHEMA VARCHAR(128) Qualified name of the index.
INDNAME VARCHAR(18)
COLNAME VARCHAR(128) Name of the column.
COLSEQ SMALLINT Numeric position of the column in the index(initial position = 1).
COLORDER CHAR(1) Order of the values in this column in theindex. Values:
A = Ascending
D = Descending
I = INCLUDE column(ordering ignored)
SYSCAT.INDEXCOLUSE
Appendix D. Catalog views 675
SYSCAT.INDEXDEP
Each row represents a dependency of an index on some other object.
Table 83. SYSCAT.INDEXDEP Catalog View
Column Name Data Type Nullable Description
INDSCHEMA VARCHAR(128) Qualified name of the index that hasdependencies on another object.INDNAME VARCHAR(18)
BTYPE CHAR(1) Type of object on which the index depends.
A = Alias
F = Function instance
O = Privilege dependency on all subtables orsubviews in a table or view hierarchy
R = Structured type
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
X = Index extension
BSCHEMA VARCHAR(128) Qualified name of the object on which the indexhas a dependency.BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE = O, S, T, U, V, or W, encodes theprivileges on the table or view that are requiredby the dependent index; otherwise null.
SYSCAT.INDEXDEP
676 SQL Reference, Volume 1
SYSCAT.INDEXES
Contains one row for each index (including inherited indexes, whereapplicable) that is defined for a table.
Table 84. SYSCAT.INDEXES Catalog View
Column Name Data Type Nullable Description
INDSCHEMA VARCHAR(128) Name of the index.
INDNAME VARCHAR(18)
DEFINER VARCHAR(128) User who created the index.
TABSCHEMA VARCHAR(128) Qualified name of the table ornickname on which the index isdefined.TABNAME VARCHAR(128)
COLNAMES VARCHAR(640) List of column names, each preceded by+ or − to indicate ascending ordescending order respectively. Warning:This column will be removed in thefuture. Use SYSCAT.INDEXCOLUSE forthis information.
UNIQUERULE CHAR(1) Unique rule:
D = Duplicates allowed
P = Primary index
U = Unique entries only allowed
MADE_UNIQUE CHAR(1) Y = Index was originally non-uniquebut was converted to a unique indexto support a unique or primary keyconstraint. If the constraint isdropped, the index will revert tonon-unique.
N = Index remains as it was created.
COLCOUNT SMALLINT Number of columns in the key, plus thenumber of include columns, if any.
UNIQUE_COLCOUNT SMALLINT The number of columns required for aunique key. Always <=COLCOUNT. <COLCOUNT only if there are includecolumns. −1 if the index has no uniquekey (permits duplicates).
INDEXTYPE CHAR(4) Type of index.
CLUS = Clustering
REG = Regular
DIM = dimension block index
BLOK = block index
SYSCAT.INDEXES
Appendix D. Catalog views 677
Table 84. SYSCAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description
ENTRYTYPE CHAR(1) H = An index on a hierarchy table(H-table)
L = Logical index on a typed table
blank if an index on an untypedtable
PCTFREE SMALLINT Percentage of each index leaf page to bereserved during initial building of theindex. This space is available for futureinserts after the index is built.
IID SMALLINT Internal index ID.
NLEAF INTEGER Number of leaf pages; −1 if statistics arenot gathered.
NLEVELS SMALLINT Number of index levels; −1 if statisticsare not gathered.
FIRSTKEYCARD BIGINT Number of distinct first key values; −1if statistics are not gathered.
FIRST2KEYCARD BIGINT Number of distinct keys using the firsttwo columns of the index; −1 if nostatistics, or if not applicable.
FIRST3KEYCARD BIGINT Number of distinct keys using the firstthree columns of the index; −1 if nostatistics, or if not applicable.
FIRST4KEYCARD BIGINT Number of distinct keys using the firstfour columns of the index; −1 if nostatistics, or if not applicable.
FULLKEYCARD BIGINT Number of distinct full key values; −1 ifstatistics are not gathered.
CLUSTERRATIO SMALLINT Degree of data clustering with theindex; −1 if statistics are not gathered,or if detailed index statistics aregathered (in which case,CLUSTERFACTOR will be usedinstead).
CLUSTERFACTOR DOUBLE Finer measurement of degree ofclustering, or −1 if detailed indexstatistics have not been gathered, or ifthe index is defined on a nickname.
SYSCAT.INDEXES
678 SQL Reference, Volume 1
Table 84. SYSCAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description
SEQUENTIAL_PAGES INTEGER Number of leaf pages located on disk inindex key order with few or no largegaps between them; −1 if no statisticsare available.
DENSITY INTEGER Ratio of SEQUENTIAL_PAGES tonumber of pages in the range of pagesoccupied by the index, expressed as apercent (integer between 0 and 100; −1if no statistics are available.)
USER_DEFINED SMALLINT 1 if this index was defined by a userand has not been dropped; otherwise 0.
SYSTEM_REQUIRED SMALLINT Valid values are:
1 if one or the other of the followingconditions is met:
– This index is required for aprimary or unique key constraint,or this index is a dimension blockindex or composite block indexfor a multi-dimensional clustering(MDC) table.
– This is an index on the (OID)column of a typed table.
2 if both of the following conditionsare met:
– This index is required for aprimary or unique key constraint,or this index is a dimension blockindex or composite block indexfor an MDC table.
– This is an index on the (OID)column of a typed table.
0 otherwise.
CREATE_TIME TIMESTAMP Time when the index was created.
STATS_TIME TIMESTAMP Yes Last time when any change was madeto recorded statistics for this index. Nullif no statistics available.
SYSCAT.INDEXES
Appendix D. Catalog views 679
Table 84. SYSCAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description
PAGE_FETCH_PAIRS VARCHAR(254) A list of pairs of integers, represented incharacter form. Each pair represents thenumber of pages in a hypotheticalbuffer, and the number of page fetchesrequired to scan the table with thisindex using that hypothetical buffer.(Zero-length string if no data available.)
MINPCTUSED SMALLINT If not zero, online indexdefragmentation is enabled, and thevalue is the threshold of minimum usedspace before merging pages.
REVERSE_SCANS CHAR(1) Y = Index supports reverse scans
N = Index does not support reversescans
INTERNAL_FORMAT SMALLINT Valid values are:
1 if the index does not havebackward pointers
>= 2 if the index has backwardpointers
6 if the index is a composite blockindex
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
IESCHEMA VARCHAR(128) Yes Qualified name of index extension. Nullfor ordinary indexes.
IENAME VARCHAR(18) Yes
IEARGUMENTS CLOB(32K) Yes External information of the parameterspecified when the index is created.Null for ordinary indexes.
INDEX_OBJECTID INTEGER Index object identifier for the table.
NUMRIDS BIGINT Total number of row identifiers (RIDs)in the index.
NUMRIDS_DELETED BIGINT Total number of row identifiers in theindex that are marked as deleted,excluding those row identifiers on leafpages on which all row identifiers areas marked deleted.
NUM_EMPTY_LEAFS BIGINT Total number of index leaf pages thathave all of their row identifiers markedas deleted.
SYSCAT.INDEXES
680 SQL Reference, Volume 1
Table 84. SYSCAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description
AVERAGE_RANDOM_FETCH_PAGES
DOUBLE Average number of random table pagesbetween sequential page accesses whenfetching using the index; −1 if it is notknown.
AVERAGE_RANDOM_PAGES
DOUBLE Average number of random indexpages between sequential index pageaccesses; −1 if it is not known.
AVERAGE_SEQUENCE_GAP
DOUBLE Gap between index page sequences.Detected through a scan of index leafpages, each gap represents the averagenumber of index pages that must berandomly fetched between sequences ofindex pages; −1 if it is not known.
AVERAGE_SEQUENCE_FETCH_GAP
DOUBLE Gap between table page sequenceswhen fetching using the index. Detectedthrough a scan of index leaf pages, eachgap represents the average number oftable pages that must be randomlyfetched between sequences of tablepages; −1 if it is not known.
AVERAGE_SEQUENCE_PAGES
DOUBLE Average number of index pagesaccessible in sequence (that is, thenumber of index pages that theprefetchers would detect as being insequence); −1 if it is not known.
AVERAGE_SEQUENCE_FETCH_PAGES
DOUBLE Average number of table pagesaccessible in sequence (that is, thenumber of table pages that theprefetchers would detect as being insequence) when fetching using theindex; −1 if it is not known.
TBSPACEID INTEGER Internal identifier for the index tablespace.
Related reference:
v “SYSCAT.INDEXCOLUSE” on page 675
SYSCAT.INDEXES
Appendix D. Catalog views 681
SYSCAT.INDEXEXPLOITRULES
Each row represents an index exploitation.
Table 85. SYSCAT.INDEXEXPLOITRULES Catalog View
Column Name Data Type Nullable Description
FUNCID INTEGER Function ID.
SPECID SMALLINT Number of the predicate specification in theCREATE FUNCTION statement.
IESCHEMA VARCHAR(128) Qualified name of index extension.
IENAME VARCHAR(18)
RULEID SMALLINT Unique exploitation rule ID.
SEARCHMETHODID SMALLINT The search method ID in the specific indexextension.
SEARCHKEY VARCHAR(320) Key used to exploit index.
SEARCHARGUMENT VARCHAR(1800) Search arguments used in the indexexploitation.
SYSCAT.INDEXEXPLOITRULES
682 SQL Reference, Volume 1
SYSCAT.INDEXEXTENSIONDEP
Contains a row for each dependency that index extensions have on variousdatabase objects.
Table 86. SYSCAT.INDEXEXTENSIONDEP Catalog View
Column Name Data Type Nullable Description
IESCHEMA VARCHAR(128) Qualified name of the index extension thathas dependencies on another object.IENAME VARCHAR(18)
BTYPE CHAR(1) Type of object on which the index extensionis dependent:
A = Alias
F = Function instance or method instance
J = Server definition
O = "Outer" dependency on hierarchicSELECT privilege
R = Structured type
S = Materialized query table
T = Table (not typed)
U = Typed table
V = View (not typed)
W = Typed view
X = Index extension
BSCHEMA VARCHAR(128) Qualified name of the object on which theindex extension depends. (If BTYPE='F', thisis the specific name of a function.)BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE='O', 'T', 'U', 'V', or 'W', encodes theprivileges on the table (or view) that arerequired by a dependent trigger; otherwisenull.
SYSCAT.INDEXEXTENSIONDEP
Appendix D. Catalog views 683
SYSCAT.INDEXEXTENSIONMETHODS
Each row represents a search method. One index extension may includemultiple search methods.
Table 87. SYSCAT.INDEXEXTENSIONMETHODS Catalog View
Column Name Data Type Nullable Description
METHODNAME VARCHAR(18) Name of search method.
METHODID SMALLINT Number of the method in the indexextension.
IESCHEMA VARCHAR(128) Qualified name of index extension.
IENAME VARCHAR(18)
RANGEFUNCSCHEMA VARCHAR(128) Qualified name of range-through function.
RANGEFUNCNAME VARCHAR(18)
RANGESPECIFICNAME VARCHAR(18) Range-through function specific name.
FILTERFUNCSCHEMA VARCHAR(128) Qualified name of filter function.
FILTERFUNCNAME VARCHAR(18)
FILTERSPECIFICNAME VARCHAR(18) Function specific name of filter function.
REMARKS VARCHAR(254) Yes User-supplied or null.
SYSCAT.INDEXEXTENSIONMETHODS
684 SQL Reference, Volume 1
SYSCAT.INDEXEXTENSIONPARMS
Each row represents an index extension instance parameter or source keydefinition.
Table 88. SYSCAT.INDEXEXTENSIONPARMS Catalog View
Column Name Data Type Nullable Description
IESCHEMA VARCHAR(128) Qualified name of index extension.
IENAME VARCHAR(18)
ORDINAL SMALLINT Sequence number of parameter or source key.
PARMNAME VARCHAR(18) Name of parameter or source key.
TYPESCHEMA VARCHAR(128) Qualified name of the instance parameter orsource key data type.TYPENAME VARCHAR(18)
LENGTH INTEGER Length of the instance parameter or sourcekey data type.
SCALE SMALLINT Scale of the instance parameter or source keydata type. Zero (0) when not applicable.
PARMTYPE CHAR(1) Type represented by the row:
P = index extension parameter
K = key column
CODEPAGE SMALLINT Code page of the index extension parameter.Zero if not a string type.
SYSCAT.INDEXEXTENSIONPARMS
Appendix D. Catalog views 685
SYSCAT.INDEXEXTENSIONS
Contains a row for each index extension.
Table 89. SYSCAT.INDEXEXTENSIONS Catalog View
Column Name Data Type Nullable Description
IESCHEMA VARCHAR(128) Qualified name of index extension.
IENAME VARCHAR(18)
DEFINER VARCHAR(128) Authorization ID under which the indexextension was defined.
CREATE_TIME TIMESTAMP Time at which the index extension wasdefined.
KEYGENFUNCSCHEMA VARCHAR(128) Qualified name of key generation function.
KEYGENFUNCNAME VARCHAR(18)
KEYGENSPECIFICNAME VARCHAR(18) Key generation function specific name.
TEXT CLOB(64K) The full text of the CREATE INDEXEXTENSION statement.
REMARKS VARCHAR(254) User-supplied comment, or null.
SYSCAT.INDEXEXTENSIONS
686 SQL Reference, Volume 1
SYSCAT.INDEXOPTIONS
Each row contains index specific option values.
Table 90. SYSCAT.INDEXOPTIONS Catalog View
Column Name Data Type Nullable Description
INDSCHEMA VARCHAR(128) Schema name of the index.
INDNAME VARCHAR(18) Local name of the index.
OPTION VARCHAR(128) Name of the index option.
SETTING VARCHAR(255) Value.
SYSCAT.INDEXOPTIONS
Appendix D. Catalog views 687
SYSCAT.KEYCOLUSE
Lists all columns that participate in a key (including inherited primary orunique keys where applicable) defined by a unique, primary key, or foreignkey constraint.
Table 91. SYSCAT.KEYCOLUSE Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the constraint (unique within atable).
TABSCHEMA VARCHAR(128) Qualified name of the table containing thecolumn.TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of the column.
COLSEQ SMALLINT Numeric position of the column in the key(initial position=1).
SYSCAT.KEYCOLUSE
688 SQL Reference, Volume 1
SYSCAT.NAMEMAPPINGS
Each row represents the mapping between logical objects and thecorresponding implementation objects that implement the logical objects.
Table 92. SYSCAT.NAMEMAPPINGS Catalog View
Column Name Data Type Nullable Description
TYPE CHAR(1) C = Column
I = Index
U = Typed table
LOGICAL_SCHEMA VARCHAR(128) Qualified name of the logical object.
LOGICAL_NAME VARCHAR(128)
LOGICAL_COLNAME VARCHAR(128) Yes If TYPE = C, then the name of the logicalcolumn. Otherwise null.
IMPL_SCHEMA VARCHAR(128) Qualified name of the implementation objectthat implements the logical object.IMPL_NAME VARCHAR(128)
IMPL_COLNAME VARCHAR(128) Yes If TYPE = C, then the name of theimplementation column. Otherwise null.
SYSCAT.NAMEMAPPINGS
Appendix D. Catalog views 689
SYSCAT.PACKAGEAUTH
Contains a row for every privilege held on a package.
Table 93. SYSCAT.PACKAGEAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privileges.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
PKGSCHEMA VARCHAR(128) Name of the package on which theprivileges are held.PKGNAME CHAR(8)
CONTROLAUTH CHAR(1) Indicates whether grantee holds CONTROLprivilege on the package:
Y = Privilege is held.
N = Privilege is not held.
BINDAUTH CHAR(1) Indicates whether grantee holds BINDprivilege on the package:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
EXECUTEAUTH CHAR(1) Indicates whether grantee holds EXECUTEprivilege on the package:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
SYSCAT.PACKAGEAUTH
690 SQL Reference, Volume 1
SYSCAT.PACKAGEDEP
Contains a row for each dependency that packages have on indexes, tables,views, triggers, functions, aliases, types, and hierarchies.
Table 94. SYSCAT.PACKAGEDEP Catalog View
Column Name Data Type Nullable Description
PKGSCHEMA VARCHAR(128) Name of the package.
PKGNAME CHAR(8)
UNIQUEID CHAR(8) Internal date and time informationindicating when the package was firstcreated. Useful for identifying a specificpackage when multiple packages having thesame name exist.
PKGVERSION VARCHAR(64) Version identifier of the package.
BINDER VARCHAR(128) Yes Binder of the package.
BTYPE CHAR(1) Type of object BNAME:
A = Alias
B = Trigger
D = Server definition
F = Function instance
I = Index
M = Function mapping
N = Nickname
O = Privilege dependency on allsubtables or subviews in a table or viewhierarchy
P = Page size
R = Structured type
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
BSCHEMA VARCHAR(128) Qualified name of an object on which thepackage depends.BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE is O, S, T, U, V or W then itencodes the privileges that are required bythis package (Select, Insert, Delete, Update).
SYSCAT.PACKAGEDEP
Appendix D. Catalog views 691
Table 94. SYSCAT.PACKAGEDEP Catalog View (continued)
Column Name Data Type Nullable Description
Note: If a function instance with dependencies is dropped, the package is put into an “inoperative”state, and it must be explicitly rebound. If any other object with dependencies is dropped, the package isput into an “invalid” state, and the system will attempt to rebind the package automatically when it isfirst referenced.
SYSCAT.PACKAGEDEP
692 SQL Reference, Volume 1
SYSCAT.PACKAGES
Contains a row for each package that has been created by binding anapplication program.
Table 95. SYSCAT.PACKAGES Catalog View
Column Name Data Type Nullable Description
PKGSCHEMA VARCHAR(128) Name of the package.
PKGNAME CHAR(8)
PKGVERSION VARCHAR(64) Version identifier of the package.
BOUNDBY VARCHAR(128) Authorization ID (OWNER) of the binder ofthe package.
DEFINER VARCHAR(128) User ID under which the package wasbound.
DEFAULT_SCHEMA VARCHAR(128) Default schema (QUALIFIER) name used forunqualified names in static SQL statements.
VALID CHAR(1) Y = Valid
N = Not valid
X = Package is inoperative because somefunction instance on which it dependshas been dropped. Explicit rebind isneeded. (If a function instance withdependencies is dropped, the package isput into an “inoperative” state, and itmust be explicitly rebound. If any otherobject with dependencies is dropped, thepackage is put into an “invalid” state,and the system will attempt to rebindthe package automatically when it is firstreferenced.)
UNIQUE_ID CHAR(8) Internal date and time informationindicating when the package was firstcreated. Useful for identifying a specificpackage when multiple packages having thesame name exist.
TOTAL_SECT SMALLINT Total number of sections in the package.
SYSCAT.PACKAGES
Appendix D. Catalog views 693
Table 95. SYSCAT.PACKAGES Catalog View (continued)
Column Name Data Type Nullable Description
FORMAT CHAR(1) Date and time format associated with thepackage:
0 = Format associated with the territorycode of the client
1 = USA date and time
2 = EUR date, EUR time
3 = ISO date, ISO time
4 = JIS date, JIS time
5 = LOCAL date, LOCAL time
ISOLATION CHAR(2) Yes Isolation level:
RR = Repeatable read
RS = Read stability
CS = Cursor stability
UR = Uncommitted read
BLOCKING CHAR(1) Yes Cursor blocking option:
N = No blocking
U = Block unambiguous cursors
B = Block all cursors
INSERT_BUF CHAR(1) Insert option used during bind:
Y = Inserts are buffered
N = Inserts are not buffered
LANG_LEVEL CHAR(1) Yes LANGLEVEL value used during BIND:
0 = SAA1
1 = SQL92E or MIA
FUNC_PATH VARCHAR(254) The SQL path used by the last BINDcommand for this package. This is used asthe default path for REBIND. SYSIBM forpre-Version 2 packages.
QUERYOPT INTEGER Optimization class under which thispackage was bound. Used for REBIND. Theclasses are: 0, 1, 3, 5 and 9.
EXPLAIN_LEVEL CHAR(1) Indicates whether Explain was requestedusing the EXPLAIN or EXPLSNAP bindoption.
P = Plan Selection level
Blank if ’No’ Explain requested
SYSCAT.PACKAGES
694 SQL Reference, Volume 1
Table 95. SYSCAT.PACKAGES Catalog View (continued)
Column Name Data Type Nullable Description
EXPLAIN_MODE CHAR(1) Value of EXPLAIN bind option:
Y = Yes (static)
N = No
A = All (static and dynamic)
EXPLAIN_SNAPSHOT CHAR(1) Value of EXPLSNAP bind option:
Y = Yes (static)
N = No
A = All (static and dynamic)
SQLWARN CHAR(1) Are positive SQLCODEs resulting fromdynamic SQL statements returned to theapplication?
Y = Yes
N = No, they are suppressed.
SQLMATHWARN CHAR(1) Value of the database configurationparameter DFT_SQLMATHWARN at thetime of bind. Are arithmetic errors andretrieval conversion errors in static SQLstatements handled as nulls with a warning?
Y = Yes
N = No, they are suppressed.
EXPLICIT_BIND_TIME TIMESTAMP The time at which this package was lastexplicitly bound or rebound. When thepackage is implicitly rebound, no functioninstance will be selected that was createdlater than this time.
LAST_BIND_TIME TIMESTAMP Time at which the package last explicitly orimplicitly bound or rebound.
CODEPAGE SMALLINT Application code page at bind time (-1 if notknown).
DEGREE CHAR(5) Indicates the limit on intra-partitionparallelism (as a bind option) when packagewas bound.
1 = No intra-partition parallelism.
2 - 32 767 = Degree of intra-partitionparallelism.
ANY = Degree was determined by thedatabase manager.
SYSCAT.PACKAGES
Appendix D. Catalog views 695
Table 95. SYSCAT.PACKAGES Catalog View (continued)
Column Name Data Type Nullable Description
MULTINODE_PLANS CHAR(1) Y = Package was bound in a multiplepartition environment.
N =Package was bound in a singlepartition environment.
INTRA_PARALLEL CHAR(1) Indicates the use of intra-partitionparallelism by static SQL statements withinthe package.
Y = one or more static SQL statement inpackage uses intra-partition parallelism.
N = no static SQL statement in packageuses intra-partition parallelism.
F = one or more static SQL statement inpackage can use intra-partitionparallelism; this parallelism has beendisabled for use on a system that is notconfigured for intra-partition parallelism.
VALIDATE CHAR(1) B = All checking must be performedduring BIND
R = Reserved
SYSCAT.PACKAGES
696 SQL Reference, Volume 1
Table 95. SYSCAT.PACKAGES Catalog View (continued)
Column Name Data Type Nullable Description
DYNAMICRULES CHAR(1) B = BIND. Dynamic SQL statements areexecuted with bind behavior.
D = DEFINEBIND. When the package isrun within a routine context, dynamicSQL statements in the package areexecuted with define behavior. When thepackage is not run within a routinecontext, dynamic SQL statements in thepackage are executed with bind behavior.
E = DEFINERUN. When the package isrun within a routine context, dynamicSQL statements in the package areexecuted with define behavior. When thepackage is not run within a routinecontext, dynamic SQL statements in thepackage are executed with run behavior.
H = INVOKEBIND. When the package isrun within a routine context, dynamicSQL statements in the package areexecuted with invoke behavior. Whenthe package is not run within a routinecontext, dynamic SQL statements in thepackage are executed with bind behavior.
I = INVOKERUN. When the package isrun within a routine context, dynamicSQL statements in the package areexecuted with invoke behavior. Whenthe package is not run within a routinecontext, dynamic SQL statements in thepackage are executed with run behavior.
R = RUN. Dynamic SQL statements areexecuted with run behavior. This is thedefault.
SQLERROR CHAR(1) Indicates SQLERROR option on the mostrecent subcommand that bound or reboundthe package.
C = Reserved
N = No package
REFRESHAGE DECIMAL (20,6) Timestamp duration indicating themaximum length of time between when aREFRESH TABLE statement is run for amaterialized query table and when thematerialized query table is used in place ofa base table.
SYSCAT.PACKAGES
Appendix D. Catalog views 697
Table 95. SYSCAT.PACKAGES Catalog View (continued)
Column Name Data Type Nullable Description
TRANSFORMGROUP CHAR(1024) Yes String containing the transform group bindoption.
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
SYSCAT.PACKAGES
698 SQL Reference, Volume 1
SYSCAT.PARTITIONMAPS
Contains a row for each partitioning map that is used to distribute table rowsamong the partitions in a database partition group, based on hashing thetable’s partitioning key.
Table 96. SYSCAT.PARTITIONMAPS Catalog View
Column Name Data Type Nullable Description
PMAP_ID SMALLINT Identifier of the partitioning map.
PARTITIONMAP LONG VARCHARFOR BIT DATA
The actual partitioning map, a vector of4 096 two-byte integers for a multiplepartition database partition group. For asingle partition database partition group,there is one entry denoting the partitionnumber of the single partition.
SYSCAT.PARTITIONMAPS
Appendix D. Catalog views 699
SYSCAT.PASSTHRUAUTH
This catalog view contains information about authorizations to query datasources in pass-through sessions. A constraint on the base table requires thatthe values in SERVER correspond to the values in the SERVER column ofSYSCAT.SERVERS. None of the fields in SYSCAT.PASSTHRUAUTH arenullable.
Table 97. Columns in SYSCAT.PASSTHRUAUTHCatalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who granted theprivilege.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privilege.
GRANTEETYPE CHAR(1) A letter that specifies the type of grantee:
U = Grantee is an individual user.
G = Grantee is a group.
SERVERNAME VARCHAR(128) Name of the data source that the user or groupis being granted authorization to.
SYSCAT.PASSTHRUAUTH
700 SQL Reference, Volume 1
SYSCAT.PREDICATESPECS
Each row represents a predicate specification.
Table 98. SYSCAT.PREDICATESPECS Catalog View
Column Name Data Type Nullable Description
FUNCSCHEMA VARCHAR(128) Qualified name of function.
FUNCNAME VARCHAR(18)
SPECIFICNAME VARCHAR(18) The name of the function instance.
FUNCID INTEGER Function ID.
SPECID SMALLINT ID of this predicate specification.
CONTEXTOP CHAR(8) Comparison operator is one of the built-inrelational operators (=, <, >=, and so on).
CONTEXTEXP CLOB(32K) Constant, or an SQL expression.
FILTERTEXT CLOB(32K) Yes Text of data filter expression.
SYSCAT.PREDICATESPECS
Appendix D. Catalog views 701
SYSCAT.PROCOPTIONS
Each row contains procedure specific option values.
Table 99. SYSCAT.PROCOPTIONS Catalog View
Column Name Data Type Nullable Description
PROCSCHEMA VARCHAR(128) Qualifier for the stored procedure name ornickname.
PROCNAME VARCHAR(128) Name or nickname of the stored procedure.
OPTION VARCHAR(128) Name of the stored procedure option.
SETTING VARCHAR(255) Value of the stored procedure option.
SYSCAT.PROCOPTIONS
702 SQL Reference, Volume 1
SYSCAT.PROCPARMOPTIONS
Each row contains procedure parameter specific option values.
Table 100. SYSCAT.PROCPARMOPTIONS Catalog View
Column Name Data Type Nullable Description
PROCSCHEMA VARCHAR(128) Qualified procedure name or nickname.
PROCNAME VARCHAR(128)
ORDINAL SMALLINT The parameter’s numerical position within theprocedure signature.
OPTION VARCHAR(128) Name of the stored procedure parameter option.
SETTING VARCHAR(255) Value of the stored procedure parameter option.
SYSCAT.PROCPARMOPTIONS
Appendix D. Catalog views 703
SYSCAT.REFERENCES
Contains a row for each defined referential constraint.
Table 101. SYSCAT.REFERENCES Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the constraint.
TABSCHEMA VARCHAR(128) Qualified name of the table.
TABNAME VARCHAR(128)
DEFINER VARCHAR(128) User who created the constraint.
REFKEYNAME VARCHAR(18) Name of parent key.
REFTABSCHEMA VARCHAR(128) Qualified name of the parent table.
REFTABNAME VARCHAR(128)
COLCOUNT SMALLINT Number of columns in the foreign key.
DELETERULE CHAR(1) Delete rule:
A = NO ACTION
C = CASCADE
N = SET NULL
R = RESTRICT
UPDATERULE CHAR(1) Update rule:
A = NO ACTION
R = RESTRICT
CREATE_TIME TIMESTAMP The timestamp when the referentialconstraint was defined.
FK_COLNAMES VARCHAR (640) List of foreign key column names. Warning:This column will be removed in the future.Use SYSCAT.KEYCOLUSE for thisinformation.
PK_COLNAMES VARCHAR (640) List of parent key column names. Warning:This column will be removed in the future.Use SYSCAT.KEYCOLUSE for thisinformation.
Note: The SYSCAT.REFERENCES view is based on the SYSIBM.SYSRELS table from Version 1.
Related reference:
v “SYSCAT.KEYCOLUSE” on page 688
SYSCAT.REFERENCES
704 SQL Reference, Volume 1
SYSCAT.REVTYPEMAPPINGS
Each row contains reverse data type mappings (mappings from data typesdefined locally to data source data types). No data in this version. Defined forpossible future use with data type mappings.
Table 102. SYSCAT.REVTYPEMAPPINGS Catalog View
Column Name Data Type Nullable Description
TYPE_MAPPING VARCHAR(18) Name of the reverse type mapping (may besystem-generated).
TYPESCHEMA VARCHAR(128) Yes Schema name of the type. Null for systembuilt-in types.
TYPENAME VARCHAR(18) Name of the local type in a reverse typemapping.
TYPEID SMALLINT Type identifier.
SOURCETYPEID SMALLINT Source type identifier.
DEFINER VARCHAR(128) Authorization ID under which this typemapping was created.
LOWER_LEN INTEGER Yes Lower bound of the length/precision of thelocal type.
UPPER_LEN INTEGER Yes Upper bound of the length/precision of thelocal type. If null then the system determinesthe best length/precision attribute.
LOWER_SCALE SMALLINT Yes Lower bound of the scale for local decimaldata types.
UPPER_SCALE SMALLINT Yes Upper bound of the scale for local decimaldata types. If null, then the systemdetermines the best scale attribute.
S_OPR_P CHAR(2) Yes Relationship between local scale and localprecision. Basic comparison operators can beused. A null indicates that no specificrelationship is required.
BIT_DATA CHAR(1) Yes Y = Type is for bit data.
N = Type is not for bit data.
NULL = This is not a character data typeor that the system determines the bit dataattribute.
WRAPNAME VARCHAR(128) Yes Mapping applies to this data access protocol.
SERVERNAME VARCHAR(128) Yes Name of the data source.
SERVERTYPE VARCHAR(30) Yes Mapping applies to this type of data source.
SYSCAT.REVTYPEMAPPINGS
Appendix D. Catalog views 705
Table 102. SYSCAT.REVTYPEMAPPINGS Catalog View (continued)
Column Name Data Type Nullable Description
SERVERVERSION VARCHAR(18) Yes Mapping applies to this version ofSERVERTYPE.
REMOTE_TYPESCHEMA VARCHAR(128) Yes Schema name of the remote type.
REMOTE_TYPENAME VARCHAR(128) Name of the data type as defined on the datasource(s).
REMOTE_META_TYPE CHAR(1) Yes S = Remote type is a system built-in type.
T = Remote type is a distinct type.
REMOTE_LENGTH INTEGER Yes Maximum number of digits for remotedecimal type, and maximum number ofcharacters for remote character type.Otherwise null.
REMOTE_SCALE SMALLINT Yes Maximum number of digits allowed to theright of the decimal point (for remotedecimal types). Otherwise null.
REMOTE_BIT_DATA CHAR(1) Yes Y = Type is for bit data.
N = Type is not for bit data.
NULL = This is not a character data typeor that the system determines the bit dataattribute.
USER_DEFINED CHAR(1) Defined by user.
CREATE_TIME TIMESTAMP Time when this mapping was created.
REMARKS VARCHAR(254) Yes User supplied comments, or null.
SYSCAT.REVTYPEMAPPINGS
706 SQL Reference, Volume 1
SYSCAT.ROUTINEAUTH
Contains one or more rows for each user or group who is granted EXECUTEprivilege on a particular routine in the database.
Table 103. SYSCAT.ROUTINEAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privilege or SYSIBM.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privilege.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
SCHEMA VARCHAR(128) Qualifier of the routine.
SPECIFICNAME VARCHAR(128) Yes Specific name of the routine. IfSPECIFICNAME is null and ROUTINETYPEis not M, the privilege applies to all routinesin the schema of the type specified inROUTINETYPE. If SPECIFICNAME is nulland ROUTINETYPE is M, the privilegeapplies to all methods in the schema ofsubject type TYPENAME.
TYPESCHEMA VARCHAR(128) Yes Qualifier of the type name for the method.If ROUTINETYPE is not M, TYPESCHEMAis null.
TYPENAME VARCHAR(18) Yes Type name for the method. IfROUTINETYPE is not M, TYPENAME isnull. If TYPENAME is null andROUTINETYPE is M, the privilege appliesto subject types in the schemaTYPESCHEMA.
ROUTINETYPE CHAR(1) Type of routine:
F = Function
M = Method
P = Procedure
EXECUTEAUTH CHAR(1) Indicates whether grantee holds EXECUTEprivilege on the function or method:
Y = Privilege is held.
G = Privilege is held and grantable.
N = Privilege is not held.
GRANT_TIME TIMESTAMP Time at which the EXECUTE privilege isgranted.
SYSCAT.ROUTINEAUTH
Appendix D. Catalog views 707
SYSCAT.ROUTINEDEP
Each row represents a dependency of a routine on some other object. (Thiscatalog view supercedes SYSCAT.FUNCDEP. The other view exists, but willremain as it was in DB2 Version 7.1.)
Table 104. SYSCAT.FUNCDEP Catalog View
Column Name Data Type Nullable Description
ROUTINESCHEMA VARCHAR(128) Qualified name of the routine that hasdependencies on another object.ROUTINENAME VARCHAR(128)
BTYPE CHAR(1) Type of object on which the routine depends.
A = Alias
F = Routine instance
O = Privilege dependency on all subtables orsubviews in a table or view hierarchy
R = Structured type
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
X = Index extension
BSCHEMA VARCHAR(128) Qualified name of the object on which thefunction or method depends (if BTYPE = F, thisis the specific name of a routine).BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE = O, S, T, U, V or W, it encodes theprivileges on the table or view that are requiredby the dependent routine. Otherwise null.
SYSCAT.ROUTINEDEP
708 SQL Reference, Volume 1
SYSCAT.ROUTINEPARMS
Contains a row for every parameter or result of a routine defined inSYSCAT.ROUTINES. (This catalog view supercedes SYSCAT.FUNCPARMSand SYSCAT.PROCPARMS. The other views exist, but will remain as theywere in DB2 Version 7.1.)
Table 105. SYSCAT.ROUTINEPARMS Catalog View
Column Name Data Type Nullable Description
ROUTINESCHEMA VARCHAR(128) Qualified routine name.
ROUTINENAME VARCHAR(18)
SPECIFICNAME VARCHAR(18) The name of the routine instance (may besystem-generated).
PARMNAME VARCHAR(128) Yes Name of parameter or result column, or nullif no name exists.
ROWTYPE CHAR(1) B = Both input and output parameter
C = Result after casting
O = Output parameter
P = Input parameter
R = Result before casting
ORDINAL SMALLINT If ROWTYPE = B, O, or P, the parameter’snumerical position within the routinesignature. If ROWTYPE = R, and the routineis a table function, the column’s numericalposition within the result table. Otherwise 0.
TYPESCHEMA VARCHAR(128) Qualified name of data type of parameter orresult.TYPENAME VARCHAR(18)
LOCATOR CHAR(1) Y = Parameter or result is passed in theform of a locator.
N = Parameter or result is not passed inthe form of a locator.
LENGTH INTEGER Length of parameter or result. 0 if parameteror result is a distinct type. See Note 1.
SCALE SMALLINT Scale of parameter or result. 0 if parameter orresult is a distinct type. See Note 1.
CODEPAGE SMALLINT Code page of parameter or result. 0 denoteseither not applicable, or a parameter or resultfor character data declared with the FOR BITDATA attribute.
SYSCAT.ROUTINEPARMS
Appendix D. Catalog views 709
Table 105. SYSCAT.ROUTINEPARMS Catalog View (continued)
Column Name Data Type Nullable Description
CAST_FUNCSCHEMA VARCHAR(128) Yes Qualified name of the function used to castan argument or a result. Applies to sourcedand external functions; null otherwise.CAST_FUNCSPECIFIC VARCHAR(18) Yes
TARGET_TYPESCHEMA VARCHAR(128) Yes Qualified name of the target type, if the typeof the parameter or result is REFERENCE.Null value if the type of the parameter orresult is not REFERENCE.
TARGET_TYPENAME VARCHAR(18) Yes
SCOPE_TABSCHEMA VARCHAR(128) Yes Qualified name of the scope (target table), ifthe type of the parameter or result isREFERENCE. Null value if the type of theparameter or result is not REFERENCE, orthe scope is not defined.
SCOPE_TABNAME VARCHAR(128) Yes
TRANSFORM_GRPNAME VARCHAR(18) Yes Name of transform group for a structuredtype parameter or result.
REMARKS VARCHAR(254) Yes Parameter remarks.
Notes:
1. LENGTH and SCALE are set to 0 for sourced functions (functions defined with a reference toanother function), because they inherit the length and scale of parameters from their source.
SYSCAT.ROUTINEPARMS
710 SQL Reference, Volume 1
SYSCAT.ROUTINES
Contains a row for each user-defined function (scalar, table, or source),system-generated method, user-defined method, or procedure. Does notinclude built-in functions. (This catalog view supercedesSYSCAT.FUNCTIONS and SYSCAT.PROCEDURES. The other views exist, butwill remain as they were in DB2 Version 7.1.)
Table 106. SYSCAT.ROUTINES Catalog View
Column Name Data Type Nullable Description
ROUTINESCHEMA VARCHAR(128) Qualified routine name.
ROUTINENAME VARCHAR(18)
ROUTINETYPE CHAR(1) F = Function
M = Method
P = Procedure.
DEFINER VARCHAR(128) Authorization ID of routine definer.
SPECIFICNAME VARCHAR(18) The name of the routine instance (maybe system-generated).
ROUTINEID INTEGER Internally-assigned routine ID.
RETURN_TYPESCHEMA VARCHAR(128) Yes Qualified name of the return type for ascalar function or method.RETURN_TYPENAME VARCHAR(128) Yes
ORIGIN CHAR(1) B = Built-in
E = User-defined, external
M = Template
Q = SQL-bodied
U = User-defined, based on a source
S = System-generated
T = System-generated transform
FUNCTIONTYPE CHAR(1) C = Column function
R = Row function
S = Scalar function or method
T = Table function
Blank = Procedure
PARM_COUNT SMALLINT Number of parameters.
LANGUAGE CHAR(8) Implementation language of routinebody. Possible values are C, COBOL,JAVA, OLE, OLEDB, or SQL. Blank ifORIGIN is not E or Q.
SYSCAT.ROUTINES
Appendix D. Catalog views 711
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
SOURCESCHEMA VARCHAR(128) Yes If ORIGIN = U and the routine is auser-defined function, contains thequalified name of the source function. IfORIGIN = U and the source function isbuilt-in, SOURCESCHEMA is 'SYSIBM'and SOURCESPECIFIC is 'N/A forbuilt-in'. Null if ORIGIN is not U.
SOURCESPECIFIC VARCHAR(18) Yes
DETERMINISTIC CHAR(1) Y = Deterministic (results areconsistent)
N = Non-deterministic (results maydiffer)
Blank if ORIGIN is not E or Q.
EXTERNAL_ACTION CHAR(1) E = Function has externalside-effects (number of invocationsis important)
N = No side-effects
Blank if ORIGIN is not E or Q.
NULLCALL CHAR(1) Y = CALLED ON NULL INPUT
N = RETURNS NULL ON NULLINPUT (result is implicitly null ifoperand(s) are null).
Blank if ORIGIN is not E or Q.
CAST_FUNCTION CHAR(1) Y = This is a cast function
N = This is not a cast function
ASSIGN_FUNCTION CHAR(1) Y = Implicit assignment function
N = Not an assignment function
SCRATCHPAD CHAR(1) Y = This routine has a scratch pad
N = This routine does not have ascratch pad
Blank if ORIGIN is not E orROUTINETYPE is P.
SCRATCHPAD_LENGTH SMALLINT n = Length of the scratch pad inbytes
0 = SCRATCHPAD is N
-1 = LANGUAGE is OLEDB
SYSCAT.ROUTINES
712 SQL Reference, Volume 1
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
FINALCALL CHAR(1) Y = Final call is made to thisfunction at runtimeend-of-statement.
N = No final call is made.
Blank if ORIGIN is not E.
PARALLEL CHAR(1) Y = Function can be executed inparallel.
N = Function cannot be executed inparallel.
Blank if ORIGIN is not E.
PARAMETER_STYLE CHAR(8) Indicates the parameter style declaredwhen the routine was created. Values:
DB2SQL
SQL
DB2GENRL
GENERAL
JAVA
DB2DARI
GNRLNULL
Blank if ORIGIN is not E.
FENCED CHAR(1) Y = Fenced
N = Not fenced
Blank if ORIGIN is not E.
SQL_DATA_ACCESS CHAR(1) C = CONTAINS SQL: only SQL thatdoes not read or modify SQL data isallowed.
M = MODIFIES SQL DATA: all SQLallowed in routines is allowed.
N = NO SQL: SQL is not allowed.
R = READS SQL DATA: only SQLthat reads SQL data is allowed.
DBINFO CHAR(1) Y = DBINFO is passed.
N = DBINFO is not passed.
PROGRAMTYPE CHAR(1) M = Main
S = Subroutine
SYSCAT.ROUTINES
Appendix D. Catalog views 713
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
COMMIT_ON_RETURN CHAR(1) N = Changes are not committedafter the procedure completes.
Blank if ROUTINETYPE is not P.
RESULT_SETS SMALLINT Estimated upper limit of returned resultsets.
SPEC_REG CHAR(1) I = INHERIT SPECIAL REGISTERS:special registers start with theirvalues from the invoking statement.
Blank if ORIGIN is not E or Q.
FEDERATED CHAR(1) Y = Routine can access federatedobjects.
N = Routine may not accessfederated objects.
Blank if ORIGIN is not E or Q.
THREADSAFE CHAR(1) Y = Routine can run in the sameprocess as other routines.
N = Routine must be run in aseparate process from other routines.
Blank if ORIGIN is not E.
VALID CHAR(1) Y = SQL procedure is valid.
N = SQL procedure is invalid.
X = SQL procedure is inoperativebecause some object it requires hasbeen dropped. The SQL proceduremust be explicitly dropped andrecreated.
Blank if ORIGIN is not Q.
METHODIMPLEMENTED CHAR(1) Y = Method is implemented.
N = Method specification withoutan implementation.
Blank if ROUTINETYPE is not M.
METHODEFFECT CHAR(2) MU = Mutator method
OB = Observer method
CN = Constructor method
Blanks if FUNCTIONTYPE is not T.
SYSCAT.ROUTINES
714 SQL Reference, Volume 1
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
TYPE_PRESERVING CHAR(1) Y = Return type is governed by a″type-preserving″ parameter. Allsystem-generated mutator methodsare type-preserving.
N = Return type is the declaredreturn type of the method.
Blank if ROUTINETYPE is not M.
WITH_FUNC_ACCESS CHAR(1) Y = This method can be invoked byusing functional notation.
N = This method cannot be invokedby using functional notation.
Blank if ROUTINETYPE is not M.
OVERRIDEN_METHODID INTEGER Yes Reserved for future use.
SUBJECT_TYPESCHEMA VARCHAR(128) Yes Subject type for method.
SUBJECT_TYPENAME VARCHAR(18) Yes
CLASS VARCHAR(128) Yes If LANGUAGE = JAVA, identifies theclass that implements this routine. Nullotherwise.
JAR_ID VARCHAR(128) Yes If LANGUAGE = JAVA, identifies thejar file that implements this routine.Null otherwise.
JARSCHEMA VARCHAR(128) Yes If LANGUAGE = JAVA, identifies theschema of the jar file that implementsthis routine. Null otherwise.
JAR_SIGNATURE VARCHAR(128) Yes If LANGUAGE = JAVA, identifies thesignature of the Java method thatimplements this routine. Nullotherwise.
CREATE_TIME TIMESTAMP Timestamp of routine creation. Set to 0for Version 1 functions.
ALTER_TIME TIMESTAMP Timestamp of most recent routinealteration. If the routine has not beenaltered, set to CREATE_TIME.
FUNC_PATH VARCHAR(254) Yes SQL path at the time the routine wasdefined.
QUALIFIER VARCHAR(128) Value of default schema at objectdefinition time.
IOS_PER_INVOC DOUBLE Estimated number of I/Os perinvocation; -1 if not known (0 default).
SYSCAT.ROUTINES
Appendix D. Catalog views 715
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
INSTS_PER_INVOC DOUBLE Estimated number of instructions perinvocation; -1 if not known (450default).
IOS_PER_ARGBYTE DOUBLE Estimated number of I/Os per inputargument byte; -1 if not known (0default).
INSTS_PER_ARGBYTE DOUBLE Estimated number of instructions perinput argument byte; -1 if not known (0default).
PERCENT_ARGBYTES SMALLINT Estimated average percent of inputargument bytes that the routine willactually read; -1 if not known (100default).
INITIAL_IOS DOUBLE Estimated number of I/Os performedthe first/last time the routine isinvoked; -1 if not known (0 default).
INITIAL_INSTS DOUBLE Estimated number of instructionsexecuted the first/last time the routineis invoked; -1 if not known (0 default).
CARDINALITY BIGINT The predicted cardinality of a tablefunction; -1 if not known, or if theroutine is not a table function.
SELECTIVITY DOUBLE Used for user-defined predicates; -1 ifthere are no user-defined predicates.See Note 1.
RESULT_COLS SMALLINT For a table function (ROUTINETYPE =F and TYPE = T) contains the numberof columns in the result table. For otherfunctions and methods (ROUTINETYPE= F or M), contains 1. For procedures(ROUTINETYPE = P), contains 0.
IMPLEMENTATION VARCHAR(254) Yes If ORIGIN = E, identifies thepath/module/function that implementsthis function. If ORIGIN = U and thesource function is built-in, this columncontains the name and signature of thesource function. Null otherwise.
LIB_ID INTEGER Yes Reserved for future use.
TEXT_BODY_OFFSET INTEGER If LANGUAGE = SQL, the offset to thestart of the SQL procedure body in thefull text of the CREATE statement; 0 ifLANGUAGE is not SQL.
SYSCAT.ROUTINES
716 SQL Reference, Volume 1
Table 106. SYSCAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description
TEXT CLOB(1M) Yes If LANGUAGE = SQL, the text of theCREATE FUNCTION, CREATEMETHOD, or CREATE PROCEDUREstatement.
NEWSAVEPOINTLEVEL CHAR(1) Indicates whether the routine initiates anew savepoint level when it is invoked.
Y = A new savepoint level isinitiated when the routine isinvoked.
N = A new savepoint level is notinitiated when the routine isinvoked. The routine uses theexisting savepoint level.
Blank - not applicable.
DEBUG_MODE CHAR(1) 0 = Debugging is off for this routine.
1 = Debugging is on for this routine.
TRACE_LEVEL CHAR(1) Reserved for future use.
DIAGNOSTIC_LEVEL CHAR(1) Reserved for future use.
CHECKOUT_USERID VARCHAR(128) Yes User ID of the user who performed acheckout of the object. Null if notchecked out.
PRECOMPILE_OPTIONS VARCHAR(1024) Yes Precompile options specified for theroutine.
COMPILE_OPTIONS VARCHAR(1024) Yes Compile options specified for theroutine.
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
Notes:
1. This column will be set to -1 during migration in the packed descriptor and system catalogs for alluser-defined routines. For a user-defined predicate, the selectivity in the system catalog will be -1. Inthis case, the selectivity value used by the optimizer is 0.01.
SYSCAT.ROUTINES
Appendix D. Catalog views 717
SYSCAT.SCHEMAAUTH
Contains one or more rows for each user or group who is granted a privilegeon a particular schema in the database. All schema privileges for a singleschema granted by a specific grantor to a specific grantee appear in a singlerow.
Table 107. SYSCAT.SCHEMAAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privileges or SYSIBM.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.G = Grantee is a group.
SCHEMANAME VARCHAR(128) Name of the schema.
ALTERINAUTH CHAR(1) Indicates whether grantee holds ALTERINprivilege on the schema:
Y = Privilege is held.G = Privilege is held and grantable.N = Privilege is not held.
CREATEINAUTH CHAR(1) Indicates whether grantee holds CREATEINprivilege on the schema:
Y = Privilege is held.G = Privilege is held and grantable.N = Privilege is not held.
DROPINAUTH CHAR(1) Indicates whether grantee holds DROPINprivilege on the schema:
Y = Privilege is held.G = Privilege is held and grantable.N = Privilege is not held.
SYSCAT.SCHEMAAUTH
718 SQL Reference, Volume 1
SYSCAT.SCHEMATA
Contains a row for each schema.
Table 108. SYSCAT.SCHEMATA Catalog View
Column Name Data Type Nullable Description
SCHEMANAME VARCHAR(128) Name of the schema.
OWNER VARCHAR(128) Authorization id of the schema. The valuefor implicitly created schemas is SYSIBM.
DEFINER VARCHAR(128) User who created the schema.
CREATE_TIME TIMESTAMP Timestamp indicating when the object wascreated.
REMARKS VARCHAR(254) Yes User-provided comment.
SYSCAT.SCHEMATA
Appendix D. Catalog views 719
SYSCAT.SEQUENCEAUTH
Contains a row for each authorization ID that can be used to use or to alter asequence.
Table 109. SYSCAT.SEQUENCEAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) SYSIBM or authorization ID that granted theprivilege.
GRANTEE VARCHAR(128) Authorization ID that holds the privilege.
GRANTEETYPE CHAR(1) Type of authorization ID that holds theprivilege.
U = grantee is an individual user
SEQSCHEMA VARCHAR(128) Qualified name of the sequence.
SEQNAME VARCHAR(128)
USAGEAUTH CHAR(1) Y = privilege is held
N = privilege is not held
G = privilege is held and is grantable
ALTERAUTH CHAR(1) Y = privilege is held
N = privilege is not held
G = privilege is held and is grantable
SYSCAT.SEQUENCEAUTH
720 SQL Reference, Volume 1
SYSCAT.SEQUENCES
Contains a row for each sequence defined in the database. This catalog viewis updated during normal operations, in response to SQL data definitionstatements, environment routines, and certain utilities. Data in the catalogview is available through normal SQL query facilities. Columns haveconsistent names based on the type of objects that they describe.
Table 110. Columns in SYSCAT.SEQUENCES Catalog View
Column Name Data Type Nullable Description
SEQSCHEMA VARCHAR(128) Qualified name of the sequence (generated byDB2 for an identity column).SEQNAME VARCHAR(128)
DEFINER VARCHAR(128) Definer of the sequence.
OWNER VARCHAR(128) Owner of the sequence.
SEQID INTEGER Internal ID of the sequence.
SEQTYPE CHAR(1) Sequence type
S = Regular sequence
I = Identity sequence
INCREMENT DECIMAL(31,0) Increment value.
START DECIMAL(31,0) Starting value.
MAXVALUE DECIMAL(31,0) Maximal value.
MINVALUE DECIMAL(31,0) Minimum value.
CYCLE CHAR(1) Whether cycling will occur when a boundary isreached:
Y - cycling will occur
N - cycling will not occur
CACHE INTEGER Number of sequence values to preallocate inmemory for faster access. 0 indicates that valuesare not preallocated.
ORDER CHAR(1) Whether or not the sequence numbers must begenerated in order of request:
Y - sequence numbers must be generated inorder of request
N - sequence numbers are not required to begenerated in order of request
DATATYPEID INTEGER For built-in types, the internal ID of the built-intype. For distinct types, the internal ID of thedistinct type.
SYSCAT.SEQUENCES
Appendix D. Catalog views 721
Table 110. Columns in SYSCAT.SEQUENCES Catalog View (continued)
Column Name Data Type Nullable Description
SOURCETYPEID INTEGER For a built-in type, this has a value of 0. For adistinct type, this is the internal ID of thebuilt-in type that is the source type for thedistinct type.
CREATE_TIME TIMESTAMP Time when the sequence was created.
ALTER_TIME TIMESTAMP Time when the last ALTER SEQUENCEstatement was executed for this sequence.
PRECISION SMALLINT The precision of the data type of the sequence.Values are: 5 for a SMALLINT, 10 for INTEGER,and 19 for BIGINT. For DECIMAL, it is theprecision of the specified DECIMAL data type.
ORIGIN CHAR(1) Sequence Origin
U - User generated sequence
S - System generated sequence
REMARKS VARCHAR(254) Yes User supplied comments, or null.
SYSCAT.SEQUENCES
722 SQL Reference, Volume 1
SYSCAT.SERVEROPTIONS
Each row contains configuration options at the server level.
Table 111. Columns in SYSCAT.SERVEROPTIONS Catalog View
Column Name Data Type Nullable Description
WRAPNAME VARCHAR(128) Yes Wrapper name.
SERVERNAME VARCHAR(128) Yes Name of the server.
SERVERTYPE VARCHAR(30) Yes Server type.
SERVERVERSION VARCHAR(18) Yes Server version.
CREATE_TIME TIMESTAMP Time when entry is created.
OPTION VARCHAR(128) Name of the server option.
SETTING VARCHAR(2048) Value of the server option.
SERVEROPTIONKEY VARCHAR(18) Uniquely identifies a row.
REMARKS VARCHAR(254) Yes User supplied comments, or null.
SYSCAT.SERVEROPTIONS
Appendix D. Catalog views 723
SYSCAT.SERVERS
Each row represents a data source. Catalog entries are not necessary for tablesthat are stored in the same instance that contains this catalog table.
Table 112. Columns in SYSCAT.SERVERS Catalog View
Name Data Type Nullable Description
WRAPNAME VARCHAR(128) Wrapper name.
SERVERNAME VARCHAR(128) Name of data source as it is known to thesystem.
SERVERTYPE VARCHAR(30) Yes Type of data source (always uppercase).
SERVERVERSION VARCHAR(18) Yes Version of data source.
REMARKS VARCHAR(254) Yes User supplied comments, or null.
SYSCAT.SERVERS
724 SQL Reference, Volume 1
SYSCAT.STATEMENTS
Contains one or more rows for each SQL statement in each package in thedatabase.
Table 113. SYSCAT.STATEMENTS Catalog View
Column Name Data Type Nullable Description
PKGSCHEMA VARCHAR(128) Name of the package.
PKGNAME CHAR(8)
UNIQUEID CHAR(8) Internal date and time informationindicating when the package was firstcreated. Useful for identifying a specificpackage when multiple packages having thesame name exist.
PKGVERSION VARCHAR(64) Version identifier of the package.
STMTNO INTEGER Line number of the SQL statement in thesource module of the application program.
SECTNO SMALLINT Number of the package section containingthe SQL statement.
SEQNO SMALLINT Always 1.
TEXT CLOB (64K) Text of the SQL statement.
SYSCAT.STATEMENTS
Appendix D. Catalog views 725
SYSCAT.TABAUTH
Contains one or more rows for each user or group who is granted a privilegeon a particular table or view in the database. All the table privileges for asingle table or view granted by a specific grantor to a specific grantee appearin a single row.
Table 114. SYSCAT.TABAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR VARCHAR(128) Authorization ID of the user who grantedthe privileges or SYSIBM.
GRANTEE VARCHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
TABSCHEMA VARCHAR(128) Qualified name of the table or view.
TABNAME VARCHAR(128)
CONTROLAUTH CHAR(1) Indicates whether grantee holds CONTROLprivilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
ALTERAUTH CHAR(1) Indicates whether grantee holds ALTERprivilege on the table:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
DELETEAUTH CHAR(1) Indicates whether grantee holds DELETEprivilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
INDEXAUTH CHAR(1) Indicates whether grantee holds INDEXprivilege on the table:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
SYSCAT.TABAUTH
726 SQL Reference, Volume 1
Table 114. SYSCAT.TABAUTH Catalog View (continued)
Column Name Data Type Nullable Description
INSERTAUTH CHAR(1) Indicates whether grantee holds INSERTprivilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
SELECTAUTH CHAR(1) Indicates whether grantee holds SELECTprivilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
REFAUTH CHAR(1) Indicates whether grantee holdsREFERENCE privilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
UPDATEAUTH CHAR(1) Indicates whether grantee holds UPDATEprivilege on the table or view:
Y = Privilege is held.
N = Privilege is not held.
G = Privilege is held and grantable.
SYSCAT.TABAUTH
Appendix D. Catalog views 727
SYSCAT.TABCONST
Each row represents a table constraint of type CHECK, UNIQUE, PRIMARYKEY, or FOREIGN KEY.
Table 115. SYSCAT.TABCONST Catalog View
Column Name Data Type Nullable Description
CONSTNAME VARCHAR(18) Name of the constraint (unique within atable).
TABSCHEMA VARCHAR(128) Qualified name of the table to whichthis constraint applies.TABNAME VARCHAR(128)
DEFINER VARCHAR(128) Authorization ID under which theconstraint was defined.
TYPE CHAR(1) Indicates the constraint type:
F = FOREIGN KEY
K = CHECK
P = PRIMARY KEY
U = UNIQUE
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
ENFORCED CHAR(1) Y = Enforce constraint
N = Do not enforce constraint
CHECKEXISTINGDATA CHAR(1) D = Defer checking of existing data
I = Immediately check existing data
N = Never check existing data
ENABLEQUERYOPT CHAR(1) Y = Query optimization is enabled
N = Query optimization is disabled
SYSCAT.TABCONST
728 SQL Reference, Volume 1
SYSCAT.TABDEP
Contains a row for every dependency of a view or a materialized query tableon some other object. Also encodes how privileges on this view depend onprivileges on underlying tables and views. (The VIEWDEP catalog view is stillavailable, but only at the Version 7.1 level.)
Table 116. SYSCAT.TABDEP Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Name of the view or materialized querytable with dependencies on a base table.TABNAME VARCHAR(128)
DTYPE CHAR(1) S = Materialized query table
V = View (untyped)
W = Typed view
DEFINER VARCHAR(128) Yes Authorization ID of the creator of the view.
BTYPE CHAR(1) Type of object BNAME:
A = Alias
F = Function instance
N = Nickname
O = Privilege dependency on allsubtables or subviews in a table or viewhierarchy
I = Index if recording dependency on abase table
R = Structured type
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
BSCHEMA VARCHAR(128) Qualified name of the object on which theview depends.BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE = O, S, T, U, V, W, encodes theprivileges on the underlying table or viewon which this table depends. Otherwisenull.
SYSCAT.TABDEP
Appendix D. Catalog views 729
SYSCAT.TABLES
Contains one row for each table, view, nickname or alias that is created. All ofthe catalog tables and views have entries in the SYSCAT.TABLES catalog view.
Table 117. SYSCAT.TABLES Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified name of the table, view, nickname,or alias.TABNAME VARCHAR(128)
DEFINER VARCHAR(128) User who created the table, view, nicknameor alias.
TYPE CHAR(1) The type of object:
A = Alias
H = Hierarchy table
N = Nickname
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
STATUS CHAR(1) The check pending status of the object:
N = Normal table, view, alias ornickname
C = Check pending on table or nickname
X = Inoperative view or nickname
DROPRULE CHAR(1) N = No rule
R = Restrict rule applies on drop
BASE_TABSCHEMA VARCHAR(128) Yes If TYPE = A, these columns identify thetable, view, alias, or nickname that isreferenced by this alias; otherwise they arenull.
BASE_TABNAME VARCHAR(128) Yes
ROWTYPESCHEMA VARCHAR(128) Yes Contains the qualified name of the rowtypeof this table, where applicable. Nullotherwise.ROWTYPENAME VARCHAR(18)
CREATE_TIME TIMESTAMP The timestamp indicating when the objectwas created.
STATS_TIME TIMESTAMP Yes Last time when any change was made torecorded statistics for this table. Null if nostatistics available.
COLCOUNT SMALLINT Number of columns in the table.
SYSCAT.TABLES
730 SQL Reference, Volume 1
Table 117. SYSCAT.TABLES Catalog View (continued)
Column Name Data Type Nullable Description
TABLEID SMALLINT Internal table identifier.
TBSPACEID SMALLINT Internal identifier of primary table space forthis table.
CARD BIGINT Total number of rows in the table. For tablesin a table hierarchy, the number of rows atthe given level of the hierarchy; −1 ifstatistics are not gathered, or the rowdescribes a view or alias; −2 for hierarchytables (H-tables).
NPAGES INTEGER Total number of pages on which the rows ofthe table exist; −1 if statistics are notgathered, or the row describes a view oralias; −2 for subtables or H-tables.
FPAGES INTEGER Total number of pages; −1 if statistics arenot gathered, or the row describes a view oralias; −2 for subtables or H-tables.
OVERFLOW INTEGER Total number of overflow records in thetable; −1 if statistics are not gathered, or therow describes a view or alias; −2 forsubtables or H-tables.
TBSPACE VARCHAR(18) Yes Name of primary table space for the table. Ifno other table space is specified, all parts ofthe table are stored in this table space. Nullfor aliases and views.
INDEX_TBSPACE VARCHAR(18) Yes Name of table space that holds all indexescreated on this table. Null for aliases andviews, or if the INDEX IN clause wasomitted or specified with the same value asthe IN clause of the CREATE TABLEstatement.
LONG_TBSPACE VARCHAR(18) Yes Name of table space that holds all long data(LONG or LOB column types) for this table.Null for aliases and views, or if the LONGIN clause was omitted or specified with thesame value as the IN clause of the CREATETABLE statement.
PARENTS SMALLINT Yes Number of parent tables of this table (thenumber of referential constraints in whichthis table is a dependent).
CHILDREN SMALLINT Yes Number of dependent tables of this table(the number of referential constraints inwhich this table is a parent).
SYSCAT.TABLES
Appendix D. Catalog views 731
Table 117. SYSCAT.TABLES Catalog View (continued)
Column Name Data Type Nullable Description
SELFREFS SMALLINT Yes Number of self-referencing referentialconstraints for this table (the number ofreferential constraints in which this table isboth a parent and a dependent).
KEYCOLUMNS SMALLINT Yes Number of columns in the primary key ofthe table.
KEYINDEXID SMALLINT Yes Index ID of the primary index. This field isnull or 0 if there is no primary key.
KEYUNIQUE SMALLINT Number of unique constraints (other thanprimary key) defined on this table.
CHECKCOUNT SMALLINT Number of check constraints defined on thistable.
DATACAPTURE CHAR(1) Y = Table participates in data replication
N = Does not participate
L = Table participates in data replication,including replication of LONGVARCHAR and LONG VARGRAPHICcolumns
CONST_CHECKED CHAR(32) Byte 1 represents foreign key constraints.Byte 2 represents check constraints. Byte 5represents materialized query table. Byte 6represents generated columns. Byte 7represents staging table. Other bytes arereserved. Encodes constraint information onchecking. Values:
Y = Checked by system
U = Checked by user
N = Not checked (pending)
W = Was in a ’U’ state when the tablewas placed in check pending (pending)
F = In byte 5, the materialized querytable cannot be refreshed incrementally.In byte 7, the content of the staging tableis incomplete and cannot be used forincremental refresh of the associatedmaterialized query table.
PMAP_ID SMALLINT Yes Identifier of the partitioning map used bythis table. Null for aliases and views.
SYSCAT.TABLES
732 SQL Reference, Volume 1
Table 117. SYSCAT.TABLES Catalog View (continued)
Column Name Data Type Nullable Description
PARTITION_MODE CHAR(1) Mode used for tables in a partitioneddatabase.
H = Hash on the partitioning key
R = Table replicated across databasepartitions
Blank for aliases, views and tables insingle partition database partition groupswith no partitioning key defined. Alsoblank for nicknames.
LOG_ATTRIBUTE CHAR(1) 0 = Default logging
1 = Table created not logged initially
PCTFREE SMALLINT Percentage of each page to be reserved forfuture inserts. Can be changed by ALTERTABLE.
APPEND_MODE CHAR(1) Controls how rows are inserted on pages:
N = New rows are inserted into existingspaces if available
Y = New rows are appended at end ofdata
Initial value is N.
REFRESH CHAR(1) Refresh mode:
D = Deferred
I = Immediate
O = Once
Blank if not a materialized query table
REFRESH_TIME TIMESTAMP Yes For REFRESH = D or O, timestamp of theREFRESH TABLE statement that lastrefreshed the data. Otherwise null.
LOCKSIZE CHAR(1) Indicates preferred lock granularity fortables when accessed by DML statements.Only applies to tables. Possible values are:
R = Row
T = Table
Blank if not applicable
Initial value is R.
VOLATILE CHAR(1) C = Cardinality of the table is volatile
Blank if not applicable
SYSCAT.TABLES
Appendix D. Catalog views 733
Table 117. SYSCAT.TABLES Catalog View (continued)
Column Name Data Type Nullable Description
ROW_FORMAT CHAR(1) Version of the row format. Possible valuesare:
O = Object does not physically exist ondisk (for example, a view)
1 = Row format starting with DB2Version 8
2 = Row format prior to DB2 Version 8
PROPERTY VARCHAR(32) Properties for the table. A single blankindicates that the table has no properties.
STATISTICS_PROFILE CLOB(32K) Yes RUNSTATS command used to register astatistical profile of the table.
COMPRESSION CHAR(1) V = Value compression is activated, anda row format that supports compressionis used
N = No compression. A row format thatdoes not support compression is used
ACCESS_MODE CHAR(1) Access mode of the object. This access modeis used in conjunction with the STATUSfield to represent one of four states. Possiblevalues are:
N = No access (corresponds to a statusvalue of C)
R = Read-only (corresponds to a statusvalue of C)
D = No data movement (corresponds toa status value of N)
F = Full access (corresponds to a statusvalue of N)
CLUSTERED CHAR(1) Yes Y = multi-dimensional clustering (MDC)table
Null for a non-MDC table
ACTIVE_BLOCKS INTEGER Yes Total number of in-use blocks in an MDCtable; −1 if statistics are not gathered.
REMARKS VARCHAR(254) Yes User-provided comment.
SYSCAT.TABLES
734 SQL Reference, Volume 1
SYSCAT.TABLESPACES
Contains a row for each table space.
Table 118. SYSCAT.TABLESPACES Catalog View
Column Name Data Type Nullable Description
TBSPACE VARCHAR(18) Name of table space.
DEFINER VARCHAR(128) Authorization ID of table space definer.
CREATE_TIME TIMESTAMP Creation time of table space.
TBSPACEID INTEGER Internal table space identifier.
TBSPACETYPE CHAR(1) The type of the table space:
S = System managed space
D = Database managed space
DATATYPE CHAR(1) Type of data that can be stored:
A = All types of permanent data
L = Large data - long data or index data
T = System temporary tables only
U = Declared temporary tables only
EXTENTSIZE INTEGER Size of extent, in pages of size PAGESIZE.This many pages are written to onecontainer in the table space before switchingto the next container.
PREFETCHSIZE INTEGER Number of pages of size PAGESIZE to beread when prefetch is performed.
OVERHEAD DOUBLE Controller overhead and disk seek andlatency time in milliseconds.
TRANSFERRATE DOUBLE Time to read one page of size PAGESIZEinto the buffer.
PAGESIZE INTEGER Size (in bytes) of pages in the table space.
DBPGNAME VARCHAR(18) Name of the database partition group forthe table space.
BUFFERPOOLID INTEGER ID of buffer pool used by this tablespace (1indicates default buffer pool).
DROP_RECOVERY CHAR(1) N = table is not recoverable after aDROP TABLE statement
Y = table is recoverable after a DROPTABLE statement
REMARKS VARCHAR(254) Yes User-provided comment.
SYSCAT.TABLESPACES
Appendix D. Catalog views 735
SYSCAT.TABOPTIONS
Each row contains option associated with a remote table.
Table 119. SYSCAT.TABOPTIONS Catalog View
Column Name Data Type Nullable Description
TABSCHEMA VARCHAR(128) Qualified name of table, view, alias ornickname.TABNAME VARCHAR(128)
OPTION VARCHAR(128) Name of the table, view, alias or nicknameoption.
SETTING VARCHAR(255) Value.
SYSCAT.TABOPTIONS
736 SQL Reference, Volume 1
SYSCAT.TBSPACEAUTH
Contains one row for each user or group who is granted USE privilege on aparticular table space in the database.
Table 120. SYSCAT.TBSPACEAUTH Catalog View
Column Name Data Type Nullable Description
GRANTOR CHAR(128) Authorization ID of the user who granted theprivileges or SYSIBM.
GRANTEE CHAR(128) Authorization ID of the user or group whoholds the privileges.
GRANTEETYPE CHAR(1) U = Grantee is an individual user.
G = Grantee is a group.
TBSPACE VARCHAR(18) Name of the table space.
USEAUTH CHAR(1) Indicates whether grantee holds USE privilegeon the table space:
G = Privilege is held and grantable.
N = Privilege is not held.
Y = Privilege is held.
SYSCAT.TBSPACEAUTH
Appendix D. Catalog views 737
SYSCAT.TRANSFORMS
Contains a row for each transform function type within a user-defined typecontained in a named transform group.
Table 121. SYSCAT.TRANSFORMS Catalog View
Column Name Data Type Nullable Description
TYPEID SMALLINT Internal type ID as defined inSYSCAT.DATATYPES
TYPESCHEMA VARCHAR(128) Qualified name of the given user-definedstructured type.TYPENAME VARCHAR(18)
GROUPNAME VARCHAR(18) Transform group name.
FUNCID INTEGER Yes Internal function ID for the associatedtransform function, as defined inSYSCAT.FUNCTIONS. Null only for internalsystem functions.
FUNCSCHEMA VARCHAR(128) Qualified name of the associated transformfunctions.FUNCNAME VARCHAR(18)
SPECIFICNAME VARCHAR(18) Function specific (instance) name.
TRANSFORMTYPE VARCHAR(8) 'FROM SQL' = Transform functiontransforms a structured type from SQL
'TO SQL' = Transform function transformsa structured type to SQL
FORMAT CHAR(1) 'U' = User defined
MAXLENGTH INTEGER Yes Maximum length (in bytes) of output fromthe FROM SQL transform. Null for TO SQLtransforms.
ORIGIN CHAR(1) 'O' = Original transform group (user- orsystem-defined)
'R' = Redefined
REMARKS VARCHAR(254) Yes User-supplied comment or null.
SYSCAT.TRANSFORMS
738 SQL Reference, Volume 1
SYSCAT.TRIGDEP
Contains a row for every dependency of a trigger on some other object.
Table 122. SYSCAT.TRIGDEP Catalog View
Column Name Data Type Nullable Description
TRIGSCHEMA VARCHAR(128) Qualified name of the trigger.
TRIGNAME VARCHAR(18)
BTYPE CHAR(1) Type of object BNAME:
A = Alias
B = Trigger
F = Function instance
N = Nickname
O = Privilege dependency on allsubtables or subviews in a table or viewhierarchy
R = Structured type
S = Materialized query table
T = Table
U = Typed table
V = View
W = Typed view
X = Index extension
BSCHEMA VARCHAR(128) Qualified name of object depended on by atrigger.BNAME VARCHAR(128)
TABAUTH SMALLINT Yes If BTYPE= O, S, T, U, V or W encodes theprivileges on the table or view that arerequired by this trigger; otherwise null.
SYSCAT.TRIGDEP
Appendix D. Catalog views 739
SYSCAT.TRIGGERS
Contains one row for each trigger. For table hierarchies, each trigger isrecorded only at the level of the hierarchy where it was created.
Table 123. SYSCAT.TRIGGERS Catalog View
Column Name Data Type Nullable Description
TRIGSCHEMA VARCHAR(128) Qualified name of the trigger.
TRIGNAME VARCHAR(18)
DEFINER VARCHAR(128) Authorization ID under which the trigger wasdefined.
TABSCHEMA VARCHAR(128) Qualified name of the table or view to whichthis trigger applies.
TABNAME VARCHAR(128)
TRIGTIME CHAR(1) Time when triggered actions are applied to thebase table, relative to the event that fired thetrigger:
A = Trigger applied after event
B = Trigger applied before event
I = Trigger applied instead of event
TRIGEVENT CHAR(1) Event that fires the trigger.
I = Insert
D = Delete
U = Update
GRANULARITY CHAR(1) Trigger is executed once per:
S = Statement
R = Row
VALID CHAR(1) Y = Trigger is valid
X = Trigger is inoperative; must bere-created.
CREATE_TIME TIMESTAMP Time at which the trigger was defined. Usedin resolving functions and types.
QUALIFIER VARCHAR(128) Contains value of the default schema at thetime of object definition.
FUNC_PATH VARCHAR(254) Function path at the time the trigger wasdefined. Used in resolving functions andtypes.
TEXT CLOB(64K) The full text of the CREATE TRIGGERstatement, exactly as typed.
REMARKS VARCHAR(254) Yes User-supplied comment, or null.
SYSCAT.TRIGGERS
740 SQL Reference, Volume 1
SYSCAT.TYPEMAPPINGS
Each row contains a user-defined mapping of a remote built-in data type to alocal built-in data type.
Table 124. SYSCAT.TYPEMAPPINGS Catalog View
Column Name Data Type Nullable Description
TYPE_MAPPING VARCHAR(18) Name of the type mapping (may besystem-generated).
TYPESCHEMA VARCHAR(128) Yes Schema name of the type. Null for systembuilt-in types.
TYPENAME VARCHAR(18) Name of the local type in a data typemapping.
TYPEID SMALLINT Type identifier.
SOURCETYPEID SMALLINT Source type identifier.
DEFINER VARCHAR(128) Authorization ID under which this typemapping was created.
LENGTH INTEGER Yes Maximum length or precision of the datatype. If null, the system determines the bestlength/precision.
SCALE SMALLINT Yes Scale for DECIMAL fields. If null, the systemdetermines the best scale attribute.
BIT_DATA CHAR(1) Yes Y = Type is for bit data.
N = Type is not for bit data.
NULL = This is not a character data typeor that the system determines the bit dataattribute.
WRAPNAME VARCHAR(128) Yes Mapping applies to this data access protocol.
SERVERNAME VARCHAR(128) Yes Name of the data source.
SERVERTYPE VARCHAR(30) Yes Mapping applies to this type of data source.
SERVERVERSION VARCHAR(18) Yes Mapping applies to this version ofSERVERTYPE.
REMOTE_TYPESCHEMA VARCHAR(128) Yes Schema name of the remote type.
REMOTE_TYPENAME VARCHAR(128) Name of the data type as defined on the datasource(s).
REMOTE_META_TYPE CHAR(1) Yes S = Remote type is a system built-in type.
T = Remote type is a distinct type.
SYSCAT.TYPEMAPPINGS
Appendix D. Catalog views 741
Table 124. SYSCAT.TYPEMAPPINGS Catalog View (continued)
Column Name Data Type Nullable Description
REMOTE_LOWER_LEN INTEGER Yes Lower bound of the length/precision of theremote decimal type. For character datatypes, this field indicates the number ofcharacter.
REMOTE_UPPER_LEN INTEGER Yes Upper bound of the length/precision of theremote decimal type. For character datatypes, this field indicates the number ofcharacter.
REMOTE_LOWER_SCALE SMALLINT Yes Lower bound of the scale of the remote type.
REMOTE_UPPER_SCALE SMALLINT Yes Upper bound of the scale of the remote type.
REMOTE_S_OPR_P CHAR(2) Yes Relationship between remote scale andremote precision. Basic comparison operatorscan be used. A null indicated that no specificrelationship is required.
REMOTE_BIT_DATA CHAR(1) Yes Y = Type is for bit data.
N = Type is not for bit data.
NULL = This is not a character data typeor that the system determines the bit dataattribute.
USER_DEFINED CHAR(1) Definition supplied by user.
CREATE_TIME TIMESTAMP Time when this mapping was created.
REMARKS VARCHAR(254) Yes User supplied comments, or null.
SYSCAT.TYPEMAPPINGS
742 SQL Reference, Volume 1
SYSCAT.USEROPTIONS
Each row contains server specific option values.
Table 125. SYSCAT.USEROPTIONS Catalog View
Column Name Data Type Nullable Description
AUTHID VARCHAR(128) Local authorization ID (always uppercase)
SERVERNAME VARCHAR(128) Name of the server for which the user isdefined.
OPTION VARCHAR(128) Name of the user options.
SETTING VARCHAR(255) Value.
SYSCAT.USEROPTIONS
Appendix D. Catalog views 743
SYSCAT.VIEWS
Contains one or more rows for each view that is created.
Table 126. SYSCAT.VIEWS Catalog View
Column Name Data Type Nullable Description
VIEWSCHEMA VARCHAR(128) Qualified name of a view or the qualifiedname of a table that is used to define amaterialized query table or a staging table.VIEWNAME VARCHAR(128)
DEFINER VARCHAR(128) Authorization ID of the creator of the view.
SEQNO SMALLINT Always 1.
VIEWCHECK CHAR(1) States the type of view checking:
N = No check option
L = Local check option
C = Cascaded check option
READONLY CHAR(1) Y = View is read-only because of itsdefinition.
N = View is not read-only.
VALID CHAR(1) Y = View or materialized query tabledefinition is valid.
X = View or materialized query tabledefinition is inoperative; must bere-created.
QUALIFIER VARCHAR(128) Contains value of the default schema at thetime of object definition.
FUNC_PATH VARCHAR(254) The SQL path of the view creator at thetime the view was defined. When the viewis used in data manipulation statements,this path must be used to resolve functioncalls in the view. SYSIBM for views createdbefore Version 2.
TEXT CLOB(64k) Text of the CREATE VIEW statement.
SYSCAT.VIEWS
744 SQL Reference, Volume 1
SYSCAT.WRAPOPTIONS
Each row contains wrapper specific options.
Table 127. SYSCAT.WRAPOPTIONS Catalog View
Column Name Data Type Nullable Description
WRAPNAME VARCHAR(128) Wrapper name.
OPTION VARCHAR(128) Name of wrapper option.
SETTING VARCHAR(255) Value.
SYSCAT.WRAPOPTIONS
Appendix D. Catalog views 745
SYSCAT.WRAPPERS
Each row contains information on the registered wrapper.
Table 128. SYSCAT.WRAPPERS Catalog View
Column Name Data Type Nullable Description
WRAPNAME VARCHAR(128) Wrapper name.
WRAPTYPE CHAR(1) N = Non-relational
R = Relational
WRAPVERSION INTEGER Version of the wrapper.
LIBRARY VARCHAR(255) Name of the file that contains the code used tocommunicate with the data sources associatedwith this wrapper.
REMARKS VARCHAR(254) Yes User supplied comment, or null.
SYSCAT.WRAPPERS
746 SQL Reference, Volume 1
SYSSTAT.COLDIST
Each row describes the Nth-most-frequent value or Nth quantile value ofsome column. Statistics are not recorded for inherited columns of typed tables.
Table 129. SYSSTAT.COLDIST Catalog View
Column Name Data Type Nullable Description Updatable
TABSCHEMA VARCHAR(128) Qualified name of the table towhich this entry applies.
TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Name of the column to whichthis entry applies.
TYPE CHAR(1) Type of statistic collected:
F = Frequency (most frequentvalue)
Q = Quantile value
SEQNO SMALLINT If TYPE = F, then N in thiscolumn identifies the Nth mostfrequent value. If TYPE = Q,then N in this column identifiesthe Nth quantile value.
COLVALUE VARCHAR(254) Yes The data value, as a characterliteral or a null value.
This column can be updatedwith a valid representation ofthe value appropriate to thecolumn that the statistic isassociated with. If null is therequired frequency value, thecolumn should be set to NULL.
Yes
VALCOUNT BIGINT If TYPE = F, then VALCOUNT isthe number of occurrences ofCOLVALUE in the column. IfTYPE = Q, then VALCOUNT isthe number of rows whose valueis less than or equal toCOLVALUE.
This column can be onlyupdated with the followingvalues:
v >= 0 (zero)
Yes
SYSSTAT.COLDIST
Appendix D. Catalog views 747
Table 129. SYSSTAT.COLDIST Catalog View (continued)
Column Name Data Type Nullable Description Updatable
DISTCOUNT BIGINT If TYPE = q, this column recordsthe number of distinct valuesthat are less than or equal toCOLVALUE (null if unavailable.)the number of rows whose valueis less than or equal toCOLVALUE.
Yes
SYSSTAT.COLDIST
748 SQL Reference, Volume 1
SYSSTAT.COLUMNS
Contains one row for each column for which statistics can be updated.Statistics are not recorded for inherited columns of typed tables.
Table 130. SYSSTAT.COLUMNS Catalog View
ColumnName
Data Type Nullable Description Updatable
TABSCHEMA VARCHAR(128) Qualified name of the table that containsthe column.TABNAME VARCHAR(128)
COLNAME VARCHAR(128) Column name.
COLCARD BIGINT Number of distinct values in the column;−1 if statistics are not gathered; −2 forinherited columns and columns ofH-tables.
For any column, COLCARD cannot havea value higher than the cardinality of thetable containing that column.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
HIGH2KEY VARCHAR(33) Yes Second highest value of the column. Thisfield is empty if statistics are not gatheredand for inherited columns and columns ofH-tables.
This column can be updated with a validrepresentation of the value appropriate tothe column that the statistic is associatedwith.
LOWKEY2 should not be greater thanHIGH2KEY.
Yes
LOW2KEY VARCHAR(33) Yes Second lowest value of the column.Empty if statistics not gathered and forinherited columns and columns ofH-tables.
This column can be updated with a validrepresentation of the value appropriate tothe column that the statistic is associatedwith.
Yes
SYSSTAT.COLUMNS
Appendix D. Catalog views 749
Table 130. SYSSTAT.COLUMNS Catalog View (continued)
ColumnName
Data Type Nullable Description Updatable
AVGCOLLEN INTEGER Average column length. −1 if a long fieldor LOB, or statistics have not beencollected; −2 for inherited columns andcolumns of H-tables.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
NUMNULLS BIGINT Contains the number of nulls in a column.−1 if statistics are not gathered.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
SUB_COUNT SMALLINT Average number of sub-elements. Onlyapplicable for character columns. Forexample, consider the following string:’database simulation analytical businessintelligence’. In this example,SUB_COUNT = 5, because there are 5sub-elements in the string.
SUB_DELIM_LENGTH
SMALLINT Average length of each delimiterseparating each sub-element. Onlyapplicable for character columns. Forexample, consider the following string:’database simulation analytical businessintelligence’. In this example,SUB_DELIM_LENGTH = 1, because eachdelimiter is a single blank.
SYSSTAT.COLUMNS
750 SQL Reference, Volume 1
SYSSTAT.INDEXES
Contains one row for each index that is defined for a table.
Table 131. SYSSTAT.INDEXES Catalog View
Column Name Data Type Nullable Description Updatable
INDSCHEMA VARCHAR(128) Qualified name of the index.
INDNAME VARCHAR(18)
TABSCHEMA VARCHAR(128) Qualifier of the table name.
TABNAME VARCHAR(128) Name of the table or nickname onwhich the index is defined.
COLNAMES CLOB(1M) List of column names with + or −prefixes.
NLEAF INTEGER Number of leaf pages; −1 if statisticsare not gathered.
This column can only be updated withthe following values:
v −1 or > 0 (zero)
Yes
NLEVELS SMALLINT Number of index levels; −1 if statisticsare not gathered.
This column can only be updated withthe following values:
v −1 or > 0 (zero)
Yes
FIRSTKEYCARD BIGINT Number of distinct first key values; −1if statistics are not gathered.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
FIRST2KEYCARD BIGINT Number of distinct keys using the firsttwo columns of the index (−1 if nostatistics, or not applicable).
This column can only be updated withthe following values;
v −1 or >= 0 (zero)
Yes
SYSSTAT.INDEXES
Appendix D. Catalog views 751
Table 131. SYSSTAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description Updatable
FIRST3KEYCARD BIGINT Number of distinct keys using the firstthree columns of the index (−1 if nostatistics, or not applicable).
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
FIRST4KEYCARD BIGINT Number of distinct keys using the firstfour columns of the index (−1 if nostatistics, or not applicable).
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
FULLKEYCARD BIGINT Number of distinct full key values; −1if statistics are not gathered.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
CLUSTERRATIO SMALLINT This column is used by the optimizer.It indicates the degree of dataclustering with the index; −1 ifstatistics are not gathered, or ifdetailed index statistics have beengathered.
This column can only be updated withthe following values:
v −1 or between 0 and 100
Yes
CLUSTERFACTOR DOUBLE This column is used by the optimizer.It is a finer measurement of degree ofclustering, or −1 if detailed indexstatistics have not been gathered.
This column can only be updated withthe following values:
v −1 or between 0 and 1
Yes
SYSSTAT.INDEXES
752 SQL Reference, Volume 1
Table 131. SYSSTAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description Updatable
SEQUENTIAL_PAGES INTEGER Number of leaf pages located on diskin index key order with few or nolarge gaps between them; −1 if nostatistics are available.
This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
DENSITY INTEGER Ratio of SEQUENTIAL_PAGES tonumber of pages in the range of pagesoccupied by the index, expressed as apercent (integer between 0 and 100; −1if no statistics are available.)
This column can only be updated withthe following values:
v −1 or between 0 and 100
Yes
PAGE_FETCH_PAIRS VARCHAR(254) A list of pairs of integers, representedin character form. Each pair representsthe number of pages in a hypotheticalbuffer, and the number of page fetchesrequired to scan the index using thathypothetical buffer. (Zero-length stringif no data available.)
This column can be updated with thefollowing input values:
v The pair delimiter and pairseparator characters are the onlynon-numeric characters accepted.
v Blanks are the only charactersrecognized as a pair delimiter andpair separator.
v Each number entry must have anaccompanying partner number entrywith the two being separated by thepair separator character.
v Each pair must be separated fromany other pairs by the pair delimitercharacter.
v Each expected number entry mustbetween 0-9 (positive values only).
Yes
NUMRIDS BIGINT Number of RIDs in the index; −1 ifstatistics are not gathered.
Yes
SYSSTAT.INDEXES
Appendix D. Catalog views 753
Table 131. SYSSTAT.INDEXES Catalog View (continued)
Column Name Data Type Nullable Description Updatable
NUMRIDS_DELETED BIGINT Number of RIDs in the index that aremarked deleted, excluding the ones onpages on which all RIDs are markeddeleted; −1 if statistics are notgathered.
Yes
NUM_EMPTY_LEAFS BIGINT Number of leaf pages in the index onwhich all RIDs are marked deleted; −1if statistics are not gathered.
Yes
AVERAGE_RANDOM_FETCH_PAGES
DOUBLE Average number of random tablepages between sequential pageaccesses when fetching using theindex; −1 if it is not known.
AVERAGE_RANDOM_PAGES
DOUBLE Average number of random indexpages between sequential index pageaccesses; −1 if it is not known.
AVERAGE_SEQUENCE_GAP
DOUBLE Gap between index page sequences.Detected through a scan of index leafpages, each gap represents the averagenumber of index pages that must berandomly fetched between sequencesof index pages; −1 if it is not known.
AVERAGE_SEQUENCE_FETCH_GAP
DOUBLE Gap between table page sequenceswhen fetching using the index.Detected through a scan of index leafpages, each gap represents the averagenumber of table pages that must berandomly fetched between sequencesof table pages; −1 if it is not known.
AVERAGE_SEQUENCE_PAGES
DOUBLE Average number of index pagesaccessible in sequence (that is, thenumber of index pages that theprefetchers would detect as being insequence); −1 if it is not known.
AVERAGE_SEQUENCE_FETCH_PAGES
DOUBLE Average number of table pagesaccessible in sequence (that is, thenumber of table pages that theprefetchers would detect as being insequence) when fetching using theindex; −1 if it is not known.
SYSSTAT.INDEXES
754 SQL Reference, Volume 1
SYSSTAT.ROUTINES
Contains a row for each user-defined function (scalar, table, or source),system-generated method, user-defined method, or procedure. Does notinclude built-in functions. (This catalog view supercedesSYSSTAT.FUNCTIONS. The other view exists, but will remain as it was inDB2 Version 7.1.)
Table 132. SYSSTAT.ROUTINES Catalog View
Column Name Data Type Nullable Description Updatable
ROUTINESCHEMA VARCHAR(128) Qualified routine name.
ROUTINENAME VARCHAR(18)
ROUTINETYPE CHAR(1) F = Function
M = Method
P = Procedure.
SPECIFICNAME VARCHAR(18) The name of the routine instance (maybe system-generated).
IOS_PER_INVOC DOUBLE Estimated number of I/Os perinvocation; −1 if not known (0 default).This column can only be updated with−1 or >= 0 (zero).
Yes
INSTS_PER_INVOC DOUBLE Estimated number of instructions perinvocation; −1 if not known (450default). This column can only beupdated with −1 or >= 0 (zero).
Yes
IOS_PER_ARGBYTE DOUBLE Estimated number of I/Os per inputargument byte; −1 if not known (0default). This column can only beupdated with −1 or >= 0 (zero).
Yes
INSTS_PER_ARGBYTE DOUBLE Estimated number of instructions perinput argument byte; −1 if not known(0 default). This column can only beupdated with −1 or >= 0 (zero).
Yes
PERCENT_ARGBYTE SMALLINT Estimated average percent of inputargument bytes that the routine willactually read; −1 if not known (100default). This column can only beupdated with −1 or a number between0 (zero) and 100.
Yes
SYSSTAT.ROUTINES
Appendix D. Catalog views 755
Table 132. SYSSTAT.ROUTINES Catalog View (continued)
Column Name Data Type Nullable Description Updatable
INITIAL_IOS DOUBLE Estimated number of I/Os performedthe first/last time the routine isinvoked; −1 if not known (0 default).This column can only be updated with−1 or >= 0 (zero).
Yes
INITIAL_INSTS DOUBLE Estimated number of instructionsexecuted the first/last time the routineis invoked; −1 if not known (0 default).This column can only be updated with−1 or >= 0 (zero).
Yes
CARDINALITY BIGINT The predicted cardinality of a tablefunction; −1 if not known, or if theroutine is not a table function. Thiscolumn can only be updated with −1 or>= 0 (zero).
Yes
SELECTIVITY DOUBLE Used for user-defined predicates; −1 ifthere are no user-defined predicates.See Note 1.
Notes:
1. This column will be set to −1 during migration from DB2 Version 5.2 to 8.1 in the system catalogs forall user-defined functions. For a user-defined predicate, the selectivity in the system catalog will be−1. In this case, the selectivity value used by the optimizer is 0.01.
SYSSTAT.ROUTINES
756 SQL Reference, Volume 1
SYSSTAT.TABLES
Contains one row for each base table. Views or aliases are, therefore, notincluded. For typed tables, only the root table of a table hierarchy is includedin this view. Statistics are not recorded for inherited columns of typed tables.The CARD value applies to the root table only while the other statistics applyto the entire table hierarchy.
Table 133. SYSSTAT.TABLES Catalog View
ColumnName
Data Type Nullable Description Updatable
TABSCHEMA VARCHAR(128) Qualified name of the table.
TABNAME VARCHAR(128)
CARD BIGINT Total number of rows in the table; −1 ifstatistics are not gathered. An update toCARD for a table should not attempt toassign it a value less than the COLCARDvalue of any of the columns in that table.A value of −2 cannot be changed and acolumn value cannot be directly set to −2.This column can only be updated withthe following values:
v −1 or >= 0 (zero)
Yes
NPAGES INTEGER Total number of pages on which the rowsof the table exist; −1 if statistics are notgathered, and −2 for subtables andH-tables. A value of −2 cannot be changedand a column value cannot be directly setto −2. This column can only be updatedwith the following values:
v −1 or >= 0 (zero)
Yes
FPAGES INTEGER Total number of pages in the file; −1 ifstatistics are not gathered, and −2 forsubtables and H-tables. A value of −2cannot be changed and a column valuecannot be directly set to −2. This columncan only be updated with the followingvalues:
v −1 or > 0 (zero)
Yes
ACTIVE_BLOCKS
INTEGER Total number of in-use blocks in amulti-dimensional clustering (MDC) table;−1 if statistics are not gathered.
Yes
SYSSTAT.TABLES
Appendix D. Catalog views 757
Table 133. SYSSTAT.TABLES Catalog View (continued)
ColumnName
Data Type Nullable Description Updatable
OVERFLOW INTEGER Total number of overflow records in thetable; −1 if statistics are not gathered, and−2 for subtables and H-tables. A value of−2 cannot be changed and a column valuecannot be directly set to −2. This columncan only be updated with the followingvalues:
v −1 or >= 0 (zero)
Yes
SYSSTAT.TABLES
758 SQL Reference, Volume 1
Appendix E. Federated systems
Valid server types in SQL statements
Server types indicate what kind of data source the server will represent.Server types vary by vendor, purpose, and operating system. Supportedvalues depend on the wrapper being used.
You need to specify a valid server type in the CREATE SERVER statement.
CTLIB wrapperSybase data sources supported by Sybase CTLIB client software
Server Type Data Source
SYBASE Sybase
DBLIB wrapperSybase or Microsoft SQL Server data sources supported by DBLIB clientsoftware
Server Type Data Source
SYBASE Sybase
DJXMSSQL3 wrapperMicrosoft SQL Server data sources supported by ODBC 3.0 (or higher) driver
Server Type Data Source
MSSQLSERVER Microsoft SQL Server
DRDA wrapperDB2 Family
Table 134. IBM DB2 for UNIX and Windows
Server Type Data Source
DB2/UDB IBM DB2 Universal Database
DATAJOINER IBM DB2 DataJoiner V2.1 and V2.1.1
DB2/6000 IBM DB2 for AIX
DB2/AIX IBM DB2 for AIX
© Copyright IBM Corp. 1993 - 2002 759
Table 134. IBM DB2 for UNIX and Windows (continued)
Server Type Data Source
DB2/HPUX IBM DB2 for HP-UX V1.2
DB2/HP IBM DB2 for HP-UX
DB2/NT IBM DB2 for Windows NT
DB2/EEE IBM DB2 Enterprise-Extended Edition
DB2/CS IBM DB2 for Common Server
DB2/SUN IBM DB2 for Solaris V1 and V1.2
DB2/PE IBM DB2 for Personal Edition
DB2/2 IBM DB2 for OS/2
DB2/LINUX IBM DB2 for Linux
DB2/PTX IBM DB2 for NUMA-Q
DB2/SCO IBM DB2 for SCO Unixware
Table 135. IBM DB2 for iSeries (and AS/400)
Server Type Data Source
DB2/400 IBM DB2 for iSeries and AS/400
Table 136. IBM DB2 for z/OS and OS/390
Server Type Data Source
DB2/ZOS IBM DB2 for z/OS
DB2/390 IBM DB2 for OS/390
DB2/MVS IBM DB2 for MVS
Table 137. IBM DB2 Server for VM and VSE
Server Type Data Source
DB2/VM IBM DB2 for VM
DB2/VSE IBM DB2 for VSE
SQL/DS IBM SQL/DS
760 SQL Reference, Volume 1
Informix wrapperInformix data sources supported by Informix Client SDK software
Server Type Data Source
INFORMIX Informix
MSSQLODBC3 wrapperMicrosoft SQL Server data sources supported by DataDirect Connect ODBC3.6 driver
Server Type Data Source
MSSQLSERVER Microsoft SQL Server
NET8 wrapperOracle data sources supported by Oracle Net8 client software.
Server Type Data Source
ORACLE Oracle Version 8.0. or later
ODBC wrapperODBC data sources supported by the ODBC 3.0 driver.
Server Type Data Source
ODBCSERVER ODBC
OLE DB wrapperOLE DB providers compliant with Microsoft OLE DB 2.0 or later.
Server Type Data Source
none required Any OLE DB provider
SQLNET wrapperOracle data sources supported by Oracle SQL*Net V1 or V2 client software.
Server Type Data Source
ORACLE Oracle V7.3. or later
Appendix E. Federated systems 761
Column options for federated systems
You can specify column information in the CREATE NICKNAME or ALTERNICKNAME statements using parameters called column options. The primarypurpose of column options is to provide information about nickname columnsto the SQL Compiler. Setting column options for one or more columns to ’Y’allows the SQL Compiler to consider additional pushdown possibilities forpredicates that perform evaluation operation. This assists the Compiler inreaching global optimization.You can specify any of these values in eitherupper- or lowercase.
Note: The Life Sciences Data Connect wrappers allow additional columnoptions.
Table 138. Column options and their settings
Option Valid settings Defaultsetting
NUMERIC_STRING‘Y’ Yes, this column contains strings of numeric characters
’0’, ’1’, ’2’, .... ’9’. It does not contain blanks.IMPORTANT: If this column contains only numericstrings followed by trailing blanks, it is inadvisable tospecify ‘Y’.
‘N’ No, this column is either not a numeric string columnor is a numeric string column that contains blanks.
By setting NUMERIC_STRING to ‘Y’ for a column, you areinforming the optimizer that this column contains no blanksthat could interfere with sorting of the column’s data. Thisoption is helpful when the collating sequence of a data source isdifferent from DB2. Columns marked with this option will notbe excluded from remote evaluation because of a differentcollating sequence.
‘N’
VARCHAR_NO_TRAILING_BLANKS
This option applies to data sources which have variablecharacter data types that do not pad the lenght with trailingblanks.
‘Y’ Yes, trailing blanks are absent from this VARCHARcolumn.
‘N’ No, trailing blanks are present in this VARCHARcolumn.
Some data sources, such as Oracle, have non-blank-paddedcomparison semantics that return the same results as the DB2for UNIX and Windows comparison semantics. Set this optionwhen you want it to apply only to a specifc VARCHAR orVARCHAR2 column in a data source object.
‘N‘
762 SQL Reference, Volume 1
Related concepts:
v “Fast track to configuring your data sources” in the Federated Systems Guide
v “Column options” on page 53v “Pushdown analysis” in the Federated Systems Guide
Related tasks:
v “Global optimization” in the Federated Systems Guide
Function mapping options for federated systems
DB2 supplies default mappings between existing built-in data source functionsand built-in DB2 functions. For most data sources, the default functionmappings are in the wrappers. To use a data source function that thefederated server does not recognize, you must create a function mappingbetween a data source function and a counterpart function at the federateddatabase.
The primary purpose of function mapping options, is to provide informationabout the potential cost of executing a data source function at the data source.Pushdown analysis determines if a function at the data source is able toexecute a function in a query. The query optimizer decides if pushing downthe function processing to the data source is the least cost alternative.
The statistical information provided in the function mapping definition helpsthe query optimizer compare the estimated cost of executing the data sourcefunction with the estimated cost of executing the DB2 function.
Table 139. Function mapping options and their settings
Option Valid settings Defaultsetting
DISABLE Disable a default function mapping. Valid values are‘Y’ and ‘N’.
‘N’
INITIAL_INSTS Estimated number of instructions processed the firstand last time that the data source function isinvoked.
‘0’
INITIAL_IOS Estimated number of I/Os performed the first andlast time that the data source function is invoked.
‘0’
IOS_PER_ARGBYTE Estimated number of I/Os expended for each byte ofthe argument set that’s passed to the data sourcefunction.
‘0’
IOS_PER_INVOC Estimated number of I/Os per invocation of a datasource function.
‘0’
Appendix E. Federated systems 763
Table 139. Function mapping options and their settings (continued)
Option Valid settings Defaultsetting
INSTS_PER_ARGBYTE Estimated number of instructions processed for eachbyte of the argument set that’s passed to the datasource function.
‘0’
INSTS_PER_INVOC Estimated number of instructions processed perinvocation of the data source function.
‘450’
PERCENT_ARGBYTES Estimated average percent of input argument bytesthat the data source function will actually read.
‘100’
REMOTE_NAME Name of the data source function. localname
Server options for federated systems
Server options are used with the CREATE SERVER statement to describe adata source server. Server options specify data integrity, location, security, andperformance information. Some server options are data source specific, andare noted in the following table. Life Sciences data sources have additional,very specific server options.
The common federated server options are:v Compatibility options. COLLATING_SEQUENCE, IGNORE_UDTv Data integrity options. IUD_APP_SVPT_ENFORCEv Location options. CONNECTSTRING, DBNAME, IFILEv Security options. FOLD_ID, FOLD_PW, PASSWORDv Performance options. COMM_RATE, CPU_RATIO, IO_RATIO,
LOGIN_TIMEOUT, PACKET_SIZE, PLAN_HINTS, PUSHDOWN,TIMEOUT, VARCHAR_NO_TRAILING_BLANKS
764 SQL Reference, Volume 1
Table 140. Server options and their settings
Option Valid settings Defaultsetting
Applies to
COLLATING_SEQUENCE Specifies whether the data source uses the samedefault collating sequence as the federateddatabase, based on the NLS code set and thecountry information.
’Y’ The data source has the same collatingsequence as the DB2 federateddatabase.
’N’ The data source has a differentcollating sequence than the DB2federated database collating sequence.
’I’ The data source has a differentcollating sequence than the DB2federated database collating sequence,and the data source collating sequenceis insensitive to case (for example,’STEWART’ and ’StewART’ areconsidered equal).
’N’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
COMM_RATE Specifies the communication rate between thefederated server and the data source server.Expressed in megabytes per second.
Valid values are greater than 0 and less than2147483648. Values may be expressed as wholenumbers only, for example 12.
’2’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
CONNECTSTRING Specifies initialization properties needed toconnect to an OLE DB provider.
None OLE DB
Appendix E. Federated systems 765
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
CPU_RATIO Indicates how much faster or slower a datasource’s CPU runs than the federated server’sCPU.
Valid values are greater than 0 and less than1x1023 . Values may be expressed in any validdouble notation, for example 123E10, 123, or1.21E4.
’1.0’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
DBNAME Name of the data source database that youwant the federated server to access. For DB2,this value corresponds to a specific databasewithin an instance or, with DB2 for z/OS orOS/390, the database LOCATION value. Doesnot apply to Oracle data sources because Oracleinstances contain only one database.
None. DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Sybase
766 SQL Reference, Volume 1
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
FOLD_ID
(See notes 1 and 4 at theend of this table.)
Applies to user IDs that the federated serversends to the data source server forauthentication. Valid values are:
’U’ The federated server folds the user IDto uppercase before sending it to thedata source. This is a logical choice forDB2 family and Oracle data sources(See note 2 at end of this table.)
’N’ The federated server does nothing tothe user ID before sending it to thedata source. (See note 2 at end of thistable.)
’L’ The federated server folds the user IDto lowercase before sending it to thedata source.
If none of these settings are used, the federatedserver tries to send the user ID to the datasource in uppercase. If the user ID fails, theserver tries sending it in lowercase.
None. DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
FOLD_PW
(See notes 1, 3 and 4 at theend of this table.)
Applies to passwords that the federated serversends to data sources for authentication. Validvalues are:
’U’ The federated server folds thepassword to uppercase before sendingit to the data source. This is a logicalchoice for DB2 family and Oracle datasources.
’N’ The federated server does nothing tothe password before sending it to thedata source.
’L’ The federated server folds thepassword to lowercase before sendingit to the data source.
If none of these settings are used, the federatedserver tries to send the password to the datasource in uppercase. If the password fails, theserver tries sending it in lowercase.
None. DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
Appendix E. Federated systems 767
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
IFILE Specifies the path and name of the Sybase OpenClient interfaces file. On Windows NT federatedservers, the default is %DB2PATH%\interfaces.On UNIX federated servers, the default pathand name value is$DB2INSTANCE/sqllib/interfaces.
None. Sybase
768 SQL Reference, Volume 1
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
IGNORE_UDT Specifies whether the federated server shoulddetermine the built-in type that underlies aUDT without strong typing. Applies only todata sources accessed through the CTLIB andDBLIB protocols. Valid values are:
’Y’ Ignore the fact that UDTs areuser-defined and determine whatbuilt-in types under lie them.
’N’ Do not ignore user-definedspecifications of UDTs.
When DB2 creates nicknames, it looks for andcatalogs information about the objects (tables,views, stored procedures) that the nicknamespoint to. As it looks for the information, itmight find that some objects have data typesthat it doesn’t recognize (that is, data types thatdon’t map to counterparts at the federateddatabase). Such unrecognizable types caninclude:
v New built-in types
v UDTs with strong typing
v UDTs without strong typing. These arebuilt-in types that the user has simplyrenamed. These types are supported only bycertain data sources, such as Sybase andMicrosoft SQL Server.
When the federated server data types that itdoesn’t recognize, it returns the error message,SQL3324N. However, it can make an exceptionto this practice. For data sources accessiblethrough the CTLIB or DBLIB protocols, you canset the IGNORE_UDT server option so thatwhen the federated database encounters anunrecognizable UDT without strong typing, thefederated database determines what the UDT’sunderlying built-in type is. Then, if thefederated database recognizes this built-in type,the federated database returns informationabout the built-in type to the catalog. To havethe federated database determine theunderlying built-in types of UDTs that do nothave strong typing, set IGNORE_UDT to ’Y’.
’N’ Sybase
Appendix E. Federated systems 769
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
IO_RATIO Denotes how much faster or slower a datasource’s I/O system runs than the federatedserver’s I/O system.
Valid values are greater than 0 and less than1x1023 . Values may be expressed in any validdouble notation, for example 123E10, 123, or1.21E4.
’1.0’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
IUD_APP_SVPT_ENFORCE Specifies whether DB2 federated system shouldenforce detecting or building of applicationsavepoint statements.
’Y’ The federated server will not allowINSERT, UPDATE, or DELETEstatements on nicknames if the datasource does not support applicationsavepoint statements. A SQL error code(SQL20190) will be generated whenDB2 cannot perform atomic INSERT,UPDATE, or DELETE.
’N’ The federated server will allowINSERT, UPDATE, or DELETEstatements on nicknames.
’Y’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
LOGIN_TIMOUT Specifies the number of seconds for the DB2federated server to wait for a response fromSybase Open Client to the login request. Thedefault values are the same as for TIMEOUT.
’0’ Sybase
NODE Name by which a data source is defined as aninstance to its RDBMS.
None. Informix,MS SQLServer,Oracle,Sybase
770 SQL Reference, Volume 1
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
PACKET_SIZE Specifies the packet size of the Sybase interfacesfile in bytes. If the data source does not supportthe specified packet size, the connection willfail. Increasing the packet size when each recordis very large (for example, when inserting rowsinto large tables) significantly increasesperformance. The byte size is a numeric value.
Sybase
PASSWORD Specifies whether passwords are sent to a datasource.
’Y’ Passwords are always sent to the datasource and validated. This is thedefault value.
’N’ Passwords are not sent to the datasource (regardless of any usermappings) and not validated.
’ENCRYPTION’Passwords are always sent to the datasource in encrypted form andvalidated. Valid only for DB2 familydata sources that support encryptedpasswords.
’Y’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
PLAN_HINTS Specifies whether plan hints are to be enabled.Plan hints are statement fragments that provideextra information for data source optimizers.This information can, for certain query types,improve query performance. The plan hints canhelp the data source optimizer decide whetherto use an index, which index to use, or whichtable join sequence to use.
’Y’ Plan hints are to be enabled at the datasource if the data source supports planhints.
’N’ Plan hints are not to be enabled at thedata source.
’N’ Informix,MS SQLServer,ODBC,Oracle,Sybase
Appendix E. Federated systems 771
Table 140. Server options and their settings (continued)
Option Valid settings Defaultsetting
Applies to
PUSHDOWN’Y’ DB2 will consider letting the data
source evaluate operations.
’N’ DB2 will only retrieve columns fromthe remote data source and will not letthe data source evaluate otheroperations, such as joins.
’Y’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
TIMEOUT Specifies the number of seconds the DB2federated server will wait for a response fromSybase Open Client for any SQL statement. Thevalue of seconds is a positive whole number inDB2 Universal Database’s integer range. Thetimeout value that you specify depends onwhich wrapper you are using. The defaultbehavior of the TIMEOUT option for the Sybasewrappers is 0, which causes DB2 to waitindefinitely for a response.
’0’ Sybase
VARCHAR_NO_TRAILING_BLANKS
This option applies to data sources which havevariable character data types that do not padthe length with trailing blanks. Some datasources, such as Oracle, have non-blank-paddedcomparison semantics that return the sameresults as the DB2 for UNIX and Windowscomparison semantics. Set this option when youwant it to apply to all the VARCHAR andVARCHAR2 columns in the data source objectsthat will be accessed from the designatedserver. This includes views.
’Y’ This data source has non-blank-paddedcomparison semantics similar to thefederated server.
’N’ This data source has differentvarying-length character comparisonsemantics than the federated server.
’N’ DB2 foriSeries
DB2 forz/OS andOS/390
DB2 forUNIX andWindows
Informix,MS SQLServer,ODBC,Oracle,Sybase
772 SQL Reference, Volume 1
Notes on this table:1. This field is applied regardless of the value specified for authentication.2. Because DB2 stores user IDs in uppercase, the values ‘N’ and ‘U’ are
logically equivalent to each other.3. The setting for FOLD_PW has no effect when the setting for password is
‘N’. Because no password is sent, case cannot be a factor.4. Avoid null settings for either of these options. A null setting may seem
attractive because DB2 will make multiple attempts to resolve user IDsand passwords; however, performance might suffer (it is possible that DB2will send a user ID and password four times before successfully passingdata source authentication).
Related concepts:
v “Server definitions and server options” on page 50v “Server characteristics affecting pushdown opportunities” in the Federated
Systems Guide
v “Server characteristics affecting global optimization” in the Federated SystemsGuide
Related tasks:
v “Registering the server for table-structured files” in the DB2 Life SciencesData Connect Planning, Installation, and Configuration Guide
v “Registering the server for Documentum data sources” in the DB2 LifeSciences Data Connect Planning, Installation, and Configuration Guide
v “Registering the server for an Excel data source” in the DB2 Life SciencesData Connect Planning, Installation, and Configuration Guide
v “Registering the server for a BLAST data source” in the DB2 Life SciencesData Connect Planning, Installation, and Configuration Guide
v “Registering the server for an XML data source” in the DB2 Life SciencesData Connect Planning, Installation, and Configuration Guide
Related reference:
v “CREATE SERVER statement” in the SQL Reference, Volume 2
User options for federated systems
User options provide authorization and accounting string information for usermappings between the federated server and a data source. These options canbe used with any data source that supports user ID and passwordauthorization.
These options are used with the CREATE USER MAPPING statement.
Appendix E. Federated systems 773
Table 141. User Options and their settings
Option Valid settings Defaultsetting
ACCOUNTING_STRING Used to specify a DRDA accounting string. Valid settingsinclude any string of length 255 or less. This option is requiredonly if accounting information needs to be passed. See the DB2Connect Users Guide for more information.
None
REMOTE_AUTHID Indicates the authorization ID used at the data source. Validsettings include any string of length 255 or less. If this option isnot specified, the ID used to connect to database is used.
None
REMOTE_DOMAIN Indicates the Windows NT domain used to authenticate usersconnecting to this data source. Valid settings include any validWindows NT domain name. If this option is not specified, thedata source will authenticate using the default authenticationdomain for that database.
None
REMOTE_PASSWORD Indicates the authorization password used at the data source.Valid settings include any string of length 32 or less. If thisoption is not specified, the password used to connect to thedatabase is used.
None
Related concepts:
v “DB2 Connect and DRDA” in the DB2 Connect User’s Guide
v “DRDA and data access” in the DB2 Connect User’s Guide
Wrapper options for federated systems
Wrapper options are used to configure the wrapper or to define how DB2 usesthe wrapper. Currently, there is only one wrapper option, DB2_FENCED. TheDB2_FENCED wrapper option indicates if the wrapper is fenced or trusted byDB2. A fenced wrapper operates under some restrictions.
If you did not explicitly set the DB2_FENCED wrapper option to ’N’, you canalter the wrapper to include this option. If you have scripts or applicationsthat you use for DDL statements, consider using this option. Even though thecurrent default setting for DB2_FENCED is ’N’, it is possible that IBM willchange the default setting in the future. When the default changes, anywrappers created without this option will adhere to the new default. If youexplicitly set the DB2_FENCED wrapper to ’N’, you can ensure that thebehavior of the wrapper will not change when you run the scripts orapplications.
774 SQL Reference, Volume 1
Table 142. Wrapper options and their settings
Option Valid settings Defaultsetting
DB2_FENCED Indicates if the wrapper is fenced or trusted byDB2.
’N’ The tasks performed by the wrapper arenot restricted.
’N’
Related concepts:
v “Create the wrapper” in the Federated Systems Guide
v “Wrappers and wrapper modules” on page 48v “Modifying wrappers” in the Federated Systems Guide
Default forward data type mappings
When a nickname is created for a data source object, DB2 for UNIX andWindows populates the global catalog with information about the table.
This information includes the remote data type for each column, and thecorresponding DB2 for UNIX and Windows data type. The DB2 for UNIX andWindows data type is referred to as the local data type.
The federated database uses data type mappings to determine which DB2 forUNIX and Windows data type should be defined for the column of a datasource object.
The data types at the data source must map to corresponding DB2 for UNIXand Windows data types so that the federated server can retrieve data fromdata sources. For most data sources, the default type mappings are in thewrappers. The default type mappings for DB2 family data sources are in theDRDA wrapper. The default type mappings for Informix are in theINFORMIX wrapper, and so forth.
DB2 for UNIX and Windows federated servers do not support mappings forthese data types: LONG VARCHAR, LONG VARGRAPHIC, DATALINK, anduser-defined types.
There are two kinds of mappings between data source data types andfederated database data types: forward type mappings and reverse typemappings. In a forward type mapping, the mapping is from a remote type to acomparable local type.
Appendix E. Federated systems 775
You can override a default type mapping, or create a new type mapping withthe CREATE TYPE MAPPING statement.
The following tables show the default forward mappings between DB2 forUNIX and Windows data types and data source data types.
These mappings are valid with all the supported versions, unless otherwisenoted.
Note: For all default forward data types mapping from a data source to DB2for UNIX and Windows, the DB2 federated schema is SYSIBM.
DB2 for z/OS and OS/390 data sources
Table 143. DB2 for z/OS and OS/390 forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SMALLINT - - - - - - SMALLINT - 0 -
INTEGER - - - - - - INTEGER - 0 -
DECIMAL - - - - - - DECIMAL - - -
FLOAT - - - - - - DOUBLE - - -
CHAR 1 254 - - - - CHAR - 0 N
CHAR 255 32672 - - - - VARCHAR - 0 N
VARCHAR 1 32672 - - - - VARCHAR - 0 N
CHAR 1 254 - - Y - CHAR - 0 Y
CHAR 255 32672 - - Y - VARCHAR - 0 Y
VARCHAR 1 32672 - - Y - VARCHAR - 0 Y
GRAPHIC 1 127 - - - - GRAPHIC - 0 N
VARGRAPHIC 1 16336 - - - - VARGRAPHIC - 0 N
VARG 1 16336 - - - - VARGRAPHIC - 0 N
DATE - - - - - - DATE - 0 -
TIME - - - - - - TIME - 0 -
776 SQL Reference, Volume 1
Table 143. DB2 for z/OS and OS/390 forward default data type mappings (Not all columnsshown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
TIMESTAMP - - - - - - TIMESTAMP - 0 -
TIMESTMP - - - - - - TIMESTAMP - 0 -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
DB2 for iSeries data sources
Table 144. DB2 for iSeries forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SMALLINT - - - - - - SMALLINT - 0 -
INTEGER - - - - - - INTEGER - 0 -
NUMERIC - - - - - - DECIMAL - - -
DECIMAL - - - - - - DECIMAL - - -
FLOAT - - - - - - DOUBLE - - -
CHAR 1 254 - - - - CHAR - 0 N
CHAR 255 32672 - - - - VARCHAR - 0 N
Appendix E. Federated systems 777
Table 144. DB2 for iSeries forward default data type mappings (Not all columns shown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
VARCHAR 1 32672 - - - - VARCHAR - 0 N
CHAR 1 254 - - Y - CHAR - 0 Y
CHAR 255 32672 - - Y - VARCHAR - 0 Y
VARCHAR 1 32672 - - Y - VARCHAR - 0 Y
GRAPHIC 1 127 - - - - GRAPHIC - 0 N
GRAPHIC 128 16336 - - - - VARGRAPHIC - 0 N
VARGRAPHIC 1 16336 - - - - VARGRAPHIC - 0 N
VARG 1 16336 - - - - VARGRAPHIC - 0 N
DATE - - - - - - DATE - 0 -
TIME - - - - - - TIME - 0 -
TIMESTAMP - - - - - - TIMESTAMP - 0 -
TIMESTMP - - - - - - TIMESTAMP - 0 -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
778 SQL Reference, Volume 1
DB2 Server for VM and VSE data sources
Table 145. DB2 Server for VM and VSE forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SMALLINT - - - - - - SMALLINT - - -
INTEGER - - - - - - INTEGER - - -
DECIMAL - - - - - - DECIMAL - - -
FLOAT - - - - - - DOUBLE - - -
CHAR 1 254 - - - - CHAR - 0 N
VARCHAR 1 32672 - - - - VARCHAR - 0 N
CHAR 1 254 - - Y - CHAR - 0 Y
VARCHAR 1 32672 - - Y - VARCHAR - 0 Y
GRAPHIC 1 127 - - - - GRAPHIC - 0 N
VARGRAPHIC 1 16336 - - - - VARGRAPHIC - 0 N
VARGRAPH 1 16336 - - - - VARGRAPHIC - 0 N
DATE - - - - - - DATE - 0 -
TIME - - - - - - TIME - 0 -
TIMESTAMP - - - - - - TIMESTAMP - 0 -
TIMESTMP - - - - - - TIMESTAMP - 0 -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
DBAHW - - - - - - SMALLINT - 0 -
DBAINT - - - - - - INTEGER - 0 -
Appendix E. Federated systems 779
DB2 for UNIX and Windows data sources
Table 146. DB2 for UNIX and Windows forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SMALLINT - - - - - - SMALLINT - 0 -
INTEGER - - - - - - INTEGER - 0 -
BIGINT - - - - - - BIGINT - 0 -
DECIMAL - - - - - - DECIMAL - - -
REAL - - - - - - REAL - - -
FLOAT - - - - - - DOUBLE - - -
DOUBLE - - - - - - DOUBLE - - -
CHAR - - - - - - CHAR - 0 N
VARCHAR - - - - - - VARCHAR - 0 N
CHAR - - - - Y - CHAR - 0 Y
VARCHAR - - - - Y - VARCHAR - 0 Y
GRAPHIC - - - - - - GRAPHIC - 0 N
VARGRAPHIC - - - - - - VARGRAPHIC - 0 N
VARGRAPH - - - - - - VARGRAPHIC - 0 N
DATE - - - - - - DATE - 0 -
TIME - - - - - - TIME - 0 -
TIMESTAMP - - - - - - TIMESTAMP - 0 -
TIMESTMP - - - - - - TIMESTAMP - 0 -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
780 SQL Reference, Volume 1
Informix data sources
Table 147. Informix forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
BLOB - - - - - - BLOB 2147483647 - -
BOOLEAN - - - - - - SMALLINT 2 - -
BYTE - - - - - - BLOB 2147483647 - -
CHAR 1 254 - - - - CHARACTER - - -
CHAR 255 32672 - - - - VARCHAR - - -
CLOB - - - - - - CLOB 2147483647 - -
DATE - - - - - - DATE 4 - -
DATETIME 0 4 0 4 - - DATE 4 - -
DATETIME 6 10 6 10 - - TIME 3 - -
DATETIME 0 4 6 15 - - TIMESTAMP 10 - -
DATETIME 6 10 11 15 - - TIMESTAMP 10 - -
DECIMAL 1 31 0 31 - - DECIMAL - - -
DECIMAL 32 32 - - - - DOUBLE 8 - -
FLOAT - - - - - - DOUBLE 8 - -
INTEGER - - - - - - INTEGER 4 - -
INTERVAL - - - - - - DECIMAL 19 5 -
INT8 - - - - - - BIGINT 19 0 -
LVARCHAR 1 32672 - - - - VARCHAR - - -
MONEY 1 31 0 31 - - DECIMAL - - -
MONEY 32 32 - - - - DOUBLE 8 - -
NCHAR 1 254 - - - - CHARACTER - - -
NCHAR 255 32672 - - - - VARCHAR - - -
NVARCHAR 1 32672 - - - - VARCHAR - - -
Appendix E. Federated systems 781
Table 147. Informix forward default data type mappings (Not all columns shown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
REAL - - - - - - REAL 4 - -
SERIAL - - - - - - INTEGER 4 - -
SERIAL8 - - - - - - BIGINT 19 0
SMALLFLOAT - - - - - - REAL 4 - -
SMALLINT - - - - - - SMALLINT 2 - -
TEXT - - - - - - CLOB 2147483647 - -
VARCHAR 1 32672 - - - - VARCHAR - - -
Oracle SQLNET data sources
Table 148. Oracle SQLNET forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
NUMBER 1 38 -84 127 - \0 DOUBLE 0 0 N
NUMBER 1 31 0 31 - >= DECIMAL 0 0 N
NUMBER 1 5 0 0 - \0 SMALLINT 0 0 N
NUMBER 6 10 0 0 - \0 INTEGER 0 0 N
FLOAT 1 63 0 0 - \0 REAL 0 0 N
FLOAT 64 126 0 0 - \0 DOUBLE 0 0 N
782 SQL Reference, Volume 1
Table 148. Oracle SQLNET forward default data type mappings (Not all columns shown) (continued)R
EM
OT
E_T
YP
EN
AM
E
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
CHAR 1 254 0 0 - \0 CHAR 0 0 N
CHAR 255 32672 0 0 - \0 VARCHAR 0 0 N
VARCHAR2 1 32672 0 0 - \0 VARCHAR 0 0 N
RAW 1 254 0 0 - \0 CHAR 0 0 Y
RAW 255 32672 0 0 - \0 VARCHAR 0 0 Y
LONG 0 0 0 0 - \0 CLOB 2147483647 0 N
LONG RAW 0 0 0 0 - \0 BLOB 2147483647 0 Y
DATE 0 0 0 0 - \0 TIMESTAMP 0 0 N
MLSLABEL 0 0 0 0 - \0 VARCHAR 255 0 N
ROWID 0 0 0 NULL- \0 CHAR 18 0 N
Oracle NET8 data sources
Table 149. Oracle NET8 forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
NUMBER 1 38 -84 127 - \0 DOUBLE 0 0 N
NUMBER 1 31 0 31 - >= DECIMAL 0 0 N
NUMBER 1 5 0 0 - \0 SMALLINT 0 0 N
Appendix E. Federated systems 783
Table 149. Oracle NET8 forward default data type mappings (Not all columns shown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
NUMBER 6 10 0 0 - \0 INTEGER 0 0 N
FLOAT 1 63 0 0 - \0 REAL 0 0 N
FLOAT 64 126 0 0 - \0 DOUBLE 0 0 N
CHAR 1 254 0 0 - \0 CHAR 0 0 N
CHAR 255 32672 0 0 - \0 VARCHAR 0 0 N
VARCHAR2 1 32672 0 0 - \0 VARCHAR 0 0 N
RAW 1 254 0 0 - \0 CHAR 0 0 Y
RAW 255 32672 0 0 - \0 VARCHAR 0 0 Y
CLOB 0 0 0 0 - \0 CLOB 2147483647 0 N
BLOB 0 0 0 0 - \0 BLOB 2147483647 0 Y
DATE 0 0 0 0 - \0 TIMESTAMP 0 0 N
MLSLABEL 0 0 0 0 - \0 VARCHAR 255 0 N
ROWID 0 0 0 NULL - \0 CHAR 18 0 N
784 SQL Reference, Volume 1
Microsoft SQL Server data sources
Table 150. Microsoft SQL Server forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
int - - - - - - INTEGER 4 - -
intn - - - - - - INTEGER 4 - -
smallint - - - - - - SMALLINT 2 - -
tinyint - - - - - - SMALLINT 2 - -
bit - - - - - - SMALLINT 2 - -
float - 8 - - - - DOUBLE 8 - -
floatn - 8 - - - - DOUBLE 8 - -
float - 4 - - - - REAL 4 - -
floatn - 4 - - - - REAL 4 - -
real - - - - - - REAL 4 - -
money - - - - - - DECIMAL 19 4 -
moneyn - - - - - - DECIMAL 19 4 -
smallmoney - - - - - - DECIMAL 10 4 -
smallmoneyn - - - - - - DECIMAL 10 4 -
decimal 1 31 0 31 - - DECIMAL - - -
decimal 32 38 0 38 - - DOUBLE - - -
decimaln 1 31 0 31 - - DECIMAL - - -
decimaln 32 38 0 38 - - DOUBLE - - -
numeric 1 31 0 31 - - DECIMAL - - -
numeric 32 38 0 38 - - DOUBLE 8 - -
numericn 1 31 0 31 - - DECIMAL - - -
numericn 32 38 0 38 - - DOUBLE - - -
char 1 254 - - - - CHAR - - N
Appendix E. Federated systems 785
Table 150. Microsoft SQL Server forward default data type mappings (Not all columns shown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
sysname 1 254 - - - - CHAR - - N
char 255 8000 - - - - VARCHAR - - N
varchar 1 8000 - - - - VARCHAR - - N
text - - - - - - CLOB - - N
nchar 1 127 - - - - GRAPHIC - - N
nchar 128 4000 - - - - VARGRAPHIC - - N
nvarchar 1 4000 - - - - VARGRAPHIC - - N
binary 1 254 - - - - CHARACTER - - Y
binary 255 8000 - - - - VARCHAR - - Y
varbinary 1 8000 - - - - VARCHAR - - Y
image - - - - - - BLOB 2147483647 - Y
datetime - - - - - - TIMESTAMP 10 - -
datetimen - - - - - - TIMESTAMP 10 - -
smalldatetime - - - - - - TIMESTAMP 10 - -
timestamp - - - - - - VARCHAR 8 Y
sysname - - - - - - VARCHAR 30 Y
SQL_INTEGER - - - - - - INTEGER 4 - -
SQL_SMALLINT - - - - - - SMALLINT 2 - -
SQL_DECIMAL 1 31 0 31 - - DECIMAL - - -
SQL_DECIMAL 32 38 0 38 - - DOUBLE 8 - -
SQL_NUMERIC 1 31 0 31 - - DECIMAL - - -
SQL_DECIMAL 32 32 0 31 - - DOUBLE 8 - -
SQL_FLOAT - - - - - - DOUBLE 8 - -
SQL_DOUBLE - - - - - - DOUBLE 8 - -
786 SQL Reference, Volume 1
Table 150. Microsoft SQL Server forward default data type mappings (Not all columns shown) (continued)R
EM
OT
E_T
YP
EN
AM
E
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SQL_REAL - - - - - - DOUBLE 8 - -
SQL_CHAR 1 254 - - - - CHAR - - N
SQL_CHAR 255 8000 - - - - VARCHAR - - N
SQL_BINARY 1 254 - - - - CHARACTER - - Y
SQL_BINARY 255 8000 - - - - VARCHAR - - Y
SQL_VARCHAR 1 8000 - - - - VARCHAR - - N
SQL_VARBINARY 1 8000 - - - - VARCHAR - - Y
SQL_LONGVARCHAR - - - - - - CLOB 2147483647 - N
SQL_LONGVARBINARY- - - - - - BLOB - - Y
SQL_DATE - - - - - - DATE 4 - -
SQL_TIME - - - - - - TIME 3 - -
SQL_TIMESTAMP - - - - - - TIMESTAMP 10 - -
SQL_BIT - - - - - - SMALLINT 2 - -
SQL_TINYINT - - - - - - SMALLINT 2 - -
SQL_BIGINT - - - - - - DECIMAL - - -
DUMMY65 1 1 38 -84 127 - - DOUBLE - - -
uniqueidentifier 2 1 4000 - - Y - VARCHAR 16 - Y
SQL_GUID 2 1 4000 - - Y - VARCHAR 16 - Y
ntext 2 - - - - - - CLOB 2147483647 - Y
DUMMY2000 3 1 38 -84 127 - - DOUBLE - - -
Notes:
1. This type mapping is only valid with Microsoft SQL Server Version 6.5.
2. This type mapping is only valid with Microsoft SQL Server Version 7.
3. This type mapping is only valid with Windows 2000 operating systems.
Appendix E. Federated systems 787
ODBC data sources
Table 151. ODBC forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SQL_INTEGER - - - - - - INTEGER 4 - -
SQL_SMALLINT - - - - - - SMALLINT 2 - -
SQL_DECIMAL 1 31 0 31 - - DECIMAL - - -
SQL_DECIMAL 32 38 0 38 - - DOUBLE 8 - -
SQL_NUMERIC 1 31 0 31 - - DECIMAL - - -
SQL_NUMERIC 32 32 0 31 - - DOUBLE 8 - -
SQL_FLOAT - - - - - - DOUBLE 8 - -
SQL_DOUBLE - - - - - - DOUBLE 8 - -
SQL_REAL - - - - - - DOUBLE 8 - -
SQL_CHAR 1 254 - - - - CHAR - - N
SQL_CHAR 255 32672 - - - - VARCHAR - - N
SQL_BINARY 1 254 - - - - CHARACTER - - Y
SQL_BINARY 255 32672 - - - - VARCHAR - - Y
SQL_VARCHAR 1 32672 - - - - VARCHAR - - N
SQL_VARBINARY 1 32672 - - - - VARCHAR - - Y
SQL_LONGVARCHAR - - - - - - CLOB 2147483647 - N
SQL_LONGVARBINARY- - - - - - BLOB - - Y
SQL_DATE - - - - - - DATE 4 - Y
SQL_TIME - - - - - - TIME 3 - Y
SQL_TIMESTAMP - - - - - - TIMESTAMP 10 - Y
SQL_BIT - - - - - - SMALLINT 2 - -
SQL_TINYINT - - - - - - SMALLINT 2 - -
SQL_BIGINT - - - - - - DECIMAL - - -
788 SQL Reference, Volume 1
Table 151. ODBC forward default data type mappings (Not all columns shown) (continued)R
EM
OT
E_T
YP
EN
AM
E
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SQL_WCHAR 1 127 - - - - GRAPHIC - - N
SQL_WCHAR 128 16336 - - - - VARGRAPHIC - - N
SQL_WVARCHAR 1 16336 - - - - VARGRAPHIC - - N
SQL_WLONGVARCHAR- - - - - - DBCLOB 1073741823 -NY
Sybase data sources
Table 152. Sybase CTLIB forward default data type mappings (Not all columns shown)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TAint - - - - - - INTEGER - - -
intn - - - - - - INTEGER - - -
smallint - - - - - - SMALLINT - - -
tinyint - - - - - - SMALLINT - - -
bit - - - - - - SMALLINT - - -
float - 8 - - - - DOUBLE - - -
floatn - 8 - - - - DOUBLE - - -
float - 4 - - - - REAL - - -
Appendix E. Federated systems 789
Table 152. Sybase CTLIB forward default data type mappings (Not all columns shown) (continued)
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
floatn - 4 - - - - REAL - - -
real - - - - - - REAL - - -
money - - - - - - DECIMAL 19 4 -
moneyn - - - - - - DECIMAL 19 4 -
smallmoney - - - - - - DECIMAL 10 4 -
decimal 1 31 0 31 - - DECIMAL - - -
decimal 32 32 - - - - DOUBLE - - -
decimaln 1 31 0 31 - - DECIMAL - - -
decimaln 32 32 - - - - DOUBLE - - -
numeric 1 31 0 31 - - DECIMAL - - -
numeric 32 32 - - - - DOUBLE - - -
numericn 1 31 0 31 - - DECIMAL - - -
numericn 32 32 - - - - DOUBLE - - -
char 1 254 - - - - CHAR - - Y
sysname 1 254 - - - - CHAR - - Y
char 255 255 - - - - VARCHAR - - Y
varchar 1 255 - - - - VARCHAR - - Y
nchar 1 127 - - - - GRAPHIC - - -
nchar 128 255 - - - - VARGRAPHIC - - -
nvarchar 1 255 - - - - VARGRAPHIC - - -
binary 1 254 - - - - CHAR - - Y
binary 255 255 - - - - VARCHAR - - Y
text - - - - - - CLOB - - -
image - - - - - - BLOB - - -
790 SQL Reference, Volume 1
Table 152. Sybase CTLIB forward default data type mappings (Not all columns shown) (continued)R
EM
OT
E_T
YP
EN
AM
E
RE
MO
TE
_LO
WE
R_L
EN
RE
MO
TE
_UP
PE
R_L
EN
RE
MO
TE
_LO
WE
R_S
CA
LE
RE
MO
TE
_UP
PE
R_S
CA
LE
RE
MO
TE
_BIT
_DA
TA
RE
MO
TE
_DA
TA_O
PE
RA
TO
RS
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LE
NG
TH
FED
ER
AT
ED
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
varbinary 1 255 - - - - VARCHAR - - Y
datetime - - - - - - TIMESTAMP - - -
datetimen - - - - - - TIMESTAMP - - -
smalldatetime - - - - - - TIMESTAMP - - -
timestamp - - - - - - VARCHAR 8 - Y
Default reverse data type mappings
There are two kinds of mappings between data source data types andfederated database data types: forward type mappings and reverse typemappings. In a forward type mapping, the mapping is from a remote type to acomparable local type. The other type of mapping is a reverse type mapping,which is used with transparent DDL to create or modify remote tables.
For most data sources, the default type mappings are in the wrappers. Thedefault type mappings for DB2 family data sources are in the DRDA wrapper.The default type mappings for Informix are in the INFORMIX wrapper, andso forth.
When you define a remote table or view to the DB2 federated database, thedefinition includes a reverse type mapping. The mapping is from a local DB2for UNIX and Windows data type for each column, and the correspondingremote data type. For example, there is a default reverse type mapping inwhich the local type REAL points to the Informix type SMALLFLOAT.
DB2 for UNIX and Windows federated servers do not support mappings forthese local data types: LONG VARCHAR, LONG VARGRAPHIC, DATALINK,and user-defined types.
Appendix E. Federated systems 791
When you use the CREATE TABLE statement to create a remote table, youspecify the local data types you want to include in the remote table. Thesedefault reverse type mappings will assign corresponding remote types tothese columns. For example, suppose that you use the CREATE TABLEstatement to define an Informix table with a column C2. You specify BIGINTas the data type for C2 in the statement. The default reverse type mapping ofBIGINT depends on which version of Informix you are creating the table on.The mapping for C2 in the Informix table will be to DECIMAL in InformixVersion 7 and to INT8 in Informix Version 8.
You can override a default type mapping, or create a new type mapping withthe CREATE TYPE MAPPING statement.
The following tables show the default reverse mappings between DB2 forUNIX and Windows local data types and remote data source data types.
These mappings are valid with all the supported versions, unless otherwisenoted.
DB2 for z/OS and OS/390 data sources
Table 153. DB2 for z/OS and OS/390 reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
SMALLINT - 2 - - - - SMALLINT - - -
INTEGER - 4 - - - - INTEGER - - -
DECIMAL - - - - - - DECIMAL - - -
FLOAT - 8 - - - - DOUBLE - - -
CHARACTER - - - - - - CHAR - - N
VARCHAR - - - - - - VARCHAR - - N
CHARACTER - - - - Y - CHAR - - Y
VARCHAR - - - - Y - VARCHAR - - Y
792 SQL Reference, Volume 1
Table 153. DB2 for z/OS and OS/390 reverse default data type mappings (Not all columnsshown) (continued)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
GRAPHIC - - - - - - GRAPHIC - - N
VARGRAPHIC - - - - - - VARGRAPHIC - - N
DATE - 4 - - - - DATE - - -
TIME - 3 - - - - TIME - - -
TIMESTAMP - 10 - - - - TIMESTAMP - - -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
DB2 for iSeries data sources
Table 154. DB2 for iSeries reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
SMALLINT - 2 - - - - SMALLINT - - -
INTEGER - 4 - - - - INTEGER - - -
Appendix E. Federated systems 793
Table 154. DB2 for iSeries reverse default data type mappings (Not all columns shown) (continued)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
DECIMAL - - - - - - NUMERIC - - -
DECIMAL - - - - - - DECIMAL - - -
DOUBLE - 8 - - - - FLOAT - - -
CHARACTER - - - - - - CHARACTER - - N
VARCHAR - - - - - - VARCHAR - - N
CHARACTER - - - - Y - CHARACTER - - Y
VARCHAR - - - - Y - VARCHAR - - Y
GRAPHIC - - - - - - GRAPHIC - - N
VARGRAPHIC - - - - - - VARG - - N
DATE - 4 - - - - DATE - - -
TIME - 3 - - - - TIME - - -
TIMESTAMP - 10 - - - - TIMESTAMP - - -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
794 SQL Reference, Volume 1
DB2 Server for VM and VSE data sources
Table 155. DB2 Server for VM and VSE reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
SMALLINT - 2 - - - - SMALLINT - - -
INTEGER - 4 - - - - INTEGER - - -
DECIMAL - - - - - - DECIMAL - - -
DOUBLE - 8 - - - - FLOAT - - -
CHARACTER - - - - - - CHAR - - -
VARCHAR - - - - - - VARCHAR - - -
CHARACTER - - - - Y - CHAR - - Y
VARCHAR - - - - Y - VARCHAR - - Y
GRAPHIC - - - - - - GRAPHIC - - N
VARGRAPH - - - - - - VARGRAPH - - N
DATE - 4 - - - - DATE - - -
TIME - 3 - - - - TIME - - -
TIMESTAMP - 10 - - - - TIMESTAMP - - -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
Appendix E. Federated systems 795
DB2 for UNIX and Windows data sources
Table 156. DB2 for UNIX and Windows reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
FED
ER
AT
ED
_BIT
_DA
TA
SMALLINT - 2 - - - - SMALLINT - - -
INTEGER - 4 - - - - INTEGER - - -
BIGINT - 8 - - - - BIGINT - - -
DECIMAL - - - - - - DECIMAL - - -
FLOAT - 8 - - - - DOUBLE - - -
DOUBLE - 8 - - - - DOUBLE - - -
CHARACTER - - - - - - CHAR - - N
VARCHAR - - - - - - VARCHAR - - N
CHARACTER - - - - Y - CHAR - - Y
VARCHAR - - - - Y - VARCHAR - - Y
GRAPHIC - - - - - - GRAPHIC - - N
VARGRAPH - - - - - - VARGRAPHIC - - N
DATE - 4 - - - - DATE - - -
TIME - 3 - - - - TIME - - -
TIMESTAMP - 10 - - - - TIMESTAMP - - -
CLOB - - - - - - CLOB - - -
BLOB - - - - - - BLOB - - -
DBCLOB - - - - - - DBCLOB - - -
796 SQL Reference, Volume 1
Informix data sources
Table 157. Informix reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
BIGINT1 - 19 0 - - - DECIMAL 21 - -
BIGINT 2 - - - - - - INT8 - - -
BLOB 1 2147483647- - - - BYTE - - -
CHARACTER - - - - N - CHAR - - -
CHARACTER - - - - Y - BYTE - - -
CLOB 1 2147483647- - - - TEXT - - -
DATE - 4 - - - - DATE - - -
DECIMAL - - - - - - DECIMAL - - -
DOUBLE - 8 - - - - FLOAT - - -
INTEGER - 4 - - - - INTEGER - - -
LONGVARCHAR
- 32700 - - N - TEXT - - -
LONGVARCHAR
- 32700 - - Y - BYTE - - -
REAL - 4 - - - - SMALLFLOAT - - -
SMALLINT - 2 - - - - INTEGER - - -
TIME - 3 - - - - DATETIME 6 10 -
TIMESTAMP - 10 - - - - DATETIME 0 15 -
VARCHAR 1 254 - - N - VARCHAR - - -
VARCHAR 255 32672 - - N - TEXT - - -
VARCHAR - - - - Y - BYTE - - -
VARCHAR 2 255 32672 - - N - LVARCHAR - - -
Appendix E. Federated systems 797
Table 157. Informix reverse default data type mappings (Not all columns shown) (continued)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
Notes:
1. This type mapping is only valid with Informix server Version 7 (or lower).
2. This type mapping is only valid with Informix server Version 8 (or higher).
Oracle SQLNET data sourcesNote: The DB2 for UNIX and Windows BIGINT data type is not available fortransparent DDL. You cannot specify the BIGINT data type in a CREATETABLE statement when creating a remote Oracle table.
Table 158. Oracle SQLNET reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
DOUBLE 0 8 0 0 N \0 FLOAT 126 0 N
REAL 0 4 0 0 N \0 FLOAT 63 0 N
DECIMAL 0 0 0 0 N \0 NUMBER 0 0 N
SMALLINT 0 2 0 0 N \0 NUMBER 5 0 N
INTEGER 0 4 0 0 N \0 NUMBER 10 0 N
798 SQL Reference, Volume 1
Table 158. Oracle SQLNET reverse default data type mappings (Not all columns shown) (continued)FE
DE
RA
TE
D_T
YP
EN
AM
E
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
CHARACTER 1 254 0 0 N \0 CHAR 0 0 N
VARCHAR 1 4000 0 0 N \0 VARCHAR2 0 0 N
CLOB 0 21474836470 0 N \0 LONG 0 0 N
CHARACTER 0 0 0 0 Y \0 RAW 0 0 Y
VARCHAR 1 2000 0 0 Y \0 RAW 0 0 Y
BLOB 0 21474836470 0 Y \0 LONG RAW 0 0 Y
TIMESTAMP 0 10 0 0 N \0 DATE 0 0 N
DATE 0 4 0 0 N \0 DATE 0 0 N
TIME 0 3 0 0 N \0 DATE 0 0 N
Oracle NET8 data sourcesNote: The DB2 for UNIX and Windows BIGINT data type is not available fortransparent DDL. You cannot specify the BIGINT data type in a CREATETABLE statement when creating a remote Oracle table.
Appendix E. Federated systems 799
Table 159. Oracle NET8 reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
DOUBLE 0 8 0 0 N \0 FLOAT 126 0 N
REAL 0 4 0 0 N \0 FLOAT 63 0 N
DECIMAL 0 0 0 0 N \0 NUMBER 0 0 N
SMALLINT 0 2 0 0 N \0 NUMBER 5 0 N
INTEGER 0 4 0 0 N \0 NUMBER 10 0 N
CHARACTER 1 254 0 0 N \0 CHAR 0 0 N
VARCHAR 1 4000 0 0 N \0 VARCHAR2 0 0 N
CLOB 0 21474836470 0 N \0 CLOB 0 0 N
CHARACTER 0 0 0 0 Y \0 RAW 0 0 Y
VARCHAR 1 2000 0 0 Y \0 RAW 0 0 Y
BLOB 0 21474836470 0 Y \0 BLOB 0 0 Y
TIMESTAMP 0 10 0 0 N \0 DATE 0 0 N
DATE 0 4 0 0 N \0 DATE 0 0 N
TIME 0 3 0 0 N \0 DATE 0 0 N
800 SQL Reference, Volume 1
Microsoft SQL Server data sources
Table 160. Microsoft SQL Server reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
INTEGER - - - - - - int - - -
SMALLINT - - - - - - smallint - - -
DOUBLE - 8 - - - - float - - -
DECIMAL - - - - - - decimal - - -
CHARACTER - - - - N - char - - -
VARCHAR 1 8000 - - N - varchar - - -
VARCHAR 8001 32672 - - N - text - - -
CLOB - - - - - - text - - -
CHARACTER - - - - Y - binary - - -
VARCHAR 1 8000 - - Y - varbinary - - -
VARCHAR 8001 32672 - - Y - image - - -
LONGVARCHAR
- 32700 - - Y - image- - -
BLOB - - - - - - image - - -
TIMESTAMP - 10 - - - - datetime - - -
TIME - 3 - - - - datetime - - -
DATE - 4 - - - - datetime - - -
Sybase data sourcesThese data type mappings only apply to the CTLIB wrapper. The DBLIBwrapper is read-only and does not support transparent DDL in a Version 8federated system.
Appendix E. Federated systems 801
Table 161. Sybase CTLIB reverse default data type mappings (Not all columns shown)
FED
ER
AT
ED
_TY
PE
NA
ME
FED
ER
AT
ED
_LO
WE
R_L
EN
FED
ER
AT
ED
_UP
PE
R_L
EN
FED
ER
AT
ED
_LO
WE
R_S
CA
LE
FED
ER
AT
ED
_UP
PE
R_S
CA
LE
FED
ER
AT
ED
_BIT
_DA
TA
FED
ER
AT
ED
_DA
TA_O
PE
RA
TO
RS
RE
MO
TE
_TY
PE
NA
ME
RE
MO
TE
_LE
NG
TH
RE
MO
TE
_SC
AL
E
RE
MO
TE
_BIT
_DA
TA
INTEGER - - - - - - integer - - -
SMALLINT - - - - - - smallint - - -
BIGINT - - - - - - decimal 19 0 -
DOUBLE - - - - - - float - - -
REAL - - - - - - real - - -
DECIMAL - - - - - - decimal - - -
CHARACTER - - - - N - char - - -
VARCHAR 1 255 - - N - varchar - - -
VARCHAR 256 32672 - - N - text - - -
CHARACTER - - - - Y - binary - - -
CLOB - - - - - - text - - -
BLOB - - - - - - image - - -
VARCHAR 1 255 - - Y - varbinary - - -
VARCHAR 256 32672 - - Y - image - - -
GRAPHIC - - - - - - nchar - - -
VARGRAPHIC 1 255 - - - - nvarchar - - -
DATE - - - - - - datetime - - -
TIME - - - - - - datetime - - -
TIMESTAMP - - - - - - datetime - - -
802 SQL Reference, Volume 1
Appendix F. The SAMPLE database
Many of the code examples in the DB2 documentation use the SAMPLEdatabase. Following is a description of each of the tables in the SAMPLEdatabase. Instructions for creating and dropping the database are alsoprovided. Initial data values for each table are given; a dash (−) indicates aNULL value.
Creating the SAMPLE database
Use the DB2SAMPL command to create the SAMPLE database. To create adatabase you must have SYSADM authority.v When using UNIX-based platforms
If you are using the operating system command prompt, issue:sqllib/bin/db2sampl <path>
from the home directory of the database manager instance owner, wherepath is an optional parameter specifying the path where the SAMPLEdatabase is to be created. If the path parameter is not specified, the sampledatabase is created in the default path specified by the DFTDBPATHparameter in the database manager configuration file. The schema forDB2SAMPL is the value of the CURRENT SCHEMA special register.
v When using Windows platforms
If you are using the operating system command prompt, issue:db2sampl e
where e is an optional parameter specifying the drive where the database isto be created. If the drive parameter is not specified, the sample database iscreated on the same drive as DB2.
Erasing the SAMPLE database
If you do not need to access the SAMPLE database, you can erase it by usingthe DROP DATABASE command:
db2 drop database sample
CL_SCHED table
Name: CLASS_CODE DAY STARTING ENDING
Type: char(7) smallint time time
© Copyright IBM Corp. 1993 - 2002 803
Name: CLASS_CODE DAY STARTING ENDING
Desc: Class Code(room:teacher)
Day # of 4 dayschedule
Class Start Time Class End Time
DEPARTMENT table
Name: DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION
Type: char(3) not null varchar(29) not null char(6) char(3) not null char(16)
Desc: Departmentnumber
Name describing generalactivities of department
Employeenumber(EMPNO) ofdepartmentmanager
Department(DEPTNO) towhich thisdepartmentreports
Name of theremote location
Values: A00 SPIFFY COMPUTER SERVICEDIV.
000010 A00 -
B01 PLANNING 000020 A00 -
C01 INFORMATION CENTER 000030 A00 -
D01 DEVELOPMENT CENTER - A00 -
D11 MANUFACTURING SYSTEMS 000060 D01 -
D21 ADMINISTRATION SYSTEMS 000070 D01 -
E01 SUPPORT SERVICES 000050 A00 -
E11 OPERATIONS 000090 E01 -
E21 SOFTWARE SUPPORT 000100 E01 -
EMPLOYEE table
Names: EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE
Type: char(6) notnull
varchar(12)not null
char(1) notnull
varchar(15)not null
char(3) char(4) date
Desc: Employeenumber
First name Middleinitial
Last name Department(DEPTNO)in which theemployeeworks
Phonenumber
Date of hire
JOB EDLEVEL SEX BIRTHDATE SALARY BONUS COMM
char(8) smallint not null char(1) date dec(9,2) dec(9,2) dec(9,2)
Job Number of years offormal education
Sex (Mmale, Ffemale)
Date of birth Yearly salary Yearly bonus Yearlycommission
CL_SCHED table
804 SQL Reference, Volume 1
The following table contains the values in the EMPLOYEE table.
EMPLOYEE table
Appendix F. The SAMPLE database 805
EM
PN
OFI
RS
TN
ME
MID
INIT
LA
ST
NA
ME
WO
RK
DE
PT
PH
ON
EN
OH
IRE
DA
TE
JOB
ED
LE
VE
LS
EX
BIR
TH
DA
TE
SA
LA
RY
BO
NU
SC
OM
M
char
(6)
not
null
varc
har(
12)
not
null
char
(1)
not
null
varc
har(
15)
not
null
char
(3)
char
(4)
dat
ech
ar(8
)sm
allin
tno
tnu
llch
ar(1
)d
ate
dec
(9,2
)d
ec(9
,2)
dec
(9,2
)
0000
10C
HR
IST
INE
IH
AA
SA
0039
7819
65-0
1-01
PRE
S18
F19
33-0
8-24
5275
010
0042
20
0000
20M
ICH
AE
LL
TH
OM
PSO
NB
0134
7619
73-1
0-10
MA
NA
GE
R18
M19
48-0
2-02
4125
080
033
00
0000
30SA
LLY
AK
WA
NC
0147
3819
75-0
4-05
MA
NA
GE
R20
F19
41-0
5-11
3825
080
030
60
0000
50JO
HN
BG
EY
ER
E01
6789
1949
-08-
17M
AN
AG
ER
16M
1925
-09-
1540
175
800
3214
0000
60IR
VIN
GF
STE
RN
D11
6423
1973
-09-
14M
AN
AG
ER
16M
1945
-07-
0732
250
500
2580
0000
70E
VA
DPU
LA
SKI
D21
7831
1980
-09-
30M
AN
AG
ER
16F
1953
-05-
2636
170
700
2893
0000
90E
ILE
EN
WH
EN
DE
RSO
NE
1154
9819
70-0
8-15
MA
NA
GE
R16
F19
41-0
5-15
2975
060
023
80
0001
00T
HE
OD
OR
EQ
SPE
NSE
RE
2109
7219
80-0
6-19
MA
NA
GE
R14
M19
56-1
2-18
2615
050
020
92
0001
10V
INC
EN
ZO
GL
UC
CH
ESS
IA
0034
9019
58-0
5-16
SAL
ESR
EP
19M
1929
-11-
0546
500
900
3720
0001
20SE
AN
O’C
ON
NE
LL
A00
2167
1963
-12-
05C
LE
RK
14M
1942
-10-
1829
250
600
2340
0001
30D
OL
OR
ES
MQ
UIN
TAN
AC
0145
7819
71-0
7-28
AN
ALY
ST16
F19
25-0
9-15
2380
050
019
04
0001
40H
EA
TH
ER
AN
ICH
OL
LS
C01
1793
1976
-12-
15A
NA
LYST
18F
1946
-01-
1928
420
600
2274
0001
50B
RU
CE
AD
AM
SON
D11
4510
1972
-02-
12D
ESI
GN
ER
16M
1947
-05-
1725
280
500
2022
0001
60E
LIZ
AB
ET
HR
PIA
NK
AD
1137
8219
77-1
0-11
DE
SIG
NE
R17
F19
55-0
4-12
2225
040
017
80
0001
70M
ASA
TOSH
IJ
YO
SHIM
UR
AD
1128
9019
78-0
9-15
DE
SIG
NE
R16
M19
51-0
1-05
2468
050
019
74
0001
80M
AR
ILY
NS
SCO
UT
TE
ND
1116
8219
73-0
7-07
DE
SIG
NE
R17
F19
49-0
2-21
2134
050
017
07
0001
90JA
ME
SH
WA
LK
ER
D11
2986
1974
-07-
26D
ESI
GN
ER
16M
1952
-06-
2520
450
400
1636
0002
00D
AV
IDB
RO
WN
D11
4501
1966
-03-
03D
ESI
GN
ER
16M
1941
-05-
2927
740
600
2217
0002
10W
ILL
IAM
TJO
NE
SD
1109
4219
79-0
4-11
DE
SIG
NE
R17
M19
53-0
2-23
1827
040
014
62
0002
20JE
NN
IFE
RK
LU
TZ
D11
0672
1968
-08-
29D
ESI
GN
ER
18F
1948
-03-
1929
840
600
2387
0002
30JA
ME
SJ
JEFF
ER
SON
D21
2094
1966
-11-
21C
LE
RK
14M
1935
-05-
3022
180
400
1774
0002
40SA
LVA
TOR
EM
MA
RIN
OD
2137
8019
79-1
2-05
CL
ER
K17
M19
54-0
3-31
2876
060
023
01
0002
50D
AN
IEL
SSM
ITH
D21
0961
1969
-10-
30C
LE
RK
15M
1939
-11-
1219
180
400
1534
0002
60SY
BIL
PJO
HN
SON
D21
8953
1975
-09-
11C
LE
RK
16F
1936
-10-
0517
250
300
1380
0002
70M
AR
IAL
PER
EZ
D21
9001
1980
-09-
30C
LE
RK
15F
1953
-05-
2627
380
500
2190
0002
80E
TH
EL
RSC
HN
EID
ER
E11
8997
1967
-03-
24O
PER
ATO
R17
F19
36-0
3-28
2625
050
021
00
0002
90JO
HN
RPA
RK
ER
E11
4502
1980
-05-
30O
PER
ATO
R12
M19
46-0
7-09
1534
030
012
27
0003
00PH
ILIP
XSM
ITH
E11
2095
1972
-06-
19O
PER
ATO
R14
M19
36-1
0-27
1775
040
014
20
0003
10M
AU
DE
FSE
TR
IGH
TE
1133
3219
64-0
9-12
OPE
RA
TOR
12F
1931
-04-
2115
900
300
1272
0003
20R
AM
LA
LV
ME
HTA
E21
9990
1965
-07-
07FI
EL
DR
EP
16M
1932
-08-
1119
950
400
1596
EMPLOYEE table
806 SQL Reference, Volume 1
EM
PN
OFI
RS
TN
ME
MID
INIT
LA
ST
NA
ME
WO
RK
DE
PT
PH
ON
EN
OH
IRE
DA
TE
JOB
ED
LE
VE
LS
EX
BIR
TH
DA
TE
SA
LA
RY
BO
NU
SC
OM
M
0003
30W
ING
LE
EE
2121
0319
76-0
2-23
FIE
LD
RE
P14
M19
41-0
7-18
2537
050
020
30
0003
40JA
SON
RG
OU
NO
TE
2156
9819
47-0
5-05
FIE
LD
RE
P16
M19
26-0
5-17
2384
050
019
07
EMPLOYEE table
Appendix F. The SAMPLE database 807
EMP_ACT table
Name: EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE
Type: char(6) not null char(6) not null smallint notnull
dec(5,2) date date
Desc: Employeenumber
Project number Activitynumber
Proportion ofemployee’s
time spent onproject
Date activitystarts
Date activityends
Values: 000010 AD3100 10 .50 1982-01-01 1982-07-01
000070 AD3110 10 1.00 1982-01-01 1983-02-01
000230 AD3111 60 1.00 1982-01-01 1982-03-15
000230 AD3111 60 .50 1982-03-15 1982-04-15
000230 AD3111 70 .50 1982-03-15 1982-10-15
000230 AD3111 80 .50 1982-04-15 1982-10-15
000230 AD3111 180 1.00 1982-10-15 1983-01-01
000240 AD3111 70 1.00 1982-02-15 1982-09-15
000240 AD3111 80 1.00 1982-09-15 1983-01-01
000250 AD3112 60 1.00 1982-01-01 1982-02-01
000250 AD3112 60 .50 1982-02-01 1982-03-15
000250 AD3112 60 .50 1982-12-01 1983-01-01
000250 AD3112 60 1.00 1983-01-01 1983-02-01
000250 AD3112 70 .50 1982-02-01 1982-03-15
000250 AD3112 70 1.00 1982-03-15 1982-08-15
000250 AD3112 70 .25 1982-08-15 1982-10-15
000250 AD3112 80 .25 1982-08-15 1982-10-15
000250 AD3112 80 .50 1982-10-15 1982-12-01
000250 AD3112 180 .50 1982-08-15 1983-01-01
000260 AD3113 70 .50 1982-06-15 1982-07-01
000260 AD3113 70 1.00 1982-07-01 1983-02-01
000260 AD3113 80 1.00 1982-01-01 1982-03-01
000260 AD3113 80 .50 1982-03-01 1982-04-15
000260 AD3113 180 .50 1982-03-01 1982-04-15
000260 AD3113 180 1.00 1982-04-15 1982-06-01
000260 AD3113 180 .50 1982-06-01 1982-07-01
000270 AD3113 60 .50 1982-03-01 1982-04-01
000270 AD3113 60 1.00 1982-04-01 1982-09-01
000270 AD3113 60 .25 1982-09-01 1982-10-15
000270 AD3113 70 .75 1982-09-01 1982-10-15
000270 AD3113 70 1.00 1982-10-15 1983-02-01
EMP_ACT table
808 SQL Reference, Volume 1
Name: EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE
000270 AD3113 80 1.00 1982-01-01 1982-03-01
000270 AD3113 80 .50 1982-03-01 1982-04-01
000030 IF1000 10 .50 1982-06-01 1983-01-01
000130 IF1000 90 1.00 1982-01-01 1982-10-01
000130 IF1000 100 .50 1982-10-01 1983-01-01
000140 IF1000 90 .50 1982-10-01 1983-01-01
000030 IF2000 10 .50 1982-01-01 1983-01-01
000140 IF2000 100 1.00 1982-01-01 1982-03-01
000140 IF2000 100 .50 1982-03-01 1982-07-01
000140 IF2000 110 .50 1982-03-01 1982-07-01
000140 IF2000 110 .50 1982-10-01 1983-01-01
000010 MA2100 10 .50 1982-01-01 1982-11-01
000110 MA2100 20 1.00 1982-01-01 1982-03-01
000010 MA2110 10 1.00 1982-01-01 1983-02-01
000200 MA2111 50 1.00 1982-01-01 1982-06-15
000200 MA2111 60 1.00 1982-06-15 1983-02-01
000220 MA2111 40 1.00 1982-01-01 1983-02-01
000150 MA2112 60 1.00 1982-01-01 1982-07-15
000150 MA2112 180 1.00 1982-07-15 1983-02-01
000170 MA2112 60 1.00 1982-01-01 1983-06-01
000170 MA2112 70 1.00 1982-06-01 1983-02-01
000190 MA2112 70 1.00 1982-02-01 1982-10-01
000190 MA2112 80 1.00 1982-10-01 1983-10-01
000160 MA2113 60 1.00 1982-07-15 1983-02-01
000170 MA2113 80 1.00 1982-01-01 1983-02-01
000180 MA2113 70 1.00 1982-04-01 1982-06-15
000210 MA2113 80 .50 1982-10-01 1983-02-01
000210 MA2113 180 .50 1982-10-01 1983-02-01
000050 OP1000 10 .25 1982-01-01 1983-02-01
000090 OP1010 10 1.00 1982-01-01 1983-02-01
000280 OP1010 130 1.00 1982-01-01 1983-02-01
000290 OP1010 130 1.00 1982-01-01 1983-02-01
000300 OP1010 130 1.00 1982-01-01 1983-02-01
000310 OP1010 130 1.00 1982-01-01 1983-02-01
000050 OP2010 10 .75 1982-01-01 1983-02-01
000100 OP2010 10 1.00 1982-01-01 1983-02-01
000320 OP2011 140 .75 1982-01-01 1983-02-01
EMP_ACT table
Appendix F. The SAMPLE database 809
Name: EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE
000320 OP2011 150 .25 1982-01-01 1983-02-01
000330 OP2012 140 .25 1982-01-01 1983-02-01
000330 OP2012 160 .75 1982-01-01 1983-02-01
000340 OP2013 140 .50 1982-01-01 1983-02-01
000340 OP2013 170 .50 1982-01-01 1983-02-01
000020 PL2100 30 1.00 1982-01-01 1982-09-15
EMP_PHOTO table
Name: EMPNO PHOTO_FORMAT PICTURE
Type: char(6) not null varchar(10) not null blob(100k)
Desc: Employee number Photo format Photo of employee
Values: 000130 bitmap db200130.bmp
000130 gif db200130.gif
000130 xwd db200130.xwd
000140 bitmap db200140.bmp
000140 gif db200140.gif
000140 xwd db200140.xwd
000150 bitmap db200150.bmp
000150 gif db200150.gif
000150 xwd db200150.xwd
000190 bitmap db200190.bmp
000190 gif db200190.gif
000190 xwd db200190.xwd
EMP_RESUME table
Name: EMPNO RESUME_FORMAT RESUME
Type: char(6) not null varchar(10) not null clob(5k)
Desc: Employee number Resume Format Resume of employee
Values: 000130 ascii db200130.asc
000130 script db200130.scr
000140 ascii db200140.asc
000140 script db200140.scr
000150 ascii db200150.asc
000150 script db200150.scr
EMP_ACT table
810 SQL Reference, Volume 1
Name: EMPNO RESUME_FORMAT RESUME
000190 ascii db200190.asc
000190 script db200190.scr
IN_TRAY table
Name: RECEIVED SOURCE SUBJECT NOTE_TEXT
Type: timestamp char(8) char(64) varchar(3000)
Desc: Date and Timereceived
User id of personsending note
Brief description The note
ORG table
Name: DEPTNUMB DEPTNAME MANAGER DIVISION LOCATION
Type: smallint not null varchar(14) smallint varchar(10) varchar(13)
Desc: Departmentnumber
Department name Manager number Division ofcorporation
City
Values: 10 Head Office 160 Corporate New York
15 New England 50 Eastern Boston
20 Mid Atlantic 10 Eastern Washington
38 South Atlantic 30 Eastern Atlanta
42 Great Lakes 100 Midwest Chicago
51 Plains 140 Midwest Dallas
66 Pacific 270 Western San Francisco
84 Mountain 290 Western Denver
PROJECT table
Name: PROJNO PROJNAME DEPTNO RESPEMP PRSTAFF PRSTDATE PRENDATE MAJPROJ
Type: char(6) notnull
varchar(24)not null
char(3) notnull
char(6) notnull
dec(5,2) date date char(6)
Desc: Projectnumber
Project name Departmentresponsible
Employeeresponsible
Estimatedmeanstaffing
Estimatedstart date
Estimatedend date
Majorproject, for asubproject
Values: AD3100 ADMINSERVICES
D01 000010 6.5 1982-01-01 1983-02-01 -
AD3110 GENERALADMINSYSTEMS
D21 000070 6 1982-01-01 1983-02-01 AD3100
AD3111 PAYROLLPROGRAMMING
D21 000230 2 1982-01-01 1983-02-01 AD3110
EMP_RESUME table
Appendix F. The SAMPLE database 811
Name: PROJNO PROJNAME DEPTNO RESPEMP PRSTAFF PRSTDATE PRENDATE MAJPROJ
AD3112 PERSONNELPROGRAMMING
D21 000250 1 1982-01-01 1983-02-01 AD3110
AD3113 ACCOUNTPROGRAMMING
D21 000270 2 1982-01-01 1983-02-01 AD3110
IF1000 QUERYSERVICES
C01 000030 2 1982-01-01 1983-02-01 -
IF2000 USEREDUCATION
C01 000030 1 1982-01-01 1983-02-01 -
MA2100 WELD LINEAUTOMATION
D01 000010 12 1982-01-01 1983-02-01 -
MA2110 W LPROGRAMMING
D11 000060 9 1982-01-01 1983-02-01 MA2100
MA2111 W LPROGRAMDESIGN
D11 000220 2 1982-01-01 1982-12-01 MA2110
MA2112 W L ROBOTDESIGN
D11 000150 3 1982-01-01 1982-12-01 MA2110
MA2113 W L PRODCONTPROGS
D11 000160 3 1982-02-15 1982-12-01 MA2110
OP1000 OPERATIONSUPPORT
E01 000050 6 1982-01-01 1983-02-01 -
OP1010 OPERATION E11 000090 5 1982-01-01 1983-02-01 OP1000
OP2000 GENSYSTEMSSERVICES
E01 000050 5 1982-01-01 1983-02-01 -
OP2010 SYSTEMSSUPPORT
E21 000100 4 1982-01-01 1983-02-01 OP2000
OP2011 SCPSYSTEMSSUPPORT
E21 000320 1 1982-01-01 1983-02-01 OP2010
OP2012 APPLICATIONSSUPPORT
E21 000330 1 1982-01-01 1983-02-01 OP2010
OP2013 DB/DCSUPPORT
E21 000340 1 1982-01-01 1983-02-01 OP2010
PL2100 WELD LINEPLANNING
B01 000020 1 1982-01-01 1982-09-15 MA2100
SALES table
Name: SALES_DATE SALES_PERSON REGION SALES
Type: date varchar(15) varchar(15) int
Desc: Date of sales Employee’s last name Region of sales Number of sales
Values: 12/31/1995 LUCCHESSI Ontario-South 1
12/31/1995 LEE Ontario-South 3
12/31/1995 LEE Quebec 1
12/31/1995 LEE Manitoba 2
PROJECT table
812 SQL Reference, Volume 1
Name: SALES_DATE SALES_PERSON REGION SALES
12/31/1995 GOUNOT Quebec 1
03/29/1996 LUCCHESSI Ontario-South 3
03/29/1996 LUCCHESSI Quebec 1
03/29/1996 LEE Ontario-South 2
03/29/1996 LEE Ontario-North 2
03/29/1996 LEE Quebec 3
03/29/1996 LEE Manitoba 5
03/29/1996 GOUNOT Ontario-South 3
03/29/1996 GOUNOT Quebec 1
03/29/1996 GOUNOT Manitoba 7
03/30/1996 LUCCHESSI Ontario-South 1
03/30/1996 LUCCHESSI Quebec 2
03/30/1996 LUCCHESSI Manitoba 1
03/30/1996 LEE Ontario-South 7
03/30/1996 LEE Ontario-North 3
03/30/1996 LEE Quebec 7
03/30/1996 LEE Manitoba 4
03/30/1996 GOUNOT Ontario-South 2
03/30/1996 GOUNOT Quebec 18
03/30/1996 GOUNOT Manitoba 1
03/31/1996 LUCCHESSI Manitoba 1
03/31/1996 LEE Ontario-South 14
03/31/1996 LEE Ontario-North 3
03/31/1996 LEE Quebec 7
03/31/1996 LEE Manitoba 3
03/31/1996 GOUNOT Ontario-South 2
03/31/1996 GOUNOT Quebec 1
04/01/1996 LUCCHESSI Ontario-South 3
04/01/1996 LUCCHESSI Manitoba 1
04/01/1996 LEE Ontario-South 8
04/01/1996 LEE Ontario-North -
04/01/1996 LEE Quebec 8
04/01/1996 LEE Manitoba 9
04/01/1996 GOUNOT Ontario-South 3
04/01/1996 GOUNOT Ontario-North 1
04/01/1996 GOUNOT Quebec 3
04/01/1996 GOUNOT Manitoba 7
SALES table
Appendix F. The SAMPLE database 813
STAFF table
Name: ID NAME DEPT JOB YEARS SALARY COMM
Type: smallint notnull
varchar(9) smallint char(5) smallint dec(7,2) dec(7,2)
Desc: Employeenumber
Employeename
Departmentnumber
Job type Years ofservice
Currentsalary
Commission
Values: 10 Sanders 20 Mgr 7 18357.50 -
20 Pernal 20 Sales 8 18171.25 612.45
30 Marenghi 38 Mgr 5 17506.75 -
40 O’Brien 38 Sales 6 18006.00 846.55
50 Hanes 15 Mgr 10 20659.80 -
60 Quigley 38 Sales - 16808.30 650.25
70 Rothman 15 Sales 7 16502.83 1152.00
80 James 20 Clerk - 13504.60 128.20
90 Koonitz 42 Sales 6 18001.75 1386.70
100 Plotz 42 Mgr 7 18352.80 -
110 Ngan 15 Clerk 5 12508.20 206.60
120 Naughton 38 Clerk - 12954.75 180.00
130 Yamaguchi 42 Clerk 6 10505.90 75.60
140 Fraye 51 Mgr 6 21150.00 -
150 Williams 51 Sales 6 19456.50 637.65
160 Molinare 10 Mgr 7 22959.20 -
170 Kermisch 15 Clerk 4 12258.50 110.10
180 Abrahams 38 Clerk 3 12009.75 236.50
190 Sneider 20 Clerk 8 14252.75 126.50
200 Scoutten 42 Clerk - 11508.60 84.20
210 Lu 10 Mgr 10 20010.00 -
220 Smith 51 Sales 7 17654.50 992.80
230 Lundquist 51 Clerk 3 13369.80 189.65
240 Daniels 10 Mgr 5 19260.25 -
250 Wheeler 51 Clerk 6 14460.00 513.30
260 Jones 10 Mgr 12 21234.00 -
270 Lea 66 Mgr 9 18555.50 -
280 Wilson 66 Sales 9 18674.50 811.50
290 Quill 84 Mgr 10 19818.00 -
300 Davis 84 Sales 5 15454.50 806.10
310 Graham 66 Sales 13 21000.00 200.30
320 Gonzales 66 Sales 4 16858.20 844.00
STAFF table
814 SQL Reference, Volume 1
Name: ID NAME DEPT JOB YEARS SALARY COMM
330 Burke 66 Clerk 1 10988.00 55.50
340 Edwards 84 Sales 7 17844.00 1285.00
350 Gafney 84 Clerk 5 13030.50 188.00
STAFFG table (double-byte code pages only)
Name: ID NAME DEPT JOB YEARS SALARY COMM
Type: smallint notnull
vargraphic(9) smallint graphic(5) smallint dec(9,0) dec(9,0)
Desc: Employeenumber
Employeename
Departmentnumber
Job type Years ofservice
Currentsalary
Commission
Values: 10 Sanders 20 Mgr 7 18357.50 -
20 Pernal 20 Sales 8 18171.25 612.45
30 Marenghi 38 Mgr 5 17506.75 -
40 O’Brien 38 Sales 6 18006.00 846.55
50 Hanes 15 Mgr 10 20659.80 -
60 Quigley 38 Sales - 16808.30 650.25
70 Rothman 15 Sales 7 16502.83 1152.00
80 James 20 Clerk - 13504.60 128.20
90 Koonitz 42 Sales 6 18001.75 1386.70
100 Plotz 42 Mgr 7 18352.80 -
110 Ngan 15 Clerk 5 12508.20 206.60
120 Naughton 38 Clerk - 12954.75 180.00
130 Yamaguchi 42 Clerk 6 10505.90 75.60
140 Fraye 51 Mgr 6 21150.00 -
150 Williams 51 Sales 6 19456.50 637.65
160 Molinare 10 Mgr 7 22959.20 -
170 Kermisch 15 Clerk 4 12258.50 110.10
180 Abrahams 38 Clerk 3 12009.75 236.50
190 Sneider 20 Clerk 8 14252.75 126.50
200 Scoutten 42 Clerk - 11508.60 84.20
210 Lu 10 Mgr 10 20010.00 -
220 Smith 51 Sales 7 17654.50 992.80
230 Lundquist 51 Clerk 3 13369.80 189.65
240 Daniels 10 Mgr 5 19260.25 -
250 Wheeler 51 Clerk 6 14460.00 513.30
260 Jones 10 Mgr 12 21234.00 -
STAFF table
Appendix F. The SAMPLE database 815
Name: ID NAME DEPT JOB YEARS SALARY COMM
270 Lea 66 Mgr 9 18555.50 -
280 Wilson 66 Sales 9 18674.50 811.50
290 Quill 84 Mgr 10 19818.00 -
300 Davis 84 Sales 5 15454.50 806.10
310 Graham 66 Sales 13 21000.00 200.30
320 Gonzales 66 Sales 4 16858.20 844.00
330 Burke 66 Clerk 1 10988.00 55.50
340 Edwards 84 Sales 7 17844.00 1285.00
350 Gafney 84 Clerk 5 13030.50 188.00
Sample files with BLOB and CLOB data type
This section shows the data found in the EMP_PHOTO files (pictures ofemployees) and EMP_RESUME files (resumes of employees).
Quintana photo
Quintana resumeThe following text is found in the db200130.asc and db200130.scr files.
Resume: Dolores M. Quintana
Personal Information
Address: 1150 Eglinton Ave Mellonville, Idaho 83725
Phone: (208) 555-9933
Birthdate: September 15, 1925
Sex: Female
Marital Status: Married
Figure 14. Dolores M. Quintana
STAFFG table (double-byte code pages only)
816 SQL Reference, Volume 1
Height: 5’2″
Weight: 120 lbs.
Department Information
Employee Number: 000130
Dept Number: C01
Manager: Sally Kwan
Position: Analyst
Phone: (208) 555-4578
Hire Date: 1971-07-28
Education
1965 Math and English, B.A. Adelphi University
1960 Dental Technician Florida Institute ofTechnology
Work History
10/91 - present Advisory Systems Analyst Producingdocumentation tools for engineeringdepartment.
12/85 - 9/91 Technical Writer, Writer, text programmer, andplanner.
1/79 - 11/85 COBOL Payroll Programmer Writing payrollprograms for a diesel fuel company.
Interests
v Cookingv Readingv Sewingv Remodeling
Quintana resume
Appendix F. The SAMPLE database 817
Nicholls photo
Nicholls resumeThe following text is found in the db200140.asc and db200140.scr files.
Resume: Heather A. Nicholls
Personal Information
Address: 844 Don Mills Ave Mellonville, Idaho 83734
Phone: (208) 555-2310
Birthdate: January 19, 1946
Sex: Female
Marital Status: Single
Height: 5’8″
Weight: 130 lbs.
Department Information
Employee Number: 000140
Dept Number: C01
Manager: Sally Kwan
Position: Analyst
Phone: (208) 555-1793
Hire Date: 1976-12-15
Education
Figure 15. Heather A. Nicholls
Nicholls photo
818 SQL Reference, Volume 1
1972 Computer Engineering, Ph.D. University ofWashington
1969 Music and Physics, M.A. Vassar College
Work History
2/83 - present Architect, OCR Development Designing thearchitecture of OCR products.
12/76 - 1/83 Text Programmer Optical character recognition(OCR) programming in PL/I.
9/72 - 11/76 Punch Card Quality Analyst Checking punchcards met quality specifications.
Interests
v Model railroadingv Interior decoratingv Embroideryv Knitting
Adamson photo
Adamson resumeThe following text is found in the db200150.asc and db200150.scr files.
Resume: Bruce Adamson
Personal Information
Address: 3600 Steeles Ave Mellonville, Idaho 83757
Phone: (208) 555-4489
Figure 16. Bruce Adamson
Nicholls resume
Appendix F. The SAMPLE database 819
Birthdate: May 17, 1947
Sex: Male
Marital Status: Married
Height: 6’0″
Weight: 175 lbs.
Department Information
Employee Number: 000150
Dept Number: D11
Manager: Irving Stern
Position: Designer
Phone: (208) 555-4510
Hire Date: 1972-02-12
Education
1971 Environmental Engineering, M.Sc. JohnsHopkins University
1968 American History, B.A. NorthwesternUniversity
Work History
8/79 - present Neural Network Design Developing neuralnetworks for machine intelligence products.
2/72 - 7/79 Robot Vision Development Developingrule-based systems to emulate sight.
9/71 - 1/72 Numerical Integration Specialist Helping banksystems communicate with each other.
Interests
v Racing motorcyclesv Building loudspeakersv Assembling personal computersv Sketching
Adamson resume
820 SQL Reference, Volume 1
Walker photo
Walker resumeThe following text is found in the db200190.asc and db200190.scr files.
Resume: James H. Walker
Personal Information
Address: 3500 Steeles Ave Mellonville, Idaho 83757
Phone: (208) 555-7325
Birthdate: June 25, 1952
Sex: Male
Marital Status: Single
Height: 5’11″
Weight: 166 lbs.
Department Information
Employee Number: 000190
Dept Number: D11
Manager: Irving Stern
Position: Designer
Phone: (208) 555-2986
Hire Date: 1974-07-26
Education
Figure 17. James H. Walker
Walker photo
Appendix F. The SAMPLE database 821
1974 Computer Studies, B.Sc. University ofMassachusetts
1972 Linguistic Anthropology, B.A. University ofToronto
Work History
6/87 - present Microcode Design Optimizing algorithms formathematical functions.
4/77 - 5/87 Printer Technical Support Installing andsupporting laser printers.
9/74 - 3/77 Maintenance Programming Patching assemblylanguage compiler for mainframes.
Interests
v Wine tastingv Skiingv Swimmingv Dancing
Walker resume
822 SQL Reference, Volume 1
Appendix G. Reserved schema names and reserved words
There are restrictions on the use of certain names that are required by thedatabase manager. In some cases, names are reserved, and cannot be used byapplication programs. In other cases, certain names are not recommended foruse by application programs, although their use is not prevented by thedatabase manager.
The reserved schema names are:v SYSCATv SYSFUNv SYSIBMv SYSSTATv SYSPROC
It is strongly recommended that schema names never begin with the SYSprefix, because SYS, by convention, is used to indicate an area that is reservedby the system.
No user-defined functions, user-defined types, triggers, or aliases can beplaced into a schema whose name starts with SYS (SQLSTATE 42939).
It is also recommended that SESSION not be used as a schema name. Becausedeclared temporary tables must be qualified by SESSION, it is possible tohave an application declare a temporary table with a name that is identical tothat of a persistent table, complicating the application logic. To avoid thispossibility, do not use the schema SESSION except when dealing withdeclared temporary tables.
There are no specifically reserved words in DB2 Version 8. Keywords can beused as ordinary identifiers, except in a context where they could also beinterpreted as SQL keywords. In such cases, the word must be specified as adelimited identifier. For example, COUNT cannot be used as a column namein a SELECT statement, unless it is delimited.
IBM SQL and ISO/ANSI SQL99 include reserved words that are not enforcedby DB2 Universal Database; however, it is recommended that these words notbe used as ordinary identifiers, because it reduces portability.
The DB2 Universal Database reserved words are:
© Copyright IBM Corp. 1993 - 2002 823
ADD DETERMINISTIC LEAVE RESTARTAFTER DISALLOW LEFT RESTRICTALIAS DISCONNECT LIKE RESULTALL DISTINCT LINKTYPE RESULT_SET_LOCATORALLOCATE DO LOCAL RETURNALLOW DOUBLE LOCALE RETURNSALTER DROP LOCATOR REVOKEAND DSNHATTR LOCATORS RIGHTANY DSSIZE LOCK ROLLBACKAPPLICATION DYNAMIC LOCKMAX ROUTINEAS EACH LOCKSIZE ROWASSOCIATE EDITPROC LONG ROWSASUTIME ELSE LOOP RRNAUDIT ELSEIF MAXVALUE RUNAUTHORIZATION ENCODING MICROSECOND SAVEPOINTAUX END MICROSECONDS SCHEMAAUXILIARY END-EXEC MINUTE SCRATCHPADBEFORE END-EXEC1 MINUTES SECONDBEGIN ERASE MINVALUE SECONDSBETWEEN ESCAPE MODE SECQTYBINARY EXCEPT MODIFIES SECURITYBUFFERPOOL EXCEPTION MONTH SELECTBY EXCLUDING MONTHS SENSITIVECACHE EXECUTE NEW SETCALL EXISTS NEW_TABLE SIGNALCALLED EXIT NO SIMPLECAPTURE EXTERNAL NOCACHE SOMECARDINALITY FENCED NOCYCLE SOURCECASCADED FETCH NODENAME SPECIFICCASE FIELDPROC NODENUMBER SQLCAST FILE NOMAXVALUE SQLIDCCSID FINAL NOMINVALUE STANDARDCHAR FOR NOORDER STARTCHARACTER FOREIGN NOT STATICCHECK FREE NULL STAYCLOSE FROM NULLS STOGROUPCLUSTER FULL NUMPARTS STORESCOLLECTION FUNCTION OBID STYLECOLLID GENERAL OF SUBPAGESCOLUMN GENERATED OLD SUBSTRINGCOMMENT GET OLD_TABLE SYNONYMCOMMIT GLOBAL ON SYSFUNCONCAT GO OPEN SYSIBMCONDITION GOTO OPTIMIZATION SYSPROCCONNECT GRANT OPTIMIZE SYSTEMCONNECTION GRAPHIC OPTION TABLECONSTRAINT GROUP OR TABLESPACECONTAINS HANDLER ORDER THENCONTINUE HAVING OUT TOCOUNT HOLD OUTER TRANSACTIONCOUNT_BIG HOUR OVERRIDING TRIGGERCREATE HOURS PACKAGE TRIMCROSS IDENTITY PARAMETER TYPECURRENT IF PART UNDOCURRENT_DATE IMMEDIATE PARTITION UNION
Reserved schema names and reserved words
824 SQL Reference, Volume 1
CURRENT_LC_CTYPE IN PATH UNIQUECURRENT_PATH INCLUDING PIECESIZE UNTILCURRENT_SERVER INCREMENT PLAN UPDATECURRENT_TIME INDEX POSITION USAGECURRENT_TIMESTAMP INDICATOR PRECISION USERCURRENT_TIMEZONE INHERIT PREPARE USINGCURRENT_USER INNER PRIMARY VALIDPROCCURSOR INOUT PRIQTY VALUESCYCLE INSENSITIVE PRIVILEGES VARIABLEDATA INSERT PROCEDURE VARIANTDATABASE INTEGRITY PROGRAM VCATDAY INTO PSID VIEWDAYS IS QUERYNO VOLUMESDB2GENERAL ISOBID READ WHENDB2GENRL ISOLATION READS WHEREDB2SQL ITERATE RECOVERY WHILEDBINFO JAR REFERENCES WITHDECLARE JAVA REFERENCING WLMDEFAULT JOIN RELEASE WRITEDEFAULTS KEY RENAME YEARDEFINITION LABEL REPEAT YEARSDELETE LANGUAGE RESETDESCRIPTOR LC_CTYPE RESIGNAL
The ISO/ANSI SQL99 reserved words that are not in the list of DB2 UniversalDatabase reserved words are:ABSOLUTE DESCRIBE MODULE SESSIONACTION DESTROY NAMES SESSION_USERADMIN DESTRUCTOR NATIONAL SETSAGGREGATE DIAGNOSTICS NATURAL SIZEARE DICTIONARY NCHAR SMALLINTARRAY DOMAIN NCLOB SPACEASC EQUALS NEXT SPECIFICTYPEASSERTION EVERY NONE SQLEXCEPTIONAT EXEC NUMERIC SQLSTATEBIT FALSE OBJECT SQLWARNINGBLOB FIRST OFF STATEBOOLEAN FLOAT ONLY STATEMENTBOTH FOUND OPERATION STRUCTUREBREADTH GROUPING ORDINALITY SYSTEM_USERCASCADE HOST OUTPUT TEMPORARYCATALOG IGNORE PAD TERMINATECLASS INITIALIZE PARAMETERS THANCLOB INITIALLY PARTIAL TIMECOLLATE INPUT POSTFIX TIMESTAMPCOLLATION INT PREFIX TIMEZONE_HOURCOMPLETION INTEGER PREORDER TIMEZONE_MINUTECONSTRAINTS INTERSECT PRESERVE TRAILINGCONSTRUCTOR INTERVAL PRIOR TRANSLATIONCORRESPONDING LARGE PUBLIC TREATCUBE LAST REAL TRUECURRENT_ROLE LATERAL RECURSIVE UNDERDATE LEADING REF UNKNOWNDEALLOCATE LESS RELATIVE UNNEST
Reserved schema names and reserved words
Appendix G. Reserved schema names and reserved words 825
DEC LEVEL ROLE VALUEDECIMAL LIMIT ROLLUP VARCHARDEFERRABLE LOCALTIME SCOPE VARYINGDEFERRED LOCALTIMESTAMP SCROLL WHENEVERDEPTH MAP SEARCH WITHOUTDEREF MATCH SECTION WORKDESC MODIFY SEQUENCE ZONE
Reserved schema names and reserved words
826 SQL Reference, Volume 1
Appendix H. Comparison of isolation levels
The following table summarizes information about isolation levels.
UR CS RS RR
Can the application see uncommittedchanges made by other applicationprocesses?
Yes No No No
Can the application update uncommittedchanges made by other applicationprocesses?
No No No No
Can the re-execution of a statement beaffected by other application processes? Seephenomenon P3 (phantom) below.
Yes Yes Yes No
Can “updated” rows be updated by otherapplication processes? See Note 1 below.
No No No No
Can “updated” rows be read by otherapplication processes that are running at anisolation level other than UR?
No No No No
Can “updated” rows be read by otherapplication processes that are running at theUR isolation level?
Yes Yes Yes Yes
Can “accessed” rows be updated by otherapplication processes? See phenomenon P2(nonrepeatable read) below.
Yes Yes No No
Can “accessed” rows be read by otherapplication processes?
Yes Yes Yes Yes
Can “current” row be updated or deleted byother application processes? See phenomenonP1 (dirty-read) below.
See Note2 below.
See Note2 below.
No No
Notes:
1. The isolation level offers no protection to the application if the application is bothreading and writing a table. For example, an application opens a cursor on a tableand then performs an insert, update, or delete operation on the same table. Theapplication may see inconsistent data when more rows are fetched from the opencursor.
2. If the cursor is not updatable, with CS the current row may be updated or deletedby other application processes in some cases. For example, buffering may cause thecurrent row at the client to be different than what the current row actually is at theserver.
© Copyright IBM Corp. 1993 - 2002 827
UR CS RS RR
Examples of Phenomena:
P1 Dirty Read. Unit of work UW1 modifies a row. Unit of work UW2 reads thatrow before UW1 performs a COMMIT. If UW1 then performs a ROLLBACK,UW2 has read a nonexistent row.
P2 Nonrepeatable Read. Unit of work UW1 reads a row. Unit of work UW2modifies that row and performs a COMMIT. If UW1 then re-reads the row, itmight receive a modified value.
P3 Phantom. Unit of work UW1 reads the set of n rows that satisfies some searchcondition. Unit of work UW2 then INSERTs one or more rows that satisfiesthe search condition and performs a COMMIT. If UW1 then repeats the initialread with the same search condition, it obtains the original rows plus theinserted rows.
Related concepts:
v “Isolation levels” on page 13
Comparison of isolation levels
828 SQL Reference, Volume 1
Appendix I. Interaction of triggers and constraints
This appendix describes the interaction of triggers with referential constraintsand check constraints that may result from an update operation. Figure 18 andthe associated description are representative of the processing that isperformed for an SQL statement that updates data in the database.
Figure 18 shows the general order of processing for an SQL statement thatupdates a table. It assumes a situation where the table includes beforetriggers, referential constraints, check constraints and after triggers thatcascade. The following is a description of the boxes and other items found inFigure 18.v SQL statement S1
This is the DELETE, INSERT, or UPDATE statement that begins the process.The SQL statement S1 identifies a table (or an updatable view over sometable) referred to as the target table throughout this description.
v Determine set of affected rows (SAR)This step is the starting point for a process that repeats for referentialconstraint delete rules of CASCADE and SET NULL and for cascaded SQLstatements from after triggers.The purpose of this step is to determine the set of affected rows for the SQLstatement. The set of rows included in SAR is based on the statement:
SQL statement S1 Determine set ofaffected rows (SAR)
ProcessBEFORE triggers
Apply SAR tothe target table
ApplyConstraints
ProcessAFTER triggers
error
error
violation
error
cascaded SQL statement
= rollback changes to before S1
R
R
R
R
R
Figure 18. Processing an SQL statement with associated triggers and constraints
© Copyright IBM Corp. 1993 - 2002 829
– for DELETE, all rows that satisfy the search condition of the statement(or the current row for a positioned DELETE)
– for INSERT, the rows identified by the VALUES clause or the fullselect– for UPDATE, all rows that satisfy the search condition (or the current
row for a positioned update).
If SAR is empty, there will be no BEFORE triggers, changes to apply to thetarget table, or constraints to process for the SQL statement.
v Process BEFORE triggersAll BEFORE triggers are processed in ascending order of creation. EachBEFORE trigger will process the triggered action once for each row in SAR.An error may occur during the processing of a triggered action in whichcase all changes made as a result of the original SQL statement S1 (so far)are rolled back.If there are no BEFORE triggers or the SAR is empty, this step is skipped.
v Apply SAR to the target tableThe actual delete, insert, or update is applied using SAR to the target tablein the database.An error may occur when applying SAR (such as attempting to insert a rowwith a duplicate key where a unique index exists) in which case all changesmade as a result of the original SQL statement S1 (so far) are rolled back.
v Apply ConstraintsThe constraints associated with the target table are applied if SAR is notempty. This includes unique constraints, unique indexes, referentialconstraints, check constraints and checks related to the WITH CHECKOPTION on views. Referential constraints with delete rules of cascade orset null may cause additional triggers to be activated.A violation of any constraint or WITH CHECK OPTION results in an errorand all changes made as a result of S1 (so far) are rolled back.
v Process AFTER triggersAll AFTER triggers activated by S1 are processed in ascending order ofcreation.FOR EACH STATEMENT triggers will process the triggered action exactlyonce, even if SAR is empty. FOR EACH ROW triggers will process thetriggered action once for each row in SAR.An error may occur during the processing of a triggered action in whichcase all changes made as a result of the original S1 (so far) are rolled back.The triggered action of a trigger may include triggered SQL statements thatare DELETE, INSERT or UPDATE statements. For the purposes of thisdescription, each such statement is considered a cascaded SQL statement.
Interaction of triggers and constraints
830 SQL Reference, Volume 1
A cascaded SQL statement is a DELETE, INSERT, or UPDATE statementthat is processed as part of the triggered action of an AFTER trigger. Thisstatement starts a cascaded level of trigger processing. This can be thoughtof as assigning the triggered SQL statement as a new S1 and performing allof the steps described here recursively.Once all triggered SQL statements from all AFTER triggers activated byeach S1 have been processed to completion, the processing of the original S1
is completed.v �R� = roll back changes to before S1
Any error (including constraint violations) that occurs during processingresults in a roll back of all the changes made directly or indirectly as aresult of the original SQL statement S1. The database is therefore back in thesame state as immediately prior to the execution of the original SQLstatement S1
Interaction of triggers and constraints
Appendix I. Interaction of triggers and constraints 831
Interaction of triggers and constraints
832 SQL Reference, Volume 1
Appendix J. Explain tables
Explain tables
The Explain tables capture access plans when the Explain facility is activated.The Explain tables must be created before Explain can be invoked. You cancreate them using the documented table definitions, or you can create them byinvoking the sample command line processor (CLP) script provided in theEXPLAIN.DDL file located in the 'misc' subdirectory of the 'sqllib' directory.To invoke the script, connect to the database where the Explain tables arerequired, then issue the command:
db2 -tf EXPLAIN.DDL
The population of the Explain tables by the Explain facility will not activatetriggers or referential or check constraints. For example, if an insert triggerwere defined on the EXPLAIN_INSTANCE table, and an eligible statementwere explained, the trigger would not be activated.
Related reference:
v “EXPLAIN_ARGUMENT table” on page 834v “EXPLAIN_OBJECT table” on page 841v “EXPLAIN_OPERATOR table” on page 844v “EXPLAIN_PREDICATE table” on page 846v “EXPLAIN_STREAM table” on page 851v “ADVISE_INDEX table” on page 853v “ADVISE_WORKLOAD table” on page 856v “EXPLAIN_INSTANCE table” on page 838v “EXPLAIN_STATEMENT table” on page 848
© Copyright IBM Corp. 1993 - 2002 833
EXPLAIN_ARGUMENT table
The EXPLAIN_ARGUMENT table represents the unique characteristics foreach individual operator, if there are any.
Table 162. EXPLAIN_ARGUMENT Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No FK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No FK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No FK Name of the package running when thedynamic statement was explained or name ofthe source file when static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No FK Schema, or qualifier, of source of Explainrequest.
EXPLAIN_LEVEL CHAR(1) No FK Level of Explain information for which this rowis relevant.
STMTNO INTEGER No FK Statement number within package to which thisexplain information is related.
SECTNO INTEGER No FK Section number within package to which thisexplain information is related.
OPERATOR_ID INTEGER No No Unique ID for this operator within this query.
ARGUMENT_TYPE CHAR(8) No No The type of argument for this operator.
ARGUMENT_VALUE VARCHAR(1024) Yes No The value of the argument for this operator.NULL if the value is inLONG_ARGUMENT_VALUE.
LONG_ARGUMENT_VALUE CLOB(1M) Yes No The value of the argument for this operator,when the text will not fit inARGUMENT_VALUE. NULL if the value is inARGUMENT_VALUE.
Table 163. ARGUMENT_TYPE and ARGUMENT_VALUE column values
ARGUMENT_TYPEValue
Possible ARGUMENT_VALUE Values Description
AGGMODE COMPLETEPARTIALINTERMEDIATEFINAL
Partial aggregation indicators.
BITFLTR TRUEFALSE
Hash Join will use a bit filter to enhanceperformance.
CSETEMP TRUEFALSE
Temporary Table over CommonSubexpression Flag.
DIRECT TRUE Direct fetch indicator.
EXPLAIN_ARGUMENT table
834 SQL Reference, Volume 1
Table 163. ARGUMENT_TYPE and ARGUMENT_VALUE column values (continued)
ARGUMENT_TYPEValue
Possible ARGUMENT_VALUE Values Description
DUPLWARN TRUEFALSE
Duplicates Warning flag.
EARLYOUT TRUEFALSE
Early out indicator.
ENVVAR Each row of this type will contain:
v Environment variable name
v Environment variable value
Environment variable affecting the optimizer
FETCHMAX IGNOREINTEGER
Override value for MAXPAGES argument onFETCH operator.
GROUPBYC TRUEFALSE
Whether Group By columns were provided.
GROUPBYN Integer Number of comparison columns.
GROUPBYR Each row of this type will contain:
v Ordinal value of column in group byclause (followed by a colon and a space)
v Name of Column
Group By requirement.
INNERCOL Each row of this type will contain:
v Ordinal value of column in order (followedby a colon and a space)
v Name of Column
v Order Value
(A) Ascending
(D) Descending
Inner order columns.
ISCANMAX IGNOREINTEGER
Override value for MAXPAGES argument onISCAN operator.
JN_INPUT INNEROUTER
Indicates if operator is the operator feedingthe inner or outer of a join.
LISTENER TRUEFALSE
Listener Table Queue indicator.
MAXPAGES ALLNONEINTEGER
Maximum pages expected for Prefetch.
MAXRIDS NONEINTEGER
Maximum Row Identifiers to be included ineach list prefetch request.
NUMROWS INTEGER Number of rows expected to be sorted.
ONEFETCH TRUEFALSE
One Fetch indicator.
EXPLAIN_ARGUMENT table
Appendix J. Explain tables 835
Table 163. ARGUMENT_TYPE and ARGUMENT_VALUE column values (continued)
ARGUMENT_TYPEValue
Possible ARGUMENT_VALUE Values Description
OUTERCOL Each row of this type will contain:
v Ordinal value of column in order (followedby a colon and a space)
v Name of Column
v Order Value
(A) Ascending
(D) Descending
Outer order columns.
OUTERJN LEFTRIGHT
Outer join indicator.
PARTCOLS Name of Column Partitioning columns for operator.
PREFETCH LISTNONESEQUENTIAL
Type of Prefetch Eligible.
RMTQTEXT Query text Remote Query Text
ROWLOCK EXCLUSIVENONEREUSESHARESHORT (INSTANT) SHAREUPDATE
Row Lock Intent.
ROWWIDTH INTEGER Width of row to be sorted.
SCANDIR FORWARDREVERSE
Scan Direction.
SCANGRAN INTEGER Intra-partition parallelism, granularity of theintra-partition parallel scan, expressed inSCANUNITs.
SCANTYPE LOCAL PARALLEL intra-partition parallelism, Index or Tablescan.
SCANUNIT ROWPAGE
Intra-partition parallelism, scan granularityunit.
SERVER Remote server Remote server
SHARED TRUE Intra-partition parallelism, shared TEMPindicator.
SLOWMAT TRUEFALSE
Slow Materialization flag.
SNGLPROD TRUEFALSE
Intra-partition parallelism sort or tempproduced by a single agent.
EXPLAIN_ARGUMENT table
836 SQL Reference, Volume 1
Table 163. ARGUMENT_TYPE and ARGUMENT_VALUE column values (continued)
ARGUMENT_TYPEValue
Possible ARGUMENT_VALUE Values Description
SORTKEY Each row of this type will contain:
v Ordinal value of column in key (followedby a colon and a space)
v Name of Column
v Order Value
(A) Ascending
(D) Descending
Sort key columns.
SORTTYPE PARTITIONEDSHAREDROUND ROBINREPLICATED
Intra-partition parallelism, sort type.
TABLOCK EXCLUSIVEINTENT EXCLUSIVEINTENT NONEINTENT SHAREREUSESHARESHARE INTENT EXCLUSIVESUPER EXCLUSIVEUPDATE
Table Lock Intent.
TQDEGREE INTEGER intra-partition parallelism, number ofsubagents accessing Table Queue.
TQMERGE TRUEFALSE
Merging (sorted) Table Queue indicator.
TQREAD READ AHEADSTEPPINGSUBQUERY STEPPING
Table Queue reading property.
TQSEND BROADCASTDIRECTEDSCATTERSUBQUERY DIRECTED
Table Queue send property.
TQTYPE LOCAL Intra-partition parallelism, Table Queue.
TRUNCSRT TRUE Truncated sort (limits number of rowsproduced).
UNIQUE TRUEFALSE
Uniqueness indicator.
UNIQKEY Each row of this type will contain:
v Ordinal value of column in key (followedby a colon and a space)
v Name of Column
Unique key columns.
VOLATILE TRUE Volatile table
EXPLAIN_ARGUMENT table
Appendix J. Explain tables 837
EXPLAIN_INSTANCE table
The EXPLAIN_INSTANCE table is the main control table for all Explaininformation. Each row of data in the Explain tables is explicitly linked to oneunique row in this table. The EXPLAIN_INSTANCE table gives basicinformation about the source of the SQL statements being explained as well asinformation about the environment in which the explanation took place.
Table 164. EXPLAIN_INSTANCE Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No PK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No PK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No PK Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No PK Schema, or qualifier, of source of Explain request.
EXPLAIN_OPTION CHAR(1) No No Indicates what Explain Information was requestedfor this request.
Possible values are:P PLAN SELECTION
SNAPSHOT_TAKEN CHAR(1) No No Indicates whether an Explain Snapshot was takenfor this request.
Possible values are:Y Yes, an Explain Snapshot(s) was taken
and stored in theEXPLAIN_STATEMENT table. RegularExplain information was also captured.
N No Explain Snapshot was taken.Regular Explain information wascaptured.
O Only an Explain Snapshot was taken.Regular Explain information was notcaptured.
DB2_VERSION CHAR(7) No No Product release number for DB2 UniversalDatabase which processed this explain request.Format is vv.rr.m, where:vv Version Numberrr Release Numberm Maintenance Release Number
SQL_TYPE CHAR(1) No No Indicates whether the Explain Instance was forstatic or dynamic SQL.
Possible values are:S Static SQLD Dynamic SQL
EXPLAIN_INSTANCE table
838 SQL Reference, Volume 1
Table 164. EXPLAIN_INSTANCE Table (continued). PK means that the column is part of a primary key;FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
QUERYOPT INTEGER No No Indicates the query optimization class used by theSQL Compiler at the time of the Explaininvocation. The value indicates what level ofquery optimization was performed by the SQLCompiler for the SQL statements being explained.
BLOCK CHAR(1) No No Indicates what type of cursor blocking was usedwhen compiling the SQL statements. For moreinformation, see the BLOCK column inSYSCAT.PACKAGES.
Possible values are:N No BlockingU Block Unambiguous CursorsB Block All Cursors
ISOLATION CHAR(2) No No Indicates what type of isolation was used whencompiling the SQL statements. For moreinformation, see the ISOLATION column inSYSCAT.PACKAGES.
Possible values are:RR Repeatable ReadRS Read StabilityCS Cursor StabilityUR Uncommitted Read
BUFFPAGE INTEGER No No Contains the value of the BUFFPAGE databaseconfiguration setting at the time of the Explaininvocation.
AVG_APPLS INTEGER No No Contains the value of the AVG_APPLSconfiguration parameter at the time of theExplain invocation.
SORTHEAP INTEGER No No Contains the value of the SORTHEAP databaseconfiguration setting at the time of the Explaininvocation.
LOCKLIST INTEGER No No Contains the value of the LOCKLIST databaseconfiguration setting at the time of the Explaininvocation.
MAXLOCKS SMALLINT No No Contains the value of the MAXLOCKS databaseconfiguration setting at the time of the Explaininvocation.
LOCKS_AVAIL INTEGER No No Contains the number of locks assumed to beavailable by the optimizer for each user. (Derivedfrom LOCKLIST and MAXLOCKS.)
CPU_SPEED DOUBLE No No Contains the value of the CPUSPEED databasemanager configuration setting at the time of theExplain invocation.
REMARKS VARCHAR(254) Yes No User-provided comment.
EXPLAIN_INSTANCE table
Appendix J. Explain tables 839
Table 164. EXPLAIN_INSTANCE Table (continued). PK means that the column is part of a primary key;FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
DBHEAP INTEGER No No Contains the value of the DBHEAP databaseconfiguration setting at the time of Explaininvocation.
COMM_SPEED DOUBLE No No Contains the value of the COMM_BANDWIDTHdatabase configuration setting at the time ofExplain invocation.
PARALLELISM CHAR(2) No No Possible values are:
v N = No parallelism
v P = Intra-partition parallelism
v IP = Inter-partition parallelism
v BP = Intra-partition parallelism andinter-partition parallelism
DATAJOINER CHAR(1) No No Possible values are:
v N = Non-federated systems plan
v Y = Federated systems plan
EXPLAIN_INSTANCE table
840 SQL Reference, Volume 1
EXPLAIN_OBJECT table
The EXPLAIN_OBJECT table identifies those data objects required by theaccess plan generated to satisfy the SQL statement.
Table 165. EXPLAIN_OBJECT Table. PK means that the column is part of a primary key; FK means thatthe column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No FK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No FK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No FK Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No FK Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No FK Level of Explain information for which this row isrelevant.
STMTNO INTEGER No FK Statement number within package to which thisexplain information is related.
SECTNO INTEGER No FK Section number within package to which thisexplain information is related.
OBJECT_SCHEMA VARCHAR(128) No No Schema to which this object belongs.
OBJECT_NAME VARCHAR(128) No No Name of the object.
OBJECT_TYPE CHAR(2) No No Descriptive label for the type of object.
CREATE_TIME TIMESTAMP Yes No Time of Object’s creation; null if a table function.
STATISTICS_TIME TIMESTAMP Yes No Last time of update to statistics for this object;null if statistics do not exist for this object.
COLUMN_COUNT SMALLINT No No Number of columns in this object.
ROW_COUNT INTEGER No No Estimated number of rows in this object.
WIDTH INTEGER No No The average width of the object in bytes. Set to -1for an index.
PAGES INTEGER No No Estimated number of pages that the objectoccupies in the buffer pool. Set to -1 for a tablefunction.
DISTINCT CHAR(1) No No Indicates if the rows in the object are distinct (i.e.no duplicates)
Possible values are:
Y Yes
N No
TABLESPACE_NAME VARCHAR(128) Yes No Name of the table space in which this object isstored; set to null if no table space is involved.
EXPLAIN_OBJECT table
Appendix J. Explain tables 841
Table 165. EXPLAIN_OBJECT Table (continued). PK means that the column is part of a primary key; FKmeans that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
OVERHEAD DOUBLE No No Total estimated overhead, in milliseconds, for asingle random I/O to the specified table space.Includes controller overhead, disk seek, andlatency times. Set to -1 if no table space isinvolved.
TRANSFER_RATE DOUBLE No No Estimated time to read a data page, inmilliseconds, from the specified table space. Set to-1 if no table space is involved.
PREFETCHSIZE INTEGER No No Number of data pages to be read when prefetch isperformed. Set to -1 for a table function.
EXTENTSIZE INTEGER No No Size of extent, in data pages. This many pages arewritten to one container in the table space beforeswitching to the next container. Set to -1 for atable function.
CLUSTER DOUBLE No No Degree of data clustering with the index. If >= 1,this is the CLUSTERRATIO. If >= 0 and < 1, thisis the CLUSTERFACTOR. Set to -1 for a table,table function, or if this statistic is not available.
NLEAF INTEGER No No Number of leaf pages this index object’s valuesoccupy. Set to -1 for a table, table function, or ifthis statistic is not available.
NLEVELS INTEGER No No Number of index levels in this index object’s tree.Set to -1 for a table, table function, or if thisstatistic is not available.
FULLKEYCARD BIGINT No No Number of distinct full key values contained inthis index object. Set to -1 for a table, tablefunction, or if this statistic is not available.
OVERFLOW INTEGER No No Total number of overflow records in the table. Setto -1 for an index, table function, or if this statisticis not available.
FIRSTKEYCARD BIGINT No No Number of distinct first key values. Set to −1 for atable, table function or if this statistic is notavailable.
FIRST2KEYCARD BIGINT No No Number of distinct first key values using the first{2,3,4} columns of the index. Set to −1 for a table,table function or if this statistic is not available.
FIRST3KEYCARD BIGINT No No
FIRST4KEYCARD BIGINT No No
SEQUENTIAL_PAGES INTEGER No No Number of leaf pages located on disk in index keyorder with few or no large gaps between them.Set to −1 for a table, table function or if thisstatistic is not available.
DENSITY INTEGER No No Ratio of SEQUENTIAL_PAGES to number ofpages in the range of pages occupied by theindex, expressed as a percentage (integer between0 and 100). Set to −1 for a table, table function orif this statistic is not available.
EXPLAIN_OBJECT table
842 SQL Reference, Volume 1
Table 166. Possible OBJECT_TYPE Values
Value Description
IX Index
TA Table
TF Table Function
EXPLAIN_OBJECT table
Appendix J. Explain tables 843
EXPLAIN_OPERATOR table
The EXPLAIN_OPERATOR table contains all the operators needed to satisfythe SQL statement by the SQL compiler.
Table 167. EXPLAIN_OPERATOR Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No FK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No FK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No FK Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No FK Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No FK Level of Explain information for which this row isrelevant.
STMTNO INTEGER No FK Statement number within package to which thisexplain information is related.
SECTNO INTEGER No FK Section number within package to which thisexplain information is related.
OPERATOR_ID INTEGER No No Unique ID for this operator within this query.
OPERATOR_TYPE CHAR(6) No No Descriptive label for the type of operator.
TOTAL_COST DOUBLE No No Estimated cumulative total cost (in timerons) ofexecuting the chosen access plan up to andincluding this operator.
IO_COST DOUBLE No No Estimated cumulative I/O cost (in data pageI/Os) of executing the chosen access plan up toand including this operator.
CPU_COST DOUBLE No No Estimated cumulative CPU cost (in instructions) ofexecuting the chosen access plan up to andincluding this operator.
FIRST_ROW_COST DOUBLE No No Estimated cumulative cost (in timerons) offetching the first row for the access plan up to andincluding this operator. This value includes anyinitial overhead required.
RE_TOTAL_COST DOUBLE No No Estimated cumulative cost (in timerons) offetching the next row for the chosen access planup to and including this operator.
RE_IO_COST DOUBLE No No Estimated cumulative I/O cost (in data pageI/Os) of fetching the next row for the chosenaccess plan up to and including this operator.
RE_CPU_COST DOUBLE No No Estimated cumulative CPU cost (in instructions) offetching the next row for the chosen access planup to and including this operator.
EXPLAIN_OPERATOR table
844 SQL Reference, Volume 1
Table 167. EXPLAIN_OPERATOR Table (continued). PK means that the column is part of a primary key;FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
COMM_COST DOUBLE No No Estimated cumulative communication cost (inTCP/IP frames) of executing the chosen accessplan up to and including this operator.
FIRST_COMM_COST DOUBLE No No Estimated cumulative communications cost (inTCP/IP frames) of fetching the first row for thechosen access plan up to and including thisoperator. This value includes any initial overheadrequired.
BUFFERS DOUBLE No No Estimated buffer requirements for this operatorand its inputs.
REMOTE_TOTAL_COST DOUBLE No No Estimated cumulative total cost (in timerons) ofperforming operation(s) on remote database(s).
REMOTE_COMM_COST DOUBLE No No Estimated cumulative communication cost ofexecuting the chosen remote access plan up to andincluding this operator.
Table 168. OPERATOR_TYPE values
Value Description
DELETE Delete
FETCH Fetch
FILTER Filter rows
GENROW Generate Row
GRPBY Group By
HSJOIN Hash Join
INSERT Insert
IXAND Dynamic Bitmap Index ANDing
IXSCAN Index Scan
MSJOIN Merge Scan Join
NLJOIN Nested loop Join
RETURN Result
RIDSCN Row Identifier (RID) Scan
RQUERY Remote Query
SORT Sort
TBSCAN Table Scan
TEMP Temporary Table Construction
TQ Table Queue
UNION Union
UNIQUE Duplicate Elimination
UPDATE Update
EXPLAIN_OPERATOR table
Appendix J. Explain tables 845
EXPLAIN_PREDICATE table
The EXPLAIN_PREDICATE table identifies which predicates are applied by aspecific operator.
Table 169. EXPLAIN_PREDICATE Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No FK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No FK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No FK Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No FK Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No FK Level of Explain information for which this row isrelevant.
STMTNO INTEGER No FK Statement number within package to which thisexplain information is related.
SECTNO INTEGER No FK Section number within package to which thisexplain information is related.
OPERATOR_ID INTEGER No No Unique ID for this operator within this query.
PREDICATE_ID INTEGER No No Unique ID for this predicate for the specifiedoperator.
HOW_APPLIED CHAR(5) No No How predicate is being used by the specifiedoperator.
WHEN_EVALUATED CHAR(3) No No Indicates when the subquery used in thispredicate is evaluated.
Possible values are:
blank This predicate does not contain asubquery.
EAA The subquery used in this predicate isevaluated at application (EAA). That is,it is re-evaluated for every rowprocessed by the specified operator, asthe predicate is being applied.
EAO The subquery used in this predicate isevaluated at open (EAO). That is, it isre-evaluated only once for the specifiedoperator, and its results are re-used inthe application of the predicate for eachrow.
MUL There is more than one type ofsubquery in this predicate.
EXPLAIN_PREDICATE table
846 SQL Reference, Volume 1
Table 169. EXPLAIN_PREDICATE Table (continued). PK means that the column is part of a primary key;FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
RELOP_TYPE CHAR(2) No No The type of relational operator used in thispredicate.
SUBQUERY CHAR(1) No No Whether or not a data stream from a subquery isrequired for this predicate. There may be multiplesubquery streams required.
Possible values are:
N No subquery stream is required
Y One or more subquery streams isrequired
FILTER_FACTOR DOUBLE No No The estimated fraction of rows that will bequalified by this predicate.
PREDICATE_TEXT CLOB(1M) Yes No The text of the predicate as recreated from theinternal representation of the SQL statement.
Null if not available.
Table 170. Possible HOW_APPLIED Values
Value Description
JOIN Used to join tables
RESID Evaluated as a residual predicate
SARG Evaluated as a sargable predicate for index or data page
START Used as a start condition
STOP Used as a stop condition
Table 171. Possible RELOP_TYPE Values
Value Description
blanks Not Applicable
EQ Equals
GE Greater Than or Equal
GT Greater Than
IN In list
LE Less Than or Equal
LK Like
LT Less Than
NE Not Equal
NL Is Null
NN Is Not Null
EXPLAIN_PREDICATE table
Appendix J. Explain tables 847
EXPLAIN_STATEMENT table
The EXPLAIN_STATEMENT table contains the text of the SQL statement as itexists for the different levels of Explain information. The original SQLstatement as entered by the user is stored in this table along with the versionused (by the optimizer) to choose an access plan to satisfy the SQL statement.The latter version may bear little resemblance to the original as it may havebeen rewritten and/or enhanced with additional predicates as determined bythe SQL Compiler.
Table 172. EXPLAIN_STATEMENT Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No PK,FK
Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No PK,FK
Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No PK,FK
Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No PK,FK
Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No PK Level of Explain information for which this rowis relevant.
Valid values are:O Original Text (as entered by user)P PLAN SELECTION
STMTNO INTEGER No PK Statement number within package to which thisexplain information is related. Set to 1 fordynamic Explain SQL statements. For static SQLstatements, this value is the same as the valueused for the SYSCAT.STATEMENTS catalog view.
SECTNO INTEGER No PK Section number within package that contains thisSQL statement. For dynamic Explain SQLstatements, this is the section number used tohold the section for this statement at runtime. Forstatic SQL statements, this value is the same asthe value used for the SYSCAT.STATEMENTScatalog view.
QUERYNO INTEGER No No Numeric identifier for explained SQL statement.For dynamic SQL statements (excluding theEXPLAIN SQL statement) issued through CLP orCLI, the default value is a sequentiallyincremented value. Otherwise, the default valueis the value of STMTNO for static SQL statementsand 1 for dynamic SQL statements.
EXPLAIN_STATEMENT table
848 SQL Reference, Volume 1
Table 172. EXPLAIN_STATEMENT Table (continued). PK means that the column is part of a primarykey; FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
QUERYTAG CHAR(20) No No Identifier tag for each explained SQL statement.For dynamic SQL statements issued through CLP(excluding the EXPLAIN SQL statement), thedefault value is 'CLP'. For dynamic SQLstatements issued through CLI (excluding theEXPLAIN SQL statement), the default value is'CLI'. Otherwise, the default value used is blanks.
STATEMENT_TYPE CHAR(2) No No Descriptive label for type of query beingexplained.
Possible values are:S SelectD DeleteDC Delete where current of cursorI InsertU UpdateUC Update where current of cursor
UPDATABLE CHAR(1) No No Indicates if this statement is consideredupdatable. This is particularly relevant to SELECTstatements which may be determined to bepotentially updatable.
Possible values are:’ ’ Not applicable (blank)N NoY Yes
DELETABLE CHAR(1) No No Indicates if this statement is considered deletable.This is particularly relevant to SELECT statementswhich may be determined to be potentiallydeletable.
Possible values are:’ ’ Not applicable (blank)N NoY Yes
TOTAL_COST DOUBLE No No Estimated total cost (in timerons) of executing thechosen access plan for this statement; set to 0(zero) if EXPLAIN_LEVEL is O (original text)since no access plan has been chosen at this time.
STATEMENT_TEXT CLOB(1M) No No Text or portion of the text of the SQL statementbeing explained. The text shown for the PlanSelection level of Explain has been reconstructedfrom the internal representation and is SQL-likein nature; that is, the reconstructed statement isnot guaranteed to follow correct SQL syntax.
EXPLAIN_STATEMENT table
Appendix J. Explain tables 849
Table 172. EXPLAIN_STATEMENT Table (continued). PK means that the column is part of a primarykey; FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
SNAPSHOT BLOB(10M) Yes No Snapshot of internal representation for this SQLstatement at the Explain_Level shown.
This column is intended for use with DB2 VisualExplain. Column is set to null ifEXPLAIN_LEVEL is 0 (original statement) sinceno access plan has been chosen at the time thatthis specific version of the statement is captured.
QUERY_DEGREE INTEGER No No Indicates the degree of intra-partition parallelismat the time of Explain invocation. For the originalstatement, this contains the directed degree ofintra-partition parallelism. For the PLANSELECTION, this contains the degree ofintra-partition parallelism generated for the planto use.
EXPLAIN_STATEMENT table
850 SQL Reference, Volume 1
EXPLAIN_STREAM table
The EXPLAIN_STREAM table represents the input and output data streamsbetween individual operators and data objects. The data objects themselvesare represented in the EXPLAIN_OBJECT table. The operators involved in adata stream are to be found in the EXPLAIN_OPERATOR table.
Table 173. EXPLAIN_STREAM Table. PK means that the column is part of a primary key; FK means thatthe column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No FK Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No FK Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No FK Name of the package running when the dynamicstatement was explained or name of the sourcefile when the static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No FK Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No FK Level of Explain information for which this row isrelevant.
STMTNO INTEGER No FK Statement number within package to which thisexplain information is related.
SECTNO INTEGER No FK Section number within package to which thisexplain information is related.
STREAM_ID INTEGER No No Unique ID for this data stream within thespecified operator.
SOURCE_TYPE CHAR(1) No No Indicates the source of this data stream:
O Operator
D Data Object
SOURCE_ID SMALLINT No No Unique ID for the operator within this query thatis the source of this data stream. Set to -1 ifSOURCE_TYPE is ’D’.
TARGET_TYPE CHAR(1) No No Indicates the target of this data stream:
O Operator
D Data Object
TARGET_ID SMALLINT No No Unique ID for the operator within this query thatis the target of this data stream. Set to -1 ifTARGET_TYPE is ’D’.
OBJECT_SCHEMA VARCHAR(128) Yes No Schema to which the affected data object belongs.Set to null if both SOURCE_TYPE andTARGET_TYPE are ’O’.
OBJECT_NAME VARCHAR(128) Yes No Name of the object that is the subject of datastream. Set to null if both SOURCE_TYPE andTARGET_TYPE are ’O’.
STREAM_COUNT DOUBLE No No Estimated cardinality of data stream.
EXPLAIN_STREAM table
Appendix J. Explain tables 851
Table 173. EXPLAIN_STREAM Table (continued). PK means that the column is part of a primary key;FK means that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
COLUMN_COUNT SMALLINT No No Number of columns in data stream.
PREDICATE_ID INTEGER No No If this stream is part of a subquery for a predicate,the predicate ID will be reflected here, otherwisethe column is set to -1.
COLUMN_NAMES CLOB(1M) Yes No This column contains the names and orderinginformation of the columns involved in thisstream.
These names will be in the format of:
NAME1(A)+NAME2(D)+NAME3+NAME4
Where (A) indicates a column in ascending order,(D) indicates a column in descending order, andno ordering information indicates that either thecolumn is not ordered or ordering is not relevant.
PMID SMALLINT No No Partitioning map ID.
SINGLE_NODE CHAR(5) Yes No Indicates if this data stream is on a single ormultiple partitions:
MULT On multiple partitions
COOR On coordinator node
HASH Directed using hashing
RID Directed using the row ID
FUNC Directed using a function(HASHEDVALUE() orDBPARTITIONNUM())
CORR Directed using a correlation value
NumbericDirected to predetermined single node
PARTITION_COLUMNS CLOB(64K) Yes No List of columns this data stream is partitioned on.
EXPLAIN_STREAM table
852 SQL Reference, Volume 1
ADVISE_INDEX table
The ADVISE_INDEX table represents the recommended indexes.
Table 174. ADVISE_INDEX Table. PK means that the column is part of a primary key; FK means that thecolumn is part of a foreign key.
Column Name Data Type Nullable? Key? Description
EXPLAIN_REQUESTER VARCHAR(128) No No Authorization ID of initiator of this Explainrequest.
EXPLAIN_TIME TIMESTAMP No No Time of initiation for Explain request.
SOURCE_NAME VARCHAR(128) No No Name of the package running when the dynamicstatement was explained or name of the sourcefile when static SQL was explained.
SOURCE_SCHEMA VARCHAR(128) No No Schema, or qualifier, of source of Explain request.
EXPLAIN_LEVEL CHAR(1) No No Level of Explain information for which this row isrelevant.
STMTNO INTEGER No No Statement number within package to which thisexplain information is related.
SECTNO INTEGER No No Section number within package to which thisexplain information is related.
QUERYNO INTEGER No No Numeric identifier for explained SQL statement.For dynamic SQL statements (excluding theEXPLAIN SQL statement) issued through CLP orCLI, the default value is a sequentiallyincremented value. Otherwise, the default value isthe value of STMTNO for static SQL statementsand 1 for dynamic SQL statements.
QUERYTAG CHAR(20) No No Identifier tag for each explained SQL statement.For dynamic SQL statements issued through CLP(excluding the EXPLAIN SQL statement), thedefault value is 'CLP'. For dynamic SQLstatements issued through CLI (excluding theEXPLAIN SQL statement), the default value is'CLI'. Otherwise, the default value used is blanks.
NAME VARCHAR(128) No No Name of the index.
CREATOR VARCHAR(128) No No Qualifier of the index name.
TBNAME VARCHAR(128) No No Name of the table or nickname on which theindex is defined.
TBCREATOR VARCHAR(128) No No Qualifier of the table name.
COLNAMES CLOB(64K) No No List of column names.
UNIQUERULE CHAR(1) No No Unique rule:
D = Duplicates allowed
P = Primary index
U = Unique entries only allowed
COLCOUNT SMALLINT No No Number of columns in the key plus the number ofinclude columns if any.
ADVISE_INDEX table
Appendix J. Explain tables 853
Table 174. ADVISE_INDEX Table (continued). PK means that the column is part of a primary key; FKmeans that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
IID SMALLINT No No Internal index ID.
NLEAF INTEGER No No Number of leaf pages; −1 if statistics are notgathered.
NLEVELS SMALLINT No No Number of index levels; −1 if statistics are notgathered.
FULLKEYCARD BIGINT No No Number of distinct full key values; −1 if statisticsare not gathered.
FIRSTKEYCARD BIGINT No No Number of distinct first key values; −1 if statisticsare not gathered.
CLUSTERRATIO SMALLINT No No Degree of data clustering with the index; −1 ifstatistics are not gathered or if detailed indexstatistics are gathered (in which case,CLUSTERFACTOR will be used instead).
CLUSTERFACTOR DOUBLE No No Finer measurement of degree of clustering, or −1if detailed index statistics have not been gatheredor if the index is defined on a nickname.
USERDEFINED SMALLINT No No Defined by the user.
SYSTEM_REQUIRED SMALLINT No No 1 if one or the other of the followingconditions is met:
– This index is required for a primary orunique key constraint, or this index is adimension block index or composite blockindex for a multi-dimensional clustering(MDC) table.
– This is an index on the (OID) column of atyped table.
2 if both of the following conditions are met:
– This index is required for a primary orunique key constraint, or this index is adimension block index or composite blockindex for an MDC table.
– This is an index on the (OID) column of atyped table.
0 otherwise.
CREATE_TIME TIMESTAMP No No Time when the index was created.
STATS_TIME TIMESTAMP Yes No Last time when any change was made to recordedstatistics for this index. Null if no statisticsavailable.
PAGE_FETCH_PAIRS VARCHAR(254) No No A list of pairs of integers, represented in characterform. Each pair represents the number of pages ina hypothetical buffer, and the number of pagefetches required to scan the table with this indexusing that hypothetical buffer. (Zero-length stringif no data available.)
ADVISE_INDEX table
854 SQL Reference, Volume 1
Table 174. ADVISE_INDEX Table (continued). PK means that the column is part of a primary key; FKmeans that the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
REMARKS VARCHAR(254) Yes No User-supplied comment, or null.
DEFINER VARCHAR(128) No No User who created the index.
CONVERTED CHAR(1) No No Reserved for future use.
SEQUENTIAL_PAGES INTEGER No No Number of leaf pages located on disk in index keyorder with few or no large gaps between them.(−1 if no statistics are available.)
DENSITY INTEGER No No Ratio of SEQUENTIAL_PAGES to number ofpages in the range of pages occupied by theindex, expressed as a percent (integer between 0and 100, −1 if no statistics are available.)
FIRST2KEYCARD BIGINT No No Number of distinct keys using the first twocolumns of the index (−1 if no statistics orinapplicable)
FIRST3KEYCARD BIGINT No No Number of distinct keys using the first threecolumns of the index (−1 if no statistics orinapplicable)
FIRST4KEYCARD BIGINT No No Number of distinct keys using the first fourcolumns of the index (−1 if no statistics orinapplicable)
PCTFREE SMALLINT No No Percentage of each index leaf page to be reservedduring initial building of the index. This space isavailable for future inserts after the index is built.
UNIQUE_COLCOUNT SMALLINT No No The number of columns required for a unique key.Always <=COLCOUNT. < COLCOUNT only ifthere a include columns. −1 if index has nounique key (permits duplicates)
MINPCTUSED SMALLINT No No If not zero, then online index defragmentation isenabled, and the value is the threshold ofminimum used space before merging pages.
REVERSE_SCANS CHAR(1) No No Y = Index supports reverse scans
N = Index does not support reverse scans
USE_INDEX CHAR(1) Yes No Y = index recommended or evaluated
N = index not to be recommended
CREATION_TEXT CLOB(1M) No No The SQL statement used to create the index.
PACKED_DESC BLOB(20M) Yes No Internal description of the table.
ADVISE_INDEX table
Appendix J. Explain tables 855
ADVISE_WORKLOAD table
The ADVISE_WORKLOAD table represents the statement that makes up theworkload.
Table 175. ADVISE_WORKLOAD Table. PK means that the column is part of a primary key; FK meansthat the column is part of a foreign key.
Column Name Data Type Nullable? Key? Description
WORKLOAD_NAME CHAR(128) No No Name of the collection of SQL statements(workload) that this statments belongs to.
STATEMENT_NO INTEGER No No Statement number within the workload to whichthis explain information is related.
STATEMENT_TEXT CLOB(1M) No No Content of the SQL statement.
STATEMENT_TAG VARCHAR(256) No No Identifier tag for each explained SQL statement.
FREQUENCY INTEGER No No The number of times this statement appearswithin the workload.
IMPORTANCE DOUBLE No No Importance of the statement.
COST_BEFORE DOUBLE Yes No The cost (in timerons) of the query if therecommended indexes are not created.
COST_AFTER DOUBLE Yes No The cost (in timerons) of the query if therecommended indexes are created.
ADVISE_WORKLOAD table
856 SQL Reference, Volume 1
Appendix K. Explain register values
Following is a description of the interaction of the CURRENT EXPLAINMODE and CURRENT EXPLAIN SNAPSHOT special register values, bothwith each other and with the PREP and BIND commands.
With dynamic SQL, the CURRENT EXPLAIN MODE and CURRENTEXPLAIN SNAPSHOT special register values interact as follows.
Table 176. Interaction of Explain Special Register Values (Dynamic SQL)
EXPLAINSNAPSHOT
values
EXPLAIN MODE values
NO YES EXPLAIN RECOMMENDINDEXES
EVALUATEINDEXES
NO v Resultsof queryreturned.
v Explain tablespopulated
v Results ofqueryreturned.
v Explain tablespopulated.
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Explain tablespopulated.
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesrecommended.
v Explain tablespopulated.
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesevaluated.
YES v ExplainSnapshottaken.
v Resultsof queryreturned.
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofqueryreturned.
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesrecommended.
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesevaluated.
© Copyright IBM Corp. 1993 - 2002 857
Table 176. Interaction of Explain Special Register Values (Dynamic SQL) (continued)
EXPLAINSNAPSHOT
values
EXPLAIN MODE values
NO YES EXPLAIN RECOMMENDINDEXES
EVALUATEINDEXES
EXPLAIN v ExplainSnapshottaken
v Resultsof querynotreturned(Dynamicstatementsnotexecuted).
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesrecommended.
v Explain tablespopulated
v ExplainSnapshottaken
v Results ofquery notreturned(Dynamicstatements notexecuted).
v Indexesevaluated.
The CURRENT EXPLAIN MODE special register interacts with the EXPLAINbind option in the following way for dynamic SQL.
Table 177. Interaction of EXPLAIN Bind Option and CURRENT EXPLAIN MODE
EXPLAINMODEvalues
EXPLAIN Bind option values
NO YES ALL
NO v Results of query returned. v Explain tables populatedfor static SQL
v Results of query returned.
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query returned.
YES v Explain tables populatedfor dynamic SQL
v Results of query returned.
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query returned.
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query returned.
EXPLAIN v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
Explain register values
858 SQL Reference, Volume 1
Table 177. Interaction of EXPLAIN Bind Option and CURRENT EXPLAIN MODE (continued)
EXPLAINMODEvalues
EXPLAIN Bind option values
NO YES ALL
RECOMMENDINDEXES
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Recommend indexes
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Recommend indexes
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Recommend indexes
EVALUATEINDEXES
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Evaluate indexes
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Evaluate indexes
v Explain tables populatedfor static SQL
v Explain tables populatedfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Evaluate indexes
The CURRENT EXPLAIN SNAPSHOT special register interacts with theEXPLSNAP bind option in the following way for dynamic SQL.
Table 178. Interaction of EXPLSNAP bind Option and CURRENT EXPLAIN SNAPSHOT
EXPLAINSNAPSHOT
values
EXPLSNAP Bind option values
NO YES ALL
NO v Results of query returned. v Explain Snapshot takenfor static SQL
v Results of query returned.
v Explain Snapshot takenfor static SQL
v Explain Snapshot takenfor dynamic SQL
v Results of query returned.
YES v Explain Snapshot takenfor dynamic SQL
v Results of query returned.
v Explain Snapshot takenfor static SQL
v Explain Snapshot takenfor dynamic SQL
v Results of query returned.
v Explain Snapshot takenfor static SQL
v Explain Snapshot takenfor dynamic SQL
v Results of query returned.
Explain register values
Appendix K. Explain register values 859
Table 178. Interaction of EXPLSNAP bind Option and CURRENT EXPLAIN SNAPSHOT (continued)
EXPLAINSNAPSHOT
values
EXPLSNAP Bind option values
NO YES ALL
EXPLAIN v Explain Snapshot takenfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Explain Snapshot takenfor static SQL
v Explain Snapshot takenfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
v Explain Snapshot takenfor static SQL
v Explain Snapshot takenfor dynamic SQL
v Results of query notreturned (Dynamicstatements not executed).
Explain register values
860 SQL Reference, Volume 1
Appendix L. Recursion example: bill of materials
Bill of materials (BOM) applications are a common requirement in manybusiness environments. To illustrate the capability of a recursive commontable expression for BOM applications, consider a table of parts withassociated subparts and the quantity of subparts required by the part. For thisexample, create the table as follows:
CREATE TABLE PARTLIST(PART VARCHAR(8),SUBPART VARCHAR(8),QUANTITY INTEGER);
To give query results for this example, assume that the PARTLIST table ispopulated with the following values:
PART SUBPART QUANTITY-------- -------- -----------00 01 500 05 301 02 201 03 301 04 401 06 302 05 702 06 603 07 604 08 1004 09 1105 10 1005 11 1006 12 1006 13 1007 14 807 12 8
Example 1: Single level explosion
The first example is called single level explosion. It answers the question,“What parts are needed to build the part identified by ’01’?”. The list willinclude the direct subparts, subparts of the subparts and so on. However, if apart is used multiple times, its subparts are only listed once.WITH RPL (PART, SUBPART, QUANTITY) AS
( SELECT ROOT.PART, ROOT.SUBPART, ROOT.QUANTITYFROM PARTLIST ROOTWHERE ROOT.PART = ’01’
UNION ALLSELECT CHILD.PART, CHILD.SUBPART, CHILD.QUANTITYFROM RPL PARENT, PARTLIST CHILD
© Copyright IBM Corp. 1993 - 2002 861
WHERE PARENT.SUBPART = CHILD.PART)
SELECT DISTINCT PART, SUBPART, QUANTITYFROM RPLORDER BY PART, SUBPART, QUANTITY;
The above query includes a common table expression, identified by the nameRPL, that expresses the recursive part of this query. It illustrates the basicelements of a recursive common table expression.
The first operand (fullselect) of the UNION, referred to as the initializationfullselect, gets the direct children of part ’01’. The FROM clause of thisfullselect refers to the source table and will never refer to itself (RPL in thiscase). The result of this first fullselect goes into the common table expressionRPL (Recursive PARTLIST). As in this example, the UNION must always be aUNION ALL.
The second operand (fullselect) of the UNION uses RPL to compute subpartsof subparts by having the FROM clause refer to the common table expressionRPL and the source table with a join of a part from the source table (child) toa subpart of the current result contained in RPL (parent). The result goes backto RPL again. The second operand of UNION is then used repeatedly until nomore children exist.
The SELECT DISTINCT in the main fullselect of this query ensures the samepart/subpart is not listed more than once.
The result of the query is as follows:PART SUBPART QUANTITY-------- -------- -----------01 02 201 03 301 04 401 06 302 05 702 06 603 07 604 08 1004 09 1105 10 1005 11 1006 12 1006 13 1007 12 807 14 8
Observe in the result that from part ’01’ we go to ’02’ which goes to ’06’ andso on. Further, notice that part ’06’ is reached twice, once through ’01’ directly
Example 1: Single level explosion
862 SQL Reference, Volume 1
and another time through ’02’. In the output, however, its subcomponents arelisted only once (this is the result of using a SELECT DISTINCT) as required.
It is important to remember that with recursive common table expressions it ispossible to introduce an infinite loop. In this example, an infinite loop wouldbe created if the search condition of the second operand that joins the parentand child tables was coded as:
PARENT.SUBPART = CHILD.SUBPART
This example of causing an infinite loop is obviously a case of not codingwhat is intended. However, care should also be exercised in determining whatto code so that there is a definite end of the recursion cycle.
The result produced by this example query could be produced in anapplication program without using a recursive common table expression.However, this approach would require starting of a new query for every levelof recursion. Furthermore, the application needs to put all the results back inthe database to order the result. This approach complicates the applicationlogic and does not perform well. The application logic becomes even harderand more inefficient for other bill of material queries, such as summarizedand indented explosion queries.
Example 2: Summarized explosion
The second example is a summarized explosion. The question posed here is,what is the total quantity of each part required to build part ’01’. The maindifference from the single level explosion is the need to aggregate thequantities. The first example indicates the quantity of subparts required forthe part whenever it is required. It does not indicate how many of thesubparts are needed to build part ’01’.WITH RPL (PART, SUBPART, QUANTITY) AS
(SELECT ROOT.PART, ROOT.SUBPART, ROOT.QUANTITYFROM PARTLIST ROOTWHERE ROOT.PART = ’01’
UNION ALLSELECT PARENT.PART, CHILD.SUBPART, PARENT.QUANTITY*CHILD.QUANTITYFROM RPL PARENT, PARTLIST CHILDWHERE PARENT.SUBPART = CHILD.PART
)SELECT PART, SUBPART, SUM(QUANTITY) AS "Total QTY Used"FROM RPLGROUP BY PART, SUBPARTORDER BY PART, SUBPART;
In the above query, the select list of the second operand of the UNION in therecursive common table expression, identified by the name RPL, shows theaggregation of the quantity. To find out how much of a subpart is used, the
Example 1: Single level explosion
Appendix L. Recursion example: bill of materials 863
quantity of the parent is multiplied by the quantity per parent of a child. If apart is used multiple times in different places, it requires another finalaggregation. This is done by the grouping over the common table expressionRPL and using the SUM column function in the select list of the mainfullselect.
The result of the query is as follows:PART SUBPART Total Qty Used-------- -------- --------------01 02 201 03 301 04 401 05 1401 06 1501 07 1801 08 4001 09 4401 10 14001 11 14001 12 29401 13 15001 14 144
Looking at the output, consider the line for subpart ’06’. The total quantityused value of 15 is derived from a quantity of 3 directly for part ’01’ and aquantity of 6 for part ’02’ which is needed 2 times by part ’01’.
Example 3: Controlling depth
The question may come to mind, what happens when there are more levels ofparts in the table than you are interested in for your query? That is, how is aquery written to answer the question, “What are the first two levels of partsneeded to build the part identified by ’01’?” For the sake of clarity in theexample, the level is included in the result.WITH RPL (LEVEL, PART, SUBPART, QUANTITY) AS
(SELECT 1, ROOT.PART, ROOT.SUBPART, ROOT.QUANTITYFROM PARTLIST ROOTWHERE ROOT.PART = ’01’
UNION ALLSELECT PARENT.LEVEL+1, CHILD.PART, CHILD.SUBPART, CHILD.QUANTITYFROM RPL PARENT, PARTLIST CHILDWHERE PARENT.SUBPART = CHILD.PART
AND PARENT.LEVEL < 2)
SELECT PART, LEVEL, SUBPART, QUANTITYFROM RPL;
This query is similar to example 1. The column LEVEL was introduced tocount the levels from the original part. In the initialization fullselect, the value
Example 2: Summarized explosion
864 SQL Reference, Volume 1
for the LEVEL column is initialized to 1. In the subsequent fullselect, the levelfrom the parent is incremented by 1. Then to control the number of levels inthe result, the second fullselect includes the condition that the parent levelmust be less than 2. This ensures that the second fullselect only processeschildren to the second level.
The result of the query is:PART LEVEL SUBPART QUANTITY-------- ----------- -------- -----------01 1 02 201 1 03 301 1 04 401 1 06 302 2 05 702 2 06 603 2 07 604 2 08 1004 2 09 1106 2 12 1006 2 13 10
Example 3: Controlling depth
Appendix L. Recursion example: bill of materials 865
Example 3: Controlling depth
866 SQL Reference, Volume 1
Appendix M. Exception tables
Exception tables are user-created tables that mimic the definition of the tablesthat are specified to be checked using SET INTEGRITY with the IMMEDIATECHECKED option. They are used to store copies of the rows that violateconstraints in the tables being checked.
The exception tables used with LOAD are identical to the ones used here.They can therefore be reused during checking with the SET INTEGRITYstatement.
Rules for creating an exception table
The rules for creating an exception table are as follows:v The first “n” columns of the exception table are the same as the columns of
the table being checked. All column attributes including name, type andlength should be identical.
v All the columns of the exception table must be free of any constraints andtriggers. Constraints include referential integrity, check constraints as wellas unique index constraints that could cause errors on insert.
v The “(n+1)” column of the exception table is an optional TIMESTAMPcolumn. This serves to identify successive invocations of checking by theSET INTEGRITY statement on the same table, if the rows within theexception table have not been deleted before issuing the SET INTEGRITYstatement to check the data.
v The “(n+2)” column should be of type CLOB(32K) or larger. This column isoptional but recommended, and will be used to give the names of theconstraints that the data within the row violates. If this column is notprovided (as could be warranted if, for example, the original table had themaximum number of columns allowed), then only the row where theconstraint violation was detected is copied.
v The exception table should be created with both “(n+1)” and “(n+2)”columns.
v There is no enforcement of any particular name for the above additionalcolumns. However, the type specification must be exactly followed.
v No additional columns are allowed.v If the original table has DATALINK columns, the corresponding columns in
the exception table should specify NO LINK CONTROL. This ensures thata file is not linked when a row (with DATALINK column) is inserted andan access token is not generated when rows are selected from the exceptiontable.
© Copyright IBM Corp. 1993 - 2002 867
v If the original table has generated columns (including the IDENTITYproperty), the corresponding columns in the exception table should notspecify the generated property.
v It should also be noted that users invoking SET INTEGRITY to check thedata must have INSERT privilege on the exception tables.
The information in the “message” column will be according to the followingstructure:
Table 179. Exception Table Message Column Structure
Fieldnumber
Contents Size Comments
1 Number of constraint violations 5 characters Right justified padded with ’0’
2 Type of first constraint violation 1 character ’K’ - Check Constraint violation’F’ - Foreign Key violation’G’ - Generated Column violation’I’ - Unique Index violationa
’L’ - DATALINK load violation’D’ - Delete Cascade violation
3 Length of constraint/columnb
/index IDc/DLVDESCd5 characters Right justified padded with ’0’
4 Constraint name/Columnnameb/index IDc/DLVDESCd
length from the previousfield
5 Separator 3 characters <space><colon><space>
6 Type of next constraint violation 1 character ’K’ - Check Constraint violation’F’ - Foreign Key violation’G’ - Generated Column violation’I’ - Unique Index violation’L’ - DATALINK load violation’D’ - Delete Cascade violation
7 Length ofconstraint/column/index ID/DLVDESC
5 characters Right justified padded with ’0’
8 Constraint name/Columnname/Index ID/ DLVDESC
length from the previousfield
..... ..... ..... Repeat Field 5 through 8 for eachviolation
Rules for creating an exception table
868 SQL Reference, Volume 1
Table 179. Exception Table Message Column Structure (continued)
Fieldnumber
Contents Size Comments
v a Unique index violations will not occur with checking using SET INTEGRITY. This will be reported,however, when running LOAD if the FOR EXCEPTION option is chosen. LOAD, on the other hand,will not report check constraint, generated column, and foreign key violations in the exception tables.
v b To retrieve the expression of a generated column from the catalog views, use a select statement. Forexample, if field 4 is MYSCHEMA.MYTABLE.GEN_1, then SELECT SUBSTR(TEXT, 1, 50) FROMSYSCAT.COLUMNS WHERE TABSCHEMA=’MYSCHEMA’ AND TABNAME=’MYNAME’ ANDCOLNAME=’GEN_1’; will return the first fifty characters of the expression, in the form ″AS(<expression>)″
v c To retrieve an index ID from the catalog views, use a select statement. For example, if field 4 is 1234,then SELECT INDSCHEMA, INDNAME FROM SYSCAT.INDEXES WHERE IID=1234.
v dDLVDESC is a DATALINK Load Violation DESCriptor described below.
Table 180. DATALINK Load Violation DESCriptor (DLVDESC)
Fieldnumber
Contents Size Comments
1 Number of violating DATALINKcolumns
4 characters Right justified padded with ’0’
2 DATALINK column number ofthe first violating column
4 characters Right justified padded with ’0’
2 DATALINK column number ofthe second violating column
4 characters Right justified padded with ’0’
..... ..... ..... Repeat for each violating columnnumber
Note:v DATALINK column number is COLNO in SYSCAT.COLUMNS for the appropriate table.
Handling rows in an exception table
The information in the exception tables can be processed in any mannerdesired. The rows could be used to correct the data and re-insert the rows intothe original tables.
If there are no INSERT triggers on the original table, transfer the correctedrows by issuing an INSERT statement with a subquery on the exception table.
If there are INSERT triggers and you wish to complete the load with thecorrected rows from exception tables without firing the triggers, the followingways are suggested:
Rules for creating an exception table
Appendix M. Exception tables 869
v Design the INSERT triggers to be fired depending on the value in a columndefined explicitly for the purpose.
v Unload the data from the exception tables and append them using LOAD.In this case if we re-check the data, it should be noted that in DB2 Version 8the constraint violation checking is not confined to the appended rows only.
v Save the trigger text from the relevant catalog table. Then drop the INSERTtrigger and use INSERT to transfer the corrected rows from the exceptiontables. Finally recreate the trigger using the saved information.
In DB2 Version 8, no explicit provision is made to prevent the firing oftriggers when inserting rows from the exception tables.
Only one violation per row will be reported for unique index violations.
If values with long string or LOB data types are in the table, the values willnot be inserted into the exception table in case of unique index violation.
Querying exception tables
The message column structure in an exception table is a concatenated list ofconstraint names, lengths and delimiters as described earlier. You may wish towrite a query on this information.
For example, let’s write a query to obtain a list of all the violations, repeatingeach row with only the constraint name along with it. Let us assume that ouroriginal table T1 had two columns C1 and C2. Assume also, that thecorresponding exception table E1 has columns C1, C2 pertaining to those inT1 and MSGCOL as the message column. The following query (usingrecursion) will list one constraint name per row (repeating the row for morethan one violation):WITH IV (C1, C2, MSGCOL, CONSTNAME, I, J) AS(SELECT C1, C2, MSGCOL,
CHAR(SUBSTR(MSGCOL, 12,INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0)))),
1,15+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0))FROM E1
UNION ALLSELECT C1, C2, MSGCOL,
CHAR(SUBSTR(MSGCOL, J+6,INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0)))),
I+1,J+9+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0))
FROM IVWHERE I < INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,1,5)),5,0))
) SELECT C1, C2, CONSTNAME FROM IV;
Handling rows in an exception table
870 SQL Reference, Volume 1
If we want all the rows that violated a particular constraint, we could extendthis query as follows:WITH IV (C1, C2, MSGCOL, CONSTNAME, I, J) AS(SELECT C1, C2, MSGCOL,
CHAR(SUBSTR(MSGCOL, 12,INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0)))),
1,15+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0))
FROM E1UNION ALLSELECT C1, C2, MSGCOL,
CHAR(SUBSTR(MSGCOL, J+6,INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0)))),
I+1,J+9+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0))
FROM IVWHERE I < INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,1,5)),5,0))
) SELECT C1, C2, CONSTNAME FROM IV WHERE CONSTNAME = ’constraintname’;
To obtain all the Check Constraint violations, one could execute the following:WITH IV (C1, C2, MSGCOL, CONSTNAME, CONSTTYPE, I, J) AS
(SELECT C1, C2, MSGCOL,CHAR(SUBSTR(MSGCOL, 12,
INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0)))),CHAR(SUBSTR(MSGCOL, 6, 1)),1,15+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,7,5)),5,0))
FROM E1UNION ALLSELECT C1, C2, MSGCOL,
CHAR(SUBSTR(MSGCOL, J+6,INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0)))),
CHAR(SUBSTR(MSGCOL, J, 1)),I+1,J+9+INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,J+1,5)),5,0))
FROM IVWHERE I < INTEGER(DECIMAL(VARCHAR(SUBSTR(MSGCOL,1,5)),5,0))
) SELECT C1, C2, CONSTNAME FROM IV WHERE CONSTTYPE = ’K’;
Querying exception tables
Appendix M. Exception tables 871
Querying exception tables
872 SQL Reference, Volume 1
Appendix N. SQL statements allowed in routines
The following table indicates whether or not an SQL statement (specified inthe first column) is allowed to execute in a routine with the specified SQLdata access indication. If an executable SQL statement is encountered in aroutine defined with NO SQL, SQLSTATE 38001 is returned. For otherexecution contexts, SQL statements that are not supported in any contextreturn SQLSTATE 38003. For other SQL statements not allowed in aCONTAINS SQL context, SQLSTATE 38004 is returned. In a READS SQLDATA context, SQLSTATE 38002 is returned. During creation of an SQLroutine, a statement that does not match the SQL data access indication willcause SQLSTATE 42985 to be returned.
If a statement invokes a routine, the effective SQL data access indication forthe statement will be the greater of:v The SQL data access indication of the statement from the following table.v The SQL data access indication of the routine specified when the routine
was created.
For example, the CALL statement has an SQL data access indication ofCONTAINS SQL. However, if a stored procedure defined as READS SQLDATA is called, the effective SQL data access indication for the CALLstatement is READS SQL DATA.
When a routine invokes an SQL statement, the effective SQL data accessindication for the statement must not exceed the SQL data access indicationdeclared for the routine. For example, a function defined as READS SQLDATA could not call a stored procedure defined as MODIFIES SQL DATA.
Table 181. SQL Statement and SQL Data Access Indication
SQL Statement NO SQL CONTAINSSQL
READS SQLDATA
MODIFIESSQL DATA
ALTER... N N N Y
BEGIN DECLARESECTION
Y(1) Y Y Y
CALL N Y Y Y
CLOSE CURSOR N N Y Y
COMMENT ON N N N Y
COMMIT N N(4) N(4) N(4)
COMPOUND SQL N Y Y Y
© Copyright IBM Corp. 1993 - 2002 873
Table 181. SQL Statement and SQL Data Access Indication (continued)
SQL Statement NO SQL CONTAINSSQL
READS SQLDATA
MODIFIESSQL DATA
CONNECT(2) N N N N
CREATE N N N Y
DECLARE CURSOR Y(1) Y Y Y
DECLARE GLOBALTEMPORARY TABLE
N N N Y
DELETE N N N Y
DESCRIBE N N Y Y
DISCONNECT(2) N N N N
DROP ... N N N Y
END DECLARE SECTION Y(1) Y Y Y
EXECUTE N Y(3) Y(3) Y
EXECUTE IMMEDIATE N Y(3) Y(3) Y
EXPLAIN N N N Y
FETCH N N Y Y
FREE LOCATOR N Y Y Y
FLUSH EVENTMONITOR
N N N Y
GRANT ... N N N Y
INCLUDE Y(1) Y Y Y
INSERT N N N Y
LOCK TABLE N Y Y Y
OPEN CURSOR N N Y Y
PREPARE N Y Y Y
REFRESH TABLE N N N Y
RELEASECONNECTION(2)
N N N N
RELEASE SAVEPOINT N N N Y
RENAME TABLE N N N Y
REVOKE ... N N N Y
ROLLBACK N N(4) N(4) N(4)
ROLLBACK TOSAVEPOINT
N N N Y
SAVEPOINT N N N Y
SQL statements allowed in routines
874 SQL Reference, Volume 1
Table 181. SQL Statement and SQL Data Access Indication (continued)
SQL Statement NO SQL CONTAINSSQL
READS SQLDATA
MODIFIESSQL DATA
SELECT INTO N N Y Y
SET CONNECTION(2) N N N N
SET INTEGRITY N N N Y
SET special register N Y Y Y
UPDATE N N N Y
VALUES INTO N N Y Y
WHENEVER Y(1) Y Y Y
Notes:
1. Although the NO SQL option implies that no SQL statements can bespecified, non-executable statements are not restricted.
2. Connection management statements are not allowed in any routineexecution context.
3. It depends on the statement being executed. The statement specified forthe EXECUTE statement must be a statement that is allowed in the contextof the particular SQL access level in effect. For example, if the SQL accesslevel in effect is READS SQL DATA, the statement must not be an INSERT,UPDATE, or DELETE.
4. The COMMIT statement and the ROLLBACK statement without the TOSAVEPOINT clause can be used in a stored procedure, but only if thestored procedure is called directly from an application, or indirectlythrough nested stored procedure calls from an application. (If any trigger,function, method, or atomic compound statement is in the call chain to thestored procedure, COMMIT or ROLLBACK of a unit of work is notallowed.)
SQL statements allowed in routines
Appendix N. SQL statements allowed in routines 875
SQL statements allowed in routines
876 SQL Reference, Volume 1
Appendix O. CALL invoked from a compiled statement
Invokes a procedure stored at the location of a database. A stored procedure,for example, executes at the location of the database, and returns data to theclient application.
Programs using the SQL CALL statement are designed to run in two parts,one on the client and the other on the server. The server procedure at thedatabase runs within the same transaction as the client application. If theclient application and stored procedure are on the same partition, the storedprocedure is executed locally.
Note: This form of the CALL statement is deprecated, and is only beingprovided for compatibility with previous versions of DB2.
Invocation:
This form of the CALL statement can only be embedded in an applicationprogram precompiled with the CALL_RESOLUTION DEFERRED option. Itcannot be used in triggers, SQL procedures, or any other non-applicationcontexts. It is an executable statement that cannot be dynamically prepared.However, the procedure name can be specified through a host variable andthis, coupled with the use of the USING DESCRIPTOR clause, allows both theprocedure name and the parameter list to be provided at run time, whichachieves an effect similar to that of a dynamically prepared statement.
Authorization:
The privileges held by the authorization ID of the CALL statement at run timemust include at least one of the following:v EXECUTE privilege for the package associated with the stored procedure
(EXECUTE privilege on the stored procedure is not checked.)v CONTROL privilege for the package associated with the stored procedurev SYSADM or DBADM authority
Syntax:
�� CALL procedure-namehost-variable
�
( ),
host-variableUSING DESCRIPTOR descriptor-name
��
© Copyright IBM Corp. 1993 - 2002 877
Description:
procedure-name or host-variableIdentifies the procedure to call. The procedure name may be specifiedeither directly or within a host variable. The procedure identified mustexist at the current server (SQLSTATE 42724).
If procedure-name is specified, it must be an ordinary identifier that is notgreater than 254 bytes. Because this can only be an ordinary identifier, itcannot contain blanks or special characters. The value is converted touppercase. If it is necessary to use lowercase names, blanks, or specialcharacters, the name must be specified via a host-variable.
If host-variable is specified, it must be a character-string variable with alength attribute that is not greater than 254 bytes, and it must not includean indicator variable. The value is not converted to uppercase. Thecharacter string must be left-justified.
The procedure name can take one of several forms:
procedure-nameThe name (with no extension) of the procedure to execute. Theprocedure that is invoked is determined as follows.1. The procedure-name is used to search the defined procedures (in
SYSCAT.ROUTINES) for a matching procedure. A matchingprocedure is determined using the steps that follow.a. Find the procedures (ROUTINETYPE is ’P’) from the catalog
(SYSCAT.ROUTINES), where the ROUTINENAME matches thespecified procedure-name, and the ROUTINESCHEMA is aschema name in the SQL path (CURRENT PATH specialregister). If the schema name is explicitly specified, the SQLpath is ignored, and only procedures with the specified schemaname are considered.
b. Next, eliminate any of these procedures that do not have thesame number of parameters as the number of argumentsspecified in the CALL statement.
c. Chose the remaining procedure that is earliest in the SQL path.
If a procedure is selected, DB2 will invoke the procedure definedby the external name.
2. If no matching procedure was found, procedure-name is used bothas the name of the stored procedure library, and the function namewithin that library. For example, if procedure-name is proclib, theDB2 server will load the stored procedure library named procliband execute the function routine proclib() within that library.
CALL invoked from a compiled statement
878 SQL Reference, Volume 1
In UNIX-based systems, the default directory for stored procedurelibraries is sqllib/function. The default directory for unfencedstored procedures is sqllib/function/unfenced.In Windows-based systems, the default directory for storedprocedure libraries is sqllib\function. The default directory forunfenced stored procedures is sqllib\function\unfenced.
If the library or function could not be found, an error is returned(SQLSTATE 42884).
procedure-library!function-nameThe exclamation character (!) acts as a delimiter between the libraryname and the function name of the stored procedure. For example, ifproclib!func is specified, proclib is loaded into memory, and thefunction func from that library is executed. This allows multiplefunctions to be placed in the same stored procedure library.
The stored procedure library is located in the directories or specifiedin the LIBPATH variable, as described in procedure-name.
absolute-path!function-nameThe absolute-path specifies the complete path to the stored procedurelibrary.
In a UNIX-based system, for example, if /u/terry/proclib!func isspecified, the stored procedure library proclib is obtained from thedirectory /u/terry, and the function func from that library isexecuted.
In all of these cases, the total length of the procedure name, including itsimplicit or explicit full path, must not be longer than 254 bytes.
(host-variable,...)Each specification of host-variable is a parameter of the CALL statement.The nth parameter of the CALL corresponds to the nth parameter of theserver’s stored procedure.
Each host-variable is assumed to be used for exchanging data in bothdirections between client and server. To avoid sending unnecessary databetween client and server, the client application should provide anindicator variable with each parameter, and set the indicator to -1 if theparameter is not used to transmit data to the stored procedure. The storedprocedure should set the indicator variable to -128 for any parameter thatis not used to return data to the client application.
If the server is DB2 Universal Database, the parameters must havematching data types in both the client and server program.
CALL invoked from a compiled statement
Appendix O. CALL invoked from a compiled statement 879
USING DESCRIPTOR descriptor-nameIdentifies an SQLDA that must contain a valid description of hostvariables. The nth SQLVAR element corresponds to the nth parameter ofthe server’s stored procedure.
Before the CALL statement is processed, the application must set thefollowing fields in the SQLDA:v SQLN to indicate the number of SQLVAR occurrences provided in the
SQLDAv SQLDABC to indicate the number of bytes of storage allocated for the
SQLDAv SQLD to indicate the number of variables used in the SQLDA when
processing the statementv SQLVAR occurrences to indicate the attributes of the variables. The
following fields of each Base SQLVAR element passed must beinitialized:– SQLTYPE– SQLLEN– SQLDATA– SQLIND
The following fields of each Secondary SQLVAR element passed mustbe initialized:– LEN.SQLLONGLEN– SQLDATALEN– SQLDATATYPE_NAME
The SQLDA is assumed to be used for exchanging data in both directionsbetween client and server. To avoid sending unnecessary data betweenclient and server, the client application should set the SQLIND field to -1if the parameter is not used to transmit data to the stored procedure. Thestored procedure should set the SQLIND field -128 for any parameter thatis not used to return data to the client application.
Notes:
v Use of Large Object (LOB) data types:If the client and server application needs to specify LOB data from anSQLDA, allocate double the number of SQLVAR entries.LOB data types have been supported by stored procedures since DB2Version 2. The LOB data types are not supported by all down level clientsor servers.
v Retrieving the RETURN_STATUS from an SQL procedure:
CALL invoked from a compiled statement
880 SQL Reference, Volume 1
If an SQL procedure successfully issues a RETURN statement with a statusvalue, this value is returned in the first SQLERRD field of the SQLCA. Ifthe CALL statement is issued in an SQL procedure, use the GETDIAGNOSTICS statement to retrieve the RETURN_STATUS value. Thevalue is −1 if the SQLSTATE indicates an error.
v Returning result sets from stored procedures:If the client application program is written using CLI, result sets can bereturned directly to the client application. The stored procedure indicatesthat a result set is to be returned by declaring a cursor on that result set,opening a cursor on the result set, and leaving the cursor open whenexiting the procedure.At the end of a procedure:– For every cursor that has been left open, a result set is returned to the
application.– If more than one cursor is left open, the result sets are returned in the
order in which their cursors were opened.– Only unread rows are passed back. For example, if the result set of a
cursor has 500 rows, and 150 of those rows have been read by the storedprocedure at the time the stored procedure is terminated, rows 151through 500 will be returned to the stored procedure.
v Handling of special registers:The settings of special registers for the caller are inherited by the storedprocedure on invocation, and restored upon return to the caller. Specialregisters may be changed within a stored procedure, but these changes donot affect the caller. This is not true for legacy stored procedures (thosedefined with parameter style DB2DARI, or found in the default library),where the changes made to special registers in a procedure become thesettings for the caller.
v Compatibilities:There is a newer, preferred, form of the CALL statement that can beembedded in an application (by precompiling the application with theCALL_RESOLUTION IMMEDIATE option), or that can be dynamicallyprepared.
Examples:
Example 1:
In C, invoke a procedure called TEAMWINS in the ACHIEVE library, passingit a parameter stored in the host variable HV_ARGUMENT.
strcpy(HV_PROCNAME, "ACHIEVE!TEAMWINS");CALL :HV_PROCNAME (:HV_ARGUMENT);
CALL invoked from a compiled statement
Appendix O. CALL invoked from a compiled statement 881
Example 2:
In C, invoke a procedure called :SALARY_PROC, using the SQLDA namedINOUT_SQLDA.
struct sqlda *INOUT_SQLDA;/* Setup code for SQLDA variables goes here */CALL :SALARY_PROCUSING DESCRIPTOR :*INOUT_SQLDA;
Example 3:
A Java stored procedure is defined in the database, using the followingstatement:
CREATE PROCEDURE PARTS_ON_HAND (IN PARTNUM INTEGER,OUT COST DECIMAL(7,2),OUT QUANTITY INTEGER)
EXTERNAL NAME ’parts!onhand’LANGUAGE JAVAPARAMETER STYLE DB2GENERAL;
A Java application calls this stored procedure using the following codefragment:
...CallableStatement stpCall;
String sql = "CALL PARTS_ON_HAND (?,?,?)";
stpCall = con.prepareCall( sql ) ; /* con is the connection */
stpCall.setInt( 1, variable1 ) ;stpCall.setBigDecimal( 2, variable2 ) ;stpCall.setInt( 3, variable3 ) ;
stpCall.registerOutParameter( 2, Types.DECIMAL, 2 ) ;stpCall.registerOutParameter( 3, Types.INTEGER ) ;
stpCall.execute() ;
variable2 = stpCall.getBigDecimal(2) ;variable3 = stpCall.getInt(3) ;...
This application code fragment will invoke the Java method onhand in classparts, because the procedure name specified on the CALL statement is foundin the database and has the external name ’parts!onhand’.
Related reference:
v “CALL statement” in the SQL Reference, Volume 2
CALL invoked from a compiled statement
882 SQL Reference, Volume 1
Appendix P. Japanese and traditional-Chinese extendedUNIX code (EUC) considerations
Extended UNIX Code (EUC) for Japanese and Traditional-Chinese defines aset of encoding rules that can support from 1 to 4 character sets. In somecases, such as Japanese EUC (eucJP) and Traditional-Chinese EUC (eucTW), acharacter may be encoded using more than two bytes. Use of such anencoding scheme has implications when used as the code page of thedatabase server or the database client. The key considerations involve thefollowing:v Expansion or contraction of strings when converting between EUC code
pages and double-byte code pagesv Use of Universal Character Set-2 (UCS-2) as the code page for graphic data
stored in a database server defined with the eucJP (Japanese) or eucTW(Traditional-Chinese) code pages.
With the exception of these considerations, the use of EUC is consistent withthe double-byte character set (DBCS) support. Throughout this book (andothers), references to double-byte have been changed to multi-byte to reflectsupport for encoding rules that allow for character representations that requiremore than 2 bytes. Detailed considerations for support of Japanese andTraditional-Chinese EUC are included here. This information should beconsidered by anyone using SQL with an EUC database server or an EUCdatabase client, and used in conjunction with application developmentinformation.
Language elements
CharactersEach multi-byte character is considered a letter with the exception of thedouble-byte blank character which is considered a special character.
TokensMulti-byte lowercase alphabetic letters are not folded to uppercase. Thisdiffers from the single byte lowercase alphabetic letters in tokens which aregenerally folded to uppercase.
Identifiers
SQL identifiersConversion between a double-byte code page and an EUC code page mayresult in the conversion of double-byte characters to multi-byte charactersencoded with more than 2 bytes. As a result, an identifier that fits the length
© Copyright IBM Corp. 1993 - 2002 883
maximum in the double-byte code page may exceed the length in the EUCcode page. Selecting identifiers for this type of environment must be donecarefully to avoid expansion beyond the maximum identifier length.
Data types
Character stringsIn an MBCS database, character strings may contain a mixture of charactersfrom a single-byte character set (SBCS) and from multi-byte character sets(MBCS). When using such strings, operations may provide different results ifthey are character based (treat the data as characters) or byte based (treat thedata as bytes). Check the function or operation description to determine howmixed strings are processed.
Graphic stringsA graphic string is defined as a sequence of double-byte character data. Inorder to allow Japanese or Traditional-Chinese EUC data to be stored ingraphic columns, EUC characters are encoded in UCS-2. Characters that arenot double-byte characters under all supported encoding schemes (forexample, PC or EBCDIC DBCS) should not be used with graphic columns.The results of using other than double-byte characters may result inreplacement by substitution characters during conversion. Retrieval of suchdata will not return the same value as was entered.
Assignments and comparisons
String assignments: Conversion of a string is performed prior to theassignment. In cases involving an eucJP/eucTW code page and a DBCS codepage, a character string may become longer (DBCS to eucJP/eucTW) orshorter (eucJP/eucTW to DBCS). This may result in errors on storageassignment and truncation on retrieval assignment. When the error on storageassignment is due to expansion during conversion, SQLSTATE 22524 isreturned instead of SQLSTATE 22001.
Similarly, assignments involving graphic strings may result in the conversionof a UCS-2 encoded double-byte character to a substitution character in a PCor EBCDIC DBCS code page for characters that do not have a correspondingdouble-byte character. Assignments that replace characters with substitutioncharacters will indicate this by setting the SQLWARN10 field of the SQLCA to’W’.
In cases of truncation during retrieval assignment involving multi-bytecharacter strings, the point of truncation may be part of a multi-byte character.In this case, each byte of the character fragment is replaced with a single-byteblank. This means that more than one single-byte blank may appear at theend of a truncated character string.
SQL identifiers
884 SQL Reference, Volume 1
String comparisons: String comparisons are performed on a byte basis.Character strings also use the collating sequence defined for the database.Graphic strings do not use the collating sequence and, in an eucJP or eucTWdatabase, are encoded using UCS-2. Thus, the comparison of two mixedcharacter strings may have a different result from the comparison of twographic strings even though they contain the same characters. Similarly, theresulting sort order of a mixed character column and a graphic column maybe different.
Rules for result data typesThe resulting data type for character strings is not affected by the possibleexpansion of the string. For example, a union of two CHAR operands will stillbe a CHAR. However, if one of the character string operands will beconverted such that the maximum expansion makes the length attribute thelargest of the two operands, then the resulting character string length attributeis affected. For example, consider the result expressions of a CASE expressionthat have data types of VARCHAR(100) and VARCHAR(120). Assume theVARCHAR(100) expression is a mixed string host variable (that may requireconversion) and the VARCHAR(120) expression is a column in the eucJPdatabase. The resulting data type is VARCHAR(200) since the VARCHAR(100)is doubled to allow for possible conversion. The same scenario without theinvolvement of an eucJP or eucTW database would have a result type ofVARCHAR(120).
Notice that the doubling of the host variable length is based on the fact thatthe database server is Japanese EUC or Traditional-Chinese EUC. Even if theclient is also eucJP or eucTW, the doubling is still applied. This allows thesame application package to be used by double-byte or multi-byte clients.
Rules for string conversionsThe types of operations listed in the corresponding section of the SQLReference may convert operands to either the application or the database codepage.
If such operations are done in a mixed code page environment that includesJapanese or Traditional-Chinese EUC, expansion or contraction of mixedcharacter string operands can occur. Therefore, the resulting data type has alength attribute that accommodates the maximum expansion, if possible. Incases where there are restrictions on the length attribute of the data type, themaximum allowed length for the data type is used. For example in anenvironment where maximum growth is double, a VARCHAR(200) hostvariable is treated as if it is a VARCHAR(400), but CHAR(200) host variable istreated as if it is a CHAR(254). A run-time error may occur when conversionis performed if the converted string would exceed the maximum length forthe data type. For example, the union of CHAR(200) and CHAR(10) would
String comparisons
Appendix P. Japanese and traditional-Chinese extended UNIX code (EUC) considerations 885
have a result type of CHAR(254). When the value from the left side of theUNION is converted, if more than 254 characters are required, an error occurs.
In some cases, allowing for the maximum growth for conversion will causethe length attribute to exceed a limit. For example, UNION only allowscolumns up to 254 bytes. Thus, a query with a union that included a hostvariable in the column list (call it :hv1) that was a DBCS mixed characterstring defined as a varying length character string 128 bytes long, would setthe data type to VARCHAR(256) resulting in an error preparing the query,even though the query in the application does not appear to have anycolumns greater than 254. In a situation where the actual string is not likely tocause expansion beyond 254 bytes, the following can be used to prepare thestatement.
SELECT CAST(:hv1 CONCAT ’ AS VARCHAR(254)), C2 FROM T1UNIONSELECT C1, C2 FROM T2
The concatenation of the null string with the host variable will force theconversion to occur before the cast is done. This query can be prepared in theDBCS to eucJP/eucTW environment although a truncation error may occur atrun time.
This technique (null string concat with cast) can be used to handle the similar254-byte limit for SELECT DISTINCT or use of the column in ORDER BY orGROUP BY clauses.
Constants
Graphic string constantsJapanese or Traditional-Chinese EUC client, may contain single or multi-bytecharacters (like a mixed character string). The string should not contain morethan 2 000 characters. It is recommended that only characters that convert todouble-byte characters in all related PC and EBCDIC double-byte code pagesbe used in graphic constants. A graphic string constant in an SQL statement isconverted from the client code page to the double-byte encoding at thedatabase server. For a Japanese or Traditional-Chinese EUC server, theconstant is converted to UCS-2, the double-byte encoding used for graphicstrings. For a double-byte server, the constant is converted from the clientcode page to the DBCS code page of the server.
FunctionsThe design of user-defined functions should consider the impact ofsupporting Japanese or Tradition-Chinese EUC on the parameter data types.One part of function resolution considers the data types of the arguments to afunction call. Mixed character string arguments involving a Japanese orTraditional-Chinese EUC client may require additional bytes to specify theargument. This may require that the data type change to allow the increased
Rules for string conversions
886 SQL Reference, Volume 1
length. For example, it may take 4001 bytes to represent a character string inthe application (a LONG VARCHAR) that fits into a VARCHAR(4000) stringat the server. If a function signature is not included that allows the argumentto be a LONG VARCHAR, function resolution will fail to find a function.
Some functions exist that do not allow long strings for various reasons. Use ofLONG VARCHAR or CLOB arguments with such functions will not succeed.For example, LONG VARCHAR as the second argument of the built-inPOSSTR function, will fail function resolution (SQLSTATE 42884).
Expressions
With the concatenation operatorThe potential expansion of one of the operands of concatenation may causethe data type and length of concatenated operands to change when in anenvironment that includes a Japanese or Traditional-Chinese EUC databaseserver. For example, with an EUC server where the value from a host variablemay double in length, consider the following example.
CHAR200 CONCAT :char50
The column CHAR200 is of type CHAR(200). The host variable char50 isdefined as CHAR(50). The result type for this concatenation operation wouldnormally be CHAR(250). However, given an eucJP or eucTW database server,the assumption is that the string may expand to double the length. Hencechar50 is treated as a CHAR(100) and the resulting data type isVARCHAR(300). Note that even though the result is a VARCHAR, it willalways have 300 bytes of data including trailing blanks. If the extra trailingblanks are not desired, define the host variable as VARCHAR(50) instead ofCHAR(50).
Predicates
LIKE predicateFor a LIKE predicate involving mixed character strings in an EUC database:v A single-byte underscore represents any one single-byte character.v A single-byte percent represents a string of zero or more characters
(single-byte or multi-byte characters).v A double-byte underscore represents any one multi-byte character.v A double-byte percent represents a string of zero or more characters
(single-byte or multi-byte characters).
The escape character must be one single-byte character or one double-bytecharacter.
Note that use of the underscore character may produce different results,depending on the code page of the LIKE operation. For example, Katakana
Functions
Appendix P. Japanese and traditional-Chinese extended UNIX code (EUC) considerations 887
characters in Japanese EUC are multi-byte characters (CS2) but in the JapaneseDBCS code page they are single-byte characters. A query with the single-byteunderscore in the pattern-expression would return occurrences of Katakanacharacter in the position of the underscore from a Japanese DBCS server.However, the same rows from the equivalent table in a Japanese EUC serverwould not be returned, since the Katakana characters will only match with adouble-byte underscore.
For a LIKE predicate involving graphic strings in an EUC database:v The character used for underscore and percent must map to the underscore
and percent character, respectively.v The underscore represents any one UCS-2 character.v Percent represents a string of zero or more UCS-2 characters.
Functions
LENGTHThe processing of this function is no different for mixed character strings inan EUC environment. The value returned is the length of the string in thecode page of the argument. As of Version 8, if the argument is a host variable,the value returned is the length of the string in the database code page. Whenusing this function to determine the length of a value, careful considerationshould be given to how the length is used. This is especially true for mixedstring constants since the length is given in bytes, not characters. For example,the length of a mixed string column in a DBCS database returned by theLENGTH function may be less than the length of the retrieved value of thatcolumn on an eucJP or eucTW client due to the conversion of some DBCScharacters to multi-byte eucJP or eucTW characters.
SUBSTRThe SUBSTR function operates on mixed character strings on a byte basis. Theresulting string may therefore include fragments of multi-byte characters atthe beginning or end of the resulting string. No processing is provided todetect or process fragments of characters.
TRANSLATEThe TRANSLATE function supports mixed character strings includingmulti-byte characters. The corresponding characters of the to-string-exp and thefrom-string-exp must have the same number of bytes and cannot end with partof a multi-byte character.
The pad-char-exp must result in a single-byte character when the char-string-expis a character string. Since TRANSLATE is performed in the code page of thechar-string-exp, the pad-char-exp may be converted from a multi-byte characterto a single-byte character.
LIKE predicate
888 SQL Reference, Volume 1
A char-string-exp that ends with part of a multi-byte character will not havethose bytes translated.
VARGRAPHICThe VARGRAPHIC function on a character string operand in a Japanese orTraditional-Chinese EUC code page returns a graphic string in the UCS-2 codepage.v Single-byte characters are converted first to their corresponding double-byte
character in the code set to which they belong (eucJP or eucTW). Then theyare converted to the corresponding UCS-2 representation. If there is nodouble-byte representation, the character is converted to the double-bytesubstitution character defined for that code set before being converted toUCS-2 representation.
v Characters from eucJP that are Katakana (eucJP CS2) are actually singlebyte characters in some encoding schemes. They are thus converted tocorresponding double-byte characters in eucJP or to the double-bytesubstitution character before converting to UCS-2.
v Multi-byte characters are converted to their UCS-2 representations.
Statements
CONNECTThe processing of a successful CONNECT statement returns information inthe SQLCA that is important when the possibility exists for applications toprocess data in an environment that includes a Japanese orTraditional-Chinese EUC code page at the client or server. The SQLERRD(1)field gives the maximum expansion of a mixed character string whenconverted from the application code page to the database code page. TheSQLERRD(2) field gives the maximum expansion of a mixed character stringwhen converted from the database code page to the application code page.The value is positive if expansion could occur and negative if contractioncould occur. If the value is negative, the value is always -1 since the worstcase is that no contraction occurs and the full length of the string is requiredafter conversion. Positive values may be as large as 2, meaning that in theworst case, double the string length may be required for the character stringafter conversion.
The code page of the application server and the application client are alsoavailable in the SQLERRMC field of the SQLCA.
PREPAREThe data types determined for untyped parameter markers are not changed inan environment that includes Japanese or Traditional-Chinese EUC. As aresult, it may be necessary in some cases to use typed parameter markers to
TRANSLATE
Appendix P. Japanese and traditional-Chinese extended UNIX code (EUC) considerations 889
provide sufficient length for mixed character strings in eucJP or eucTW. Forexample, consider an insert to a CHAR(10) column. Preparing the statement:
INSERT INTO T1 (CH10) VALUES (?)
would result in a data type of CHAR(10) for the parameter marker. If theclient was eucJP or eucTW, more than 10 bytes may be required to representthe string to be inserted but the same string in the DBCS code page of thedatabase is not more than 10 bytes. In this case, the statement to prepareshould include a typed parameter marker with a length greater than 10. Thus,preparing the statement:
INSERT INTO T1 (CH10) VALUES (CAST(? AS VARCHAR(20))
would result in a data type of VARCHAR(20) for the parameter marker.
Related reference:
v “PREPARE statement” in the SQL Reference, Volume 2
PREPARE
890 SQL Reference, Volume 1
Appendix Q. Backus-Naur form (BNF) specifications forDATALINKs
A DATALINK value is an encapsulated value that contains a logical referencefrom the database to a file stored outside the database.
The data location attribute of this encapsulated value is a logical reference to afile in the form of a uniform resource locator (URL). The value of thisattribute conforms to the syntax for URLs as specified by the following BNF,based on RFC 1738 : Uniform Resource Locators (URL), T. Berners-Lee, L.Masinter, M. McCahill, December 1994. (BNF is an acronym for ″Backus-NaurForm″, a formal notation to describe the syntax of a given language.)
The following conventions are used in the BNF specification:v "|" is used to designate alternativesv brackets [ ] are used around optional or repeated elementsv literals are quoted with ""v elements may be preceded with [n]* to designate n or more repetitions of
the following element; if n is not specified, the default is 0
The BNF specification for DATALINKs:URLurl = httpurl | fileurl | uncurl | dfsurl | emptyurl
HTTPhttpurl = "http://" hostport [ "/" hpath ]hpath = hsegment *[ "/" hsegment ]hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
Note that the search element from the original BNF in RFC1738 has beenremoved, because it is not an essential part of the file reference and doesnot make sense in DATALINKs context.FILEfileurl = "file://" host "/" fpathfpath = fsegment *[ "/" fsegment ]fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ]
Note that host is not optional and the ″localhost″ string does not haveany special meaning, in contrast with RFC1738. This avoids confusinginterpretations of ″localhost″ in client/server and partitioned databaseconfigurations.UNC
© Copyright IBM Corp. 1993 - 2002 891
uncurl = "unc:\\" hostname "\" sharename "\" uncpathsharename = *ucharuncpath = fsegment *[ "\" fsegment ]
Supports the commonly used UNC naming convention on Windows. Thisis not a standard scheme in RFC1738.DFSdfsurl = "dfs://.../" cellname "/" fpathcellname = hostname
Supports the DFS naming scheme. This is not a standard scheme inRFC1738.EMPTYURLemptyurl = ""hostport = host [ ":" port ]host = hostname | hostnumberhostname = *[ domainlabel "." ] toplabeldomainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigittoplabel = alpha | alpha *[ alphadigit | "-" ] alphadigitalphadigit = alpha | digithostnumber = digits "." digits "." digits "." digitsport = digits
Empty (zero-length) URLs are also supported for DATALINK values.These are useful to update DATALINK columns when reconcile exceptionsare reported and non-nullable DATALINK columns are involved. Azero-length URL is used to update the column and cause a file to beunlinked.Miscellaneous Definitionslowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
"i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |"q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |"y" | "z"
hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" |"I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" |"Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" |"Y" | "Z"
alpha = lowalpha | hialphadigit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
"8" | "9"safe = "$" | "-" | "_" | "." | "+"extra = "!" | "*" | "'" | "(" | ")" | ","hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
"a" | "b" | "c" | "d" | "e" | "f"escape = "%" hex hexunreserved = alpha | digit | safe | extrauchar = unreserved | escapedigits = 1*digit
Backus-Naur form (BNF) specifications for DATALINKs
892 SQL Reference, Volume 1
Leading and trailing blank characters are trimmed by DB2 while parsing.Also, the scheme names (’HTTP’, ’FILE’, ’UNC’, ’DFS’) and host arecase-insensitive, and are always stored in the database in uppercase.
Backus-Naur form (BNF) specifications for DATALINKs
Appendix Q. Backus-Naur form (BNF) specifications for DATALINKs 893
894 SQL Reference, Volume 1
Appendix R. DB2 Universal Database technical information
Overview of DB2 Universal Database technical information
DB2 Universal Database technical information can be obtained in thefollowing formats:v Books (PDF and hard-copy formats)v A topic tree (HTML format)v Help for DB2 tools (HTML format)v Sample programs (HTML format)v Command line helpv Tutorials
This section is an overview of the technical information that is provided andhow you can access it.
Categories of DB2 technical informationThe DB2 technical information is categorized by the following headings:v Core DB2 informationv Administration informationv Application development informationv Business intelligence informationv DB2 Connect informationv Getting started informationv Tutorial informationv Optional component informationv Release notes
The following tables describe, for each book in the DB2 library, theinformation needed to order the hard copy, print or view the PDF, or locatethe HTML directory for that book. A full description of each of the books inthe DB2 library is available from the IBM Publications Center atwww.ibm.com/shop/publications/order
The installation directory for the HTML documentation CD differs for eachcategory of information:htmlcdpath/doc/htmlcd/%L/category
where:
© Copyright IBM Corp. 1993 - 2002 895
v htmlcdpath is the directory where the HTML CD is installed.v %L is the language identifier. For example, en_US.v category is the category identifier. For example, core for the core DB2
information.
In the PDF file name column in the following tables, the character in the sixthposition of the file name indicates the language version of a book. Forexample, the file name db2d1e80 identifies the English version of theAdministration Guide: Planning and the file name db2d1g80 identifies theGerman version of the same book. The following letters are used in the sixthposition of the file name to indicate the language version:
Language IdentifierArabic wBrazilian Portuguese bBulgarian uCroatian 9Czech xDanish dDutch qEnglish eFinnish yFrench fGerman gGreek aHungarian hItalian iJapanese jKorean kNorwegian nPolish pPortuguese vRomanian 8Russian rSimp. Chinese cSlovakian 7Slovenian lSpanish zSwedish sTrad. Chinese tTurkish m
No form number indicates that the book is only available online and does nothave a printed version.
896 SQL Reference, Volume 1
Core DB2 informationThe information in this category cover DB2 topics that are fundamental to allDB2 users. You will find the information in this category useful whether youare a programmer, a database administrator, or you work with DB2 Connect,DB2 Warehouse Manager, or other DB2 products.
The installation directory for this category is doc/htmlcd/%L/core.
Table 182. Core DB2 information
Name Form Number PDF File Name
IBM DB2 Universal DatabaseCommand Reference
SC09-4828 db2n0x80
IBM DB2 Universal DatabaseGlossary
No form number db2t0x80
IBM DB2 Universal DatabaseMaster Index
SC09-4839 db2w0x80
IBM DB2 Universal DatabaseMessage Reference, Volume 1
GC09-4840 db2m1x80
IBM DB2 Universal DatabaseMessage Reference, Volume 2
GC09-4841 db2m2x80
IBM DB2 Universal DatabaseWhat’s New
SC09-4848 db2q0x80
Administration informationThe information in this category covers those topics required to effectivelydesign, implement, and maintain DB2 databases, data warehouses, andfederated systems.
The installation directory for this category is doc/htmlcd/%L/admin.
Table 183. Administration information
Name Form number PDF file name
IBM DB2 Universal DatabaseAdministration Guide:Planning
SC09-4822 db2d1x80
IBM DB2 Universal DatabaseAdministration Guide:Implementation
SC09-4820 db2d2x80
IBM DB2 Universal DatabaseAdministration Guide:Performance
SC09-4821 db2d3x80
IBM DB2 Universal DatabaseAdministrative API Reference
SC09-4824 db2b0x80
Appendix R. DB2 Universal Database technical information 897
Table 183. Administration information (continued)
Name Form number PDF file name
IBM DB2 Universal DatabaseData Movement Utilities Guideand Reference
SC09-4830 db2dmx80
IBM DB2 Universal DatabaseData Recovery and HighAvailability Guide andReference
SC09-4831 db2hax80
IBM DB2 Universal DatabaseData Warehouse CenterAdministration Guide
SC27-1123 db2ddx80
IBM DB2 Universal DatabaseFederated Systems Guide
GC27-1224 db2fpx80
IBM DB2 Universal DatabaseGuide to GUI Tools forAdministration andDevelopment
SC09-4851 db2atx80
IBM DB2 Universal DatabaseReplication Guide and Reference
SC27-1121 db2e0x80
IBM DB2 Installing andAdministering a SatelliteEnvironment
GC09-4823 db2dsx80
IBM DB2 Universal DatabaseSQL Reference, Volume 1
SC09-4844 db2s1x80
IBM DB2 Universal DatabaseSQL Reference, Volume 2
SC09-4845 db2s2x80
IBM DB2 Universal DatabaseSystem Monitor Guide andReference
SC09-4847 db2f0x80
Application development informationThe information in this category is of special interest to application developersor programmers working with DB2. You will find information aboutsupported languages and compilers, as well as the documentation required toaccess DB2 using the various supported programming interfaces, such asembedded SQL, ODBC, JDBC, SQLj, and CLI. If you view this informationonline in HTML you can also access a set of DB2 sample programs in HTML.
898 SQL Reference, Volume 1
The installation directory for this category is doc/htmlcd/%L/ad.
Table 184. Application development information
Name Form number PDF file name
IBM DB2 Universal DatabaseApplication DevelopmentGuide: Building and RunningApplications
SC09-4825 db2axx80
IBM DB2 Universal DatabaseApplication DevelopmentGuide: Programming ClientApplications
SC09-4826 db2a1x80
IBM DB2 Universal DatabaseApplication DevelopmentGuide: Programming ServerApplications
SC09-4827 db2a2x80
IBM DB2 Universal DatabaseCall Level Interface Guide andReference, Volume 1
SC09-4849 db2l1x80
IBM DB2 Universal DatabaseCall Level Interface Guide andReference, Volume 2
SC09-4850 db2l2x80
IBM DB2 Universal DatabaseData Warehouse CenterApplication Integration Guide
SC27-1124 db2adx80
IBM DB2 XML ExtenderAdministration andProgramming
SC27-1234 db2sxx80
Business intelligence informationThe information in this category describes how to use components thatenhance the data warehousing and analytical capabilities of DB2 UniversalDatabase.
The installation directory for this category is doc/htmlcd/%L/wareh.
Table 185. Business intelligence information
Name Form number PDF file name
IBM DB2 Warehouse ManagerInformation Catalog CenterAdministration Guide
SC27-1125 db2dix80
IBM DB2 Warehouse ManagerInstallation Guide
GC27-1122 db2idx80
Appendix R. DB2 Universal Database technical information 899
DB2 Connect informationThe information in this category describes how to access host or iSeries datausing DB2 Connect Enterprise Edition or DB2 Connect Personal Edition.
The installation directory for this category is doc/htmlcd/%L/conn.
Table 186. DB2 Connect information
Name Form number PDF file name
APPC, CPI-C, and SNA SenseCodes
No form number db2apx80
IBM Connectivity Supplement No form number db2h1x80
IBM DB2 Connect QuickBeginnings for DB2 ConnectEnterprise Edition
GC09-4833 db2c6x80
IBM DB2 Connect QuickBeginnings for DB2 ConnectPersonal Edition
GC09-4834 db2c1x80
IBM DB2 Connect User’sGuide
SC09-4835 db2c0x80
Getting started informationThe information in this category is useful when you are installing andconfiguring servers, clients, and other DB2 products.
The installation directory for this category is doc/htmlcd/%L/start.
Table 187. Getting started information
Name Form number PDF file name
IBM DB2 Universal DatabaseQuick Beginnings for DB2Clients
GC09-4832 db2itx80
IBM DB2 Universal DatabaseQuick Beginnings for DB2Servers
GC09-4836 db2isx80
IBM DB2 Universal DatabaseQuick Beginnings for DB2Personal Edition
GC09-4838 db2i1x80
IBM DB2 Universal DatabaseInstallation and ConfigurationSupplement
GC09-4837 db2iyx80
IBM DB2 Universal DatabaseQuick Beginnings for DB2Data Links Manager
GC09-4829 db2z6x80
900 SQL Reference, Volume 1
Tutorial informationTutorial information introduces DB2 features and teaches how to performvarious tasks.
The installation directory for this category is doc/htmlcd/%L/tutr.
Table 188. Tutorial information
Name Form number PDF file name
Business Intelligence Tutorial:Introduction to the DataWarehouse
No form number db2tux80
Business Intelligence Tutorial:Extended Lessons in DataWarehousing
No form number db2tax80
Development Center Tutorialfor Video Online usingMicrosoft Visual Basic
No form number db2tdx80
Information Catalog CenterTutorial
No form number db2aix80
Video Central for e-businessTutorial
No form number db2twx80
Visual Explain Tutorial No form number db2tvx80
Optional component informationThe information in this category describes how to work with optional DB2components.
The installation directory for this category is doc/htmlcd/%L/opt.
Table 189. Optional component information
Name Form number PDF file name
IBM DB2 Life Sciences DataConnect Planning, Installation,and Configuration Guide
GC27-1235 db2lsx80
IBM DB2 Spatial ExtenderUser’s Guide and Reference
SC27-1226 db2sbx80
IBM DB2 Universal DatabaseData Links ManagerAdministration Guide andReference
SC27-1221 db2z0x80
Appendix R. DB2 Universal Database technical information 901
Table 189. Optional component information (continued)
Name Form number PDF file name
IBM DB2 Universal DatabaseNet Search ExtenderAdministration andProgramming GuideNote: HTML for thisdocument is not installedfrom the HTMLdocumentation CD.
SH12-6740 N/A
Release notesThe release notes provide additional information specific to your product’srelease and FixPak level. They also provides summaries of the documentationupdates incorporated in each release and FixPak.
Table 190. Release notes
Name Form number PDF file name HTML directory
DB2 Release Notes See note. See note. doc/prodcd/%L/db2ir
where %L is thelanguage identifier.
DB2 Connect ReleaseNotes
See note. See note. doc/prodcd/%L/db2cr
where %L is thelanguage identifier.
DB2 Installation Notes Available onproduct CD-ROMonly.
Available onproduct CD-ROMonly.
Note: The HTML version of the release notes is available from theInformation Center and on the product CD-ROMs. To view the ASCIIfile:v On UNIX-based platforms, see the Release.Notes file. This file is
located in the DB2DIR/Readme/%L directory, where %L representsthe locale name and DB2DIR represents:– /usr/opt/db2_08_01 on AIX– /opt/IBM/db2/V8.1 on all other UNIX operating systems
v On other platforms, see the RELEASE.TXT file. This file is located inthe directory where the product is installed.
Related tasks:
v “Printing DB2 books from PDF files” on page 903
902 SQL Reference, Volume 1
v “Ordering printed DB2 books” on page 904v “Accessing online help” on page 904v “Finding product information by accessing the DB2 Information Center
from the administration tools” on page 908v “Viewing technical documentation online directly from the DB2 HTML
Documentation CD” on page 909
Printing DB2 books from PDF files
You can print DB2 books from the PDF files on the DB2 PDF DocumentationCD. Using Adobe Acrobat Reader, you can print either the entire book or aspecific range of pages.
Prerequisites:
Ensure that you have Adobe Acrobat Reader. It is available from the AdobeWeb site at www.adobe.com
Procedure:
To print a DB2 book from a PDF file:1. Insert the DB2 PDF Documentation CD. On UNIX operating systems,
mount the DB2 PDF Documentation CD. Refer to your Quick Beginningsbook for details on how to mount a CD on UNIX operating systems.
2. Start Adobe Acrobat Reader.3. Open the PDF file from one of the following locations:
v On Windows operating systems:x:\doc\language directory, where x represents the CD-ROM drive letterand language represents the two-character territory code that representsyour language (for example, EN for English).
v On UNIX operating systems:/cdrom/doc/%L directory on the CD-ROM, where /cdrom represents themount point of the CD-ROM and %L represents the name of the desiredlocale.
Related tasks:
v “Ordering printed DB2 books” on page 904v “Finding product information by accessing the DB2 Information Center
from the administration tools” on page 908v “Viewing technical documentation online directly from the DB2 HTML
Documentation CD” on page 909
Related reference:
Appendix R. DB2 Universal Database technical information 903
v “Overview of DB2 Universal Database technical information” on page 895
Ordering printed DB2 books
Procedure:
To order printed books:v Contact your IBM authorized dealer or marketing representative. To find a
local IBM representative, check the IBM Worldwide Directory of Contacts atwww.ibm.com/shop/planetwide
v Phone 1-800-879-2755 in the United States or 1-800-IBM-4YOU in Canada.v Visit the IBM Publications Center at
www.ibm.com/shop/publications/order
Related tasks:
v “Printing DB2 books from PDF files” on page 903v “Finding topics by accessing the DB2 Information Center from a browser”
on page 906v “Viewing technical documentation online directly from the DB2 HTML
Documentation CD” on page 909
Related reference:
v “Overview of DB2 Universal Database technical information” on page 895
Accessing online help
The online help that comes with all DB2 components is available in threetypes:v Window and notebook helpv Command line helpv SQL statement help
Window and notebook help explain the tasks that you can perform in awindow or notebook and describe the controls. This help has two types:v Help accessible from the Help buttonv Infopops
The Help button gives you access to overview and prerequisite information.The infopops describe the controls in the window or notebook. Window andnotebook help are available from DB2 centers and components that have userinterfaces.
904 SQL Reference, Volume 1
Command line help includes Command help and Message help. Commandhelp explains the syntax of commands in the command line processor.Message help describes the cause of an error message and describes anyaction you should take in response to the error.
SQL statement help includes SQL help and SQLSTATE help. DB2 returns anSQLSTATE value for conditions that could be the result of an SQL statement.SQLSTATE help explains the syntax of SQL statements (SQL states and classcodes).
Note: SQL help is not available for UNIX operating systems.
Procedure:
To access online help:v For window and notebook help, click Help or click that control, then click
F1. If the Automatically display infopops check box on the General pageof the Tool Settings notebook is selected, you can also see the infopop for aparticular control by holding the mouse cursor over the control.
v For command line help, open the command line processor and enter:– For Command help:
? command
where command represents a keyword or the entire command.
For example, ? catalog displays help for all the CATALOG commands,while ? catalog database displays help for the CATALOG DATABASEcommand.
v For Message help:? XXXnnnnn
where XXXnnnnn represents a valid message identifier.
For example, ? SQL30081 displays help about the SQL30081 message.v For SQL statement help, open the command line processor and enter:
– For SQL help:? sqlstate or ? class code
where sqlstate represents a valid five-digit SQL state and class coderepresents the first two digits of the SQL state.
For example, ? 08003 displays help for the 08003 SQL state, while ? 08displays help for the 08 class code.
– For SQLSTATE help:
Appendix R. DB2 Universal Database technical information 905
help statement
where statement represents an SQL statement.
For example, help SELECT displays help about the SELECT statement.
Related tasks:
v “Finding topics by accessing the DB2 Information Center from a browser”on page 906
v “Viewing technical documentation online directly from the DB2 HTMLDocumentation CD” on page 909
Finding topics by accessing the DB2 Information Center from a browser
The DB2 Information Center accessed from a browser enables you to accessthe information you need to take full advantage of DB2 Universal Databaseand DB2 Connect. The DB2 Information Center also documents major DB2features and components including replication, data warehousing, metadata,Life Sciences Data Connect, and DB2 extenders.
The DB2 Information Center accessed from a browser is composed of thefollowing major elements:
Navigation treeThe navigation tree is located in the left frame of the browser window.The tree expands and collapses to show and hide topics, the glossary,and the master index in the DB2 Information Center.
Navigation toolbarThe navigation toolbar is located in the top right frame of the browserwindow. The navigation toolbar contains buttons that enable you tosearch the DB2 Information Center, hide the navigation tree, and findthe currently displayed topic in the navigation tree.
Content frameThe content frame is located in the bottom right frame of the browserwindow. The content frame displays topics from the DB2 InformationCenter when you click on a link in the navigation tree, click on asearch result, or follow a link from another topic or from the masterindex.
Prerequisites:
To access the DB2 Information Center from a browser, you must use one ofthe following browsers:v Microsoft Explorer, version 5 or laterv Netscape Navigator, version 6.1 or later
906 SQL Reference, Volume 1
Restrictions:
The DB2 Information Center contains only those sets of topics that you choseto install from the DB2 HTML Documentation CD. If your Web browser returnsa File not found error when you try to follow a link to a topic, you mustinstall one or more additional sets of topics DB2 HTML Documentation CD.
Procedure:
To find a topic by searching with keywords:1. In the navigation toolbar, click Search.2. In the top text entry field of the Search window, enter two or more terms
related to your area of interest and click Search. A list of topics ranked byaccuracy displays in the Results field.Entering more terms increases the precision of your query while reducingthe number of topics returned from your query.
3. In the Results field, click the title of the topic you want to read. The topicdisplays in the content frame.
To find a topic in the navigation tree:1. In the navigation tree, click the book icon of the category of topics related
to your area of interest. A list of subcategories displays underneath theicon.
2. Continue to click the book icons until you find the category containingthe topics in which you are interested. Categories that link to topicsdisplay the category title as an underscored link when you move thecursor over the category title. The navigation tree identifies topics with apage icon.
3. Click the topic link. The topic displays in the content frame.
To find a topic or term in the master index:1. In the navigation tree, click the “Index” category. The category expands to
display a list of links arranged in alphabetical order in the navigation tree.2. In the navigation tree, click the link corresponding to the first character of
the term relating to the topic in which you are interested. A list of termswith that initial character displays in the content frame. Terms that havemultiple index entries are identified by a book icon.
3. Click the book icon corresponding to the term in which you areinterested. A list of subterms and topics displays below the term youclicked. Topics are identified by page icons with an underscored title.
4. Click on the title of the topic that meets your needs. The topic displays inthe content frame.
Appendix R. DB2 Universal Database technical information 907
Related concepts:
v “Accessibility” on page 915v “DB2 Information Center for topics” on page 917
Related tasks:
v “Finding product information by accessing the DB2 Information Centerfrom the administration tools” on page 908
v “Updating the HTML documentation installed on your machine” on page910
v “Troubleshooting DB2 documentation search with Netscape 4.x” on page912
v “Searching the DB2 documentation” on page 913
Related reference:
v “Overview of DB2 Universal Database technical information” on page 895
Finding product information by accessing the DB2 Information Center from theadministration tools
The DB2 Information Center provides quick access to DB2 productinformation and is available on all operating systems for which the DB2administration tools are available.
The DB2 Information Center accessed from the tools provides six types ofinformation.
Tasks Key tasks you can perform using DB2.
ConceptsKey concepts for DB2.
ReferenceDB2 reference information, such as keywords, commands, and APIs.
TroubleshootingError messages and information to help you with common DB2problems.
SamplesLinks to HTML listings of the sample programs provided with DB2.
TutorialsInstructional aid designed to help you learn a DB2 feature.
Prerequisites:
908 SQL Reference, Volume 1
Some links in the DB2 Information Center point to Web sites on the Internet.To display the content for these links, you will first have to connect to theInternet.
Procedure:
To find product information by accessing the DB2 Information Center fromthe tools:1. Start the DB2 Information Center in one of the following ways:
v From the graphical administration tools, click on the InformationCenter icon in the toolbar. You can also select it from the Help menu.
v At the command line, enter db2ic.2. Click the tab of the information type related to the information you are
attempting to find.3. Navigate through the tree and click on the topic in which you are
interested. The Information Center will then launch a Web browser todisplay the information.
4. To find information without browsing the lists, click the Search icon to theright of the list.Once the Information Center has launched a browser to display theinformation, you can perform a full-text search by clicking the Search iconin the navigation toolbar.
Related concepts:
v “Accessibility” on page 915v “DB2 Information Center for topics” on page 917
Related tasks:
v “Finding topics by accessing the DB2 Information Center from a browser”on page 906
v “Searching the DB2 documentation” on page 913
Viewing technical documentation online directly from the DB2 HTMLDocumentation CD
All of the HTML topics that you can install from the DB2 HTMLDocumentation CD can also be read directly from the CD. Therefore, you canview the documentation without having to install it.
Restrictions:
Appendix R. DB2 Universal Database technical information 909
Because the following items are installed from the DB2 product CD and notthe DB2 HTML Documentation CD, you must install the DB2 product to viewthese items:v Tools helpv DB2 Quick Tourv Release notes
Procedure:
1. Insert the DB2 HTML Documentation CD. On UNIX operating systems,mount the DB2 HTML Documentation CD. Refer to your Quick Beginningsbook for details on how to mount a CD on UNIX operating systems.
2. Start your HTML browser and open the appropriate file:v For Windows operating systems:
e:\Program Files\sqllib\doc\htmlcd\%L\index.htm
where e represents the CD-ROM drive, and %L is the locale of thedocumentation that you wish to use, for example, en_US for English.
v For UNIX operating systems:/cdrom/Program Files/sqllib/doc/htmlcd/%L/index.htm
where /cdrom/ represents where the CD is mounted, and %L is the localeof the documentation that you wish to use, for example, en_US forEnglish.
Related tasks:
v “Finding topics by accessing the DB2 Information Center from a browser”on page 906
v “Copying files from the DB2 HTML Documentation CD to a Web Server”on page 912
Related reference:
v “Overview of DB2 Universal Database technical information” on page 895
Updating the HTML documentation installed on your machine
It is now possible to update the HTML installed from the DB2 HTMLDocumentation CD when updates are made available from IBM. This can bedone in one of two ways:v Using the Information Center (if you have the DB2 administration GUI
tools installed).v By downloading and applying a DB2 HTML documentation FixPak .
910 SQL Reference, Volume 1
Note: This will NOT update the DB2 code; it will only update the HTMLdocumentation installed from the DB2 HTML Documentation CD.
Procedure:
To use the Information Center to update your local documentation:1. Start the DB2 Information Center in one of the following ways:
v From the graphical administration tools, click on the InformationCenter icon in the toolbar. You can also select it from the Help menu.
v At the command line, enter db2ic.2. Ensure your machine has access to the external Internet; the updater will
download the latest documentation FixPak from the IBM server ifrequired.
3. Select Information Center —> Update Local Documentation from themenu to start the update.
4. Supply your proxy information (if required) to connect to the externalInternet.
The Information Center will download and apply the latest documentationFixPak, if one is available.
To manually download and apply the documentation FixPak :1. Ensure your machine is connected to the Internet.2. Open the DB2 support page in your Web browser at:
www.ibm.com/software/data/db2/udb/winos2unix/support3. Follow the link for version 8 and look for the ″Documentation FixPaks″
link.4. Determine if the version of your local documentation is out of date by
comparing the documentation FixPak level to the documentation level youhave installed. This current documentation on your machine is at thefollowing level: DB2 v8.1 GA.
5. If there is a more recent version of the documentation available thendownload the FixPak applicable to your operating system. There is oneFixPak for all Windows platforms, and one FixPak for all UNIX platforms.
6. Apply the FixPak:v For Windows operating systems: The documentation FixPak is a self
extracting zip file. Place the downloaded documentation FixPak in anempty directory, and run it. It will create a setup command which youcan run to install the documentation FixPak.
v For UNIX operating systems: The documentation FixPak is acompressed tar.Z file. Uncompress and untar the file. It will create adirectory named delta_install with a script called installdocfix. Runthis script to install the documentation FixPak.
Appendix R. DB2 Universal Database technical information 911
Related tasks:
v “Copying files from the DB2 HTML Documentation CD to a Web Server”on page 912
Related reference:
v “Overview of DB2 Universal Database technical information” on page 895
Copying files from the DB2 HTML Documentation CD to a Web Server
The entire DB2 information library is delivered to you on the DB2 HTMLDocumentation CD, so you can install the library on a Web server for easieraccess. Simply copy to your Web server the documentation for the languagesthat you want.
Procedure:
To copy files from the DB2 HTML Documentation CD to a Web server, use theappropriate path:v For Windows operating systems:
E:\Program Files\sqllib\doc\htmlcd\%L\*.*
where E represents the CD-ROM drive and %L represents the languageidentifier.
v For UNIX operating systems:/cdrom:Program Files/sqllib/doc/htmlcd/%L/*.*
where cdrom represents the CD-ROM drive and %L represents the languageidentifier.
Related tasks:
v “Searching the DB2 documentation” on page 913
Related reference:
v “Supported DB2 interface languages, locales, and code pages” in the QuickBeginnings for DB2 Servers
v “Overview of DB2 Universal Database technical information” on page 895
Troubleshooting DB2 documentation search with Netscape 4.x
Most search problems are related to the Java support provided by webbrowsers. This task describes possible workarounds.
Procedure:
912 SQL Reference, Volume 1
A common problem with Netscape 4.x involves a missing or misplacedsecurity class. Try the following workaround, especially if you see thefollowing line in the browser Java console:Cannot find class java/security/InvalidParameterException
v On Windows operating systems:From the DB2 HTML Documentation CD, copy the supplied x:ProgramFiles\sqllib\doc\htmlcd\locale\InvalidParameterException.class file tothe java\classes\java\security\ directory relative to your Netscapebrowser installation, where x represents the CD-ROM drive letter and localerepresents the name of the desired locale.
Note: You may have to create the java\security\ subdirectory structure.v On UNIX operating systems:
From the DB2 HTML Documentation CD, copy the supplied /cdrom/ProgramFiles/sqllib/doc/htmlcd/locale/InvalidParameterException.class file tothe java/classes/java/security/ directory relative to your Netscapebrowser installation, where cdrom represents the mount point of theCD-ROM and locale represents the name of the desired locale.
Note: You may have to create the java/security/ subdirectory structure.
If your Netscape browser still fails to display the search input window, try thefollowing:v Stop all instances of Netscape browsers to ensure that there is no Netscape
code running on the machine. Then open a new instance of the Netscapebrowser and try to start the search again.
v Purge the browser’s cache.v Try a different version of Netscape, or a different browser.
Related tasks:
v “Searching the DB2 documentation” on page 913
Searching the DB2 documentation
To search DB2’s documentation, you need Netscape 6.1 or higher, orMicrosoft’s Internet Explorer 5 or higher. Ensure that your browser’s Javasupport is enabled.
A pop-up search window opens when you click the search icon in thenavigation toolbar of the Information Center accessed from a browser. If youare using the search for the first time it may take a minute or so to load intothe search window.
Restrictions:
Appendix R. DB2 Universal Database technical information 913
The following restrictions apply when you use the documentation search:v Boolean searches are not supported. The boolean search qualifiers and and
or will be ignored in a search. For example, the following searches wouldproduce the same results:– servlets and beans– servlets or beans
v Wildcard searches are not supported. A search on java* will only look forthe literal string java* and would not, for example, find javadoc.
In general, you will get better search results if you search for phrases insteadof single words.
Procedure:
To search the DB2 documentation:1. In the navigation toolbar, click Search.2. In the top text entry field of the Search window, enter two or more terms
related to your area of interest and click Search. A list of topics ranked byaccuracy displays in the Results field.Entering more terms increases the precision of your query while reducingthe number of topics returned from your query.
3. In the Results field, click the title of the topic you want to read. The topicdisplays in the content frame.
Note: When you perform a search, the first result is automatically loaded intoyour browser frame. To view the contents of other search results, clickon the result in results lists.
Related tasks:
v “Troubleshooting DB2 documentation search with Netscape 4.x” on page912
Online DB2 troubleshooting information
With the release of DB2® UDB Version 8, there will no longer be aTroubleshooting Guide. The troubleshooting information once contained in thisguide has been integrated into the DB2 publications. By doing this, we areable to deliver the most up-to-date information possible. To find informationon the troubleshooting utilities and functions of DB2, access the DB2Information Center from any of the tools.
Refer to the DB2 Online Support site if you are experiencing problems andwant help finding possible causes and solutions. The support site contains a
914 SQL Reference, Volume 1
large, constantly updated database of DB2 publications, TechNotes, APAR(product problem) records, FixPaks, and other resources. You can use thesupport site to search through this knowledge base and find possible solutionsto your problems.
Access the Online Support site atwww.ibm.com/software/data/db2/udb/winos2unix/support, or by clickingthe Online Support button in the DB2 Information Center. Frequentlychanging information, such as the listing of internal DB2 error codes, is nowalso available from this site.
Related concepts:
v “DB2 Information Center for topics” on page 917
Related tasks:
v “Finding product information by accessing the DB2 Information Centerfrom the administration tools” on page 908
Accessibility
Accessibility features help users with physical disabilities, such as restrictedmobility or limited vision, to use software products successfully. These are themajor accessibility features in DB2® Universal Database Version 8:v DB2 allows you to operate all features using the keyboard instead of the
mouse. See “Keyboard Input and Navigation”.v DB2 enables you customize the size and color of your fonts. See “Accessible
Display” on page 916.v DB2 allows you to receive either visual or audio alert cues. See “Alternative
Alert Cues” on page 916.v DB2 supports accessibility applications that use the Java™ Accessibility API.
See “Compatibility with Assistive Technologies” on page 916.v DB2 comes with documentation that is provided in an accessible format.
See “Accessible Documentation” on page 916.
Keyboard Input and Navigation
Keyboard InputYou can operate the DB2 Tools using only the keyboard. You can use keys orkey combinations to perform most operations that can also be done using amouse.
Appendix R. DB2 Universal Database technical information 915
Keyboard FocusIn UNIX-based systems, the position of the keyboard focus is highlighted,indicating which area of the window is active and where your keystrokes willhave an effect.
Accessible DisplayThe DB2 Tools have features that enhance the user interface and improveaccessibility for users with low vision. These accessibility enhancementsinclude support for customizable font properties.
Font SettingsThe DB2 Tools allow you to select the color, size, and font for the text inmenus and dialog windows, using the Tools Settings notebook.
Non-dependence on ColorYou do not need to distinguish between colors in order to use any of thefunctions in this product.
Alternative Alert CuesYou can specify whether you want to receive alerts through audio or visualcues, using the Tools Settings notebook.
Compatibility with Assistive TechnologiesThe DB2 Tools interface supports the Java Accessibility API enabling use byscreen readers and other assistive technologies used by people withdisabilities.
Accessible DocumentationDocumentation for the DB2 family of products is available in HTML format.This allows you to view documentation according to the display preferencesset in your browser. It also allows you to use screen readers and otherassistive technologies.
DB2 tutorials
The DB2® tutorials help you learn about various aspects of DB2 UniversalDatabase. The tutorials provide lessons with step-by-step instructions in theareas of developing applications, tuning SQL query performance, workingwith data warehouses, managing metadata, and developing Web servicesusing DB2.
Before you begin:
Before you can access these tutorials using the links below, you must installthe tutorials from the DB2 HTML Documentation CD-ROM.
916 SQL Reference, Volume 1
If you do not want to install the tutorials, you can view the HTML versions ofthe tutorials directly from the DB2 HTML Documentation CD. PDF versions ofthese tutorials are also available on the DB2 PDF Documentation CD.
Some tutorial lessons use sample data or code. See each individual tutorial fora description of any prerequisites for its specific tasks.
DB2 Universal Database tutorials:
If you installed the tutorials from the DB2 HTML Documentation CD-ROM,you can click on a tutorial title in the following list to view that tutorial.
Business Intelligence Tutorial: Introduction to the Data Warehouse CenterPerform introductory data warehousing tasks using the DataWarehouse Center.
Business Intelligence Tutorial: Extended Lessons in Data WarehousingPerform advanced data warehousing tasks using the Data WarehouseCenter. (Not provided on CD. You can download this tutorial from theDownloads section of the Business Intelligence Solutions Web site athttp://www.ibm.com/software/data/bi/.)
Development Center Tutorial for Video Online using Microsoft® Visual BasicBuild various components of an application using the DevelopmentCenter Add-in for Microsoft Visual Basic.
Information Catalog Center TutorialCreate and manage an information catalog to locate and use metadatausing the Information Catalog Center.
Video Central for e-business TutorialDevelop and deploy an advanced DB2 Web Services application usingWebSphere® products.
Visual Explain TutorialAnalyze, optimize, and tune SQL statements for better performanceusing Visual Explain.
DB2 Information Center for topics
The DB2® Information Center gives you access to all of the information youneed to take full advantage of DB2 Universal Database™ and DB2 Connect™
in your business. The DB2 Information Center also documents major DB2features and components including replication, data warehousing, theInformation Catalog Center, Life Sciences Data Connect, and DB2 extenders.
The DB2 Information Center accessed from a browser has the followingfeatures:
Appendix R. DB2 Universal Database technical information 917
Regularly updated documentationKeep your topics up-to-date by downloading updated HTML.
SearchSearch all of the topics installed on your workstation by clickingSearch in the navigation toolbar.
Integrated navigation treeLocate any topic in the DB2 library from a single navigation tree. Thenavigation tree is organized by information type as follows:v Tasks provide step-by-step instructions on how to complete a goal.v Concepts provide an overview of a subject.v Reference topics provide detailed information about a subject,
including statement and command syntax, message help,requirements.
Master indexAccess the information in topics and tools help from one masterindex. The index is organized in alphabetical order by index term.
Master glossaryThe master glossary defines terms used in the DB2 InformationCenter. The glossary is organized in alphabetical order by glossaryterm.
Related tasks:
v “Finding topics by accessing the DB2 Information Center from a browser”on page 906
v “Finding product information by accessing the DB2 Information Centerfrom the administration tools” on page 908
v “Updating the HTML documentation installed on your machine” on page910
918 SQL Reference, Volume 1
Appendix S. Notices
IBM may not offer the products, services, or features discussed in thisdocument in all countries. Consult your local IBM representative forinformation on the products and services currently available in your area. Anyreference to an IBM product, program, or service is not intended to state orimply that only that IBM product, program, or service may be used. Anyfunctionally equivalent product, program, or service that does not infringeany IBM intellectual property right may be used instead. However, it is theuser’s responsibility to evaluate and verify the operation of any non-IBMproduct, program, or service.
IBM may have patents or pending patent applications covering subject matterdescribed in this document. The furnishing of this document does not giveyou any license to these patents. You can send license inquiries, in writing, to:
IBM Director of LicensingIBM CorporationNorth Castle DriveArmonk, NY 10504-1785U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact theIBM Intellectual Property Department in your country/region or sendinquiries, in writing, to:
IBM World Trade Asia CorporationLicensing2-31 Roppongi 3-chome, Minato-kuTokyo 106, Japan
The following paragraph does not apply to the United Kingdom or anyother country/region where such provisions are inconsistent with local law:INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THISPUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allowdisclaimer of express or implied warranties in certain transactions; therefore,this statement may not apply to you.
This information could include technical inaccuracies or typographical errors.Changes are periodically made to the information herein; these changes willbe incorporated in new editions of the publication. IBM may make
© Copyright IBM Corp. 1993 - 2002 919
improvements and/or changes in the product(s) and/or the program(s)described in this publication at any time without notice.
Any references in this information to non-IBM Web sites are provided forconvenience only and do not in any manner serve as an endorsement of thoseWeb sites. The materials at those Web sites are not part of the materials forthis IBM product, and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way itbelieves appropriate without incurring any obligation to you.
Licensees of this program who wish to have information about it for thepurpose of enabling: (i) the exchange of information between independentlycreated programs and other programs (including this one) and (ii) the mutualuse of the information that has been exchanged, should contact:
IBM Canada LimitedOffice of the Lab Director8200 Warden AvenueMarkham, OntarioL6G 1C7CANADA
Such information may be available, subject to appropriate terms andconditions, including in some cases payment of a fee.
The licensed program described in this document and all licensed materialavailable for it are provided by IBM under terms of the IBM CustomerAgreement, IBM International Program License Agreement, or any equivalentagreement between us.
Any performance data contained herein was determined in a controlledenvironment. Therefore, the results obtained in other operating environmentsmay vary significantly. Some measurements may have been made ondevelopment-level systems, and there is no guarantee that thesemeasurements will be the same on generally available systems. Furthermore,some measurements may have been estimated through extrapolation. Actualresults may vary. Users of this document should verify the applicable data fortheir specific environment.
Information concerning non-IBM products was obtained from the suppliers ofthose products, their published announcements, or other publicly availablesources. IBM has not tested those products and cannot confirm the accuracyof performance, compatibility, or any other claims related to non-IBMproducts. Questions on the capabilities of non-IBM products should beaddressed to the suppliers of those products.
920 SQL Reference, Volume 1
All statements regarding IBM’s future direction or intent are subject to changeor withdrawal without notice, and represent goals and objectives only.
This information may contain examples of data and reports used in dailybusiness operations. To illustrate them as completely as possible, the examplesinclude the names of individuals, companies, brands, and products. All ofthese names are fictitious, and any similarity to the names and addresses usedby an actual business enterprise is entirely coincidental.
COPYRIGHT LICENSE:
This information may contain sample application programs, in sourcelanguage, which illustrate programming techniques on various operatingplatforms. You may copy, modify, and distribute these sample programs inany form without payment to IBM for the purposes of developing, using,marketing, or distributing application programs conforming to the applicationprogramming interface for the operating platform for which the sampleprograms are written. These examples have not been thoroughly tested underall conditions. IBM, therefore, cannot guarantee or imply reliability,serviceability, or function of these programs.
Each copy or any portion of these sample programs or any derivative workmust include a copyright notice as follows:
© (your company name) (year). Portions of this code are derived from IBMCorp. Sample Programs. © Copyright IBM Corp. _enter the year or years_. Allrights reserved.
Appendix S. Notices 921
Trademarks
The following terms are trademarks of International Business MachinesCorporation in the United States, other countries, or both, and have been usedin at least one of the documents in the DB2 UDB documentation library.
ACF/VTAMAISPOAIXAIXwindowsAnyNetAPPNAS/400BookManagerC Set++C/370CICSDatabase 2DataHubDataJoinerDataPropagatorDataRefresherDB2DB2 ConnectDB2 ExtendersDB2 OLAP ServerDB2 Universal DatabaseDistributed Relational
Database ArchitectureDRDAeServerExtended ServicesFFSTFirst Failure Support TechnologyIBMIMSIMS/ESAiSeries
LAN DistanceMVSMVS/ESAMVS/XANet.DataNetViewOS/390OS/400PowerPCpSeriesQBICQMFRACFRISC System/6000RS/6000S/370SPSQL/400SQL/DSSystem/370System/390SystemViewTivoliVisualAgeVM/ESAVSE/ESAVTAMWebExplorerWebSphereWIN-OS/2z/OSzSeries
The following terms are trademarks or registered trademarks of othercompanies and have been used in at least one of the documents in the DB2UDB documentation library:
Microsoft, Windows, Windows NT, and the Windows logo are trademarks ofMicrosoft Corporation in the United States, other countries, or both.
Intel and Pentium are trademarks of Intel Corporation in the United States,other countries, or both.
922 SQL Reference, Volume 1
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc.in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States andother countries.
Other company, product, or service names may be trademarks or servicemarks of others.
Appendix S. Notices 923
924 SQL Reference, Volume 1
Index
Special Characters(asterisk)
in select column names 554in subselect column names 554
AABS or ABSVAL function
basic description 249detailed format description 292values and arguments, rules
for 292access plans
description 44accessibility
features 915ACCOUNTING_STRING
option 773ACOS function
basic description 249ACOS scalar function
description 293values and arguments 293
ADVISE_INDEX table 853ADVISE_WORKLOAD table 856aggregate function
COUNT 273description 269MIN 282
alias name, definition 65aliases
definition 7description 65TABLE_NAME function 460TABLE_SCHEMA function 461
ALL clausequantified predicate 230SELECT statement 554
ALL option 595ambiguous reference errors 65AND truth table 226ANY clause 230application process
connection states 29definition 16
application requesters 29arguments of COALESCE 134arithmetic
AVG function, operation of 270
arithmetic (continued)columns, adding values
(SUM) 289CORRELATION function
operation 272COVARIANCE function
operation 277date operations, rules 187datetime, SQL rules 187decimal operations, scale and
precision formulas 187decimal values from numeric
expressions 327distinct type operands 187expressions, adding values
(SUM) 289finding maximum value 280floating point operands
rules and precisionvalues 187
with integers, results 187floating point values from
numeric expressions 357, 435integer values, returning from
expressions 299, 384operators, summary 187regression functions 284returning small integer values
from expressions 452STDDEV function 288time operations, rules 187timestamp operations, rules 187unary minus sign, effect on
operand 187unary plus sign, effect on
operand 187VARIANCE function
operation 290AS clause
in SELECT clause 554ORDER BY clause 554
ASC clauseSELECT statement 554
ASCII functionbasic description 249
ASCII scalar functiondescription 294values and arguments 294
ASIN functionbasic description 249
ASIN scalar functiondescription 295values and arguments 295
assignmentsbasic SQL operations 117storage 187
asterisk (*)in COUNT 273in COUNT_BIG 275in select column names 554in subselect column names 554
ATAN functionbasic description 249
ATAN scalar functiondescription 296values and arguments 296
ATAN2 functionbasic description 249
ATAN2 scalar functiondescription 297values and arguments 297
ATANH functionbasic description 249
ATANH scalar functiondescription 298values and arguments 298
attribute namedefinition 65dereference operation 187
authorizationdefinition 2
authorization ID 65authorization names
definition 65description 65restrictions governing 65
AVG aggregate function 270AVG function
basic description 249
Bbase table
definition 5basic predicate
detailed format 229best fit (function)
choosing 168
© Copyright IBM Corp. 1993 - 2002 925
best fit (method)choosing 178
BETWEEN clausein OLAP functions 187
BETWEEN predicatedetailed diagram 233
big integer 94BIGINT function
basic description 250integer values from
expressions 299BIGINT SQL data type
description 94binary large objects (BLOBs)
definition 98scalar function description 301
binary string data typesdescription 98
bindingdata retrieval, role in
optimizing 1function semantics 168method semantics 168
bit datadefinition 95
BLASTvalid objects for nicknames 52
BLOB data typedescription 98
BLOB functionbasic description 250
buffer pool namedefinition 65
buffer poolsdefinition 26
building a DATALINK valueDLVALUE function 355
built-in functionsdescription 168
business rulestransitional 24
byte length values, list for datatypes 390
CCall Level Interface (CLI)
definition 19CALL statements
invoked from a compiledstatement 877
CASE expression 187case sensitive identifiers 63CAST
expression as operand 187null as operand 187
CAST (continued)parameter marker as
operand 187specifications 187
castingbetween data types 113reference types 113user-defined types 113
catalog viewsATTRIBUTES 639BUFFERPOOLDBPARTITIONS 641BUFFERPOOLNODES (see
BUFFERPOOLDBPARTITIONS) 641BUFFERPOOLS 642CASTFUNCTIONS 643CHECKS 644COLAUTH 645COLCHECKS 646COLDIST 647COLGROUPDIST 648COLGROUPDISTCOUNTS 649COLGROUPS 650COLOPTIONS 651COLUMNS 652COLUSE 657CONSTDEP 658DATATYPES 659DBAUTH 661DBPARTITIONGROUPDEF 663DBPARTITIONGROUPS 664description 20EVENTMONITORS 665EVENTS 667EVENTTABLES 668FULLHIERARCHIES 669FUNCDEP (see
ROUTINEDEP) 708FUNCMAPOPTIONS 670FUNCMAPPARMOPTIONS 671FUNCMAPPINGS 672FUNCPARMS (see
ROUTINEPARMS) 709FUNCTIONS (see
ROUTINES) 711HIERARCHIES 673INDEXAUTH 674INDEXCOLUSE 675INDEXDEP 676INDEXES 677INDEXEXPLOITRULES 682INDEXEXTENSIONDEP 683INDEXEXTENSIONMETHODS 684INDEXEXTENSIONPARMS 685INDEXEXTENSIONS 686INDEXOPTIONS 687
catalog views (continued)KEYCOLUSE 688NAMEMAPPINGS 689NODEGROUPDEF (see
DBPARTITIONGROUPDEF) 663NODEGROUPS (see
DBPARTITIONGROUPS) 664overview 636PACKAGEAUTH 690PACKAGEDEP 691PACKAGES 693PARTITIONMAPS 699PASSTHRUAUTH 700PREDICATESPECS 701PROCEDURES (see
ROUTINES) 711PROCOPTIONS 702PROCPARMOPTIONS 703PROCPARMS (see
ROUTINEPARMS) 709read-only 636REFERENCES 704REVTYPEMAPPINGS 705ROUTINEAUTH 707ROUTINEDEP (formerly
FUNCDEP) 708ROUTINEPARMS (formerly
FUNCPARMS,PROCPARMS) 709
ROUTINES (formerlyFUNCTIONS,PROCEDURES) 711
SCHEMAAUTH 718SCHEMATA 719SEQUENCEAUTH 720SEQUENCES 721SERVEROPTIONS 723SERVERS 724STATEMENTS 725SYSDUMMY1 638SYSSTAT.COLDIST 747SYSSTAT.COLUMNS 749SYSSTAT.FUNCTIONS (see
SYSSTAT.ROUTINES) 755SYSSTAT.ROUTINES (formerly
SYSSTAT.FUNCTIONS) 755SYSSTAT.TABLES 757SYSSTATINDEXES 751TABAUTH 726TABCONST 728TABDEP 729TABLES 730TABLESPACES 735TABOPTIONS 736TBSPACEAUTH 737
926 SQL Reference, Volume 1
catalog views (continued)TRANSFORMS 738TRIGDEP 739TRIGGERS 740TYPEMAPPINGS 741updatable 636USEROPTIONS 743VIEWS 744WRAPOPTIONS 745WRAPPERS 746
CEIL functiondescription 302values and arguments 302
CEIL or CEILING functionbasic description 250
CEILING functiondescription 302values and arguments 302
CHARfunction description 303
CHAR data typedescription 95
CHAR functionbasic description 250
CHARfunction(SYSFUN.CHAR) 250
characterconversion 20SQL language element 61
character conversionrules for assignments 117rules for comparison 117rules for operations combining
strings 139rules when comparing
strings 139character sets
definition 20character string constant 143character string data types 95character strings
arithmetic operators, prohibiteduse 187
assignment 117BLOB string representation 301comparisons 117double-byte character string 489equality definition 117equality, collating sequence
examples 117POSSTR scalar function 427returning from host variable
name 475translating string syntax 475VARCHAR scalar function 485
character strings (continued)VARGRAPHIC scalar
function 489character subtypes 95check pending state 8CHR function
basic description 250description 309values and arguments 309
CLI (Call Level Interface)definition 19
CLIENT ACCTNG specialregister 148
CLIENT APPLNAME specialregister 149
CLIENT USERID specialregister 150
CLIENT WRKSTNNAME specialregister 151
CLOB (character large object) datatype
description 95CLOB (character large object)
functiondescription 310values and arguments 310
CLOB functionbasic description 250
CLSCHED sample table 803COALESCE function 311
basic description 250code pages
attributes 20definition 20
code point 20collating sequence
string comparison rules 117COLLATING_SEQUENCE
server optionvalid settings 764
collocation, table 28column function
description 168column name
definition 65uses 65
column name qualification inCOMMENT ON statement 65
column options 762description 53
columnsadding values (SUM) 289ambiguous name reference
errors 65
columns (continued)averaging a set of values
(AVG) 270BASIC predicate, use in matching
strings 229BETWEEN predicate, in matching
strings 233correlation between a set of
number pairs(CORRELATION) 272
covariance of a set of numberpairs (COVARIANCE) 277
definitiontables 5
EXISTS predicate, in matchingstrings 234
finding maximum value 280GROUP BY, use in limiting in
SELECT clause 554grouping column names in
GROUP BY 554HAVING clause, search names,
rules 554HAVING, use in limiting in
SELECT clause 554IN predicate, fullselect, values
returned 235LIKE predicate, in matching
strings 238name, qualified conditions 65name, unqualified conditions 65names in ORDER BY clause 554naming conventions 65nested table expression 65null values in result
columns 554qualified column name rules 65result data 554scalar fullselect 65searching using WHERE
clause 554SELECT clause syntax
diagram 554standard deviation of a set of
values (STDDEV) 288string assignment rules 117subquery 65undefined name reference
errors 65variance of a column set of
values (VARIANCE) 290combining grouping sets 554COMM_RATE
valid settings 764
Index 927
commentshost language, format 63SQL, format 63
commit processinglocks, relation to uncommitted
changes 16common syntax elements xvcommon table expressions
definition 601recursive 601recursive example 861select statement 601
comparing a value with acollection 233
comparing LONG VARGRAPHICstrings, restricted use 117
comparing two predicates, truthconditions 229, 244
comparison, basic SQLoperation 117
compatibilitydata types 117data types, summary 117rules 117rules for operation types 117
compensationdescription 45
composite column value 554composite keys
definition 7CONCAT function
description 312values and arguments 312
CONCAT or || functionbasic description 250
concatenationdistinct type 187operators 187result data type 187result length 187
condition name in SQLprocedure 65
connected statedescription 29
connection state 29remote unit of work 29
CONNECTSTRINGvalid settings 764
consistencypoints of 16
constantscharacter string 143decimal 143floating-point 143graphic string 143
constants (continued)hexadecimal 143integer 143SQL language element 143with user-defined types 143
constraintsExplain tables 833name, definition 65referential 8table check 8unique 8
containersdefinition 26
CONTROL privilegeoverview 2
conventions, namingnaming 65
conversion rulesassignments 117comparisons 117operations combining
strings 139string comparisons 139
conversionsCHAR, returning converted
datetime values 303character string to
timestamp 466datetime to string variable 117DBCS from mixed SBCS and
DBCS 489decimal values from numeric
expressions 327double-byte character string 489floating point values from
numeric expressions 357, 435integer to decimal, mixed
expression rules 187numeric, scale and precision,
summary 117correlated reference
use in nested tableexpression 65
use in scalar fullselect 65use in subquery 65use in subselect 554
CORRELATION function 272correlation name
definition 65FROM clause, subselect
rules 554in SELECT clause, syntax
diagram 554qualified reference 65rules 65
CORRELATION or CORR 251COS function
basic description 251description 313values and arguments 313
COSH functionbasic description 251description 314values and arguments 314
COT functionbasic description 251description 315values and arguments 315
COUNT function 273basic description 251
COUNT_BIG functionbasic description 251detailed format description 275values and arguments 275
COVARIANCE function 277COVARIANCE or COVAR function
basic description 251CPU_RATIO
valid settings 764CREATE REVERSE TYPE MAPPING
statementdiscussion 791
CREATE TYPE MAPPING statementdiscussion 791
cross tabulation rows 554CS (cursor stability)
comparision table 827isolation level 13
CUBEexamples 554query description 554
current connection state 29CURRENT DATE special
register 152CURRENT DBPARTITIONNUM
special register 153CURRENT DEFAULT TRANSFORM
GROUP special register 154CURRENT DEGREE special register
description 155CURRENT EXPLAIN MODE special
registerdescription 156
CURRENT EXPLAIN SNAPSHOTspecial register
description 157CURRENT FUNCTION PATH
special registerdescription 159
928 SQL Reference, Volume 1
CURRENT MAINTAINED TABLETYPES FOR OPTIMIZATIONspecial register 158
CURRENT PATH special registerdescription 159
CURRENT QUERY OPTIMIZATIONspecial register
description 160CURRENT REFRESH AGE special
registerdescription 161
CURRENT SCHEMA specialregister 162
CURRENT SERVER specialregister 163
CURRENT SQLID specialregister 162
CURRENT TIME specialregister 164
CURRENT TIMESTAMP specialregister 165
CURRENT TIMEZONE specialregister 166
cursor namedefinition 65
cursor stability (CS)comparision table 827isolation levels 13
Ddata
partitioning 28data definition language (DDL)
definition 1data source name 65data source objects
description 52data sources
access methods protocols, clientsoftware, drivers 41
default wrapper names 48description 41supported versions 41valid objects for nicknames 52valid server types 759
data structurespacked decimal 621
data type mappingsdescription 54forward
introduction 775, 791reverse
introduction 791data types
BIGINT 94
data types (continued)binary string 98BLOB 98casting between 113CHAR 95character string 95CLOB 95DATALINK 105DATE 101datetime 101DBCLOB 97DECIMAL or NUMERIC 94DOUBLE or FLOAT 94GRAPHIC 97graphic string 97INTEGER 94LONG VARCHAR 95LONG VARGRAPHIC 97numeric 94partition compatibility 141promotion 111promotion in a Unicode
database 111REAL 94result columns 554SMALLINT 94SQL language element 92TIME 101TIMESTAMP 101TYPE_ID function 480TYPE_NAME function 481TYPE_SCHEMA function 482unsupported 54user-defined 108VARCHAR 95VARGRAPHIC 97XML 107
database managerlimits 607SQL interpretation 1
databasescreating
sample 803erasing sample 803
DATALINK data typeBNF specifications 891description 105extracting comment 338extracting complete URL 347extracting file server 354extracting link type 339extracting path and file
name 350, 351extracting scheme 353returning a data link value 355
DATALINK data type (continued)unsupported 54
DATE data typeCHAR, use in format
conversion 303day durations, finding from
range 323description 101duration format 187WEEK scalar function 491WEEK_ISO scalar function 492
DATE functionarithmetic operations 187basic description 251description 316value to date format
conversion 316dates
month, returning from datetimevalue 405
string representationformats 101
using year in expressions 493datetime data types
arithmetic operations 187description 101string representation of 101VARCHAR scalar function 485
DAY function 318basic description 251
DAYNAME functionbasic description 251
DAYNAME scalar functiondescription 319
DAYOFWEEK functionbasic description 252
DAYOFWEEK scalar functiondescription 320
DAYOFWEEK_ISO functionbasic description 252
DAYOFWEEK_ISO scalar functiondescription 321
DAYOFYEAR functionbasic description 252
DAYOFYEAR scalar functiondescription 322values and arguments 322
DAYS functionbasic description 252
DAYS scalar function 323DB2 documentation search
using Netscape 4.x 912DB2 family
default wrapper name 48valid objects for nicknames 52
Index 929
DB2 for iSeries data sourcesdefault forward data type
mappings 775DB2 for OS/390 data sources
default reverse data typemappings 791
DB2 for OS/400 data sourcesdefault reverse data type
mappings 791DB2 for VM data sources 791DB2 for z/OS and OS/390 data
sourcesdefault forward type
mappings 775DB2 Information Center 917DB2 Server for VM and VSE
default forward typemappings 775
DB2 tutorials 916DB2_FENCED wrapper option
valid settings 774db2nodes.cfg file
DBPARTITIONNUMfunction 325
DBADM authoritydescription 2
DBCLOB data typedescription 97
DBCLOB functionbasic description 252description 324values and arguments 324
DBNAMEvalid settings 764
DBPARTITIONNUM functionbasic description 252description 325values and arguments 325
DDL (data definition language)definition 1
decimal constantdescription 143
decimal conversion from integer,summary 117
DECIMAL data type 94arithmetic formulas, scale and
precision 187conversion from
floating-point 117DECIMAL function
description 327values and arguments 327
DECIMAL or DEC functionbasic description 252
DECIMAL or NUMERIC data typedescription 94
declared temporary tabledefinition 5
declusteringpartial 28
decrementing a date, rules 187decrementing a time, rules 187DECRYPT function
description 332values and arguments 332
DECRYPT_BIN functionbasic description 253
DECRYPT_CHAR functionbasic description 253
decrypting informationDECRYPT function 332
DEGREES functionbasic description 253
DEGREES scalar functiondescription 334values and arguments 334
delete rulewith referential constraint 8
delimiter tokendefinition 63
DENSERANK (DENSE_RANK)OLAP function 187
DEPARTMENT sample table 803dependent row 8dependent table 8DEREF function
basic description 253description 335reference types 335values and arguments 335
dereference operatorsattribute-name operand 187
DESC clauseof select statement 554
descendent row 8descendent table 8descriptor name
definition 65diagnostic string
in RAISE_ERROR function 432DIFFERENCE function
basic description 253description 336values and arguments 336
DIGITS functionbasic description 253description 337values and arguments 337
dirty read 827
disability 915DISABLE function mapping
option 763DISTINCT keyword
aggregate function 269AVG function 270COUNT_BIG function 275MAX function restriction 280STDDEV function 288subselect statement 554SUM function 289VARIANCE function 290
distinct type namedefinition 65
distinct typesas arithmetic operands 187comparison 117concatenation 187constants 143description 108
Distributed Relational DatabaseArchitecture (DRDA) 29
distributed relational databasesapplication requester 29application server 29application-directed distributed
unit of work 29definition 29remote unit of work 29requester-server protocols 29
distributed unit of workdescription 29
DLCOMMENT functionbasic description 253description 338values and arguments 338
DLLINKTYPE functionbasic description 253description 339values and arguments 339
DLNEWCOPY functionbasic description 253description 340values and arguments 340
DLPREVIOUSCOPY functionbasic description 253description 343values and arguments 343
DLREPLACECONTENT functionbasic description 253description 345values and arguments 345
DLURLCOMPLETE functionbasic description 253description 347
930 SQL Reference, Volume 1
DLURLCOMPLETE function(continued)
values and arguments 347DLURLCOMPLETEONLY function
basic description 254description 348values and arguments 348
DLURLCOMPLETEWRITE functionbasic description 254description 349values and arguments 349
DLURLPATH functionbasic description 254description 350values and arguments 350
DLURLPATHONLY functionbasic description 254description 351values and arguments 351
DLURLPATHWRITE functionbasic description 254description 352values and arguments 352
DLURLSCHEME functionbasic description 254description 353values and arguments 353
DLURLSERVER functionbasic description 254description 354values and arguments 354
DLVALUE functionbasic description 254description 355values and arguments 355
Documentumvalid objects for nicknames 52
dormant connection state 29DOUBLE
CHAR, use in formatconversion 303
DOUBLE functionbasic description 254description 357values and arguments 357
DOUBLE or DOUBLE_PRECISIONfunction
basic description 254DOUBLE or FLOAT data type
description 94double-byte character strings
returning string 489double-byte characters
truncated duringassignment 117
double-precision floating-point datatype 94
duration 187adding 187date format 187labeled 187subtracting 187time format 187timestamp 187
dynamic dispatch of methods 178dynamic SQL
definition 1EXECUTE statement 1PREPARE statement 1SQLDA used with 621
Eembedded SQL for Java (SQLJ)
Java database connectivity 19EMPACT sample table 803EMPLOYEE sample table 803EMPPHOTO sample table 803EMPRESUME sample table 803empty string 95, 97encoding scheme
definition 20ENCRYPT function
basic description 254ENCRYPT scalar function 359encrypting information
ENCRYPT function 359GETHINT function 366
error message codesSQLCA definitions 615
ESCAPE clausesLIKE predicate 238
EUC (extended UNIX code)considerations 883
evaluation orderexpressions 187
event monitor namedefinition 65
event monitorsdefinition 23EVENT_MON_STATE
function 362types 23
EVENT_MON_STATE functionbasic description 254
EXCEPT operator of fullselect 595exception tables
structure 867exclusive lock 13EXECUTE IMMEDIATE statement
dynamic SQL 1
EXECUTE privilege 168, 178EXECUTE statement
dynamic SQL 1EXISTS predicate
description 234EXP function
basic description 255description 363values and arguments 363
explain tablesoverview 833
EXPLAIN_ARGUMENT tabledescription 834
EXPLAIN_INSTANCE tabledescription 838
EXPLAIN_OBJECT tabledescription 841
EXPLAIN_OPERATOR tabledescription 844
EXPLAIN_PREDICATE tabledescription 846
EXPLAIN_STATEMENT tabledescription 848
EXPLAIN_STREAM tabledescription 851
exposed correlation-name in FROMclause 65
expressionsarithmetic operators 187CASE 187CAST specification 187CAST specifications 187concatenation operators 187datetime operands 187decimal operands 187dereference operations 187floating-point operands 187format and rules 187grouping-expressions in GROUP
BY 554in a subselect 554in ORDER BY clause 554in SELECT clause, syntax
diagram 554integer operands 187mathematical operators 187method invocation 187OLAP functions 187precedence of operation 187scalar fullselect 187sequences 187strings 187substitution operators 187subtype treatment 187values 187
Index 931
expressions (continued)without operators 187
external functiondescription 168
extracting comment fromDATALINK value
DLCOMMENT function 338extracting complete URL from
DATALINK valueDLURLCOMPLETE
function 347extracting file server from
DATALINK valueDLURLSERVER function 354
extracting linktype from DATALINKvalue
DLLINKTYPE function 339extracting path and file name from
DATALINK valueDLURLPATH function 350DLURLPATHONLY
function 351extracting scheme from DATALINK
valueDLURLSCHEME function 353
Ffederated databases
definition 1description 43
federated serverdescription 39
federated systemsdescription 39
file reference variablesBLOB 65CLOB 65DBCLOB 65
fixed-length character string 95fixed-length graphic string 97FLOAT function
basic description 255description 364values and arguments 364
FLOAT or DOUBLE data typedescription 94
floating-point constantdescription 143
floating-point to decimalconversion 117
FLOOR functionbasic description 255description 365values and arguments 365
FOLD_IDvalid settings 764
FOLD_PWvalid settings 764
FOR FETCH ONLY clauseSELECT statement 601
FOR READ ONLY clauseSELECT statement 601
foreign keys 8definition 7
forward type mappingsdescription 775
fragments in SUBSTR function,warning 456
FROM clausecorelation-name example 65exposed names explained 65non-exposed names
explained 65subselect syntax 554use of correlation names 65
fullselectdetailed syntax 595examples 595initialization 601, 861iterative 601, 861multiple operations, order of
execution 595ORDER BY clause 554scalar 187subquery role, search
condition 65table reference 554
function designator syntaxelement xv
function mapping namedefinition 65
function mapping optionsdescription 57DISABLE
valid settings 763INITIAL_INSTS
valid settings 763INITIAL_IOS
valid settings 763INSTS_PER_ARGBYTE
valid settings 763INSTS_PER_INVOC
valid settings 763IOS_PER_ARGBYTE
valid settings 763IOS_PER_INVOC
valid settings 763PERCENT_ARGBYTES
valid settings 763
function mapping options(continued)
REMOTE_NAMEvalid settings 763
function mappingsdescription 56
function namedefinition 65
function pathbuilt-in 168
function signature 168function templates
description 56functions
aggregate 269COUNT 273MIN 282
arguments 247built-in 168column 168, 269
AVG 249, 270CORR 272CORRELATION 272CORRELATION or
CORR 251COUNT 251, 273COUNT_BIG 251, 275COVAR 277COVARIANCE 277COVARIANCE or
COVAR 251MAX 257, 280MIN 258, 282REGR_AVGX 260, 284REGR_AVGY 260, 284REGR_COUNT 260, 284REGR_ICPT 284REGR_INTERCEPT 284REGR_INTERCEPT OR
REGR_ICPT 260REGR_R2 260, 284REGR_SLOPE 260, 284REGR_SXX 260, 284REGR_SXY 260, 284REGR_SYY 261, 284regression functions 284STDDEV 262, 288SUM 262, 289VAR, options 290VAR, results 290VARIANCE or VAR 265VARIANCE, options 290VARIANCE, results 290
description 247external 168
932 SQL Reference, Volume 1
functions (continued)in a Unicode database 291in expressions 247OLAP
DENSERANK 187RANK 187ROWNUMBER 187
overloaded 168procedures 545row 168scalar 168, 291
ABS 292ABS or ABSVAL 249ABSVAL 292ACOS 249, 293ASCII 249, 294ASIN 249, 295ATAN 249, 296ATAN2 249, 297ATANH 249, 298AVG 270BIGINT 250, 299BLOB 250, 301CEIL 302CEIL or CEILING 250CEILING 302CHAR 250, 303CHAR (SYSFUN
schema) 250CHR 250, 309CLOB 250, 310COALESCE 250, 311CONCAT 312CONCAT or || 250COS 251, 313COSH 251, 314COT 251, 315DATE 251, 316DAY 251, 318DAYNAME 251, 319DAYOFWEEK 252, 320DAYOFWEEK_ISO 252, 321DAYOFYEAR 252, 322DAYS 252, 323DBCLOB 252, 324DBPARTITIONNUM 252,
325DECIMAL 327DECIMAL or DEC 252DECRYPT_BIN 253DECRYPT_CHAR 253DECRYPTBIN 332DECRYPTCHAR 332DEGREES 253, 334DEREF 253, 335
functions (continued)scalar (continued)
DIFFERENCE 253, 336DIGITS 253, 337DLCOMMENT 253, 338DLLINKTYPE 253, 339DLNEWCOPY 253, 340DLPREVIOUSCOPY 253, 343DLREPLACECONTENT 253,
345DLURLCOMPLETE 253, 347DLURLCOMPLETEONLY 254,
348DLURLCOMPLETEWRITE 254,
349DLURLPATH 254, 350DLURLPATHONLY 254, 351DLURLPATHWRITE 254,
352DLURLSCHEME 254, 353DLURLSERVER 254, 354DLVALUE 254, 355DOUBLE 254, 357DOUBLE or
DOUBLE_PRECISION 254DOUBLE_PRECISION 357ENCRYPT 254, 359EVENT_MON_STATE 254,
362EXP 255, 363FLOAT 255, 364FLOOR 255, 365GENERATE_UNIQUE 255,
367GET_ROUTINE_SAR 255,
259GETHINT 255, 366GRAPHIC 255, 369GROUPING 255, 278HASHEDVALUE 255, 371HEX 255, 373HOUR 256, 375IDENTITY_VAL_LOCAL 256,
376INSERT 256, 382INTEGER 384INTEGER or INT 256JULIAN_DAY 256, 386LCASE 256, 388LCASE (SYSFUN
schema) 256LCASE or LOWER 387LEFT 256, 389LENGTH 256, 390LN 256, 392
functions (continued)scalar (continued)
LOCATE 257, 393LOG 257, 394LOG10 257, 395LONG_VARCHAR 257, 396LONG_VARGRAPHIC 257,
397LTRIM 257, 398, 400LTRIM (SYSFUN
schema) 257MICROSECOND 258, 401MIDNIGHT_SECONDS 258,
402MINUTE 258, 403MOD 258, 404MONTH 258, 405MONTHNAME 258, 406MQPUBLISH 258, 407MQREAD 258, 410MQREADCLOB 412MQRECEIVE 259, 414MQRECEIVECLOB 416MQSEND 259, 418MQSUBSCRIBE 259, 420MQUNSUBSCRIBE 259, 422MULTIPLY_ALT 259, 424NODENUMBER (see
DBPARTITIONNUM) 325NULLIF 259, 426PARTITION (see
HASHEDVALUE) 371POSSTR 259, 427POWER 259, 429, 431QUARTER 260, 430RADIANS 260RAISE_ERROR 260, 432RAND 260, 434REAL 260, 435REC2XML 260, 436REPEAT 261, 441REPLACE 261, 442RIGHT 261, 443ROUND 261, 444RTRIM 261, 446, 447RTRIM (SYSFUN
schema) 261SECOND 261, 448SIGN 262, 449SIN 262, 450SINH 262, 451SMALLINT 262, 452SOUNDEX 262, 453SPACE 262, 454SQRT 262, 455
Index 933
functions (continued)scalar (continued)
SUBSTR 262, 456TABLE_NAME 263, 460TABLE_SCHEMA 263, 461TAN 263, 463TANH 263, 464TIME 263, 465TIMESTAMP 263, 466TIMESTAMP_FORMAT 263,
468TIMESTAMP_ISO 263, 470TIMESTAMPDIFF 264, 471TO_CHAR 264, 473TO_DATE 264, 474TRANSLATE 264, 475TRUNC 478TRUNC or TRUNCATE 264TRUNCATE 478TYPE_ID 265, 480TYPE_NAME 265, 481TYPE_SCHEMA 265, 482UCASE 265, 483UCASE (SYSFUN
schema) 265UPPER 483VALUE 265, 484VARCHAR 265, 485VARCHAR_FORMAT 265,
487VARGRAPHIC 265, 489WEEK 265, 491WEEK_ISO 266, 492YEAR 266, 493
sourced 168SQL 168SQL language element 168table 168, 494
MQREADALL 259, 495MQREADALLCLOB 497MQRECEIVEALL 259, 499MQRECEIVEALLCLOB 502SNAPSHOT_AGENT 505SNAPSHOT_APPL 506SNAPSHOT_APPL_INFO 510SNAPSHOT_BP 512SNAPSHOT_CONTAINER 514SNAPSHOT_DATABASE 516SNAPSHOT_DBM 521SNAPSHOT_DYN_SQL 523SNAPSHOT_FCM 525SNAPSHOT_FCMPARTITION 526SNAPSHOT_LOCK 527SNAPSHOT_LOCKWAIT 529SNAPSHOT_QUIESCERS 531
functions (continued)table (continued)
SNAPSHOT_RANGES 532SNAPSHOT_STATEMENT 533SNAPSHOT_SUBSECT 535SNAPSHOT_SWITCHES 537SNAPSHOT_TABLE 538SNAPSHOT_TBS 540SNAPSHOT_TBS_CFG 542SQLCACHE_SNAPSHOT 262,
544user-defined 168, 550
GGENERATE_UNIQUE function
basic description 255syntax 367
generic data sources 775, 791GET_ROUTINE_SAR 546GET_ROUTINE_SAR function
basic description 255GETHINT function
basic description 255description 366values and arguments 366
global catalogdescription 43
grand total row 554GRAPHIC data type
description 97GRAPHIC function
basic description 255description 369values and arguments 369
graphic string constantdescription 143
graphic string data typesdescription 97
graphic stringsreturning from host variable
name 475translating string syntax 475
GROUP BY clausesubselect results 554subselect rules and syntax 554
group namedefinition 65
GROUPING function 278basic description 255
grouping sets 554grouping-expression 554
Hhash partitioning 28
HASHEDVALUE functionbasic description 255description 371values and arguments 371
HAVING clausesearch conditions with
subselect 554subselect results 554
held connection state 29HEX function
basic description 255description 373values and arguments 373
hexadecimal constantdescription 143
host identifiersin host variable 65
host variablesBLOB 65CLOB 65DBCLOB 65definition 65indicator variables 65syntax diagram 65
HOUR functionbasic description 256description 375values and arguments 375
Iidentifiers
delimited 65host 65length limits 607ordinary 65SQL 65
IDENTITY_VAL_LOCAL functionbasic description 256description 376values and arguments 376
IFILEvalid settings 764
IGNORE_UDTvalid settings 764
IMPLICITSCHEMA authority 4IN predicate 235incrementing a date, rules 187incrementing a time, rules 187index name
definition 65index specifications
description 58indexes
definition 7
934 SQL Reference, Volume 1
indicator variablesdescription 65host variable, uses in
declaring 65infix operators 187Informix
default forward typemappings 775
default wrapper name 48valid objects for nicknames 52
INITIAL_INSTSvalid settings for function
mapping option 763INITIAL_IOS
valid settings for functionmapping option 763
initialization fullselect 601, 861INSERT function
basic description 256description 382values and arguments 382
insert rule with referentialconstraint 8
INSTS_PER_ARGBYTEvalid settings for function
mapping option 763INSTS_PER_INVOC
valid settings for functionmapping option 763
integer constantdescription 143
INTEGER data typedescription 94
INTEGER functiondescription 384values and arguments 384
INTEGER or INT functionbasic description 256
integer values from expressionsINTEGER function 384
integersdecimal conversion
summary 117in ORDER BY clause 554
interactive SQL 1intermediate result tables 554INTERSECT operator
duplicate rows, use of ALL 595of fullselect, role in
comparison 595INTO clause
FETCH statement, use in hostvariable 65
SELECT INTO statement, use inhost variable 65
INTO clause (continued)values from applications
programs 65INTRAY sample table 803invocation
function 168IO_RATIO
valid settings 764IOS_PER_ARGBYTE
valid settings for functionmapping option 763
IOS_PER_INVOCvalid settings for function
mapping option 763isolation levels
comparisons 827cursor stability 13cursor stability (CS) 827description 13in DELETE statement 601none 827read stability (RS) 13, 827repeatable read (RR) 13, 827uncommitted read (UR) 13, 827
iterative fullselect 601, 861IUD_APP_SVPT_ENFORCE
valid settings 764
JJava database connectivity (JDBC)
embedded SQL for Java 19JDBC (Java database
connectivity) 19joined table
subselect clause 554table reference 554
joinsexamples 554full outer join 554inner join 554left outer join 554right outer join 554subselect examples 554
JULIAN_DAY functionbasic description 256description 386values and arguments 386
Kkeys
composite 7definition 7foreign 7, 8parent 8partitioning 7
keys (continued)primary 7unique 7, 8
Llabeled duration, in expressions 187labels
object names in SQLprocedures 65
large integer 94large object locator 99large objects (LOBs)
description 99LCASE function
basic description 256LCASE
function(SYSFUN.LCASE) 256LCASE or LOWER scalar function
detailed format description 387values and arguments, rules
for 387LCASE scalar function
description 388values and arguments 388
LEFT functionbasic description 256
LEFT scalar functiondescription 389values and arguments 389
lengthLENGTH scalar function 390
LENGTH functionbasic description 256
LENGTH scalar functiondescription 390values and arguments 390
LIKE predicate 238limits
identifier length 607SQL 607
literalsdescription 143
LN functionbasic description 256description 392values and arguments 392
LOB (large object) data typesdescription 99
LOB locators 99local
catalog information 43LOCATE function
basic description 257LOCATE scalar function
description 393
Index 935
LOCATE scalar function (continued)values and arguments 393
locatorslarge object (LOB) 99variable description 65
lockingdefinition 16
locksexclusive (X) 13share (S) 13update (U) 13
LOG functionbasic description 257description 394values and arguments 394
LOG10 functionbasic description 257
LOG10 scalar functiondescription 395values and arguments 395
logical operators, search rules 226LOGIN_TIMEOUT
valid settings 764LONG VARCHAR data type
description 95unsupported 54
LONG VARGRAPHIC data typedescription 97unsupported 54
LONG_VARCHAR functionbasic description 257description 396values and arguments 396
LONG_VARGRAPHIC functionbasic description 257description 397values and arguments 397
LTRIM functionbasic description 257
LTRIMfunction(SYSFUN.LTRIM) 257
LTRIM scalar functiondescription 398, 400values and arguments 398, 400
Mmap, partitioning 26MAX function
basic description 257detailed format description 280values and arguments 280
method designator syntaxelement xv
method invocation 187method name 65
method signature 178methods
built-in 178dynamic dispatch of 178external 178invoking 187overloaded 178SQL 178SQL language element 178type preserving 178user-defined 178
MICROSECOND functionbasic description 258description 401values and arguments 401
Microsoft SQL Serverdata sources
default forward typemappings 775, 791
MIDNIGHT_SECONDS functionbasic description 258description 402values and arguments 402
MIN function 282basic description 258
MINUTE functionbasic description 258description 403values and arguments 403
mixed datadefinition 95LIKE predicate 238
MOD functionbasic description 258description 404values and arguments 404
monitoringdatabase events 23
MONTH functionbasic description 258description 405values and arguments 405
MONTHNAME functionbasic description 258description 406values and arguments 406
MQPUBLISH functionbasic description 258description 407values and arguments 407
MQREAD functionbasic description 258description 410values and arguments 410
MQREADALL functionbasic description 259description 495values and arguments 495
MQREADALLCLOB functiondescription 497values and arguments 497
MQREADCLOB functiondescription 412values and arguments 412
MQRECEIVE functionbasic description 259description 414values and arguments 414
MQRECEIVEALL functionbasic description 259description 499values and arguments 499
MQRECEIVEALLCLOB functiondescription 502values and arguments 502
MQRECEIVECLOB functiondescription 416values and arguments 416
MQSEND functionbasic description 259description 418values and arguments 418
MQSUBSCRIBE functionbasic description 259description 420values and arguments 420
MQUNSUBSCRIBE functionbasic description 259description 422values and arguments 422
multiple row VALUES clauseresult data type 134
MULTIPLY_ALT functionbasic description 259detailed format description 424values and arguments, rules
for 424
Nnames
identifying columns insubselect 554
naming conventionsidentifiers 65qualified column rules 65
nested table expressions 554nextval-expression 187nicknames
definition 65
936 SQL Reference, Volume 1
nicknames (continued)description 52exposed names in FROM
clause 65FROM clause 554non-exposed names in FROM
clause 65qualifying a column name 65SELECT clause, syntax
diagram 554valid data source objects 52
NODEvalid settings 764
nodegroupsdefinition 26name 65
NODENUMBER function (seeDBPARTITIONNUM) 325
non-exposed correlation-name inFROM clause 65
nonrelational data sourcesdata type mappings,
specifying 54nonrepeatable read 827NOT NULL clause
in NULL predicate 243NUL-terminated character
strings 95null
CAST specification 187NULL predicate rules 243null value
definition 92null value, SQL
assignment 117grouping-expressions, allowable
uses 554occurrences in duplicate
rows 554result columns 554specified by indicator
variable 65unknown condition 226
NULLIF functionbasic description 259description 426values and arguments 426
numbersprecision 621scale 621
numericassignments in SQL
operations 117comparisons 117
numeric data typesdescription 94
NUMERIC or DECIMAL data typedescription 94
NUMERIC_STRINGcolumn option
valid settings 762
Oobject table 65ODBC (open database connectivity)
description 19valid objects for nicknames 52
OLAP functionsBETWEEN clause 187CURRENT ROW clause 187description 187ORDER BY clause 187OVER clause 187PARTITION BY clause 187RANGE clause 187ROW clause 187UNBOUNDED clause 187
OLE DBdefault wrapper name 48
onlinehelp, accessing 904
online analytical processing(OLAP) 187
open database connectivity(ODBC) 19
operandsdatetime
date duration 187labeled duration 187time duration 187
decimal 187decimal rules 187floating-point 187integer 187integer rules 187result data type 134strings 187
operationsassignments 117comparisons 117datetime, SQL rules 187dereference 187
operators, arithmetic 187optimizer
description 44OR truth table 226Oracle data sources
default forward typemappings 791
Oracle data sources (continued)default wrapper names 48NET8
default forward typemappings 775
SQLNETdefault forward type
mappings 775valid objects for nicknames 52
ORDER BY clausein OLAP functions 187select statement 554
order of evaluationexpressions 187
ordering DB2 books 904ordinary tokens 63ORG sample table 803outer join
joined table 554OVER clause, in OLAP
functions 187overloaded function
multiple function instances 168overloaded method 178
Ppackage names
definition 65packages
authorization IDsand binding 65in dynamic statements 65
definition 20page 764parameter markers
CAST specification 187host variables in dynamic
SQL 65parameter name
definition 65parent key 8parent row 8parent table 8parentheses, precedence of
operations 187partial declustering 28PARTITION BY clause
in OLAP functions 187PARTITION function (see
HASHEDVALUE) 371partitioned relational database 1partitioning data
across multiple partitions 28compatibility table 141partition compatibility 141
Index 937
partitioning keysdescription 7
partitioning mapsdefinition 26
partitionscompatibility 141
pass-throughdescription 46restrictions 46
PASSWORDvalid settings 764
path, SQL 168PERCENT_ARGBYTES function
mapping option 763phantom row 13, 827PLAN_HINTS
valid settings 764point of consistency, database 16POSSTR function
basic description 259description 427values and arguments 427
POWER functionbasic description 259
POWER scalar functiondescription 429values and arguments 429
precedencelevel operatorsor 187order of evaluating
operations 187precision
numbers, determined bySQLLEN variable 621
precision-integer DECIMALfunction 327
predicatesbasic, detailed diagram 229BETWEEN, detailed
diagram 233description 225EXISTS 234IN 235LIKE 238NULL 243quantified 230TYPE 244
prefixoperator 187
PREPARE statementdynamic SQL 1
prevval-expression 187primary keys
definition 7printed books, ordering 904
privilegesCONTROL 2description 2EXECUTE 168, 178
procedure designator syntaxelement xv
procedure namedefinition 65
PROJECT sample table 803promoting
data types 111PUSHDOWN
valid settings 764pushdown analysis
description 44PUT_ROUTINE_SAR function
basic description 259PUT_ROUTINE_SAR stored
procedure 548
Qqualified column names 65qualifiers
object name 65reserved 823
quantified predicate 230QUARTER function
basic description 260description 430values and arguments 430
queriesauthorization IDs required 553definition 553description 16example
recursive 861SELECT statement 601
fragments 44recursive 601
query optimizationdescription 44
RRADIANS function
basic description 260description 431values and arguments 431
RAISE_ERROR functionbasic description 260
RAISE_ERROR scalar functiondescription 432values and arguments 432
raising errorsRAISE_ERROR function 432
RAND functionbasic description 260
RAND scalar functiondescription 434values and arguments 434
RANGE clause, OLAPfunctions 187
RANK OLAP function 187read stability (RS) 13
comparision table 827REAL data type
description 94REAL function
basic description 260description 435single precision conversion 435values and arguments 435
REC2XML functionbasic description 260
REC2XML scalar functiondescription 436values and arguments 436
recursionexample 861query 601
recursive common tableexpression 601, 861
reference typescasting 113comparisons 117DEREF function 335description 108
referential constraintsdescription 8
referential integrityconstraints 8
REGR_AVGX function 260REGR_AVGY function 260REGR_COUNT function
basic description 260REGR_INTERCEPT or REGR_ICPT
functionbasic description 260
REGR_R2 functionbasic description 260
REGR_SLOPE functionbasic description 260
REGR_SXX function 260REGR_SXY function 260REGR_SYY function 261regression functions
description 284REGR_AVGX 284REGR_AVGY 284REGR_COUNT 284
938 SQL Reference, Volume 1
regression functions (continued)REGR_ICPT 284REGR_INTERCEPT 284REGR_R2 284REGR_SLOPE 284REGR_SXX 284REGR_SXY 284REGR_SYY 284
relational databasedefinition 1
release-pending connection state 29remote
catalog information 43function name 65type name 65
remote authorization name 65remote unit of work
description 29REMOTE_AUTHID user option 773REMOTE_DOMAIN user
option 773REMOTE_NAME function mapping
option 763REMOTE_PASSWORD user
option 773remote-object-name 65remote-schema-name 65remote-table-name 65REPEAT function
basic description 261REPEAT scalar function
description 441values and arguments 441
repeatable read (RR)comparision table 827description 13
REPLACE functionbasic description 261
REPLACE scalar functiondescription 442values and arguments 442
requester, application 29reserved
qualifiers 823schemas 823words 823
resolutionfunction 168method 178
result columnssubselect 554
result data typearguments of COALESCE 134multiple row VALUES
clause 134
result data type (continued)operands 134result expressions of CASE 134set operator 134
result expressions of CASEresult data type 134
result tabledefinition 5query 553
return identity column valueIDENTITY_VAL_LOCAL
function 376returning hour part of values
HOUR function 375returning microsecond from value
MICROSECOND function 401returning minute from value
MINUTE function 403returning month from value
MONTH function 405returning seconds from value
SECOND function 448returning substrings from a string
SUBSTR function 456returning timestamp from values
TIMESTAMP function 466reverse type mappings
introduction 791RIGHT function
basic description 261RIGHT scalar function
description 443values and arguments 443
rollbackdefinition 16
ROLLUP grouping of GROUP BYclause 554
ROUND functionbasic description 261
ROUND scalar functiondescription 444values and arguments 444
routinesprocedures 545SQL statements allowed 873
ROW clausein OLAP functions 187
row functiondescription 168
ROWNUMBER (ROW_NUMBER)OLAP function 187
rowsCOUNT_BIG function 275definition 5dependent 8
rows (continued)descendent 8GROUP BY clause 554HAVING clause 554parent 8search conditions, syntax 226SELECT clause, syntax
diagram 554self-referencing 8
RR (repeatable read) isolation levelcomparision table 827description 13
RS (read stability) isolation levelcomparision table 827description 13
RTRIM (SYSFUN schema) scalarfunction 447
RTRIM functionbasic description 261
RTRIMfunction(SYSFUN.RTRIM) 261
RTRIM scalar functiondescription 446
run-time authorization ID 65
SSALES sample table 803sample database
creating 803description 803erasing 803
savepoint namedefinition 65
SBCS (single-byte character set) datadefinition 95
scalar fullselect expressions 187scalar functions
DECIMAL function 327description 168, 291
scaleof data
comparisons in SQL 117determined by SQLLEN
variable 621in arithmetic operations 187number conversion in
SQL 117of numbers
determined by SQLLENvariable 621
schema namesdefinition 65
schemascontrolling use 4definition 4
Index 939
schemas (continued)privileges 4reserved 823
scopedefining in CAST
specification 187definition 108dereference operation 187
SCOPE clausein CAST specification 187
scoped-ref-expressiondereference operation 187
search conditionsAND logical operator 226description 226HAVING clause
arguments and rules 554NOT logical operator 226OR logical operator 226order of evaluation 226WHERE clause 554
SECOND functionbasic description 261description 448values and arguments 448
sectionsdefinition 20
SELECT clauselist notation, column
reference 554with DISTINCT keyword 554
select listapplication rules and syntax 554description 554notation rules and
conventions 554SELECT statement
definition 601examples 601fullselect detailed syntax 595subselects 554VALUES clause 595
self-referencing row 8self-referencing table 8sequences
invoking 187nextval-expression 187prevval-expression 187values, ordering 367
server optionsCOLLATING_SEQUENCE 764COMM_RATE 764CONNECTSTRING 764CPU_RATIO 764DBNAME 764
server options (continued)description 50FOLD_ID 764FOLD_PW 764IFILE 764IGNORE_UDT 764IO_RATIO 764IUD_APP_SVPT_
ENFORCE 764LOGIN_TIMEOUT 764NODE 764PACKET_SIZE 764PASSWORD 764PLAN_HINTS 764PUSHDOWN 764temporary 50TIMEOUT 764VARCHAR_NO_TRAILING_
BLANKS 764server types, valid data source
types 759server-name 65servers
applicationconnecting applications to 29
description 50set operators
EXCEPT, comparingdifferences 595
INTERSECT, role of AND incomparisons 595
result data type 134UNION, correspondence to
OR 595SET SERVER OPTION statement
setting an option temporarily 50share locks 13shift-in characters, not truncated by
assignments 117SIGN function
basic description 262SIGN scalar function
description 449values and arguments 449
signaturesfunction 168method 178
SIN functionbasic description 262
SIN scalar functiondescription 450values and arguments 450
single-precision floating-point datatype 94
SINH functionbasic description 262
SINH scalar functiondescription 451values and arguments 451
size limitsidentifier length 607SQL 607
small integer values fromexpressions, SMALLINTfunction 452
small integersSee SMALLINT data type 94
SMALLINT data typedescription 94
SMALLINT functionbasic description 262description 452values and arguments 452
SNAPSHOT_AGENT function 505SNAPSHOT_APPL function 506SNAPSHOT_APPL_INFO
function 510SNAPSHOT_BP function 512SNAPSHOT_CONTAINER
function 514SNAPSHOT_DATABASE
function 516SNAPSHOT_DBM function 521SNAPSHOT_DYN_SQL
function 523SNAPSHOT_FCM function 525SNAPSHOT_FCMPARTITION
function 526SNAPSHOT_LOCK function 527SNAPSHOT_LOCKWAIT
function 529SNAPSHOT_QUIESCERS
function 531SNAPSHOT_RANGES function 532SNAPSHOT_STATEMENT
function 533SNAPSHOT_SUBSECT
function 535SNAPSHOT_SWITCHES
function 537SNAPSHOT_TABLE function 538SNAPSHOT_TBS function 540SNAPSHOT_TBS_CFG function 542SOME quantified predicate 230sorting
ordering of results 117string comparisons 117
SOUNDEX functionbasic description 262
940 SQL Reference, Volume 1
SOUNDEX function (continued)description 453values and arguments 453
sourced functions 168SPACE function
basic description 262SPACE scalar function
description 454values and arguments 454
space, rules governing 63special registers
CLIENT ACCTNG 148CLIENT APPLNAME 149CLIENT USERID 150CLIENT WRKSTNNAME 151CURRENT DATE 152CURRENT
DBPARTITIONNUM 153CURRENT DEFAULT
TRANSFORM GROUP 154CURRENT DEGREE 155CURRENT EXPLAIN
MODE 156CURRENT EXPLAIN
SNAPSHOT 157CURRENT FUNCTION
PATH 159CURRENT MAINTAINED
TABLE TYPES FOROPTIMIZATION 158
CURRENT NODE (seeCURRENTDBPARTITIONNUM) 153
CURRENT PATH 159CURRENT QUERY
OPTIMIZATION 160CURRENT REFRESH AGE 161CURRENT SCHEMA 162CURRENT SERVER 163CURRENT SQLID 162CURRENT TIME 164CURRENT TIMESTAMP 165CURRENT TIMEZONE 166interaction, Explain 857SQL language element 146updatable 146USER 167
specific namedefinition 65
specificationsCAST 187
SQL (Structured Query Language)limits 607path 168
SQL dialectdescription 45
SQL functions 168SQL operations
basic 117SQL Server
default wrapper names 48valid objects for nicknames 52
SQL statementsallowed in routines 873CALL 877dynamic SQL, definition 1immediate execution of dynamic
SQL 1interactive SQL, definition 1preparing and executing dynamic
SQL 1static SQL, definition 1
SQL subquery, WHERE clause 554SQL syntax
AVG aggregate function, resultson column set 270
basic predicate, detaileddiagram 229
comparing two predicates, truthconditions 229, 244
CORRELATION aggregatefunction results 272
COUNT_BIG function, argumentsand results 275
COVARIANCE aggregatefunction results 277
EXISTS predicate 234GENERATE_UNIQUE
function 367GROUP BY clause, use in
subselect 554IN predicate description 235LIKE predicate, rules 238multiple operations, order of
execution 595regression functions results 284search conditions, detailed
formats and rules 226SELECT clause description 554SQLCACHE_SNAPSHOT
function, results on set numberpairs 544
STDDEV aggregate function,results 288
TYPE predicate 244VARIANCE aggregate function
results 290WHERE clause search
conditions 554
SQL SyntaxBETWEEN predicate, rules 233
SQL variable name 65SQLCA (SQL communication area)
description 615error reporting 615partitioned database
systems 615viewing interactively 615
SQLCACHE_SNAPSHOTfunction 544
basic description 262SQLD field in SQLDA 621SQLDA (SQL descriptor area)
contents 621SQLDABC field in SQLDA 621SQLDAID field in SQLDA 621SQLDATA field in SQLDA 621SQLDATALEN field in SQLDA 621SQLDATATYPE_NAME field in
SQLDA 621SQLIND field in SQLDA 621SQLJ (embedded SQL for Java)
connectivity 19SQLLEN field in SQLDA 621SQLLONGLEN field in SQLDA 621SQLN field in SQLDA 621SQLNAME field in SQLDA 621SQLSTATE
in RAISE_ERROR function 432SQLTYPE field in SQLDA 621SQLVAR field in SQLDA 621SQRT function
basic description 262SQRT scalar function
description 455STAFF sample table 803STAFFG sample table 803statements
names 65states
connection 29static SQL
description 1STDDEV function 288
basic description 262storage
structures 26stored procedures
CALL statement 877strings
assignment conversion rules 117definition 20expressions 187operands 187
Index 941
Structured Query Language (SQL)assignments 117basic operands, assignments and
comparisons 117comparison operation,
overview 117structured types
description 108host variables 65method invocation 187subtype treatment 187
sub-total rows 554subqueries
HAVING clause 554using fullselect as search
condition 65WHERE clause 554
subselectdescription 554example sequence of
operations 554examples 554FROM clause, relation to
subselect 554SUBSTR function
basic description 262SUBSTR scalar function
description 456values and arguments 456
substrings 456subtypes
treatment in expressions 187SUM function
basic description 262SUM functions
detailed format description 289values and arguments 289
summary tablesdefinition 5
super-aggregate rows 554super-groups 554supertype
identifier names 65Sybase
data sources 52default forward type
mappings 775, 791default wrapper names 48
symmetric super-aggregaterows 554
synonymsqualifying a column name 65
syntaxcommon elements xvdescription xiii
syntax (continued)function designator xvmethod designator xvprocedure designator xv
SYSADM authorityDB2 2
SYSCTRL authority 2SYSMAINT authority 2system administration (SYSADM)
authorityoverview 2
system catalogsviews on system tables 636
system control authority(SYSCTRL) 2
system maintenance authority(SYSMAINT) 2
TTABLE clause
table reference 554table expressions
common 16common table expressions 601description 16
table functionsdescription 168, 494
table referencealias 554nested table expressions 554nickname 554table name 554view name 554
table spacesdescription 26name 65
TABLE_NAME functionalias 460basic description 263description 460values and arguments 460
TABLE_SCHEMA functionalias 461basic description 263description 461values and arguments 461
table-structured filesvalid objects for nicknames 52
tablesbase 5catalog views on system
tables 636check constraints
types 8collocation 28
tables (continued)correlation name 65declared temporary
description 5definition 5dependent 8descendent 8designator to avoid
ambiguity 65exception 867exposed names in FROM
clause 65foreign key 7FROM clause, subselect naming
conventions 554names
description 65in FROM clause 554in SELECT clause, syntax
diagram 554nested table expression 65non-exposed names in FROM
clause 65parent 8partitioning key 7primary key
description 7qualified column name 65results 5SAMPLE database 803scalar fullselect 65self-referencing 8subquery 65summary 5tablereference 554transition 24typed 5unique correlation names 65
TAN functionbasic description 263
TAN scalar functiondescription 463values and arguments 463
TANH functionbasic description 263
TANH scalar functiondescription 464values and arguments 464
timearithmetic operations, rules 187CHAR, use in format
conversion 303duration format 187hour values, using in an
expression (HOUR) 375
942 SQL Reference, Volume 1
time (continued)in expressions, TIME
function 465returning
microseconds, from datetimevalue 401
minutes, from datetimevalue 403
seconds, from datetimevalue 448
timestamp from values 466values based on time 465
string representationformats 101
using time in expressions 465TIME data type
description 101TIME function
basic description 263description 465values and arguments 465
TIMEOUTvalid settings 764
TIMESTAMP data typedescription 101WEEK scalar function 491WEEK_ISO scalar function 492
TIMESTAMP functionbasic description 263description 466values and arguments 466
TIMESTAMP_FORMAT functionbasic description 263description 468values and arguments 468
TIMESTAMP_ISO functionbasic description 263description 470values and arguments 470
TIMESTAMPDIFF functionbasic description 264
TIMESTAMPDIFF scalar functiondescription 471values and arguments 471
timestampsarithmetic operations 187data type 187duration 187from GENERATE_UNIQUE 367string representation
formats 101TO_CHAR function
basic description 264description 473values and arguments 473
TO_DATE functionbasic description 264description 474values and arguments 474
tokenscase sensitivity 63delimiter 63ordinary 63SQL language element 63
TRANSLATE functionbasic description 264
TRANSLATE scalar functioncharacter string 475description 475graphic string 475values and arguments 475
treatment subtype 187triggers
cascading 24constraints, interaction 829description 24Explain tables 833interactions 829names 65
troubleshootingDB2 documentation search 912online information 914
TRUNC or TRUNCATE functionbasic description 264
TRUNCATE or TRUNC scalarfunction
description 478values and arguments 478
truncationnumbers 117
truth tables 226truth valued logic 226tutorials 916type mapping
name 65type name 65TYPE predicate
format 244type preserving method 178TYPE_ID function
basic description 265data types 480description 480values and arguments 480
TYPE_NAME functionbasic description 265description 481values and arguments 481
TYPE_SCHEMA functionbasic description 265
TYPE_SCHEMA function (continued)data types 482description 482values and arguments 482
typed tablesdescription 5names 65
typed viewsdescription 6names 65
typesdistinct 108reference 108structured 108
UUCASE function
basic description 265UCASE
function(SYSFUN.UCASE) 265UCASE scalar function
description 483values and arguments 483
UDFs (user-defined functions)description 550
UDTs (user-defined types)unsupported 54
unaryminus sign 187plus sign 187
uncommitted reads (UR)comparision table 827isolation levels 13
unconnected state 29undefined reference errors 65Unicode (UCS-2)
functions in 291UNION operator, role in comparison
of fullselect 595unique constraint
definition 8unique correlation names
table designators 65unique keys
description 7, 8units of work (UOW)
definition 16distributed 29remote 29
unknown condition, null value 226updatable special registers 146update lock 13update rule, with referential
constraints 8
Index 943
UPPER functiondescription 483values and arguments 483
UR (uncommitted read) isolationlevel 13, 827
user mappingdescription 51
user optionsACCOUNTING_STRING 773description 51REMOTE_AUTHID 773REMOTE_DOMAIN 773REMOTE_PASSWORD 773
USER special register 167user-defined functions (UDFs)
description 168, 247, 550user-defined methods
description 178user-defined types (UDTs)
casting 113description 108distinct types
description 108reference type 108structured types 108unsupported data types 54
Vvalue
definition 5, 92null 92
VALUE functionbasic description 265description 484values and arguments 484
VALUES clausefullselect 595
VARCHAR data typedescription 95DOUBLE scalar function 357WEEK scalar function 491WEEK_ISO scalar function 492
VARCHAR functionbasic description 265description 485values and arguments 485
VARCHAR_FORMAT functionbasic description 265description 487values and arguments 487
VARCHAR_NO_TRAILING_BLANKS
column optionvalid settings 762
VARCHAR_NO_TRAILING_BLANKS (continued)
server optionvalid settings 764
VARGRAPHIC data typedescription 97
VARGRAPHIC functionbasic description 265description 489values and arguments 489
variablestransition 24
VARIANCE aggregate function 290VARIANCE or VAR function
basic description 265varying-length character string 95varying-length graphic string 97view name
definition 65VIEWDEP catalog view
see catalog views, TABDEP 729views
description 6exposed names in FROM
clause 65FROM clause, subselect naming
conventions 554names in FROM clause 554names in SELECT clause, syntax
diagram 554non-exposed names in FROM
clause 65qualifying a column name 65
WWEEK function
basic description 265WEEK scalar function
description 491values and arguments 491
WEEK_ISO functionbasic description 266
WEEK_ISO scalar functiondescription 492values and arguments 492
WHERE clausesearch function, subselect 554
wild cards, in LIKE predicate 238WITH common table
expression 601words, SQL reserved 823wrappers
default names 48description 48names 65
wrappers (continued)options
DB2_FENCED 774
XXML
data types 107functions
XML2CLOB 187XMLAGG 187XMLATTRIBUTES 187XMLELEMENT 187
nicknames, valid objects for 52XML2CLOB
XML function 187XMLAGG
XML function 187XMLATTRIBUTES
XML function 187XMLELEMENT
XML function 187
YYEAR function
basic description 266YEAR scalar function
description 493values and arguments 493
944 SQL Reference, Volume 1
Contacting IBM
In the United States, call one of the following numbers to contact IBM:v 1-800-237-5511 for customer servicev 1-888-426-4343 to learn about available service optionsv 1-800-IBM-4YOU (426-4968) for DB2 marketing and sales
In Canada, call one of the following numbers to contact IBM:v 1-800-IBM-SERV (1-800-426-7378) for customer servicev 1-800-465-9600 to learn about available service optionsv 1-800-IBM-4YOU (1-800-426-4968) for DB2 marketing and sales
To locate an IBM office in your country or region, check IBM’s Directory ofWorldwide Contacts on the web at www.ibm.com/planetwide
Product information
Information regarding DB2 Universal Database products is available bytelephone or by the World Wide Web atwww.ibm.com/software/data/db2/udb
This site contains the latest information on the technical library, orderingbooks, client downloads, newsgroups, FixPaks, news, and links to webresources.
If you live in the U.S.A., then you can call one of the following numbers:v 1-800-IBM-CALL (1-800-426-2255) to order products or to obtain general
information.v 1-800-879-2755 to order publications.
For information on how to contact IBM outside of the United States, go to theIBM Worldwide page at www.ibm.com/planetwide
© Copyright IBM Corp. 1993 - 2002 945
����
Part Number: CT17RNA
Printed in U.S.A.
SC09-4844-00
(1P)
P/N:
CT17RNA
Spin
ein
form
atio
n:
��
�IB
M®
DB
2U
nive
rsal
Dat
abas
e™
SQL
Ref
eren
ce,V
olum
e1
Vers
ion
8