ibm db2 - sql reference v7.pdf

1597
IB M ® DB2 ® Universal Database SQL Reference V ersion 7 SC09-2974-01

Upload: cmatoshot

Post on 29-Oct-2015

92 views

Category:

Documents


0 download

TRANSCRIPT

  • IBM

    DB2

    Universal Database

    SQL Reference

    Version 7

    SC09-2974-01

  • IBM

    DB2

    Universal Database

    SQL Reference

    Version 7

    SC09-2974-01

  • Before using this information and the product it supports, be sure to read the general information underAppendix S. Notices on page 1541.

    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.

    Order publications through your IBM representative or the IBM branch office serving your locality or by calling1-800-879-2755 in the United States or 1-800-IBM-4YOU in Canada.

    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, 2001. All rights reserved.US Government Users Restricted Rights Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.

  • ContentsChapter 1. Introduction . . . . . . . . 1Who Should Use This Book . . . . . . . 1How To Use This Book. . . . . . . . . 1

    How This Book is Structured. . . . . . 1How to Read the Syntax Diagrams . . . . . 3Conventions Used in This Manual . . . . . 5

    Error Conditions . . . . . . . . . . 5Highlighting Conventions . . . . . . . 5

    Related Documentation for This Book . . . . 6

    Chapter 2. Concepts . . . . . . . . . 9Relational Database Definitions . . . . . . 9Structured Query Language (SQL) . . . . . 9Authorization and Privileges . . . . . . 10Schemas . . . . . . . . . . . . . 12

    Controlling the Use of Schemas . . . . 12Tables . . . . . . . . . . . . . . 13Views . . . . . . . . . . . . . . 14Aliases . . . . . . . . . . . . . . 14Indexes . . . . . . . . . . . . . 15Keys . . . . . . . . . . . . . . 15

    Unique Keys . . . . . . . . . . . 16Primary Keys . . . . . . . . . . 16Foreign Keys . . . . . . . . . . . 16Partitioning Keys . . . . . . . . . 16

    Constraints . . . . . . . . . . . . 16Unique Constraints . . . . . . . . 17Referential Constraints . . . . . . . 17Table Check Constraints . . . . . . . 21

    Isolation Level . . . . . . . . . . . 21Repeatable Read (RR) . . . . . . . . 22Read Stability (RS) . . . . . . . . . 23Cursor Stability (CS) . . . . . . . . 23Uncommitted Read (UR) . . . . . . . 24Comparison of Isolation Levels . . . . 24

    Queries . . . . . . . . . . . . . 24Table Expressions . . . . . . . . . . 24

    Common Table Expressions . . . . . . 24Application Processes, Concurrency, andRecovery . . . . . . . . . . . . . 25Interactive SQL . . . . . . . . . . . 27Embedded SQL . . . . . . . . . . . 28

    Static SQL. . . . . . . . . . . . 28Dynamic SQL . . . . . . . . . . 28

    DB2 Call Level Interface (CLI) and OpenDatabase Connectivity (ODBC). . . . . . 28Java Database Connectivity (JDBC) andEmbedded SQL for Java (SQLJ) Programs . . 29Packages . . . . . . . . . . . . . 30Catalog Views . . . . . . . . . . . 30Character Conversion . . . . . . . . . 30

    Character Sets and Code Pages. . . . . 31Code Page Attributes . . . . . . . . 32

    Event Monitors . . . . . . . . . . . 33Triggers . . . . . . . . . . . . . 34Table Spaces and Other Storage Structures . . 35Data Partitioning Across Multiple Partitions 37

    Partitioning Maps . . . . . . . . . 38Table Collocation . . . . . . . . . 38

    Distributed Relational Database . . . . . 39Application Servers . . . . . . . . 40CONNECT (Type 1) and CONNECT (Type2) . . . . . . . . . . . . . . 40Remote Unit of Work . . . . . . . . 41Application-Directed Distributed Unit ofWork . . . . . . . . . . . . . 44Data Representation Considerations . . . 50

    DB2 Federated Systems . . . . . . . . 50The Federated Server, Federated Database,and Data Sources . . . . . . . . . 50Tasks Performed in a DB2 FederatedSystem . . . . . . . . . . . . . 51Wrappers and Wrapper Modules . . . . 53Server Definitions and Server Options . . 53User Mappings and User Options . . . . 55Data Type Mappings . . . . . . . . 56Function Mappings, Function Templates,and Function Mapping Options . . . . 57Nicknames and Column Options . . . . 57Index Specifications . . . . . . . . 58Distributed Requests . . . . . . . . 59Compensation . . . . . . . . . . 60Pass-Through . . . . . . . . . . 60

    Chapter 3. Language Elements . . . . . 63Characters . . . . . . . . . . . . 63

    MBCS Considerations . . . . . . . . 64Tokens . . . . . . . . . . . . . . 64

    MBCS Considerations . . . . . . . . 65

    Copyright IBM Corp. 1993, 2001 iii

    |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

    |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

  • Identifiers . . . . . . . . . . . . . 65SQL Identifiers . . . . . . . . . . 65Host Identifiers . . . . . . . . . . 66

    Naming Conventions and Implicit ObjectName Qualifications . . . . . . . . . 66Aliases . . . . . . . . . . . . . . 71Authorization IDs and authorization-names 72

    Dynamic SQL Characteristics at run-time 73Authorization IDs and StatementPreparation . . . . . . . . . . . 75

    Data Types . . . . . . . . . . . . 75Nulls . . . . . . . . . . . . . 76Large Objects (LOBs) . . . . . . . . 76Character Strings . . . . . . . . . 78Graphic Strings . . . . . . . . . . 80Binary String. . . . . . . . . . . 81Numbers . . . . . . . . . . . . 81Datetime Values. . . . . . . . . . 82DATALINK Values . . . . . . . . . 85User Defined Types . . . . . . . . 87

    Promotion of Data Types. . . . . . . . 90Casting Between Data Types . . . . . . 91Assignments and Comparisons. . . . . . 94

    Numeric Assignments. . . . . . . . 95String Assignments . . . . . . . . 96Datetime Assignments . . . . . . . 99DATALINK Assignments. . . . . . . 99User-defined Type Assignments . . . . 101Reference Type Assignments . . . . . 102Numeric Comparisons . . . . . . . 102String Comparisons . . . . . . . . 102Datetime Comparisons . . . . . . . 106User-defined Type Comparisons . . . . 106Reference Type Comparisons . . . . . 107

    Rules for Result Data Types . . . . . . 107Character Strings . . . . . . . . . 108Graphic Strings . . . . . . . . . 109Binary Large Object (BLOB) . . . . . 109Numeric . . . . . . . . . . . . 109DATE . . . . . . . . . . . . . 110TIME . . . . . . . . . . . . . 110TIMESTAMP . . . . . . . . . . 110DATALINK . . . . . . . . . . . 110User-defined Types . . . . . . . . 110Nullable Attribute of Result . . . . . 111

    Rules for String Conversions . . . . . . 111Partition Compatibility . . . . . . . . 114Constants . . . . . . . . . . . . 115

    Integer Constants . . . . . . . . . 115Floating-Point Constants . . . . . . 116

    Decimal Constants . . . . . . . . 116Character String Constants . . . . . . 116Hexadecimal Constants . . . . . . . 117Graphic String Constants . . . . . . 117Using Constants with User-defined Types 117

    Special Registers . . . . . . . . . . 118CLIENT ACCTNG . . . . . . . . 118CLIENT APPLNAME . . . . . . . 118CLIENT USERID . . . . . . . . . 119CLIENT WRKSTNNAME . . . . . . 119CURRENT DATE . . . . . . . . . 120CURRENT DEFAULT TRANSFORMGROUP . . . . . . . . . . . . 120CURRENT DEGREE . . . . . . . . 121CURRENT EXPLAIN MODE . . . . . 122CURRENT EXPLAIN SNAPSHOT . . . 123CURRENT NODE . . . . . . . . 124CURRENT PATH . . . . . . . . . 124CURRENT QUERY OPTIMIZATION . . 125CURRENT REFRESH AGE. . . . . . 125CURRENT SCHEMA . . . . . . . 126CURRENT SERVER . . . . . . . . 126CURRENT TIME . . . . . . . . . 127CURRENT TIMESTAMP . . . . . . 127CURRENT TIMEZONE . . . . . . . 127USER . . . . . . . . . . . . . 128

    Column Names . . . . . . . . . . 128Qualified Column Names . . . . . . 129Correlation Names . . . . . . . . 129Column Name Qualifiers to AvoidAmbiguity . . . . . . . . . . . 132Column Name Qualifiers in CorrelatedReferences . . . . . . . . . . . 133

    References to Host Variables . . . . . . 135Host Variables in Dynamic SQL . . . . 136References to BLOB, CLOB, and DBCLOBHost Variables . . . . . . . . . . 138References to Locator Variables . . . . 139References to BLOB, CLOB, and DBCLOBFile Reference Variables . . . . . . . 139References to Structured Type HostVariables . . . . . . . . . . . . 142

    Functions . . . . . . . . . . . . 143External, SQL and Sourced User-DefinedFunctions . . . . . . . . . . . 144Scalar, Column, Row and TableUser-Defined Functions . . . . . . . 144Function Signatures . . . . . . . . 145SQL Path . . . . . . . . . . . 145Function Resolution . . . . . . . . 145

    iv SQL Reference

    ||||||||

  • Function Invocation . . . . . . . . 150Methods . . . . . . . . . . . . . 150

    External and SQL User-Defined Methods 151Method Signatures . . . . . . . . 152Method Invocation . . . . . . . . 152Method Resolution . . . . . . . . 152Method of Choosing the Best Fit . . . . 154Example of Method Resolution . . . . 155Method Invocation . . . . . . . . 156

    Conservative Binding Semantics . . . . . 157Expressions . . . . . . . . . . . . 159

    Without Operators . . . . . . . . 160With the Concatenation Operator . . . 160With Arithmetic Operators . . . . . . 163Two Integer Operands . . . . . . . 164Integer and Decimal Operands . . . . 164Two Decimal Operands . . . . . . . 165Decimal Arithmetic in SQL . . . . . 165Floating-Point Operands . . . . . . 165User-defined Types as Operands . . . . 166Scalar Fullselect . . . . . . . . . 166Datetime Operations and Durations. . . 166Datetime Arithmetic in SQL . . . . . 168Precedence of Operations . . . . . . 172CASE Expressions . . . . . . . . 173CAST Specifications . . . . . . . . 175Dereference Operations . . . . . . . 178OLAP Functions . . . . . . . . . 179Method Invocation . . . . . . . . 186Subtype Treatment . . . . . . . . 187Sequence Reference . . . . . . . . 188

    Predicates . . . . . . . . . . . . 193Basic Predicate . . . . . . . . . . 194Quantified Predicate . . . . . . . . 195BETWEEN Predicate . . . . . . . . 198EXISTS Predicate . . . . . . . . . 200IN Predicate . . . . . . . . . . 201LIKE Predicate . . . . . . . . . . 204NULL Predicate . . . . . . . . . 209TYPE Predicate . . . . . . . . . 210

    Search Conditions. . . . . . . . . . 212Examples . . . . . . . . . . . 214

    Chapter 4. Functions . . . . . . . . 215Column Functions . . . . . . . . . 235

    AVG . . . . . . . . . . . . . 236CORRELATION . . . . . . . . . 238COUNT . . . . . . . . . . . . 239COUNT_BIG . . . . . . . . . . 241COVARIANCE. . . . . . . . . . 243

    GROUPING . . . . . . . . . . 244MAX . . . . . . . . . . . . . 246MIN . . . . . . . . . . . . . 248REGRESSION Functions . . . . . . 250STDDEV . . . . . . . . . . . . 254SUM . . . . . . . . . . . . . 255VARIANCE . . . . . . . . . . . 256

    Scalar Functions . . . . . . . . . . 257ABS or ABSVAL . . . . . . . . . 258ACOS. . . . . . . . . . . . . 259ASCII . . . . . . . . . . . . . 260ASIN . . . . . . . . . . . . . 261ATAN. . . . . . . . . . . . . 262ATAN2 . . . . . . . . . . . . 263BIGINT . . . . . . . . . . . . 264BLOB . . . . . . . . . . . . . 265CEILING or CEIL . . . . . . . . . 266CHAR . . . . . . . . . . . . 267CHR . . . . . . . . . . . . . 273CLOB . . . . . . . . . . . . . 274COALESCE . . . . . . . . . . . 275CONCAT . . . . . . . . . . . 276COS . . . . . . . . . . . . . 277COT . . . . . . . . . . . . . 278DATE . . . . . . . . . . . . . 279DAY . . . . . . . . . . . . . 281DAYNAME . . . . . . . . . . . 282DAYOFWEEK . . . . . . . . . . 283DAYOFWEEK_ISO . . . . . . . . 284DAYOFYEAR . . . . . . . . . . 285DAYS . . . . . . . . . . . . . 286DBCLOB. . . . . . . . . . . . 287DECIMAL . . . . . . . . . . . 288DECRYPT_BIN and DECRYPT_CHAR 291DEGREES . . . . . . . . . . . 293DEREF . . . . . . . . . . . . 294DIFFERENCE . . . . . . . . . . 295DIGITS . . . . . . . . . . . . 296DLCOMMENT. . . . . . . . . . 297DLLINKTYPE . . . . . . . . . . 298DLURLCOMPLETE . . . . . . . . 299DLURLPATH . . . . . . . . . . 300DLURLPATHONLY . . . . . . . . 301DLURLSCHEME . . . . . . . . . 302DLURLSERVER . . . . . . . . . 303DLVALUE . . . . . . . . . . . 304DOUBLE. . . . . . . . . . . . 306ENCRYPT . . . . . . . . . . . 308EVENT_MON_STATE . . . . . . . 311EXP . . . . . . . . . . . . . 312

    Contents v

    ||

    ||

    ||

    ||

  • FLOAT . . . . . . . . . . . . 313FLOOR . . . . . . . . . . . . 314GETHINT . . . . . . . . . . . 315GENERATE_UNIQUE . . . . . . . 316GRAPHIC . . . . . . . . . . . 318HEX . . . . . . . . . . . . . 319HOUR . . . . . . . . . . . . 321IDENTITY_VAL_LOCAL . . . . . . 322INSERT . . . . . . . . . . . . 328INTEGER . . . . . . . . . . . 330JULIAN_DAY . . . . . . . . . . 331LCASE or LOWER . . . . . . . . 332LCASE (SYSFUN schema) . . . . . . 333LEFT . . . . . . . . . . . . . 334LENGTH . . . . . . . . . . . 335LN. . . . . . . . . . . . . . 337LOCATE . . . . . . . . . . . . 338LOG . . . . . . . . . . . . . 339LOG10 . . . . . . . . . . . . 340LONG_VARCHAR . . . . . . . . 341LONG_VARGRAPHIC . . . . . . . 342LTRIM . . . . . . . . . . . . 343LTRIM (SYSFUN schema) . . . . . . 344MICROSECOND . . . . . . . . . 345MIDNIGHT_SECONDS . . . . . . . 346MINUTE. . . . . . . . . . . . 347MOD . . . . . . . . . . . . . 348MONTH . . . . . . . . . . . . 349MONTHNAME . . . . . . . . . 350MQPUBLISH . . . . . . . . . . 351MQREAD . . . . . . . . . . . 353MQRECEIVE . . . . . . . . . . 355MQSEND . . . . . . . . . . . 357MQSUBSCRIBE . . . . . . . . . 359MQUNSUBSCRIBE . . . . . . . . 361MULTIPLY_ALT . . . . . . . . . 363NODENUMBER . . . . . . . . . 365NULLIF . . . . . . . . . . . . 367PARTITION. . . . . . . . . . . 368POSSTR . . . . . . . . . . . . 370POWER . . . . . . . . . . . . 372QUARTER . . . . . . . . . . . 373RADIANS . . . . . . . . . . . 374RAISE_ERROR. . . . . . . . . . 375RAND . . . . . . . . . . . . 377REAL . . . . . . . . . . . . . 378REC2XML . . . . . . . . . . . 379REPEAT . . . . . . . . . . . . 384REPLACE . . . . . . . . . . . 385RIGHT . . . . . . . . . . . . 386

    ROUND . . . . . . . . . . . . 387RTRIM . . . . . . . . . . . . 389RTRIM (SYSFUN schema) . . . . . . 390SECOND . . . . . . . . . . . 391SIGN . . . . . . . . . . . . . 392SIN . . . . . . . . . . . . . 393SMALLINT . . . . . . . . . . . 394SOUNDEX . . . . . . . . . . . 395SPACE . . . . . . . . . . . . 396SQRT . . . . . . . . . . . . . 397SUBSTR . . . . . . . . . . . . 398TABLE_NAME. . . . . . . . . . 402TABLE_SCHEMA . . . . . . . . . 404TAN . . . . . . . . . . . . . 406TIME . . . . . . . . . . . . . 407TIMESTAMP . . . . . . . . . . 408TIMESTAMP_ISO . . . . . . . . . 410TIMESTAMPDIFF . . . . . . . . . 411TRANSLATE . . . . . . . . . . 413TRUNCATE or TRUNC . . . . . . . 416TYPE_ID. . . . . . . . . . . . 417TYPE_NAME . . . . . . . . . . 418TYPE_SCHEMA . . . . . . . . . 419UCASE or UPPER . . . . . . . . 420VALUE . . . . . . . . . . . . 421VARCHAR . . . . . . . . . . . 422VARGRAPHIC. . . . . . . . . . 424WEEK . . . . . . . . . . . . 426WEEK_ISO . . . . . . . . . . . 427YEAR . . . . . . . . . . . . . 428

    Table Functions . . . . . . . . . . 429MQREADALL . . . . . . . . . . 430MQRECEIVEALL . . . . . . . . . 432SQLCACHE_SNAPSHOT . . . . . . 435

    Procedures . . . . . . . . . . . . 436GET_ROUTINE_SAR . . . . . . . 437PUT_ROUTINE_SAR . . . . . . . 438

    User-Defined Functions . . . . . . . . 440

    Chapter 5. Queries . . . . . . . . . 443subselect . . . . . . . . . . . . . 444

    select-clause. . . . . . . . . . . 445from-clause . . . . . . . . . . . 450table-reference . . . . . . . . . . 451joined-table . . . . . . . . . . . 455where-clause . . . . . . . . . . 458group-by-clause . . . . . . . . . 459having-clause . . . . . . . . . . 466

    Examples of subselects . . . . . . . . 468Examples of Joins . . . . . . . . . . 471

    vi SQL Reference

    ||

    ||

    ||||||||||||||

    ||

    ||

    ||||

    ||||

  • Examples of Grouping Sets, Cube, andRollup . . . . . . . . . . . . . 475fullselect . . . . . . . . . . . . . 484

    Examples of a fullselect . . . . . . . 487select-statement . . . . . . . . . . 489

    common-table-expression . . . . . . 490order-by-clause . . . . . . . . . 493update-clause . . . . . . . . . . 496read-only-clause . . . . . . . . . 497fetch-first-clause . . . . . . . . . 498optimize-for-clause . . . . . . . . 499Examples of a select-statement . . . . 500

    Chapter 6. SQL Statements . . . . . . 503How SQL Statements Are Invoked . . . . 507

    Embedding a Statement in an ApplicationProgram . . . . . . . . . . . . 508Dynamic Preparation and Execution . . 509Static Invocation of a select-statement . . 509Dynamic Invocation of a select-statement 510Interactive Invocation . . . . . . . 510SQL Use With Other Host Systems . . . 510

    SQL Return Codes . . . . . . . . . 511SQLCODE . . . . . . . . . . . 511SQLSTATE . . . . . . . . . . . 511

    SQL Comments . . . . . . . . . . 513ALTER BUFFERPOOL . . . . . . . . 514ALTER NICKNAME . . . . . . . . . 516ALTER NODEGROUP . . . . . . . . 520ALTER SEQUENCE . . . . . . . . . 524ALTER SERVER . . . . . . . . . . 528ALTER TABLE . . . . . . . . . . . 532ALTER TABLESPACE . . . . . . . . 562ALTER TYPE (Structured) . . . . . . . 568ALTER USER MAPPING . . . . . . . 575ALTER VIEW . . . . . . . . . . . 577BEGIN DECLARE SECTION . . . . . . 579CALL . . . . . . . . . . . . . . 581CLOSE . . . . . . . . . . . . . 589COMMENT. . . . . . . . . . . . 591COMMIT . . . . . . . . . . . . 602Compound SQL (Dynamic) . . . . . . 604Compound SQL (Embedded) . . . . . . 609CONNECT (Type 1) . . . . . . . . . 614CONNECT (Type 2) . . . . . . . . . 622CREATE ALIAS . . . . . . . . . . 630CREATE BUFFERPOOL. . . . . . . . 633CREATE DISTINCT TYPE . . . . . . . 636CREATE EVENT MONITOR . . . . . . 643CREATE FUNCTION . . . . . . . . 653

    CREATE FUNCTION (External Scalar) . . . 654CREATE FUNCTION (External Table) . . . 679CREATE FUNCTION (OLE DB ExternalTable) . . . . . . . . . . . . . . 695CREATE FUNCTION (Sourced or Template) 703CREATE FUNCTION (SQL Scalar, Table orRow) . . . . . . . . . . . . . . 713CREATE FUNCTION MAPPING . . . . 720CREATE INDEX . . . . . . . . . . 725CREATE INDEX EXTENSION . . . . . 732CREATE METHOD . . . . . . . . . 739CREATE NICKNAME . . . . . . . . 744CREATE NODEGROUP. . . . . . . . 750CREATE PROCEDURE . . . . . . . . 753CREATE SCHEMA . . . . . . . . . 769CREATE SEQUENCE . . . . . . . . 773CREATE SERVER . . . . . . . . . . 778CREATE TABLE . . . . . . . . . . 782CREATE TABLESPACE . . . . . . . . 834CREATE TRANSFORM . . . . . . . . 844CREATE TRIGGER . . . . . . . . . 850CREATE TYPE (Structured) . . . . . . 862CREATE TYPE MAPPING . . . . . . . 886CREATE USER MAPPING . . . . . . . 891CREATE VIEW . . . . . . . . . . 893CREATE WRAPPER . . . . . . . . . 909DECLARE CURSOR . . . . . . . . . 911DECLARE GLOBAL TEMPORARY TABLE 916DELETE . . . . . . . . . . . . . 925DESCRIBE . . . . . . . . . . . . 931DISCONNECT . . . . . . . . . . . 936DROP. . . . . . . . . . . . . . 939END DECLARE SECTION . . . . . . . 966EXECUTE . . . . . . . . . . . . 967EXECUTE IMMEDIATE. . . . . . . . 972EXPLAIN . . . . . . . . . . . . 975FETCH . . . . . . . . . . . . . 980FLUSH EVENT MONITOR . . . . . . 983FREE LOCATOR . . . . . . . . . . 984GRANT (Database Authorities) . . . . . 985GRANT (Index Privileges) . . . . . . . 988GRANT (Package Privileges) . . . . . . 990GRANT (Schema Privileges) . . . . . . 993GRANT (Sequence Privileges). . . . . . 996GRANT (Server Privileges). . . . . . . 997GRANT (Table, View, or NicknamePrivileges) . . . . . . . . . . . . 999GRANT (Table Space Privileges) . . . . 1007INCLUDE . . . . . . . . . . . . 1009INSERT . . . . . . . . . . . . . 1011

    Contents vii

    ||

    ||||

    ||

    ||

  • LOCK TABLE. . . . . . . . . . . 1020OPEN . . . . . . . . . . . . . 1022PREPARE . . . . . . . . . . . . 1027REFRESH TABLE . . . . . . . . . 1037RELEASE (Connection) . . . . . . . 1038RELEASE SAVEPOINT . . . . . . . 1040RENAME TABLE . . . . . . . . . 1041RENAME TABLESPACE . . . . . . . 1043REVOKE (Database Authorities) . . . . 1045REVOKE (Index Privileges) . . . . . . 1048REVOKE (Package Privileges) . . . . . 1050REVOKE (Schema Privileges) . . . . . 1053REVOKE (Server Privileges) . . . . . . 1055REVOKE (Table, View, or NicknamePrivileges) . . . . . . . . . . . . 1057REVOKE (Table Space Privileges) . . . . 1063ROLLBACK . . . . . . . . . . . 1065SAVEPOINT . . . . . . . . . . . 1068SELECT. . . . . . . . . . . . . 1070SELECT INTO . . . . . . . . . . 1071SET CONNECTION . . . . . . . . 1073SET CURRENT DEFAULT TRANSFORMGROUP. . . . . . . . . . . . . 1075SET CURRENT DEGREE . . . . . . . 1077SET CURRENT EXPLAIN MODE . . . . 1079SET CURRENT EXPLAIN SNAPSHOT 1081SET CURRENT PACKAGESET . . . . . 1083SET CURRENT QUERY OPTIMIZATION 1085SET CURRENT REFRESH AGE . . . . . 1088SET ENCRYPTION PASSWORD . . . . 1090SET EVENT MONITOR STATE . . . . . 1092SET INTEGRITY . . . . . . . . . . 1094SET PASSTHRU . . . . . . . . . . 1104SET PATH . . . . . . . . . . . . 1106SET SCHEMA . . . . . . . . . . 1108SET SERVER OPTION . . . . . . . . 1110SET Variable . . . . . . . . . . . 1112UPDATE . . . . . . . . . . . . 1117VALUES . . . . . . . . . . . . 1128VALUES INTO . . . . . . . . . . 1129WHENEVER . . . . . . . . . . . 1131

    Chapter 7. SQL Control Statements . . 1133SQL Procedure Statement . . . . . . . 1134ALLOCATE CURSOR Statement . . . . 1136Assignment Statement . . . . . . . . 1138ASSOCIATE LOCATORS Statement . . . 1140CASE Statement . . . . . . . . . . 1142FOR Statement . . . . . . . . . . 1144GET DIAGNOSTICS Statement . . . . . 1146

    GOTO Statement. . . . . . . . . . 1148IF Statement . . . . . . . . . . . 1150ITERATE Statement . . . . . . . . . 1152LEAVE Statement . . . . . . . . . 1153LOOP Statement . . . . . . . . . . 1154Compound Statement (Procedure) . . . . 1156REPEAT Statement . . . . . . . . . 1162RESIGNAL Statement . . . . . . . . 1164RETURN Statement . . . . . . . . . 1167SIGNAL Statement . . . . . . . . . 1169WHILE Statement . . . . . . . . . 1172

    Appendix A. SQL Limits . . . . . . 1175

    Appendix B. SQL Communications(SQLCA) . . . . . . . . . . . . 1183Viewing the SQLCA Interactively . . . . 1183SQLCA Field Descriptions . . . . . . 1183Order of Error Reporting . . . . . . . 1187DB2 Enterprise - Extended Edition Usage ofthe SQLCA . . . . . . . . . . . 1188

    Appendix C. SQL Descriptor Area(SQLDA) . . . . . . . . . . . . 1189Field Descriptions . . . . . . . . . 1189

    Fields in the SQLDA Header . . . . . 1191Fields in an Occurrence of a BaseSQLVAR . . . . . . . . . . . 1192Fields in an Occurrence of a SecondarySQLVAR . . . . . . . . . . . 1194

    Effect of DESCRIBE on the SQLDA . . . 1196SQLTYPE and SQLLEN . . . . . . . 1197

    Unrecognized and UnsupportedSQLTYPES . . . . . . . . . . . 1199Packed Decimal Numbers. . . . . . 1200SQLLEN Field for Decimal . . . . . 1201

    Appendix D. Catalog Views . . . . . 1203Updatable Catalog Views . . . . . . . 1204Roadmap to Catalog Views . . . . . . 1204Roadmap to Updatable Catalog Views 1206SYSIBM.SYSDUMMY1 . . . . . . . . 1207SYSCAT.ATTRIBUTES . . . . . . . . 1208SYSCAT.BUFFERPOOLNODES . . . . . 1210SYSCAT.BUFFERPOOLS . . . . . . . 1211SYSCAT.CASTFUNCTIONS . . . . . . 1212SYSCAT.CHECKS . . . . . . . . . 1213SYSCAT.COLAUTH. . . . . . . . . 1214SYSCAT.COLCHECKS . . . . . . . . 1215SYSCAT.COLDIST . . . . . . . . . 1216

    viii SQL Reference

    ||

    ||

    ||

    ||

    ||

  • SYSCAT.COLOPTIONS . . . . . . . 1217SYSCAT.COLUMNS . . . . . . . . 1218SYSCAT.CONSTDEP . . . . . . . . 1223SYSCAT.DATATYPES . . . . . . . . 1224SYSCAT.DBAUTH . . . . . . . . . 1226SYSCAT.EVENTMONITORS . . . . . . 1228SYSCAT.EVENTS . . . . . . . . . 1230SYSCAT.FULLHIERARCHIES . . . . . 1231SYSCAT.FUNCDEP . . . . . . . . . 1232SYSCAT.FUNCMAPOPTIONS . . . . . 1233SYSCAT.FUNCMAPPARMOPTIONS . . . 1234SYSCAT.FUNCMAPPINGS . . . . . . 1235SYSCAT.FUNCPARMS . . . . . . . . 1236SYSCAT.FUNCTIONS . . . . . . . . 1238SYSCAT.HIERARCHIES . . . . . . . 1243SYSCAT.INDEXAUTH . . . . . . . . 1244SYSCAT.INDEXCOLUSE . . . . . . . 1245SYSCAT.INDEXDEP . . . . . . . . 1246SYSCAT.INDEXES . . . . . . . . . 1247SYSCAT.INDEXOPTIONS. . . . . . . 1250SYSCAT.KEYCOLUSE . . . . . . . . 1251SYSCAT.NAMEMAPPINGS . . . . . . 1252SYSCAT.NODEGROUPDEF . . . . . . 1253SYSCAT.NODEGROUPS . . . . . . . 1254SYSCAT.PACKAGEAUTH . . . . . . 1255SYSCAT.PACKAGEDEP . . . . . . . 1256SYSCAT.PACKAGES . . . . . . . . 1257SYSCAT.PARTITIONMAPS . . . . . . 1261SYSCAT.PASSTHRUAUTH . . . . . . 1262SYSCAT.PROCEDURES . . . . . . . 1263SYSCAT.PROCOPTIONS . . . . . . . 1266SYSCAT.PROCPARMOPTIONS . . . . . 1267SYSCAT.PROCPARMS . . . . . . . . 1268SYSCAT.REFERENCES. . . . . . . . 1270SYSCAT.REVTYPEMAPPINGS . . . . . 1271SYSCAT.SCHEMAAUTH . . . . . . . 1273SYSCAT.SCHEMATA . . . . . . . . 1274SYSCAT.SEQUENCES . . . . . . . . 1275SYSCAT.SERVEROPTIONS . . . . . . 1277SYSCAT.SERVERS . . . . . . . . . 1278SYSCAT.STATEMENTS . . . . . . . 1279SYSCAT.TABAUTH . . . . . . . . . 1280SYSCAT.TABCONST . . . . . . . . 1282SYSCAT.TABLES. . . . . . . . . . 1283SYSCAT.TABLESPACES . . . . . . . 1287SYSCAT.TABOPTIONS. . . . . . . . 1288SYSCAT.TBSPACEAUTH . . . . . . . 1289SYSCAT.TRIGDEP . . . . . . . . . 1290SYSCAT.TRIGGERS . . . . . . . . . 1291SYSCAT.TYPEMAPPINGS . . . . . . 1292

    SYSCAT.USEROPTIONS . . . . . . . 1294SYSCAT.VIEWDEP . . . . . . . . . 1295SYSCAT.VIEWS . . . . . . . . . . 1296SYSCAT.WRAPOPTIONS . . . . . . . 1297SYSCAT.WRAPPERS . . . . . . . . 1298SYSSTAT.COLDIST . . . . . . . . . 1299SYSSTAT.COLUMNS . . . . . . . . 1300SYSSTAT.FUNCTIONS. . . . . . . . 1302SYSSTAT.INDEXES . . . . . . . . . 1304SYSSTAT.TABLES . . . . . . . . . 1307

    Appendix E. Catalog Views For Use WithStructured Types . . . . . . . . . 1309Roadmap to Catalog Views . . . . . . 1310OBJCAT.INDEXES . . . . . . . . . 1312OBJCAT.INDEXEXPLOITRULES . . . . 1315OBJCAT.INDEXEXTENSIONDEP . . . . 1316OBJCAT.INDEXEXTENSIONMETHODS 1317OBJCAT.INDEXEXTENSIONPARMS . . . 1318OBJCAT.INDEXEXTENSIONS . . . . . 1319OBJCAT.PREDICATESPECS . . . . . . 1320OBJCAT.TRANSFORMS . . . . . . . 1321

    Appendix F. Federated Systems . . . . 1323Server Types . . . . . . . . . . . 1323SQL Options for Federated Systems . . . 1324

    Column Options . . . . . . . . . 1325Function Mapping Options . . . . . 1326Server Options . . . . . . . . . 1326User Options . . . . . . . . . . 1331

    Default Data Type Mappings . . . . . 1331Default Type Mappings between DB2and DB2 Universal Database for OS/390(and DB2 for MVS/ESA) Data Sources . 1332Default Type Mappings between DB2and 2 Universal Database for AS/400(and DB2 for OS/400) Data Sources . . 1332Default Type Mappings between DB2and Oracle Data Sources . . . . . . 1332Default Type Mappings between DB2and DB2 for VM and VSE (and SQL/DS)Data Sources . . . . . . . . . . 1333

    Pass-Through Facility Processing . . . . 1333SQL Processing in Pass-ThroughSessions. . . . . . . . . . . . 1333Considerations and Restrictions. . . . 1334

    Appendix G. Sample Database Tables 1337The Sample Database . . . . . . . . 1338

    To Create the Sample Database . . . . 1338

    Contents ix

    ||

  • To Erase the Sample Database . . . . 1338CL_SCHED Table . . . . . . . . 1338DEPARTMENT Table . . . . . . . 1339EMPLOYEE Table . . . . . . . . 1339EMP_ACT Table . . . . . . . . . 1342EMP_PHOTO Table. . . . . . . . 1344EMP_RESUME Table . . . . . . . 1344IN_TRAY Table . . . . . . . . . 1345ORG Table . . . . . . . . . . . 1345PROJECT Table . . . . . . . . . 1346SALES Table . . . . . . . . . . 1347STAFF Table . . . . . . . . . . 1348STAFFG Table . . . . . . . . . 1349

    Sample Files with BLOB and CLOB DataType . . . . . . . . . . . . . . 1350

    Quintana Photo . . . . . . . . . 1350Quintana Resume . . . . . . . . 1350Nicholls Photo . . . . . . . . . 1351Nicholls Resume . . . . . . . . . 1352Adamson Photo . . . . . . . . . 1353Adamson Resume . . . . . . . . 1353Walker Photo . . . . . . . . . . 1354Walker Resume . . . . . . . . . 1355

    Appendix H. Reserved Schema Namesand Reserved Words. . . . . . . . 1357Reserved Schemas . . . . . . . . . 1357Reserved Words . . . . . . . . . . 1357IBM SQL reserved words . . . . . . . 1359ISO/ANS SQL92 Reserved Words . . . . 1361

    Appendix I. Comparison of IsolationLevels . . . . . . . . . . . . . 1363

    Appendix J. Interaction of Triggers andConstraints . . . . . . . . . . . 1365

    Appendix K. Explain Tables andDefinitions . . . . . . . . . . . 1369EXPLAIN_ARGUMENT Table . . . . . 1370EXPLAIN_INSTANCE Table . . . . . . 1374EXPLAIN_OBJECT Table . . . . . . . 1376EXPLAIN_OPERATOR Table . . . . . 1378EXPLAIN_PREDICATE Table . . . . . 1380EXPLAIN_STATEMENT Table . . . . . 1383EXPLAIN_STREAM Table . . . . . . 1385ADVISE_INDEX Table . . . . . . . . 1387ADVISE_WORKLOAD Table . . . . . 1390Table Definitions for Explain Tables . . . 1390

    EXPLAIN_ARGUMENT Table Definition 1392

    EXPLAIN_INSTANCE Table Definition 1393EXPLAIN_OBJECT Table Definition . . 1394EXPLAIN_OPERATOR Table Definition 1395EXPLAIN_PREDICATE Table Definition 1396EXPLAIN_STATEMENT Table Definition 1397EXPLAIN_STREAM Table Definition 1398ADVISE_INDEX Table Definition . . . 1399ADVISE_WORKLOAD Table Definition 1401

    Appendix L. Explain Register Values 1403

    Appendix M. Recursion Example: Bill ofMaterials . . . . . . . . . . . . 1407Example 1: Single Level Explosion . . . . 1407Example 2: Summarized Explosion . . . 1409Example 3: Controlling Depth . . . . . 1410

    Appendix N. Exception Tables . . . . 1413Rules for Creating an Exception Table . . 1413Handling Rows in the Exception Tables 1415Querying the Exception Tables . . . . . 1416

    Appendix O. Japanese andTraditional-Chinese EUC Considerations. 1419Language Elements . . . . . . . . . 1419

    Characters . . . . . . . . . . . 1419Tokens . . . . . . . . . . . . 1419Identifiers . . . . . . . . . . . 1419Data Types. . . . . . . . . . . 1420Assignments and Comparisons . . . . 1420Rules for Result Data Types . . . . . 1421Rules for String Conversions. . . . . 1421Constants . . . . . . . . . . . 1422Functions . . . . . . . . . . . 1422Expressions . . . . . . . . . . 1423Predicates . . . . . . . . . . . 1423

    Functions . . . . . . . . . . . . 1424LENGTH . . . . . . . . . . . 1424SUBSTR . . . . . . . . . . . 1424TRANSLATE . . . . . . . . . . 1424VARGRAPHIC . . . . . . . . . 1425

    Statements . . . . . . . . . . . . 1425CONNECT . . . . . . . . . . 1425PREPARE . . . . . . . . . . . 1425

    Appendix P. BNF Specifications forDATALINKs . . . . . . . . . . . 1427

    Appendix Q. Glossary . . . . . . . 1431

    x SQL Reference

  • Appendix R. Using the DB2 Library . . 1523DB2 PDF Files and Printed Books . . . . 1523

    DB2 Information . . . . . . . . . 1523Printing the PDF Books . . . . . . 1532Ordering the Printed Books . . . . . 1533

    DB2 Online Documentation . . . . . . 1534Accessing Online Help. . . . . . . 1534Viewing Information Online . . . . . 1536Using DB2 Wizards . . . . . . . . 1538Setting Up a Document Server . . . . 1539

    Searching Information Online . . . . 1540

    Appendix S. Notices . . . . . . . . 1541Trademarks . . . . . . . . . . . 1544

    Index . . . . . . . . . . . . . 1547

    Contacting IBM. . . . . . . . . . 1579Product Information . . . . . . . . 1579

    Contents xi

  • xii SQL Reference

  • Chapter 1. Introduction

    This introductory chapter:v Identifies this books purpose and audience,v Explains how to use the book and its structure,v Explains the syntax diagram notation, the naming and highlighting

    conventions used throughout the manual,v Lists related documentation,v Presents the product family overview.

    Who Should Use This BookThis 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 general users using thecommand line processor.

    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 To Use This BookThis book defines the SQL language used by DB2 Universal Database Version7. Use it as a reference manual for information on relational databaseconcepts, language elements, functions, the forms of queries, and the syntaxand semantics of the SQL statements. The appendixes can be used to findlimitations and information on important components.

    How This Book is StructuredThis reference manual is divided into two volumes. Volume 1 contains thefollowing sections:v Chapter 1. Introduction, identifies the purpose, the audience, and the use

    of the book.v Chapter 2. Concepts on page 9, discusses the basic concepts of relational

    databases and SQL.v Chapter 3. Language Elements on page 63, describes the basic syntax of

    SQL and the language elements that are common to many SQL statements.v Chapter 4. Functions on page 215, contains syntax diagrams, semantic

    descriptions, rules, and usage examples of SQL column and scalarfunctions.

    Copyright IBM Corp. 1993, 2001 1

  • v Chapter 5. Queries on page 443, describes the various forms of a query.v The appendixes included in Volume 1 contain the following information:

    Appendix A. SQL Limits on page 1175 contains the SQL limitations Appendix B. SQL Communications (SQLCA) on page 1183 contains the

    SQLCA structure Appendix C. SQL Descriptor Area (SQLDA) on page 1189 contains the

    SQLDA structure Appendix D. Catalog Views on page 1203 contains the catalog views

    for the database Appendix E. Catalog Views For Use With Structured Types on

    page 1309 contains the structured type catalog views for the database Appendix F. Federated Systems on page 1323 contains options and type

    mappings for Federated Systems Appendix G. Sample Database Tables on page 1337 contains the sample

    tables used for examples Appendix H. Reserved Schema Names and Reserved Words on

    page 1357 contains the reserved schema names and the reserved wordsfor the IBM SQL and ISO/ANS SQL92 standards

    Appendix I. Comparison of Isolation Levels on page 1363 contains asummary of the isolation levels.

    Appendix J. Interaction of Triggers and Constraints on page 1365discusses the interaction of triggers and referential constraints.

    Appendix K. Explain Tables and Definitions on page 1369 contains theExplain tables and how they are defined.

    Appendix L. Explain Register Values on page 1403 describes theinteraction of the CURRENT EXPLAIN MODE and CURRENT EXPLAINSNAPSHOT special register values with each other and the PREP andBIND commands.

    Appendix M. Recursion Example: Bill of Materials on page 1407contains an example of a recursive query.

    Appendix N. Exception Tables on page 1413 contains information onuser-created tables that are used with the SET INTEGRITY statement.

    Appendix O. Japanese and Traditional-Chinese EUC Considerations onpage 1419 lists considerations when using EUC character sets.

    Appendix P. BNF Specifications for DATALINKs on page 1427 containsthe BNF specifications for DATALINKs.

    Volume 2 contains the following sections:v Chapter 6. SQL Statements on page 503, contains syntax diagrams,

    semantic descriptions, rules, and examples of all SQL statements.

    2 SQL Reference

  • v Chapter 7. SQL Control Statements on page 1133, contains syntaxdiagrams, semantic descriptions, rules, and examples of SQL procedurestatements.

    How to Read the Syntax DiagramsThroughout 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 statement.

    The symbol indicates that the statement syntax is continued on the nextline.

    The symbol indicates that a statement is continued from the previousline.

    The symbol indicates the end of a statement.

    Required items appear on the horizontal line (the main path).

    STATEMENT required item

    Optional items appear below the main path.

    STATEMENToptional item

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

    STATEMENToptional 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.

    Chapter 1. Introduction 3

  • STATEMENT required choice1required choice2

    If choosing none of the items is an option, the entire stack appears below themain path.

    STATEMENToptional choice1optional choice2

    If one of the items is the default, it will appear above the main path and theremaining choices will be shown below.

    STATEMENTdefault 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.

    STATEMENT repeatable item

    If the repeat arrow contains a comma, you must separate repeated items witha comma.

    STATEMENT

    ,

    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.

    4 SQL Reference

  • 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 set of several parameters. Forexample, in the following diagram, the variable parameter-block can bereplaced by any of the interpretations of the diagram that is headedparameter-block:

    STATEMENT parameter-block

    parameter-block:

    parameter1parameter2 parameter3

    parameter4

    Adjacent segments occurring between large bullets (*) may be specified inany sequence.

    STATEMENT item1 * item2 * item3 * item4

    The above diagram shows that item2 and item3 may be specified in eitherorder. Both of the following are valid:STATEMENT item1 item2 item3 item4STATEMENT item1 item3 item2 item4

    Conventions Used in This ManualThis 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 brackets. For example: A duplicatesignature 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.

    Chapter 1. Introduction 5

  • Italics Indicates one of the following:v Names or values (variables) that must be supplied by the userv General emphasisv The introduction of a new termv A reference to another source of information.

    Monospace Indicates one of the following:v Files and directoriesv Information that you are instructed to type at a command prompt

    or in a windowv Examples of specific data valuesv Examples of text similar to what may be displayed by the systemv Examples of system messages.

    Related Documentation for This BookThe 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 by

    DB2 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 OS/390 and z/OS SQL Reference This book defines Structured Query Language (SQL) used in DB2 for

    z/OS (OS/390). This manual provides query forms, SQL statements, SQLprocedure statements, DB2 limits, SQLCA, SQLDA, catalog tables, andSQL reserved words for z/OS (OS/390) systems running DB2.

    v DB2 Spatial Extender Users Guide and Reference Discusses how to write applications to create and use a geographic

    information system (GIS). Creating and using a GIS involves supplying adatabase with resources and then querying the data to obtaininformation such as locations, distances, and distributions within areas.

    v IBM SQL Reference

    6 SQL Reference

    ||||||||||||

  • This manual contains all the common elements of SQL that span acrossIBMs library of database products. It provides limits and rules that assistin preparing portable programs using IBM databases. It 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.v ISO/IEC 9075-4:1999, Database Language SQL -- Part 4: Persistent Stored

    Modules (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.

    Chapter 1. Introduction 7

  • 8 SQL Reference

  • Chapter 2. Concepts

    This conceptual overview explains the concepts commonly used in theStructured Query Language (SQL). The intent of this chapter is to provide ahigh-level view of the concepts. The reference material that follows provides amore detailed view.

    Relational Database DefinitionsA 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 where the 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)1 statements take partition informationinto consideration (for example, CREATE NODEGROUP).

    A federated database is a relational database where the data is stored inmultiple data sources (such as separate relational databases). The data appearsas if it were all in a single large database and can be accessed throughtraditional SQL queries. Changes to the data can be explicitly directed to theappropriate data source. See DB2 Federated Systems on page 50 for moreinformation.

    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.

    1. Data Definition Language (DDL) is the subset of SQL statements used to describe data relationships in a database.

    Copyright IBM Corp. 1993, 2001 9

    ||||||||||||||||||||||||||||||||

  • 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 PrivilegesAn 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 by that user toperform a specific task. Explicit authorities or privileges are granted to theuser (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.

    The person or persons with administrative authority have the task ofcontrolling the database manager and are responsible for the safety andintegrity of the data. They control who will have access to the databasemanager and to what extent each user has access.

    The database manager provides two administrative authorities:v SYSADM - system administrator authorityv DBADM - database 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

    10 SQL Reference

    |

    |||

    ||||||||||||||||||

    |||||||

  • The database manager also provides two system control authorities:v SYSCTRL - system control authorityv SYSMAINT - system maintenance authority

    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 privileges of DBADM, SYSCTRL, and SYSMAINT,and the authority to grant or revoke DBADM authorities.

    DBADM authority is the administrative authority specific to a single database.This authority includes privileges to create objects, issue database commands,and access the data in any of its tables through SQL statements. DBADMauthority also includes the authority to grant or revoke CONTROL andindividual privileges.

    SYSCTRL authority is the higher level of system control authority and appliesonly to operations affecting system resources. It does not allow direct access todata. This authority includes privileges to create, update, or drop a database;halt an instance or database; and drop or create a table space.

    SYSMAINT 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 to data.This authority includes privileges to update database configuration files,backup a database or table space, restore an existing database, and monitor adatabase.

    Database authorities apply to those activities that an administrator hasallowed a user to perform within the database that do not apply to a specificinstance of a database object. For example, a user may be granted theauthority to create packages but not create tables.

    Privileges apply to those activities that an administrator or object owner hasallowed a user to perform on database objects. Users with privileges cancreate objects, though they face some constraints, unlike a user with anauthority like SYSADM or DBADM. For example, a user may have theprivilege to create a view on a table but not a trigger on the same table. Userswith privileges have access to the objects they own, and can pass onprivileges on their own objects to other users by using the GRANT statement.

    CONTROL privilege allows the user to access a specific database object asrequired and to GRANT and REVOKE privileges to and from other users onthat object. DBADM authority is required to grant CONTROL privilege.

    Chapter 2. Concepts 11

    ||||||||||||||||||||||||||||||||||||

  • 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 using the WITH GRANT OPTION on the GRANT statement.

    SchemasA 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 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)

    Controlling the Use of SchemasWhen 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, then schemas areeither explicitly created using the CREATE SCHEMA statement, or implicitlycreated by users (such as those with DBADM authority) who are grantedIMPLICIT_SCHEMA authority. Although revoking IMPLICIT_SCHEMAauthority from PUBLIC increases control over the use of schema names, it canresult in authorization errors in existing applications when these applicationsattempt to create objects.

    12 SQL Reference

    |||||||||||||||||||||||||||||||||||||||

  • Schemas also have associated privileges, allowing the schema owner tocontrol which users have the privilege to create, alter, and drop objects in theschema. A schema owner is initially given all of these privileges on theschema, with the ability to grant them to others. An implicitly created schemais owned by the system, and all users are initially given the privilege to createobjects in such a schema. A user with DBADM or SYSADM authority canchange the privileges held by users on any schema. Therefore, access to create,alter, and drop objects in any schema (even one that is implicitly created) canbe controlled.

    TablesTables 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 CURRENTQUERY OPTIMIZATION special registers.

    A table can define the data type of each column separately, or base the typesfor the columns on the attributes of a user-defined structured type. This iscalled a typed table. A user-defined structured type may be part of a typehierarchy. A subtype inherits attributes from its supertype. Similarly, a typedtable can be part of a table hierarchy. A subtable inherit columns from itssupertable. Note that the term subtype applies to a user-defined structured typeand all user-defined structured types that are below it in the type hierarchy. Aproper subtype of a structured type T is a structured type below T in the typehierarchy. Similarly, the term subtable applies to a typed table and all typedtables that are below it in the table hierarchy. A proper subtable of a table T is atable below T in the table hierarchy.

    Chapter 2. Concepts 13

    ||||||||||||||||||||||||||||||||||||||

  • 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.

    ViewsA view provides an alternative way of looking at the data in one or moretables.

    A view is a named specification of a result table. The specification is aSELECT statement that is executed whenever the view is referenced in an SQLstatement. Consider a view to have columns and rows just like a base table.For retrieval, all views can be used just like base tables. Whether a view canbe used in an insert, update, or delete operation depends on its definition asexplained in the description of the CREATE VIEW statement. See CREATEVIEW on page 893 for more information.

    When the column of a view is directly derived from a column of a base table,that column inherits any constraints that apply to the column of the basetable. 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 the base table. Also, if the base table of a view is a parent table,DELETE and UPDATE operations using that view are subject to the samerules as 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 for the columns on the attributes of a user-defined structured type.This is called a typed view. Similar to a typed table, a typed view can be partof a view hierarchy. A subview inherits columns from its superview. The termsubview applies to a typed view and all typed views that are below it in theview hierarchy. A proper subview of a view V is a view below V in the typedview hierarchy.

    A view can become inoperative (for example, if the base table is dropped); ifthis occurs, the view is no longer available for SQL statements.

    AliasesAn alias is an alternative name for a table or view. It can be used to referencea table or view in those cases where an existing table or view can bereferenced. An alias cannot be used in all contexts. For example, it cannot beused in the check condition of a check constraint. Also, an alias cannotreference a declared temporary table.

    14 SQL Reference

    ||||||||||||||||||||||||||||||||||||||

  • Like tables and 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 an alias. Access to the tables andviews referred to by the alias, however, still requires the appropriateauthorization for the current context.

    In addition to table aliases, there are other types of aliases such as databaseand network aliases. Aliases can also be created for nicknames (data tables orviews located on federated systems).

    See Aliases on page 71 and CREATE ALIAS on page 630 for moreinformation about aliases.

    IndexesAn index is an ordered set of pointers to rows of 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 structure and maintains it automatically.

    Indexes are used by the database manager to:v Improve performance. In most cases, access to data is faster than without

    an index.An index cannot be created for a view. However, an index created for atable on which a view is based can sometimes improve the performance ofoperations on the view.

    v Ensure uniqueness. A table with a unique index cannot have rows withidentical keys.

    KeysA 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 composed of more than one column is called a composite key. In a tablewith a composite key, the order of the columns within the composite key isnot 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 ofthe 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.

    Chapter 2. Concepts 15

    |||||||||||||||||||||||||||||||||||||

  • Unique KeysA 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.See Unique Constraints on page 17 for a more detailed description.

    Primary KeysA primary key is a special case of a unique key. A table cannot have more thanone primary key. See Unique Keys for a more detailed description.

    Foreign KeysA foreign key is a key that is specified in the definition of a referentialconstraint. See Referential Constraints on page 17 for a more detaileddescription.

    Partitioning KeysA 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.

    ConstraintsA 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 corporations suppliers. Occasionally, a suppliers 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 inserts, updates, or deletes that would otherwise result in missingsupplier information.

    16 SQL Reference

    ||||||||||||||||||||||||||||||||||||||

  • v A table check constraint sets restrictions on data added to a specific table. Forexample, the constraint can restrict the salary level for an employee to be atleast $20,000 whenever salary data is added or updated in a tablecontaining personnel information.

    Referential and table check constraints can be turned on or off. Loading largeamounts of data into the database is typically a time to turn off checking theenforcement of a constraint. The details of turning constraints on or off arediscussed in SET INTEGRITY on page 1094.

    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 a 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 key is a column or set of columns in a table whosevalues are required to match at least one primary key or unique key value ofa row of its parent table. A referential constraint is the rule that the values ofthe foreign key are valid only if one of these conditions is true:

    Chapter 2. Concepts 17

    ||||||||||||||||||||||||||||||||||||||

  • v They appear as values of a parent key.v Some component of the foreign key is null.

    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 CREATE TABLEstatements and ALTER TABLE statements. Referential constraints are enforcedby the database manager during the execution of INSERT, UPDATE, DELETE,ALTER TABLE, ADD CONSTRAINT, and SET INTEGRITY statements. Theenforcement is effectively performed at the completion of the statement.

    Referential constraints with a delete or update rule of RESTRICT are enforcedbefore all other referential constraints. Referential constraints with a delete orupdate rule of NO ACTION behave like RESTRICT in most cases. However,in certain SQL statements there can be a difference.

    Note that referential integrity, check constraints, and triggers can be combinedin execution. For further information on the combination of these elements,see Appendix J. Interaction of Triggers and Constraints on page 1365.

    The rules of referential integrity involve the following concepts andterminology:

    Parent keyA primary key or 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 of 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 of 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.

    18 SQL Reference

    ||||||||||||||||||||||||||||||||||||||

  • 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.

    Self-referencing rowA row that is a parent of itself.

    Self-referencing tableA table that is a parent and a dependent in the same referentialconstraint. The constraint is called a self-referencing constraint.

    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, these 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.

    Chapter 2. Concepts 19

    ||||||||||||||||||||||||||||||||||

  • 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 thedependent table, and p is a parent row that is the object of a delete orpropagated delete operation. The delete rule works as follows:v For RESTRICT or NO ACTION, an error occurs and no rows are deleted.v For CASCADE, the delete operation is propagated to the dependents of p

    in table D.v For 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.

    20 SQL Reference

    |||||||||||||||||||||||||||||||||||||

  • 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 of a table. A constraint is optional, and can bedefined using the SQL statements CREATE TABLE and ALTER TABLE.Specifying table check constraints is done through a restricted form of asearch condition. One of the restrictions is that a column name in a tablecheck constraint on table T must identify a column of T.

    A table can have an arbitrary number of table check constraints. They areenforced when a row is inserted into the table or a row of the table isupdated.

    A table check constraint is enforced by applying its search condition to eachrow that is inserted or updated. An error occurs if the result of the searchcondition is false for any row.

    When one or more table check constraints are defined in the ALTER TABLEstatement for a table with existing data, the existing data is checked againstthe new condition before the ALTER TABLE statement succeeds. The table canbe placed in check pending state which will allow the ALTER TABLE statementto succeed without checking the data. The SET INTEGRITY statement is usedto place the table into check pending state. It is also used to resume thechecking of each row against the constraint.

    Isolation LevelThe 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. For details ondifferent types and attributes of specific locks, see the Administration Guide.Declared temporary tables and the rows of declared temporary tables are not

    Chapter 2. Concepts 21

    ||||||||||||||||||||||||||||||||||||||||

  • locked at all because they are only accessible by the application that declaredthe temporary tables. Thus, the following discussion on locking and isolationlevels does not apply to declared temporary tables.

    The database manager supports three general categories of locks:

    ShareLimits concurrent application processes to read-only operations on thedata.

    UpdateLimits concurrent application processes to read-only operations on thedata providing these processes have not declared they might updatethe row. The database manager assumes the process looking at therow presently may update the row.

    ExclusivePrevents concurrent application processes from accessing the data inany way except for application processes with an isolation level ofuncommitted read, which can read but not modify the data. (SeeUncommitted Read (UR) on page 24.)

    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 isolation levels.Regardless of the isolation level, the database manager places exclusive lockson every row that is inserted, updated, or deleted. Thus, all isolation levelsensure that any row that is changed by this application process during a unitof work is not changed by any other application processes until the unit ofwork is complete. The isolation levels are:

    Repeatable Read (RR)The Repeatable Read level ensures that:v Any row read during a unit of work2 is not changed by other application

    processes until the unit of work is complete.3

    v Any row changed by another application process cannot be read until it iscommitted by that application process.

    2. The rows are read in the same unit of work as the corresponding OPEN statement. See WITH HOLD inDECLARE CURSOR on page 911.

    3. Use of the optional WITH RELEASE clause on the CLOSE statement means that any guarantees againstnon-repeatable reads and phantom reads no longer apply to any previously accessed rows if the cursor is reopened.

    22 SQL Reference

    |||||||||||||||||||||||||||||||||

  • 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 completely isolatedfrom the effects of concurrent application processes.

    Read Stability (RS)Like the Repeatable Read level, the Read Stability level ensures that:v Any row read during a unit of work4 is not changed by other application

    processes until the unit of work is complete.5

    v Any row changed by another application process cannot be read until it iscommitted by that application process.

    Unlike Repeatable Read, the Read Stability level does not completely isolatethe application process from the effects of concurrent application processes. Atthe RS level, application processes that issue the same query more than oncemay see additional rows caused by other application processes appendingnew information to the database. These additional rows are called phantomrows.

    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 RSlevel acquires at least share locks on all the qualifying rows.

    Cursor Stability (CS)Like the Repeatable Read level, Cursor Stability ensures that any row that waschanged by another application process cannot be read until it is committedby that application process.

    However, unlike the Repeatable Read level, Cursor Stability only ensures thatthe current row of every updatable cursor is not changed by other application

    4. The rows are read in the same unit of work as the corresponding OPEN statement. See WITH HOLD inDECLARE CURSOR on page 911.

    5. Use of the optional WITH RELEASE clause on the CLOSE statement means that any guarantees againstnon-repeatable reads no longer apply to any previously accessed rows if the cursor is reopened.

    Chapter 2. Concepts 23

    |||||||||||||||||||||||||||||||||

  • processes. Thus, the rows that were read during a unit of work can bechanged by other application processes.

    In addition to any exclusive locks, an application process running at the CSlevel has at least a share lock for the current row of every cursor.

    Uncommitted Read (UR)For a SELECT INTO, FETCH with a read-only cursor, fullselect used in anINSERT, row fullselect in an UPDATE, or scalar fullselect (wherever it isused), the Uncommitted Read level allows:v Any row read during the unit of work to be changed by other application

    processes.v 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, the rules of the CS level apply.

    Comparison of Isolation LevelsA comparison of the four isolation levels can be found in Appendix I.Comparison of Isolation Levels on page 1363.

    QueriesA query is a component of certain SQL statements that specifies a (temporary)result table.

    For a complete discussion of queries, see Chapter 5. Queries on page 443.

    Table ExpressionsA 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 and specifythat they must have over 15 years of working experience and be located at theNew York branch office.

    Common Table ExpressionsA common table expression is like a temporary view within a complex query,and can be referenced in other places within the query. For example, it can beused in place of a view, thus avoid the need to create a view. Each use of aspecific common table expression within a complex query shares the sametemporary view.

    Recursive use of a common table expression within a query can be used tosupport applications such as airline reservation systems, bill of materials

    24 SQL Reference

    ||||||||||||||||||||||||||||||||||||

  • (BOM) generators, and network planning. A set of examples from a BOMapplication is contained in Appendix M. Recursion Example: Bill ofMaterials on page 1407.

    Application Processes, Concurrency, and RecoveryAll 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 in order to prevent uncommittedchanges made by one application process from being accidentally perceivedby any other process. The database manager releases all locks it has acquiredand retained on behalf of an application process when that process ends.However, an application process can explicitly request that locks be releasedsooner. This is done using a commit operation which releases locks acquiredduring the unit of work and also commits database changes made during theunit 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 a deadlock or lock time-outsituation. An application process itself, however, can explicitly request that itsdatabase changes be backed out. This operation is called a rollback.

    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. Aunit of work is also initiated when the previous unit of work is ended bysomething other than the termination of the application process. A unit ofwork is ended by a commit operation, a rollback operation, or the end of anapplication process. A commit or rollback operation affects only the databasechanges made within the unit of work it ends.

    While these changes remain uncommitted, other application processes areunable to perceive them and they can be backed out. This is true except forwhen the isolation level uncommitted read (UR) is used, as described inUncommitted Read (UR) on page 24. Once committed, these databasechanges are accessible by other application processes and can no longer bebacked out by a rollback.

    Chapter 2. Concepts 25

    ||||||||||||||||||||||||||||||||||||||||

  • Both DB2 CLI and embedded SQL allow for a connection mode calledconcurrent transactions that supports multiple connections, each of which is anindependent transaction. An application can have multiple concurrentconnections to the same database. See the Application Development Guide fordetails on multiple thread database access.

    Locks acquired by the database manager on behalf of an application processare held until the end of a unit of work. The exceptions to this rule are cursorstability isolation level, where the lock is released as the cursor moves fromrow to row, and uncommitted read level, where locks are not obtained (seeIsolation Level on page 21).

    The initiation and termination of a unit of work define points of consistencywithin an application process. For example, a banking transaction mayinvolve the transfer of funds from one account to another.

    Such a transaction would require that these funds be subtracted from the firstaccount, and added to the second.

    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

    26 SQL Reference

    |

    |||

    |||||||||||||||||

  • Following the subtraction step, the data is inconsistent. Only after the fundshave been added to the second account is consistency reestablished. Whenboth steps are complete, the commit operation can be used to end the unit ofwork, thereby making the changes available to other application processes.

    If a failure occurs before the unit of work ends, the database manager will rollback uncommitted changes to restore the data consistency that it assumesexisted when the unit of work was initiated.

    Note: An application process is never prevented from performing operationsbecause of its own locks. However, if an application uses concurrenttransactions, then the locks from one transaction may affect theoperation of a concurrent transaction. See the Application DevelopmentGuide for details.

    Interactive SQLInteractive SQL statements are entered by a user through an interface like thecommand line processor (CLP) or the Command Center. These statements areprocessed as dynamic SQL statements. For example, an interactive SELECTstatement can be processed dynamically using the DECLARE CURSOR,PREPARE, DESCRIBE, OPEN, FETCH, and CLOSE statements.

    The Command Reference lists the commands that can be issued using the CLPor similar facilities and products.

    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

    Chapter 2. Concepts 27

    |

    ||||||||||||||||||||||||

  • Embedded SQLEmbedded SQL statements are SQL statements written within applicationprogramming languages such as C and Java. These statments are preprocessedby an SQL precompiler before the application program is compiled. There aretwo types of embedded SQL: static and dynamic.

    Static SQLThe source form of a static SQL statement is embedded within an applicationprogram written in a host language such as COBOL. The statement isprepared before the program is executed and the operational form of thestatement persists beyond the execution of the program.

    A source program containing static SQL statements must be processed by anSQL precompiler before it is compiled. The precompiler turns the SQLstatements into host language comments, and generates host languagestatements to invoke the database manager. The syntax of the SQL statementsis checked during the precompile process.

    The preparation of an SQL application program includes precompilation, thebinding of its static SQL statements to the target database, and compilation ofthe modified source program. The steps are specified in the ApplicationDevelopment Guide.

    Dynamic SQLPrograms containing embedded dynamic SQL statements must beprecompiled like those containing static SQL, but unlike static SQL, thedynamic SQL statements are constructed and prepared at run time. The SQLstatement text is prepared and executed using either the PREPARE andEXECUTE statements, or the EXECUTE IMMEDIATE statement. Thestatement can also be executed with cursor operations if it is a SELECTstatement.

    For more information on processing cursors in dynamic SQL statements, seethe Application Development Guide.

    DB2 Call Level Interface (CLI) and Open Database Connectivity (ODBC)The DB2 Call Level Interface is an application programming interface inwhich functions are provided to application programs to process dynamicSQL statements. CLI programs can also be compiled using an Open DatabaseConnectivity (ODBC) Software Developers Kit, available from Microsoft orother vendors, enabling access to ODBC data sources. Unlike using embeddedSQL, no precompilation is required. Applications developed using thisinterface can be executed on a variety of databases without being compiledagainst each of the databases. Through the interface, applications use

    28 SQL Reference

    ||||||||||||||||||||||||||||||||||||||||

  • procedure calls at execution time to connect to databases, to issue SQLstatements, and to get returned data and status information.

    The DB2 CLI interface provides many features not available in embeddedSQL. A few of these are:v CLI provides function calls that support a consistent way to query and

    retrieve database system catalog information across the DB2 family ofdatabase management systems. This reduces the need to write catalogqueries specific to 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 written using CLI canreturn result sets to those programs.

    The CLI Guide and Reference describes the APIs supported with this interface.

    Java Database Connectivity (JDBC) and Embedded SQL for Java (SQLJ)Programs

    DB2 Universal Database implements two standards-based Java programmingAPIs: Java Database Connectivity (JDBC) and embedded SQL for Java (SQLJ).Both can be used to create Java applications and applets that access DB2.

    JDBC calls are translated to calls to DB2 CLI through Java native methods.JDBC requests flow from the DB2 client through DB2 CLI to the DB2 server.JDBC cannot use static SQL.

    SQLJ applications use JDBC as a foundation for such tasks as connecting todatabases and handling SQL errors, but can also contain embedded static SQLstatements in the SQLJ source files. An SQLJ source file has to be translatedwith the SQLJ translator before the resulting Java source code can becompiled.

    For more information on JDBC and SQLJ applications, see the ApplicationDevelopment Guide.

    Chapter 2. Concepts 29

    |||||||||||||||||||||||||||||||||

  • PackagesA package is an object that contains all the sections from a single source file. Asection is the compiled form of an SQL statement. While every sectioncorresponds to one statement, every statement does not necessarily have asection. The sections created for static SQL are compar