Programación de Base de Datos SQL
Programación de Base de Datos SQL
7.5
Database
SQL programming
IBM
Note
Before using this information and the product it supports, read the information in “Notices” on page
401.
This edition applies to IBM i 7.5 (product number 5770-SS1) and to all subsequent releases and modifications until
otherwise indicated in new editions. This version does not run on all reduced instruction set computer (RISC) models nor
does it run on CISC models.
This document may contain references to Licensed Internal Code. Licensed Internal Code is Machine Code and is
licensed to you under the terms of the IBM License Agreement for Machine Code.
© Copyright International Business Machines Corporation 1998, 2022.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
IBM Corp.
Contents
SQL programming.................................................................................................. 1
What's new for IBM i 7.5..............................................................................................................................1
PDF file for SQL programming..................................................................................................................... 2
Introduction to Db2 for i Structured Query Language................................................................................ 3
SQL concepts.......................................................................................................................................... 3
SQL relational database and system terminology........................................................................... 4
SQL and system naming conventions...............................................................................................5
Types of SQL statements.................................................................................................................. 6
SQL communication area..................................................................................................................7
SQL diagnostics area.........................................................................................................................8
SQL objects............................................................................................................................................. 8
Schemas............................................................................................................................................ 8
Journals and journal receivers......................................................................................................... 8
Catalogs.............................................................................................................................................8
Tables, rows, and columns............................................................................................................... 9
Aliases............................................................................................................................................... 9
Views................................................................................................................................................. 9
Indexes..............................................................................................................................................9
Constraints...................................................................................................................................... 10
Triggers............................................................................................................................................10
Stored procedures.......................................................................................................................... 10
Sequences.......................................................................................................................................11
Global variables.............................................................................................................................. 11
User-defined functions................................................................................................................... 11
User-defined types......................................................................................................................... 11
XSR objects..................................................................................................................................... 11
SQL packages..................................................................................................................................12
Application program objects................................................................................................................12
User source file............................................................................................................................... 13
Output source file member.............................................................................................................13
Program...........................................................................................................................................14
SQL package....................................................................................................................................14
Module.............................................................................................................................................14
Service program..............................................................................................................................15
Data definition language............................................................................................................................15
Creating a schema................................................................................................................................ 15
Creating a table.................................................................................................................................... 15
Adding and removing constraints...................................................................................................16
Referential integrity and tables...................................................................................................... 16
Adding and removing referential constraints........................................................................... 17
Example: Adding referential constraints.................................................................................. 17
Example: Removing constraints..................................................................................................... 18
Check pending................................................................................................................................ 18
Creating a table using LIKE.................................................................................................................. 19
Creating a table using AS..................................................................................................................... 20
Creating and altering a materialized query table................................................................................ 20
Creating a system-period temporal table............................................................................................21
Declaring a global temporary table......................................................................................................22
Creating a table with remote server data............................................................................................ 22
Creating a row change timestamp column.......................................................................................... 23
Creating auditing columns................................................................................................................... 23
iii
Creating and altering an identity column.............................................................................................24
Using ROWID........................................................................................................................................ 25
Creating and using sequences............................................................................................................. 25
Comparison of identity columns and sequences........................................................................... 27
Defining field procedures..................................................................................................................... 28
Field definition for field procedures............................................................................................... 29
Specifying the field procedure........................................................................................................29
When field procedures are invoked................................................................................................29
Parameter list for execution of field procedures........................................................................... 30
The field procedure parameter value list (FPPVL)....................................................................32
Parameter value descriptors for field procedures....................................................................33
Field-definition (function code 8)............................................................................................. 33
Field-encoding (function code 0)..............................................................................................34
Field-decoding (function code 4)..............................................................................................35
Example field procedure program............................................................................................ 36
General guidelines for writing field procedures.............................................................................47
Index considerations.................................................................................................................47
Thread considerations...............................................................................................................48
Debug considerations............................................................................................................... 48
Guidelines for writing field procedures that mask data................................................................ 48
Example field procedure program that masks data................................................................. 51
Creating descriptive labels using the LABEL statement..................................................................... 52
Describing an SQL object using COMMENT......................................................................................... 53
Changing a table definition.................................................................................................................. 54
Adding a column............................................................................................................................. 54
Changing a column..........................................................................................................................54
Allowable conversions of data types..............................................................................................55
Deleting a column........................................................................................................................... 56
Order of operations for the ALTER TABLE statement.................................................................... 56
Using CREATE OR REPLACE TABLE................................................................................................ 57
Creating and using ALIAS names.........................................................................................................58
Creating and using views......................................................................................................................58
WITH CHECK OPTION on a view.................................................................................................... 60
WITH CASCADED CHECK OPTION............................................................................................60
WITH LOCAL CHECK OPTION................................................................................................... 61
Example: Cascaded check option............................................................................................. 62
Creating indexes................................................................................................................................... 63
Creating and using global variables..................................................................................................... 63
Replacing existing objects....................................................................................................................64
Dropping a database object................................................................................................................. 64
DROP IF EXISTS..............................................................................................................................65
Restrict on drop.............................................................................................................................. 65
Catalogs in database design................................................................................................................ 67
Getting catalog information about a table..................................................................................... 67
Getting catalog information about a column................................................................................. 67
Data manipulation language......................................................................................................................68
Retrieving data using the SELECT statement...................................................................................... 68
Basic SELECT statement.................................................................................................................68
Specifying a search condition using the WHERE clause................................................................69
Expressions in the WHERE clause............................................................................................ 70
Comparison operators...............................................................................................................72
NOT keyword............................................................................................................................. 72
GROUP BY clause............................................................................................................................72
HAVING clause................................................................................................................................74
ORDER BY clause............................................................................................................................75
Static SELECT statements.............................................................................................................. 77
Handling null values........................................................................................................................77
Special registers in SQL statements...............................................................................................79
iv
Casting data types.......................................................................................................................... 80
Date, time, and timestamp data types........................................................................................... 81
Specifying current date and time values.................................................................................. 81
Date/time arithmetic................................................................................................................. 81
Boolean data type...........................................................................................................................82
Row change expressions................................................................................................................ 82
Handling duplicate rows................................................................................................................. 82
Defining complex search conditions.............................................................................................. 83
Special considerations for LIKE................................................................................................ 85
Multiple search conditions within a WHERE clause................................................................. 85
Using OLAP specifications.............................................................................................................. 86
Joining data from more than one table.......................................................................................... 92
Inner join................................................................................................................................... 92
Left outer join............................................................................................................................ 93
Right outer join.......................................................................................................................... 94
Exception join............................................................................................................................ 94
Cross join................................................................................................................................... 95
Full outer join.............................................................................................................................96
Multiple join types in one statement........................................................................................ 96
Using table expressions..................................................................................................................97
Using recursive queries.................................................................................................................. 99
Using the UNION keyword to combine subselects......................................................................111
Specifying the UNION ALL keyword....................................................................................... 114
Using the EXCEPT keyword.......................................................................................................... 115
Using the INTERSECT keyword.................................................................................................... 117
Data retrieval errors......................................................................................................................119
Selecting data from a remote database.......................................................................................120
Inserting rows using the INSERT statement..................................................................................... 121
Inserting rows using the VALUES clause..................................................................................... 122
Inserting rows using a select-statement..................................................................................... 123
Inserting multiple rows using the blocked INSERT statement................................................... 124
Inserting data into tables with referential constraints................................................................124
Inserting values into an identity column......................................................................................125
Selecting inserted values............................................................................................................. 126
Inserting data from a remote database....................................................................................... 126
Changing data in a table using the UPDATE statement.................................................................... 127
Updating a table using a scalar-subselect...................................................................................128
Updating a table with rows from another table........................................................................... 128
Updating tables with referential constraints............................................................................... 129
Examples: UPDATE rules........................................................................................................ 129
Updating an identity column........................................................................................................ 130
Updating data as it is retrieved from a table................................................................................130
Removing rows from a table using the DELETE statement...............................................................132
Removing rows from tables with referential constraints............................................................ 132
Example: DELETE rules...........................................................................................................134
Removing rows from a table using the TRUNCATE statement......................................................... 135
Merging data ...................................................................................................................................... 136
Overriding system generation of column values............................................................................... 137
Using subqueries................................................................................................................................137
Subqueries in SELECT statements............................................................................................... 138
Subqueries and search conditions......................................................................................... 139
Usage notes on subqueries.....................................................................................................139
Including subqueries in the WHERE or HAVING clause........................................................ 139
Correlated subqueries.................................................................................................................. 141
Correlated names and references.......................................................................................... 141
Example: Correlated subquery in a WHERE clause............................................................... 141
Example: Correlated subquery in a HAVING clause.............................................................. 143
Example: Correlated subquery in a select-list....................................................................... 143
v
Example: Correlated subquery in an UPDATE statement...................................................... 144
Example: Correlated subquery in a DELETE statement.........................................................145
Processing special data types................................................................................................................. 145
Large objects...................................................................................................................................... 145
Large object data types................................................................................................................ 145
Large object locators.................................................................................................................... 146
Example: Using a locator to work with a CLOB value.................................................................. 146
Example: LOBLOC in C............................................................................................................ 147
Example: LOBLOC in COBOL................................................................................................... 148
Indicator variables and LOB locators...........................................................................................149
LOB file reference variables......................................................................................................... 149
Example: Extracting CLOB data to a file.......................................................................................150
Example: LOBFILE in C............................................................................................................151
Example: LOBFILE in COBOL.................................................................................................. 151
Example: Inserting data into a CLOB column.............................................................................. 152
Displaying the layout of LOB columns..........................................................................................152
Journal entry layout of LOB columns........................................................................................... 153
User-defined distinct types................................................................................................................153
Using strongly typed UDTs............................................................................................................154
Defining a strongly typed UDT................................................................................................ 155
Examples: Using strongly typed UDTs.................................................................................... 156
Using weakly typed UDTs............................................................................................................. 159
Defining a weakly typed UDT.................................................................................................. 160
Altering a table to use a weakly typed UDT............................................................................160
Weakly typed UDTs and database catalogs............................................................................160
Examples: Using UDTs, UDFs, and LOBs........................................................................................... 161
Example: Defining the UDT and UDFs ......................................................................................... 161
Example: Using the LOB function to populate the database.......................................................162
Example: Using UDFs to query instances of UDTs....................................................................... 162
Example: Using LOB locators to manipulate UDT instances....................................................... 163
Using DataLinks..................................................................................................................................163
Linking control levels in DataLinks............................................................................................... 164
NO LINK CONTROL..................................................................................................................164
FILE LINK CONTROL with FS permissions............................................................................. 164
FILE LINK CONTROL with DB permissions.............................................................................164
Working with DataLinks................................................................................................................ 165
Sort sequences and normalization in SQL.............................................................................................. 167
Sort sequence used with ORDER BY and row selection................................................................... 167
Sort sequence and ORDER BY......................................................................................................168
Sort sequence and row selection................................................................................................. 169
Sort sequence and views................................................................................................................... 170
Sort sequence and the CREATE INDEX statement............................................................................171
Sort sequence and constraints.......................................................................................................... 171
ICU sort sequence..............................................................................................................................171
Normalization..................................................................................................................................... 172
Data protection........................................................................................................................................ 173
Security for SQL objects.....................................................................................................................173
Authorization ID............................................................................................................................174
Views.............................................................................................................................................174
Column masks and row permissions........................................................................................... 174
Auditing.........................................................................................................................................174
Data integrity...................................................................................................................................... 175
Concurrency..................................................................................................................................175
Journaling..................................................................................................................................... 176
Commitment control.....................................................................................................................177
Savepoints.................................................................................................................................... 181
Atomic operations........................................................................................................................ 182
Constraints....................................................................................................................................184
vi
Adding and using check constraints....................................................................................... 184
Save and restore SQL objects.......................................................................................................185
Damage tolerance.........................................................................................................................186
Index recovery.............................................................................................................................. 186
Catalog integrity............................................................................................................................187
User auxiliary storage pool...........................................................................................................187
Independent auxiliary storage pool............................................................................................. 187
Routines and triggers...............................................................................................................................188
Stored procedures..............................................................................................................................188
Defining an external procedure.................................................................................................... 189
Defining an SQL procedure...........................................................................................................189
Defining a procedure with default parameters............................................................................ 194
Calling a stored procedure........................................................................................................... 195
Using the CALL statement where procedure definition exists...............................................196
Using the embedded CALL statement where no procedure definition exists....................... 197
Using the embedded CALL statement with an SQLDA...........................................................197
Using the dynamic CALL statement where no CREATE PROCEDURE exists......................... 198
Examples: CALL statements................................................................................................... 199
Returning result sets from stored procedures.............................................................................202
Example 1: Calling a stored procedure that returns a single result set................................ 203
Example 2: Calling a stored procedure that returns a result set from a nested procedure..204
Writing a program or SQL procedure to receive the result sets from a stored procedure..........208
Indicator variables and stored procedures..................................................................................213
Returning a completion status to the calling program................................................................ 215
Passing parameters from Db2 to external procedures............................................................... 215
Parameter style SQL................................................................................................................215
Parameter style GENERAL...................................................................................................... 217
Parameter style GENERAL WITH NULLS................................................................................ 217
Parameter style DB2GENERAL............................................................................................... 218
Parameter style Java...............................................................................................................218
Parameter passing conventions for stored procedures and user-defined functions.......................218
Dynamic compound statement..........................................................................................................223
Using user-defined functions.............................................................................................................224
UDF concepts................................................................................................................................225
Writing UDFs as SQL functions..................................................................................................... 227
Example: SQL scalar UDFs......................................................................................................227
Example: SQL table UDFs....................................................................................................... 227
Writing UDFs as external functions.............................................................................................. 228
Registering UDFs..................................................................................................................... 228
Passing arguments from Db2 to external functions...............................................................230
Table function considerations.................................................................................................235
Error processing for UDFs....................................................................................................... 236
Threads considerations...........................................................................................................236
Parallel processing.................................................................................................................. 237
Fenced or unfenced considerations....................................................................................... 237
Defining UDFs with default parameters....................................................................................... 237
Examples: UDF code.....................................................................................................................238
Example: Square of a number UDF.........................................................................................238
Example: Counter....................................................................................................................239
Example: Weather table function........................................................................................... 240
Using UDFs in SQL statements..................................................................................................... 245
Using parameter markers or the NULL values as function arguments.................................. 245
Using qualified function references........................................................................................246
Using unqualified function references....................................................................................246
Invoking UDFs with named arguments.................................................................................. 247
Summary of function references............................................................................................ 247
SQL routine names............................................................................................................................. 249
Triggers............................................................................................................................................... 250
vii
SQL triggers...................................................................................................................................251
BEFORE SQL triggers...............................................................................................................251
AFTER SQL triggers................................................................................................................. 252
Multiple event SQL triggers.....................................................................................................253
INSTEAD OF SQL triggers....................................................................................................... 254
Handlers in SQL triggers......................................................................................................... 256
Using SIGNAL within an SQL trigger....................................................................................... 257
SQL trigger transition tables................................................................................................... 258
External triggers........................................................................................................................... 259
Varying length parameter lists for external procedures and functions ........................................... 259
Using the INCLUDE statement...........................................................................................................260
Array support in SQL procedures and functions............................................................................... 264
Debugging an SQL routine..................................................................................................................266
Obfuscating an SQL routine or SQL trigger........................................................................................267
Managing SQL and external routine objects......................................................................................268
Improving performance of procedures and functions...................................................................... 269
Improving implementation of procedures and functions............................................................270
Redesigning routines for performance........................................................................................ 272
Working with JSON data..........................................................................................................................273
JSON concepts................................................................................................................................... 273
Using JSON_TABLE............................................................................................................................ 276
Generating JSON data........................................................................................................................280
HTTP functions overview.........................................................................................................................285
Using SQL in different environments...................................................................................................... 291
Using a cursor.....................................................................................................................................291
Types of cursors............................................................................................................................291
Examples: Using a cursor............................................................................................................. 292
Step 1: Defining the cursor..................................................................................................... 294
Step 2: Opening the cursor..................................................................................................... 295
Step 3: Specifying what to do when the end of data is reached............................................295
Step 4: Retrieving a row using a cursor.................................................................................. 296
Step 5a: Updating the current row......................................................................................... 296
Step 5b: Deleting the current row.......................................................................................... 297
Step 6: Closing the cursor.......................................................................................................297
Example: Using the OFFSET clause with a cursor....................................................................... 298
Using the multiple-row FETCH statement................................................................................... 298
Multiple-row FETCH using a host structure array.................................................................. 299
Multiple-row FETCH using a row storage area....................................................................... 300
Unit of work and open cursors..................................................................................................... 302
Dynamic SQL applications................................................................................................................. 303
Running dynamic SQL statements............................................................................................... 303
CCSID of dynamic SQL statements.............................................................................................. 303
Processing non-SELECT statements............................................................................................ 304
Using the PREPARE and EXECUTE statements...................................................................... 304
Processing SELECT statements and using a descriptor.............................................................. 305
Fixed-list SELECT statements.................................................................................................305
Varying-list SELECT statements............................................................................................. 306
SQL descriptor areas...............................................................................................................306
SQLDA format..........................................................................................................................307
Example: A SELECT statement for allocating storage for SQLDA.......................................... 309
Example: A SELECT statement using an allocated SQL descriptor....................................... 313
Parameter markers................................................................................................................. 316
Using interactive SQL......................................................................................................................... 317
Starting interactive SQL................................................................................................................318
Using the statement entry function............................................................................................. 319
Prompting..................................................................................................................................... 319
Syntax checking...................................................................................................................... 321
Statement processing mode...................................................................................................321
viii
Subqueries.............................................................................................................................. 321
CREATE TABLE prompting.......................................................................................................321
Entering DBCS data................................................................................................................. 321
Using the list selection function................................................................................................... 322
Example: Using the list selection function............................................................................. 322
Session services description........................................................................................................ 324
Exiting interactive SQL..................................................................................................................325
Using an existing SQL session...................................................................................................... 326
Recovering an SQL session...........................................................................................................326
Accessing remote databases with interactive SQL......................................................................326
Using the SQL statement processor.................................................................................................. 328
Execution of statements after errors occur................................................................................. 330
Commitment control in the SQL statement processor................................................................ 330
Source listing for the SQL statement processor.......................................................................... 330
Using the RUNSQL CL command....................................................................................................... 331
Distributed relational database function and SQL..................................................................................333
Db2 for i distributed relational database support.............................................................................334
Db2 for i distributed relational database example program.............................................................335
SQL package support......................................................................................................................... 336
Valid SQL statements in an SQL package.....................................................................................336
Considerations for creating an SQL package............................................................................... 337
CRTSQLPKG authorization...................................................................................................... 337
Creating a package on a database other than Db2 for i......................................................... 337
Target release (TGTRLS) parameter....................................................................................... 337
SQL statement size................................................................................................................. 338
Statements that do not require a package............................................................................. 338
Package object type................................................................................................................ 338
ILE programs and service programs.......................................................................................338
Package creation connection..................................................................................................338
Unit of work............................................................................................................................. 338
Creating packages locally....................................................................................................... 339
Labels...................................................................................................................................... 339
Consistency token................................................................................................................... 339
SQL and recursion................................................................................................................... 339
CCSID considerations for SQL........................................................................................................... 339
Connection management and activation groups.............................................................................. 340
Source code for PGM1.................................................................................................................. 340
Source code for PGM2.................................................................................................................. 341
Source code for PGM3.................................................................................................................. 341
Multiple connections to the same relational database............................................................... 343
Implicit connection management for the default activation group............................................ 344
Implicit connection management for nondefault activation groups...........................................344
Distributed support............................................................................................................................ 345
Determining the connection type.................................................................................................345
Connect and commitment control restrictions............................................................................347
Determining the connection status..............................................................................................348
Distributed unit of work connection considerations....................................................................349
Ending connections...................................................................................................................... 350
Distributed unit of work..................................................................................................................... 350
Managing distributed unit of work connections...........................................................................350
Checking the connection status................................................................................................... 352
Cursors and prepared statements............................................................................................... 352
DRDA stored procedure considerations............................................................................................ 353
WebSphere MQ with Db2........................................................................................................................ 353
WebSphere MQ messages................................................................................................................. 354
WebSphere MQ message handling.............................................................................................. 354
Db2 MQ services..................................................................................................................... 354
Db2 MQ policies...................................................................................................................... 355
ix
Db2 MQ functions...............................................................................................................................355
Db2 MQ dependencies................................................................................................................. 357
Db2 MQ tables....................................................................................................................................357
Db2 MQ CCSID conversion.................................................................................................................365
Websphere MQ transactions..............................................................................................................366
Basic messaging with WebSphere MQ.............................................................................................. 367
Sending messages with WebSphere MQ........................................................................................... 368
Retrieving messages with WebSphere MQ........................................................................................368
Application to application connectivity with WebSphere MQ...........................................................369
Db2 for i sample tables............................................................................................................................370
Sample tables.....................................................................................................................................370
Department table (DEPARTMENT)...............................................................................................370
DEPARTMENT..........................................................................................................................371
Employee table (EMPLOYEE)........................................................................................................372
EMPLOYEE............................................................................................................................... 374
Employee photo table (EMP_PHOTO).......................................................................................... 375
EMP_PHOTO............................................................................................................................ 375
Employee resumé table (EMP_RESUME)..................................................................................... 375
EMP_RESUME.......................................................................................................................... 376
Employee to project activity table (EMPPROJACT)..................................................................... 376
EMPPROJACT.......................................................................................................................... 377
Project table (PROJECT)...............................................................................................................379
PROJECT..................................................................................................................................380
Project activity table (PROJACT).................................................................................................. 381
PROJACT................................................................................................................................. 382
Activity table (ACT)....................................................................................................................... 384
ACT.......................................................................................................................................... 384
Class schedule table (CL_SCHED)................................................................................................385
CL_SCHED............................................................................................................................... 385
In-tray table (IN_TRAY)................................................................................................................385
IN_TRAY.................................................................................................................................. 386
Organization table (ORG)..............................................................................................................387
ORG..........................................................................................................................................387
Staff table (STAFF)........................................................................................................................387
STAFF.......................................................................................................................................388
Sales table (SALES)...................................................................................................................... 389
SALES...................................................................................................................................... 389
Sample XML tables.............................................................................................................................390
Product table (PRODUCT)............................................................................................................ 391
PRODUCT.................................................................................................................................391
Purchase order table (PURCHASEORDER).................................................................................. 392
PURCHASEORDER...................................................................................................................393
Customer table (CUSTOMER)....................................................................................................... 396
CUSTOMER.............................................................................................................................. 396
Catalog table (CATALOG).............................................................................................................. 398
CATALOG..................................................................................................................................398
Suppliers table (SUPPLIERS)....................................................................................................... 398
SUPPLIERS.............................................................................................................................. 398
Inventory table (INVENTORY)...................................................................................................... 398
INVENTORY............................................................................................................................. 399
Product Supplier table (PRODUCTSUPPLIER)............................................................................. 399
PRODUCTSUPPLIER................................................................................................................399
Db2 for i CL command descriptions...................................................................................................399
Notices..............................................................................................................401
Programming interface information........................................................................................................ 402
Trademarks.............................................................................................................................................. 402
x
Terms and conditions.............................................................................................................................. 403
xi
xii
SQL programming
The Db2® for IBM® i database provides a wide range of support for Structured Query Language (SQL).
The examples of SQL statements shown in this topic collection are based on the sample tables and
assume that the following statements are true:
• Each SQL example is shown on several lines, with each clause of the statement on a separate line.
• SQL keywords are highlighted.
• Table names provided in the sample tables use the schema CORPDATA. Table names that are not found
in the Sample Tables should use schemas you create.
• The SQL naming convention is used.
• The APOST and APOSTSQL precompiler options are assumed although they are not the default options
in COBOL. Character string literals within SQL and host language statements are delimited by single-
quotation marks (').
• A sort sequence of *HEX is used, unless otherwise noted.
Whenever the examples vary from these assumptions, it is stated.
Because this topic collection is for the application programmer, most of the examples are shown as if
they were written in an application program. However, many examples can be slightly changed and run
interactively by using interactive SQL. The syntax of an SQL statement, when using interactive SQL, differs
slightly from the format of the same statement when it is embedded in a program.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 399.
Related concepts
Embedded SQL programming
Related reference
Db2 for i sample tables
These sample tables are referred to and used in the SQL programming and the SQL reference topic
collections.
Db2 for i SQL reference
SQL concepts
Db2 for i SQL consists of several main parts, such as SQL runtime support, precompilers, and interactive
SQL.
• SQL runtime support
SQL run time parses SQL statements and runs any SQL statements. This support is part of the IBM i
licensed program, which allows applications that contain SQL statements to be run on systems where
the IBM Db2 Query Manager and SQL Development Kit for i licensed program is not installed.
• SQL precompilers
SQL precompilers support precompiling embedded SQL statements in host languages. The following
languages are supported:
– ILE C
– ILE C++
– ILE COBOL
– COBOL
– PL/I
– RPG III (part of RPG)
– ILE RPG
The SQL host language precompilers prepare an application program that contains SQL statements. The
host language compilers then compile the precompiled host source programs. For more information
about precompiling, see Preparing and running a program with SQL statements in the Embedded SQL
programming information. The precompiler support is part of the IBM Db2 Query Manager and SQL
Development Kit for i licensed program.
• Run SQL Scripts in IBM i Access Client Solutions (ACS)
For information about ACS, see https://www.ibm.com/support/pages/ibm-i-access-client-solutions
• Run SQL Statements (RUNSQLSTM) CL command
The RUNSQLSTM command can be used to run a series of SQL statements that are stored in a source
file or a source stream file. For more information about the RUNSQLSTM command, see “Using the SQL
statement processor” on page 328.
SQL programming 3
• Run SQL (RUNSQL) CL command
The RUNSQL command can be used to run a single SQL statements. For more information about the
RUNSQL command, see “Using the RUNSQL CL command” on page 331.
• DB2® Query Manager
DB2 Query Manager provides a prompt-driven interactive interface that allows you to create data, add
data, maintain data, and run reports on the databases. Query Manager is part of the IBM Db2 Query
Manager and SQL Development Kit for i licensed program. For more information, see Query Manager
Use .
Related concepts
Distributed database programming
schema/table
or
schema.table
schema.table
Related reference
Qualification of unqualified object names
SQL programming 5
Types of SQL statements
There are several basic types of SQL statements. They are listed here according to their functions.
• SQL schema statements, also known as data definition language (DDL) statements
• SQL data and data change statements, also known as data manipulation language (DML) statements
• Dynamic SQL statements
• Embedded SQL host language statements
DELETE CONNECT
INSERT DISCONNECT
MERGE RELEASE
TRUNCATE SET CONNECTION
UPDATE
SQL statements can operate on objects that are created by SQL as well as externally described physical
files and single-format logical files. They cannot refer to the interactive data definition utility (IDDU)
dictionary definition for program-described files. Program-described files appear as a table with only a
single column.
Related concepts
Data definition language
Data definition language (DDL) describes the portion of SQL that creates, alters, and deletes database
objects. These database objects include schemas, tables, views, sequences, catalogs, indexes, variables,
masks, permissions, and aliases.
Data manipulation language
Data manipulation language (DML) describes the portion of SQL that manipulates or controls data.
Related reference
Db2 for i SQL reference
SQL programming 7
SQL diagnostics area
The SQL diagnostics area maintained by the database manager provides information about the SQL
statement that is most recently run. Your application program can access the SQL diagnostics area using
the GET DIAGNOSTICS statement.
Related concepts
Using the SQL diagnostics area
Related reference
GET DIAGNOSTICS statement
SQL objects
SQL objects are schemas, journals, catalogs, tables, aliases, views, indexes, constraints, triggers, masks,
permissions, sequences, stored procedures, user-defined functions, user-defined types, global variables,
and SQL packages. SQL creates and maintains these objects as system objects.
Schemas
A schema provides a logical grouping of SQL objects. A schema consists of a library, a journal, a journal
receiver, a catalog, and, optionally, a data dictionary.
Tables, views, and system objects (such as programs) can be created, moved, or restored into any system
library. All system files can be created or moved into an SQL schema if the SQL schema does not contain a
data dictionary. If the SQL schema contains a data dictionary then:
• Source physical files or nonsource physical files with one member can be created, moved, or restored
into an SQL schema.
• Logical files cannot be placed in an SQL schema because they cannot be described in the data
dictionary.
You can create and own many schemas.
Catalogs
An SQL catalog is a collection of tables and views that describe tables, views, indexes, procedures,
functions, sequences, triggers, masks, permissions, variables, constraints, programs, packages, and XSR
objects.
This information is contained in a set of cross-reference tables in libraries QSYS and QSYS2. In each SQL
schema there is a set of views built over the catalog tables that contains information about the objects in
the schema.
A catalog is automatically created when you create a schema. You cannot drop or explicitly change the
catalog.
Related reference
Catalog
Aliases
An alias is an alternate name for a table or view.
You can use an alias to refer to a table or view in those cases where an existing table or view can be
referred to. Additionally, aliases can refer to a specific member of a table. An alias can also be a three-part
name with an RDB name that refers to a remote system.
Related reference
Aliases
Views
A view appears like a table to an application program. However, a view contains no data and only logically
represents one or more tables over which it is created.
A view can contain all the columns and rows of the given tables or a subset of them. The columns can
be arranged differently in a view than they are in the tables from which they are taken. A view in SQL is a
special form of a nonkeyed logical file.
Related reference
Views
Indexes
An SQL index is a subset of the data in the columns of a table that are logically arranged in either
ascending or descending order.
Each index defines a set of columns or expressions as keys. These keys are used for ordering, grouping,
and joining. The index is used by the system for faster data retrieval.
Db2 for i supports two types of indexes: binary radix tree indexes and encoded vector indexes (EVIs).
Creating an index is optional. You can create any number of indexes. You can create or drop an index
at any time. The index is automatically maintained by the system. However, because the indexes are
maintained by the system, a large number of indexes can adversely affect the performance of the
applications that change the table.
SQL programming 9
Related concepts
Creating an index strategy
Related reference
CREATE INDEX
Constraints
A constraint is a rule enforced by the database manager to limit the values that can be inserted, deleted,
or updated in a table.
Db2 for i supports the following constraints:
• Unique constraints
A unique constraint is the rule that the values of the key are valid only if they are unique. You can create
a unique constraint using the CREATE TABLE or ALTER TABLE statement. Although the CREATE INDEX
statement can create a unique index that also guarantees uniqueness, such an index is not a constraint.
Unique constraints are enforced during the execution of INSERT and UPDATE statements. A PRIMARY
KEY constraint is a form of the UNIQUE constraint. The difference is that a PRIMARY KEY cannot contain
any nullable columns.
• Referential constraints
A referential constraint is the rule that the values of the foreign key are valid only if one of the following
conditions is met:
– They appear as values of a parent key.
– Some component of the foreign key is null.
Referential constraints are enforced during the execution of INSERT, UPDATE, and DELETE statements.
• Check constraints
A check constraint is the rule that limits the values allowed in a column or group of columns. You can
create a check constraint using the CREATE TABLE or ALTER TABLE statement. Check constraints are
enforced during the execution of INSERT and UPDATE statements. To satisfy the constraint, each row
of data inserted or updated in the table must make the specified condition either TRUE or unknown
(because of a null value).
Related reference
Constraints
The Db2 for i database supports unique, referential, and check constraints.
Triggers
A trigger is a set of actions that runs automatically whenever a specified event occurs to a specified table
or view.
An event can be an insert, an update, a delete, or a read operation. A trigger can run either before or after
the event. Db2 for i supports SQL insert, update, and delete triggers and external triggers.
Related tasks
Triggering automatic events in your database
Stored procedures
A stored procedure is a program that can be called with the SQL CALL statement.
Db2 for i supports external procedures and SQL procedures. An external procedure can be any system
program, service program, or REXX procedure. It cannot be a System/36 program or procedure. An SQL
procedure is defined entirely in SQL and can contain SQL statements, including SQL control statements.
Related concepts
Stored procedures
Sequences
A sequence is a data area object that provides a quick and easy way of generating unique numbers.
You can use a sequence to replace an identity column or a user-generated numeric column. A sequence
has uses similar to these alternatives.
Related reference
Creating and using sequences
Sequences are similar to identity columns in that they both generate unique values. However, sequences
are objects that are independent of any tables. You can use sequences to generate values quickly and
easily.
Global variables
A global variable is a named variable that can be created, accessed, and modified using SQL.
A global variable can provide a unique value for a session. The variable can be used as part of any
expression in places such as a query, a create view, or an insert statement.
User-defined functions
A user-defined function is a program that can be called like any built-in functions.
Db2 for i supports external functions, SQL functions, and sourced functions. An external function can be
any system ILE program or service program. An SQL function is defined entirely in SQL and can contain
SQL statements, including SQL control statements. A sourced function is built over any built-in or any
existing user-defined function. You can create a scalar function or a table function as either an SQL
function or an external function.
Related concepts
Using user-defined functions
In writing SQL applications, you can implement some actions or operations as a user-defined function
(UDF) or as a subroutine in your application. Although it might appear easier to implement new operations
as subroutines, you might want to consider the advantages of using a UDF instead.
User-defined types
A user-defined type is a data type that you can define independently of the data types that are provided by
the database management system.
Distinct data types map to built-in types. Array data types are defined using a built-in type as the element
type and a maximum cardinality value.
Related concepts
User-defined distinct types
A user-defined distinct type (UDT) allows the Db2 for i built-in data types to be reused for more specific
purposes.
XSR objects
An XSR object is one or more XML schema documents that have been registered in the XML schema
repository with the same name.
You can use an XSR object during validation of an XML document or during annotated XML schema
decomposition.
SQL programming 11
SQL packages
An SQL package is an object that contains the control structure produced when the SQL statements in an
application program are bound to a remote relational database management system (DBMS).
The DBMS uses the control structure to process SQL statements encountered while running the
application program.
SQL packages are created when a relational database name (RDB parameter) is specified on a Create SQL
(CRTSQLxxx) command and a program object is created. Packages can also be created with the Create
SQL Package (CRTSQLPKG) command.
Note: The xxx in this command refers to the host language indicators: CI for ILE C, CPPI for ILE C++, CBL
for COBOL, CBLI for ILE COBOL, PLI for PL/I, RPG for RPG/400®, and RPGI for ILE RPG.
SQL packages can also be created with the Process Extended Dynamic SQL (QSQPRCED) API. The SQL
packages mentioned within this topic collection refer exclusively to distributed program SQL packages.
The QSQPRCED API uses SQL packages to provide extended dynamic SQL support.
Related reference
Distributed relational database function and SQL
A distributed relational database consists of a set of SQL objects that are spread across interconnected
computer systems.
Process Extended Dynamic SQL (QSQPRCED) API
With a nondistributed ILE Db2 for i program, you might need to manage the original source, the modules,
and the resulting program or service program. The following figure shows the objects involved and
the steps that happen during the precompile and compile processes for a nondistributed ILE Db2
for i program when OBJTYPE(*PGM) is specified on the precompile command. The user source file
precompiles the source to a temporary source file member. This member is then compiled into a module
that binds to a program.
With a distributed ILE Db2 for i program, you must manage the original source, module objects, the
resulting program or service program, and the resulting packages. An SQL package can be created for
each distributed module in a distributed ILE program or service program. The following figure shows
the objects and the steps that occur during the precompile and compile processes for a distributed ILE
Db2 for i program. The user source file precompiles the source to a temporary source file member. This
member is then compiled into a module that binds to a program. After the program is created, an SQL
package is created to hold the program.
Note: The access plans associated with the Db2 for i distributed program object are not created until the
program is run locally.
Related tasks
Preparing and running a program with SQL statements
SQL programming 13
• Calls to the SQL runtime support, which have replaced embedded SQL statements
• Parsed and syntax-checked SQL statements
By default, the precompiler calls the host language compiler.
Related tasks
Preparing and running a program with SQL statements
Program
A program is an object that is created as a result of the compilation process for non-ILE compilations or as
a result of the bind process for ILE compilations.
An access plan is a set of internal structures and information that tells SQL how to run an embedded SQL
statement most effectively. It is created only when the program has been successfully created. Access
plans are not created during program creation for SQL statements if the statements refer to an object,
such as a table or view, that cannot be found or to which you are not authorized.
The access plans for such statements are created when the program is run. If, at that time, the table
or view still cannot be found or you are still not authorized, a negative SQLCODE is returned. Access
plans are stored and maintained in the program object for non-distributed SQL programs and in the SQL
package for distributed SQL programs.
SQL package
An SQL package contains the access plans for a distributed SQL program.
An SQL package is an object that is created when:
• You successfully create a distributed SQL program by specifying the relational database (RDB)
parameter on the CREATE SQL (CRTSQLxxx) commands.
• You run the Create SQL Package (CRTSQLPKG) command.
When a distributed SQL program is created, the name of the SQL package and an internal consistency
token are saved in the program. They are used at run time to find the SQL package and to verify that
the SQL package is correct for this program. Because the name of the SQL package is critical for running
distributed SQL programs, an SQL package cannot be:
• Moved
• Renamed
• Duplicated
• Restored to a different library
Module
A module is an Integrated Language Environment® (ILE) object that you create by compiling source code
using the Create Module (CRTxxxMOD) command (or any of the Create Bound Program (CRTBNDxxx)
commands, where xxx is C, CBL, CPP, or RPG).
You can run a module only if you use the Create Program (CRTPGM) command to bind it into a program.
You typically bind several modules together, but you can bind a module by itself. Modules contain
information about the SQL statements; however, the SQL access plans are not created until the modules
are bound into either a program or service program.
Related reference
Create Program (CRTPGM) command
Creating a schema
A schema provides a logical grouping of SQL objects. To create a schema, use the CREATE SCHEMA
statement.
A schema consists of a library, a journal, a journal receiver, a catalog, and optionally, a data dictionary.
Tables, views, and system objects (such as programs) can be created, moved, or restored into any system
libraries. All system files can be created or moved into an SQL schema if the SQL schema does not contain
a data dictionary. If the SQL schema contains a data dictionary then:
• Source physical files or non-source physical files with one member can be created, moved, or restored
into an SQL schema.
• Logical files cannot be placed in an SQL schema because they cannot be described in the data
dictionary.
You can create and own many schemas.
You can create a schema using the CREATE SCHEMA statement. For example, create a schema called
DBTEMP:
Related reference
CREATE SCHEMA
Creating a table
A table can be visualized as a two-dimensional arrangement of data that consists of rows and columns. To
create a table, use the CREATE TABLE statement.
The row is the horizontal part containing one or more columns. The column is the vertical part containing
one or more rows of data of one data type. All data for a column must be of the same type. A table in SQL
is a keyed or non-keyed physical file.
You can create a table using the CREATE TABLE statement. You provide a name for the table. If the table
name is not a valid system object name, you can use the optional FOR SYSTEM NAME clause to specify a
system name.
The definition includes the names and attributes of its columns. The definition can include other
attributes of the table, such as the primary key.
SQL programming 15
Example: Given that you have administrative authority, create a table named 'INVENTORY' with the
following columns:
• Part number: Integer between 1 and 9999, and must not be null
• Description: Character of length 0 to 24
• Quantity on hand: Integer between 0 and 100000
The primary key is PARTNO.
Related concepts
Data types
To make this key a unique key, replace the keyword PRIMARY with UNIQUE.
You can remove a constraint using the same ALTER TABLE statement:
SQL programming 17
ON DELETE SET NULL ON UPDATE RESTRICT,
PHONENO CHAR(4),
HIREDATE DATE,
JOB CHAR(8),
EDLEVEL SMALLINT NOT NULL,
SEX CHAR(1),
BIRTHDATE DATE,
SALARY DECIMAL(9,2),
BONUS DECIMAL(9,2),
COMM DECIMAL(9,2),
CONSTRAINT UNIQUE_LNAME_IN_DEPT UNIQUE (WORKDEPT, LASTNAME));
In this case, the DEPARTMENT table has a column of unique department numbers (DEPTNO) which
functions as a primary key, and is a parent table in two constraint relationships:
REPORTS_TO_EXISTS
is a self-referencing constraint in which the DEPARTMENT table is both the parent and the dependent
in the same relationship. Every non-null value of ADMRDEPT must match a value of DEPTNO. A
department must report to an existing department in the database. The DELETE CASCADE rule
indicates that if a row with a DEPTNO value n is deleted, every row in the table for which the
ADMRDEPT is n is also deleted.
WORKDEPT_EXISTS
establishes the EMPLOYEE table as a dependent table, and the column of employee department
assignments (WORKDEPT) as a foreign key. Thus, every value of WORKDEPT must match a value of
DEPTNO. The DELETE SET NULL rule says that if a row is deleted from DEPARTMENT in which the
value of DEPTNO is n, then the value of WORKDEPT in EMPLOYEE is set to null in every row in which
the value was n. The UPDATE RESTRICT rule says that a value of DEPTNO in DEPARTMENT cannot be
updated if there are values of WORKDEPT in EMPLOYEE that match the current DEPTNO value.
Constraint UNIQUE_LNAME_IN_DEPT in the EMPLOYEE table causes LASTNAME to be unique within a
department. While this constraint is unlikely, it illustrates how a constraint made up of several columns
can be defined at the table level.
Check pending
Referential constraints and check constraints can be in a check pending state, where potential violations
of the constraints exist.
For referential constraints, a violation occurs when potential mismatches exist between parent and
foreign keys. For check constraints, a violation occurs when potential values exist in columns that are
limited by the check constraint. When the system determines that a constraint might have been violated
(such as after a restore operation), the constraint is marked as check pending. When this happens,
restrictions are placed on the use of tables involved in the constraint. For referential constraints, the
following restrictions apply:
• No input or output operations are allowed on the dependent file.
• Only read and insert operations are allowed on the parent file.
Related reference
CREATE TABLE
SQL programming 19
Creating a table using AS
You can create a table from the result of a SELECT statement. To create this type of table, use the CREATE
TABLE AS statement.
All of the expressions that can be used in a SELECT statement can be used in a CREATE TABLE AS
statement. You can also include all of the data from the table or tables that you are selecting from.
For example, create a table named EMPLOYEE3 that includes a subset of column definitions and data
from the EMPLOYEE table where the WORKDEPT = D11.
If the specified table or view contains an identity column, you must specify the option INCLUDING
IDENTITY on the CREATE TABLE statement if you want the identity column to exist in the new table.
The default behavior for CREATE TABLE is EXCLUDING IDENTITY. There are similar options to include
the default value, the hidden attribute, and the row change timestamp attribute. The WITH NO DATA
clause indicates that the column definitions are to be copied without the data. If you want to include
the data in the new table EMPLOYEE3, include the WITH DATA clause. If the specified query includes a
non-SQL-created physical file or logical file, any non-SQL result attributes are removed.
Related concepts
Retrieving data using the SELECT statement
The SELECT statement tailors your query to gather data. You can use the SELECT statement to retrieve a
specific row or retrieve data in a specific way.
Related reference
Creating a table with remote server data
You can create a table on the local server that references one or more tables on a remote server.
CREATE TABLE
This materialized query table specifies that the table is not populated at the time that it is created
by using the DATA INITIALLY DEFERRED clause. REFRESH DEFERRED indicates that changes made to
TRANS are not reflected in STRANS. Additionally, this table is maintained by the user, enabling the user to
use ALTER, INSERT, DELETE, and UPDATE statements.
To populate the materialized query table or refresh the table after it has been populated, use the
REFRESH TABLE statement. This causes the query associated with the materialized query table to be
You can create a materialized query table from an existing base table as long as the result of the
select-statement provides a set of columns that match the columns in the existing table (same number of
columns and compatible column definitions). For example, create a table TRANSCOUNT. Then, change the
base table TRANSCOUNT into a materialized query table:
To create the table:
Finally, you can change a materialized query table back to a base table. For example:
In this example, the table TRANSCOUNT is not dropped, but it is no longer a materialized query table.
Related concepts
Tables, rows, and columns
A table is a two-dimensional arrangement of data that consists of rows and columns.
SQL programming 21
Then you would tie them together in a versioning relationship like this:
Once versioning is defined for the system-period temporal table, updates and deletes to it cause the
version of the row prior to the change to be inserted as a row in the history table. The special row begin
and row end timestamp columns are set by the system to indicate the time span when the data for the
historical row was the active data.
You can write a query that will automatically return data from both the system-period temporal table and
the history table.
For example, to see what the DEPARTMENT table looked like six months ago, issue the following query:
Related reference
Working with system-period temporal tables
CREATE TABLE
ALTER TABLE
This table is created in QTEMP. To reference the table using a schema name, use either SESSION or
QTEMP. You can issue SELECT, INSERT, UPDATE, and DELETE statements against this table, the same as
any other table. You can drop this table by issuing the DROP TABLE statement:
Related reference
DECLARE GLOBAL TEMPORARY TABLE
The following restrictions apply to using a remote server as the source for the new table:
• The materialized query table clauses are not allowed.
• A column with a FIELDPROC cannot be listed in the select list.
• The copy options cannot be specified if the remote server is Db2 for LUW or Db2 for z/OS®.
Related reference
Creating a table using AS
You can create a table from the result of a SELECT statement. To create this type of table, use the CREATE
TABLE AS statement.
When a row is inserted into the ORDERS table, the CHANGE_TS column for the row is set to the timestamp
of the insert operation. Any time a row in ORDERS is updated, the CHANGE_TS column for the row is
modified to reflect the timestamp of the update operation.
You can drop the row change timestamp attribute from a column:
The column CHANGE_TS remains as a TIMESTAMP column in the table, but the system no longer
automatically updates timestamp values for this column.
SQL programming 23
• A column defined to contain a generated data change operation column will be updated with an I or U
to indicate whether the last modification was an insert or an update. For a history table, a value of D can
be generated to indicate that the row was deleted.
• A column defined to contain a generated special register value will be assigned the current value of the
special register when the data change operation occurs.
• A column defined to contain a generated built-in global variable value will be assigned the current value
of the global variable when the data change operation occurs.
When you create a table, you can define columns for these generated expressions. For example, create a
table EMPLOYEE with columns called EMPNO, NAME, WORKDEPT, and SALARY. Define auditing columns
to track the type of change, the user who made the change, the application that made the change, and the
qualified job name where the change originated.
When you add a generated expression column to an existing table, defining the IMPLICITLY HIDDEN
attribute for the column as well can prevent existing applications that use SQL from requiring
modifications. Hidden columns are excluded when a SELECT *, an INSERT without a column list, or an
UPDATE using ROW determines its implicit list of columns. The only time a hidden column is included is
when it is explicitly mentioned by name.
These auditing columns can be especially useful when using a system-period temporal table. Since all
the historical rows are kept in the corresponding history table, an auditing column will complement the
history by recording information such as who was responsible for each change.
Related reference
CREATE TABLE
Using a system-period temporal table for tracking auditing information
This column is defined with a starting value of 500, incremented by 1 for every new row inserted, and will
fail when the maximum value is reached. In this example, the maximum value for the identity column is
the maximum value for the data type. Because the data type is defined as SMALLINT, the range of values
that can be assigned to ORDERNO is from 500 to 32767. Once the identity column value reaches 32767,
the range of values has been exhausted and no additional rows can be inserted.
The column ORDERNO remains as a SMALLINT column, but the identity attribute is dropped. The system
will no longer generate values for this column.
Related reference
Comparison of identity columns and sequences
While identity columns and sequences are similar in many ways, there are also differences.
Inserting values into an identity column
You can insert a value into an identity column or allow the system to insert a value for you.
Updating an identity column
You can update the value in an identity column to a specified value or have the system generate a new
value.
Using ROWID
Using ROWID is another way to have the system assign a unique value to a column. ROWID is similar to
identity columns. But rather than being an attribute of a numeric column, it is a separate data type.
To create a table similar to the identity column example:
SQL programming 25
NOCYCLE
CACHE 24;
This sequence is defined with a starting value of 500, incremented by 1 for every use, and will not recycle
when the maximum value is reached. In this example, the maximum value for the sequence is 1000. Once
1000 is generated, no additional values can be provided and an error is issued.
After this sequence is created, you can insert values into a column using the sequence. For example,
insert the next value of the sequence ORDER_SEQ into a table ORDERS with columns ORDERNO and
CUSTNO.
First, create the table ORDERS:
SELECT *
FROM ORDERS;
In this example, the next value for sequence ORDER is inserted into the ORDERNO column. Issue the
INSERT statement again. Then run the SELECT statement.
You can also insert the previous value for the sequence ORDER by using the PREVIOUS VALUE expression.
You can use NEXT VALUE and PREVIOUS VALUE in the following expressions:
• Within the select-clause of a SELECT statement or SELECT INTO statement as long as the statement
does not contain a DISTINCT keyword, a GROUP BY clause, an ORDER BY clause, a UNION keyword, an
INTERSECT keyword, or an EXCEPT keyword
• Within a VALUES clause of an INSERT statement
• Within the select-clause of the fullselect of an INSERT statement
• Within the SET clause of a searched or positioned UPDATE statement, though NEXT VALUE cannot be
specified in the select-clause of the subselect of an expression in the SET clause
The CREATE SEQUENCE statement provides a way to define an IBM i system name for the generated
object. If the name of the sequence is longer than ten characters, use the FOR SYSTEM NAME clause to
specify the system name to be assigned to the object. This example shows both names being provided
on the CREATE SEQUENCE statement. Either name can be used when referencing the sequence in an SQL
statement.
You can alter a sequence by issuing the ALTER SEQUENCE statement. Sequences can be altered in the
following ways:
• Restarting the sequence
• Changing the increment between future sequence values
• Setting or eliminating the minimum or maximum values
• Changing the number of cached sequence numbers
• Changing the attribute that determines whether the sequence can cycle or not
• Changing whether sequence numbers must be generated in order of request
For example, change the increment of values of sequence ORDER from 1 to 5:
After this change is complete, run the INSERT statement again and then the SELECT statement. Now the
table contains the following columns.
Notice that the next value that the sequence uses is a 528. At first glance, this number appears to be
incorrect. However, look at the events that lead up to this assignment. First, when the sequence was
originally create, a cache value of 24 was assigned. The system assigns the first 24 values for this cache.
Next, the sequence was altered. When the ALTER SEQUENCE statement is issued, the system drops the
assigned values and starts up again with the next available value; in this case the original 24 that was
cached, plus the next increment, 5. If the original CREATE SEQUENCE statement did not have the CACHE
clause, the system automatically assigns a default cache value of 20. If that sequence was altered, then
the next available value is 25.
Related concepts
Sequences
A sequence is a data area object that provides a quick and easy way of generating unique numbers.
SQL programming 27
A sequence has the following characteristics:
• A sequence is a system object of type *DTAARA that is not tied to a table.
• A sequence generates sequential values that can be used in any SQL statement.
• There are two expressions used to retrieve the next values in the sequence and to look at the previous
value assigned for the sequence. The PREVIOUS VALUE expression returns the most recently generated
value for the specified sequence for a previous statement within the current session. The NEXT VALUE
expression returns the next value for the specified sequence. The use of these expressions allows the
same value to be used across several SQL statements within several tables.
While these are not all of the characteristics of identity columns and sequences, these characteristics can
help you determine which to use depending on your database design and the applications that use the
database.
Related reference
Creating and altering an identity column
Every time a row is added to a table with an identity column, the identity column value for the new row is
generated by the system.
SQL programming 29
trigger and if the trigger changes the data in the trigger buffer. The database manager will ensure that
the field procedure is called to encode the data that will be inserted into the table.
• For field-decoding, when a stored value is to be field-decoded back into its original value. This occurs
for any value that is:
– Retrieved by an SQL SELECT or FETCH statement, or by a native read operation.
– If the data needs to be copied and the source column has a field procedure, it is possible that the
field procedure may be invoked to decode the data prior to making the copy. Examples include the
SQL statements ALTER TABLE or CREATE TABLE (with a LIKE or as-result-table clause) and the CL
commands CPYF or RGZPFM.
– Is compared to a column with a field procedure. The QAQQINI option
FIELDPROC_ENCODED_COMPARISON is used by the optimizer to decide if the column value is
decoded or if the variable or constant is encoded.
A field procedure is never invoked to process a null value. It is also not invoked for a DELETE operation
without a WHERE clause when the table has no DELETE triggers. The field procedure is invoked for
empty strings.
Recommendation: Avoid encoding blanks in a field procedure. When Db2 for i compares the values of two
strings with different lengths, it temporarily pads the shorter string with the appropriate blank characters
(for example, EBCDIC or double-byte blanks) up to the length of the longer string. If the shorter string is
the value of a column with a field procedure, padding is done to the encoded value, but the pad character
is not encoded. Therefore, if the procedure changes blanks to some other character, encoded blanks at
the end of the longer string are not equal to padded blanks at the end of the shorter string. That situation
can lead to errors; for example, some strings that ought to be equal might not be recognized as such.
Therefore, encoding blanks in a field procedure is not recommended.
SQL programming 31
use the non-SQL interface for data access. This parameter can be useful for field procedure that
mask data.
Supported values are:
– '0' - Not called for key positioning.
– '1' - Called for key positioning.
If a field procedure encounters a masked value on an encode request to build a key value, there are
two actions for the field procedure to take:
– Return SQLSTATE '09501' in parameter 7 which will cause the key positioning operation to fail
with a field procedure error.
– Return the masked value as the encoded value in parameter 6, so that the key positioning
operation can continue using the masked value. In this case, the key positioning operation may or
may not be successful. For example, an RPG SETLL request will likely be successful. However, an
RPG CHAIN operation will likely fail with a record not found error.
Include SQLFP in QSYSINC/H describes these parameters.
Offse
Name t Data Type Description
Table 6. sqlfpOptionalParameterValueDescriptor_T
Offse
Name t Data Type Description
Offse
Name t Data Type Description
sqlfpAllocatedLength 16 unsigned 2-byte integer The allocated length specified for the
column on the CREATE TABLE or ALTER
TABLE statement.
SQL programming 33
• Parameter 3
Input - The structure sqlfpParameterDescription_T containing the decoded data attributes.
• Parameter 4
Not used.
• Parameter 5
Output - The structure sqlfpParameterDescription_T containing the encoded data attributes. The
output sqlfpParameterDescription_T must be valid with the appropriate CCSID, length, precision, and
scale fields set.
• Parameter 6
Not used.
• Parameter 7
Input/Output - The SQLSTATE (character(5)).
• Parameter 8
Input/Output - The message text area (varchar(1000)).
• Parameter 9
Input - Reserved.
Errors returned by a field procedure result in SQLCODE -681 (SQLSTATE '23507'), which is set in the SQL
communication area (SQLCA) and the DB2_RETURNED_SQLCODE and RETURNED_SQLSTATE condition
area item of the SQL diagnostics area. The contents of Parameter 7 and 8 are placed into the tokens,
in SQLCA, as field SQLERRMT and in the SQL Diagnostic area condition area item MESSAGE_TEXT. The
meaning of the error message is determined by the field procedure.
Invalid data in Parameter 5, sqlfpParameterDescription_T, or an invalid length in Parameter 2 results in
SQLCODE -685 (SQLSTATE '58002'). If the database manager is unable to invoke the field procedure then
SQLCODE -682 (SQLSTATE '57010') is returned.
The FPPVL can be redefined to suit the field procedure, and returned as the modified FPPVL, subject to
the following restriction:
• sqlfpOptParmValueListLength must contain the actual length of the modified FPPVL. If no parameter list
is returned, then sqlfpOptParmValueListLength must be set to 8.
The modified FPPVL is recorded in the catalog table QSYS2.SYSFIELDS, and is passed to the field
procedure during field-encoding and field-decoding. The modified FPPVL need not have the format
of a field procedure parameter list, and it need not describe constants by optional parameter value
descriptors.
The nullability attribute of the column may not be changed.
If the encoded data attribute is a character, graphic or XML type, the CCSID value must be set to a valid
CCSID for the data type.
If the column has a non-null default value, the encoded default value must not exceed the length allowed
for the column's default value.
SQL programming 35
Errors returned by a field procedure result in SQLCODE -681 (SQLSTATE '23507'), which is set in the SQL
communication area (SQLCA) and the DB2_RETURNED_SQLCODE and RETURNED_SQLSTATE condition
area item of the SQL diagnostics area. The contents of Parameter 7 and 8 are placed into the tokens,
in SQLCA, as field SQLERRMT and in the SQL Diagnostic area condition area item MESSAGE_TEXT. If the
database manager is unable to invoke the field procedure then SQLCODE -682 (SQLSTATE '57010') is
returned.
The following two field procedure programs demonstrate the same operations being done first in ILE RPG
and then in C. These programs illustrate how a field procedure program could use the IBM i Cryptographic
Services APIs to encrypt and decrypt fixed length character, variable length character, or character LOB
data.
The program demonstrates some of the possibilities with field procedure programs but does not attempt
to handle every possible situation and error. Note how the following items are handled:
• Changing of the encoded data type from the decoded data type
• The addressing differences required for fixed length character, varying length character, and CLOB data.
• Usage of the optional parm structure (sqlfpOptionalParameterValueDescriptor_T).
More information about IBM i Cryptographic Services APIs, see Cryptographic Services APIs
ctl-opt main(SampleFieldProcProgram);
ctl-opt option(*srcstmt);
ctl-opt stgmdl(*inherit);
ctl-opt thread(*concurrent);
/if defined(*crtbndrpg)
ctl-opt actgrp(*caller);
/endif
/copy QSYSINC/QRPGLESRC,QC3CCI
/copy QSYSINC/QRPGLESRC,QUSEC
/copy QSYSINC/QRPGLESRC,SQL
/copy QSYSINC/QRPGLESRC,SQLFP
// QSYSINC/H QC3DTAEN
dcl-pr Qc3EncryptData extproc(*dclcase);
clearData pointer value;
clearDataLen int(10) const;
clearDataFormat char(8) const;
algorithmDesc likeds(QC3D0200); // Qc3_Format_ALGD0200
algorithmDescFormat char(8) const;
keyDesc likeds(T_key_descriptor0200) const;
keyDescFormat char(8) const;
cryptoServiceProvider char(1) const;
cryptoDeviceName char(10) const;
encryptedData pointer value;
lengthOfAreaForEncryptedData int(10) const;
lengthOfEncryptedDataReturned int(10);
errorCode likeds(QUSEC);
end-pr;
// QSYSINC/H QC3DTADE
dcl-pr Qc3DecryptData extproc(*dclcase);
// Other constants
dcl-c KEY_MGMT_SIZE 16;
dcl-c MAX_VARCHAR_SIZE 32767;
dcl-c MAX_CLOB_SIZE 100000;
SQL programming 37
bytes uns(10);
type_indicator char(1);
end-ds;
// Main procedure
dcl-proc SampleFieldProcProgram;
dcl-pi *n EXTPGM('FP_EXV1RPG');
FuncCode uns(5) const;
OptionalParms likeds(T_optional);
DecodedDataType likeds(SQLFPD); // sqlfpParameterDescription_T
DecodedData likeds(T_DECODED_DATA);
EncodedDataType likeds(SQLFPD); // sqlfpParameterDescription_T
EncodedData likeds(T_ENCODED_DATA);
SqlState char(5);
Msgtext varchar(1000); // SQLFMT DS in QSYSINC/SQLFP is an RPG VARCHAR
end-pi;
ErrCode = *allx'00';
ErrCode.QUSBPRV = %size(QUSEC); // Bytes_provided
if FuncCode = 0; // encode
SQL programming 39
: EncryptedDataLen
: ALGD0200
: Qc3_Alg_Block_Cipher
: KeyDesc0200
: Qc3_Key_Parms
: Qc3_Any_CSP
: ' '
: Decrypted_Datap
: DecryptedDataLen
: RtnLen
: ErrCode);
else; // 0 length data
RtnLen = 0;
endif;
// tell the database manager how many characters of data are being returned
select;
when DecodedDataType.SQLFST = SQL_TYP_VARCHAR
or DecodedDataType.SQLFST = SQL_TYP_NVARCHAR;
DecodedData.varchar.len = RtnLen;
when DecodedDataType.SQLFST = SQL_TYP_CLOB
or DecodedDataType.SQLFST = SQL_TYP_NCLOB;
DecodedData.clob.len = RtnLen;
other;
// must be fixed Length and the full number of characters must be
// returned
endsl;
else; // unsupported option -- error
SqlState = '38003';
endif;
end-proc SampleFieldProcProgram;
// procedure FieldCreatedOrAltered
dcl-proc FieldCreatedOrAltered;
dcl-pi *n extproc(*dclcase);
OptionalParms_p pointer value;
DecodedDataType likeds(SQLFPD); // sqlfpParameterDescription_T
EncodedDataType likeds(SQLFPD); // sqlfpParameterDescription_T
SqlState char(5);
Msgtext varchar(1000);
end-pi;
// Note that while optional parameters are not supported on input into
// this fieldproc, it will set information into the structure for
// usage by encode/decode operations. The length of this
// structure must be at least 8 bytes long, so the length is not
// reset.
select;
when DecodedDataType.SQLFST = SQL_TYP_CHAR // Fixed char
or DecodedDataType.SQLFST = SQL_TYP_NCHAR;
// set the encode data type to VarChar
EncodedDataType.SQLFST = SQL_TYP_VARCHAR;
// This example shows how the fieldproc pgm can modify the optional parm data area
to
// store "constant" information to be used by the fieldproc on encode and decode
operations.
// Indicate that the encode type is varchar.
outputOptionalParms.type_indicator = '0';
// Determine the result length by adding one byte for the pad character counter and
// rounding the length up to a multiple of 15-- the AES encryption alogrithm
// will return the encrypted data in a multiple of 15.
// This example also shows how additional data can be stored by the fieldproc
// program in the encrypted data. An additional 16 bytes are added for use by
// the fieldproc program.
// Note that this fieldproc does not check for exceeding the maximum length for
// the data type. There may also be other conditions that are not handled by
// this sample fieldproc program.
EncodedDataType.SQLFL =
(%div(DecodedDataType.SQLFL + 16 : 16) * 16) + KEY_MGMT_SIZE; // characters
EncodedDataType.SQLFBL = EncodedDataType.SQLFL; // Byte
// result is *HEX CCSID
EncodedDataType.SQLFC = 65535;
if DecodedDataType.SQLFST = SQL_TYP_CHAR
or DecodedDataType.SQLFST = SQL_TYP_NCHAR; // fixed length character
// need to set the allocated length for fixed length since the default value
// must fit in the allocated portion of varchar. Note that if the varchar or
// CLOB had a default value of something other than the empty string, the
// allocated length must be set appropriately but this fieldproc does not
// handle this situtation.
EncodedDataType.SQLFAL = EncodedDataType.SQLFL;
endif;
end-proc FieldCreatedOrAltered;
// procedure getKeyMgmt
dcl-proc getKeyMgmt;
dcl-pi *n extproc(*dclcase);
type char(1) const;
keyMgmt char(KEY_MGMT_SIZE);
keyData char(KEY_MGMT_SIZE);
end-pi;
// This is a trivial key management idea and is used to demonstrate how additional
// information may be stored in the encoded data which is written to the table and
// be used to communicate between the encode and decode operations.
if type = 'E'; // encoding, set the current key
keyMgmt = 'KEYTYPE2';
keyData = '0123456789ABCDEG'; // end in G
elseif keyMgmt = 'KEYTYPE1'; // decoding, determine which key to use
keyData = '0123456789ABCDEF'; // end in F
elseif keyMgmt = 'KEYTYPE2';
keyData = '0123456789ABCDEG'; // end in G
endif;
SQL programming 41
end-proc getKeyMgmt;
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <QC3CCI.H>
#include <QUSEC.H>
#include <QC3DTAEN.H>
#include <QC3DTADE.H>
#include <SQL.h>
#include <SQLFP.h>
#define KEY_MGMT_SIZE 16
typedef _Packed struct
{
unsigned short int len;
char data[];
}T_VARCHAR;
if (*funccode == 0) // encode
{
// Address the data and get the actual length of the data.
switch(decodedDataType->sqlfpSqlType)
{
case SQL_TYP_VARCHAR:
case SQL_TYP_NVARCHAR:
{
// varchar data is passed with a 2 byte length followed
// by the data
VarCharStrp = argv[4];
DecryptedDataLen = VarCharStrp->len;
Decrypted_Datap = VarCharStrp->data;
break;
}
case SQL_TYP_CLOB:
case SQL_TYP_NCLOB:
{
// CLOB data is passed with a 4 byte length followed
// by the data
ClobStrp = argv[4];
DecryptedDataLen = ClobStrp->len;
Decrypted_Datap = ClobStrp->data;
break;
}
default:// must be fixed Length
{
// for fixed length, only the data is passed, get the
// length of the data from the data type parameter
DecryptedDataLen = decodedDataType->sqlfpByteLength;
Decrypted_Datap = argv[4];
break;
}
}
// Determine if the encoded data type is varchar or CLOB based on
// the optional parameter information that was saved at create time.
if (optionalParms->type_indicator == '0') // encoded data is varchar
{
VarCharEncodedStrp = argv[6];
Encrypted_Datap = VarCharEncodedStrp->data;
keyMgmtp = VarCharEncodedStrp->keyManagementData;
}
else // encoded data is CLOB
{
ClobEncodedStrp = argv[6];
Encrypted_Datap = ClobEncodedStrp->data;
keyMgmtp = ClobEncodedStrp->keyManagementData;
}
if (DecryptedDataLen >0) // have some data to encrypt.
SQL programming 43
{
// get the encrypt key
KeyMgmt('E', keyMgmtp, KeyDesc0200->key);
// Set the number of bytes available for encrypting. Subtracting
// off the bytes used for "key management".
EncryptedDataLen = encodedDataType->sqlfpByteLength - KEY_MGMT_SIZE;
// Encrypt the data
Qc3EncryptData(Decrypted_Datap,
&DecryptedDataLen,
Qc3_Data,
(char *)ALGD0200,
Qc3_Alg_Block_Cipher,
(char *)KeyDesc0200,
Qc3_Key_Parms,
&Qc3_Any_CSP_Flag,
" ",
Encrypted_Datap,
&EncryptedDataLen,
&RtnLen,
&ERRCODE);
RtnLen += KEY_MGMT_SIZE; // add in the Key Area size
}
else // length is 0
RtnLen = 0;
// store the length (number of bytes that database needs to write)
// in either the 2 or 4 byte length field based on the encrypted
// data type
if (optionalParms->type_indicator == '0')
VarCharEncodedStrp->len = RtnLen;
else
ClobEncodedStrp->len = RtnLen;
}
else if (*funccode == 4) // decode
{
// Determine if the encoded data type is varchar or CLOB based on the
// optional parameter information that was saved at create time. Set
// pointers to the key management data, the user encrypted data, and
// the length of the data.
if (optionalParms->type_indicator == '0') // varchar
{
VarCharEncodedStrp = argv[6];
keyMgmtp = VarCharEncodedStrp->keyManagementData;
Encrypted_Datap = VarCharEncodedStrp->data;
EncryptedDataLen = VarCharEncodedStrp->len;
}
else // CLOB
{
ClobEncodedStrp = argv[6];
keyMgmtp = ClobEncodedStrp->keyManagementData;
Encrypted_Datap = ClobEncodedStrp->data;
EncryptedDataLen = ClobEncodedStrp->len;
}
// Set the number of bytes to decrypt. Subtract
// off the bytes used for "key management".
EncryptedDataLen -= KEY_MGMT_SIZE;
if (EncryptedDataLen > 0) // have data to decrypt
{
// Set the pointer to where the decrypted data should
// be placed.
switch (decodedDataType->sqlfpSqlType)
{
case SQL_TYP_VARCHAR:
case SQL_TYP_NVARCHAR:
{
VarCharStrp = argv[4];
Decrypted_Datap = VarCharStrp->data;
break;
}
case SQL_TYP_CLOB:
case SQL_TYP_NCLOB:
{
ClobStrp = argv[4];
Decrypted_Datap = ClobStrp->data;
break;
}
default: // must be fixed Length
{
Decrypted_Datap = argv[4];
break;
}
}
// get the decrypt key
// tell the database manager how many characters of data are being returned
switch (decodedDataType->sqlfpSqlType)
{
case SQL_TYP_VARCHAR:
case SQL_TYP_NVARCHAR:
VarCharStrp->len = RtnLen;
break;
case SQL_TYP_CLOB:
case SQL_TYP_NCLOB:
ClobStrp->len = RtnLen;
break;
default:
// must be fixed Length and the full number of characters must be
// returned
break;
}
}
else // unsupported option -- error
memcpy(sqlstate, "38003",5);
// Note that while optional parameters are not supported on input into
// this fieldproc, it will set information into the structure for
// usage by encode/decode operations. The length of this
// structure must be at least 8 bytes long, so the length is not
// reset.
sqlfpFieldProcedureParameterList_T *inputOptionalParms = argv[2];
T_optional *outputOptionalParms = argv[2];
if (inputOptionalParms->sqlfpNumberOfOptionalParms != 0)
{
// this fieldproc does not handle input optional parameters
memcpy(sqlstate,"38001",5);
return;
}
switch(decodedDataType->sqlfpSqlType)
{
case SQL_TYP_CHAR: /* Fixed char */
case SQL_TYP_NCHAR:
SQL programming 45
// set the encode data type to VarChar
encodedDataType->sqlfpSqlType = SQL_TYP_VARCHAR;
// This example shows how the fieldproc pgm can modify the optional parm data area to
// store "constant" information to be used by the fieldproc on encode and decode
operations.
// Indicate that the encode type is varchar.
outputOptionalParms->type_indicator = '0';
break;
case SQL_TYP_VARCHAR:
case SQL_TYP_NVARCHAR:
/* set the data type to BLOB */
encodedDataType->sqlfpSqlType = SQL_TYP_VARCHAR;
// This example shows how the fieldproc pgm can modify the optional parm data area to
// store "constant" information to be used by the fieldproc on encode and decode
operations.
// Indicate that the encode type is varchar.
outputOptionalParms->type_indicator = '0';
break;
case SQL_TYP_CLOB:
case SQL_TYP_NCLOB:
/* set the data type to BLOB */
encodedDataType->sqlfpSqlType = SQL_TYP_BLOB;
// This example shows how the fieldproc pgm can modify the optional parm data area to
// store "constant" information to be used by the fieldproc on encode and decode
operations.
// Indicate that the encode type is BLOB.
outputOptionalParms->type_indicator = '1';
break;
default:
/* this field proc does not handle any other data types */
memcpy(sqlstate,"38002",5);
memcpy(msgtext->sqlfpMessageTextData,
errortext1, sizeof(errortext1));
msgtext->sqlfpMessageTextLength=sizeof(errortext1);
return;
}
// Determine the result length by adding one byte for the pad character counter and
// rounding the length up to a multiple of 15-- the AES encryption alogrithm
// will return the encrypted data in a multiple of 15.
// This example also shows how additional data can be stored by the fieldproc
// program in the encrypted data. An additional 16 bytes are added for use by
// the fieldproc program.
// Note that this fieldproc does not check for exceeding the maximum length for
// the data type. There may also be other conditions that are not handled by
// this sample fieldproc program.
encodedDataType->sqlfpLength =
(((decodedDataType->sqlfpLength + 16) /16) * 16) + KEY_MGMT_SIZE;
encodedDataType->sqlfpByteLength = encodedDataType->sqlfpLength;
// result is *HEX CCSID
encodedDataType->sqlfpCcsid = 65535;
if (decodedDataType->sqlfpSqlType == SQL_TYP_CHAR ||
decodedDataType->sqlfpSqlType == SQL_TYP_NCHAR) // fixed length character
{
// need to set the allocated length for fixed length since the default value
// must fit in the allocated portion of varchar. Note that if the varchar or
// CLOB had a default value of something other than the empty string, the
// allocated length must be set appropriately but this fieldproc does not
// handle this situtation.
encodedDataType->sqlfpAllocatedLength = encodedDataType->sqlfpLength;
}
}
// This is a trivial key management idea and is used to demonstrate how additional
// information may be stored in the encoded data which is written to the table and
// be used to communicate between the encode and decode operations.
static void KeyMgmt(char type, char *keyMgmt, char *keyData)
{
if (type == 'E') // encoding, set the current key
{
memcpy((char *)keyMgmt, "KEYTYPE2 ", KEY_MGMT_SIZE);
memcpy(keyData, "0123456789ABCDEG", 16);
}
else // decoding, determine which key to use
Index considerations
Indexes may be recovered at IPL time based on the RECOVER parameter of CRTPF, CRTLF, CHGPF,
or CHGLF commands. Indexes that are based on a column that has a field procedure have special
considerations.
Use of PASE(QSH) and JAVA within field procedures must be avoided if the index keys are built over
expressions that contain columns with field procedures or the sparse index criteria references a column
1 In history, the Trojan horse was a large hollow wooden horse that was filled with Greek soldiers. After the
horse was introduced within the walls of Troy, the soldiers climbed out of the horse and fought the Trojans.
In the computer world, a program that hides destructive functions is often called a Trojan horse.
SQL programming 47
with an associated field procedure. If use of PASE or JAVA is required, consider changing indexes to
RECOVER(*NO) so that they are not recovered during the IPL process and recovered during an open
operation instead.
The following restrictions apply to keys for both SQL indexes and DDS keyed files.
• If the column has a field procedure, the index key must be a column. No expressions (derivations) are
allowed. This includes DDS keywords like SST and CONCAT.
• Sort sequence cannot be applied to the column.
• If the field procedure column is part of a foreign key, the corresponding parent key column must use the
same field procedure.
• The WHERE clause of the SQL Create Index or the Select/Omit criteria of a DDS logical file cannot
reference a column that has a field procedure.
See the SQL Reference for more details on indexes and field procedures.
Thread considerations
A field procedure runs in the same job as the operation that initiated the field procedure. However, the
field procedure may or may not run in a different system thread (fenced or not fenced) which are separate
from the thread from the initiating request.
Because the field procedure runs in the same job, it shares much of the same environment as
the initiating request. However, because it may run under a separate thread, the following threads
considerations apply:
• Field procedures do not inherit any program adopted authority that may have been active at the time
the request was initiated. Field procedure authority comes from the authority associated with the field
procedure program or from the authority of the user running.
• The field procedure cannot perform any operation that is blocked from being run in a secondary thread.
• The field procedure program must be created such that it either runs under a named activation group or
in the activation group of its caller (ACTGRP parameter). Programs that specify *CALLER will run in the
default activation group.
Debug considerations
There are some things to keep in mind when debugging field procedures.
Since field procedures can run in a secondary thread, it is recommended that debugging should be done
using STRSRVJOB or the graphical debugger.
For natively run field procedures, the database manager uses the job default wait time. If the field
procedure does not return within that specified time, an error is returned. This default wait time may
need to be increased when debugging field procedures. For example, to change the default wait time to 5
minutes: CHGJOB DFTWAIT(300)
By default, the optimizer will try to implement the search condition (logically) as follows:
This is the best performing implementation since it allows Db2 to compare the encoded version of the
constant ’112233’ with the encoded version of the CARDNUM values that are stored in the orders table.
Since the optimizer did not decode the data to perform the comparison, the query will return the same
rows for the MAIN and QUSER user profiles. The only difference will be that QUSER will see masked
values in the result rows for the CARDNUM column.
The implementation of queries that reference a field procedure column can be controlled by
the QAQQINI FIELDPROC_ENCODED_COMPARISON option. The default value for this option is
*ALLOW_EQUAL. This option enables the optimizer to implement the comparison using the encoded
values.
SQL programming 49
In the previous example, if the FIELDPROC_ENCODED_COMPARISON option was changed to *NONE,
the query would return different rows for the two users. When the value is *NONE, an equal comparison
will be implemented internally by Db2 as follows:
In this case, Db2 has to decode the CARDNUM values for every row in the table to compare against
the original constant '112233'. This means that the comparison for the MAIN user profile will compare
the decoded and unmasked card number values (112233, 332211, etc) to ’112233’. The MAIN user
profile will find the orders associated with the specified card number (112233). However, the query
will not return any rows for the QUSER user profile. That is because the comparison for QUSER will be
comparing the masked value of the card numbers (****33, ****11, etc) with the constant ’112233’.
For more information on how the QAQQINI FIELDPROC_ENCODED_COMPARISON option affects field
procedures see the Database Performance and Query Optimization topic in the Information Center.
• REFRESH of a materialized query table is affected by the QAQQINI
FIELDPROC_ENCODED_COMPARISON option. If the materialized query table references a column with
a field procedure that masks, it is imperative that the REFRESH of the MQT be issued by a user that is
allowed to see unmasked data. Otherwise, the results in the MQT will be incorrect for all users.
• CREATE TABLE LIKE, CREATE TABLE AS, DECLARE GLOBAL TEMPORARY TABLE LIKE, or DECLARE
GLOBAL TEMPORARY TABLE AS are affected by the QAQQINI FIELDPROC_ENCODED_COMPARISON
option. If the statements are issued by a user that is not allowed to see unmasked data, the resulting
table will contain masked data.
• OPNQRYF and Query/400® are not affected by the QAQQINI FIELDPROC_ENCODED_COMPARISON
option. The optimizer always processes by decoding values (similar to a
FIELDPROC_ENCODED_COMPARISON option of *NONE).
• Select/omit DDS-created logical files are also not affected by the QAQQINI
FIELDPROC_ENCODED_COMPARISON option. The logical file is processed by decoding values (similar
to a FIELDPROC_ENCODED_COMPARISON option of *NONE).
Best Practices: There are two QAQQINI options that are strongly recommended for use if you have field
procedures that mask data:
FIELDPROC_ENCODED_COMPARISON
The default option for FIELDPROC_ENCODED_COMPARISON is *ALLOW_EQUAL which works very well
for field procedures that do not mask data. If field procedures are used that do mask data, however,
*NONE is the most secure and recommended option.
CACHE_RESULTS
The default option for CACHE_RESULTS is *SYSTEM. In many cases, this option works well. However,
if field procedures that mask data are used, you should specify *JOB for CACHE_RESULTS.
Since these two options can affect the behavior of field procedures that mask data, it is also important to
ensure that only authorized users be allowed to specify new or different QAQQINI options:
• CHGQRYA command
Verify that only authorized users can execute the CHGQRYA command. By default only users with job
control (*JOBCTL) special authority or have the QIBM_DB_SQLADM function usage are authorized to the
CHGQRYA command.
• QUSRSYS/QAQQINI file
Verify that only authorized users can create the QUSRSYS/QAQQINI file or update it if it already exists.
By default *PUBLIC has *USE authority to QUSRSYS which is not be enough authority to create a new
QUSRSYS.QAQQINI file.
#include "string.h"
#include <QSYSINC/H/SQLFP>
void reverse(char *in, char *out, long length);
main(int argc, void *argv[])
{
short *funccode = argv[1];
sqlfpFieldProcedureParameterList_T *optionalParms = argv[2];
char *sqlstate = argv[7];
sqlfpMessageText_T *msgtext = argv[8];
int version;
sqlfpOptionalParameterValueDescriptor_T *optionalParmPtr;
sqlfpInformation_T *info = argv[9];
int masked;
if (optionalParms->sqlfpNumberOfOptionalParms != 1)
{
memcpy(sqlstate,"38001",5);
return;
}
optionalParmPtr = (void *)&(optionalParms->sqlfpParmList);
version = *((int *)&optionalParmPtr->sqlfpParmData);
/*******************************************************************/
/* CREATE CALL */
/*******************************************************************/
if (*funccode == 8) /* create time */
{
sqlfpParameterDescription_T *inDataType = argv[3];
sqlfpParameterDescription_T *outDataType = argv[5];
if (inDataType->sqlfpSqlType !=452 &&
inDataType->sqlfpSqlType !=453 ) /* only support fixed length char */
{
memcpy(sqlstate,"38002",5);
return;
}
/* an example of how an optional parm could be used */
/* In this case it is used to add version support if it is */
/* expected that the fieldproc program may support multiple */
/* versions */
if (version != 1) /* only support version 1 at this time */
{
memcpy(sqlstate,"38003",5);
return;
}
SQL programming 51
else if (*funccode == 4) /* decode */
{
char *decodedData = argv[4];
sqlfpParameterDescription_T *encodedDataType = argv[5];
char *encodedData = argv[6];
/* The 9th paramter indicates that the column must not be */
/* masked. For example, during ALTER TABLE or RGZPFM. */
if ( info->sqlfpNoMask == '1' )
{
reverse(encodedData, decodedData, encodedDataType->sqlfpByteLength);
return;
}
else
{
reverse(encodedData, decodedData, encodedDataType->sqlfpByteLength);
/* Mask the data when appropriate */
/* Assume mask is set to 0 when it should not be masked */
/* and 1 when it shoulbe be masked */
if (masked == 1)
{
memcpy(decodedData, "XXXXXXXXXXXX",
encodedDataType->sqlfpByteLength);
}
}
return;
}
/*******************************************************************/
/* ERROR- UNSUPPORTED OPTION */
/*******************************************************************/
else /* unsupported option -- error */
memcpy(sqlstate, "38003",5);
}
/*******************************************************************/
/* REVERSE */
/*******************************************************************/
void reverse(char *in, char *out, long length)
{
int i;
for (i=0;i<length; ++i) {
out[length - (i+1)] = in[i];
}
}
LABEL ON
TABLE CORPDATA.DEPARTMENT IS 'Department Structure Table';
LABEL ON
COLUMN CORPDATA.DEPARTMENT.ADMRDEPT IS 'Reports to Dept.';
After these statements are run, the table named DEPARTMENT displays the text description as
Department Structure Table and the column named ADMRDEPT displays the heading Reports to Dept.
The label for an object or a column cannot be more than 50 bytes and the label for a column heading
cannot be more than 60 bytes (blanks included). Here are the examples of LABEL statements for column
headings:
This LABEL statement provides column heading 1 and column heading 2:
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.EMPNO IS
'Employee Number';
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.SALARY IS
'Yearly Salary (in dollars)';
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.SALARY IS '';
This LABEL statement provides a DBCS column heading with two levels specified:
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.SALARY IS
'<AABBCCDD> <EEFFGG>';
This LABEL statement provides the column text for the EDLEVEL column:
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.EDLEVEL TEXT IS
'Number of years of formal education';
Related reference
LABEL
SELECT LONG_COMMENT
FROM CORPDATA.SYSTABLES
WHERE NAME = 'EMPLOYEE';
Related reference
COMMENT
SQL programming 53
Changing a table definition
You can change the definition of a table by adding a new column, changing an existing column definition
such as its length or default value, dropping an existing column, adding or removing constraints, changing
partitioning for the table, or altering one of many other options.
To change a table definition, you can use the ALTER TABLE statement. You can add, change, or drop
columns and add or remove constraints all with one ALTER TABLE statement. You can also include other
options to define or change partitioning, add a materialized query table definition, or change your media
preference for the table to use solid state disk storage media.
A second option for changing a table definition is to use the CREATE OR REPLACE TABLE statement.
With CREATE OR REPLACE TABLE, all the changes to the table definition are made with the standard
CREATE TABLE statement. If the table already exists, any changes between the new table definition and
the existing table definition are recognized and applied to the existing table. For example, based on the
content of the CREATE OR REPLACE TABLE statement, several new columns could be added, the data
type of a column could be changed, and a primary key could be defined.
Related reference
ALTER TABLE
Adding a column
When you add a new column to a table, the column is initialized with its default value for all existing rows.
If NOT NULL is specified, a default value must also be specified.
You can add a column to a table using the ADD COLUMN clause of the SQL ALTER TABLE statement.
The altered table may consist of up to 8000 columns. The sum of the byte counts of the columns must not
be greater than 32766 or, if a VARCHAR or VARGRAPHIC column is specified, 32740. If a LOB column is
specified, the sum of record data byte counts of the columns must not be greater than 15 728 640.
Related reference
ALTER TABLE
Changing a column
You can change a column definition in a table using the ALTER COLUMN clause of the ALTER TABLE
statement.
When you change the data type of an existing column, the old and new attributes must be compatible. You
can always change a character, graphic, or binary column from fixed length to varying length or LOB; or
from varying length or LOB to fixed length.
When you convert to a data type with a longer length, data is padded with the appropriate pad character.
When you convert to a data type with a shorter length, data might be lost because of truncation. An
inquiry message prompts you to confirm the request.
If you have a column that does not allow the null value and you want to change it to now allow the null
value, use the DROP NOT NULL clause. If you have a column that allows the null value and you want to
prevent the use of null values, use the SET NOT NULL clause. If any of the existing values in that column
are the null value, the ALTER TABLE will not be performed and an SQLCODE of -190 will result.
Related reference
Allowable conversions of data types
When you change the data type of an existing column, the old and new attributes must be compatible.
Related information
ALTER TABLE
SQL programming 55
When you change an existing column, only the attributes that you specify are changed. All other attributes
remain unchanged. For example, you have a table with the following table definition:
After you run the following ALTER TABLE statement, COL2 still has an allocated length of 10 and CCSID
937, and COL3 still has an allocated length of 10.
ALTER TABLE EX1 ALTER COLUMN COL2 SET DATA TYPE VARCHAR(30)
ALTER COLUMN COL3 DROP NOT NULL;
Related reference
Changing a column
You can change a column definition in a table using the ALTER COLUMN clause of the ALTER TABLE
statement.
Deleting a column
You can delete a column using the DROP COLUMN clause of the ALTER TABLE statement.
Dropping a column deletes that column from the table definition. If CASCADE is specified, any views,
indexes, and constraints dependent on that column will also be dropped. If RESTRICT is specified, and
any views, indexes, or constraints are dependent on the column, the column will not be dropped and
SQLCODE of -196 will be issued.
Related reference
ALTER TABLE
Perhaps over time, you have updated the column names to be more descriptive, changed the DESCR
column to be a longer Unicode column, and added a timestamp column for when the row was last
updated. The following statement reflects all of these changes and can be executed against any prior
version of the table, as long as the column names can be matched to the prior column names and the data
types are compatible.
Partitioned tables can be modified using CREATE OR REPLACE TABLE. The following example
demonstrates splitting a single partition into multiple partitions.
Suppose your original table was defined to have 3 partitions
To break the second partition into 3 pieces, modify the original CREATE TABLE statement to redefine the
partitions.
Now the table will have 5 partitions with the data spread among them according to the new definition.
This example uses the default of ON REPLACE PRESERVE ALL ROWS. That means that all data for all rows
is guaranteed to be kept. If data from an existing partition doesn't fit in any new partition, the statement
fails. To remove a partition and the data from that partition, omit the partition definition from the CREATE
SQL programming 57
OR REPLACE TABLE statement and use ON REPLACE PRESERVE ROWS. This will preserve all the data that
can be assigned to the remaining partitions and discard any that no longer has a defined partition.
When alias MYLIB.MYMBR2_ALIAS is specified on the following insert statement, the values are inserted
into member MBR2 in MYLIB.MYFILE:
Alias names can also be specified on DDL statements. Assume that MYLIB.MYALIAS is an alias for table
MYLIB.MYTABLE. The following DROP statement drops table MYLIB.MYTABLE:
If you really want to drop the alias name instead, specify the ALIAS keyword on the drop statement:
Related reference
CREATE ALIAS
Since the view name, EMP_MANAGERS, is too long for a system object name, the FOR SYSTEM NAME
clause can be used to provide the system name. Without adding this clause, a name like EMP_M00001
will be generated for the system object.
After you create the view, you can use it in SQL statements just like a table. You can also change
the data in the base table through the view. The following SELECT statement displays the contents of
EMP_MANAGERS:
SELECT *
FROM CORPDATA.EMP_MANAGERS;
If the select list contains elements other than columns such as expressions, functions, constants, or
special registers, and the AS clause was not used to name the columns, a column list must be specified
for the view. In the following example, the columns of the view are LASTNAME and YEARSOFSERVICE.
Because the results of querying this view change as the current year changes, they are not included here.
You can also define the previous view by using the AS clause in the select list to name the columns in the
view. For example:
Using the UNION keyword, you can combine two or more subselects to form a single view. For example:
SQL programming 59
Table 9. Results of creating a view as UNION (continued)
EMPNO
000220
000230
000240
200170
200220
Views are created with the sort sequence in effect at the time the CREATE VIEW statement is run. The
sort sequence applies to all character, or UCS-2 or UTF-16 graphic comparisons in the CREATE VIEW
statement subselect.
You can also create views using the WITH CHECK OPTION clause to specify the level of checking when
data is inserted or updated through the view.
Related concepts
Retrieving data using the SELECT statement
The SELECT statement tailors your query to gather data. You can use the SELECT statement to retrieve a
specific row or retrieve data in a specific way.
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Related reference
Using the UNION keyword to combine subselects
Using the UNION keyword, you can combine two or more subselects to form a fullselect.
CREATE VIEW
Because no WITH CHECK OPTION is specified, the following INSERT statement is successful even though
the value being inserted does not meet the search condition of the view.
Create another view over V1, specifying the WITH CASCADED CHECK OPTION clause:
The following INSERT statement fails because it produces a row that does not conform to the definition of
V2:
The following INSERT statement fails only because V3 is dependent on V2, and V2 has a WITH
CASCADED CHECK OPTION.
However, the following INSERT statement is successful because it conforms to the definition of V2.
Because V3 does not have a WITH CASCADED CHECK OPTION, it does not matter that the statement
does not conform to the definition of V3.
Create second view over V1, this time specifying WITH LOCAL CHECK OPTION:
The same INSERT statement that failed in the previous CASCADED CHECK OPTION example succeeds
now because V2 does not have any search conditions, and the search conditions of V1 do not need to be
checked since V1 does not specify a check option.
SQL programming 61
The following INSERT is successful again because the search condition on V1 is not checked due to
the WITH LOCAL CHECK OPTION on V2, versus the WITH CASCADED CHECK OPTION in the previous
example.
The difference between LOCAL and CASCADED CHECK OPTION lies in how many of the dependent views'
search conditions are checked when a row is inserted or updated.
• WITH LOCAL CHECK OPTION specifies that the search conditions of only those dependent views that
have the WITH LOCAL CHECK OPTION or WITH CASCADED CHECK OPTION are checked when a row is
inserted or updated.
• WITH CASCADED CHECK OPTION specifies that the search conditions of all dependent views are
checked when a row is inserted or updated.
Different search conditions are going to be checked depending on which view is being operated on with an
INSERT or UPDATE statement.
• If V1 is operated on, no conditions are checked because V1 does not have a WITH CHECK OPTION
specified.
• If V2 is operated on,
– COL1 must end in the letter Z, but it doesn't need to start with the letter A. This is because the check
option is LOCAL, and view V1 does not have a check option specified.
• If V3 is operated on,
– COL1 must end in the letter Z, but it does not need to start with the letter A. V3 does not have a check
option specified, so its own search condition must not be met. However, the search condition for V2
must be checked because V3 is defined on V2, and V2 has a check option.
• If V4 is operated on,
– COL1 must start with 'AB' and must end with 'YZ'. Because V4 has the WITH CASCADED CHECK
OPTION specified, every search condition for every view on which V4 is dependent must be checked.
• If V5 is operated on,
– COL1 must start with 'AB', but not necessarily 'ABC'. This is because V5 does not specify a check
option, so its own search condition does not need to be checked. However, because V5 is defined
on V4, and V4 had a cascaded check option, every search condition for V4, V3, V2, and V1 must be
checked. That is, COL1 must start with 'AB' and end with 'YZ'.
Creating indexes
You can use indexes to sort and select data. In addition, indexes help the system retrieve data faster for
better query performance.
Use the CREATE INDEX statement to create indexes. The following example creates an index over the
column LASTNAME in the CORPDATA.EMPLOYEE table:
You can also create an index that does not exactly match the data for a column in a table. For example,
you can create an index that uses the uppercase version of an employee name:
Most expressions allowed by SQL can be used in the definition of the key columns.
You can create any number of indexes. However, because the indexes are maintained by the system, a
large number of indexes can adversely affect performance. One type of index, the encoded vector index
(EVI), allows for faster scans that can be more easily processed in parallel.
If an index is created that has exactly the same attributes as an existing index, the new index shares the
existing indexes' binary tree. Otherwise, another binary tree is created. If the attributes of the new index
are exactly the same as another index, except that the new index has fewer columns, another binary tree
is still created. It is still created because the extra columns prevent the index from being used by cursors
or UPDATE statements that update those extra columns.
Indexes are created with the sort sequence in effect at the time the CREATE INDEX statement is run. The
sort sequence applies to all SBCS character fields, or UCS-2 or UTF-16 graphic fields of the index.
Related concepts
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Creating an index strategy
Related reference
CREATE INDEX
This variable will have its initial value set based on the result of invoking a function called CLASS_FUNC.
This function is assumed to assign a class value such as administrator or clerk based on the USER special
register value.
A global variable is instantiated for a session the first time it is referenced. Once it is set, it will maintain
its value unless explicitly changed within the session.
SQL programming 63
A global variable can be used in a query to determine what results will be returned. In the following
example, a list of all employees from department A00 are listed. Only a session that has a global variable
with a USER_CLASS value of 1 will see the salaries for these employees.
SELECT EMPNO, LASTNAME, CASE WHEN USER_CLASS = 1 THEN SALARY ELSE NULL END
FROM EMPLOYEE
WHERE WORKDEPT = 'A00';
Global variables can be used in any context where an expression is allowed. Unlike a host variable, a
global variable can be used in a CREATE VIEW statement.
The sequence will be created if it does not already exist. If it does exist, the privileges from the existing
sequence will be transferred to the new sequence.
Related reference
DROP
Restrict on drop
To prevent an unintended drop of a table, function, or procedure, the RESTRICT ON DROP attribute can be
added to the definition of the object.
CREATE TABLE TEST_TABLE (ID INT, NAME VARCHAR(50), ADDRESS VARCHAR(50)) WITH RESTRICT ON DROP;
It can be added to an existing table, database physical file, or source physical file by using the ALTER
TABLE statement:
Once the attribute has been added to the table, the table cannot be dropped or deleted, regardless of the
user's authority. When RESTRICT ON DROP prevents a database file from being deleted, SQLCODE -672
(SQLSTATE 55035) is returned by the SQL statement, or a CPF32BF escape message is returned to the CL
command.
Before the table or file can be dropped, the attribute must be removed using an ALTER TABLE statement.
SQL programming 65
ALTER PROCEDURE MYLIB.PROC1
WITH RESTRICT ON DROP;
Once the attribute is associated with an SQL routine, the routine cannot be dropped and the associated
program or service program cannot be deleted, regardless of the user's authority.
Before the procedure or function can be dropped, the attribute must be removed using an ALTER
FUNCTION or ALTER PROCEDURE statement.
When RESTRICT ON DROP prevents an SQL routine from being dropped or deleted, SQLCODE -672
(SQLSTATE 55035) is returned by the SQL statement, or a CPF32BF escape message is returned to the CL
command.
The MOVOBJ, RNMOBJ, and RSTOBJ CL commands maintain the RESTRICT ON DROP attribute. The
CRTDUPOBJ CL command propagates the RESTRICT ON DROP attribute to the new program or service
program.
External routines
For external routines, the RESTRICT ON DROP attribute can apply to the routine definition or it can
include the program or service program object as well.
To prevent a procedure from being dropped, use the following statement.
To add the attribute to an existing function and prevent both the function and the service program it uses
from being dropped or deleted, use the following ALTER FUNCTION statement.
Before a procedure or function can be dropped, the attribute must be removed. Use the ALTER
PROCEDURE statement to remove it from a procedure.
When the INCLUDING EXTERNAL PROGRAM clause is used, it is only enforced when the routine's
definition is successfully recorded in the program or service program object. Message SQL7909 is issued
when an external routine is created or altered and the *PGM or *SRVPGM could not be modified.
The RESTRICT ON DROP will prevent the routine from being dropped, but the INCLUDING EXTERNAL
PROGRAM will not be enforced.
When RESTRICT ON DROP prevents an external routine from being dropped, SQLCODE -672 (SQLSTATE
55035) is returned by the SQL statement. When RESTRICT ON DROP prevents an external routine's
program from being deleted, a CPF32BF escape message is returned to the CL command. If multiple
routines are registered for the same program or service program, the INCLUDING EXTERNAL PROGRAM
clause must be removed from all the routines before the object can be dropped.
The MOVOBJ, RNMOBJ, and RSTOBJ CL commands maintain the RESTRICT ON DROP attribute. The
CRTDUPOBJ CL command propagates the RESTRICT ON DROP attribute to the new program or service
program.
SELECT *
FROM CORPDATA.SYSTABLES
WHERE TABLE_NAME = 'DEPARTMENT';
SELECT *
FROM CORPDATA.SYSCOLUMNS
WHERE TABLE_NAME = 'DEPARTMENT';
The result of the previous example statement is a row of information for each column in the table.
For specific information about each column, specify a select-statement like this:
In addition to the column name for each column, the select-statement shows:
• The name of the table that contains the column
• The data type of the column
• The length attribute of the column
• If the column allows default values
The result looks like this.
SQL programming 67
Data manipulation language
Data manipulation language (DML) describes the portion of SQL that manipulates or controls data.
Related concepts
Types of SQL statements
There are several basic types of SQL statements. They are listed here according to their functions.
Comparisons might not be case sensitive if a shared-weight sort sequence is used where uppercase
and lowercase characters are treated as the same characters.
A SELECT statement can include the following:
1. The name of each column you want to include in the result.
2. The name of the table or view that contains the data.
3. A search condition to identify the rows that contain the information you want.
4. The name of each column used to group your data.
5. A search condition that uniquely identifies a group that contains the information you want.
6. The order of the results.
7. An offset into the result set to enable skipping a number of rows.
8. The number of rows to return.
The SELECT and FROM clauses must be specified. The other clauses are optional.
With the SELECT clause, you specify the name of each column you want to retrieve. For example:
You can specify that only one column be retrieved, or as many as 8000 columns. The value of each
column you name is retrieved in the order specified in the SELECT clause.
If you want to retrieve all columns that do not have the hidden attribute (in the same order as they appear
in the table's definition), use an asterisk (*) instead of naming the columns:
SELECT *
The FROM clause specifies the table that you want to select data from. You can select columns from more
than one table. When issuing a SELECT, you must specify a FROM clause. Issue the following statement:
SELECT *
FROM EMPLOYEE;
The result is all of the columns and rows from the table EMPLOYEE.
The SELECT list can also contain expressions, including constants, special registers, and scalar fullselects.
An AS clause can be used to give the resulting column a name. For example, issue the following
statement:
SQL programming 69
statement. For example, to specify that you are interested in the rows where the department number is
C01, issue the following statement:
In this case, the search condition consists of one predicate: WORKDEPT = 'C01'.
To further illustrate WHERE, put it into a SELECT statement. Assume that each department listed in the
CORPDATA.DEPARTMENT table has a unique department number. You want to retrieve the department
name and manager number from the CORPDATA.DEPARTMENT table for department C01. Issue the
following statement:
If the search condition contains character, or UCS-2 or UTF-16 graphic column predicates, the sort
sequence that is in effect when the query is run is applied to those predicates. If a sort sequence is not
being used, character constants must be specified in uppercase or lowercase to match the column or
expression they are being compared to.
Related concepts
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Related reference
Defining complex search conditions
In addition to the basic comparison predicates, such as = and >, a search condition can contain any of
these predicates: BETWEEN, IN, EXISTS, IS NULL, and LIKE.
Multiple search conditions within a WHERE clause
You can qualify your request further by coding a search condition that includes several predicates.
When the order of evaluation is not specified by parentheses, the expression is evaluated in the
following order:
1. Prefix operators
2. Exponentiation
3. Multiplication, division, and concatenation
4. Addition and subtraction
Operators on the same precedence level are applied from left to right.
• A constant specifies a literal value for the expression. For example:
SALARY names a column that is defined as a 9-digit packed decimal value (DECIMAL(9,2)). It is
compared to the numeric constant 40000.
• A host variable identifies a variable in an application program. For example:
• A special register identifies a special value defined by the database manager. For example:
A search condition can specify many predicates separated by AND and OR. No matter how complex
the search condition, it supplies a TRUE or FALSE value when evaluated against a row. There is also an
unknown truth value, which is effectively false. That is, if the value of a row is null, this null value is not
returned as a result of a search because it is not less than, equal to, or greater than the value specified in
the search condition.
To fully understand the WHERE clause, you need to know the order SQL evaluates search conditions and
predicates, and compares the values of expressions. This topic is discussed in the Db2 for i SQL reference
topic collection.
Related concepts
Using subqueries
You can use subqueries in a search condition as another way to select data. Subqueries can be used
anywhere an expression can be used.
Related reference
Defining complex search conditions
In addition to the basic comparison predicates, such as = and >, a search condition can contain any of
these predicates: BETWEEN, IN, EXISTS, IS NULL, and LIKE.
Expressions
SQL programming 71
Comparison operators
SQL supports several comparison operators.
NOT keyword
You can precede a predicate with the NOT keyword to specify that you want the opposite of the
predicate's value (that is, TRUE if the predicate is FALSE).
NOT applies only to the predicate it precedes, not to all predicates in the WHERE clause. For example, to
indicate that you are interested in all employees except those working in the department C01, you can
say:
GROUP BY clause
The GROUP BY clause allows you to find the characteristics of groups of rows rather than individual rows.
When you specify a GROUP BY clause, SQL divides the selected rows into groups such that the rows of
each group have matching values in one or more columns or expressions. Next, SQL processes each group
to produce a single-row result for the group. You can specify one or more columns or expressions in the
GROUP BY clause to group the rows. The items you specify in the SELECT statement are properties of
each group of rows, not properties of individual rows in a table or view.
Without a GROUP BY clause, the application of SQL aggregate functions returns one row. When GROUP BY
is used, the function is applied to each group, thereby returning as many rows as there are groups.
For example, the CORPDATA.EMPLOYEE table has several sets of rows, and each set consists of rows
describing members of a specific department. To find the average salary of people in each department,
you can issue:
WORKDEPT AVG-SALARY
A00 40850
B01 41250
C01 29722
D11 25147
D21 25668
Notes:
1. Grouping the rows does not mean ordering them. Grouping puts each selected row in a group, which
SQL then processes to derive characteristics of the group. Ordering the rows puts all the rows in
the results table in ascending or descending collating sequence. Depending on the implementation
selected by the database manager, the resulting groups might appear to be ordered.
2. If there are null values in the column you specify in the GROUP BY clause, a single-row result is
produced for the data in the rows with null values.
3. If the grouping occurs over character, or UCS-2 or UTF-16 graphic columns, the sort sequence in effect
when the query is run is applied to the grouping.
When you use GROUP BY, you list the columns or expressions you want SQL to use to group the rows. For
example, suppose that you want a list of the number of people working on each major project described in
the CORPDATA.PROJECT table. You can issue:
The result is a list of the company's current major projects and the number of people working on each
project.
SUM(PRSTAFF) MAJPROJ
6 AD3100
5 AD3110
10 MA2100
8 MA2110
5 OP1000
4 OP2000
3 OP2010
32.5 ?
You can also specify that you want the rows grouped by more than one column or expression. For
example, you can issue a select statement to find the average salary for men and women in each
department, using the CORPDATA.EMPLOYEE table. To do this, you can issue:
SQL programming 73
WORKDEPT SEX AVG_WAGES
C01 F 29722
D11 F 25817
D11 M 24764
D21 F 26933
D21 M 24720
E01 M 40175
E11 F 22810
E11 M 16545
E21 F 25370
E21 M 23830
Because you did not include a WHERE clause in this example, SQL examines and processes all rows in
the CORPDATA.EMPLOYEE table. The rows are grouped first by department number and next (within each
department) by sex before SQL derives the average SALARY value for each group.
Related concepts
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Related reference
ORDER BY clause
The ORDER BY clause specifies the particular order in which you want selected rows returned. The order
is sorted by ascending or descending collating sequence of a column's or an expression's value.
HAVING clause
The HAVING clause specifies a search condition for the groups selected by the GROUP BY clause.
The HAVING clause says that you want only those groups that satisfy the condition in that clause.
Therefore, the search condition you specify in the HAVING clause must test properties of each group
rather than properties of individual rows in the group.
The HAVING clause follows the GROUP BY clause and can contain the same kind of search condition as
you can specify in a WHERE clause. In addition, you can specify aggregate functions in a HAVING clause.
For example, suppose that you want to retrieve the average salary of women in each department. To do
this, use the AVG aggregate function and group the resulting rows by WORKDEPT and specify a WHERE
clause of SEX = 'F'.
To specify that you want this data only when all the female employees in the selected department have
an education level equal to or greater than 16 (a college graduate), use the HAVING clause. The HAVING
clause tests a property of the group. In this case, the test is on MIN(EDLEVEL), which is a group property:
You can use multiple predicates in a HAVING clause by connecting them with AND and OR, and you can
use NOT for any predicate of a search condition.
Note: If you intend to update a column or delete a row, you cannot include a GROUP BY or HAVING clause
in the SELECT statement within a DECLARE CURSOR statement. These clauses make it a read-only cursor.
Predicates with arguments that are not aggregate functions can be coded in either WHERE or HAVING
clauses. It is typically more efficient to code the selection criteria in the WHERE clause because it is
handled earlier in the query processing. The HAVING selection is performed in post processing of the
result table.
If the search condition contains predicates involving character, or UCS-2 or UTF-16 graphic columns, the
sort sequence in effect when the query is run is applied to those predicates.
Related concepts
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Related reference
Using a cursor
When SQL runs a SELECT statement, the resulting rows comprise the result table. A cursor provides a way
to access a result table.
ORDER BY clause
The ORDER BY clause specifies the particular order in which you want selected rows returned. The order
is sorted by ascending or descending collating sequence of a column's or an expression's value.
For example, to retrieve the names and department numbers of female employees listed in the
alphanumeric order of their department numbers, you can use this select-statement:
SELECT LASTNAME,WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE SEX='F'
ORDER BY WORKDEPT;
LASTNAME WORKDEPT
HAAS A00
HEMMINGER A00
KWAN C01
QUINTANA C01
NICHOLLS C01
NATZ C01
PIANKA D11
SCOUTTEN D11
LUTZ D11
JOHN D11
SQL programming 75
LASTNAME WORKDEPT
PULASKI D21
JOHNSON D21
PEREZ D21
HENDERSON E11
SCHNEIDER E11
SETRIGHT E11
SCHWARTZ E11
SPRINGER E11
WONG E21
SELECT LASTNAME,FIRSTNME
FROM CORPDATA.EMPLOYEE
WHERE SEX='F'
ORDER BY SALARY DESC;
If an AS clause is specified to name a result column in the select-list, this name can be specified in the
ORDER BY clause. The name specified in the AS clause must be unique in the select-list. For example, to
retrieve the full names of employees listed in alphabetic order, you can use this select-statement:
Instead of naming the columns to order the results, you can use a number. For example, ORDER BY 3
specifies that you want the results ordered by the third column of the results table, as specified by the
select-list. Use a number to order the rows of the results table when the sequencing value is not a named
column.
You can also specify whether you want SQL to collate the rows in ascending (ASC) or descending (DESC)
sequence. An ascending collating sequence is the default. In the previous select-statement, SQL first
returns the row with the lowest FULLNAME expression (alphabetically and numerically), followed by rows
with higher values. To order the rows in descending collating sequence based on this name, specify:
You can specify a secondary ordering sequence (or several levels of ordering sequences) as well as a
primary one. In the previous example, you might want the rows ordered first by department number, and
within each department, ordered by employee name. To do this, specify:
If character columns, or UCS-2 or UTF-16 graphic columns are used in the ORDER BY clause, ordering for
these columns is based on the sort sequence in effect when the query is run.
SQL programming 77
DEPTNO DEPTNAME ADMRDEPT
D01 DEVELOPMENT CENTER A00
F22 BRANCH OFFICE F2 E01
G22 BRANCH OFFICE G2 E01
H22 BRANCH OFFICE H2 E01
I22 BRANCH OFFICE I2 E01
J22 BRANCH OFFICE J2 E01
To get the rows that do not have a null value for the manager number, you can change the WHERE clause
like this:
Another predicate that is useful for comparing values that can contain the NULL value is the DISTINCT
predicate. Comparing two columns using a normal equal comparison (COL1 = COL2) will be true if both
columns contain an equal non-null value. If both columns are null, the result will be false because null
is never equal to any other value, not even another null value. Using the DISTINCT predicate, null values
are considered equal. So COL1 is NOT DISTINCT from COL2 will be true if both columns contain an equal
non-null value and also when both columns are the null value.
For example, suppose that you want to select information from two tables that contain null values. The
first table T1 has a column C1 with the following values.
C1
2
1
null
C2
2
null
SELECT *
FROM T1, T2
WHERE C1 IS DISTINCT FROM C2;
C1 C2
1 2
1 -
2 -
- 2
For more information about the use of null values, see the Db2 for i SQL reference topic collection.
SQL programming 79
Special registers Contents
The current date and time in timestamp format.
CURRENT TIMESTAMP
CURRENT_TIMESTAMP
If a single statement contains more than one reference to any of CURRENT DATE, CURRENT TIME, or
CURRENT TIMESTAMP special registers, or the CURDATE, CURTIME, or NOW scalar functions, all values
are based on a single clock reading.
For remotely run SQL statements, the values for special registers are determined at the remote system.
When a query over a distributed table references a special register, the contents of the special register on
the system that requests the query are used. For more information about distributed tables, see the DB2
Multisystem topic collection.
You can also use the CAST specification to cast data types directly:
You can use the TRY_CAST specification when there is a possibility that the cast could fail. For example,
a character column might be expected to contain a valid integer value, but for some rows it does not. For
rows where the cast is not successful, TRY_CAST returns the null value rather than an error.
The CURRENT TIMEZONE special register allows a local time to be converted to Universal Time
Coordinated (UTC). For example, if you have a table named DATETIME that contains a time column type
with a name of STARTT, and you want to convert STARTT to UTC, you can use the following statement:
Date/time arithmetic
Addition and subtraction are the only arithmetic operators applicable to date, time, and timestamp values.
You can increment and decrement a date, time, or timestamp by a duration; or subtract a date from a
date, a time from a time, or a timestamp from a timestamp.
Related reference
Datetime arithmetic in SQL
SQL programming 81
Boolean data type
The Boolean data type represents the values of true, false, and unknown.
Boolean constants TRUE, FALSE, and UNKNOWN represent the corresponding Boolean truth values. ON
and OFF are synonyms for TRUE and FALSE. UNKNOWN is identical to the NULL constant.
When performing comparisons and assignments, a Boolean value is compatible with character and
graphic strings, and numeric values that are integer or decimal floating point values. String values
representing true are 't' , 'true' , 'y', 'yes' , 'on', and '1'. False can be represented by 'f', 'false', 'n', 'no',
'off', and '0'. Any combination of uppercase and lowercase characters are recognized. Numeric values are
interpreted as false if they have a value of 0. Otherwise, they are true.
The normal comparison predicates can be used with Boolean values. A Boolean predicate of IS TRUE or
IS FALSE can be used as well. In addition, a Boolean value can be specified alone in a predicate, which is
an implicit use of the IS TRUE predicate. For comparisons, true is greater than false.
The following three predicates have the same meaning:
Altering a column between any other data type and Boolean is not supported.
The ROW CHANGE TOKEN expression can be used for both tables that have a row change timestamp and
tables that do not. It represents a modification point for a row. If a table has a row change timestamp, it
is derived from the timestamp. If a table does not have a row change timestamp, it is based on an internal
modification time that is not row-based, so it is not as accurate as for a table that has a row change
timestamp.
DISTINCT means that you want to select only the unique rows. If a selected row duplicates another row in
the result table, the duplicate row is ignored (it is not put into the result table). For example, suppose you
want a list of employee job codes. You do not need to know which employee has what job code. Because
JOB
DESIGNER
MANAGER
If you do not include DISTINCT in a SELECT clause, you might find duplicate rows in your result, because
SQL returns the JOB column's value for each row that satisfies the search condition. Null values are
treated as duplicate rows for DISTINCT.
If you include DISTINCT in a SELECT clause and you also include a shared-weight sort sequence, fewer
values might be returned. The sort sequence causes values that contain the same characters to be
weighted the same. If 'MGR', 'Mgr', and 'mgr' are all in the same table, only one of these values is
returned.
Related concepts
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
The BETWEEN keyword is inclusive. A more complex, but explicit, search condition that produces the
same result is:
• IN says you are interested in rows in which the value of the specified expression is among the values
you listed. For example, to find the names of all employees in departments A00, C01, and E21, you can
specify:
• EXISTS says you are interested in testing for the existence of certain rows. For example, to find out if
there are any employees that have a salary greater than 60000, you can specify:
SQL programming 83
• IS NULL says that you are interested in testing for null values. For example, to find out if there are any
employees without a phone listing, you can specify:
• LIKE says you are interested in rows in which an expression is similar to the value you supply. When you
use LIKE, SQL searches for a character string similar to the one you specify. The degree of similarity is
determined by two special characters used in the string that you include in the search condition:
_
An underline character stands for any single character.
%
A percent sign stands for an unknown string of 0 or more characters. If the percent sign starts the
search string, then SQL allows 0 or more character(s) to precede the matching value in the column.
Otherwise, the search string must begin in the first position of the column.
Note: If you are operating on MIXED data, the following distinction applies: an SBCS underline character
refers to one SBCS character. No such restriction applies to the percent sign; that is, a percent sign
refers to any number of SBCS or DBCS characters. See the Db2 for i SQL reference topic collection for
more information about the LIKE predicate and MIXED data.
Use the underline character or percent sign either when you do not know or do not care about all the
characters of the column's value. For example, to find out which employees live in Minneapolis, you can
specify:
SQL returns any row with the string MINNEAPOLIS in the ADDRESS column, no matter where the string
occurs.
In another example, to list the towns whose names begin with 'SAN', you can specify:
If you want to find any addresses where the street name isn't in your master street name list, you can
use an expression in the LIKE expression. In this example, the STREET column in the table is assumed
to be upper case.
If you want to search for a character string that contains either the underscore or percent character,
use the ESCAPE clause to specify an escape character. For example, to see all businesses that have a
percent in their name, you can specify:
The first and last percent characters in the LIKE string are interpreted as the normal LIKE percent
characters. The combination '@%' is taken as the actual percent character.
Related concepts
Using subqueries
You can use subqueries in a search condition as another way to select data. Subqueries can be used
anywhere an expression can be used.
Sort sequences and normalization in SQL
A sort sequence defines how characters in a character set relate to each other when they are compared or
ordered. Normalization allows you to compare strings that contain combining characters.
Related reference
Specifying a search condition using the WHERE clause
However, if you do a search using the search pattern 'ABC%' contained in a host variable with a fixed
length of 10, these values can be returned, assuming that the column has a length of 12:
Note: All returned values start with 'ABC' and end with at least 6 blanks. Blanks are used because the
last 6 characters in the host variable are not assigned a specific value.
If you want to do a search using a fixed-length host variable where the last 7 characters can be
anything, search for 'ABC%%%%%%%'. These are some of the values that can be returned:
...
WHERE WORKDEPT = 'D21' AND HIREDATE > '1987-12-31'
• OR says that, for a row to qualify, the row can satisfy the condition set by either or both predicates of
the search condition. For example, to find out which employees are in either department C01 or D11,
you can specify :
...
WHERE WORKDEPT = 'C01' OR WORKDEPT = 'D11'
Note: You can also use IN to specify this request: WHERE WORKDEPT IN ('C01', 'D11').
SQL programming 85
• NOT says that, to qualify, a row must not meet the criteria set by the search condition or predicate that
follows the NOT. For example, to find all employees in the department E11 except those with a job code
equal to analyst, you can specify:
...
WHERE WORKDEPT = 'E11' AND NOT JOB = 'ANALYST'
When SQL evaluates search conditions that contain these connectors, it does so in a specific order. SQL
first evaluates the NOT clauses, next evaluates the AND clauses, and then the OR clauses.
You can change the order of evaluation by using parentheses. The search conditions enclosed in
parentheses are evaluated first. For example, to select all employees in departments E11 and E21 who
have education levels greater than 12, you can specify:
...
WHERE EDLEVEL > 12 AND
(WORKDEPT = 'E11' OR WORKDEPT = 'E21')
The parentheses determine the meaning of the search condition. In this example, you want all rows that
have a:
• WORKDEPT value of E11 or E21, and
• EDLEVEL value greater than 12
If you did not use parentheses:
...
WHERE EDLEVEL > 12 AND WORKDEPT = 'E11'
OR WORKDEPT = 'E21'
Your result is different. The selected rows are rows that have:
• WORKDEPT = E11 and EDLEVEL > 12, or
• WORKDEPT = E21, regardless of the EDLEVEL value
If you are combining multiple equal comparisons, you can write the predicate with the ANDs as shown in
the following example:
...
WHERE WORKDEPT = 'E11' AND EDLEVEL = 12 AND JOB = 'CLERK'
...
WHERE (WORKDEPT, EDLEVEL, JOB) = ('E11', 12, 'CLERK')
When two lists are used, the first item in the first list is compared to the first item in the second list, and so
on through both lists. Thus, each list must contain the same number of entries. Using lists is identical to
writing the query with AND. Lists can only be used with the equal and not equal comparison operators.
Related reference
Specifying a search condition using the WHERE clause
The WHERE clause specifies a search condition that identifies the row or rows that you want to retrieve,
update, or delete.
In this example, the SALARY descending order with the top 10 returned. The RANK column shows the
relative ranking of each salary. Notice that there are two rows with the same salary at position 2. Each of
those rows is assigned the same rank value. The following row is assigned the value of 4. RANK returns a
value for a row that is one more than the total number of rows that precede that row. There are gaps in the
numbering sequence whenever there are duplicates.
In contrast, the DENSE_RANK column shows a value of 3 for the row directly after the duplicate rows.
DENSE_RANK returns a value for a row that is one more than the number of distinct row values that
precede it. There will never be gaps in the numbering sequence.
ROW_NUMBER returns a unique number for each row. For rows that contain duplicate values according to
the specified ordering, the assignment of a row number is arbitrary; the row numbers could be assigned in
a different order for the duplicate rows when the query is run another time.
SQL programming 87
Table 13. Results of previous query (continued)
WORKDEPT AVERAGE AVG_SALARY QUANTILE
A00 40,850 2 1
E01 40,175 3 1
C01 29,722 4 2
D21 25,668 5 2
D11 25,147 6 2
E21 24,086 7 3
E11 21,020 8 3
In this example, the NTILE function has an argument of 3, meaning that the results are to be grouped into
3 equal-sized sets. Since the result set is not evenly divisible by the number of quantiles, an additional
row is included in each of the two lowest number quantiles.
BONUS_RANK_
IN_DEPT
LASTNAME WORKDEPT BONUS
GEYER E01 800.00 1
HENDERSON E11 600.00 1
SCHNEIDER E11 500.00 2
SCHWARTZ E11 500.00 2
SMITH E11 400.00 3
PARKER E11 300.00 4
SETRIGHT E11 300.00 4
SPRINGER E11 300.00 4
SPENSER E21 500.00 1
LEE E21 500.00 1
GOUNOT E21 500.00 1
WONG E21 500.00 1
ALONZO E21 500.00 1
MENTA E21 400.00 2
ROLLING_ ROLLING_
TOTAL TOTAL_
RANGE ROWS
ROW LASTNAME SALARY DISTRIBUTION
1 JONES 18,270.00 18,270.00 18,270.00 .091
2 WALKER 20,450.00 38,720.00 38,720.00 .182
3 SCOUTTEN 21,340.00 60,060.00 60,060.00 .273
4 PIANKA 22,250.00 82,310.00 82,310.00 .364
SQL programming 89
Table 16. Results of the previous query (continued)
ROLLING_ ROLLING_
TOTAL TOTAL_
RANGE ROWS
ROW LASTNAME SALARY DISTRIBUTION
5 YOSHIMURA 24,680.00 131,670.00 106,990.00 .545
6 YAMAMOTO 24,680.00 131,670.00 131,670.00 .545
7 ADAMSON 25,280.00 156,950.00 156,950.00 .636
8 BROWN 27,740.00 184,690.00 184,690.00 .727
9 LUTZ 29,840.00 244,370.00 214,530.00 .909
10 JOHN 29,840.00 244,370.00 244,370.00 .909
11 STERN 32,250.00 276,620.00 276,620.00 1.000
This example shows two ways of defining the window to be used for calculating the value of a group.
The first way to define the window is with RANGE, which defines a group for all rows that have the same
order by value. Row numbers 5 and 6 have the same salary value, so they are treated as a group. Their
salaries are summed together and added to the previous total to generate the same value for each of the
rows as seen in the ROLLING_TOTAL_RANGE column.
The second way to define the window is with ROWS, which treats each row as a group. In the
ROLLING_TOTAL_ROWS column each row shows the sum calculated up to and including the current
row. For rows that have the same salary value, such as rows 5 and 6, the order in which they are returned
is not defined.
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is the default aggregation group and
could be omitted from the ROLLING_TOTAL_RANGE specification.
An ORDER BY is specified for the entire query to guarantee the rows are returned ordered.
ROLLING_ WINDOWED_
TOTAL TOTAL
LASTNAME SALARY FIRST_VALUE LAST_VALUE
JONES 18,270.00 18,270.00 18,270.00 18,270.00 18,270.00
ROLLING_ WINDOWED_
TOTAL TOTAL
LASTNAME SALARY FIRST_VALUE LAST_VALUE
WALKER 20,450.00 38,720.00 41,790.00 20,450.00 21,340.00
SCOUTTEN 21,340.00 60,060.00 64,040.00 20,450.00 22,250.00
PIANKA 22,250.00 82,310.00 43,590.00 21,340.00 25,280.00
YOSHIMURA 24,680.00 131,670.00 74,640.00 24,680.00 25,280.00
YAMAMOTO 24,680.00 131,670.00 74,640.00 24,680.00 25,280.00
ADAMSON 25,280.00 156,950.00 74,640.00 24,680.00 25,280.00
BROWN 27,740.00 184,690.00 27,740.00 27,740.00 27,740.00
LUTZ 29,840.00 244,370.00 59,680.00 29,840.00 29,840.00
JOHN 29,840.00 244,370.00 59,680.00 29,840.00 29,840.00
STERN 32,250.00 276,620.00 32,250.00 32,250.00 32,250.00
For each employee, a group is defined that contains all other employees in department D11 with salaries
that fall within a range of 1000 below (PRECEDING) or 1000 above (FOLLOWING) that employee's salary.
The WINDOWED_TOTAL column returns the sum of all the salaries in that group. The FIRST_VALUE
column returns the lowest salary value that is part of the group. The LAST_VALUE column returns the
highest salary value that is part of the group. Any employee that has a salary that is more than 1000 from
the closest other salary is its own group.
An ORDER BY is specified for the entire query to guarantee the rows are returned ordered.
SQL programming 91
Table 18. Results of the previous query (continued)
LASTNAME SALARY AVG_SALARY
LUTZ 29,840.00 29,140.00
JOHN 29,840.00 30,643.33
STERN 32,250.00 31,045.00
Inner join
An inner join returns only the rows from each table that have matching values in the join columns. Any
rows that do not have a match between the tables do not appear in the result table.
With an inner join, column values from one row of a table are combined with column values from another
row of another (or the same) table to form a single row of data. SQL examines both tables specified for the
join to retrieve data from all the rows that meet the search condition for the join. There are two ways of
specifying an inner join: using the JOIN syntax, and using the WHERE clause.
Suppose you want to retrieve the employee numbers, names, and project numbers for all employees
that are responsible for a project. In other words, you want the EMPNO and LASTNAME columns from
the CORPDATA.EMPLOYEE table and the PROJNO column from the CORPDATA.PROJECT table. Only
employees with last names starting with 'S' or later should be considered. To find this information, you
need to join the two tables.
The result of this query contains some employees that do not have a project number. They are listed in the
query, but have the null value returned for their project number.
SQL programming 93
EMPNO LASTNAME PROJNO
000020 THOMPSON PL2100
000060 STERN MA2110
000100 SPENSER OP2010
000170 YOSHIMURA -
000180 SCOUTTEN -
000190 WALKER -
000250 SMITH AD3112
000280 SCHNEIDER -
000300 SMITH -
000310 SETRIGHT -
200170 YAMAMOTO -
200280 SCHWARTZ -
200310 SPRINGER -
200330 WONG -
Note: Using the RRN or RID scalar functions to return the relative record number for a column in the table
on the right in a left outer join or exception join will return a value of 0 for the unmatched rows.
The results of this query are identical to the results from the left outer join query.
Exception join
A left exception join returns only the rows from the first table that do not have a match in the second
table.
Using the same tables as before, return those employees that are not responsible for any projects.
An exception join can also be written as a subquery using the NOT EXISTS predicate. The previous query
can be rewritten in the following way:
The only difference in this query is that it cannot return values from the PROJECT table.
There is a right exception join, too, that works just like a left exception join but with the tables reversed.
Cross join
A cross join, also known as a Cartesian Product join, returns a result table where each row from the first
table is combined with each row from the second table.
The number of rows in the result table is the product of the number of rows in each table. If the tables
involved are large, this join can take a very long time.
A cross join can be specified in two ways: using the JOIN syntax or by listing the tables in the FROM
clause separated by commas without using a WHERE clause to supply join criteria.
Suppose that the following tables exist.
SELECT * FROM A, B;
The result table for either of these SELECT statements looks like this.
SQL programming 95
ACOL1 ACOL2 BCOL1 BCOL2
A1 AA1 B1 BB1
A1 AA1 B2 BB2
A2 AA2 B1 BB1
A2 AA2 B2 BB2
A3 AA3 B1 BB1
A3 AA3 B2 BB2
Because there are no projects without an assigned employee, the query returns the same rows as a left
outer join. Here are the results.
SQL programming 97
MGRNO